// ============================================================
// MARKET SENSOR TEASER — desktop section for index.html
// Replaces the old RadarTeaser. Reads data/pulse.json and shows
// today's volatility-regime read (state chip + composite z +
// action) inside the existing dark .radar-page shell, with a CTA
// to the full market-sensor.html page. Degrades gracefully.
// Exports window.MarketSensorTeaser
// ============================================================
(function () {
  const { useState, useEffect } = React;

  const MST_TONE = { green:'#69B083', navy:'#9CA3AE', amber:'#8197CE', red:'#CC7A6C', purple:'#9B8FB5', grey:'#9CA3AE' };
  const MST_GLYPH = { CONFIRMING:'\u25B2', MILD_BULL:'\u25B2', NEUTRAL:'\u25CF', MILD_BEAR:'\u25BE', WHIPSAW:'\u2195', DIRECTIONAL_RISK:'\u25BC', EVENT_RISK:'\u25C8', UNKNOWN:'?' };
  const MST_SUB = { CONFIRMING:'Trend confirming — trade your plan', MILD_BULL:'Mild bullish tilt', NEUTRAL:'Calm / range conditions', MILD_BEAR:'Informational — not a sell signal', WHIPSAW:'Wide-range warning — size down', DIRECTIONAL_RISK:'Confirmed downside risk', EVENT_RISK:'Scheduled event pending — wait it out', UNKNOWN:'Sensor data unavailable' };
  const MST_FRESH = { previous_session_close:'prev close', previous_close_only:'prev close only', last_48h:'last 48h', live:'live', unavailable:'offline' };

  function mstClockET(meta) {
    const iso = meta && (meta.run_time_utc || meta.run_time_et);
    if (!iso) return '—';
    try { return new Date(iso).toLocaleTimeString('en-US', { timeZone: 'America/New_York', hour: '2-digit', minute: '2-digit', hour12: false }) + ' ET'; }
    catch (e) { return '—'; }
  }
  const mstZ = (v) => (v == null || isNaN(v)) ? '—' : (v >= 0 ? '+' : '\u2212') + Math.abs(v).toFixed(2);

  function MarketSensorTeaser() {
    const [data, setData] = useState(null);
    useEffect(() => {
      fetch('data/pulse.json', { cache: 'no-store' })
        .then((r) => { if (!r.ok) throw 0; return r.json(); })
        .then((j) => setData(j))
        .catch(() => {});
    }, []);

    const s = data ? (data.state || {}) : {};
    const meta = data ? (data.meta || {}) : {};
    const fr = data ? (data.data_freshness || {}) : {};
    const tone = MST_TONE[s.color] || '#9CA3AE';
    const z = data && data.sensors ? data.sensors.composite_z : null;

    return (
      <section className="radar-page" id="market-sensor" style={{ borderTop: '1px solid rgba(255,255,255,0.07)' }}>
        <div className="radar-shell" style={{ minHeight: 'auto' }}>
          <div className="sec">
            <h2 className="sec-h">Today's volatility regime for QQQ</h2>
            <p className="sec-d">
              The Market Sensor reads one thing before the open — the <b>volatility regime</b> — and tells you whether to
              trade your plan, reduce size, widen stops, or stand aside. <b>Structural Bias picks the direction; the Sensor
              adjusts size &amp; stops.</b>
            </p>

            {meta.asof &&
              <div className="asof-bar in-sec">
                <span className="asof-dot" />
                <span className="asof-txt">Updated <b>{mstClockET(meta)}</b><span className="sep">·</span>before open</span>
                <span className="asof-right">prices {MST_FRESH[fr.premarket_quotes] || fr.premarket_quotes || '—'} · news {MST_FRESH[fr.news] || fr.news || '—'}</span>
              </div>
            }

            {data ?
              <div style={{
                display: 'flex', alignItems: 'stretch', gap: 18, flexWrap: 'wrap',
                background: 'rgba(255,255,255,0.035)', border: '1px solid rgba(243,240,232,0.12)',
                borderRadius: 14, padding: '22px 24px', marginTop: 4
              }}>
                <div style={{ flex: '1 1 360px', minWidth: 280 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 11, flexWrap: 'wrap', marginBottom: 12 }}>
                    <span style={{
                      display: 'inline-flex', alignItems: 'center', gap: 8,
                      fontFamily: 'var(--sb-fmono, monospace)', fontWeight: 700, fontSize: 12,
                      letterSpacing: '0.12em', textTransform: 'uppercase', padding: '7px 14px', borderRadius: 999,
                      background: 'color-mix(in srgb,' + tone + ' 20%, transparent)',
                      border: '1px solid color-mix(in srgb,' + tone + ' 60%, transparent)', color: '#fff'
                    }}>
                      <span style={{ color: tone, fontSize: 13, lineHeight: 1 }}>{MST_GLYPH[s.label] || '\u25CF'}</span>{s.label}
                    </span>
                    <span style={{ fontFamily: 'var(--sb-fmono, monospace)', fontSize: 11.5, color: 'rgba(156,163,174,0.9)' }}>{MST_SUB[s.label] || ''}</span>
                  </div>
                  <p style={{ fontFamily: 'var(--sb-fsans, sans-serif)', fontSize: 14.5, lineHeight: 1.55, color: '#F2F4F6', margin: 0 }}>{s.one_line_message}</p>
                </div>

                <div style={{ display: 'flex', alignItems: 'center', gap: 22, flexWrap: 'wrap' }}>
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ fontFamily: 'var(--sb-fdisp, sans-serif)', fontWeight: 700, fontSize: 40, lineHeight: 1, color: tone, fontVariantNumeric: 'tabular-nums' }}>{mstZ(z)}</div>
                    <div style={{ fontFamily: 'var(--sb-fmono, monospace)', fontSize: 9.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'rgba(156,163,174,0.85)', marginTop: 5 }}>Composite z</div>
                  </div>
                  <div style={{
                    borderLeft: '4px solid ' + tone, paddingLeft: 14,
                    background: 'color-mix(in srgb,' + tone + ' 12%, transparent)', borderRadius: 8, padding: '11px 15px 11px 14px'
                  }}>
                    <div style={{ fontFamily: 'var(--sb-fmono, monospace)', fontSize: 9, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: tone, marginBottom: 4 }}>Today's action</div>
                    <div style={{ fontFamily: 'var(--sb-fsans, sans-serif)', fontSize: 16, fontWeight: 700, color: '#F2F4F6' }}>{s.action_label}</div>
                  </div>
                </div>
              </div>
              :
              <div style={{ height: 150, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'rgba(156,163,174,0.55)', fontFamily: 'var(--sb-fmono, monospace)', fontSize: 12, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
                Loading sensor…
              </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, sans-serif)', fontSize: 13.5, lineHeight: 1.55, margin: 0, color: 'rgba(156,163,174,0.85)', maxWidth: '60ch' }}>
              The full page shows how today's state changes your plan, the news catalysts driving it, the composite / leadership / macro sensors, and the 18 inputs behind the score.
            </p>
            <a href="market-sensor.html" style={{
              display: 'inline-flex', alignItems: 'center', gap: 9,
              background: 'rgba(129,151,206,0.14)', color: '#8197CE',
              border: '1px solid rgba(129,151,206,0.34)', borderRadius: 999,
              fontFamily: 'var(--sb-fsans, sans-serif)', fontSize: 13, fontWeight: 700,
              padding: '11px 20px', textDecoration: 'none', whiteSpace: 'nowrap'
            }}>
              Open Market Sensor
              <span style={{ fontFamily: 'var(--sb-fsans, sans-serif)', fontWeight: 700, fontSize: 16, lineHeight: 1 }}>→</span>
            </a>
          </div>
        </div>
      </section>);
  }

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