// ============================================================
// TANK'S TRADING DESK — home-sections.jsx
// Option-D homepage sections. Top-level functions become globals
// (same pattern as kpis.jsx / structural-bias.jsx) and are consumed
// by app.jsx. Composes with the bound design-system components on
// window.TankSTradingDeskDesignSystem_d2ea96 where natural.
// ============================================================

const _DS = typeof window !== 'undefined' && window.TankSTradingDeskDesignSystem_d2ea96 || {};
const { Pill: DSPill, AuditRow: DSAuditRow, Button: DSButton, Disclaimer: DSDisclaimer } = _DS;

const { useState: hsUseState, useEffect: hsUseEffect, useRef: hsUseRef } = React;

// ---------- shared formatters (fall back if globals not present) ----------
const hsUSD0 = (n) => '$' + Math.round(n).toLocaleString();
const hsSignedUSD = (n) => (n >= 0 ? '+' : '−') + '$' + Math.abs(Math.round(n)).toLocaleString();

// ============================================================
// KPI TICKER — "current performance", scrolls left → right
// ============================================================
function KpiTicker({ kpis, account, benchmarkPct, tradingDay }) {
  if (!kpis) return null;
  const initial = account?.initial_capital_usd || 500000;
  const equity = account?.current_nav_usd != null ? account.current_nav_usd : initial + (kpis.live_pnl_usd || 0);
  const retPct = initial ? kpis.live_pnl_usd / initial * 100 : 0;

  const fmtDate = (iso) => {
    if (!iso) return '';
    const [y, m, d] = iso.split('-');
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    return `${parseInt(d, 10)} ${months[+m - 1]} ${y}`;
  };

  return (
    <div className="kpi-fixed" aria-label="Current performance">
      <div className="kpi-fixed-head">Since {fmtDate(account?.inception_date)} · ${(initial / 1000).toFixed(0)}K start · one asset, one system</div>
      <div className="kpi-fixed-tiles">
        <div className="kpi-fixed-tile">
          <div className="kft-l">ACCOUNT EQUITY</div>
          <div className="kft-v">${Math.round(equity).toLocaleString()}</div>
          <div className="kft-s">As of {fmtDate(tradingDay)}</div>
        </div>
        <div className="kpi-fixed-tile">
          <div className="kft-l">NET P&amp;L</div>
          <div className="kft-v">${Math.round(kpis.live_pnl_usd).toLocaleString()}</div>
          <div className="kft-s">Realized ${Math.round(kpis.realized_pnl_usd).toLocaleString()} · Open ${Math.round(kpis.open_unrealized_usd || 0).toLocaleString()}</div>
        </div>
        <div className="kpi-fixed-tile">
          <div className="kft-l">RETURN</div>
          <div className="kft-v accent">{(retPct >= 0 ? '+' : '') + retPct.toFixed(1)}%</div>
          <div className="kft-s">On starting capital</div>
        </div>
        <a className="kpi-fixed-tile kpi-fixed-cta" href="dashboard.html?from=index" aria-label="Open the performance dashboard">
          <span className="kft-cta-label">Performance Dashboard</span>
          <span className="kft-cta-arrow">→</span>
        </a>
      </div>
    </div>);

}

// ============================================================
// SYSTEM PIPELINE — Market Data → Bias / Sensing → Premarket Plan → Trade with Tank
// ============================================================
function SystemPipeline({ active, onSelect, onJoin }) {
  const Arrow = () => <div className="sp-arrow" aria-hidden="true">→</div>;
  const is = (id) => active === id;
  const [sess, setSess] = hsUseState('');
  hsUseEffect(() => {
    const R = window.__resources || {};
    fetch(R.premarket || 'data/premarket_sectors.json').then((r) => r.ok ? r.json() : Promise.reject()).then((d) => setSess(d.meta && d.meta.session_label || '')).catch(() => {});
  }, []);
  const [mins, setMins] = hsUseState(null);
  hsUseEffect(() => {
    const calc = () => {
      try {
        const now = new Date();
        const et = new Date(now.toLocaleString('en-US', { timeZone: 'America/New_York' }));
        const open = new Date(et);open.setHours(9, 30, 0, 0);
        let diff = Math.round((open - et) / 60000);
        if (diff < 0) diff += 24 * 60;
        setMins(diff);
      } catch (e) {setMins(null);}
    };
    calc();
    const t = setInterval(calc, 30000);
    return () => clearInterval(t);
  }, []);
  const liveLabel = (() => {
    if (mins == null) return 'Market open';
    const h = Math.floor(mins / 60),m = mins % 60;
    return (h > 0 ? h + 'h ' : '') + m + 'm to market open';
  })();
  return (
    <section className="sys-pipe" aria-label="The system, left to right">
      <div className="sys-headrow">
        <h2 className="sys-headline">Planning for session{sess ? <span className="sys-headline-date"> · {sess}</span> : null}</h2>
        <h2 className="sys-headline sys-headline-live">{liveLabel}</h2>
      </div>
      <div className="sys-phase" aria-hidden="true">
        <div className="phase-track">
          <span className="phase-line planning" />
          <span className="phase-node" />
          <span className="phase-line live" />
        </div>
      </div>
      <div className="sys-pipe-row" role="tablist">
        <button className={`sp-stage ${is('data') ? 'active' : ''}`} role="tab" aria-selected={is('data')} onClick={() => onSelect('data')}>Market Data<span className="sp-sub">raw · pre-open</span></button>
        <Arrow />
        <button className={`sp-stage ${is('bias') ? 'active' : ''}`} role="tab" aria-selected={is('bias')} onClick={() => onSelect('bias')}>Structural Bias<span className="sp-sub">regime</span></button>
        <Arrow />
        <button className={`sp-stage ${is('sensing') ? 'active' : ''}`} role="tab" aria-selected={is('sensing')} onClick={() => onSelect('sensing')}>Risk Sensing<span className="sp-sub">volatility</span></button>
        <Arrow />
        <button className={`sp-stage ${is('plan') ? 'active' : ''}`} role="tab" aria-selected={is('plan')} onClick={() => onSelect('plan')}>Premarket Plan<span className="sp-sub">discipline</span></button>
        <Arrow />
        <button className="sp-stage cta" onClick={onJoin}>Trade with Tank<span className="sp-sub">live</span></button>
      </div>
    </section>);

}

// ============================================================
// PRICE SCALE — QQQ spot · expected-move band · planned tier levels
// Pure presentational; receives resolved levels + tiers.
// ============================================================
function PriceScale({ spot, em, ticks, tiers, compact }) {
  const H = compact ? 300 : 320;
  const prices = [
  spot,
  ...ticks.map((t) => t.p),
  ...tiers.map((t) => t.level),
  em.low, em.high];

  const hi = Math.max(...prices) + 1.5;
  const lo = Math.min(...prices) - 1.5;
  const Y = (p) => (hi - p) / (hi - lo) * H;
  const axisX = compact ? 116 : 150;
  const cardX = compact ? 188 : 238;
  const busX = (axisX + cardX) / 2;
  const cardH = 90,gap = 12;

  // de-collide tier cards top→bottom
  let lastBottom = -Infinity;
  const placed = [...tiers].
  sort((a, b) => Y(a.level) - Y(b.level)).
  map((t) => {
    let top = Math.max(0, Math.min(H - cardH, Y(t.level) - cardH / 2));
    if (top < lastBottom + gap) top = lastBottom + gap;
    lastBottom = top + cardH;
    return { ...t, top, midY: Y(t.level), cardCenter: top + cardH / 2 };
  });

  return (
    <div className="price-scale-wrap">
      <div className="price-scale-h"><span>QQQ · planned levels</span><span style={{ color: '#5C6773' }}>1D EM {em.low}–{em.high}</span></div>
      <div className="price-scale" style={{ height: H }}>
        {/* vertical axis + caps */}
        <div className="ps-axis" style={{ left: axisX, top: 4, bottom: 4 }} />

        {/* leaders + tier cards — single straight connector per tier */}
        {placed.map((t) =>
        <div className="ps-leader" key={'L' + t.n} style={{ left: axisX + 6, top: t.cardCenter - 1, width: cardX - axisX - 6, height: 2 }} />
        )}

        {/* ticks */}
        {ticks.map((t) =>
        <div key={t.p} style={{ position: 'absolute', left: 0, top: Y(t.p) + (t.dy || 0), width: axisX + 70, height: 0 }}>
            <div className="ps-tick-label" style={{ right: `calc(100% - ${axisX - 12}px)`, top: 0 }}>
              <span className="ps-tick-price" style={{ fontSize: t.big ? 15 : 11.5, color: t.big ? '#fff' : '#C7D2DA' }}>{t.label}</span>
              <div className="ps-tick-role" style={{ color: t.c }}>{t.role}</div>
            </div>
            <div className="ps-tick-dot" style={{ left: axisX, top: 0, width: t.big ? 11 : 9, height: t.big ? 11 : 9, background: t.hollow ? '#18222E' : t.c, border: `2px solid ${t.c}`, boxShadow: t.big ? '0 0 0 3px rgba(129,151,206,0.25)' : 'none' }} />
          </div>
        )}

        {/* tier cards */}
        {placed.map((t) =>
        <div key={t.n} className={`ps-tier-card ${t.state}`} style={{ left: cardX, right: 0, top: t.top }}>
            <div className="ps-tier-name">
              <span className="ps-tier-label">Short Tier {t.n}</span>
              <span className={`ps-tier-state ${t.state}`}>{t.state === 'active' ? 'Allowed' : 'Armed'}</span>
            </div>
            <div className="ps-tier-legs">
              {[['Entry', t.entry], ['Target', t.target], ['Stop', t.stop]].map(([k, v]) =>
            <div key={k}><div className="ps-tier-leg-l">{k}</div><div className="ps-tier-leg-v">{v}</div></div>
            )}
            </div>
            <div className="ps-tier-invalid"><span className="ps-tier-invalid-l">Thesis invalidation</span>{t.invalidation}</div>
          </div>
        )}
      </div>
    </div>);

}

// ============================================================
// TIER PLAYBOOK — full swing-tier breakdown below the price scale
// ============================================================
function TierPlaybook({ tiers }) {
  const rows = [
  ['Zone type', 'zoneType'],
  ['Zone / level', 'zone'],
  ['Swing activation', 'activation'],
  ['Thesis invalidation', 'invalidation'],
  ['Destination zones', 'destination']];

  return (
    <div className="tier-pb">
      <div className="tier-pb-head">Swing tier playbook</div>
      <div className="tier-pb-grid">
        {tiers.map((t) =>
        <div className={`tier-pb-card ${t.state}`} key={t.n}>
            <div className="tier-pb-top">
              <span className="tier-pb-name">Short Tier {t.n}</span>
              <span className={`tier-pb-state ${t.state}`}>{t.state === 'active' ? 'Allowed' : 'Armed'}</span>
            </div>
            <div className="tier-pb-setup">{t.setup}</div>
            <dl className="tier-pb-dl">
              {rows.map(([label, key]) =>
            <div className="tier-pb-row" key={key}>
                  <dt>{label}</dt><dd>{t[key]}</dd>
                </div>
            )}
            </dl>
          </div>
        )}
      </div>
    </div>);

}

// ============================================================
// TV CHARTING — live Advanced Chart widget (QQQ 30m) + deep-link
// ============================================================
function TvCharting() {
  return (
    <div className="tv-charting">
      <div className="tv-charting-head">
        <a className="tv-deeplink" href="https://www.tradingview.com/script/nQMXkpBp-QQQ-Pro-Plan-Zone/" target="_blank" rel="noopener noreferrer">Open on TradingView ↗</a>
        <span className="tv-charting-eb">QQQ Pro Plan Zone · charting</span>
      </div>
      <p className="tv-shot-cap">A live frame of the published <a href="https://www.tradingview.com/script/nQMXkpBp-QQQ-Pro-Plan-Zone/" target="_blank" rel="noopener noreferrer">QQQ Pro Plan Zone</a> chart on TradingView — it re-pulls on every visit and refreshes automatically each time the plan is republished.</p>
      <a className="tv-shot" href="https://www.tradingview.com/script/nQMXkpBp-QQQ-Pro-Plan-Zone/" target="_blank" rel="noopener noreferrer" aria-label="Open the QQQ Pro Plan Zone on TradingView">
        <img className="tv-shot-img" src={`https://s3.tradingview.com/n/nQMXkpBp_big.png?t=${Date.now()}`} alt="QQQ Pro Plan Zone — live chart from TradingView" loading="lazy" onError={(e) => {e.currentTarget.setAttribute('data-failed', '1');}} />
      </a>
    </div>);

}

// ============================================================
// PREMARKET PLAN HERO — today's plan, free, before the bell
// Self-fetches premarket_sectors.json (like the other embeds).
// ============================================================
function PremarketPlanHero({ onJoin }) {
  const [pm, setPm] = hsUseState(null);
  hsUseEffect(() => {
    const R = window.__resources || {};
    const url = R.premarket || 'data/premarket_sectors.json';
    fetch(url).then((r) => r.ok ? r.json() : Promise.reject(r.status)).then(setPm).catch(() => {});
  }, []);

  if (!pm) {
    return (
      <section className="plan-hero" id="plan">
        <div className="plan-hero-wrap">
          <div className="plan-hero-head">
            <p className="plan-hero-eb">Today · pre-open</p>
            <h2 className="plan-hero-h">Pre-Market Plan</h2>
          </div>
          <div className="plan-panel" style={{ minHeight: 220, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#7E8893', fontFamily: 'var(--font-sans)' }}>Loading today's plan…</div>
        </div>
      </section>);

  }

  const m = pm.meta;
  const spot = m.anchor?.price ?? 716;
  const em = m.expected_move?.d1 || { low: spot - 7, high: spot + 7 };
  // punchy day label from the session date, e.g. "Tuesday 9 Jun"
  const _WD = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  const _MO = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  let dayLabel = m.session_label || 'Today';
  if (m.session && /^\d{4}-\d{2}-\d{2}$/.test(m.session)) {
    const [yy, mm, dd] = m.session.split('-').map(Number);
    const wd = new Date(Date.UTC(yy, mm - 1, dd)).getUTCDay();
    dayLabel = `${_WD[wd]} ${dd} ${_MO[mm - 1]}`;
  }
  // levels from the structure sector
  const flip = 727.77,callWall = 730.0,putWall = 700.0,swingLow = 686.37;

  const ticks = [
  { p: callWall, label: callWall.toFixed(1), role: 'Call wall · cap', c: 'var(--loss, #A14A47)' },
  { p: flip, label: flip.toFixed(2), role: 'Gamma flip · Tier 1 shelf', c: 'var(--loss, #A14A47)' },
  { p: spot, label: spot.toFixed(2), role: 'QQQ spot · 6/9 close', c: 'var(--accent, #4B5E8E)', big: true },
  { p: putWall, label: putWall.toFixed(1), role: 'Put wall · Tier 2 trigger', c: 'var(--ink, #1F2937)' },
  { p: swingLow, label: swingLow.toFixed(2), role: '6/9 low · 50D EMA', c: 'var(--loss, #A14A47)' }];

  const tiers = [
  { n: '1', level: flip, entry: '727.3–728.3', target: '716.5', stop: '730.5', state: 'active', cond: 'Reject the 727.8 flip / 730 call-wall shelf',
    setup: 'Setup E — Failed-Breakout / Reversal Short', zoneType: 'Options pivot + EMA confluence', zone: '727.27–728.27 (≈1.00 pt)',
    activation: 'Rally into 727.3–728.3, rejection, daily close back below 724.00', invalidation: 'Daily close above 730.50 (reclaims flip + call wall)',
    destination: '716.52 EMA20 → 707.83 → 700.00 put wall' },
  { n: '2', level: putWall, entry: '<699.5', target: '686.4', stop: '706.0', state: 'armed', cond: 'Decisive daily close below the 700 put wall (PPI Thu)',
    setup: 'Setup C extension — Put-Wall Break Fade', zoneType: 'Options level', zone: '699.50–700.50 (≈1.00 pt)',
    activation: 'Daily close below 699.50 (PPI Thu catalyst)', invalidation: 'Daily close back above 706.00',
    destination: '686.37 / 685.28 (50D) → 684.10 monthly EM low' }];


  const allowed = m.composite?.allowed || [];
  const blocked = m.composite?.blocked || [];
  const compact = typeof window !== 'undefined' && window.innerWidth < 760;

  return (
    <section className="plan-hero" id="plan">
      <div className="plan-hero-wrap">
        <div className="plan-hero-head">
          <h2 className="plan-hero-h">Pre-Market Plan</h2>
          <div className="plan-hero-meta">
            <div className="phm"><span className="k">Session</span><span className="v">{m.session_label}</span></div>
            <div className="phm"><span className="k">Rulebook</span><span className="v">{(m.rulebook || '').replace(/\s*\(.*\)$/, '')}</span></div>
            <div className="phm"><span className="k">Composite</span><span className="v">{m.composite?.label}</span></div>
            <div className="phm"><span className="k">Risk mode</span><span className="v">Trade as planned · full size</span></div>
          </div>
        </div>

        <div className="plan-panel">
          <div className="allow-2col">
            <div className="a2-col ok">
              <p className="a2-h" style={{ fontSize: "18px" }}>Allowed</p>
              {allowed.map((t, i) => <div className="a2-row" key={i}><span className="a2-m">+</span><span>{t}</span></div>)}
            </div>
            <div className="a2-rule" />
            <div className="a2-col no">
              <p className="a2-h" style={{ fontSize: "18px" }}>Not allowed</p>
              {blocked.map((t, i) => <div className="a2-row" key={i}><span className="a2-m">−</span><span>{t}</span></div>)}
            </div>
          </div>
          <PriceScale spot={spot} em={em} ticks={ticks} tiers={tiers} compact={compact} />

          <PlanCandidates tiers={tiers} spot={spot} />

          <OpenPositions />

          <TvCharting />
        </div>
      </div>
    </section>);

}

// ============================================================
// PLAN CANDIDATES — today's new plan tiers + untriggered carry-
// forwards (past 5 sessions), each with distance to pre-market price.
// ============================================================
function PlanCandidates({ tiers, spot }) {
  const [unt, setUnt] = hsUseState([]);
  hsUseEffect(() => {
    const R = window.__resources || {};
    fetch(R.trades || 'data/trades.json').then((r) => r.ok ? r.json() : Promise.reject(r.status)).then((d) => setUnt(d.untriggered_plans || [])).catch(() => {});
  }, []);
  const dist = (lvl) => {if (lvl == null) return '\u2014';const d = lvl - spot;return (d >= 0 ? '+' : '\u2212') + Math.abs(d).toFixed(2);};
  const today = (tiers || []).map((t) => ({ key: 't' + t.n, label: 'Short Tier ' + t.n, dir: 'short', trigger: t.entry, level: t.level, cond: t.cond || '\u2014', state: t.state === 'active' ? 'Allowed' : 'Armed', when: 'New \u00b7 today' }));
  const past = (unt || []).slice(0, 8).map((u, i) => ({
    key: 'u' + i, label: u.plan_id || u.label || 'Carry \u00b7 ' + (u.date || ''),
    dir: u.direction || '', trigger: u.qqq ? `${u.qqq.low}\u2013${u.qqq.high}` : u.note || '\u2014',
    level: u.qqq ? u.qqq.low : null, cond: u.activation || u.note || '\u2014', state: (u.status || 'carried').replace(/_/g, ' '), when: u.date || 'carry-forward'
  }));
  const rows = [...today, ...past];
  return (
    <div className="plan-cand">
      <div className="open-pos-head">
        <span className="open-pos-eb">Plan to watch</span>
        <span className="open-pos-note">new plan + untriggered carry-forwards (past 5 sessions)</span>
      </div>
      <div className="pc-table">
        <div className="pc-row pc-head">
          <span>Plan</span><span>Dir</span><span>Trigger zone</span><span>Condition to activate</span><span className="r">Dist to PM</span><span className="r">Status</span>
        </div>
        {rows.length === 0 ?
        <div className="pc-empty">No active candidates into today.</div> :
        rows.map((r) =>
        <div className="pc-row" key={r.key}>
            <span className="pc-name">{r.label}</span>
            <span className={`pc-dir ${r.dir}`}>{r.dir === 'short' ? '\u25BC Short' : r.dir === 'long' ? '\u25B2 Long' : '\u2014'}</span>
            <span className="pc-trig">{r.trigger}</span>
            <span className="pc-cond">{r.cond}</span>
            <span className="r pc-dist">{dist(r.level)}</span>
            <span className="r"><span className={`pc-state ${String(r.state).toLowerCase().replace(/\s/g, '-')}`}>{r.state}</span></span>
          </div>
        )}
      </div>
    </div>);

}

// ============================================================
// OPEN POSITIONS — carried into today, each with a planned action.
// Part of the premarket plan. Self-fetches performance.json for
// open_positions[]; degrades to a clean "flat" state when none.
// ============================================================
function OpenPositions() {
  const [perf, setPerf] = hsUseState(null);
  hsUseEffect(() => {
    const R = window.__resources || {};
    fetch(R.performance || 'data/performance.json').then((r) => r.ok ? r.json() : Promise.reject(r.status)).then(setPerf).catch(() => {});
  }, []);
  const positions = perf && perf.open_positions || [];
  const fmtP = (n) => n == null ? '\u2014' : Number(n).toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 2 });
  const fmtUSD = (n) => (n >= 0 ? '+$' : '\u2212$') + Math.abs(Math.round(n)).toLocaleString();
  return (
    <div className="open-pos">
      <div className="open-pos-head">
        <span className="open-pos-eb">Open positions · planned action</span>
        <span className="open-pos-note">carried into today — how each is managed</span>
      </div>
      {positions.length === 0 ?
      <div className="open-pos-empty"><span className="dot" />Flat into the open — no positions carried overnight. Today starts clean.</div> :
      <div className="open-pos-list">
          {positions.map((p, i) => {
          const up = (p.unrealized_pnl_usd || 0) >= 0;
          const isLong = p.direction === 'long';
          const action = p.planned_action || `Manage to plan · stop ${fmtP(p.stop_price)} · trail on follow-through, no adds`;
          return (
            <div className="open-pos-row" key={p.id || i}>
                <div className="opr-l">
                  <div className="opr-top">
                    <span className={`opr-dir ${isLong ? 'long' : 'short'}`}>{isLong ? '\u25B2 Long' : '\u25BC Short'}</span>
                    <span className="opr-label">{p.label}</span>
                    <span className="opr-size">{p.size} {p.contract}</span>
                    <span className={`opr-pnl ${up ? 'up' : 'down'}`}>{fmtUSD(p.unrealized_pnl_usd)}</span>
                  </div>
                  <div className="opr-legs">
                    <span><i>entry</i> {fmtP(p.entry_price)}</span>
                    <span><i>mark</i> {fmtP(p.current_mark)}</span>
                    <span><i>stop</i> {fmtP(p.stop_price)}</span>
                  </div>
                </div>
                <div className="opr-action">
                  <span className="opr-action-eb">Planned action</span>
                  <span className="opr-action-t">{action}</span>
                </div>
              </div>);
        })}
        </div>
      }
    </div>);

}

// ============================================================
// EMAIL CAPTURE — free, notify before the open (stub, persists locally)
// ============================================================
function EmailCapture() {
  const [email, setEmail] = hsUseState('');
  const [done, setDone] = hsUseState(false);
  hsUseEffect(() => {
    try {if (localStorage.getItem('ttd:planEmail')) setDone(true);} catch (e) {}
  }, []);
  const submit = (e) => {
    e.preventDefault();
    if (!/.+@.+\..+/.test(email)) return;
    try {localStorage.setItem('ttd:planEmail', email);} catch (e2) {}
    setDone(true);
  };
  if (done) {
    return (
      <div className="email-cap done">
        <div className="email-cap-done"><span className="dot" />You're on the list — today's plan lands in your inbox ~30 min before the US open. Free, always.</div>
      </div>);

  }
  return (
    <div className="email-cap">
      <div className="email-cap-copy">
        <div className="email-cap-eb">Free · before the open</div>
        <div className="email-cap-h">Get today's plan in your inbox</div>
        <div className="email-cap-sub">The full pre-market map, ~30 minutes before the bell. No price, no pitch — the map is free.</div>
      </div>
      <form className="email-cap-form" onSubmit={submit}>
        <input className="email-cap-input" type="email" required placeholder="you@email.com" aria-label="Your email" value={email} onChange={(e) => setEmail(e.target.value)} />
        <button className="email-cap-btn" type="submit">Email me the plan</button>
      </form>
    </div>);

}

// ============================================================
// TRADE WITH TANK — the live desk (Discord), live-only value
// ============================================================
function TradeWithTank({ onJoin }) {
  return (
    <section className="pad" id="cta">
      <div className="t1-cta">
        <div className="t1-cta-eb">the live desk</div>
        <div className="t1-cta-h">The map is free. <em>The operating room is paid.</em></div>
        <p className="t1-cta-p">
          The full pre-market plan above is public, every day. <b>Trade with Tank</b> is the live room: a daily 5-minute video walkthrough and live execution &amp; order commentary as the plan meets the tape. Post-market review isn't locked away — it's the calendar and performance dashboard on this site, free. You're paying to learn the process while it runs, not for signals.
        </p>
        <button className="t1-cta-btn" onClick={onJoin} style={{ marginTop: 14 }}>Trade with Tank →</button>
        {DSDisclaimer ? <div style={{ marginTop: 14 }}><DSDisclaimer onDark /></div> : null}
      </div>
    </section>);

}

// ============================================================
// MARKET DATA SHEET — today's raw indicator verification sheet.
// Mirrors the calendar workbench's Market Data tab (same .mdv-/.mdf-
// structure), driven by today's premarket_sectors.json sectors.
// ============================================================
function MarketDataSheet() {
  const [pm, setPm] = hsUseState(null);
  const [openSet, setOpenSet] = hsUseState([]);
  hsUseEffect(() => {
    const R = window.__resources || {};
    const url = R.premarket || 'data/premarket_sectors.json';
    fetch(url).then((r) => r.ok ? r.json() : Promise.reject(r.status)).then((d) => {setPm(d);setOpenSet((d.sectors || []).map((_, i) => i));}).catch(() => {});
  }, []);

  const statusCls = (s) => {
    const u = (s || '').toUpperCase();
    if (u === 'BULL' || u === 'BULLISH') return 'bull';
    if (u === 'BEAR' || u === 'BEARISH') return 'bear';
    if (u === 'NEUTRAL' || u === 'NEUT') return 'neut';
    return 'none';
  };
  const confCls = (c) => {
    const u = (c || '').toUpperCase();
    if (u === 'HIGH') return 'high';
    if (u === 'LOW') return 'low';
    return 'med';
  };
  const verdictCls = (v) => v === 'bullish' ? 'bull' : v === 'bearish' ? 'bear' : 'neut';

  if (!pm) {
    return (
      <section className="md-sheet-sec">
        <div className="md-sheet-wrap">
          <div className="md-sheet-head"><h2 className="md-sheet-h">Pre-Market Data</h2></div>
          <div style={{ minHeight: 160, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#7E8893', fontFamily: 'var(--font-sans)' }}>Loading the raw data sheet…</div>
        </div>
      </section>);

  }

  const sectors = pm.sectors || [];
  return (
    <section className="md-sheet-sec" id="market-data">
      <div className="md-sheet-wrap">
        <div className="md-sheet-head">
          <h2 className="md-sheet-h">Pre-Market Data</h2>
          <div className="md-sheet-meta">
            <div className="mm"><span className="k">Session</span><span className="v">{pm.meta?.session_label}</span></div>
            <div className="mm"><span className="k">Rulebook</span><span className="v">{(pm.meta?.rulebook || '').replace(/\s*\(.*\)$/, '')}</span></div>
          </div>
        </div>
        <div className="md-scr-bar">
          <button className="md-scr-toggle" onClick={() => setOpenSet(openSet.length === (pm.sectors || []).length ? [] : (pm.sectors || []).map((_, i) => i))}>
            {openSet.length === (pm.sectors || []).length ? 'Collapse all' : 'Expand all'}
          </button>
        </div>
        <table className="md-scr">
          <thead><tr><th>Indicator</th><th>Reading</th><th className="c">Status</th><th className="c">Conf.</th></tr></thead>
          <tbody>
            {sectors.map((g, gi) => {
              const open = openSet.includes(gi);
              return [
              <tr className={'md-scr-mod' + (open ? ' open' : '')} key={'m' + (g.id || gi)} onClick={() => setOpenSet(open ? openSet.filter((i) => i !== gi) : [...openSet, gi])}>
                <td colSpan="2"><span className="md-scr-caret">{open ? '−' : '+'}</span>{g.num ? g.num + ' \u00b7 ' : ''}{g.full_name || g.name}</td>
                <td className={'c md-scr-mc ' + verdictCls(g.verdict)} colSpan="2">{g.score || g.tag}</td>
              </tr>,
              ...(open ? (g.indicators || []).map((r, ri) =>
              <tr className="md-scr-ir" key={(g.id || gi) + '-' + ri}>
                  <td className="md-scr-ind">{r.name}</td>
                  <td className="md-scr-read">{r.reading}</td>
                  <td className={'c md-scr-stat ' + statusCls(r.status)}>{r.status}</td>
                  <td className="c md-scr-conf">{r.conf}</td>
                </tr>) : [])];
            })}
          </tbody>
        </table>
      </div>
    </section>);

}

Object.assign(window, {
  KpiTicker, SystemPipeline, PriceScale, TvCharting, PremarketPlanHero, OpenPositions, PlanCandidates, EmailCapture, TradeWithTank, MarketDataSheet
});