{% extends "dashboard_base.html" %}

{% block title %}Positioning — {{ 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>Market Positioning</h1>
    <p class="page-masthead-sub">CFTC COT · managed money net position · KC=F price action</p>
  </div>
  <div style="display:flex;gap:0.5rem;flex-wrap:wrap;align-items:center;">
    <a href="{{ url_for('public.methodology') }}" class="freshness-badge">
      <strong>CFTC COT</strong>
      {% if cot_latest %}{{ cot_latest.report_date }}{% else %}—{% endif %}
    </a>
    <a href="{{ url_for('public.methodology') }}" class="freshness-badge">
      <strong>KC=F</strong>
      {% if price_latest %}{{ price_latest.trade_date }}{% else %}—{% endif %}
    </a>
  </div>
</div>

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

  <!-- Report type toggle -->
  <div class="filter-pills" id="type-pills" style="margin-left: 1.5rem; border-left: 1px solid var(--color-parchment); padding-left: 1.5rem;">
    {% for val, label in [("fut", "Futures"), ("combined", "F+O Combined")] %}
    <button type="button"
            class="filter-pill {{ 'active' if cot_type == val }}"
            onclick="setType('{{ val }}')">{{ label }}</button>
    {% endfor %}
  </div>

  <!-- MA toggles (client-side only) -->
  <label class="filter-check">
    <input type="checkbox" id="ma20-toggle" checked onchange="toggleMA('sma20')"> 20d MA
  </label>
  <label class="filter-check">
    <input type="checkbox" id="ma50-toggle" checked onchange="toggleMA('sma50')"> 50d MA
  </label>
</div>

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

{% endblock %}

{% block scripts %}
<script>
var POSITIONING_URL = '{{ url_for("dashboard.positioning") }}';
var currentRange = {{ range_key | tojson }};
var currentType = {{ cot_type | tojson }};

function _positioningUrl() {
  return POSITIONING_URL + '?range=' + currentRange + '&type=' + currentType;
}

function _swapCanvas(url) {
  var el = document.getElementById('positioning-canvas');
  el.style.minHeight = el.offsetHeight + 'px';
  el.classList.add('canvas-loading');
  htmx.ajax('GET', url, { target: '#positioning-canvas', swap: 'innerHTML' });
}

function setRange(val) {
  currentRange = val;
  var url = _positioningUrl();
  window.history.pushState({}, '', url);
  _swapCanvas(url);
}

function setType(val) {
  currentType = val;
  var url = _positioningUrl();
  window.history.pushState({}, '', url);
  // Sync type pill active state immediately (canvas swap will also re-sync)
  document.querySelectorAll('#type-pills .filter-pill').forEach(function (btn) {
    btn.classList.toggle('active', btn.textContent.trim() === (val === 'combined' ? 'F+O Combined' : 'Futures'));
  });
  _swapCanvas(url);
}

// MA toggles: client-side only — update Chart.js dataset visibility
function toggleMA(key) {
  var chart = Chart.getChart('priceChart');
  if (!chart) return;
  var idx = key === 'sma20' ? 1 : 2;
  chart.data.datasets[idx].hidden = !chart.data.datasets[idx].hidden;
  chart.update();
}

document.addEventListener('htmx:afterSwap', function (e) {
  if (e.detail.target.id === 'positioning-canvas') {
    var el = document.getElementById('positioning-canvas');
    el.classList.remove('canvas-loading');
    el.style.minHeight = '';   // release height lock
    requestAnimationFrame(function() {
      ['priceChart', 'cotChart'].forEach(function(id) {
        var c = Chart.getChart(id);
        if (c) c.resize();
      });
      // Re-apply MA checkbox state after resize
      var ma20 = document.getElementById('ma20-toggle');
      var ma50 = document.getElementById('ma50-toggle');
      var chart = Chart.getChart('priceChart');
      if (chart && ma20 && ma50) {
        chart.data.datasets[1].hidden = !ma20.checked;
        chart.data.datasets[2].hidden = !ma50.checked;
        chart.update();
      }
    });
  }
});

window.addEventListener('popstate', function () {
  var p = new URLSearchParams(window.location.search);
  currentRange = p.get('range') || '1y';
  currentType = p.get('type') || 'fut';
  var url = _positioningUrl();
  document.getElementById('positioning-canvas').classList.add('canvas-loading');
  htmx.ajax('GET', url, { target: '#positioning-canvas', swap: 'innerHTML' });
});
</script>
{% endblock %}
