// Catalysts module — hero countdown for next big event + horizontal week rail.
// Designed for dopamine: live ticker, impact badges, "PLAY" CTA on each card.

(function() {
  const useStateC = React.useState;
  const useEffectC = React.useEffect;

  const IMPACT = {
    mega: { label: 'MEGA',   color: 'var(--acid)',  bg: 'rgba(212,255,77,0.10)',  border: 'rgba(212,255,77,0.35)' },
    high: { label: 'HIGH',   color: 'var(--coral)', bg: 'rgba(255,107,107,0.08)', border: 'rgba(255,107,107,0.30)' },
    med:  { label: 'MED',    color: 'var(--amber)', bg: 'rgba(255,176,84,0.08)',  border: 'rgba(255,176,84,0.30)' },
    low:  { label: 'LOW',    color: 'var(--text-3)',bg: 'var(--bg-elev-2)',       border: 'var(--line-subtle)' },
  };

  function fmtCountdown(hours) {
    if (hours < 1) return { big: '<1', unit: 'hour', d: 0, h: 0, m: Math.round(hours * 60) };
    if (hours < 24) {
      const h = Math.floor(hours);
      const m = Math.round((hours - h) * 60);
      return { big: h, unit: h === 1 ? 'hour' : 'hours', d: 0, h, m };
    }
    const d = Math.floor(hours / 24);
    const h = Math.round(hours - d * 24);
    return { big: d, unit: d === 1 ? 'day' : 'days', d, h, m: 0 };
  }

  // ============== Catalysts hero + rail ==============
  function CatalystsBlock({ go, openTicket }) {
    const VD = window.VD;
    const all = VD.VD_CATALYSTS;
    const next = all[0]; // FOMC May 7
    const rail = all.slice(1, 6);

    // Live tick
    const [tick, setTick] = useStateC(0);
    useEffectC(() => {
      const t = setInterval(() => setTick(x => x + 1), 1000);
      return () => clearInterval(t);
    }, []);

    // Decrement countdown by elapsed seconds (mock — assets are static; we just shave seconds)
    const liveHours = Math.max(0.001, next.hours - tick / 3600);

    return (
      <div>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 16 }}>
          <div>
            <div className="cap-sm" style={{ color: 'var(--text-3)', marginBottom: 6 }}>↳ The week ahead · {all.length} live catalysts</div>
            <h2 className="serif" style={{ fontSize: 36, fontWeight: 400, letterSpacing: '-0.025em', margin: 0, lineHeight: 1 }}>
              What's <em style={{ color: 'var(--acid)' }}>about to happen</em>?
            </h2>
          </div>
          <button onClick={() => go('strategies')} className="btn" style={{ padding: '8px 14px', fontSize: 12 }}>
            All catalysts →
          </button>
        </div>

        {/* HERO countdown card */}
        <CatalystHero c={next} hours={liveHours} go={go} openTicket={openTicket} />

        {/* Horizontal rail */}
        <div style={{ marginTop: 16 }}>
          <div className="cap-sm" style={{ marginBottom: 10, color: 'var(--text-3)' }}>Next up · 5 events</div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: `repeat(${rail.length}, 1fr)`,
            gap: 10,
          }}>
            {rail.map(c => <CatalystCard key={c.id} c={c} go={go} />)}
          </div>
        </div>
      </div>
    );
  }

  // ============== Hero countdown ==============
  function CatalystHero({ c, hours, go, openTicket }) {
    const VD = window.VD;
    const { AssetGlyph } = window.VDIcons;
    const cd = fmtCountdown(hours);
    const imp = IMPACT[c.impact];
    const a = VD.VD_ASSETS.find(x => x.sym === c.asset);

    // For sub-day events show H:M:S
    const showHMS = hours < 48;
    const totalSec = Math.max(0, Math.floor(hours * 3600));
    const dd = Math.floor(totalSec / 86400);
    const hh = Math.floor((totalSec % 86400) / 3600);
    const mm = Math.floor((totalSec % 3600) / 60);
    const ss = totalSec % 60;

    return (
      <button onClick={() => go('catalyst', c.id)} style={{
        display: 'block', width: '100%', textAlign: 'left',
        padding: 0, border: 'none', cursor: 'pointer',
        background: 'transparent',
      }}>
        <div style={{
          position: 'relative', overflow: 'hidden',
          background: 'linear-gradient(135deg, var(--bg-elev) 0%, rgba(212,255,77,0.04) 100%)',
          border: `1px solid ${imp.border}`,
          borderRadius: 0, // sharp
          padding: '24px 28px',
          display: 'grid', gridTemplateColumns: '1fr auto', gap: 24, alignItems: 'center',
        }}>
          {/* Sweep highlight */}
          <div style={{
            position: 'absolute', top: 0, right: 0, width: 240, height: '100%',
            background: `radial-gradient(circle at 80% 50%, ${imp.bg}, transparent 70%)`,
            pointerEvents: 'none',
          }} />

          {/* LEFT: meta */}
          <div style={{ position: 'relative', zIndex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
              <span style={{
                padding: '3px 8px', fontSize: 10, fontWeight: 700,
                color: imp.color, background: imp.bg, border: `1px solid ${imp.border}`,
                fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.12em',
              }}>{imp.label} IMPACT</span>
              <span style={{ fontSize: 11, color: 'var(--text-3)', fontFamily: 'JetBrains Mono, monospace', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
                NEXT · {c.day} {c.date}
              </span>
              <span style={{ fontSize: 11, color: 'var(--text-3)' }}>· {c.markets} markets · vol {c.volume}</span>
            </div>
            <h3 className="serif" style={{ fontSize: 44, fontWeight: 400, letterSpacing: '-0.030em', lineHeight: 1, margin: '0 0 8px' }}>
              {c.name}
            </h3>
            <p style={{ color: 'var(--text-2)', fontSize: 14, lineHeight: 1.45, margin: 0, maxWidth: 520 }}>{c.desc}</p>

            {/* Live odds bar */}
            <div style={{ marginTop: 18, maxWidth: 480 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 4 }}>
                <span style={{ fontSize: 11, color: 'var(--text-3)', fontFamily: 'JetBrains Mono, monospace' }}>
                  "{c.yesQ}"
                </span>
                <span className="num" style={{ fontSize: 11, color: 'var(--text-3)' }}>
                  YES {Math.round(c.yesOdds * 100)}¢ · NO {Math.round((1 - c.yesOdds) * 100)}¢
                </span>
              </div>
              <div style={{ height: 8, background: 'var(--bg-elev-2)', position: 'relative', display: 'flex', overflow: 'hidden' }}>
                <div style={{ width: `${c.yesOdds * 100}%`, background: 'var(--mint)' }} />
                <div style={{ flex: 1, background: 'var(--coral)' }} />
              </div>
            </div>
          </div>

          {/* RIGHT: countdown clock */}
          <div style={{ position: 'relative', zIndex: 1, textAlign: 'right' }}>
            <div className="cap-sm" style={{ color: 'var(--text-3)', marginBottom: 6, fontSize: 9 }}>resolves in</div>
            {showHMS ? (
              <div style={{ display: 'flex', gap: 8, alignItems: 'flex-end', justifyContent: 'flex-end' }}>
                {dd > 0 && <ClockUnit n={dd} unit="d" />}
                <ClockUnit n={hh} unit="h" />
                <ClockUnit n={mm} unit="m" />
                <ClockUnit n={ss} unit="s" pulse />
              </div>
            ) : (
              <div>
                <div className="num dlg" style={{ fontSize: 88, fontWeight: 600, color: 'var(--acid)', letterSpacing: '-0.04em', lineHeight: 0.9 }}>
                  {cd.big}
                </div>
                <div style={{ fontSize: 14, color: 'var(--text-2)', textTransform: 'uppercase', letterSpacing: '0.12em', fontFamily: 'JetBrains Mono, monospace', fontWeight: 600 }}>
                  {cd.unit}
                </div>
              </div>
            )}
            <div style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'flex-end' }}>
              <AssetGlyph sym={c.asset} size={18} />
              <span style={{ fontSize: 12, color: 'var(--text-2)', fontWeight: 600 }}>{c.asset}</span>
              <span className="num" style={{ fontSize: 11, color: a.change >= 0 ? 'var(--mint)' : 'var(--coral)' }}>
                {a.change >= 0 ? '+' : ''}{a.change.toFixed(2)}%
              </span>
            </div>
          </div>
        </div>
      </button>
    );
  }

  function ClockUnit({ n, unit, pulse }) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', minWidth: 56 }}>
        <span className="num" style={{
          fontSize: 44, fontWeight: 600, color: pulse ? 'var(--acid)' : 'var(--text)',
          letterSpacing: '-0.025em', lineHeight: 0.9,
          fontFamily: 'JetBrains Mono, monospace',
          fontVariantNumeric: 'tabular-nums',
          textShadow: pulse ? '0 0 20px rgba(212,255,77,0.4)' : 'none',
          transition: 'all 100ms',
        }}>{String(n).padStart(2, '0')}</span>
        <span style={{
          fontSize: 9, color: 'var(--text-3)',
          fontFamily: 'JetBrains Mono, monospace', textTransform: 'uppercase', letterSpacing: '0.15em',
          marginTop: 4,
        }}>{unit}</span>
      </div>
    );
  }

  // ============== Compact rail card ==============
  function CatalystCard({ c, go }) {
    const VD = window.VD;
    const { AssetGlyph } = window.VDIcons;
    const cd = fmtCountdown(c.hours);
    const imp = IMPACT[c.impact];

    return (
      <button onClick={() => go('catalyst', c.id)} style={{
        background: 'var(--bg-elev)', border: '1px solid var(--line-subtle)',
        padding: '14px 14px 12px', textAlign: 'left', cursor: 'pointer',
        display: 'flex', flexDirection: 'column', gap: 8,
        transition: 'all 120ms var(--ease)', position: 'relative', overflow: 'hidden',
      }}
        onMouseEnter={e => { e.currentTarget.style.borderColor = imp.color; e.currentTarget.style.background = 'var(--bg-elev-2)'; }}
        onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line-subtle)'; e.currentTarget.style.background = 'var(--bg-elev)'; }}
      >
        {/* Top: date + impact */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>
            {c.day} · {c.date}
          </div>
          <span style={{
            padding: '2px 5px', fontSize: 8, fontWeight: 700,
            color: imp.color, background: imp.bg, border: `1px solid ${imp.border}`,
            fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.1em',
          }}>{imp.label}</span>
        </div>

        {/* Name */}
        <div style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.2, letterSpacing: '-0.01em' }}>{c.name}</div>

        {/* Asset chip + countdown */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 'auto' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <AssetGlyph sym={c.asset} size={16} />
            <span style={{ fontSize: 11, color: 'var(--text-2)', fontWeight: 600 }}>{c.asset}</span>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="num" style={{ fontSize: 18, fontWeight: 700, color: imp.color, lineHeight: 1, fontFamily: 'JetBrains Mono, monospace' }}>
              {cd.big}<span style={{ fontSize: 10, fontWeight: 400, marginLeft: 2, color: 'var(--text-3)' }}>{cd.unit[0]}</span>
            </div>
          </div>
        </div>

        {/* Mini odds bar */}
        <div style={{ height: 3, background: 'var(--bg-elev-2)', display: 'flex' }}>
          <div style={{ width: `${c.yesOdds * 100}%`, background: 'var(--mint)' }} />
          <div style={{ flex: 1, background: 'var(--coral)' }} />
        </div>
      </button>
    );
  }

  window.VDCatalysts = { CatalystsBlock };
})();
