{#
  warehouse_canvas.html — HTMX partial for /dashboard/warehouse
  Only runs queries for the active view.
#}

{% set PORT_COLS  = ['new_york_bags','new_orleans_bags','houston_bags','miami_bags','antwerp_bags','hamburg_bremen_bags','barcelona_bags','virginia_bags'] %}
{% set PORT_NAMES = ['New York','New Orleans','Houston','Miami','Antwerp','Hamburg/Bremen','Barcelona','Virginia'] %}
{% set PORT_COLORS = ['#B45309','#15803D','#7C3AED','#0284C7','#BE185D','#0F766E','#C2410C','#1D4ED8'] %}

<!-- State sync (runs immediately, before charts) -->
<script>
(function () {
  var range = {{ range_key | tojson }};
  var view  = {{ view | tojson }};
  document.querySelectorAll('#range-pills .filter-pill').forEach(function (btn) {
    btn.classList.toggle('active', btn.textContent.trim().toLowerCase() === range);
  });
  document.querySelectorAll('#view-pills .filter-pill').forEach(function (btn) {
    var label = btn.textContent.trim().toLowerCase().replace(/ /g,'');
    btn.classList.toggle('active',
      (view === 'stocks'  && label === 'dailystocks') ||
      (view === 'aging'   && label === 'aging') ||
      (view === 'byport'  && label === 'byport'));
  });
  if (typeof currentRange !== 'undefined') currentRange = range;
  if (typeof currentView  !== 'undefined') currentView  = view;
}());
</script>

{% if view == "stocks" %}

  {% if stocks_latest %}
  <!-- Metric cards -->
  <div class="grid-4 mb-6">
    <div class="metric-card">
      <div class="metric-label">Certified Stocks</div>
      <div class="metric-value">{{ "{:,.0f}".format(stocks_latest.total_certified_bags) }}</div>
      <div class="metric-sub">60-kg bags · {{ stocks_latest.report_date }}</div>
    </div>
    <div class="metric-card">
      <div class="metric-label">Week-over-Week</div>
      <div class="metric-value {% if stocks_latest.wow_change_bags and stocks_latest.wow_change_bags > 0 %}text-bean-green{% elif stocks_latest.wow_change_bags and stocks_latest.wow_change_bags < 0 %}text-danger{% endif %}">
        {% if stocks_latest.wow_change_bags is not none %}{{ "{:+,d}".format(stocks_latest.wow_change_bags | int) }}{% else %}--{% endif %}
      </div>
      <div class="metric-sub">bags vs previous report</div>
    </div>
    <div class="metric-card">
      <div class="metric-label">30-Day Average</div>
      <div class="metric-value">{{ "{:,.0f}".format(stocks_latest.avg_30d_bags) }}</div>
      <div class="metric-sub">60-kg bags</div>
    </div>
    <div class="metric-card">
      <div class="metric-label">Drawdown from 52w High</div>
      <div class="metric-value {% if stocks_latest.drawdown_from_52w_high_pct and stocks_latest.drawdown_from_52w_high_pct < -10 %}text-danger{% endif %}">
        {% if stocks_latest.drawdown_from_52w_high_pct is not none %}{{ "{:.1f}%".format(stocks_latest.drawdown_from_52w_high_pct) }}{% else %}--{% endif %}
      </div>
      <div class="metric-sub">below 52-week peak</div>
    </div>
  </div>
  {% endif %}

  {% if stocks_trend %}
  <div class="cc-chart-card">
    <div class="cc-chart-top">
      <div>
        <div class="cc-chart-title">Daily Certified Stocks</div>
        <div class="cc-chart-meta">ICE certified for Coffee C delivery · 60-kg bags</div>
      </div>
      <span class="cc-chart-unit">bags</span>
    </div>
    <div class="cc-chart-body">
      <canvas id="stocksChart"></canvas>
    </div>
  </div>
  {% else %}
  <div class="cc-empty">
    <div class="cc-empty-title">No Data Available Yet</div>
    <p class="cc-empty-body">Daily certified stock data is updating. Check back shortly.</p>
  </div>
  {% endif %}

{% elif view == "aging" %}

  {% if aging_latest %}
  {% set aging_total = aging_latest | sum(attribute='total_bags') %}
  {% set youngest = aging_latest | selectattr('age_bucket_start_days', 'equalto', 0) | list %}
  {% set oldest   = aging_latest | selectattr('age_bucket_start_days', 'ge', 720) | list %}
  {% set youngest_pct = (youngest | sum(attribute='total_bags') / aging_total * 100) if aging_total > 0 else 0 %}
  {% set oldest_pct   = (oldest   | sum(attribute='total_bags') / aging_total * 100) if aging_total > 0 else 0 %}

  <div class="grid-4 mb-6">
    <div class="metric-card">
      <div class="metric-label">Total Certified</div>
      <div class="metric-value">{{ "{:,.0f}".format(aging_total) }}</div>
      <div class="metric-sub">60-kg bags · {{ aging_latest[0].report_date }}</div>
    </div>
    <div class="metric-card">
      <div class="metric-label">Young Stock (0–120d)</div>
      <div class="metric-value text-bean-green">{{ "{:.1f}%".format(youngest_pct) }}</div>
      <div class="metric-sub">freshest certified supply</div>
    </div>
    <div class="metric-card">
      <div class="metric-label">Old Stock (720+ days)</div>
      <div class="metric-value {% if oldest_pct > 20 %}text-danger{% endif %}">{{ "{:.1f}%".format(oldest_pct) }}</div>
      <div class="metric-sub">at risk of cert expiry</div>
    </div>
    <div class="metric-card">
      <div class="metric-label">Age Buckets</div>
      <div class="metric-value">{{ aging_latest | length }}</div>
      <div class="metric-sub">tracking ranges</div>
    </div>
  </div>

  <div class="cc-chart-card">
    <div class="cc-chart-top">
      <div>
        <div class="cc-chart-title">Stock Aging Distribution</div>
        <div class="cc-chart-meta">Latest aging report · by delivery port · 60-kg bags</div>
      </div>
    </div>
    <div class="cc-chart-body">
      <canvas id="agingChart"></canvas>
    </div>
  </div>
  {% else %}
  <div class="cc-empty">
    <div class="cc-empty-title">No Data Available Yet</div>
    <p class="cc-empty-body">Aging distribution data is updating. Check back shortly.</p>
  </div>
  {% endif %}

{% elif view == "byport" %}

  {% if byport_latest %}
  <div class="grid-4 mb-6">
    <div class="metric-card">
      <div class="metric-label">Total Certified</div>
      <div class="metric-value">{{ "{:,.0f}".format(byport_latest.total_bags) }}</div>
      <div class="metric-sub">60-kg bags · {{ byport_latest.report_date }}</div>
    </div>
    <div class="metric-card">
      <div class="metric-label">Month-over-Month</div>
      <div class="metric-value {% if byport_latest.mom_change_bags and byport_latest.mom_change_bags > 0 %}text-bean-green{% elif byport_latest.mom_change_bags and byport_latest.mom_change_bags < 0 %}text-danger{% endif %}">
        {% if byport_latest.mom_change_bags is not none %}{{ "{:+,d}".format(byport_latest.mom_change_bags | int) }}{% else %}--{% endif %}
      </div>
      <div class="metric-sub">bags vs prior month</div>
    </div>
    <div class="metric-card">
      <div class="metric-label">12-Month Average</div>
      <div class="metric-value">{{ "{:,.0f}".format(byport_latest.avg_12m_bags) }}</div>
      <div class="metric-sub">60-kg bags</div>
    </div>
    <div class="metric-card">
      <div class="metric-label">History</div>
      <div class="metric-value">30 yrs</div>
      <div class="metric-sub">since Nov 1996</div>
    </div>
  </div>
  {% endif %}

  {% if byport_trend %}
  <div class="cc-chart-card">
    <div class="cc-chart-top">
      <div>
        <div class="cc-chart-title">Warehouse Stocks by Delivery Port</div>
        <div class="cc-chart-meta">End-of-month certified stocks · stacked area · 60-kg bags</div>
      </div>
      <span class="cc-chart-unit">bags</span>
    </div>
    <div class="cc-chart-body">
      <canvas id="byPortChart"></canvas>
    </div>
  </div>
  {% else %}
  <div class="cc-empty">
    <div class="cc-empty-title">No Data Available Yet</div>
    <p class="cc-empty-body">By-port warehouse data is updating. Check back shortly.</p>
  </div>
  {% endif %}

{% endif %}

<!-- Chart init -->
<script>
(function () {
  var C = {
    copper: '#B45309', green: '#15803D', roast: '#4A2C1A', stone: '#78716C',
  };
  var PALETTE = ['#B45309','#15803D','#7C3AED','#0284C7','#BE185D','#0F766E','#C2410C','#1D4ED8'];

  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: 12 },
    },
    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',
        callback: function (v) { return v >= 1000000 ? (v/1000000).toFixed(1)+'M' : v >= 1000 ? (v/1000).toFixed(0)+'k' : v; },
      },
    },
  };

  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' },
  };

  // Daily stocks chart
  var stocksCanvas = document.getElementById('stocksChart');
  var stocksRaw = {{ stocks_trend | tojson }};
  if (stocksCanvas && stocksRaw.length > 0) {
    var stocksAsc = stocksRaw.slice().reverse();
    new Chart(stocksCanvas, {
      type: 'line',
      data: {
        labels: stocksAsc.map(function (r) { return r.report_date; }),
        datasets: [
          {
            label: 'Certified Stocks',
            data: stocksAsc.map(function (r) { return r.total_certified_bags; }),
            borderColor: C.roast, backgroundColor: C.roast + '18', fill: true,
            tension: 0.2, pointRadius: 0, borderWidth: 2.5,
          },
          {
            label: '30d Average',
            data: stocksAsc.map(function (r) { return r.avg_30d_bags; }),
            borderColor: C.stone, borderDash: [5, 4], tension: 0.2, 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, { title: { display: true, text: '60-kg bags', font: { size: 10 }, color: '#78716C' } }),
        }),
      },
    });
  }

  // Aging chart
  var agingCanvas = document.getElementById('agingChart');
  var agingRaw = {{ aging_latest | tojson }};
  if (agingCanvas && agingRaw.length > 0) {
    var portCols  = ['antwerp_bags','hamburg_bremen_bags','houston_bags','miami_bags','new_orleans_bags','new_york_bags'];
    var portNames = ['Antwerp','Hamburg/Bremen','Houston','Miami','New Orleans','New York'];
    new Chart(agingCanvas, {
      type: 'bar',
      data: {
        labels: agingRaw.map(function (r) { return r.age_bucket; }),
        datasets: portCols.map(function (col, i) {
          return {
            label: portNames[i],
            data: agingRaw.map(function (r) { return r[col] || 0; }),
            backgroundColor: PALETTE[i],
            borderWidth: 0,
          };
        }),
      },
      options: {
        responsive: true, aspectRatio: 2.5, interaction: { mode: 'index', intersect: false }, animation: { duration: 350 },
        plugins: { legend: LEGEND, tooltip: TOOLTIP },
        scales: {
          x: Object.assign({}, AXES.x, { stacked: true, ticks: Object.assign({}, AXES.x.ticks, { maxRotation: 45 }) }),
          y: Object.assign({}, AXES.y, { stacked: true, beginAtZero: true,
             title: { display: true, text: '60-kg bags', font: { size: 10 }, color: '#78716C' } }),
        },
      },
    });
  }

  // By-port chart
  var byPortCanvas = document.getElementById('byPortChart');
  var byPortRaw = {{ byport_trend | tojson }};
  if (byPortCanvas && byPortRaw.length > 0) {
    var byPortAsc = byPortRaw.slice().reverse();
    var portCols  = ['new_york_bags','new_orleans_bags','houston_bags','miami_bags','antwerp_bags','hamburg_bremen_bags','barcelona_bags','virginia_bags'];
    var portNames = ['New York','New Orleans','Houston','Miami','Antwerp','Hamburg/Bremen','Barcelona','Virginia'];
    new Chart(byPortCanvas, {
      type: 'line',
      data: {
        labels: byPortAsc.map(function (r) { return r.report_date; }),
        datasets: portCols.map(function (col, i) {
          return {
            label: portNames[i],
            data: byPortAsc.map(function (r) { return r[col] || 0; }),
            borderColor: PALETTE[i],
            backgroundColor: PALETTE[i] + '22',
            fill: true,
            tension: 0.2,
            pointRadius: 0,
            borderWidth: 2,
          };
        }),
      },
      options: {
        responsive: true, aspectRatio: 2.5, interaction: { mode: 'index', intersect: false }, animation: { duration: 350 },
        plugins: { legend: LEGEND, tooltip: TOOLTIP },
        scales: {
          x: Object.assign({}, AXES.x, { stacked: true }),
          y: Object.assign({}, AXES.y, { stacked: true, beginAtZero: true,
             title: { display: true, text: '60-kg bags', font: { size: 10 }, color: '#78716C' } }),
        },
      },
    });
  }
}());
</script>
