{#
  positioning_canvas.html — HTMX partial for /dashboard/positioning
#}

{% if price_latest or cot_latest %}

<!-- 4 metric cards -->
<div class="grid-4 mb-6">
  <div class="metric-card">
    <div class="metric-label">KC=F Close</div>
    <div class="metric-value">
      {% if price_latest %}{{ "{:.2f}".format(price_latest.close) }}{% else %}--{% endif %}
    </div>
    <div class="metric-sub">¢/lb
      {% if price_latest and price_latest.daily_return_pct is not none %}
      · <span class="{% if price_latest.daily_return_pct > 0 %}text-bean-green{% elif price_latest.daily_return_pct < 0 %}text-danger{% endif %}">{{ "{:+.2f}%".format(price_latest.daily_return_pct) }}</span>
      {% endif %}
    </div>
  </div>

  <div class="metric-card">
    <div class="metric-label">MM Net Position{% if cot_type == "combined" %} <span style="font-size:0.7em;opacity:0.7">F+O</span>{% endif %}</div>
    <div class="metric-value {% if cot_latest and cot_latest.managed_money_net > 0 %}text-bean-green{% elif cot_latest and cot_latest.managed_money_net < 0 %}text-danger{% endif %}">
      {% if cot_latest %}{{ "{:+,d}".format(cot_latest.managed_money_net | int) }}{% else %}--{% endif %}
    </div>
    <div class="metric-sub">contracts (long − short)</div>
    {% if options_delta %}
    <div class="metric-sub" style="font-family: 'Commit Mono', ui-monospace, monospace; margin-top: 0.25rem; {{ 'color: var(--color-bean-green)' if options_delta.options_delta > 0 else 'color: var(--color-copper)' }}">
      Opt &Delta;: {{ "{:+,d}".format(options_delta.options_delta | int) }}
    </div>
    {% endif %}
  </div>

  <div class="metric-card">
    <div class="metric-label">COT Index 26w</div>
    <div class="metric-value">
      {% if cot_latest %}{{ "{:.0f}".format(cot_latest.cot_index_26w) }}{% else %}--{% endif %}
    </div>
    <div class="metric-sub">0 = most bearish · 100 = most bullish</div>
  </div>

  <div class="metric-card">
    <div class="metric-label">Open Interest</div>
    <div class="metric-value">
      {% if cot_latest %}{{ "{:,d}".format(cot_latest.open_interest | int) }}{% else %}--{% endif %}
    </div>
    <div class="metric-sub">total contracts outstanding</div>
  </div>
</div>

<!-- Price chart -->
{% if price_series %}
<div class="cc-chart-card mb-4">
  <div class="cc-chart-top">
    <div>
      <div class="cc-chart-title">KC=F Coffee Futures Price</div>
      <div class="cc-chart-meta">ICE Coffee C Arabica · daily close + moving averages · ¢/lb</div>
    </div>
    <span class="cc-chart-unit">¢/lb</span>
  </div>
  <div class="cc-chart-body">
    <canvas id="priceChart"></canvas>
  </div>
</div>
{% endif %}

<!-- COT chart -->
{% if cot_trend %}
<div class="cc-chart-card">
  <div class="cc-chart-top">
    <div>
      <div class="cc-chart-title">Managed Money Net Position{{ " (F+O Combined)" if cot_type == "combined" else "" }} + COT Index</div>
      <div class="cc-chart-meta">CFTC Commitment of Traders · weekly · {{ "futures + options delta-adjusted" if cot_type == "combined" else "futures only" }} · area = net contracts · dashed = COT index (0–100)</div>
    </div>
  </div>
  <div class="cc-chart-body">
    <canvas id="cotChart"></canvas>
  </div>
</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">
      <polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/>
      <polyline points="17 6 23 6 23 12"/>
    </svg>
  </div>
  <div class="cc-empty-title">No Data Available Yet</div>
  <p class="cc-empty-body">Positioning data is updating. Check back shortly.</p>
</div>

{% endif %}

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

  // Sync range pills
  document.querySelectorAll('#range-pills .filter-pill').forEach(function (btn) {
    btn.classList.toggle('active', btn.textContent.trim().toLowerCase() === range);
  });

  // Sync type pills
  document.querySelectorAll('#type-pills .filter-pill').forEach(function (btn) {
    var label = cotType === 'combined' ? 'F+O Combined' : 'Futures';
    btn.classList.toggle('active', btn.textContent.trim() === label);
  });

  if (typeof currentRange !== 'undefined') currentRange = range;
  if (typeof currentType !== 'undefined') currentType = cotType;

  var C = {
    copper: '#B45309', green: '#15803D', roast: '#4A2C1A', stone: '#78716C',
    espresso: '#2C1810',
  };

  var AXES_STYLE = {
    grid:   { color: 'rgba(232,223,213,0.45)', drawTicks: false },
    border: { display: false },
    ticks:  { font: { family: "'DM Sans', sans-serif", size: 11 }, color: '#78716C' },
  };

  // Price chart
  var priceRaw = {{ price_series | tojson }};
  var priceCanvas = document.getElementById('priceChart');
  if (priceCanvas && priceRaw.length > 0) {
    var priceAsc = priceRaw.slice().reverse();
    var existing = Chart.getChart(priceCanvas);
    if (existing) existing.destroy();
    new Chart(priceCanvas, {
      type: 'line',
      data: {
        labels: priceAsc.map(function (r) { return r.trade_date; }),
        datasets: [
          {
            label: 'Close (¢/lb)',
            data: priceAsc.map(function (r) { return r.close; }),
            borderColor: C.copper,
            backgroundColor: C.copper + '18',
            fill: true,
            tension: 0.2,
            pointRadius: 0,
            borderWidth: 2.5,
          },
          {
            label: '20d MA',
            data: priceAsc.map(function (r) { return r.sma_20d; }),
            borderColor: C.green,
            borderDash: [4, 3],
            tension: 0.2,
            pointRadius: 0,
            borderWidth: 1.75,
          },
          {
            label: '50d MA',
            data: priceAsc.map(function (r) { return r.sma_50d; }),
            borderColor: C.roast,
            borderDash: [8, 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: {
            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,
          },
        },
        scales: {
          x: Object.assign({}, AXES_STYLE, { ticks: Object.assign({}, AXES_STYLE.ticks, { maxTicksLimit: 12 }) }),
          y: Object.assign({}, AXES_STYLE, {
            beginAtZero: false,
            title: { display: true, text: '¢/lb', font: { size: 10 }, color: '#78716C' },
            ticks: Object.assign({}, AXES_STYLE.ticks, {
              font: { family: "ui-monospace, 'Cascadia Code', monospace", size: 11 },
              callback: function (v) { return v.toFixed(0); },
            }),
          }),
        },
      },
    });
  }

  // COT chart
  var cotRaw = {{ cot_trend | tojson }};
  var cotCanvas = document.getElementById('cotChart');
  if (cotCanvas && cotRaw.length > 0) {
    var cotAsc = cotRaw.slice().reverse();
    var existing = Chart.getChart(cotCanvas);
    if (existing) existing.destroy();
    new Chart(cotCanvas, {
      type: 'line',
      data: {
        labels: cotAsc.map(function (r) { return r.report_date; }),
        datasets: [
          {
            label: 'MM Net (contracts)',
            data: cotAsc.map(function (r) { return r.managed_money_net; }),
            borderColor: C.copper,
            backgroundColor: C.copper + '22',
            fill: true,
            tension: 0.3,
            pointRadius: 0,
            borderWidth: 2.5,
            yAxisID: 'y',
          },
          {
            label: 'COT Index 26w (0–100)',
            data: cotAsc.map(function (r) { return r.cot_index_26w; }),
            borderColor: C.roast,
            borderDash: [5, 4],
            tension: 0.3,
            pointRadius: 0,
            borderWidth: 1.75,
            yAxisID: 'y1',
          },
        ],
      },
      options: {
        responsive: true,
        aspectRatio: 2.5,
        interaction: { mode: 'index', intersect: false },
        animation: { duration: 350 },
        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,
          },
        },
        scales: {
          x: Object.assign({}, AXES_STYLE, { ticks: Object.assign({}, AXES_STYLE.ticks, { maxTicksLimit: 12 }) }),
          y: Object.assign({}, AXES_STYLE, {
            position: 'left',
            title: { display: true, text: 'Net Contracts', font: { size: 10 }, color: '#78716C' },
            ticks: Object.assign({}, AXES_STYLE.ticks, {
              font: { family: "ui-monospace, 'Cascadia Code', monospace", size: 11 },
              callback: function (v) { return v >= 1000 ? (v / 1000).toFixed(0) + 'k' : v; },
            }),
          }),
          y1: Object.assign({}, AXES_STYLE, {
            position: 'right',
            min: 0, max: 100,
            title: { display: true, text: 'COT Index', font: { size: 10 }, color: '#78716C' },
            grid: { drawOnChartArea: false },
            ticks: Object.assign({}, AXES_STYLE.ticks, {
              font: { family: "ui-monospace, 'Cascadia Code', monospace", size: 11 },
            }),
          }),
        },
      },
    });
  }
}());
</script>
