// App shell — top nav, routing, tweaks panel, modal orchestration
const { useState, useEffect, useMemo } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "proMode": false
}/*EDITMODE-END*/;

function App() {
  const VD = window.VD;
  const { ICONS, Logo, AssetGlyph } = window.VDIcons;
  const { Home, AssetDetail, Strategies, Portfolio } = window.VDPages;
  const { TradeTicket } = window.VDTicket;
  const { Builder } = window.VDBuilder;
  const { Onboarding, Settings } = window.VDOnboarding;
  const { PlayerHUD, PlayerDrawer, WinOverlay, AchievementToast } = window.VDDopamine;

  // Route — { name: 'home'|'asset'|'strategies'|'portfolio', sym?: string, catalystId?: string }
  const [route, setRoute] = useState({ name: 'home' });
  const go = (name, arg) => {
    if (name === 'asset')         setRoute({ name, sym: arg });
    else if (name === 'catalyst') setRoute({ name, id: arg });
    else if (name === 'strategies' && arg) setRoute({ name, sym: arg });
    else                          setRoute({ name });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // Tweaks
  const [tweaks, _setTweak] = useState(TWEAK_DEFAULTS);
  const setTweak = (k, v) => {
    const edits = typeof k === 'object' ? k : { [k]: v };
    _setTweak(s => ({ ...s, ...edits }));
    try { window.parent.postMessage({ type: '__edit_mode_set_keys', edits }, '*'); } catch {}
  };


  // Modals — skip the onboarding modal entirely so the live data lands on first paint
  // (better demo first-impression). It's still reachable from the Tweaks panel via
  // "Replay onboarding" if you want to show it deliberately.
  const [showOnboarding, setShowOnboarding] = useState(false);
  const [showSettings, setShowSettings] = useState(false);
  const [ticket, setTicket] = useState(null);
  const [builderInit, setBuilderInit] = useState(null);
  const [toast, setToast] = useState(null);

  // Dopamine
  const [showPlayer, setShowPlayer] = useState(false);
  const [winOverlay, setWinOverlay] = useState(null);
  const [achQueue, setAchQueue] = useState([]);

  // Listen on the dopamine event bus
  useEffect(() => {
    const off = window.VDDopamine.on((ev) => {
      if (ev.kind === 'celebrate')   setWinOverlay(ev.payload);
      if (ev.kind === 'achievement') setAchQueue(q => [...q, ev.payload]);
    });
    return off;
  }, []);

  // First-time visit achievement toast — disabled for clean first impression on the live demo.
  // Triggerable manually from the Tweaks panel ("Fire achievement toast").

  // Holdings map (sym|side|strike|expiryKey -> {qty, avg})
  const holdings = useMemo(() => {
    const m = {};
    VD.VD_POSITIONS_OPEN.forEach(p => {
      m[`${p.sym}|${p.side}|${p.strike}|fri`] = { qty: p.qty, avg: p.avg, side: p.side, sym: p.sym, strike: p.strike };
    });
    return m;
  }, []);

  const openTicket = (ctx) => {
    if (ctx.builder) { setBuilderInit({ sym: ctx.sym }); return; }
    setTicket(ctx);
  };

  const finalizeOnboarding = () => {
    try { localStorage.setItem('vd-onboarded', '1'); } catch {}
    setShowOnboarding(false);
  };

  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg-base)' }}>
      <TopNav route={route} go={go} onSettings={() => setShowSettings(true)} onPlayer={() => setShowPlayer(true)} />

      {route.name === 'home'       && <Home go={go} account={VD.VD_ACCOUNT} openTicket={openTicket} />}
      {route.name === 'asset'      && <AssetDetail sym={route.sym} go={go} openTicket={openTicket} holdings={holdings} pro={tweaks.proMode} />}
      {route.name === 'strategies' && <Strategies initialSym={route.sym} />}
      {route.name === 'portfolio'  && <Portfolio go={go} account={VD.VD_ACCOUNT} openTicket={openTicket} />}
      {route.name === 'catalyst'   && <CatalystDetail id={route.id} go={go} openTicket={openTicket} />}

      {/* Modals */}
      {showOnboarding && <Onboarding onDone={finalizeOnboarding} />}
      {showSettings   && <Settings onClose={() => setShowSettings(false)} />}
      {showPlayer     && <PlayerDrawer onClose={() => setShowPlayer(false)} />}
      {winOverlay     && <WinOverlay data={winOverlay} onDone={() => setWinOverlay(null)} />}
      {achQueue.length > 0 && <AchievementToast a={achQueue[0]} onDone={() => setAchQueue(q => q.slice(1))} />}
      {ticket && <TradeTicket ctx={ticket} holdings={holdings} pro={tweaks.proMode}
        onClose={() => setTicket(null)}
        onPlace={(o) => { setTicket(null); setToast(`Order placed · ${o.qty} ${o.side} ${o.sym} @ ${o.price}¢`); setTimeout(() => setToast(null), 3200); }} />}
      {builderInit && <Builder initial={builderInit}
        onClose={() => setBuilderInit(null)}
        onPlace={() => { setBuilderInit(null); setToast('Strategy placed'); setTimeout(() => setToast(null), 3200); }} />}

      {/* Toast */}
      {toast && (
        <div className="vd-toast">
          <span style={{ display: 'inline-flex', color: 'var(--mint)' }}>{ICONS.check}</span>
          <span>{toast}</span>
        </div>
      )}

      {/* Tweaks */}
      <TweaksPanel>
        <TweakSection label="Chain mode" />
        <TweakRadio label="Density" value={tweaks.proMode ? 'pro' : 'std'} onChange={(v) => setTweak('proMode', v === 'pro')} options={[{value:'std',label:'Standard'},{value:'pro',label:'Pro'}]} />
        <TweakSection label="Demo" />
        <TweakButton label="Replay onboarding" onClick={() => { try{localStorage.removeItem('vd-onboarded');}catch{}; setShowOnboarding(true); }} />
        <TweakButton label="Trigger WIN celebration" onClick={() => window.VDDopamine.celebrate({ pnl: +1284.50, pct: +147.2, sym: 'BTC', side: 'YES', strike: 95000, xp: 320, streak: 4 })} />
        <TweakButton label="Trigger MISS celebration" onClick={() => window.VDDopamine.celebrate({ pnl: -442.10, pct: -100, sym: 'ETH', side: 'NO', strike: 3500 })} />
        <TweakButton label="Fire achievement toast" onClick={() => window.VDDopamine.achievement(window.VD.VD_ACHIEVEMENTS[3])} />
      </TweaksPanel>
    </div>
  );
}

function TopNav({ route, go, onSettings, onPlayer }) {
  const { Logo, ICONS } = window.VDIcons;
  const { PlayerHUD } = window.VDDopamine;
  const tabs = [['home','Home'],['strategies','Strategies'],['portfolio','Portfolio']];
  const activeIdx = tabs.findIndex(([k]) => k === route.name || (k === 'home' && route.name === 'asset'));

  // Sliding underline: measure each tab's button on layout and animate the bar's position.
  const tabRefs = React.useRef([]);
  const [bar, setBar] = useState({ left: 0, width: 0, ready: false });
  React.useLayoutEffect(() => {
    const el = tabRefs.current[activeIdx];
    if (el) setBar({ left: el.offsetLeft, width: el.offsetWidth, ready: true });
  }, [activeIdx]);
  // Re-measure on resize so the bar stays anchored
  useEffect(() => {
    const onResize = () => {
      const el = tabRefs.current[activeIdx];
      if (el) setBar({ left: el.offsetLeft, width: el.offsetWidth, ready: true });
    };
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, [activeIdx]);

  return (
    <div style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: 'rgba(7,9,12,0.92)',
      backdropFilter: 'blur(10px)',
      borderBottom: '1px solid var(--line-subtle)',
    }}>
      <div style={{ maxWidth: 1240, margin: '0 auto', display: 'grid', gridTemplateColumns: '240px 1fr auto', alignItems: 'center', gap: 16, padding: '14px 32px' }}>
        <button onClick={() => go('home')} className="vd-logo-btn" style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <span className="vd-logo-mark" style={{ display: 'inline-flex', transition: 'transform 320ms var(--spring), filter 320ms var(--ease)' }}>
            <Logo size={36} />
          </span>
          <span className="serif" style={{ fontSize: 30, fontWeight: 400, letterSpacing: '-0.025em', lineHeight: 1 }}>Verdict</span>
        </button>

        <div style={{ display: 'flex', justifyContent: 'center', gap: 0, position: 'relative', borderBottom: '1px solid transparent' }}>
          {tabs.map(([k, l], i) => {
            const active = i === activeIdx;
            return (
              <button key={k} onClick={() => go(k)}
                ref={el => tabRefs.current[i] = el}
                style={{
                  padding: '12px 26px', fontSize: 13.5, fontWeight: 600,
                  color: active ? 'var(--acid)' : 'var(--text-3)',
                  fontFamily: 'JetBrains Mono, monospace',
                  textTransform: 'uppercase', letterSpacing: '0.12em',
                  position: 'relative',
                  transition: 'color 200ms var(--ease)',
                }}
                onMouseEnter={(e) => { if (!active) e.currentTarget.style.color = 'var(--text)'; }}
                onMouseLeave={(e) => { if (!active) e.currentTarget.style.color = 'var(--text-3)'; }}>
                <span style={{ marginRight: 10, fontSize: 10.5, color: active ? 'var(--acid-dim)' : 'var(--text-4)', transition: 'color 200ms var(--ease)' }}>0{i+1}</span>
                {l}
              </button>
            );
          })}
          {/* Sliding underline — animates left+width between tabs */}
          <span style={{
            position: 'absolute',
            bottom: -1,
            left: bar.left + 16,
            width: Math.max(0, bar.width - 32),
            height: 2,
            background: 'var(--acid)',
            boxShadow: '0 0 12px rgba(232,255,82,0.6)',
            opacity: bar.ready ? 1 : 0,
            transition: 'left 360ms cubic-bezier(0.65,0,0.35,1), width 360ms cubic-bezier(0.65,0,0.35,1), opacity 200ms var(--ease)',
            pointerEvents: 'none',
          }} />
        </div>

        <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 8 }}>
          <button className="btn-ghost btn" title="Search (⌘K)" style={{
            width: 36, height: 36, padding: 0, borderRadius: 4, color: 'var(--text-3)',
          }}>{ICONS.search}</button>
          <PlayerHUD onOpen={onPlayer} />
          {window.VDLiveBlock && window.VDLiveBlock.WalletPill && <window.VDLiveBlock.WalletPill />}
          <button onClick={onSettings} title="Settings" style={{
            width: 36, height: 36, borderRadius: 4,
            background: 'var(--bg-elev-2)',
            color: 'var(--text)', fontWeight: 500, fontFamily: 'Instrument Serif, serif', fontSize: 18,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            border: '1px solid var(--line)',
            transition: 'all 120ms var(--ease)', letterSpacing: '0.02em',
          }} onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--acid)'} onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--line)'}>K</button>
        </div>
      </div>
    </div>
  );
}

// Lightweight Catalyst detail (covered as a bonus — first-class catalyst page)
function CatalystDetail({ id, go, openTicket }) {
  const VD = window.VD;
  const { ICONS, AssetGlyph } = window.VDIcons;
  const c = VD.VD_CATALYSTS.find(x => x.id === id);
  if (!c) return <div style={{ padding: 40 }}>Catalyst not found.</div>;
  const a = VD.VD_ASSETS.find(x => x.sym === c.asset);
  const chain = VD.vdBuildChain(c.asset, 'fri').slice(3, 9);
  const days = Math.floor(c.hours / 24);
  const hrs = c.hours % 24;

  return (
    <div style={{ maxWidth: 1240, margin: '0 auto', padding: '20px 32px 80px' }}>
      <button onClick={() => go('home')} className="btn-ghost btn" style={{ marginLeft: -8, marginBottom: 12, color: 'var(--text-3)' }}>{ICONS.back} Catalysts</button>

      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 18, paddingBottom: 18, borderBottom: '1px solid var(--line-subtle)', marginBottom: 22 }}>
        <div style={{ width: 64, height: 64, borderRadius: 14, background: 'var(--bg-elev-2)', border: '1px solid var(--line-subtle)', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center' }}>
          <span className="cap-sm" style={{ color: 'var(--text-3)', fontSize: 9 }}>{c.day}</span>
          <span className="num" style={{ fontSize: 20, fontWeight: 600, marginTop: 2 }}>{c.date.split(' ')[1]}</span>
        </div>
        <div>
          <div className="cap-sm" style={{ marginBottom: 4 }}>{c.date} · catalyst</div>
          <div style={{ fontSize: 32, fontWeight: 600, letterSpacing: '-0.025em' }}>{c.name}</div>
        </div>
        <div style={{ flex: 1 }} />
        <div style={{ textAlign: 'right' }}>
          <div className="cap-sm" style={{ color: 'var(--mint)', marginBottom: 4 }}>Time to event</div>
          <div className="num" style={{ fontSize: 28, fontWeight: 600, color: 'var(--mint)' }}>{days}<span style={{ color: 'var(--text-3)', fontSize: 14, fontWeight: 400 }}>d </span>{hrs.toString().padStart(2,'0')}<span style={{ color: 'var(--text-3)', fontSize: 14, fontWeight: 400 }}>h</span></div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24 }}>
        <div>
          <h2 className="h2" style={{ marginBottom: 10 }}>About this event</h2>
          <p style={{ color: 'var(--text-2)', fontSize: 14, lineHeight: 1.6, marginBottom: 24 }}>{c.desc}</p>

          <h2 className="h2" style={{ marginBottom: 12 }}>Markets resolving on this catalyst</h2>
          <div className="card" style={{ overflow: 'hidden' }}>
            {chain.map((r, i) => (
              <div key={r.strike} style={{ display:'grid', gridTemplateColumns:'auto 1fr 100px 100px', gap: 12, padding: '12px 16px', alignItems:'center', borderBottom: i === chain.length - 1 ? 'none' : '1px solid var(--line-subtle)' }}>
                <AssetGlyph sym={c.asset} size={28} />
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>{a.name} closes above ${r.strike >= 1000 ? r.strike.toLocaleString() : r.strike}</div>
                  <div style={{ color: 'var(--text-3)', fontSize: 11 }}>Resolves on {c.date} per Pyth aggregate</div>
                </div>
                <button onClick={() => openTicket({ sym: c.asset, side: 'YES', action: 'Buy', strike: r.strike, expiryKey: 'fri', price: r.yAsk, size: r.yAskSize, mid: (r.yBid + r.yAsk)/2 })} style={{
                  height: 32, borderRadius: 6, fontSize: 12, fontWeight: 600, background: 'var(--mint-bg10)', color: 'var(--mint)', border: '1px solid rgba(151,252,228,0.3)', fontFamily: 'Geist Mono'
                }}>YES {r.yAsk}¢</button>
                <button onClick={() => openTicket({ sym: c.asset, side: 'NO', action: 'Buy', strike: r.strike, expiryKey: 'fri', price: r.nAsk, size: r.nAskSize, mid: (r.nBid + r.nAsk)/2 })} style={{
                  height: 32, borderRadius: 6, fontSize: 12, fontWeight: 600, background: 'var(--coral-bg10)', color: 'var(--coral)', border: '1px solid rgba(237,112,136,0.3)', fontFamily: 'Geist Mono'
                }}>NO {r.nAsk}¢</button>
              </div>
            ))}
          </div>
        </div>

        <div>
          <div className="card" style={{ padding: 18, marginBottom: 14 }}>
            <div className="cap-sm" style={{ marginBottom: 12 }}>Event details</div>
            <KV k="Date"      v={c.date} />
            <KV k="Underlying" v={c.asset} />
            <KV k="Markets"   v={c.markets} />
            <KV k="Oracle"    v="Pyth + Chainlink agg." last />
          </div>
          <button className="btn btn-primary btn-lg btn-full" style={{ marginBottom: 8 }}>{ICONS.bell} Notify me</button>
          <button className="btn btn-lg btn-full">{ICONS.cal} Add to calendar</button>
        </div>
      </div>
    </div>
  );
}

function KV({ k, v, last }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0', borderBottom: last ? 'none' : '1px solid var(--line-subtle)' }}>
      <span style={{ color: 'var(--text-3)', fontSize: 12 }}>{k}</span>
      <span className="num" style={{ fontSize: 13, fontWeight: 600 }}>{v}</span>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
