/* ============================================================
   55 QUIZ — app root: routing, nav shell, theme, tweaks
   ============================================================ */
const { useState, useEffect, useRef } = React;

function useWidth() {
  const [w, setW] = useState(typeof window !== 'undefined' ? window.innerWidth : 1200);
  useEffect(() => {
    const onR = () => setW(window.innerWidth);
    window.addEventListener('resize', onR);
    return () => window.removeEventListener('resize', onR);
  }, []);
  return w;
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#6C4DF6",
  "roundness": 1,
  "displayFont": "Bricolage Grotesque",
  "dark": false
}/*EDITMODE-END*/;

const NAV = [
  { id: 'home', label: 'Home', icon: 'home' },
  { id: 'catalog', label: 'Catalog', icon: 'compass' },
  { id: 'create', label: 'Create', icon: 'wand' },
  { id: 'pricing', label: 'Plans', icon: 'crown' },
];

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const width = useWidth();
  const isDesktop = width >= 880;

  const [view, setView] = useState('catalog');
  const [theme, setTheme] = useState('light');
  const [quiz, setQuiz] = useState(null);
  const [result, setResult] = useState(null);
  const [subscribed, setSubscribed] = useState(false);
  const scrollRef = useRef(null);

  // sync dark tweak <-> theme
  useEffect(() => { setTheme(t.dark ? 'dark' : 'light'); }, [t.dark]);

  const go = (v) => { setView(v); if (scrollRef.current) scrollRef.current.scrollTop = 0; };
  const openQuiz = (q) => { setQuiz(q); go('detail'); };
  const playQuiz = (q) => { setQuiz(q); go('play'); };
  const finish = (r) => { setResult(r); go('result'); };
  const buy = (q, passMode) => { setQuiz(q); go('pricing'); };
  const subscribe = () => { setSubscribed(true); };

  const toggleTheme = () => { setTheme(prev => { const n = prev === 'light' ? 'dark' : 'light'; setTweak('dark', n === 'dark'); return n; }); };

  let screen = null;
  if (view === 'home') screen = <HomeScreen onOpen={openQuiz} go={go} isDesktop={isDesktop} />;
  else if (view === 'catalog') screen = <CatalogScreen onOpen={openQuiz} onSub={() => go('pricing')} isDesktop={isDesktop} subscribed={subscribed} />;
  else if (view === 'detail') screen = <QuizDetail quiz={quiz} onBack={() => go('catalog')} onPlay={playQuiz} onBuy={buy} isDesktop={isDesktop} subscribed={subscribed} />;
  else if (view === 'play') screen = <PlayScreen quiz={quiz} onExit={() => go('detail')} onFinish={finish} isDesktop={isDesktop} />;
  else if (view === 'result') screen = <ResultScreen quiz={quiz} result={result} onRetry={() => playQuiz(quiz)} onCatalog={() => go('catalog')} onOpen={openQuiz} isDesktop={isDesktop} />;
  else if (view === 'create') screen = <CreateScreen onCheckout={() => go('pricing')} isDesktop={isDesktop} />;
  else if (view === 'pricing') screen = <PricingScreen quiz={quiz} sub={subscribed} onSubscribe={subscribe} onBuy={buy} onCreate={() => go('create')} isDesktop={isDesktop} />;

  const immersive = view === 'play';

  return (
    <div data-theme={theme} style={{
      '--tw-accent': t.accent, '--tw-radius-scale': t.roundness,
      '--font-display': `'${t.displayFont}', sans-serif`,
      background: 'var(--bg)', color: 'var(--text)', minHeight: '100%',
      display: 'flex', flexDirection: isDesktop ? 'row' : 'column',
    }}>
      {/* DESKTOP SIDEBAR */}
      {isDesktop && !immersive && (
        <aside style={{ width: 232, flexShrink: 0, height: '100vh', position: 'sticky', top: 0, borderRight: '1px solid var(--border)', background: 'var(--surface-header)', display: 'flex', flexDirection: 'column', padding: 20 }}>
          <div style={{ padding: '6px 6px 22px' }}><Logo size={26} /></div>
          <nav style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            {NAV.map(n => {
              const active = view === n.id || (n.id === 'catalog' && ['detail'].includes(view));
              return (
                <button key={n.id} onClick={() => go(n.id)} style={{
                  display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderRadius: 'var(--r-md)', border: 'none',
                  background: active ? 'var(--text)' : 'transparent', color: active ? 'var(--bg)' : 'var(--text-2)',
                  fontWeight: 700, fontSize: 15, transition: 'all 150ms var(--ease)',
                }}>
                  <Icon name={n.icon} size={20} /> {n.label}
                </button>
              );
            })}
          </nav>
          <div style={{ marginTop: 'auto', display: 'flex', flexDirection: 'column', gap: 14 }}>
            {!subscribed && (
              <div style={{ padding: 16, borderRadius: 'var(--r-lg)', background: 'color-mix(in oklab, var(--brand) 12%, transparent)', border: '1px solid color-mix(in oklab, var(--brand) 25%, transparent)' }}>
                <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 4 }}>Unlock all quizzes</div>
                <p className="t-sm" style={{ margin: '0 0 10px', color: 'var(--text-2)' }}>Skip the 55s wait with the 55 Pass.</p>
                <Btn variant="primary" size="sm" full icon="infinity" onClick={() => go('pricing')}>Get 55 Pass</Btn>
              </div>
            )}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <ThemeToggle theme={theme} onToggle={toggleTheme} />
              <button style={{ width: 40, height: 40, borderRadius: 'var(--r-pill)', border: '1px solid var(--border)', background: 'var(--surface-2)', display: 'grid', placeItems: 'center', color: 'var(--text-2)' }}><Icon name="user" size={19} /></button>
            </div>
          </div>
        </aside>
      )}

      {/* MOBILE TOP BAR */}
      {!isDesktop && !immersive && (
        <header style={{ position: 'sticky', top: 0, zIndex: 30, display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px', background: 'color-mix(in oklab, var(--surface-header) 86%, transparent)', backdropFilter: 'blur(12px)', borderBottom: '1px solid var(--border)' }}>
          <Logo size={24} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <ThemeToggle theme={theme} onToggle={toggleTheme} />
          </div>
        </header>
      )}

      {/* MAIN SCROLL AREA */}
      <main ref={scrollRef} style={{ flex: 1, minWidth: 0, height: isDesktop ? '100vh' : 'auto', overflowY: isDesktop ? 'auto' : 'visible' }}>
        <div style={{ maxWidth: immersive ? 760 : 1160, margin: '0 auto', padding: isDesktop ? '32px 40px 48px' : `20px 16px ${immersive ? 24 : 96}px` }}>
          {screen}
        </div>
      </main>

      {/* MOBILE BOTTOM NAV */}
      {!isDesktop && !immersive && (
        <nav style={{ position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 40, display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', background: 'color-mix(in oklab, var(--bg) 86%, transparent)', backdropFilter: 'blur(14px)', borderTop: '1px solid var(--border)', padding: '8px 8px calc(8px + env(safe-area-inset-bottom, 0px))' }}>
          {NAV.map(n => {
            const active = view === n.id || (n.id === 'catalog' && ['detail'].includes(view));
            return (
              <button key={n.id} onClick={() => go(n.id)} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, padding: '7px 0', border: 'none', background: 'none', color: active ? 'var(--brand)' : 'var(--text-3)', fontWeight: 700, fontSize: 11 }}>
                <span style={{ display: 'grid', placeItems: 'center', width: 38, height: 30, borderRadius: 'var(--r-pill)', background: active ? 'color-mix(in oklab, var(--brand) 14%, transparent)' : 'transparent' }}><Icon name={n.icon} size={20} /></span>
                {n.label}
              </button>
            );
          })}
        </nav>
      )}

      {/* TWEAKS */}
      <TweaksPanel>
        <TweakSection label="Brand" />
        <TweakColor label="Accent" value={t.accent}
          options={['#6C4DF6', '#FF6B5E', '#25D0C0', '#4D9BFF', '#F0455A', '#1F8A5B']}
          onChange={(v) => setTweak('accent', v)} />
        <TweakSelect label="Display font" value={t.displayFont}
          options={['Bricolage Grotesque', 'Space Grotesk', 'Space Mono']}
          onChange={(v) => setTweak('displayFont', v)} />
        <TweakSection label="Shape & theme" />
        <TweakSlider label="Corner roundness" value={t.roundness} min={0} max={1.6} step={0.1}
          onChange={(v) => setTweak('roundness', v)} />
        <TweakToggle label="Dark mode" value={t.dark} onChange={(v) => setTweak('dark', v)} />
      </TweaksPanel>
    </div>
  );
}

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