{% extends "dashboard_base.html" %}

{% block title %}Warehouse — {{ config.APP_NAME }}{% endblock %}

{% block head %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
{% endblock %}

{% block content %}

<!-- Masthead -->
<div class="page-masthead">
  <div>
    <h1>ICE Warehouse Stocks</h1>
    <p class="page-masthead-sub">Physical Arabica certified for delivery against ICE Coffee C futures</p>
  </div>
  <a href="{{ url_for('public.methodology') }}" class="freshness-badge">
    <strong>ICE</strong>
    {% if stocks_latest %}{{ stocks_latest.report_date }}{% elif byport_latest %}{{ byport_latest.report_date }}{% else %}—{% endif %}
  </a>
</div>

<!-- Filter bar -->
<div class="filter-bar" id="wh-filter-bar">
  <!-- Time range -->
  <div class="filter-pills" id="range-pills">
    {% for r, label in [("3m","3M"),("1y","1Y"),("5y","5Y"),("max","Max")] %}
    <button type="button"
            class="filter-pill {{ 'active' if range_key == r }}"
            onclick="setFilter('range','{{ r }}')">{{ label }}</button>
    {% endfor %}
  </div>

  <!-- View selector -->
  <div class="filter-pills" id="view-pills">
    {% for v, label in [("stocks","Daily Stocks"),("aging","Aging"),("byport","By Port")] %}
    <button type="button"
            class="filter-pill {{ 'active' if view == v }}"
            onclick="setFilter('view','{{ v }}')">{{ label }}</button>
    {% endfor %}
  </div>
</div>

<!-- HTMX canvas -->
<div id="warehouse-canvas">
  {% include "warehouse_canvas.html" %}
</div>

{% endblock %}

{% block scripts %}
<script>
var WAREHOUSE_URL = '{{ url_for("dashboard.warehouse") }}';
var currentRange = {{ range_key | tojson }};
var currentView  = {{ view | tojson }};

function setFilter(key, val) {
  if (key === 'range') currentRange = val;
  else currentView = val;
  var url = WAREHOUSE_URL + '?range=' + currentRange + '&view=' + currentView;
  window.history.pushState({}, '', url);
  document.getElementById('warehouse-canvas').classList.add('canvas-loading');
  htmx.ajax('GET', url, { target: '#warehouse-canvas', swap: 'innerHTML' });
}

document.addEventListener('htmx:afterSwap', function (e) {
  if (e.detail.target.id === 'warehouse-canvas') {
    document.getElementById('warehouse-canvas').classList.remove('canvas-loading');
    requestAnimationFrame(function() {
      ['stocksChart', 'agingChart', 'byPortChart'].forEach(function(id) {
        var c = Chart.getChart(id);
        if (c) c.resize();
      });
    });
  }
});

window.addEventListener('popstate', function () {
  var p = new URLSearchParams(window.location.search);
  currentRange = p.get('range') || '1y';
  currentView  = p.get('view')  || 'stocks';
  var url = WAREHOUSE_URL + '?range=' + currentRange + '&view=' + currentView;
  document.getElementById('warehouse-canvas').classList.add('canvas-loading');
  htmx.ajax('GET', url, { target: '#warehouse-canvas', swap: 'innerHTML' });
});
</script>
{% endblock %}
