{# Sim result partial: the honest real-cost equity curve + metrics + timeline slider + state panel. The
   slider scrubs the per-day arrays embedded in #sim-data ENTIRELY client-side (no per-tick refetch); only a
   capital/period change re-fetches /paper/sim/run. There is NO cost/flat toggle — the cost is the MEASURED
   real per-coin spread (a fact, not a knob). When the measured artifact has not been precomputed yet we show
   a short 'precomputing' note (never a flat slider, never a 500). Bybit is the cockpit's only venue since
   Task 7a removed the legacy venue toggle. #}
<div id="sim-result">
{% if measured_pending %}
{% if is_ibkr %}
  <p class="muted" style="font-size:12px; margin-bottom:8px; color:#d29922">
    honest backtest curve precomputing — check back after the nightly job (the precomputed replay is built
    out-of-band by the <code>fxhnt-backtest-refs</code> Job).</p>
{% else %}
  <p class="muted" style="font-size:12px; margin-bottom:8px; color:#d29922">
    measured real-cost curve precomputing — check back after the nightly job (the per-coin measured-cost
    artifact is built out-of-band by <code>fxhnt compare-measured-precompute</code>).</p>
{% endif %}
{% else %}
{% if is_bybit %}
{# Measured cost caption. Each coin pays its real per-COIN cost (published taker fee + half its real measured
   spread) so the curve is the honest de-inflated number. The Bybit liquid book uses the REAL L1 quoted spread
   (forward-realistic) once a refresh has run; absent that it falls back to the Corwin–Schultz daily-high/low
   proxy. #}
{% if used_real_spread %}
<p class="muted" style="font-size:12px; color:#3fb950; margin-bottom:8px"
   data-cost-mode="measured" data-cost-drag="{{ '%.2f'|format(cost_drag_bps) }}"
   title="Each coin pays the published taker fee plus half its real L1 quoted spread (live top-of-book). A current snapshot applied across history — realistic at today's liquidity; earlier-year spreads were wider, so early-history cost is understated. The cost is measured, not a slider.">
  real trading cost, per coin — fee + spread · avg drag {{ '%.2f'|format(cost_drag_bps / 100.0) }}%</p>
{% else %}
<p class="muted" style="font-size:12px; color:#3fb950; margin-bottom:8px"
   data-cost-mode="measured" data-cost-drag="{{ '%.2f'|format(cost_drag_bps) }}"
   title="Each coin pays the published taker fee plus half its measured spread (from real daily high/low); no assumed market impact. The cost is measured, not a slider.">
  real trading cost, per coin — fee + spread · avg drag {{ '%.2f'|format(cost_drag_bps / 100.0) }}%</p>
{% endif %}
{% elif is_ibkr %}
<p class="muted" style="font-size:12px; color:#3fb950; margin-bottom:8px"
   title="The precomputed nightly replay of this strategy at real cost — the same series the reconciliation gate compares the live track against. The cost is modeled, not a slider.">
  real trading cost — modeled nightly, not adjustable</p>
{% endif %}
{% endif %}

{% if not measured_pending %}
{% if n_points == 0 %}
  <p class="muted">no simulated days for this period — pick a date range that overlaps the curve's history.</p>
  <script type="application/json" id="sim-data">{{ sim_data|tojson }}</script>
{% else %}

  <div class="sim-metrics" style="display:flex; flex-wrap:wrap; gap:16px; margin:8px 0 14px">
    <div><div class="muted" style="font-size:12px">CAGR</div>
      <b class="{{ 'pos' if metrics.cagr >= 0 else 'neg' }}">{{ '%.1f'|format(100*metrics.cagr) }}%</b></div>
    <div><div class="muted" style="font-size:12px">Sharpe</div>
      <b>{{ '%.2f'|format(metrics.sharpe) }}</b></div>
    <div><div class="muted" style="font-size:12px">max DD</div>
      <b class="neg">{{ '%.1f'|format(100*metrics.max_dd) }}%</b></div>
    <div><div class="muted" style="font-size:12px">worst year</div>
      <b class="{{ 'pos' if metrics.worst_year >= 0 else 'neg' }}">{{ '%.1f'|format(100*metrics.worst_year) }}%</b></div>
    <div><div class="muted" style="font-size:12px">best year</div>
      <b class="{{ 'pos' if metrics.best_year >= 0 else 'neg' }}">{{ '%.1f'|format(100*metrics.best_year) }}%</b></div>
    <div><div class="muted" style="font-size:12px">final $</div>
      <b>${{ metrics.end_value|money }}</b></div>
  </div>

  {% if is_bybit %}
  <div style="font-weight:600; color:#58a6ff; margin-bottom:4px">Backtest (real measured cost)
    <span class="muted" style="font-weight:400; font-size:12px">— naive equal-weight 4-edge Bybit book over the precomputed measured-cost history; scale by capital / window by period</span>
  </div>
  {% elif is_ibkr %}
  <div style="font-weight:600; color:#58a6ff; margin-bottom:4px">Backtest (honest replay cost)
    <span class="muted" style="font-weight:400; font-size:12px">— precomputed nightly replay of this strategy over its own history; scale by capital / window by period</span>
  </div>
  {% endif %}
  <div>{{ curve|safe }}</div>

  <div style="display:flex; align-items:center; gap:12px; margin:12px 0; flex-wrap:wrap">
    <span class="muted" style="font-size:12px">scrub timeline →</span>
    <input id="sim-scrub" type="range" min="0" max="{{ n_points - 1 }}" value="{{ n_points - 1 }}"
           step="1" style="flex:1; min-width:200px"
           title="Drag to inspect the curve at any day — updates the state panel below. (Nothing to click; just drag.)">
  </div>

  <div id="sim-state" style="display:flex; flex-wrap:wrap; gap:18px; border:1px solid #21262d; border-radius:8px; padding:10px 14px">
    <div><div class="muted" style="font-size:12px">date</div><b id="sim-st-date">—</b></div>
    <div><div class="muted" style="font-size:12px">equity</div><b id="sim-st-equity">—</b></div>
    <div><div class="muted" style="font-size:12px">drawdown</div><b id="sim-st-dd">—</b></div>
    <div><div class="muted" style="font-size:12px">leverage</div><b id="sim-st-lev">—</b></div>
    <div><div class="muted" style="font-size:12px">killed</div><b id="sim-st-killed">—</b></div>
    {# n_active counts the instruments/coins HELD that day (bybit: the ~64-coin liquid universe; ETF book: the
       ~5 ETFs) — NOT the book's sleeves (the 4 edges). Label it "positions" so a 4-edge book doesn't read as
       having 64 "sleeves". #}
    <div><div class="muted" style="font-size:12px">active positions</div><b id="sim-st-active">—</b></div>
  </div>

  {% if sensitivity and sensitivity.rows %}
  {# LEVERED shadow: the honest financing SENSITIVITY BAND — the verdict hinges on the IBKR margin rate, so
     show it across a range + the break-even, not one assumed number. #}
  <div style="margin-top:16px; border:1px solid #21262d; border-radius:8px; padding:12px 14px">
    <div style="font-weight:600; color:#e3a008; margin-bottom:4px">Financing sensitivity
      <span class="muted" style="font-weight:400; font-size:12px">— the levered verdict hinges on the borrow rate, shown across a range (leverage {{ '%.2f'|format(sensitivity.leverage) }}×)</span></div>
    <div class="muted" style="font-size:12px; margin-bottom:8px">Break-even ≈ <b>{{ '%.1f'|format(sensitivity.break_even_pct) }}%/yr</b> (the book's own return) — above that, leverage <b>subtracts</b> return. Unlevered 1×: {{ '%.1f'|format(sensitivity.base_ann_return_pct) }}%/yr at {{ '%.1f'|format(sensitivity.base_ann_vol_pct) }}% vol, Sharpe {{ '%.2f'|format(sensitivity.base_sharpe) }}.</div>
    <div class="table-wrap"><table><thead><tr><th>borrow rate</th><th>levered return</th><th>levered vol</th><th>Sharpe</th></tr></thead><tbody>
    {% for r in sensitivity.rows %}<tr{% if r.is_current %} style="background:rgba(227,160,8,.08)"{% endif %}><td>{{ '%.2f'|format(r.rate_pct) }}%{% if r.is_current %} <span class="muted">· current</span>{% endif %}</td><td class="{{ 'pos' if r.adds else 'neg' }}">{{ '%.1f'|format(r.ann_return_pct) }}%/yr</td><td>{{ '%.1f'|format(r.ann_vol_pct) }}%</td><td>{{ '%.2f'|format(r.sharpe) }}</td></tr>{% endfor %}
    </tbody></table></div>
    <p class="muted" style="font-size:11px; margin-top:6px">IBKR Pro USD ≈ 5.8% (&lt;$100k) to ~5.3% ($100k–1M); Lite +1%; ~1–3% = institutional/portfolio margin. Charged on the borrowed (L−1) leg only. Same Sharpe as the base before financing — leverage adds return only below the break-even, and lowers Sharpe at any positive rate.</p>
  </div>
  {% endif %}

  <script type="application/json" id="sim-data">{{ sim_data|tojson }}</script>

  <script>
    (function () {
      const dataEl = document.getElementById("sim-data");
      if (!dataEl) { return; }
      const D = JSON.parse(dataEl.textContent);
      const n = D.dates.length;
      if (!n) { return; }

      const scrub = document.getElementById("sim-scrub");
      const svg = document.getElementById("sim-curve");
      const line = document.getElementById("sim-cursor-line");
      const dot = document.getElementById("sim-cursor-dot");

      // Curve geometry republished by charts.equity_curve — used to place the cursor identically.
      const lo = parseFloat(svg.getAttribute("data-lo"));
      const span = parseFloat(svg.getAttribute("data-span"));
      const step = parseFloat(svg.getAttribute("data-step"));
      const pad = parseFloat(svg.getAttribute("data-pad"));
      const h = svg.viewBox.baseVal.height;

      function yOf(v) { return h - (v - lo) / span * (h - 2 * pad) - pad; }

      function money(x) { return "$" + Math.round(x).toLocaleString("en-US"); }
      function pct(x) { return (100 * x).toFixed(2) + "%"; }

      function render(i) {
        document.getElementById("sim-st-date").textContent = D.dates[i];
        document.getElementById("sim-st-equity").textContent = money(D.equity[i]);
        document.getElementById("sim-st-dd").textContent = pct(D.drawdown[i]);
        document.getElementById("sim-st-lev").textContent = D.leverage[i].toFixed(2) + "×";
        document.getElementById("sim-st-killed").textContent = D.killed[i] ? "yes" : "no";
        document.getElementById("sim-st-active").textContent = D.n_active[i];
        const x = i * step;
        line.setAttribute("x1", x); line.setAttribute("x2", x);
        dot.setAttribute("cx", x); dot.setAttribute("cy", yOf(D.equity[i]));
      }

      scrub.addEventListener("input", function () { render(parseInt(scrub.value, 10)); });

      render(n - 1);   // start at the latest day (drag the slider to inspect any earlier day)
    })();
  </script>
{% endif %}
{% endif %}

{% if (is_bybit or is_ibkr) and forward %}
  <div style="margin-top:22px; border-top:1px solid #21262d; padding-top:14px">
    <div style="font-weight:600; color:#3fb950; margin-bottom:4px">Live forward — {{ forward.display_name }}
      <span class="muted" style="font-weight:400; font-size:12px">({{ forward.venue }})</span>
    </div>
    <div class="muted" style="font-size:12px; margin-bottom:8px">
      {% if forward.t0 %}T0 {{ forward.t0 }} — {% endif %}
      gate <b style="color:{% if forward.gate_status in ('GO', 'PASS') %}#3fb950{% elif forward.gate_status in ('NO_GO', 'FAIL') %}#f85149{% else %}#d29922{% endif %}">{{ forward.gate_status }}</b>
      {% if forward.gate_reason %}({{ forward.gate_reason }}){% endif %}
      {% if forward.as_of %} · as of {{ forward.as_of }}{% endif %}
    </div>
    {% if forward.n_points %}
    <div class="sim-metrics" style="display:flex; flex-wrap:wrap; gap:16px; margin:6px 0 10px">
      <div><div class="muted" style="font-size:12px">forward days</div><b>{{ forward.days }}</b></div>
      <div><div class="muted" style="font-size:12px">forward return</div>
        <b class="{{ 'pos' if forward.total_return_pct >= 0 else 'neg' }}">{{ '%.2f'|format(forward.total_return_pct) }}%</b></div>
      <div><div class="muted" style="font-size:12px">forward Sharpe</div><b>{{ '%.2f'|format(forward.sharpe) }}</b></div>
    </div>
    <div>{{ forward.curve|safe }}</div>
    {% else %}
    <p class="muted">no live forward NAV recorded yet — the nightly track starts booking from T0 once the
      Bybit warehouse has data.</p>
    {% endif %}
  </div>
{% endif %}
</div>
