{#
  weather_canvas.html — HTMX partial for /dashboard/weather
  Renders overview (no location) or location detail view.
#}

<!-- State sync -->
<script>
(function () {
  var range    = {{ range_key | tojson }};
  var location = {{ location_id | tojson }};
  document.querySelectorAll('#range-pills .filter-pill').forEach(function (btn) {
    var t = btn.textContent.trim().toLowerCase();
    btn.classList.toggle('active', t === range);
  });
  if (typeof currentRange    !== 'undefined') currentRange    = range;
  if (typeof currentLocation !== 'undefined') currentLocation = location;
}());
</script>

{% if location_id and location_detail %}
{# ════════════════════════════════════════════════════════════ #}
{# DETAIL VIEW — single location                                #}
{# ════════════════════════════════════════════════════════════ #}

{% set loc = location_detail %}
{% set latest = location_series[0] if location_series else none %}

<!-- Detail header -->
<div class="cc-in mb-5" style="padding:1rem 0 0.75rem;border-bottom:1.5px solid var(--color-parchment);">
  <div style="display:flex;align-items:baseline;gap:0.75rem;flex-wrap:wrap;">
    <span style="font-family:var(--font-display);font-size:1.375rem;font-weight:800;color:var(--color-espresso);">{{ loc.location_name }}</span>
    <span class="freshness-badge" style="font-size:0.75rem;">{{ loc.country }}</span>
    <span class="freshness-badge" style="font-size:0.75rem;">{{ loc.variety }}</span>
  </div>
  <div style="font-size:0.8125rem;color:var(--color-stone);margin-top:0.25rem;">{{ loc.lat | round(2) }}°, {{ loc.lon | round(2) }}°</div>
</div>

<!-- Location metric cards -->
<div class="grid-4 mb-6 cc-in">
  <div class="metric-card">
    <div class="metric-label">Stress Index</div>
    <div class="metric-value {% if latest and latest.crop_stress_index > 40 %}text-danger{% elif latest and latest.crop_stress_index > 20 %}text-copper{% else %}text-bean-green{% endif %}">
      {% if latest %}{{ "{:.0f}".format(latest.crop_stress_index) }}/100{% else %}--{% endif %}
    </div>
    <div class="metric-sub">crop stress composite{% if latest %} · {{ latest.observation_date }}{% endif %}</div>
  </div>
  <div class="metric-card">
    <div class="metric-label">7-Day Precipitation</div>
    <div class="metric-value">
      {% if latest %}{{ "{:.1f}".format(latest.precip_sum_7d_mm) }} mm{% else %}--{% endif %}
    </div>
    <div class="metric-sub">rolling 7-day total</div>
  </div>
  <div class="metric-card">
    <div class="metric-label">30-Day Precipitation</div>
    <div class="metric-value">
      {% if latest %}{{ "{:.0f}".format(latest.precip_sum_30d_mm) }} mm{% else %}--{% endif %}
    </div>
    <div class="metric-sub">rolling 30-day total</div>
  </div>
  <div class="metric-card">
    <div class="metric-label">Temp Anomaly</div>
    <div class="metric-value {% if latest and latest.temp_anomaly_c and latest.temp_anomaly_c > 2 %}text-danger{% elif latest and latest.temp_anomaly_c and latest.temp_anomaly_c < -2 %}text-bean-green{% endif %}">
      {% if latest and latest.temp_anomaly_c is not none %}{{ "{:+.1f}°C".format(latest.temp_anomaly_c) }}{% else %}--{% endif %}
    </div>
    <div class="metric-sub">vs trailing 30-day mean</div>
  </div>
</div>

{% if location_series %}

<!-- Chart 1: Stress Index + Precipitation -->
<div class="cc-chart-card cc-in mb-5">
  <div class="cc-chart-top">
    <div>
      <div class="cc-chart-title">Crop Stress Index &amp; Precipitation</div>
      <div class="cc-chart-meta">Daily · stress index (left) · precipitation mm (right)</div>
    </div>
    <span class="cc-chart-unit">composite</span>
  </div>
  <div class="cc-chart-body">
    <canvas id="locStressChart"></canvas>
  </div>
</div>

<!-- Chart 2: Temperature + Water Balance -->
<div class="cc-chart-card cc-in-2">
  <div class="cc-chart-top">
    <div>
      <div class="cc-chart-title">Temperature &amp; Water Balance</div>
      <div class="cc-chart-meta">Daily mean °C (left) · 7-day water balance mm (right)</div>
    </div>
    <span class="cc-chart-unit">°C / mm</span>
  </div>
  <div class="cc-chart-body">
    <canvas id="locTempChart"></canvas>
  </div>
</div>

{% else %}
<div class="cc-empty">
  <div class="cc-empty-title">No Data Available</div>
  <p class="cc-empty-body">Weather data for this location is still loading.</p>
</div>
{% endif %}

{% else %}
{# ════════════════════════════════════════════════════════════ #}
{# OVERVIEW — all 12 locations                                  #}
{# ════════════════════════════════════════════════════════════ #}

<!-- Global metric cards -->
<div class="grid-4 mb-6 cc-in">
  <div class="metric-card">
    <div class="metric-label">Avg Crop Stress Index</div>
    <div class="metric-value {% if stress_latest and stress_latest.avg_crop_stress_index > 40 %}text-danger{% elif stress_latest and stress_latest.avg_crop_stress_index > 20 %}text-copper{% else %}text-bean-green{% endif %}">
      {% if stress_latest %}{{ "{:.0f}".format(stress_latest.avg_crop_stress_index) }}/100{% else %}--{% endif %}
    </div>
    <div class="metric-sub">across 12 origins{% if stress_latest %} · {{ stress_latest.observation_date }}{% endif %}</div>
  </div>
  <div class="metric-card">
    <div class="metric-label">Locations Under Stress</div>
    <div class="metric-value {% if stress_latest and stress_latest.locations_under_stress >= 6 %}text-danger{% elif stress_latest and stress_latest.locations_under_stress >= 3 %}text-copper{% else %}text-bean-green{% endif %}">
      {% if stress_latest %}{{ stress_latest.locations_under_stress }}/12{% else %}--{% endif %}
    </div>
    <div class="metric-sub">stress index &gt; 20</div>
  </div>
  <div class="metric-card">
    <div class="metric-label">Worst Origin</div>
    <div class="metric-value" style="font-size:1.1rem;">
      {% if stress_latest and stress_latest.worst_location_name %}{{ stress_latest.worst_location_name }}{% else %}--{% endif %}
    </div>
    <div class="metric-sub">{% if stress_latest and stress_latest.max_crop_stress_index %}peak stress {{ "{:.0f}".format(stress_latest.max_crop_stress_index) }}/100{% endif %}</div>
  </div>
  <div class="metric-card">
    <div class="metric-label">Active Alerts</div>
    <div class="metric-value {% if active_alerts | length >= 4 %}text-danger{% elif active_alerts | length >= 2 %}text-copper{% else %}text-bean-green{% endif %}">
      {{ active_alerts | length }}
    </div>
    <div class="metric-sub">drought / heat / frost / VPD</div>
  </div>
</div>

<!-- Leaflet map (desktop only via CSS) -->
<div id="weather-map" class="weather-map cc-in"></div>

<!-- Global stress chart -->
{% if stress_trend %}
<div class="cc-chart-card cc-in mb-5">
  <div class="cc-chart-top">
    <div>
      <div class="cc-chart-title">Global Crop Stress Index</div>
      <div class="cc-chart-meta">Daily average across all 12 origins</div>
    </div>
    <span class="cc-chart-unit">0–100</span>
  </div>
  <div class="cc-chart-body">
    <canvas id="globalStressChart"></canvas>
  </div>
</div>
{% endif %}

<!-- Active alerts table -->
{% if active_alerts %}
<div class="cc-table-card cc-in-2 mb-5">
  <div class="cc-chart-top" style="padding:1rem 1rem 0.75rem;">
    <div class="cc-chart-title">Active Weather Alerts</div>
    <div class="cc-chart-meta">Locations with at least one active stress flag today</div>
  </div>
  <div class="cc-trow cc-thead">
    <span>Location</span>
    <span>Country</span>
    <span>Stress</span>
    <span>Drought</span>
    <span>Heat</span>
    <span>Frost</span>
    <span>7d Rain</span>
  </div>
  {% for a in active_alerts %}
  <a href="{{ url_for('dashboard.weather') }}?range={{ range_key }}&location={{ a.location_id }}"
     class="cc-trow" style="text-decoration:none;color:inherit;">
    <span style="font-weight:600;color:var(--color-espresso);">{{ a.location_name }}</span>
    <span style="color:var(--color-stone);">{{ a.country }}</span>
    <span class="stress-value {% if a.crop_stress_index > 40 %}high{% elif a.crop_stress_index > 20 %}medium{% else %}low{% endif %}">
      {{ "{:.0f}".format(a.crop_stress_index) }}
    </span>
    <span>
      {% if a.is_drought %}<span class="flag-dot on" title="Drought"></span> {{ a.drought_streak_days }}d
      {% else %}<span class="flag-dot off"></span>{% endif %}
    </span>
    <span>
      {% if a.is_heat_stress %}<span class="flag-dot on" title="Heat stress"></span> {{ a.heat_streak_days }}d
      {% else %}<span class="flag-dot off"></span>{% endif %}
    </span>
    <span>
      {% if a.is_frost %}<span class="flag-dot on" title="Frost"></span>
      {% else %}<span class="flag-dot off"></span>{% endif %}
    </span>
    <span style="font-family:ui-monospace,'Cascadia Code',monospace;">{{ "{:.1f}".format(a.precip_sum_7d_mm) }} mm</span>
  </a>
  {% endfor %}
</div>
{% endif %}

<!-- Location card grid -->
{% if locations %}
<div class="location-grid cc-in-2">
  {% for loc in locations %}
  {% set stress = loc.crop_stress_index | float %}
  {% set stress_class = 'high' if stress > 40 else ('medium' if stress > 20 else 'low') %}
  <a href="{{ url_for('dashboard.weather') }}?range={{ range_key }}&location={{ loc.location_id }}"
     class="loc-card">
    <div class="loc-card-name">{{ loc.location_name }}</div>
    <div class="loc-card-meta">{{ loc.country }} · {{ loc.variety }}</div>
    <div class="loc-card-stress">
      <div class="stress-bar-track">
        <div class="stress-bar-fill {{ stress_class }}" style="width:{{ [stress, 100] | min }}%;"></div>
      </div>
      <span class="stress-value {{ stress_class }}">{{ "{:.0f}".format(stress) }}</span>
    </div>
  </a>
  {% endfor %}
</div>
{% endif %}

{% endif %}{# end overview/detail #}

<!-- Chart init -->
<script>
(function () {
  var C = {
    copper: '#B45309', green: '#15803D', roast: '#4A2C1A', stone: '#78716C',
    danger: '#DC2626', parchment: '#E8DFD5',
  };

  var AXES = {
    x: {
      grid: { color: 'rgba(232,223,213,0.45)', drawTicks: false },
      border: { display: false },
      ticks: { font: { family: "'DM Sans', sans-serif", size: 11 }, color: '#78716C', maxTicksLimit: 10 },
    },
    y: {
      grid: { color: 'rgba(232,223,213,0.45)', drawTicks: false },
      border: { display: false },
      beginAtZero: false,
      ticks: {
        font: { family: "ui-monospace, 'Cascadia Code', monospace", size: 11 }, color: '#78716C',
      },
    },
  };

  var TOOLTIP = {
    backgroundColor: '#2C1810', titleColor: 'rgba(255,255,255,0.5)',
    bodyColor: 'rgba(255,255,255,0.9)', borderColor: 'rgba(255,255,255,0.07)',
    borderWidth: 1, padding: 12, cornerRadius: 10,
  };

  var LEGEND = {
    position: 'bottom',
    labels: { boxWidth: 10, boxHeight: 10, borderRadius: 5, useBorderRadius: true, padding: 16,
              font: { family: "'DM Sans', sans-serif", size: 11.5 }, color: '#57534E' },
  };

  {% if location_id and location_series %}
  // ── Location detail charts ──────────────────────────────────
  var seriesRaw = {{ location_series | tojson }};
  var seriesAsc = seriesRaw.slice().reverse();

  // Chart 1: Stress Index (left y) + Precipitation bars (right y)
  var stressCanvas = document.getElementById('locStressChart');
  if (stressCanvas && seriesAsc.length > 0) {
    new Chart(stressCanvas, {
      type: 'bar',
      data: {
        labels: seriesAsc.map(function (r) { return r.observation_date; }),
        datasets: [
          {
            type: 'line',
            label: 'Stress Index',
            data: seriesAsc.map(function (r) { return r.crop_stress_index; }),
            borderColor: C.copper, backgroundColor: C.copper + '20',
            fill: true, tension: 0.25, pointRadius: 0, borderWidth: 2,
            yAxisID: 'yLeft',
          },
          {
            type: 'bar',
            label: 'Precipitation',
            data: seriesAsc.map(function (r) { return r.precipitation_mm; }),
            backgroundColor: C.green + 'AA',
            borderRadius: 3, borderWidth: 0,
            yAxisID: 'yRight',
          },
        ],
      },
      options: {
        responsive: true, aspectRatio: 2.5,
        interaction: { mode: 'index', intersect: false },
        animation: { duration: 350 },
        plugins: { legend: LEGEND, tooltip: TOOLTIP },
        scales: {
          x: AXES.x,
          yLeft: Object.assign({}, AXES.y, {
            position: 'left',
            min: 0, max: 100,
            title: { display: true, text: 'Stress Index', font: { size: 10 }, color: '#78716C' },
          }),
          yRight: Object.assign({}, AXES.y, {
            position: 'right',
            beginAtZero: true,
            grid: { drawOnChartArea: false },
            title: { display: true, text: 'Precip mm', font: { size: 10 }, color: '#78716C' },
          }),
        },
      },
    });
  }

  // Chart 2: Temperature (left y) + Water Balance 7d (right y)
  var tempCanvas = document.getElementById('locTempChart');
  if (tempCanvas && seriesAsc.length > 0) {
    new Chart(tempCanvas, {
      type: 'line',
      data: {
        labels: seriesAsc.map(function (r) { return r.observation_date; }),
        datasets: [
          {
            label: 'Mean Temp',
            data: seriesAsc.map(function (r) { return r.temp_mean_c; }),
            borderColor: C.copper, tension: 0.25, pointRadius: 0, borderWidth: 2,
            yAxisID: 'yLeft',
          },
          {
            label: '30d Baseline',
            data: seriesAsc.map(function (r) { return r.temp_mean_30d_c; }),
            borderColor: C.stone, borderDash: [5, 4], tension: 0.25, pointRadius: 0, borderWidth: 1.5,
            yAxisID: 'yLeft',
          },
          {
            label: '7d Water Balance',
            data: seriesAsc.map(function (r) { return r.water_balance_7d_mm; }),
            borderColor: C.green, backgroundColor: function (ctx) {
              var v = ctx.dataset.data[ctx.dataIndex];
              return v >= 0 ? C.green + '44' : C.danger + '44';
            },
            fill: 'origin', tension: 0.25, pointRadius: 0, borderWidth: 1.75,
            yAxisID: 'yRight',
          },
        ],
      },
      options: {
        responsive: true, aspectRatio: 2.5,
        interaction: { mode: 'index', intersect: false },
        animation: { duration: 350 },
        plugins: { legend: LEGEND, tooltip: TOOLTIP },
        scales: {
          x: AXES.x,
          yLeft: Object.assign({}, AXES.y, {
            position: 'left',
            title: { display: true, text: '°C', font: { size: 10 }, color: '#78716C' },
          }),
          yRight: Object.assign({}, AXES.y, {
            position: 'right',
            grid: { drawOnChartArea: false },
            title: { display: true, text: 'mm', font: { size: 10 }, color: '#78716C' },
          }),
        },
      },
    });
  }

  {% else %}
  // ── Overview charts ──────────────────────────────────────────

  // Global stress chart
  var stressCanvas = document.getElementById('globalStressChart');
  var stressRaw = {{ stress_trend | tojson }};
  if (stressCanvas && stressRaw.length > 0) {
    var stressAsc = stressRaw.slice().reverse();
    new Chart(stressCanvas, {
      type: 'line',
      data: {
        labels: stressAsc.map(function (r) { return r.observation_date; }),
        datasets: [
          {
            label: 'Avg Stress Index',
            data: stressAsc.map(function (r) { return r.avg_crop_stress_index; }),
            borderColor: C.copper, backgroundColor: C.copper + '20',
            fill: true, tension: 0.25, pointRadius: 0, borderWidth: 2.5,
          },
          {
            label: 'Max Stress Index',
            data: stressAsc.map(function (r) { return r.max_crop_stress_index; }),
            borderColor: C.stone, borderDash: [5, 4], tension: 0.25, pointRadius: 0, borderWidth: 1.75,
          },
        ],
      },
      options: {
        responsive: true, aspectRatio: 2.5,
        interaction: { mode: 'index', intersect: false },
        animation: { duration: 350 },
        plugins: { legend: LEGEND, tooltip: TOOLTIP },
        scales: Object.assign({}, AXES, {
          y: Object.assign({}, AXES.y, {
            min: 0, max: 100,
            title: { display: true, text: 'Stress Index 0–100', font: { size: 10 }, color: '#78716C' },
          }),
        }),
      },
    });
  }

  // Leaflet map
  var mapEl = document.getElementById('weather-map');
  var locData = {{ locations | tojson }};
  if (mapEl && locData.length > 0 && typeof L !== 'undefined') {
    var map = L.map(mapEl, { zoomControl: true, scrollWheelZoom: false }).setView([5, 20], 2);
    L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
      attribution: '&copy; <a href="https://carto.com/">CARTO</a>',
      subdomains: 'abcd',
      maxZoom: 10,
    }).addTo(map);

    locData.forEach(function (loc) {
      var idx = loc.crop_stress_index || 0;
      var color = idx > 40 ? '#DC2626' : (idx > 20 ? '#B45309' : '#15803D');
      var radius = 6 + Math.max(0, idx / 10);

      var circle = L.circleMarker([loc.lat, loc.lon], {
        radius: radius,
        color: color,
        fillColor: color,
        fillOpacity: 0.65,
        weight: 2,
        opacity: 0.85,
      }).addTo(map);

      var flags = [];
      if (loc.is_frost)        flags.push('❄ Frost');
      if (loc.is_heat_stress)  flags.push('🌡 Heat');
      if (loc.is_drought)      flags.push('💧 Drought');
      if (loc.is_high_vpd)     flags.push('🌬 High VPD');

      circle.bindTooltip(
        '<strong>' + loc.location_name + '</strong><br>' +
        loc.country + ' · ' + loc.variety + '<br>' +
        'Stress: <strong>' + idx.toFixed(0) + '/100</strong>' +
        (flags.length ? '<br>' + flags.join(' · ') : ''),
        { direction: 'top', offset: [0, -6] }
      );

      circle.on('click', function () {
        if (typeof setFilter === 'function') setFilter('location', loc.location_id);
      });
    });
  }

  {% endif %}
}());
</script>
