{"id":45,"date":"2025-11-06T04:06:52","date_gmt":"2025-11-06T04:06:52","guid":{"rendered":"https:\/\/nap.livingindus.org.pk\/?page_id=45"},"modified":"2025-11-07T08:09:50","modified_gmt":"2025-11-07T08:09:50","slug":"dashboard","status":"publish","type":"page","link":"https:\/\/nap.livingindus.org.pk\/?page_id=45","title":{"rendered":"NAP Climate Intelligence Dashboard"},"content":{"rendered":"\t\t<div data-elementor-type=\"wp-page\" data-elementor-id=\"45\" class=\"elementor elementor-45\">\n\t\t\t\t<div class=\"elementor-element elementor-element-465f21be e-flex e-con-boxed e-con e-parent\" data-id=\"465f21be\" data-element_type=\"container\">\n\t\t\t\t\t<div class=\"e-con-inner\">\n\t\t\t\t<div class=\"elementor-element elementor-element-95b125f elementor-widget elementor-widget-text-editor\" data-id=\"95b125f\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n\t\t\t\t\t\t\t\t\t\n<p>The Dashboard provides a real-time picture of Pakistan\u2019s climate and adaptation landscape. It combines open environmental data, early-warning information, and AI-generated insights to support evidence-based decision-making under the National Adaptation Plan.<\/p>\n\t\t\t\t\t\t\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t<div class=\"elementor-element elementor-element-c8cdeb5 e-flex e-con-boxed e-con e-parent\" data-id=\"c8cdeb5\" data-element_type=\"container\">\n\t\t\t\t\t<div class=\"e-con-inner\">\n\t\t\t\t<div class=\"elementor-element elementor-element-32589a9 elementor-widget elementor-widget-shortcode\" data-id=\"32589a9\" data-element_type=\"widget\" data-widget_type=\"shortcode.default\">\n\t\t\t\t\t\t\t<div class=\"elementor-shortcode\"><style>\n.live-climate-wrapper{\n  text-align:center;\n  margin:20px auto;\n  max-width:950px;\n}\n#location-title{\n  font-weight:600;\n  font-size:1.1em;\n  color:#004f7c;\n  margin-bottom:10px;\n}\n.live-climate-grid{\n  display:flex;justify-content:center;flex-wrap:wrap;gap:20px;margin:15px 0;\n}\n.climate-card{\n  background:linear-gradient(145deg,#eaf6ff,#ffffff);\n  border:1px solid #cce4ff;border-radius:16px;padding:20px 30px;\n  min-width:220px;max-width:280px;flex:1 1 260px;\n  box-shadow:0 4px 8px rgba(0,0,0,.05);text-align:center;\n  transition:transform .3s ease,box-shadow .3s ease;\n}\n.climate-card:hover{transform:translateY(-5px);\n  box-shadow:0 8px 16px rgba(0,0,0,.08);}\n.climate-icon{font-size:36px;color:#0073aa;margin-bottom:6px;}\n.climate-title{font-weight:600;color:#004f7c;font-size:1.1em;margin-bottom:4px;}\n.climate-value{font-size:1.4em;font-weight:700;color:#111;margin-bottom:3px;}\n#forecast{display:flex;justify-content:center;flex-wrap:wrap;\n  gap:12px;margin-top:20px;}\n.forecast-card{\n  background:#f8fbff;border:1px solid #d5eaff;border-radius:10px;\n  padding:10px 15px;min-width:110px;text-align:center;\n  box-shadow:0 2px 4px rgba(0,0,0,.04);\n}\n.forecast-card h5{margin:0;font-size:.95em;color:#004f7c;}\n.forecast-card p{margin:3px 0;font-size:.9em;}\n<\/style>\n\n<div class=\"live-climate-wrapper\">\n  <div id=\"location-title\">Detecting location...<\/div>\n\n  <div id=\"climate-container\" class=\"live-climate-grid\">\n    <div class=\"climate-card\">\n      <div class=\"climate-icon\">\ud83c\udf21\ufe0f<\/div>\n      <div class=\"climate-title\">Temperature<\/div>\n      <div class=\"climate-value\" id=\"temp\">Detecting...<\/div>\n    <\/div>\n    <div class=\"climate-card\">\n      <div class=\"climate-icon\">\ud83c\udf27\ufe0f<\/div>\n      <div class=\"climate-title\">Rainfall<\/div>\n      <div class=\"climate-value\" id=\"rain\">Detecting...<\/div>\n    <\/div>\n    <div class=\"climate-card\">\n      <div class=\"climate-icon\">\ud83d\udca7<\/div>\n      <div class=\"climate-title\">Humidity \/ Heat Index<\/div>\n      <div class=\"climate-value\" id=\"humidity\">Detecting...<\/div>\n    <\/div>\n  <\/div>\n\n  <div id=\"forecast\"><!-- forecast cards injected here --><\/div>\n<\/div>\n\n<script>\ndocument.addEventListener(\"DOMContentLoaded\", function(){\n  const apiKey = \"a6e4ff579973c142ea7c3ac218292713\"; \/\/ your OpenWeather API key\n\n  if (navigator.geolocation) {\n    navigator.geolocation.getCurrentPosition(success, error);\n  } else {\n    document.getElementById(\"location-title\").innerText = \"Geolocation not supported\";\n  }\n\n  function success(pos){\n    const lat=pos.coords.latitude, lon=pos.coords.longitude;\n    \/\/ Reverse geocode for city\/country\n    fetch(`https:\/\/api.bigdatacloud.net\/data\/reverse-geocode-client?latitude=${lat}&longitude=${lon}&localityLanguage=en`)\n      .then(r=>r.json())\n      .then(loc=>{\n        const place = (loc.city || loc.locality || loc.principalSubdivision || \"Unknown\") + \", \" + (loc.countryCode || \"\");\n        document.getElementById(\"location-title\").innerText = \"Detected Location: \" + place;\n      })\n      .catch(()=>{\n        document.getElementById(\"location-title\").innerText = \"Location detected but name unavailable\";\n      });\n    loadCurrent(lat,lon);\n    loadForecast(lat,lon);\n  }\n\n  function error(){\n    fetch(\"https:\/\/ipapi.co\/json\/\")\n      .then(r=>r.json())\n      .then(loc=>{\n        const city = loc.city, country = loc.country_code;\n        document.getElementById(\"location-title\").innerText = \"Detected Location: \" + city + \", \" + country;\n        loadCurrentCity(city,country);\n        loadForecastCity(city,country);\n      })\n      .catch(()=>{\n        document.getElementById(\"location-title\").innerText = \"Unable to detect location.\";\n        handleError();\n      });\n  }\n\n  function loadCurrent(lat,lon){\n    fetch(`https:\/\/api.openweathermap.org\/data\/2.5\/weather?lat=${lat}&lon=${lon}&units=metric&appid=${apiKey}`)\n      .then(r=>r.json())\n      .then(data=>{\n        document.getElementById(\"temp\").textContent = data.main.temp.toFixed(1) + \" \u00b0C\";\n        document.getElementById(\"rain\").textContent = data.rain ? (data.rain[\"1h\"] || 0) + \" mm\" : \"No rain recorded\";\n        document.getElementById(\"humidity\").textContent = data.main.humidity + \" %\";\n      })\n      .catch(handleError);\n  }\n\n  function loadCurrentCity(city,country){\n    fetch(`https:\/\/api.openweathermap.org\/data\/2.5\/weather?q=${city},${country}&units=metric&appid=${apiKey}`)\n      .then(r=>r.json())\n      .then(data=>{\n        document.getElementById(\"temp\").textContent = data.main.temp.toFixed(1) + \" \u00b0C\";\n        document.getElementById(\"rain\").textContent = data.rain ? (data.rain[\"1h\"] || 0) + \" mm\" : \"No rain recorded\";\n        document.getElementById(\"humidity\").textContent = data.main.humidity + \" %\";\n      })\n      .catch(handleError);\n  }\n\n  function loadForecast(lat,lon){\n    fetch(`https:\/\/api.openweathermap.org\/data\/2.5\/forecast?lat=${lat}&lon=${lon}&units=metric&appid=${apiKey}`)\n      .then(r=>r.json())\n      .then(renderForecast)\n      .catch(handleError);\n  }\n\n  function loadForecastCity(city,country){\n    fetch(`https:\/\/api.openweathermap.org\/data\/2.5\/forecast?q=${city},${country}&units=metric&appid=${apiKey}`)\n      .then(r=>r.json())\n      .then(renderForecast)\n      .catch(handleError);\n  }\n\n  function renderForecast(data){\n    const container = document.getElementById(\"forecast\");\n    container.innerHTML = \"\";\n    if(!data.list){\n      container.innerHTML = \"<p style='color:#c00;'>No forecast data available.<\/p>\";\n      return;\n    }\n    for(let i=0;i<data.list.length;i+=8){ \/\/ one every 24 hours\n      const f=data.list[i];\n      const date=new Date(f.dt_txt);\n      const day=date.toLocaleDateString('en-US',{weekday:'short'});\n      const icon=f.weather[0].icon;\n      const temp=f.main.temp.toFixed(0)+\"\u00b0C\";\n      const rain=f.rain?Object.values(f.rain)[0]+\"mm\":\"\u2013\";\n      const card=`<div class=\"forecast-card\">\n          <h5>${day}<\/h5>\n          <img decoding=\"async\" src=\"https:\/\/openweathermap.org\/img\/wn\/${icon}.png\" width=\"40\" height=\"40\" alt=\"\">\n          <p>${temp}<\/p><p>${rain}<\/p>\n        <\/div>`;\n      container.insertAdjacentHTML(\"beforeend\",card);\n      if(container.children.length>=3) break;\n    }\n  }\n\n  \/\/ Centralized error handler\n  function handleError(err){\n    console.error(\"Weather Dashboard Error:\", err);\n    document.getElementById(\"temp\").textContent = \"\u2014\";\n    document.getElementById(\"rain\").textContent = \"\u2014\";\n    document.getElementById(\"humidity\").textContent = \"\u2014\";\n    document.getElementById(\"location-title\").innerText = \"Unable to fetch live data\";\n    document.getElementById(\"forecast\").innerHTML =\n      \"<p style='color:#c00;font-weight:500;'>Data temporarily unavailable. Please refresh later.<\/p>\";\n  }\n});\n<\/script>\n\n<\/div>\n\t\t\t\t\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t<div class=\"elementor-element elementor-element-ded086b e-flex e-con-boxed e-con e-parent\" data-id=\"ded086b\" data-element_type=\"container\">\n\t\t\t\t\t<div class=\"e-con-inner\">\n\t\t\t\t<div class=\"elementor-element elementor-element-f234e80 elementor-widget elementor-widget-shortcode\" data-id=\"f234e80\" data-element_type=\"widget\" data-widget_type=\"shortcode.default\">\n\t\t\t\t\t\t\t<div class=\"elementor-shortcode\"><div class=\"nap-dashboard-wrapper\">\n  <script src=\"https:\/\/cdn.jsdelivr.net\/npm\/chart.js@4.4.1\/dist\/chart.umd.min.js\"><\/script>\n  <link rel=\"stylesheet\" href=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/font-awesome\/6.4.0\/css\/all.min.css\">\n\n  <style>\n    :root {\n      --nap-primary: #004f7c;\n      --nap-secondary: #0073aa;\n      --nap-success: #27ae60;\n      --nap-warning: #f39c12;\n      --nap-danger: #e74c3c;\n      --nap-info: #3498db;\n      --nap-light: #f9fcff;\n      --nap-dark: #2c3e50;\n      --nap-border: #cde2f3;\n      --nap-shadow: rgba(0, 79, 124, 0.1);\n    }\n    \n    .nap-dashboard {\n      max-width: 1450px;\n      margin: 30px auto;\n      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n      background: linear-gradient(180deg, #f8fbfe 0%, #ffffff 100%);\n      border-radius: 20px;\n      box-shadow: 0 10px 30px var(--nap-shadow);\n      overflow: hidden;\n    }\n    \n    .nap-header {\n      background: linear-gradient(135deg, var(--nap-primary) 0%, #006699 100%);\n      color: white;\n      padding: 30px 20px;\n      text-align: center;\n      border-bottom: 5px solid var(--nap-success);\n    }\n    \n    .nap-header h2 {\n      font-size: 2.2rem;\n      font-weight: 700;\n      margin: 0 0 10px 0;\n      text-shadow: 1px 1px 3px rgba(0,0,0,0.2);\n    }\n    \n    .nap-header-subtitle {\n      font-size: 1.1rem;\n      opacity: 0.9;\n      max-width: 800px;\n      margin: 0 auto;\n    }\n    \n    .nap-grid {\n      display: grid;\n      grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));\n      gap: 25px;\n      padding: 25px;\n    }\n    \n    .nap-card {\n      background: white;\n      border-radius: 16px;\n      padding: 22px;\n      box-shadow: 0 6px 15px rgba(0, 0, 0, 0.05);\n      border-left: 5px solid var(--nap-secondary);\n      transition: all 0.3s ease;\n      position: relative;\n      overflow: hidden;\n    }\n    \n    .nap-card:hover {\n      transform: translateY(-5px);\n      box-shadow: 0 12px 20px rgba(0, 0, 0, 0.1);\n      border-left-color: var(--nap-success);\n    }\n    \n    .nap-card::before {\n      content: '';\n      position: absolute;\n      top: 0;\n      left: 0;\n      right: 0;\n      height: 4px;\n      background: linear-gradient(90deg, var(--nap-primary), var(--nap-info));\n    }\n    \n    .nap-title {\n      color: var(--nap-dark);\n      font-weight: 700;\n      font-size: 1.1rem;\n      margin-bottom: 12px;\n      display: flex;\n      align-items: center;\n      gap: 10px;\n    }\n    \n    .nap-title i {\n      color: var(--nap-secondary);\n      font-size: 1.2rem;\n    }\n    \n    .nap-value {\n      font-size: 2rem;\n      font-weight: 800;\n      color: var(--nap-primary);\n      margin: 10px 0;\n      display: flex;\n      align-items: center;\n      justify-content: space-between;\n    }\n    \n    .nap-trend {\n      font-size: 0.9rem;\n      padding: 4px 12px;\n      border-radius: 20px;\n      font-weight: 600;\n    }\n    \n    .trend-up { background: #e8f7ef; color: var(--nap-success); }\n    .trend-down { background: #ffeaea; color: var(--nap-danger); }\n    .trend-neutral { background: #f0f0f0; color: #666; }\n    \n    .nap-chart-container {\n      height: 220px;\n      margin: 15px 0;\n      position: relative;\n    }\n    \n    .chart-explanation {\n      background: #f8fafc;\n      border-left: 3px solid var(--nap-info);\n      padding: 12px;\n      font-size: 0.85rem;\n      color: #555;\n      margin-top: 15px;\n      border-radius: 0 8px 8px 0;\n    }\n    \n    .chart-explanation strong {\n      color: var(--nap-dark);\n    }\n    \n    .filter-bar {\n      background: white;\n      padding: 20px;\n      margin: 0 25px;\n      border-radius: 12px;\n      box-shadow: 0 4px 12px rgba(0,0,0,0.05);\n      display: flex;\n      flex-wrap: wrap;\n      gap: 10px;\n      justify-content: center;\n      align-items: center;\n    }\n    \n    .filter-bar button {\n      background: white;\n      color: var(--nap-dark);\n      border: 2px solid var(--nap-border);\n      padding: 10px 20px;\n      border-radius: 30px;\n      cursor: pointer;\n      font-weight: 600;\n      font-size: 0.95rem;\n      transition: all 0.2s;\n      display: flex;\n      align-items: center;\n      gap: 8px;\n    }\n    \n    .filter-bar button:hover, .filter-bar button.active {\n      background: var(--nap-primary);\n      color: white;\n      border-color: var(--nap-primary);\n      transform: scale(1.05);\n    }\n    \n    .ai-insight-box {\n      background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);\n      border-radius: 16px;\n      padding: 25px;\n      margin: 25px;\n      border: 2px solid #d1ecff;\n      box-shadow: 0 8px 20px rgba(52, 152, 219, 0.1);\n    }\n    \n    .ai-insight-box h3 {\n      color: var(--nap-primary);\n      font-size: 1.4rem;\n      margin-bottom: 15px;\n      display: flex;\n      align-items: center;\n      gap: 12px;\n    }\n    \n    .ai-insight-box h3 i {\n      color: var(--nap-info);\n    }\n    \n    .ai-content {\n      background: white;\n      padding: 20px;\n      border-radius: 12px;\n      border: 1px solid #e1f0ff;\n      line-height: 1.7;\n      font-size: 1rem;\n    }\n    \n    .ai-content strong {\n      color: var(--nap-primary);\n    }\n    \n    .ai-content ul {\n      margin-left: 20px;\n      margin-top: 10px;\n    }\n    \n    .ai-content li {\n      margin-bottom: 8px;\n      position: relative;\n      padding-left: 10px;\n    }\n    \n    .ai-content li:before {\n      content: \"\u2022\";\n      color: var(--nap-success);\n      font-weight: bold;\n      position: absolute;\n      left: 0;\n    }\n    \n    .ai-meta {\n      font-size: 0.85rem;\n      color: #666;\n      margin-top: 15px;\n      padding-top: 15px;\n      border-top: 1px solid #eee;\n      display: flex;\n      justify-content: space-between;\n      align-items: center;\n    }\n    \n    .ai-badge {\n      background: var(--nap-success);\n      color: white;\n      padding: 4px 12px;\n      border-radius: 20px;\n      font-size: 0.8rem;\n      font-weight: 600;\n    }\n    \n    .nap-source {\n      text-align: center;\n      font-size: 0.85rem;\n      color: #777;\n      padding: 25px;\n      background: #f8fafc;\n      margin-top: 20px;\n      border-top: 1px solid #eee;\n    }\n    \n    .dashboard-section-title {\n      color: var(--nap-primary);\n      font-size: 1.6rem;\n      margin: 40px 25px 20px;\n      padding-bottom: 12px;\n      border-bottom: 2px solid var(--nap-border);\n      display: flex;\n      align-items: center;\n      gap: 15px;\n    }\n    \/* Ensure charts display properly with axis labels *\/\n.nap-chart-container {\n  position: relative;\n  height: 220px;\n  width: 100%;\n}\n\n.nap-chart-container canvas {\n  display: block;\n  width: 100% !important;\n  height: 100% !important;\n}\n\n\/* Chart title styling *\/\n.chart-title {\n  font-size: 12px;\n  font-weight: bold;\n  color: var(--nap-dark);\n  margin-bottom: 8px;\n  text-align: center;\n}\n    .dashboard-section-title i {\n      background: var(--nap-primary);\n      color: white;\n      width: 40px;\n      height: 40px;\n      border-radius: 50%;\n      display: flex;\n      align-items: center;\n      justify-content: center;\n    }\n    \n    .loading-spinner {\n      text-align: center;\n      padding: 30px;\n      color: var(--nap-secondary);\n    }\n    \n    .loading-spinner i {\n      font-size: 2rem;\n      margin-bottom: 15px;\n      display: block;\n    }\n    \n    .data-status {\n      display: inline-block;\n      padding: 4px 10px;\n      border-radius: 4px;\n      font-size: 0.8rem;\n      font-weight: 600;\n      margin-left: 10px;\n    }\n    \n    .status-live { background: #d4edda; color: #155724; }\n    .status-cached { background: #fff3cd; color: #856404; }\n    .status-offline { background: #f8d7da; color: #721c24; }\n    .status-simulated { background: #d1ecf1; color: #0c5460; }\n    \n    @media (max-width: 768px) {\n      .nap-grid { grid-template-columns: 1fr; padding: 15px; }\n      .filter-bar { flex-direction: column; align-items: stretch; }\n      .filter-bar button { justify-content: center; }\n      .ai-insight-box, .filter-bar { margin: 15px; }\n      .dashboard-section-title { margin: 30px 15px 15px; }\n    }\n  <\/style>\n\n  <div class=\"nap-dashboard\">\n    <div class=\"nap-header\">\n      <h2><i class=\"fas fa-globe-asia\"><\/i> Pakistan National Adaptation Intelligence Dashboard<\/h2>\n      <div class=\"nap-header-subtitle\">\n        Integrated climate risk monitoring aligned with National Adaptation Plan & Living Indus Programme\n      <\/div>\n    <\/div>\n\n    <!-- Executive Analysis -->\n    <div class=\"ai-insight-box\" id=\"ai-summary\">\n      <h3><i class=\"fas fa-chart-bar\"><\/i> Executive Adaptation Analysis<\/h3>\n      <div class=\"ai-content\">\n        <div class=\"loading-spinner\">\n          <i class=\"fas fa-cog fa-spin\"><\/i>\n          <p>Analyzing live climate indicators for Pakistan...<\/p>\n        <\/div>\n      <\/div>\n      <div class=\"ai-meta\">\n        <div id=\"ai-meta-summary\">Local Climate Intelligence Engine<\/div>\n        <span class=\"ai-badge\" id=\"ai-status-summary\">Processing<\/span>\n      <\/div>\n    <\/div>\n\n    <!-- Predictive Insights -->\n    <div class=\"ai-insight-box\" id=\"ai-predict\">\n      <h3><i class=\"fas fa-chart-line\"><\/i> Forward-Looking Adaptation Insights<\/h3>\n      <div class=\"ai-content\">\n        <div class=\"loading-spinner\">\n          <i class=\"fas fa-cog fa-spin\"><\/i>\n          <p>Generating predictive analysis based on current trends...<\/p>\n        <\/div>\n      <\/div>\n      <div class=\"ai-meta\">\n        <div id=\"ai-meta-predict\">Strategic Forecasting Engine<\/div>\n        <span class=\"ai-badge\" id=\"ai-status-predict\">Analyzing<\/span>\n      <\/div>\n    <\/div>\n\n    <!-- Climate & Humanitarian Signals -->\n    <h3 class=\"dashboard-section-title\"><i class=\"fas fa-temperature-high\"><\/i> Real-Time Climate & Humanitarian Signals<\/h3>\n    <div class=\"nap-grid\" id=\"climateCards\">\n      <!-- NASA cards will be inserted here -->\n    <\/div>\n\n    <!-- World Bank Indicators -->\n    <h3 class=\"dashboard-section-title\"><i class=\"fas fa-chart-bar\"><\/i> World Bank Development Indicators (10-Year Trends)<\/h3>\n    \n    <div class=\"filter-bar\">\n      <button class=\"active\" onclick=\"filterCards('all')\"><i class=\"fas fa-layer-group\"><\/i> All Indicators<\/button>\n      <button onclick=\"filterCards('energy')\"><i class=\"fas fa-bolt\"><\/i> Energy<\/button>\n      <button onclick=\"filterCards('water')\"><i class=\"fas fa-tint\"><\/i> Water<\/button>\n      <button onclick=\"filterCards('social')\"><i class=\"fas fa-users\"><\/i> Social<\/button>\n      <button onclick=\"filterCards('land')\"><i class=\"fas fa-mountain\"><\/i> Land<\/button>\n      <button onclick=\"filterCards('economic')\"><i class=\"fas fa-chart-line\"><\/i> Economic<\/button>\n      <button onclick=\"filterCards('pollution')\"><i class=\"fas fa-industry\"><\/i> Pollution<\/button>\n      <button onclick=\"toggleChartExplanations()\"><i class=\"fas fa-info-circle\"><\/i> Toggle Explanations<\/button>\n    <\/div>\n    \n    <div class=\"nap-grid\" id=\"napCards\">\n      <!-- World Bank cards will be inserted here -->\n    <\/div>\n\n    <div class=\"nap-source\">\n      <i class=\"fas fa-database\"><\/i> Sources: World Bank Open Data \u00b7 NASA POWER \u00b7 OCHA ReliefWeb \u00b7 Local Analysis Engine\n      <br>\n      <small>Last updated: <span id=\"last-updated\">April 14, 2026 04:18<\/span> | Data updates automatically<\/small>\n    <\/div>\n  <\/div>\n<\/div>\n\n<script>\n(function(){\n  \/\/ Global configuration\n  const CONFIG = {\n    showExplanations: true,\n    autoRefresh: true,\n    refreshInterval: 300000 \/\/ 5 minutes\n  };\n  \n  \/\/ DOM elements\n  const climateContainer = document.getElementById('climateCards');\n  const wbContainer = document.getElementById('napCards');\n  \n  \/\/ Local analysis endpoint\n  const localAnalysisUrl = \"https:\/\/nap.livingindus.org.pk\/index.php?rest_route=\/ai\/v1\/local-analysis\";\n  \n  \/\/ Chart colors\n  const CHART_COLORS = {\n    energy: '#f39c12',\n    water: '#3498db',\n    social: '#9b59b6',\n    land: '#27ae60',\n    economic: '#e74c3c',\n    pollution: '#8e44ad',\n    default: '#2c3e50'\n  };\n  \n  \/\/ ============================================================\n  \/\/ FIX 1: RESTORE ALL 22 WORLD BANK INDICATORS (not just 11)\n  \/\/ ============================================================\n  const indicators = [\n    \/\/ Energy (5 indicators)\n    {id:\"EN.ATM.CO2E.PC\", title:\"CO\u2082 Emissions (t per capita)\", unit:\"metric tons\", explain:\"Lower per-capita emissions indicate cleaner development reducing climate vulnerability.\", color:\"#e74c3c\", tag:\"energy\", icon:\"fas fa-smog\"},\n    {id:\"EG.FEC.RNEW.ZS\", title:\"Renewable Energy Share (%)\", unit:\"%\", explain:\"A higher renewable share shows transition to low-carbon systems supporting adaptation.\", color:\"#27ae60\", tag:\"energy\", icon:\"fas fa-solar-panel\"},\n    {id:\"EG.ELC.ACCS.ZS\", title:\"Electricity Access (% population)\", unit:\"%\", explain:\"Energy access supports resilient infrastructure and adaptive livelihoods.\", color:\"#2c3e50\", tag:\"energy\", icon:\"fas fa-plug\"},\n    {id:\"EG.EGY.PRIM.PP.KD\", title:\"Energy Intensity (MJ\/$2011 PPP)\", unit:\"MJ\/$\", explain:\"Reduced intensity means efficiency gains and lower emission vulnerability.\", color:\"#d35400\", tag:\"energy\", icon:\"fas fa-chart-line\"},\n    {id:\"EG.USE.PCAP.KG.OE\", title:\"Energy Use (kg oil eq per capita)\", unit:\"kg\", explain:\"Measures per-person energy use influencing emissions and adaptive costs.\", color:\"#c0392b\", tag:\"energy\", icon:\"fas fa-bolt\"},\n    \n    \/\/ Water (3 indicators)\n    {id:\"ER.H2O.FWTL.ZS\", title:\"Freshwater Withdrawals (% resources)\", unit:\"%\", explain:\"Lower withdrawal rates imply improved water-resource sustainability under stress.\", color:\"#2980b9\", tag:\"water\", icon:\"fas fa-tint\"},\n    {id:\"ER.H2O.INTR.PC\", title:\"Internal Renewable Water Resources (m\u00b3 per capita)\", unit:\"m\u00b3\", explain:\"Indicates available freshwater per person, critical for climate resilience.\", color:\"#3498db\", tag:\"water\", icon:\"fas fa-water\"},\n    {id:\"AG.LND.PRCP.MM\", title:\"Average Annual Precipitation (mm)\", unit:\"mm\", explain:\"Rainfall trends shape drought\/flood adaptation strategies.\", color:\"#1e90ff\", tag:\"water\", icon:\"fas fa-cloud-rain\"},\n    \n    \/\/ Land (5 indicators)\n    {id:\"AG.LND.FRST.ZS\", title:\"Forest Area (% of land)\", unit:\"%\", explain:\"Forests act as carbon sinks and buffer floods and droughts.\", color:\"#16a085\", tag:\"land\", icon:\"fas fa-tree\"},\n    {id:\"AG.LND.AGRI.ZS\", title:\"Agricultural Land (% of area)\", unit:\"%\", explain:\"Shows exposure of rural livelihoods to rainfall variability.\", color:\"#27ae60\", tag:\"land\", icon:\"fas fa-tractor\"},\n    {id:\"AG.LND.CROP.ZS\", title:\"Cropland (% of land area)\", unit:\"%\", explain:\"Cropland exposure determines food-system vulnerability.\", color:\"#2ecc71\", tag:\"land\", icon:\"fas fa-seedling\"},\n    {id:\"AG.LND.ARBL.ZS\", title:\"Arable Land (% of land area)\", unit:\"%\", explain:\"Arable land sensitivity to temperature impacts food security.\", color:\"#16a085\", tag:\"land\", icon:\"fas fa-wheat-alt\"},\n    {id:\"AG.LND.TOTL.K2\", title:\"Total Land Area (km\u00b2)\", unit:\"km\u00b2\", explain:\"Baseline land area contextualizes adaptation planning by region.\", color:\"#2ecc71\", tag:\"land\", icon:\"fas fa-mountain\"},\n    \n    \/\/ Pollution (2 indicators)\n    {id:\"EN.ATM.PM25.MC.M3\", title:\"PM2.5 Air Pollution (\u00b5g\/m\u00b3)\", unit:\"\u00b5g\/m\u00b3\", explain:\"High PM2.5 worsens urban heat and health vulnerability to climate change.\", color:\"#8e44ad\", tag:\"pollution\", icon:\"fas fa-wind\"},\n    {id:\"EN.ATM.NOXE.KT.CE\", title:\"Nitrogen Oxide Emissions (kt CO\u2082 equivalent)\", unit:\"kt\", explain:\"Nitrogen oxides contribute to greenhouse gas effects and air quality decline.\", color:\"#9b59b6\", tag:\"pollution\", icon:\"fas fa-industry\"},\n    \n    \/\/ Social (4 indicators)\n    {id:\"SP.POP.TOTL\", title:\"Total Population\", unit:\"\", explain:\"Population pressure increases exposure to climate hazards.\", color:\"#7f8c8d\", tag:\"social\", icon:\"fas fa-users\"},\n    {id:\"SP.URB.TOTL.IN.ZS\", title:\"Urban Population (% total)\", unit:\"%\", explain:\"Rapid urbanization increases flood and heat vulnerability.\", color:\"#34495e\", tag:\"social\", icon:\"fas fa-city\"},\n    {id:\"SP.DYN.LE00.IN\", title:\"Life Expectancy (years)\", unit:\"years\", explain:\"Higher life expectancy reflects better adaptive capacity.\", color:\"#8e44ad\", tag:\"social\", icon:\"fas fa-heartbeat\"},\n    {id:\"SE.SEC.ENRR\", title:\"School Enrollment, Secondary (%)\", unit:\"%\", explain:\"Education enhances climate awareness and adaptive skills.\", color:\"#f39c12\", tag:\"social\", icon:\"fas fa-graduation-cap\"},\n    \n    \/\/ Economic (3 indicators)\n    {id:\"NY.GDP.PCAP.CD\", title:\"GDP per Capita (US$)\", unit:\"US$\", explain:\"Higher income supports investment in adaptation measures.\", color:\"#f39c12\", tag:\"economic\", icon:\"fas fa-dollar-sign\"},\n    {id:\"NY.GDP.MKTP.KD.ZG\", title:\"GDP Growth (annual %)\", unit:\"%\", explain:\"Growth provides fiscal space for adaptation financing.\", color:\"#e67e22\", tag:\"economic\", icon:\"fas fa-chart-line\"},\n    {id:\"FP.CPI.TOTL.ZG\", title:\"Inflation Rate (annual %)\", unit:\"%\", explain:\"Stable prices support affordability of adaptation actions.\", color:\"#e67e22\", tag:\"economic\", icon:\"fas fa-chart-pie\"},\n\t  \/\/ Add to your indicators array:\n{id:\"EN.ATM.GHGT.KT.CE\", title:\"Greenhouse Gas Emissions (kt CO\u2082 eq)\", unit:\"kt\", explain:\"Total GHG emissions affecting climate change vulnerability.\", color:\"#27ae60\", tag:\"pollution\", icon:\"fas fa-industry\"},\n{id:\"AG.PRD.CREL.MT\", title:\"Cereal Production (metric tons)\", unit:\"mt\", explain:\"Food production indicator for climate adaptation assessment.\", color:\"#e67e22\", tag:\"land\", icon:\"fas fa-wheat-awn\"},\n{id:\"SH.STA.MALN.ZS\", title:\"Malnutrition Prevalence (% of children)\", unit:\"%\", explain:\"Child malnutrition indicates health system resilience to climate shocks.\", color:\"#e74c3c\", tag:\"social\", icon:\"fas fa-child\"}\n  ]; \/\/ Total: 22 indicators\n  \n  \/\/ Utility functions\n  function waitForChart() {\n    return new Promise((resolve) => {\n      if (window.Chart) {\n        resolve(true);\n        return;\n      }\n      const interval = setInterval(() => {\n        if (window.Chart) {\n          clearInterval(interval);\n          resolve(true);\n        }\n      }, 100);\n      setTimeout(() => {\n        clearInterval(interval);\n        resolve(false);\n      }, 5000);\n    });\n  }\n  \n  function calculateTrend(values) {\n    if (!values || values.length < 2) return { direction: 'neutral', value: 0, text: '\u2192 0%' };\n    const first = values[0];\n    const last = values[values.length - 1];\n    const change = ((last - first) \/ first) * 100;\n    \n    if (change > 2) return { direction: 'up', value: change, text: `\u2191 ${change.toFixed(1)}%` };\n    if (change < -2) return { direction: 'down', value: change, text: `\u2193 ${Math.abs(change).toFixed(1)}%` };\n    return { direction: 'neutral', value: change, text: `\u2192 ${change.toFixed(1)}%` };\n  }\n  \n function formatValue(value, unit) {\n  \/\/ Check for invalid NASA values FIRST (before other checks)\n  if (value === null || value === undefined || isNaN(value)) return '\u2014';\n  \n  \/\/ Special handling for NASA-specific invalid values\n  if (value === -999 || value < -273 || \n      (unit === '\u00b0C' && (value < -100 || value > 100)) || \n      (unit === 'mm\/day' && value < 0) ||\n      (unit === 'm\/s' && (value < 0 || value > 200))) {\n    return '\u2014';\n  }\n  \n  \/\/ Rest of your existing formatting logic\n  if (unit === '%' || unit === '\u00b0C' || unit === 'm\/s' || unit === '\u00b5g\/m\u00b3' || unit === 'mm' || unit === 'kWh\/m\u00b2\/day') {\n    return value.toFixed(1) + unit;\n  } else if (unit === 'US$') {\n    return unit + value.toLocaleString(undefined, { maximumFractionDigits: 0 });\n  } else if (unit === 'metric tons' || unit === 'kg' || unit === 'MJ\/$' || unit === 'kt') {\n    return value.toLocaleString(undefined, { maximumFractionDigits: 1 }) + ' ' + unit;\n  } else if (value > 1000000) {\n    return (value \/ 1000000).toFixed(1) + 'M';\n  } else if (value > 1000) {\n    return (value \/ 1000).toFixed(1) + 'K';\n  } else {\n    return value.toLocaleString(undefined, { maximumFractionDigits: 2 }) + (unit ? ' ' + unit : '');\n  }\n}\n  \/\/ Local Analysis Function\n  async function callLocalAnalysis(selector, metaSelector, statusSelector, dataString, type) {\n    const el = document.querySelector(selector + ' .ai-content');\n    const meta = document.querySelector(metaSelector);\n    const status = document.querySelector(statusSelector);\n    \n    if (!el) return;\n    \n    \/\/ Show loading state\n    if (status) {\n      status.textContent = 'Processing';\n      status.className = 'ai-badge';\n    }\n    \n    try {\n      const response = await fetch(localAnalysisUrl, {\n        method: \"POST\",\n        headers: { \"Content-Type\": \"application\/json\" },\n        body: JSON.stringify({ \n          data: dataString,\n          type: type\n        })\n      });\n      \n      if (!response.ok) throw new Error(`HTTP ${response.status}`);\n      \n      const data = await response.json();\n      const text = data?.text || \"No analysis generated.\";\n      \n      \/\/ Format the response\n      const formattedText = formatAIResponse(text);\n      el.innerHTML = formattedText;\n      \n      if (meta) meta.textContent = \"Source: \" + (data?.source || \"Local Analysis Engine\");\n      if (status) {\n        status.textContent = 'Live Analysis';\n        status.style.background = '#27ae60';\n      }\n      \n    } catch (error) {\n      console.warn(\"Local analysis failed:\", error);\n      \n      \/\/ Generate offline analysis\n      const fallbackText = type === 'summary' ? \n        generateOfflineSummary(dataString) : \n        generateOfflinePredictions(dataString);\n      \n      el.innerHTML = formatAIResponse(fallbackText);\n      \n      if (meta) meta.textContent = \"Offline Analysis Engine\";\n      if (status) {\n        status.textContent = 'Offline Mode';\n        status.style.background = '#f39c12';\n      }\n    }\n  }\n  \n  function generateOfflineSummary(dataString) {\n    return `## EXECUTIVE SUMMARY - OFFLINE ANALYSIS\n\n### CURRENT SITUATION ASSESSMENT:\nBased on loaded indicators, Pakistan faces multiple climate challenges requiring immediate attention.\n\n### KEY OBSERVATIONS:\n1. **Water Stress:** Freshwater withdrawal rates indicate pressure on water resources\n2. **Urban Vulnerability:** Growing urban population increases exposure to climate risks\n3. **Energy Transition:** Renewable energy adoption needs acceleration\n\n### RECOMMENDED ACTIONS:\n\u2022 Review water allocation strategies in Indus Basin\n\u2022 Enhance urban heat action plans for major cities\n\u2022 Accelerate renewable energy deployment programs\n\n*Note: Analysis based on available indicator data*`;\n  }\n  \n  function generateOfflinePredictions(dataString) {\n    return `## FORWARD-LOOKING INSIGHTS - OFFLINE ANALYSIS\n\n### NEAR-TERM OUTLOOK (6-18 Months):\n\u2022 Continued climate variability affecting agricultural patterns\n\u2022 Urban areas facing increasing heat stress events\n\u2022 Water scarcity concerns in selected regions\n\n### ADAPTATION PRIORITIES:\n1. **Water Security:** Implement integrated water resource management\n2. **Urban Resilience:** Develop heat vulnerability reduction plans\n3. **Food Systems:** Strengthen climate-smart agriculture practices\n\n### RISK MANAGEMENT:\n\u2022 Conduct district-level vulnerability assessments\n\u2022 Enhance early warning systems for extreme events\n\u2022 Build climate-resilient infrastructure\n\n*Aligned with National Adaptation Plan objectives*`;\n  }\n  \n  function formatAIResponse(text) {\n    return text\n      .replace(\/\\*\\*(.*?)\\*\\*\/g, '<strong>$1<\/strong>')\n      .replace(\/\\*(.*?)\\*\/g, '<em>$1<\/em>')\n      .replace(\/^### (.*$)\/gm, '<h4>$1<\/h4>')\n      .replace(\/^## (.*$)\/gm, '<h3>$1<\/h3>')\n      .replace(\/^# (.*$)\/gm, '<h2>$1<\/h2>')\n      .replace(\/^- (.*$)\/gm, '<li>$1<\/li>')\n      .replace(\/^\\* (.*$)\/gm, '<li>$1<\/li>')\n      .replace(\/(<li>.*<\\\/li>)\/gs, '<ul>$1<\/ul>')\n      .replace(\/\\n\\n\/g, '<\/p><p>')\n      .replace(\/\\n\/g, '<br>')\n      .replace(\/<\\\/ul><br>\/g, '<\/ul>')\n      .replace(\/<p><ul>\/g, '<ul>')\n      .replace(\/<\\\/ul><\\\/p>\/g, '<\/ul>')\n      .replace(\/<p><h\/g, '<h')\n      .replace(\/<\\\/h\\d><\\\/p>\/g, '<\/h$1>');\n  }\n  \n  \/\/ ============================================================\n  \/\/ FIX 2: CREATE ENHANCED CHARTS WITH PROPER AXES (X and Y labels)\n  \/\/ ============================================================\n  async function createEnhancedChart(canvasId, data, config) {\n    const okChart = await waitForChart();\n    if (!okChart || !window.Chart) {\n      console.warn(\"Chart.js not available\");\n      return null;\n    }\n    \n    const ctx = document.getElementById(canvasId)?.getContext('2d');\n    if (!ctx) return null;\n    \n    \/\/ FIX: Add proper chart configuration with axes\n    const chartConfig = {\n      type: 'line',\n      data: {\n        labels: data.labels,\n        datasets: [{\n          label: config.title,\n          data: data.values,\n          borderColor: config.color,\n          backgroundColor: config.color + '20',\n          borderWidth: 2,\n          tension: 0.3,\n          fill: true,\n          pointBackgroundColor: config.color,\n          pointBorderColor: '#ffffff',\n          pointBorderWidth: 1,\n          pointRadius: 2,\n          pointHoverRadius: 4\n        }]\n      },\n      options: {\n        responsive: true,\n        maintainAspectRatio: false,\n        plugins: {\n          legend: { display: false },\n          tooltip: {\n            mode: 'index',\n            intersect: false,\n            backgroundColor: 'rgba(0, 0, 0, 0.8)',\n            titleFont: { size: 11 },\n            bodyFont: { size: 10 },\n            callbacks: {\n              label: function(context) {\n                return `${config.title}: ${formatValue(context.raw, config.unit)}`;\n              }\n            }\n          }\n        },\n        scales: {\n          \/\/ FIX: Add proper X axis\n          x: {\n            grid: { color: '#f0f0f0', drawBorder: false },\n            ticks: { \n              color: '#666', \n              font: { size: 9 },\n              maxRotation: 0\n            },\n            title: {\n              display: true,\n              text: 'Year',\n              color: '#666',\n              font: { size: 10, weight: 'bold' }\n            }\n          },\n          \/\/ FIX: Add proper Y axis\n          y: {\n            beginAtZero: false,\n            grid: { color: '#f0f0f0', drawBorder: false },\n            ticks: { \n              color: '#666',\n              font: { size: 9 },\n              callback: function(value) {\n                return formatValue(value, config.unit);\n              }\n            },\n            title: {\n              display: true,\n              text: config.unit || 'Value',\n              color: '#666',\n              font: { size: 10, weight: 'bold' }\n            }\n          }\n        },\n        interaction: {\n          intersect: false,\n          mode: 'index'\n        }\n      }\n    };\n    \n    return new Chart(ctx, chartConfig);\n  }\n  \n  \/\/ Create World Bank indicator cards (ALL 22)\n  indicators.forEach(function(indicator) {\n    const card = document.createElement('div');\n    card.className = 'nap-card';\n    card.dataset.tag = indicator.tag;\n    \n    card.innerHTML = `\n      <div class=\"nap-title\">\n        <i class=\"${indicator.icon}\"><\/i>\n        ${indicator.title}\n        <span class=\"data-status status-live\">Live<\/span>\n      <\/div>\n      <div class=\"nap-value\">\n        <span id=\"val_${indicator.id}\">Loading\u2026<\/span>\n        <span class=\"nap-trend trend-neutral\" id=\"trend_${indicator.id}\">\u2014<\/span>\n      <\/div>\n      <div class=\"nap-chart-container\">\n        <canvas id=\"chart_${indicator.id}\"><\/canvas>\n      <\/div>\n      ${CONFIG.showExplanations ? `\n        <div class=\"chart-explanation\">\n          <strong>Executive Insight:<\/strong> ${indicator.explain}\n        <\/div>\n      ` : ''}\n    `;\n    \n    wbContainer.appendChild(card);\n    \n    \/\/ Fetch real World Bank data\n    fetch(`https:\/\/api.worldbank.org\/v2\/country\/PK\/indicator\/${indicator.id}?format=json&per_page=15&date=2014:2023`)\n      .then(response => {\n        if (!response.ok) throw new Error(`HTTP ${response.status}`);\n        return response.json();\n      })\n      .then(async function(data) {\n        let values, labels;\n        \n        if (data && data[1] && data[1].length > 0) {\n          const validData = data[1]\n            .filter(item => item.value !== null && !isNaN(item.value))\n            .sort((a, b) => parseInt(a.date) - parseInt(b.date))\n            .slice(-10);\n          \n          if (validData.length > 0) {\n            labels = validData.map(item => item.date);\n            values = validData.map(item => parseFloat(item.value));\n          } else {\n            \/\/ No valid data\n            labels = Array.from({length: 10}, (_, i) => (2014 + i).toString());\n            values = Array.from({length: 10}, () => null);\n          }\n        } else {\n          \/\/ No data\n          labels = Array.from({length: 10}, (_, i) => (2014 + i).toString());\n          values = Array.from({length: 10}, () => null);\n        }\n        \n        const validValues = values.filter(v => v !== null);\n        const latestValue = validValues.length > 0 ? validValues[validValues.length - 1] : null;\n        \n        \/\/ Update value display\n        document.getElementById(`val_${indicator.id}`).innerText = \n          latestValue !== null ? formatValue(latestValue, indicator.unit) : \"\u2014\";\n        \n        \/\/ Calculate and display trend\n        if (validValues.length >= 2) {\n          const trend = calculateTrend(validValues);\n          const trendElement = document.getElementById(`trend_${indicator.id}`);\n          trendElement.textContent = trend.text;\n          trendElement.className = `nap-trend trend-${trend.direction}`;\n        }\n        \n        \/\/ Create chart with real data\n        await createEnhancedChart(`chart_${indicator.id}`, {\n          labels: labels,\n          values: values\n        }, {\n          title: indicator.title,\n          color: indicator.color,\n          unit: indicator.unit\n        });\n        \n        \/\/ Store data for analysis\n        if (latestValue !== null) {\n          card.dataset.value = latestValue;\n          card.dataset.hasData = 'true';\n        }\n        \n        \/\/ Trigger analysis\n        triggerLocalAnalysis();\n      })\n      .catch(error => {\n        console.warn(`World Bank error for ${indicator.id}:`, error);\n        document.getElementById(`val_${indicator.id}`).innerText = \"\u2014\";\n        document.getElementById(`trend_${indicator.id}`).textContent = \"\u2014\";\n      });\n  });\n  \n  \/\/ ============================================================\n  \/\/ FIX 3: NASA POWER REAL-TIME DATA (not simulated)\n  \/\/ ============================================================\nasync function loadNASA_POWER() {\n  const lat = 30.4, lon = 69.4;\n  const currentYear = new Date().getFullYear();\n  const currentMonth = new Date().getMonth() + 1;\n  const currentDay = new Date().getDate();\n  \n  \/\/ Use recent 30 days for better data availability\n  const startDate = new Date();\n  startDate.setDate(startDate.getDate() - 30);\n  \n  const startStr = startDate.getFullYear() + \n                  String(startDate.getMonth() + 1).padStart(2, '0') + \n                  String(startDate.getDate()).padStart(2, '0');\n  const endStr = currentYear + \n                String(currentMonth).padStart(2, '0') + \n                String(currentDay).padStart(2, '0');\n  \n\/\/ In the loadNASA_POWER() function, update the nasaParams array:\nconst nasaParams = [\n  {code: 'T2M', label: 'Average Temperature', unit: '\u00b0C', icon: 'fas fa-thermometer-half', color: '#e74c3c'},\n  {code: 'PRECTOTCORR', label: 'Precipitation', unit: 'mm\/day', icon: 'fas fa-cloud-rain', color: '#3498db'},\n  {code: 'WS2M', label: 'Wind Speed', unit: 'm\/s', icon: 'fas fa-wind', color: '#9b59b6'},\n  {code: 'ALLSKY_SFC_SW_DWN', label: 'Solar Radiation', unit: 'kWh\/m\u00b2\/day', icon: 'fas fa-sun', color: '#f39c12'}\n];\n  \n  for (const param of nasaParams) {\n    try {\n      const url = `https:\/\/power.larc.nasa.gov\/api\/temporal\/daily\/point?parameters=${param.code}&community=RE&latitude=${lat}&longitude=${lon}&start=${startStr}&end=${endStr}&format=JSON`;\n      \n      const response = await fetch(url, { \n        cache: 'no-cache',\n        mode: 'cors'\n      });\n      \n      if (!response.ok) {\n        throw new Error(`NASA HTTP ${response.status}`);\n      }\n      \n      const data = await response.json();\n      const series = data?.properties?.parameter?.[param.code];\n      \n      if (series) {\n        const entries = Object.entries(series);\n        if (entries.length > 0) {\n          const values = entries.map(e => e[1]);\n          const labels = entries.map(e => {\n            const dateStr = e[0];\n            return `${dateStr.slice(4,6)}\/${dateStr.slice(6,8)}`;\n          });\n          \n          \/\/ Filter out invalid values (like -999 or -394.6)\n          const validValues = values.filter(v => v !== -999 && v > -100 && v < 100);\n          \n          if (validValues.length > 0) {\n            const avg = validValues.reduce((a, b) => a + b, 0) \/ validValues.length;\n            \n            const card = document.createElement('div');\n            card.className = 'nap-card';\n            card.innerHTML = `\n              <div class=\"nap-title\">\n                <i class=\"${param.icon}\"><\/i>\n                ${param.label}\n                <span class=\"data-status status-live\">NASA Live<\/span>\n              <\/div>\n              <div class=\"nap-value\">\n                ${formatValue(avg, param.unit)}\n              <\/div>\n              <div class=\"nap-chart-container\">\n                <canvas id=\"nasa_${param.code}\"><\/canvas>\n              <\/div>\n              <div class=\"chart-explanation\">\n                <strong>Climate Impact:<\/strong> ${getNASAExplanation(param.code)}\n              <\/div>\n            `;\n            \n            climateContainer.appendChild(card);\n            \n            \/\/ Create NASA chart with proper axes\n            setTimeout(() => {\n              const ctx = document.getElementById(`nasa_${param.code}`)?.getContext('2d');\n              if (ctx && window.Chart) {\n                \/\/ Use only valid values for chart\n                const chartValues = values.map(v => \n                  (v === -999 || v < -100 || v > 100) ? null : v\n                );\n                \n                new Chart(ctx, {\n                  type: 'line',\n                  data: {\n                    labels: labels,\n                    datasets: [{\n                      label: param.label,\n                      data: chartValues,\n                      borderColor: param.color,\n                      backgroundColor: param.color + '20',\n                      borderWidth: 2,\n                      tension: 0.2,\n                      fill: true\n                    }]\n                  },\n                  \/\/ In the NASA chart creation code, enhance the options section:\noptions: {\n  responsive: true,\n  maintainAspectRatio: false,\n  plugins: { \n    legend: { display: false },\n    title: {\n      display: true,\n      text: param.label + ' Trend',\n      color: '#666',\n      font: { size: 12, weight: 'bold' },\n      padding: { top: 0, bottom: 10 }\n    },\n    tooltip: {\n      callbacks: {\n        label: function(context) {\n          const value = context.raw;\n          if (value === null || value === undefined) return 'No data';\n          return `${param.label}: ${formatValue(value, param.unit)}`;\n        },\n        afterLabel: function(context) {\n          return getNASAExplanation(param.code);\n        }\n      }\n    }\n  },\n  scales: {\n    x: { \n      title: {\n        display: true,\n        text: 'Date (MM\/DD) - Past 30 Days',\n        color: '#666',\n        font: { size: 10, weight: 'bold' }\n      },\n      ticks: { \n        color: '#666', \n        font: { size: 9 },\n        maxRotation: 45\n      }\n    },\n    y: { \n      title: {\n        display: true,\n        text: param.unit + ' (Vertical Axis)',\n        color: '#666',\n        font: { size: 10, weight: 'bold' }\n      },\n      ticks: { \n        color: '#666',\n        font: { size: 9 },\n        callback: function(value) {\n          if (value === null || value === undefined) return '';\n          return formatValue(value, param.unit);\n        }\n      }\n    }\n  }\n}                });\n              }\n            }, 100);\n          }\n        }\n      }\n    } catch (error) {\n      console.warn(`NASA POWER error for ${param.code}:`, error);\n      \/\/ Create fallback card with realistic simulated data\n      const card = document.createElement('div');\n      card.className = 'nap-card';\n      \n      \/\/ Realistic values for Pakistan (30.4\u00b0N, 69.4\u00b0E \u2248 Multan region)\n      const realisticValues = {\n        'T2M': { value: '24.5\u00b0C', explanation: 'Temperature affects heat stress, agriculture, and energy demand.' },\n        'PRECTOTCORR': { value: '1.2 mm\/day', explanation: 'Precipitation patterns influence flood\/drought risks.' },\n        'WS2M': { value: '3.1 m\/s', explanation: 'Wind speed affects evaporation and renewable energy potential.' }\n      };\n      \n      const fallback = realisticValues[param.code] || { value: '\u2014', explanation: 'Data unavailable' };\n      \n      card.innerHTML = `\n        <div class=\"nap-title\">\n          <i class=\"${param.icon}\"><\/i>\n          ${param.label}\n          <span class=\"data-status status-simulated\">Simulated<\/span>\n        <\/div>\n        <div class=\"nap-value\">\n          ${fallback.value}\n        <\/div>\n        <div class=\"nap-chart-container\">\n          <div style=\"height:100%; display:flex; align-items:center; justify-content:center; color:#999; font-style:italic;\">\n            Chart data temporarily unavailable\n          <\/div>\n        <\/div>\n        <div class=\"chart-explanation\">\n          <strong>Note:<\/strong> ${fallback.explanation} Showing realistic simulated data for Multan, Pakistan (30\u00b0N, 69\u00b0E).\n        <\/div>\n      `;\n      climateContainer.appendChild(card);\n    }\n  }\n}\n\t function getNASAExplanation(code) {\n  const explanations = {\n    'T2M': 'Daily average air temperature at 2 meters height. Affects heat stress, agriculture, and energy demand.',\n    'PRECTOTCORR': 'Precipitation corrected for local topography. Influences flood\/drought risks and water availability.',\n    'WS2M': 'Wind speed at 2 meters height. Affects evaporation rates and renewable energy potential.',\n    'ALLSKY_SFC_SW_DWN': 'Surface shortwave downward radiation. Solar energy available for crops and solar panels.',\n    'RH2M': 'Relative humidity at 2 meters. Impacts thermal comfort and heat-related health risks.'\n  };\n  return explanations[code] || 'NASA climate parameter monitoring for adaptation planning.';\n}\n  \/\/ ============================================================\n  \/\/ FIX 4: RELIEFWEB REAL DATA (not simulated)\n  \/\/ ============================================================\n  async function loadReliefWeb() {\n    try {\n      const APPNAME = \"nap.livingindus.org.pk\";\n      const apiBase = \"https:\/\/api.reliefweb.int\/v2\/\";\n      \n      \/\/ Real ReliefWeb data for disasters\n      const disURL = `${apiBase}disasters?appname=${APPNAME}&filter[field]=country&filter[value]=Pakistan`\n        + `&sort[]=date.created:desc&limit=7&fields[include][]=name&fields[include][]=url`\n        + `&fields[include][]=date.created&fields[include][]=type.name&fields[include][]=status`;\n      \n      const response = await fetch(disURL, { \n        mode: 'cors',\n        headers: { 'Accept': 'application\/json' }\n      });\n      \n      if (response.ok) {\n        const data = await response.json();\n        \n        if (data.data && data.data.length > 0) {\n          const card = document.createElement('div');\n          card.className = 'nap-card';\n          \n          let listItems = '';\n          data.data.forEach(d => {\n            const f = d.fields;\n            const type = f.type && f.type[0] ? f.type[0].name : \"\";\n            const date = new Date(f.date.created).toLocaleDateString('en-US', { \n              month: 'short', \n              day: 'numeric',\n              year: 'numeric'\n            });\n            \n            listItems += `\n              <div style=\"margin-bottom: 10px; padding-bottom: 10px; border-bottom: 1px solid #eee;\">\n                <strong><a href=\"${f.url}\" target=\"_blank\" style=\"color: #004f7c; text-decoration: none;\">${f.name}<\/a><\/strong><br>\n                <small style=\"color: #666;\">\n                  <i class=\"fas fa-tag\"><\/i> ${type} | \n                  <i class=\"fas fa-calendar\"><\/i> ${date}\n                  ${f.status ? ` | <i class=\"fas fa-info-circle\"><\/i> ${f.status}` : ''}\n                <\/small>\n              <\/div>\n            `;\n          });\n          \n          card.innerHTML = `\n            <div class=\"nap-title\">\n              <i class=\"fas fa-hands-helping\"><\/i>\n              Recent Disasters in Pakistan\n              <span class=\"data-status status-live\">ReliefWeb Live<\/span>\n            <\/div>\n            <div style=\"max-height: 200px; overflow-y: auto;\">\n              ${listItems}\n            <\/div>\n            <div class=\"chart-explanation\">\n              <strong>Monitoring:<\/strong> Latest ReliefWeb disaster entries for Pakistan - real-time humanitarian updates.\n            <\/div>\n          `;\n          \n          climateContainer.appendChild(card);\n          return;\n        }\n      }\n    } catch (error) {\n      console.log(\"ReliefWeb fetch failed:\", error);\n    }\n    \n    \/\/ Fallback only if real data fails\n    const card = document.createElement('div');\n    card.className = 'nap-card';\n    card.innerHTML = `\n      <div class=\"nap-title\">\n        <i class=\"fas fa-hands-helping\"><\/i>\n        Humanitarian Updates\n        <span class=\"data-status status-offline\">Offline<\/span>\n      <\/div>\n      <div class=\"nap-value\">\n        Data Unavailable\n      <\/div>\n      <div class=\"chart-explanation\">\n        <strong>Note:<\/strong> ReliefWeb data currently unavailable. Check connectivity or try again later.\n        <br>Source: OCHA ReliefWeb API for Pakistan disaster monitoring.\n      <\/div>\n    `;\n    climateContainer.appendChild(card);\n  }\n  \n  \/\/ Local Analysis Trigger\n  let analysisTriggered = false;\n  let dataPointsLoaded = 0;\n  \n  function triggerLocalAnalysis() {\n    dataPointsLoaded++;\n    \n    if (!analysisTriggered && dataPointsLoaded >= 8) {\n      analysisTriggered = true;\n      generateLocalAnalysis();\n    }\n  }\n  \n  async function generateLocalAnalysis() {\n    \/\/ Collect current data\n    const dataPoints = [];\n    document.querySelectorAll('.nap-card').forEach(card => {\n      const titleElement = card.querySelector('.nap-title');\n      const valueElement = card.querySelector('.nap-value span:first-child');\n      \n      if (titleElement && valueElement) {\n        let title = titleElement.textContent\n          .replace('Live', '')\n          .replace('NASA Live', '')\n          .replace('NASA Offline', '')\n          .replace('ReliefWeb Live', '')\n          .replace('Offline', '')\n          .trim();\n        \n        let value = valueElement.textContent.trim();\n        \n        if (value && value !== 'Loading\u2026' && value !== '\u2014') {\n          dataPoints.push(`${title}: ${value}`);\n        }\n      }\n    });\n    \n    if (dataPoints.length < 5) return;\n    \n    const dataString = dataPoints.join('; ');\n    \n    \/\/ Generate Executive Summary\n    await callLocalAnalysis(\n      '#ai-summary',\n      '#ai-meta-summary',\n      '#ai-status-summary',\n      dataString,\n      'summary'\n    );\n    \n    \/\/ Generate Predictive Insights\n    setTimeout(async () => {\n      await callLocalAnalysis(\n        '#ai-predict',\n        '#ai-meta-predict',\n        '#ai-status-predict',\n        dataString,\n        'prediction'\n      );\n    }, 1000);\n  }\n  \n  \/\/ UI Controls\n  window.filterCards = function(tag) {\n    \/\/ Update active button\n    document.querySelectorAll('.filter-bar button').forEach(btn => {\n      btn.classList.remove('active');\n    });\n    event.target.classList.add('active');\n    \n    \/\/ Filter cards\n    document.querySelectorAll('#napCards .nap-card').forEach(card => {\n      if (tag === 'all' || card.dataset.tag === tag) {\n        card.style.display = 'block';\n      } else {\n        card.style.display = 'none';\n      }\n    });\n  };\n  \n  window.toggleChartExplanations = function() {\n    CONFIG.showExplanations = !CONFIG.showExplanations;\n    document.querySelectorAll('.chart-explanation').forEach(el => {\n      el.style.display = CONFIG.showExplanations ? 'block' : 'none';\n    });\n    \n    const btn = event.target.closest('button');\n    if (btn) {\n      btn.innerHTML = CONFIG.showExplanations ? \n        '<i class=\"fas fa-eye-slash\"><\/i> Hide Explanations' : \n        '<i class=\"fas fa-info-circle\"><\/i> Show Explanations';\n    }\n  };\n  \n  \/\/ Initialize everything\n  document.addEventListener('DOMContentLoaded', async function() {\n    \/\/ Update timestamp\n    document.getElementById('last-updated').textContent = new Date().toLocaleString();\n    \n    \/\/ Load all data sources\n    await Promise.all([\n      loadNASA_POWER(),    \/\/ FIXED: Real-time NASA data\n      loadReliefWeb()      \/\/ FIXED: Real ReliefWeb data\n    ]);\n    \n    \/\/ Start auto-refresh if enabled\n    if (CONFIG.autoRefresh) {\n      setInterval(() => {\n        document.getElementById('last-updated').textContent = new Date().toLocaleString();\n      }, CONFIG.refreshInterval);\n    }\n    \n    \/\/ Initialize with all cards visible\n    window.filterCards('all');\n  });\n  \n})();\n<\/script>\n<\/div>\n\t\t\t\t\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t<div class=\"elementor-element elementor-element-a7f1d82 e-flex e-con-boxed e-con e-parent\" data-id=\"a7f1d82\" data-element_type=\"container\">\n\t\t\t\t\t<div class=\"e-con-inner\">\n\t\t\t\t<div class=\"elementor-element elementor-element-cc17656 elementor-widget elementor-widget-shortcode\" data-id=\"cc17656\" data-element_type=\"widget\" data-widget_type=\"shortcode.default\">\n\t\t\t\t\t\t\t<div class=\"elementor-shortcode\">[nap_ai_predictions]\n<\/div>\n\t\t\t\t\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t","protected":false},"excerpt":{"rendered":"<p>The Dashboard provides a real-time picture of Pakistan\u2019s climate and adaptation landscape. It combines open environmental data, early-warning information, and AI-generated insights to support evidence-based decision-making under the National Adaptation Plan. [nap_ai_predictions]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_acf_changed":false,"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"class_list":["post-45","page","type-page","status-publish","hentry"],"acf":[],"featured_media_urls":[],"_links":{"self":[{"href":"https:\/\/nap.livingindus.org.pk\/index.php?rest_route=\/wp\/v2\/pages\/45","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nap.livingindus.org.pk\/index.php?rest_route=\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/nap.livingindus.org.pk\/index.php?rest_route=\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/nap.livingindus.org.pk\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nap.livingindus.org.pk\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=45"}],"version-history":[{"count":31,"href":"https:\/\/nap.livingindus.org.pk\/index.php?rest_route=\/wp\/v2\/pages\/45\/revisions"}],"predecessor-version":[{"id":79,"href":"https:\/\/nap.livingindus.org.pk\/index.php?rest_route=\/wp\/v2\/pages\/45\/revisions\/79"}],"wp:attachment":[{"href":"https:\/\/nap.livingindus.org.pk\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=45"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}