{#
  supply_canvas.html — HTMX partial for /dashboard/supply
  Returned on HX-Request; also included by supply.html on initial load.
#}

{% set C = {
  'copper': '#B45309', 'green': '#15803D', 'roast': '#4A2C1A',
  'forest': '#064E3B', 'stone': '#78716C', 'warning': '#D97706',
  'danger': '#EF4444', 'espresso': '#2C1810',
} %}

{% if time_series %}

<!-- Section 1: Supply/demand multi-line chart -->
<div class="cc-chart-card">
  <div class="cc-chart-top">
    <div>
      <div class="cc-chart-title">Global Supply &amp; Demand</div>
      <div class="cc-chart-meta">USDA WASDE · 1,000 60-kg bags · market year</div>
    </div>
    <span class="cc-chart-unit">1k bags</span>
  </div>
  <div class="cc-chart-body">
    <canvas id="supplyDemandChart"></canvas>
  </div>
</div>

<!-- Section 2: Stock-to-use ratio -->
<div class="cc-chart-card">
  <div class="cc-chart-top">
    <div>
      <div class="cc-chart-title">Stock-to-Use Ratio</div>
      <div class="cc-chart-meta">Ending stocks as % of total distribution · lower = tighter market</div>
    </div>
    <span class="cc-chart-unit">%</span>
  </div>
  <div class="cc-chart-body">
    <canvas id="stuChart"></canvas>
  </div>
</div>

<!-- Section 3: Top producers + YoY table -->
<div class="grid-2">
  <div class="cc-chart-card">
    <div class="cc-chart-top">
      <div>
        <div class="cc-chart-title">Top Countries — {{ metric.replace("_"," ").title() }}</div>
        <div class="cc-chart-meta">USDA · latest market year · 1,000 60-kg bags</div>
      </div>
    </div>
    <div class="cc-chart-body">
      <canvas id="topCountriesChart"></canvas>
    </div>
  </div>

  <div class="cc-table-card">
    <div class="cc-table-top">
      <span class="cc-table-label">YoY Production Change</span>
      {% if yoy %}<span class="cc-table-year">{{ yoy[0].market_year }}</span>{% endif %}
    </div>
    <div class="cc-trow cc-trow-head">
      <span></span>
      <span class="cc-t-head">Country</span>
      <span class="cc-t-head" style="text-align:right">YoY %</span>
    </div>
    {% for row in yoy[:12] %}
    <div class="cc-trow">
      <span class="cc-t-rank">{{ loop.index }}</span>
      <div class="cc-t-country">
        <span class="cc-t-name">{{ row.country_name }}</span>
      </div>
      <span class="cc-t-value {% if row.production_yoy_pct and row.production_yoy_pct > 0 %}text-bean-green{% elif row.production_yoy_pct and row.production_yoy_pct < 0 %}text-danger{% endif %}">
        {% if row.production_yoy_pct is not none %}{{ "{:+.1f}%".format(row.production_yoy_pct) }}{% else %}—{% endif %}
      </span>
    </div>
    {% endfor %}
  </div>
</div>

{% if plan == "free" %}
<div class="plan-gate">
  Free plan shows last 5 years. <a href="{{ url_for('billing.pricing') }}">Upgrade</a> for 10Y / full history and CSV export.
</div>
{% else %}
<div>
  <a href="{{ url_for('api.commodity_metrics_csv', code=711100) }}" class="btn-outline">Export CSV</a>
</div>
{% endif %}

{% else %}

<div class="cc-empty">
  <div class="cc-empty-ring">
    <svg width="22" height="22" fill="none" stroke="var(--color-copper)"
         stroke-width="1.75" stroke-linecap="round" viewBox="0 0 24 24">
      <line x1="18" y1="20" x2="18" y2="10"/>
      <line x1="12" y1="20" x2="12" y2="4"/>
      <line x1="6" y1="20" x2="6" y2="14"/>
    </svg>
  </div>
  <div class="cc-empty-title">No Data Available Yet</div>
  <p class="cc-empty-body">USDA supply &amp; demand data is updating. Check back shortly.</p>
</div>

{% endif %}

<!-- State sync + chart init -->
<script>
(function () {
  var range  = {{ range_key | tojson }};
  var metric = {{ metric | tojson }};

  // Sync filter pills
  document.querySelectorAll('#range-pills .filter-pill').forEach(function (btn) {
    btn.classList.toggle('active', btn.textContent.trim().toLowerCase().replace('y','y') === range || btn.textContent.trim().toLowerCase() === range);
  });
  document.querySelectorAll('#metric-pills .filter-pill').forEach(function (btn) {
    btn.classList.toggle('active', btn.textContent.trim().toLowerCase().replace(/ /g,'_') === metric
      || (btn.textContent.trim() === 'Stocks' && metric === 'ending_stocks'));
  });

  // Update page-level state
  if (typeof currentRange  !== 'undefined') currentRange  = range;
  if (typeof currentMetric !== 'undefined') currentMetric = metric;

  var C = {
    copper: '#B45309', green: '#15803D', roast: '#4A2C1A',
    forest: '#064E3B', stone: '#78716C', warning: '#D97706',
    danger: '#EF4444', espresso: '#2C1810',
  };

  var CHART_OPTS_BASE = {
    responsive: true,
    aspectRatio: 2.5,
    interaction: { mode: 'index', intersect: false },
    plugins: {
      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',
        },
      },
      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,
        callbacks: {
          label: function (ctx) {
            return ' ' + ctx.dataset.label + ': ' + Number(ctx.raw || 0).toLocaleString();
          },
        },
      },
    },
    scales: {
      x: {
        grid:   { color: 'rgba(232,223,213,0.45)', drawTicks: false },
        ticks:  { font: { family: "'DM Sans', sans-serif", size: 11 }, color: '#78716C', maxTicksLimit: 8 },
        border: { display: false },
      },
      y: {
        grid:   { color: 'rgba(232,223,213,0.45)', drawTicks: false },
        ticks: {
          font: { family: "ui-monospace, 'Cascadia Code', monospace", size: 11 },
          color: '#78716C',
          callback: function (v) {
            return v >= 1000000 ? (v / 1000000).toFixed(1) + 'M'
                 : v >= 1000   ? (v / 1000).toFixed(0) + 'k' : v;
          },
        },
        border: { display: false },
        beginAtZero: false,
      },
    },
  };

  // Supply/demand chart
  var tsData = {{ time_series | tojson }};
  var sdCanvas = document.getElementById('supplyDemandChart');
  if (sdCanvas && tsData.length > 0) {
    var existing = Chart.getChart(sdCanvas);
    if (existing) existing.destroy();
    new Chart(sdCanvas, {
      type: 'line',
      data: {
        labels: tsData.map(function (r) { return r.market_year; }),
        datasets: [
          { label: 'Production',    data: tsData.map(function (r) { return r.production; }),         borderColor: C.copper,  tension: 0.3, pointRadius: 0, borderWidth: 2.5 },
          { label: 'Exports',       data: tsData.map(function (r) { return r.exports; }),             borderColor: C.green,   tension: 0.3, pointRadius: 0, borderWidth: 2 },
          { label: 'Imports',       data: tsData.map(function (r) { return r.imports; }),             borderColor: C.roast,   tension: 0.3, pointRadius: 0, borderWidth: 2 },
          { label: 'Ending Stocks', data: tsData.map(function (r) { return r.ending_stocks; }),       borderColor: C.forest,  tension: 0.3, pointRadius: 0, borderWidth: 2 },
          { label: 'Distribution',  data: tsData.map(function (r) { return r.total_distribution; }), borderColor: C.stone,   tension: 0.3, pointRadius: 0, borderWidth: 2, borderDash: [5,4] },
        ],
      },
      options: Object.assign({}, CHART_OPTS_BASE, {
        plugins: Object.assign({}, CHART_OPTS_BASE.plugins, {
          legend: Object.assign({}, CHART_OPTS_BASE.plugins.legend),
        }),
        scales: Object.assign({}, CHART_OPTS_BASE.scales, {
          y: Object.assign({}, CHART_OPTS_BASE.scales.y, {
            title: { display: true, text: '1,000 60-kg bags', font: { size: 10 }, color: '#78716C' },
          }),
        }),
      }),
    });
  }

  // STU chart
  var stuData = {{ stu_trend | tojson }};
  var stuCanvas = document.getElementById('stuChart');
  if (stuCanvas && stuData.length > 0) {
    var existing = Chart.getChart(stuCanvas);
    if (existing) existing.destroy();
    new Chart(stuCanvas, {
      type: 'line',
      data: {
        labels: stuData.map(function (r) { return r.market_year; }),
        datasets: [{
          label: 'Stock-to-Use (%)',
          data: stuData.map(function (r) { return r.stock_to_use_ratio_pct; }),
          borderColor: C.copper,
          backgroundColor: C.copper + '18',
          fill: true,
          tension: 0.3,
          pointRadius: 0,
          borderWidth: 2.5,
        }],
      },
      options: Object.assign({}, CHART_OPTS_BASE, {
        plugins: Object.assign({}, CHART_OPTS_BASE.plugins, {
          legend: Object.assign({}, CHART_OPTS_BASE.plugins.legend, { display: false }),
        }),
        scales: Object.assign({}, CHART_OPTS_BASE.scales, {
          y: Object.assign({}, CHART_OPTS_BASE.scales.y, {
            title: { display: true, text: 'Stock-to-Use (%)', font: { size: 10 }, color: '#78716C' },
            ticks: Object.assign({}, CHART_OPTS_BASE.scales.y.ticks, {
              callback: function (v) { return v.toFixed(1) + '%'; },
            }),
          }),
        }),
      }),
    });
  }

  // Top countries chart
  var topData = {{ top_countries | tojson }};
  var topCanvas = document.getElementById('topCountriesChart');
  if (topCanvas && topData.length > 0) {
    var existing = Chart.getChart(topCanvas);
    if (existing) existing.destroy();
    new Chart(topCanvas, {
      type: 'bar',
      data: {
        labels: topData.map(function (r) { return r.country_name; }),
        datasets: [{
          label: metric.replace(/_/g, ' '),
          data: topData.map(function (r) { return r[metric]; }),
          backgroundColor: C.copper,
          borderRadius: 4,
        }],
      },
      options: {
        indexAxis: 'y',
        responsive: true,
        plugins: { legend: { display: false } },
        scales: {
          x: {
            title: { display: true, text: '1,000 60-kg bags', font: { size: 10 }, color: '#78716C' },
            beginAtZero: true,
            grid: { color: 'rgba(232,223,213,0.45)', drawTicks: false },
            ticks: {
              font: { family: "ui-monospace, 'Cascadia Code', monospace", size: 11 },
              color: '#78716C',
              callback: function (v) {
                return v >= 1000 ? (v / 1000).toFixed(0) + 'k' : v;
              },
            },
            border: { display: false },
          },
          y: {
            grid: { display: false },
            ticks: { font: { family: "'DM Sans', sans-serif", size: 11 }, color: '#57534E' },
            border: { display: false },
          },
        },
      },
    });
  }
}());
</script>
