// landing.jsx — public landing page shown to signed-out users.
// Replaces the old LoginScreen. Uses signIn / signUp from auth.js (already
// loaded). All internals are scoped via IIFE so function names like
// `Sidebar` / `Topbar` don't collide with app.jsx.

(function () {
  const { useState, useEffect, useRef, useMemo } = React;

  // ─── single global rAF scroll loop ──────────────────────────────────────
  // Listener registration deferred to LandingScreen's mount effect so we
  // don't pay for scroll/resize handlers when the user is signed-in and
  // LandingScreen is never rendered.
  const _subs = new Set();
  let _rafPending = false;
  const _pump = () => { _rafPending = false; for (const fn of _subs) fn(); };
  const _request = () => { if (!_rafPending) { _rafPending = true; requestAnimationFrame(_pump); } };

  function useDirectScroll(sectionRef, callback) {
    const cbRef = useRef(callback);
    cbRef.current = callback;
    useEffect(() => {
      const tick = () => {
        const s = sectionRef.current;
        if (!s) return;
        const rect = s.getBoundingClientRect();
        const h = s.offsetHeight;
        const vh = window.innerHeight;
        const total = Math.max(1, h - vh);
        const scrolled = Math.max(0, -rect.top);
        const p = Math.max(0, Math.min(1, scrolled / total));
        cbRef.current(p);
      };
      _subs.add(tick);
      tick();
      return () => { _subs.delete(tick); };
    }, [sectionRef]);
  }

  const easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);

  // ─── background icon scatter ─────────────────────────────────────────────
  const ICON_DIR = 'icons/Dashboard%20Backgroudn%20icons/';
  const BG_ICONS = [
    '02d18f077302266605aad3a4c4eef175.png',
    '056f4bce9fe1d4c33b24b34f3360e13d.png',
    '0a61d69ff71d59375e13e252f77d32a3.png',
    '14164b1d77c19c8d937c89c00d71f533.png',
    '1c0624b684dab4cfb0c09afbd34d46ab.png',
    '1f9656d31bf4dcd541aa29e8f1b0117d.png',
    '213e37bc4ead4f85b9c57ee59ae387fe.png',
    '26d5a76ddb43d17f94f7c029753ef68c.png',
    '2a36ce1b433302b3841ef8aa4b9eb727.png',
    '31019ae104fc682ff003fdd245367412.png',
    '32e982f1c9a3df365d565e7a3ea2cffa.png',
    '41f2818eb02b7cf8c2b102e7627488fc.png',
    '4712fda6157337d2924c598588f936f6.png',
    '500e624403d4ce176c3304f49490811b.png',
    '589348612b05ea834f55ceb3cefcfe36.png',
    '72e60c931de735f4e7398da9267199db.png',
    '7ec173b6287fb176788e836fe1f8bad8.png',
    '8a162d1962c832aa1ef3d6a4364bbcb6.png',
    '8f24eee2f5448759c4842b916c2a40ba.png',
    '8f96cc78123c5f2c25498fea7c08d87a.png',
    '9b3a96d8edcef9edf3fec9d30b727408.png',
    '9d6701b12f1b09ec526746334919e640.png',
    'a567cd5d61824d1245d95f1a554328b4.png',
    'c1590edb5b97b59b824a3648ddac3d30.png',
    'd64ae80f651e42b002cd092cd9da7279.png',
    'd763b75c37fc9cfac8919bb94a9ba613.png',
    'fe5e99cbaa02ce89b737adfc6f283630.png',
    'icon%20banan.png', 'icon%20bear.png', 'icon%20dice.png', 'icon.png',
    'no%20bg%20astro.png', 'no%20bg%20cloud%201.png', 'no%20bg%20cloud.png',
    'no%20bg%20icon%201.png', 'no%20bg%20icon%202.png', 'no%20bg%20icon%204.png',
    'no%20bg%20icon%205.png', 'no%20bg%20icon%206.png', 'no%20bg%20icon%209.png',
    'no%20bg%20icon.png',
    'spinbob.png',
  ];

  function makeScatter(seed, cols = 6, rows = 4) {
    let s = (seed + 1) * 99173;
    const r = () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
    const order = [...BG_ICONS];
    for (let i = order.length - 1; i > 0; i--) {
      const j = Math.floor(r() * (i + 1));
      [order[i], order[j]] = [order[j], order[i]];
    }
    const cellW = 100 / cols, cellH = 100 / rows;
    const items = [];
    for (let row = 0; row < rows; row++) {
      for (let col = 0; col < cols; col++) {
        const offset = (row % 2) * 0.5;
        const cx = (col + 0.5 + offset) * cellW + (r() - 0.5) * cellW * 0.2;
        const cy = (row + 0.5) * cellH + (r() - 0.5) * cellH * 0.18;
        items.push({
          src: order[(row * cols + col) % order.length],
          x: cx, y: cy,
          size: 64 + r() * 40, rot: (r() - 0.5) * 18,
          opacity: 0.7 + r() * 0.3,
        });
      }
    }
    return items;
  }

  function BackgroundIcons({ seed }) {
    const items = useMemo(() => makeScatter(seed), [seed]);
    return (
      <div className="landing-bg-icons">
        {items.map((p, i) => (
          <img key={i} src={ICON_DIR + p.src} alt=""
            style={{
              left: p.x + '%', top: p.y + '%',
              width: p.size + 'px', height: p.size + 'px',
              transform: `translate(-50%, -50%) rotate(${p.rot}deg)`,
              opacity: p.opacity,
            }} />
        ))}
      </div>
    );
  }

  // ─── video banner — pinned to the very top of the page ─────────────────
  function VideoBanner() {
    return (
      <section className="landing-video-banner">
        <video
          src="tung-tung-sahur-tung-tung-tung-sahur.mp4"
          autoPlay muted loop playsInline
        />
      </section>
    );
  }

  // ─── marketing top bar ───────────────────────────────────────────────────
  function LandingTopBar({ onLogin, onSignup }) {
    return (
      <header className="landing-topbar">
        <div className="landing-topbar-inner">
          <a href="#" className="landing-brand">
            <span className="landing-brand-tung">tung</span><span className="landing-brand-dot">.</span><span className="landing-brand-scholar">scholar</span>
          </a>
          <nav className="landing-nav">
            <button className="landing-link-btn" onClick={onLogin}>Log in</button>
            <button className="landing-cta-btn" onClick={onSignup}>Sign up</button>
          </nav>
        </div>
      </header>
    );
  }

  // ─── hero ────────────────────────────────────────────────────────────────
  function Hero() {
    const sectionRef = useRef(null);
    const cardRef = useRef(null);
    const dateBlockRef = useRef(null);
    const dateRef = useRef(null);
    const hintRef = useRef(null);
    const tungRef = useRef(null);
    const scholarRef = useRef(null);

    useDirectScroll(sectionRef, (progress) => {
      const exp = easeOutCubic(Math.min(1, progress / 0.45));
      const isMobile = window.innerWidth < 768;
      const w = 320 + exp * (isMobile ? 600 : 1200);
      const h = 400 + exp * (isMobile ? 200 : 400);
      const slide = exp * (isMobile ? 90 : 60);
      if (cardRef.current) {
        cardRef.current.style.width  = w + 'px';
        cardRef.current.style.height = h + 'px';
      }
      // Card is now anchored at the top of the sticky area (padding-top: 40px),
      // so the meta block sits directly below it instead of relative to viewport
      // center.
      if (dateBlockRef.current) dateBlockRef.current.style.top = `${40 + h + 20}px`;
      if (dateRef.current)    dateRef.current.style.transform   = `translate3d(-${slide}vw, 0, 0)`;
      if (hintRef.current)    hintRef.current.style.transform   = `translate3d(${slide}vw, 0, 0)`;
      if (tungRef.current)    tungRef.current.style.transform   = `translate3d(-${slide}vw, 0, 0)`;
      if (scholarRef.current) scholarRef.current.style.transform = `translate3d(${slide}vw, 0, 0)`;
    });

    return (
      <section ref={sectionRef} className="landing-hero">
        <div className="landing-hero-sticky">
          <div ref={cardRef} className="landing-hero-card grayscale-img" style={{
            backgroundImage: 'url(https://images.unsplash.com/photo-1481627834876-b7833e8f5570?w=1600&q=80&auto=format&fit=crop)',
          }} />
          <div ref={dateBlockRef} className="landing-hero-meta">
            <p ref={dateRef} className="landing-hero-vol">VOL. I — 2026</p>
            <p ref={hintRef} className="landing-hero-scroll-hint">
              <span aria-hidden="true">↓</span> scroll to enter <span aria-hidden="true" className="bob">↓</span>
            </p>
          </div>
          <div className="landing-hero-title-wrap">
            <h2 ref={tungRef} className="landing-hero-tung">tung.</h2>
            <h2 ref={scholarRef} className="landing-hero-scholar">scholar</h2>
          </div>
        </div>
      </section>
    );
  }

  function SystemHeader() {
    return (
      <section className="landing-system-header">
        <div className="landing-system-header-inner">
          <div className="landing-system-eyebrow">— index —</div>
          <h2 className="landing-system-title">The System</h2>
        </div>
      </section>
    );
  }

  // ─── demo section wrapper ────────────────────────────────────────────────
  function DemoSection({ kicker, title, from = 'bottom', seed = 1, children }) {
    const sectionRef = useRef(null);
    const titleRef = useRef(null);
    const cardRef = useRef(null);
    const ctaRef = useRef(null);

    useDirectScroll(sectionRef, (progress) => {
      const exp = easeOutCubic(Math.min(1, progress / 0.4));
      const remaining = 1 - exp;
      let tx = 0, ty = 0;
      if (from === 'bottom')      ty =  remaining * 115;
      else if (from === 'top')    ty = -remaining * 115;
      else if (from === 'left')   tx = -remaining * 115;
      else if (from === 'right')  tx =  remaining * 115;
      if (cardRef.current) {
        cardRef.current.style.transform = `translate3d(${tx}vw, ${ty}vh, 0)`;
        cardRef.current.style.pointerEvents = exp > 0.92 ? 'auto' : 'none';
      }
      if (titleRef.current) titleRef.current.style.opacity = String(Math.min(1, 0.35 + exp * 0.9));
      if (ctaRef.current)   ctaRef.current.style.opacity   = exp > 0.96 ? '1' : '0';
    });

    let initTx = 0, initTy = 0;
    if (from === 'bottom')     initTy =  115;
    else if (from === 'top')   initTy = -115;
    else if (from === 'left')  initTx = -115;
    else if (from === 'right') initTx =  115;

    return (
      <section ref={sectionRef} className="landing-demo-section">
        <div className="landing-demo-sticky">
          <BackgroundIcons seed={seed} />
          <div ref={titleRef} className="landing-demo-title-wrap" style={{ opacity: 0.35 }}>
            <span className="landing-demo-kicker">{kicker}</span>
            <h3 className="landing-demo-title">{title}</h3>
          </div>
          <div className="landing-demo-card-pos">
            <div ref={cardRef} className="landing-demo-card"
              style={{ transform: `translate3d(${initTx}vw, ${initTy}vh, 0)`, pointerEvents: 'none' }}>
              {children}
            </div>
          </div>
          <div ref={ctaRef} className="landing-demo-cta-wrap" style={{ opacity: 0 }}>
            <div className="scroll-cta">
              <svg className="mouse-svg" width="20" height="30" viewBox="0 0 20 30" fill="none">
                <rect x="1.25" y="1.25" width="17.5" height="27.5" rx="8.75" stroke="currentColor" strokeWidth="1.5" />
                <circle cx="10" cy="8" r="1.7" fill="currentColor">
                  <animate attributeName="cy" values="8;17;8" dur="1.6s" repeatCount="indefinite" />
                  <animate attributeName="opacity" values="1;0.2;1" dur="1.6s" repeatCount="indefinite" />
                </circle>
              </svg>
              <span className="label">Scroll to continue</span>
              <span className="chevs"><span>⌄</span><span>⌄</span><span>⌄</span></span>
            </div>
          </div>
        </div>
      </section>
    );
  }

  // ─── mock sidebar + topbar (mirrors real app classes) ───────────────────
  function MockSidebar({ active = 'home', activeSubject = null, activeNote = null }) {
    return (
      <aside className="sidebar">
        <div className="sidebar-head">
          <div className="brand"><span className="brand-mark">Tung.scholar</span></div>
          <button className="icon-btn" title="Settings">⚙</button>
        </div>
        <div className="search-box">
          <span style={{fontFamily: 'var(--mono)', fontSize: 11}}>⌕</span>
          <span>Search</span>
          <span className="kbd">⌘K</span>
        </div>
        <div className="nav-section" style={{padding: '8px 8px 4px'}}>
          <button className="btn primary" style={{width: '100%', justifyContent: 'center', gap: 8, fontSize: '12.5px', padding: '6px 12px'}}>
            ＋ New guide
          </button>
        </div>
        <div className="nav-section">
          <div className={"nav-item" + (active === 'home' ? ' active' : '')}>
            <span className="glyph">◧</span><span className="label">Dashboard</span>
          </div>
          <div className={"nav-item" + (active === 'library' ? ' active' : '')}>
            <span className="glyph">◆</span><span className="label">All guides</span><span className="badge">12</span>
          </div>
          <div className={"nav-item" + (active === 'calendar' ? ' active' : '')}>
            <span className="glyph">▦</span><span className="label">Calendar</span><span className="badge">7</span>
          </div>
        </div>
        <div className="nav-section">
          <div className="nav-section-label">
            <span>Subjects</span>
            <button className="icon-btn" style={{width: 16, height: 16, fontSize: 12}}>＋</button>
          </div>
          {[
            { id: 'bio',  emoji: '🧫', name: 'Biology',     count: 4 },
            { id: 'hist', emoji: '🏛', name: 'History',     count: 3 },
            { id: 'math', emoji: '∑',  name: 'Calculus III', count: 5 },
          ].map((s) => (
            <div key={s.id} className={"nav-item" + (activeSubject === s.id ? ' active' : '')}>
              <span className="glyph" style={{filter: 'grayscale(0.4)'}}>{s.emoji}</span>
              <span className="label">{s.name}</span>
              <span className="badge">{s.count}</span>
            </div>
          ))}
        </div>
        <div className="nav-section">
          <div className="nav-section-label">
            <span style={{display: 'inline-flex', alignItems: 'center', gap: 6}}>
              <img src="icons/icon%20folder%20black.png" alt="" style={{width: 14, height: 14, objectFit: 'contain'}} />
              <span>Notes</span>
              <span style={{fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 500, color: 'var(--ink-whisper)'}}>5</span>
            </span>
            <button className="icon-btn" style={{width: 16, height: 16, fontSize: 12}}>＋</button>
          </div>
          {[
            { id: 'cell', label: 'Cell biology — ch. 1' },
            { id: 'rome', label: 'Roman senate notes' },
            { id: 'lab',  label: 'Lab journal' },
          ].map((n) => (
            <div key={n.id} className={"nav-item" + (activeNote === n.id ? ' active' : '')} style={{fontSize: 12.5}}>
              <span className="glyph" style={{fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-whisper)'}}>·</span>
              <span className="label">{n.label}</span>
            </div>
          ))}
        </div>
        <div className="sidebar-spacer" />
        <div className="sidebar-foot">
          <div className="user-card">
            <div className="avatar">TU</div>
            <div style={{flex: 1, minWidth: 0}}>
              <div style={{fontSize: 12, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'}}>Tung Hwang</div>
              <div style={{fontSize: 10.5, color: 'var(--ink-mute)'}}>Personal · free plan</div>
            </div>
            <button className="icon-btn">⏻</button>
          </div>
        </div>
      </aside>
    );
  }

  function MockTopbar({ crumbs = [], leadingActions, actions }) {
    return (
      <div className="topbar">
        <div className="bar-left">
          {leadingActions && <div style={{display: 'flex', alignItems: 'center', gap: 6}}>{leadingActions}</div>}
          <div className="crumbs">
            {crumbs.map((c, i) => (
              <React.Fragment key={i}>
                {i > 0 && <span className="sep">/</span>}
                <span className={"crumb" + (i === crumbs.length - 1 ? ' last' : '')}>{c}</span>
              </React.Fragment>
            ))}
          </div>
        </div>
        <div className="bar-actions">{actions}</div>
      </div>
    );
  }

  // ─── 01 / Dashboard demo ────────────────────────────────────────────────
  function DashboardDemo() {
    const grid = useMemo(() => {
      const g = [];
      for (let i = 0; i < 5; i++) g.push({ d: null, dim: true });
      for (let d = 1; d <= 31; d++) g.push({ d, dim: false });
      while (g.length % 7 !== 0) g.push({ d: null, dim: true });
      return g;
    }, []);
    const events = { 5: 'study', 8: 'assignment', 12: 'exam', 14: 'assignment', 20: 'study', 23: 'exam', 28: 'other' };
    return (
      <div className="demo-app">
        <MockSidebar active="home" />
        <div className="demo-main">
          <MockTopbar crumbs={['Dashboard']} actions={<>
            <button className="btn sm">⚒ Edit layout</button>
            <button className="btn sm">Open calendar</button>
            <button className="btn accent sm">＋ New guide</button>
          </>} />
          <div className="scroll">
            <div className="page-pad" style={{position: 'relative', zIndex: 1}}>
              <div className="eyebrow">Saturday · May 02 · 2026</div>
              <h1 className="page-title" style={{marginTop: 4}}>Good evening, <em>Tung.</em></h1>
              <div className="page-subtitle">
                <span>You have <strong style={{color: 'var(--ink-strong)'}}>2</strong> things on the calendar this week, and <strong style={{color: 'var(--ink-strong)'}}>12</strong> guides in your library.</span>
              </div>
              <div className="dashboard-grid">
                <div className="grid-box" style={{gridColumn: 'span 3', gridRow: 'span 2'}}>
                  <div className="kpi"><div className="label">Subjects</div><div className="num">3</div><div className="sub">tracked</div></div>
                </div>
                <div className="grid-box" style={{gridColumn: 'span 3', gridRow: 'span 2'}}>
                  <div className="kpi"><div className="label">Guides</div><div className="num">12</div><div className="sub">generated</div></div>
                </div>
                <div className="grid-box" style={{gridColumn: 'span 3', gridRow: 'span 2'}}>
                  <div className="kpi"><div className="label">Cards</div><div className="num">247</div><div className="sub">across decks</div></div>
                </div>
                <div className="grid-box" style={{gridColumn: 'span 3', gridRow: 'span 2'}}>
                  <div className="kpi"><div className="label">This week</div><div className="num accent">2</div><div className="sub">events</div></div>
                </div>
                <div className="grid-box" style={{gridColumn: 'span 8', gridRow: 'span 5'}}>
                  <div className="mini-cal">
                    <div className="mini-cal-head">
                      <div className="month">May 2026</div>
                      <div className="ctrls">
                        <button className="btn ghost sm">←</button>
                        <button className="btn ghost sm">Today</button>
                        <button className="btn ghost sm">→</button>
                        <button className="btn sm">Open →</button>
                      </div>
                    </div>
                    <div className="mini-cal-grid">
                      {['Sun','Mon','Tue','Wed','Thu','Fri','Sat'].map(d => <div key={d} className="mini-dow">{d}</div>)}
                      {grid.map((c, i) => {
                        const ev = c.d ? events[c.d] : null;
                        const isToday = c.d === 2;
                        return (
                          <div key={i} className={"mini-cell" + (c.dim ? ' dim' : '') + (isToday ? ' today' : '')}>
                            <span className="day-num">{c.d || ''}</span>
                            {ev && <div className={"mini-event " + ev}>{ev === 'exam' ? 'Bio midterm' : ev === 'assignment' ? 'Essay' : 'Study'}</div>}
                          </div>
                        );
                      })}
                    </div>
                  </div>
                </div>
                <div className="grid-box" style={{gridColumn: 'span 4', gridRow: 'span 5'}}>
                  <div className="upcoming-mini">
                    <div className="upcoming-mini-head"><h3>Upcoming</h3><a>Open calendar →</a></div>
                    {[
                      { kind: 'exam',       emoji: '🧫', title: 'Biology midterm', when: 'in 10d' },
                      { kind: 'assignment', emoji: '🏛', title: 'History essay due', when: 'in 12d' },
                      { kind: 'study',      emoji: '∑',  title: 'Math review w/ Sam', when: 'in 18d' },
                      { kind: 'exam',       emoji: '∑',  title: 'Calculus final', when: 'in 21d' },
                      { kind: 'other',      emoji: '🧫', title: 'Lab report', when: 'in 26d' },
                    ].map((u, i) => (
                      <div key={i} className="upcoming-mini-row">
                        <span className={"dot " + u.kind}></span>
                        <span style={{fontSize: 13, filter: 'grayscale(0.4)'}}>{u.emoji}</span>
                        <span className="title">{u.title}</span>
                        <span className="when">{u.when}</span>
                      </div>
                    ))}
                  </div>
                </div>
                <div className="grid-box" style={{gridColumn: 'span 6', gridRow: 'span 4', background: 'transparent', border: 'none'}}>
                  <div className="upnext">
                    <div className="label">Up next</div>
                    <div className="title">Biology midterm</div>
                    <div className="meta">🧫 Biology · exam</div>
                    <div className="days">10d <span>away</span></div>
                  </div>
                </div>
                <div className="grid-box" style={{gridColumn: 'span 3', gridRow: 'span 4', background: 'transparent', border: 'none'}}>
                  <button className="quick-tile primary" style={{borderRadius: 'var(--r-md)'}}>
                    <div className="qt-glyph">＋</div>
                    <div><div className="qt-label">New guide</div><div className="qt-sub">upload + generate</div></div>
                  </button>
                </div>
                <div className="grid-box" style={{gridColumn: 'span 3', gridRow: 'span 4'}}>
                  <button className="quick-tile">
                    <div className="qt-glyph">↑</div>
                    <div><div className="qt-label">Upload files</div><div className="qt-sub">add to a subject</div></div>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ─── 02 / Guides demo ───────────────────────────────────────────────────
  function GuidesDemo() {
    const [filter, setFilter] = useState('all');
    const subjects = [
      { id: 'bio',  emoji: '🧫', name: 'Biology' },
      { id: 'hist', emoji: '🏛', name: 'History' },
      { id: 'math', emoji: '∑',  name: 'Calculus III' },
    ];
    const guides = [
      { i: 1,  emoji: '🧫', subj: 'Biology',     title: 'Photosynthesis',                 sources: 3, cards: 24, when: '2d',  sid: 'bio' },
      { i: 2,  emoji: '🧫', subj: 'Biology',     title: 'Cellular respiration',           sources: 2, cards: 18, when: '5d',  sid: 'bio' },
      { i: 3,  emoji: '🧫', subj: 'Biology',     title: 'Mitosis & meiosis',              sources: 4, cards: 21, when: '1w',  sid: 'bio' },
      { i: 4,  emoji: '🧫', subj: 'Biology',     title: 'DNA transcription & translation', sources: 3, cards: 26, when: '2w', sid: 'bio' },
      { i: 5,  emoji: '🏛', subj: 'History',     title: 'Fall of the Roman Empire',       sources: 5, cards: 32, when: '1w',  sid: 'hist' },
      { i: 6,  emoji: '🏛', subj: 'History',     title: 'WWI causes',                     sources: 3, cards: 21, when: '2w',  sid: 'hist' },
      { i: 7,  emoji: '🏛', subj: 'History',     title: 'Industrial Revolution',          sources: 4, cards: 19, when: '3w',  sid: 'hist' },
      { i: 8,  emoji: '∑',  subj: 'Calculus III', title: 'Vector calculus — ch. 12',      sources: 2, cards: 16, when: '3d',  sid: 'math' },
      { i: 9,  emoji: '∑',  subj: 'Calculus III', title: 'Multiple integrals',            sources: 3, cards: 14, when: '4d',  sid: 'math' },
      { i: 10, emoji: '∑',  subj: 'Calculus III', title: 'Line & surface integrals',      sources: 3, cards: 18, when: '6d',  sid: 'math' },
      { i: 11, emoji: '∑',  subj: 'Calculus III', title: 'Stokes & divergence',           sources: 2, cards: 22, when: '1w',  sid: 'math' },
      { i: 12, emoji: '∑',  subj: 'Calculus III', title: 'Series convergence',            sources: 4, cards: 16, when: '2w',  sid: 'math' },
    ];
    const filtered = filter === 'all' ? guides : guides.filter(g => g.sid === filter);
    return (
      <div className="demo-app">
        <MockSidebar active="library" />
        <div className="demo-main">
          <MockTopbar crumbs={['All guides']} actions={<button className="btn accent sm">＋ New guide</button>} />
          <div className="scroll">
            <div className="page-pad">
              <div className="eyebrow">§ Library</div>
              <h1 className="page-title">All guides</h1>
              <div className="page-subtitle">
                <span><strong style={{color: 'var(--ink-strong)'}}>{guides.length}</strong> guides</span>
                <span>·</span>
                <span>Click a row to open. Filter by subject to narrow.</span>
              </div>
              <div style={{display: 'flex', gap: 6, marginBottom: 16, flexWrap: 'wrap'}}>
                <button onClick={() => setFilter('all')} className={"filter-chip" + (filter === 'all' ? ' active' : '')}>All</button>
                {subjects.map((s) => (
                  <button key={s.id} onClick={() => setFilter(s.id)} className={"filter-chip" + (filter === s.id ? ' active' : '')}>
                    <span style={{filter: 'grayscale(0.4)', marginRight: 4}}>{s.emoji}</span>{s.name}
                  </button>
                ))}
              </div>
              <div className="lib-table">
                <div className="lib-row head">
                  <span></span><span>Subject</span><span>Title</span>
                  <span style={{textAlign: 'right'}}>Sources</span>
                  <span style={{textAlign: 'right'}}>Cards</span>
                  <span style={{textAlign: 'right'}}>Created</span>
                </div>
                {filtered.map((g) => (
                  <div key={g.i} className="lib-row">
                    <span className="num">{String(g.i).padStart(2, '0')}</span>
                    <span style={{display: 'flex', alignItems: 'center', gap: 6}}>
                      <span style={{filter: 'grayscale(0.4)'}}>{g.emoji}</span>
                      <span style={{color: 'var(--ink-soft)', fontSize: 12.5}}>{g.subj}</span>
                    </span>
                    <span className="lib-title">{g.title}</span>
                    <span className="num" style={{textAlign: 'right'}}>{g.sources}</span>
                    <span className="num" style={{textAlign: 'right'}}>{g.cards}</span>
                    <span className="num" style={{textAlign: 'right'}}>{g.when} ago</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ─── 03 / Calendar demo ─────────────────────────────────────────────────
  function CalendarDemo() {
    const events = {
      5:  [{ kind: 'study',      title: 'Bio study group' }],
      8:  [{ kind: 'assignment', title: 'Hist essay draft' }],
      12: [{ kind: 'exam',       title: 'Biology midterm' }, { kind: 'study', title: 'Review' }],
      14: [{ kind: 'assignment', title: 'Hist essay due' }],
      20: [{ kind: 'study',      title: 'Math review' }],
      23: [{ kind: 'exam',       title: 'Calculus final' }],
      28: [{ kind: 'other',      title: 'Lab report' }],
    };
    const grid = useMemo(() => {
      const g = [];
      for (let i = 0; i < 5; i++) g.push({ d: null, dim: true });
      for (let d = 1; d <= 31; d++) g.push({ d, dim: false });
      while (g.length % 7 !== 0) g.push({ d: null, dim: true });
      return g;
    }, []);
    return (
      <div className="demo-app">
        <MockSidebar active="calendar" />
        <div className="demo-main">
          <MockTopbar crumbs={['Calendar']} actions={<>
            <button className="btn ghost sm">←</button>
            <button className="btn ghost sm">Today</button>
            <button className="btn ghost sm">→</button>
            <button className="btn sm">⊟ Events</button>
            <button className="btn sm">✦ AI edit</button>
            <button className="btn sm">Import</button>
            <button className="btn accent sm">＋ Event</button>
          </>} />
          <div className="scroll">
            <div className="page-pad">
              <div className="eyebrow">§ Calendar</div>
              <h1 className="page-title">May 2026</h1>
              <div className="page-subtitle">
                <span><strong style={{color: 'var(--ink-strong)'}}>7 events</strong> tracked.</span>
                <span>·</span>
                <span>Click any day to add. Click an event to view or delete.</span>
              </div>
              <div className="cal-grid">
                {['Sun','Mon','Tue','Wed','Thu','Fri','Sat'].map(d => <div key={d} className="cal-dow">{d}</div>)}
                {grid.map((c, i) => {
                  const evs = c.d ? (events[c.d] || []) : [];
                  const isToday = c.d === 2;
                  return (
                    <div key={i} className={"cal-cell" + (c.dim ? ' dim' : '') + (isToday ? ' today' : '')}>
                      <span className="day-num">{c.d || ''}</span>
                      {evs.slice(0, 3).map((e, j) => (
                        <div key={j} className={"cal-event " + e.kind}>{e.title}</div>
                      ))}
                      {evs.length > 3 && <div style={{fontFamily: 'var(--mono)', fontSize: 9.5, color: 'var(--ink-mute)'}}>+{evs.length - 3}</div>}
                    </div>
                  );
                })}
              </div>
              <div style={{marginTop: 22, display: 'flex', gap: 22, alignItems: 'center', flexWrap: 'wrap'}}>
                <div className="eyebrow">Legend</div>
                {[
                  { k: 'exam',       label: 'Exam' },
                  { k: 'assignment', label: 'Assignment' },
                  { k: 'study',      label: 'Study' },
                  { k: 'other',      label: 'Other' },
                ].map(l => (
                  <span key={l.k} style={{display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--ink-soft)'}}>
                    <span className={"legend-dot " + l.k}></span>{l.label}
                  </span>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ─── 04 / Notes demo ────────────────────────────────────────────────────
  function NotesDemo() {
    return (
      <div className="demo-app">
        <MockSidebar activeNote="cell" />
        <div className="demo-main">
          <MockTopbar crumbs={['All notes', 'Cell biology — ch. 1']} actions={<>
            <span style={{fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-mute)', textTransform: 'uppercase', letterSpacing: '0.06em', marginRight: 6}}>Saved · 2m ago</span>
            <button className="btn sm">↻ Outline</button>
            <button className="btn sm">↗ Share</button>
            <button className="btn sm">✦ AI</button>
            <button className="btn ghost sm">⛶</button>
          </>} />
          <div className="note-fullscreen">
            <div className="note-toc-rail">
              <div className="eyebrow" style={{marginBottom: 10}}>Outline</div>
              <div className="note-toc-item h1">Cell biology — ch. 1</div>
              <div className="note-toc-item h2">The bilayer</div>
              <div className="note-toc-item h2">Transport</div>
              <div className="note-toc-item h3">Passive diffusion</div>
              <div className="note-toc-item h3">Active transport</div>
              <div className="note-toc-item h2">Membrane proteins</div>
              <div className="eyebrow" style={{marginTop: 22, marginBottom: 8}}>Linked guide</div>
              <div style={{padding: 8, border: '1px solid var(--hairline)', borderRadius: 'var(--r-sm)', background: 'var(--page)', cursor: 'pointer'}}>
                <div style={{fontSize: 12, fontWeight: 500, color: 'var(--ink-strong)'}}>Photosynthesis</div>
                <div style={{fontSize: 10.5, color: 'var(--ink-mute)', marginTop: 2, fontFamily: 'var(--mono)'}}>24 cards · 2d ago</div>
              </div>
            </div>
            <div className="note-main">
              <div className="note-main-inner">
                <input className="note-title-input" defaultValue="Cell biology — ch. 1" />
                <div className="note-toolbar">
                  <button className="tb-btn bold">B</button>
                  <button className="tb-btn italic">I</button>
                  <button className="tb-btn"><u>U</u></button>
                  <span className="tb-sep"></span>
                  <button className="tb-btn">H1</button>
                  <button className="tb-btn">H2</button>
                  <button className="tb-btn">H3</button>
                  <span className="tb-sep"></span>
                  <button className="tb-btn">•</button>
                  <button className="tb-btn">1.</button>
                  <button className="tb-btn">☐</button>
                  <span className="tb-sep"></span>
                  <button className="tb-btn code">{'</>'}</button>
                  <button className="tb-btn">"</button>
                  <span className="tb-sep"></span>
                  <button className="tb-btn">↶</button>
                  <button className="tb-btn">↷</button>
                </div>
                <div className="note-editor" contentEditable suppressContentEditableWarning>
                  <h2>The bilayer</h2>
                  <p>Lipids form the outer membrane of every eukaryotic cell. The phospholipid bilayer is fluid and selectively permeable, allowing certain molecules to pass freely while keeping others out.</p>
                  <ul>
                    <li><strong>Phospholipids</strong> — hydrophilic head, hydrophobic tail</li>
                    <li><strong>Cholesterol</strong> — modulates fluidity at varying temperatures</li>
                    <li><strong>Glycoproteins</strong> — surface markers, signaling, recognition</li>
                  </ul>
                  <p>The bilayer is held together by <code>hydrophobic interactions</code> between the lipid tails — not covalent bonds, which is why membranes can self-assemble and self-heal.</p>
                  <h2>Transport</h2>
                  <p>Small nonpolar molecules (O₂, CO₂) diffuse directly through the bilayer. Polar and charged species require channels or carriers — passive (facilitated diffusion) or active (ATP-driven).</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ─── 05 / Flashcards demo ───────────────────────────────────────────────
  function FlashcardsDemo() {
    return (
      <div className="demo-app">
        <MockSidebar active="library" activeSubject="bio" />
        <div className="demo-main">
          <MockTopbar crumbs={['Dashboard', 'Biology', 'Photosynthesis', 'Flashcards']}
                      actions={<button className="btn ghost sm">Exit</button>} />
          <div className="scroll">
            <div className="page-pad" style={{maxWidth: 880, margin: '0 auto'}}>
              <div className="eyebrow">§ Study mode</div>
              <h1 className="page-title">Pick a mode.</h1>
              <div className="page-subtitle">
                <span><strong style={{color: 'var(--ink-strong)'}}>24</strong> cards in this deck.</span>
                <span>·</span>
                <span>Cram for a deadline, or learn long-term with spaced repetition.</span>
              </div>
              <div className="mode-grid">
                <button className="mode-tile">
                  <div className="mode-glyph">⚡</div>
                  <div className="mode-name">Cram</div>
                  <div className="mode-tag">Timed · stateless</div>
                  <div className="mode-desc">Drill the whole deck before a deadline. Mark each card <strong>Pass</strong> or <strong>Fail</strong>; failed cards re-queue, and a card clears after 2 passes in a row.</div>
                  <div className="mode-meta"><span>24 cards</span><span>·</span><span>no progress saved</span></div>
                </button>
                <button className="mode-tile">
                  <div className="mode-glyph">∞</div>
                  <div className="mode-name">Long-term</div>
                  <div className="mode-tag">Spaced repetition · FSRS</div>
                  <div className="mode-desc">Learn for retention. Rate each card <strong>Again / Hard / Good / Easy</strong>; the FSRS scheduler picks when you'll see it next. New cards capped at 10/day.</div>
                  <div className="mode-meta"><span>persistent state</span><span>·</span><span>per-card schedule</span></div>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ─── auth modal — wraps signIn/signUp from auth.js ──────────────────────
  function AuthModal({ initialMode = 'login', onClose }) {
    const [mode, setMode] = useState(initialMode);
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [busy, setBusy] = useState(false);
    const [error, setError] = useState(null);
    const [info, setInfo] = useState(null);

    useEffect(() => {
      const onKey = (e) => { if (e.key === 'Escape') onClose(); };
      window.addEventListener('keydown', onKey);
      return () => window.removeEventListener('keydown', onKey);
    }, [onClose]);

    const submit = async (e) => {
      e.preventDefault();
      setError(null); setInfo(null);
      if (!email || !password) { setError('Email and password are required.'); return; }
      if (password.length < 6) { setError('Password must be at least 6 characters.'); return; }
      setBusy(true);
      try {
        const fn = mode === 'signup' ? window.signUp : window.signIn;
        const { data, error: err } = await fn(email, password);
        if (err) {
          setError(err.message);
        } else if (mode === 'signup' && !data.session) {
          setInfo('Account created. Check your email for a confirmation link, then sign in.');
          setMode('login');
        }
        // success: auth listener flips the screen automatically
      } catch (err) {
        setError(err.message || String(err));
      } finally {
        setBusy(false);
      }
    };

    return (
      <div className="auth-modal-backdrop" onClick={onClose}>
        <div className="auth-modal" onClick={(e) => e.stopPropagation()}>
          <button className="auth-modal-close" type="button" onClick={onClose} aria-label="Close">×</button>
          <div className="auth-modal-eyebrow">{mode === 'login' ? 'Welcome back' : 'New here'}</div>
          <h2 className="auth-modal-title">{mode === 'login' ? 'Sign in.' : 'Create your account.'}</h2>
          <p className="auth-modal-sub">{mode === 'login' ? 'Pick up where you left off.' : 'Personal use, no card required.'}</p>
          <form onSubmit={submit} className="auth-form">
            <label className="auth-field">
              <span>Email</span>
              <input type="email" required value={email} onChange={(e) => setEmail(e.target.value)}
                     placeholder="you@example.com" autoComplete="email" autoFocus />
            </label>
            <label className="auth-field">
              <span>Password</span>
              <input type="password" required minLength={6} value={password} onChange={(e) => setPassword(e.target.value)}
                     placeholder="six characters or more"
                     autoComplete={mode === 'signup' ? 'new-password' : 'current-password'} />
            </label>
            {error && <div className="auth-alert error">{error}</div>}
            {info && <div className="auth-alert info">{info}</div>}
            <button type="submit" className="auth-submit" disabled={busy}>
              {busy ? 'opening the notebook…' : (mode === 'login' ? 'Sign in →' : 'Create account →')}
            </button>
          </form>
          <div className="auth-switch">
            {mode === 'login' ? "No account yet? " : 'Already have an account? '}
            <a href="#" onClick={(e) => { e.preventDefault(); setError(null); setInfo(null); setMode(mode === 'login' ? 'signup' : 'login'); }}>
              {mode === 'login' ? 'Sign up' : 'Sign in'}
            </a>
          </div>
        </div>
      </div>
    );
  }

  // ─── top-level landing ──────────────────────────────────────────────────
  function LandingScreen() {
    const [authMode, setAuthMode] = useState(null);
    useEffect(() => {
      window.addEventListener('scroll', _request, { passive: true });
      window.addEventListener('resize', _request);
      return () => {
        window.removeEventListener('scroll', _request);
        window.removeEventListener('resize', _request);
      };
    }, []);
    return (
      <div className="landing-page">
        <LandingTopBar onLogin={() => setAuthMode('login')} onSignup={() => setAuthMode('signup')} />
        <VideoBanner />
        <Hero />
        <SystemHeader />
        <DemoSection kicker="01 / 05" title="Dashboard"  from="bottom" seed={3}><DashboardDemo /></DemoSection>
        <DemoSection kicker="02 / 05" title="Guides"     from="right"  seed={11}><GuidesDemo /></DemoSection>
        <DemoSection kicker="03 / 05" title="Calendar"   from="top"    seed={29}><CalendarDemo /></DemoSection>
        <DemoSection kicker="04 / 05" title="Notes"      from="left"   seed={47}><NotesDemo /></DemoSection>
        <DemoSection kicker="05 / 05" title="Flashcards" from="bottom" seed={71}><FlashcardsDemo /></DemoSection>
        <footer className="landing-footer">
          <div className="eyebrow">end of demo</div>
          <div className="landing-footer-cta">
            <button className="auth-submit" style={{maxWidth: 240, margin: '14px auto 0'}} onClick={() => setAuthMode('signup')}>
              Get started →
            </button>
          </div>
        </footer>
        {authMode && <AuthModal initialMode={authMode} onClose={() => setAuthMode(null)} />}
      </div>
    );
  }

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