// ============================================================
// RADAR TEASER -- desktop section for index.html
// Renders the live QQQ Coupling-Onset RadarPlot (from radar-core.jsx)
// inside a dark navy section with as-of bar and CTA.
// Now polarity-aware: shows BULL-QQQ / BEAR-QQQ / WATCH dots.
// Exports window.RadarTeaser
// ============================================================
(function () {
  const { useState, useEffect, useMemo } = React;

  function rtFmtAsof(iso) {
    if (!iso) return '';
    const [y, m, d] = iso.split('-').map(Number);
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    return months[m - 1] + ' ' + d + ', ' + y;
  }

  function RadarTeaser() {
    const [payload, setPayload] = useState(null);

    useEffect(() => {
      fetch('data/radar.json', { cache: 'no-store' }).
      then((r) => {if (!r.ok) throw 0;return r.json();}).
      then((j) => setPayload(j)).
      catch(() => {});
    }, []);

    const meta = payload ? payload.meta : {};
    const allRows = payload ? payload.rows : [];
    const hl = '5', thr = 0.3;

    const radarRows = useMemo(() => {
      if (!payload || !window.classify) return [];
      const active = allRows.filter((r) => window.classify(r, hl, thr) !== 'stable');
      active.sort((a, b) => {
        const ha = (a.hl[hl] || a.hl['5']).onset;
        const hb = (b.hl[hl] || b.hl['5']).onset;
        return Math.abs(hb) - Math.abs(ha);
      });
      return active.slice(0, 28);
    }, [payload]);

    return (
      <section className="radar-page" id="market-sensing"
      style={{ borderTop: '1px solid rgba(255,255,255,0.07)' }}>
        <div className="radar-shell" style={{ minHeight: 'auto' }}>
          <div className="sec">
            <h2 className="sec-h">What just turned bullish or bearish for QQQ</h2>
            <p className="sec-d">
              Each active instrument sits on a spoke grouped by class. Distance from the center is its{' '}
              <b>beta to QQQ</b>; the faint ring marks beta 5 sessions ago and the solid dot is today --
              the <b>drift between them is the coupling onset</b>. Color reads polarity-aware:
              green = BULL-QQQ, red = BEAR-QQQ, amber = WATCH.
            </p>
            {meta.asof &&
            <div className="asof-bar in-sec">
                <span className="asof-dot" />
                <span className="asof-txt">
                  As of prior close<span className="sep">·</span>before open{' '}
                  <b>{rtFmtAsof(meta.asof)}</b>
                </span>
                <span className="asof-right">{meta.n} instruments scanned</span>
              </div>
            }
            {window.RadarPlot ?
            <window.RadarPlot rows={radarRows} hl={hl} thr={thr} betaCap={2.5} /> :

            <div style={{ height: 180, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'rgba(149,169,171,0.55)', fontFamily: 'var(--sb-fmono)', fontSize: 12, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
                  Loading radar data...
                </div>

            }
          </div>

          {/* CTA strip */}
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            flexWrap: 'wrap', gap: 14, padding: '18px 22px 36px',
            borderTop: '1px solid rgba(255,255,255,0.07)'
          }}>
            <p style={{
              fontFamily: 'var(--sb-fsans)', fontSize: 13.5, lineHeight: 1.55, margin: 0,
              color: 'rgba(149,169,171,0.85)', maxWidth: '60ch'
            }}>
              The full page shows the QQQ signal feed, the regime + fragility read, and the sortable universe table with sparklines for every tracked instrument.
            </p>
            <a href="market-sensing.html" style={{
              display: 'inline-flex', alignItems: 'center', gap: 9,
              background: 'rgba(220,180,130,0.12)', color: '#DCB482',
              border: '1px solid rgba(220,180,130,0.32)', borderRadius: 999,
              fontFamily: 'var(--sb-fsans)', fontSize: 13, fontWeight: 700,
              padding: '11px 20px', textDecoration: 'none', whiteSpace: 'nowrap',
              transition: 'background 140ms ease, border-color 140ms ease'
            }}>
              Open Market Sensing
              <span style={{ fontFamily: 'Georgia, serif', fontStyle: 'italic', fontWeight: 700, fontSize: 16, lineHeight: 1 }}>→</span>
            </a>
          </div>
        </div>
      </section>);

  }

  Object.assign(window, { RadarTeaser });
})();
