/* Brainstorm X — App shell (connected prototype).
   Real hash-routed app over the BXStore mock backend:
     #/                  marketing landing
     #/login             dummy magic-link sign-in
     #/app               dashboard (your naming sessions)
     #/s/<id>/<stage>    a session stage: wizard|invite|arena|shortlist|report
   Every screen reads/writes through BXStore, so state persists across
   reloads and each page is genuinely connected to the next. */
(function () {
  const { useState, useEffect } = React;
  const DS = window.BrainstormXDesignSystem_f2a458;
  const { Button, Card, NameCard, KeywordOrb, AvatarStack, Avatar, Badge, Input } = DS;
  const I = window.BXIcons;
  const Store = window.BXStore;
  const { useTweaks, TweaksPanel, TweakSection, TweakToggle, TweakSlider, TweakColor } = window;

  const STAGES_LIST = ['wizard', 'invite', 'arena', 'shortlist', 'report'];

  // ---- routing ---------------------------------------------------------
  function useHash() {
    const [h, setH] = useState(location.hash || '#/');
    useEffect(() => {
      const f = () => setH(location.hash || '#/');
      window.addEventListener('hashchange', f);
      return () => window.removeEventListener('hashchange', f);
    }, []);
    return h;
  }
  function parse(h) {
    const p = h.replace(/^#\/?/, '').split('/').filter(Boolean);
    if (!p.length) return { name: 'home' };
    if (p[0] === 'login') return { name: 'login' };
    if (p[0] === 'app') return { name: 'dashboard' };
    if (p[0] === 's' && p[1]) return { name: 'session', sessionId: p[1], stage: STAGES_LIST.includes(p[2]) ? p[2] : 'arena' };
    return { name: 'home' };
  }
  const nav = (h) => { location.hash = h; };
  function ago(t) {
    const m = Math.round((Date.now() - t) / 60000);
    if (m < 1) return 'just now'; if (m < 60) return m + 'm ago';
    const hr = Math.round(m / 60); if (hr < 24) return hr + 'h ago';
    return Math.round(hr / 24) + 'd ago';
  }

  // ---- live user (reactive to store) -----------------------------------
  function useUser() {
    const [u, setU] = useState(Store.snapshot().user);
    useEffect(() => Store.subscribe((db) => setU(db.user)), []);
    return u;
  }

  function Stars({ n = 50 }) {
    const stars = React.useMemo(() => Array.from({ length: n }, () => ({
      top: Math.random() * 100, left: Math.random() * 100, s: Math.random() * 2 + 1,
      o: Math.random() * 0.6 + 0.15, glow: Math.random() > 0.88,
    })), [n]);
    return <div style={{ position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none' }}>
      {stars.map((s, i) => <span key={i} style={{ position: 'absolute', top: s.top + '%', left: s.left + '%', width: s.s, height: s.s, borderRadius: '50%', background: '#fff', opacity: s.o, boxShadow: s.glow ? '0 0 6px var(--neon-cyan)' : 'none' }} />)}
    </div>;
  }

  function Logo({ size = 22 }) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <img src="../assets/mark-spark.svg" width={size * 1.5} height={size * 1.5} alt="" />
        <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: size, color: 'var(--text-1)', letterSpacing: '-0.02em' }}>Brainstorm<span className="bx-text-nebula"> X</span></span>
      </div>
    );
  }

  // ---- marketing landing ----------------------------------------------
  function Landing({ user, motion }) {
    const cta = () => nav(user ? '#/app' : '#/login');
    return (
      <div className="bx-nebula-bg" style={{ minHeight: '100vh', position: 'relative', overflow: 'hidden', display: 'flex', alignItems: 'center' }}>
        <Stars n={56} />
        <div style={{ position: 'absolute', top: 22, left: 0, right: 0, padding: '0 40px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <Logo />
          <Button variant="secondary" size="sm" onClick={cta}>{user ? 'Open dashboard' : 'Sign in'}</Button>
        </div>
        <div style={{ position: 'relative', maxWidth: 1240, margin: '0 auto', padding: '0 40px', display: 'grid', gridTemplateColumns: '1.05fr 0.95fr', gap: 48, alignItems: 'center', width: '100%' }}>
          <div>
            <span className="bx-eyebrow" style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><I.Sparkles size={14} /> Collaborative AI naming</span>
            <h1 style={{ fontSize: 'clamp(40px,5vw,66px)', margin: '16px 0 0', lineHeight: 1.02 }}>
              Brainstorm brand names in a live <span className="bx-text-nebula">AI-powered 3D space</span>
            </h1>
            <p style={{ fontSize: 19, color: 'var(--text-2)', lineHeight: 1.55, margin: '22px 0 0', maxWidth: '50ch' }}>
              Create a naming session, invite your team and watch ideas evolve as everyone votes, boosts and shortlists their favourites.
            </p>
            <div style={{ display: 'flex', gap: 14, marginTop: 32, flexWrap: 'wrap' }}>
              <Button size="lg" onClick={cta} iconRight={<I.ArrowRight size={18} />}>Start a naming session</Button>
              <Button size="lg" variant="secondary" onClick={() => nav(user ? '#/app' : '#/login')} iconLeft={<I.Compass size={18} />}>See your sessions</Button>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 30 }}>
              <AvatarStack people={window.BXpeople} max={4} size={32} />
              <span style={{ fontSize: 14, color: 'var(--text-3)' }}>No password — just a magic link. Free to start.</span>
            </div>
          </div>
          <div style={{ position: 'relative', height: 460 }}>
            <div style={{ position: 'absolute', top: 10, left: 30, transform: 'scale(0.92)' }}>
              <NameCard name="Pawlio" style="brandable" score={14} heat="on_fire" confidence={82} keywords={['pet', 'playful']} counts={{ up: 14, fire: 6 }} shortlisted floating={motion} />
            </div>
            <div style={{ position: 'absolute', top: 250, left: 0, transform: 'scale(0.8)' }}>
              <NameCard name="Nuvio" style="evocative" score={5} heat="warm" keywords={['fresh']} counts={{ up: 6, down: 1 }} floating={motion} />
            </div>
            <div style={{ position: 'absolute', top: 150, right: -10, transform: 'scale(0.84)' }}>
              <NameCard name="Snugglo" style="compound" score={9} heat="hot" keywords={['cute', 'cosy']} counts={{ up: 9, fire: 2 }} floating={motion} />
            </div>
            <div style={{ position: 'absolute', bottom: 6, right: 70 }}>
              <KeywordOrb label="quirky" state="favourite" weight={3} count={5} floating={motion} />
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ---- login (dummy magic link) ----------------------------------------
  function Login() {
    const [email, setEmail] = useState('you@studio.co.uk');
    const [stage, setStage] = useState('enter'); // enter | sent | signing
    const send = (e) => { e.preventDefault(); if (email.trim()) setStage('sent'); };
    const open = async () => { setStage('signing'); await Store.signIn(email.trim()); nav('#/app'); };
    return (
      <div className="bx-nebula-bg" style={{ minHeight: '100vh', position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
        <Stars n={40} />
        <div style={{ position: 'absolute', top: 22, left: 40 }}><Logo /></div>
        <Card glass glow="violet" style={{ width: 'min(440px,100%)', padding: '34px 34px', position: 'relative' }}>
          {stage === 'enter' && (<>
            <span className="bx-eyebrow">Welcome back</span>
            <h1 style={{ fontSize: 28, margin: '10px 0 6px' }}>Sign in to Brainstorm X</h1>
            <p style={{ fontSize: 15, color: 'var(--text-2)', marginBottom: 22 }}>Enter your email and we'll send a secure magic link. No password needed.</p>
            <form onSubmit={send}>
              <Input type="email" placeholder="you@studio.co.uk" value={email} onChange={(e) => setEmail(e.target.value)} iconLeft={<I.Mail size={18} />} />
              <div style={{ marginTop: 18 }}><Button type="submit" fullWidth size="lg" iconRight={<I.ArrowRight size={18} />}>Send magic link</Button></div>
            </form>
            <p style={{ fontSize: 12.5, color: 'var(--text-3)', marginTop: 16, textAlign: 'center' }}>Prototype — any email works, nothing is sent.</p>
          </>)}
          {(stage === 'sent' || stage === 'signing') && (<>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 56, height: 56, borderRadius: '50%', margin: '0 auto 18px', background: 'color-mix(in srgb, var(--neon-cyan) 16%, transparent)', border: '1px solid color-mix(in srgb, var(--neon-cyan) 45%, transparent)', color: 'var(--neon-cyan)' }}><I.Mail size={26} /></div>
            <h1 style={{ fontSize: 24, margin: '0 0 6px', textAlign: 'center' }}>Check your inbox</h1>
            <p style={{ fontSize: 15, color: 'var(--text-2)', marginBottom: 22, textAlign: 'center' }}>We sent a magic link to <strong style={{ color: 'var(--text-1)' }}>{email}</strong>.</p>
            <Button fullWidth size="lg" onClick={open} disabled={stage === 'signing'} iconRight={<I.ArrowRight size={18} />}>{stage === 'signing' ? 'Signing in…' : 'Open the magic link'}</Button>
            <button onClick={() => setStage('enter')} style={{ display: 'block', margin: '14px auto 0', background: 'none', border: 'none', color: 'var(--text-3)', cursor: 'pointer', fontSize: 13 }}>Use a different email</button>
          </>)}
        </Card>
      </div>
    );
  }

  // ---- dashboard -------------------------------------------------------
  function Dashboard({ user }) {
    const [sessions, setSessions] = useState(null);
    const reload = () => Store.listSessions().then(setSessions);
    useEffect(() => { reload(); return Store.subscribe(() => reload()); }, []);

    return (
      <div className="bx-nebula-bg" style={{ minHeight: '100vh', position: 'relative' }}>
        <Stars n={36} />
        <header style={{ position: 'sticky', top: 0, zIndex: 20, display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 32px', borderBottom: '1px solid var(--line-1)', background: 'rgba(10,10,24,0.6)', backdropFilter: 'blur(18px)', WebkitBackdropFilter: 'blur(18px)' }}>
          <button onClick={() => nav('#/')} style={{ background: 'none', border: 'none', cursor: 'pointer' }}><Logo size={19} /></button>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
              <Avatar name={user ? user.name : 'You'} size={30} ring />
              <span style={{ fontSize: 14, color: 'var(--text-2)' }}>{user ? user.email : ''}</span>
            </div>
            <Button variant="ghost" size="sm" onClick={async () => { await Store.signOut(); nav('#/'); }}>Sign out</Button>
          </div>
        </header>

        <div style={{ position: 'relative', maxWidth: 1100, margin: '0 auto', padding: '40px 32px 80px' }}>
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, marginBottom: 26, flexWrap: 'wrap' }}>
            <div>
              <span className="bx-eyebrow">Your workspace</span>
              <h1 style={{ fontSize: 'clamp(28px,3.5vw,40px)', margin: '12px 0 0' }}>Naming sessions</h1>
            </div>
            <Button size="lg" onClick={() => nav('#/s/new/wizard')} iconLeft={<I.Plus size={18} />}>New session</Button>
          </div>

          {!sessions && <div style={{ color: 'var(--text-3)', fontFamily: 'var(--font-mono)', fontSize: 14 }}>Loading sessions…</div>}

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(330px, 1fr))', gap: 18 }}>
            {sessions && sessions.map((s) => (
              <Card key={s.id} hover onClick={() => nav('#/s/' + s.id + '/arena')} style={{ cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 14 }}>
                <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 10 }}>
                  <div>
                    <h3 style={{ fontSize: 21, fontFamily: 'var(--font-display)', color: 'var(--text-1)' }}>{s.project}</h3>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginTop: 4 }}>{s.type} · {s.industry || 'naming'}</div>
                  </div>
                  <Badge tone="cyan" mono size="sm">Wave {s.wave}</Badge>
                </div>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  <Badge tone="neutral" size="sm">{s.nameCount} names</Badge>
                  <Badge tone="fire" size="sm">🔥 {s.onFire}</Badge>
                  <Badge tone="warm" size="sm">★ {s.shortlisted} shortlisted</Badge>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, marginTop: 'auto' }}>
                  <AvatarStack people={s.members} max={4} size={28} />
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-3)' }}>updated {ago(s.updatedAt)}</span>
                </div>
                <div style={{ display: 'flex', gap: 8, borderTop: '1px solid var(--line-1)', paddingTop: 12 }}>
                  <Button variant="secondary" size="sm" onClick={(e) => { e.stopPropagation(); nav('#/s/' + s.id + '/arena'); }} iconLeft={<I.Zap size={15} />}>Arena</Button>
                  <Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); nav('#/s/' + s.id + '/shortlist'); }} iconLeft={<I.Star size={15} />}>Shortlist</Button>
                  <Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); nav('#/s/' + s.id + '/report'); }} iconLeft={<I.Layers size={15} />}>Report</Button>
                </div>
              </Card>
            ))}

            {sessions && (
              <button onClick={() => nav('#/s/new/wizard')} style={{
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 10, minHeight: 220,
                borderRadius: 'var(--radius-lg)', cursor: 'pointer', color: 'var(--text-3)',
                border: '1px dashed var(--line-3)', background: 'color-mix(in srgb, var(--neon-cyan) 5%, transparent)',
              }}>
                <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 48, height: 48, borderRadius: '50%', background: 'var(--surface-2)', color: 'var(--neon-cyan)' }}><I.Plus size={24} /></span>
                <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 700, color: 'var(--text-2)' }}>Start a new session</span>
                <span style={{ fontSize: 12.5 }}>Run the naming wizard</span>
              </button>
            )}
          </div>
        </div>
      </div>
    );
  }

  // ---- stage nav (inside a session) ------------------------------------
  const STAGE_META = [
    { id: 'wizard', label: 'Wizard', ic: 'WandSparkles' },
    { id: 'invite', label: 'Invite', ic: 'Users' },
    { id: 'arena', label: 'Arena', ic: 'Zap' },
    { id: 'shortlist', label: 'Shortlist', ic: 'Star' },
    { id: 'report', label: 'Report', ic: 'Layers' },
  ];
  function StageNav({ sid, stage }) {
    return (
      <div style={{
        position: 'fixed', bottom: 16, left: '50%', transform: 'translateX(-50%)', zIndex: 70,
        display: 'flex', gap: 4, padding: 6, borderRadius: 'var(--radius-pill)',
        background: 'var(--surface-glass-strong)', border: '1px solid var(--line-2)',
        backdropFilter: 'blur(18px)', WebkitBackdropFilter: 'blur(18px)', boxShadow: 'var(--shadow-lg)',
      }}>
        <button onClick={() => nav('#/app')} title="Dashboard" style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 13px', borderRadius: 'var(--radius-pill)', border: 'none', cursor: 'pointer', background: 'transparent', color: 'var(--text-2)', fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 700 }}><I.Compass size={15} />Sessions</button>
        <span style={{ width: 1, background: 'var(--line-2)', margin: '6px 2px' }} />
        {STAGE_META.map((s) => {
          const Ic = I[s.ic]; const on = stage === s.id;
          return (
            <button key={s.id} onClick={() => nav('#/s/' + sid + '/' + s.id)} title={s.label} style={{
              display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 13px',
              borderRadius: 'var(--radius-pill)', border: 'none', cursor: 'pointer',
              background: on ? 'var(--neon-cyan)' : 'transparent', color: on ? 'var(--accent-ink)' : 'var(--text-2)',
              fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 700,
              boxShadow: on ? 'var(--glow-cyan)' : 'none', transition: 'all var(--dur-base) var(--ease-out)',
            }}><Ic size={15} />{s.label}</button>
          );
        })}
      </div>
    );
  }

  function Loader({ label }) {
    return (
      <div className="bx-nebula-bg" style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-3)', fontFamily: 'var(--font-mono)', fontSize: 14 }}>
        {label || 'Loading…'}
      </div>
    );
  }

  function sessionToMeta(s) {
    return {
      project: s.project, type: s.type, industry: s.industry, audience: s.audience,
      description: s.description, keywordsList: s.keywordsList, avoid: s.avoid,
      styles: s.styles, randomness: s.randomness, personality: s.personality,
    };
  }

  // ---- a session + its active stage ------------------------------------
  function SessionApp({ sid, stage, tweaks, setTweak }) {
    const isNew = sid === 'new';
    const [session, setSession] = useState(null);
    const [loading, setLoading] = useState(!isNew);
    const [busy, setBusy] = useState(false);

    useEffect(() => {
      if (isNew) { setSession(null); setLoading(false); return; }
      let live = true; setLoading(true);
      Store.getSession(sid).then((s) => { if (live) { setSession(s); setLoading(false); } });
      return () => { live = false; };
    }, [sid, isNew]);

    // store-backed setters (persist on every change)
    const persist = (next) => { Store.saveSessionSync(next); return next; };
    const setNames = (upd) => setSession((p) => persist({ ...p, names: typeof upd === 'function' ? upd(p.names) : upd }));
    const setKeywords = (upd) => setSession((p) => persist({ ...p, keywords: typeof upd === 'function' ? upd(p.keywords) : upd }));
    const setWave = (upd) => setSession((p) => persist({ ...p, wave: typeof upd === 'function' ? upd(p.wave) : upd }));
    const goto = (st) => nav('#/s/' + sid + '/' + st);

    // ---- wizard (create or edit) ----
    if (stage === 'wizard') {
      const onComplete = async (meta) => {
        setBusy(true);
        if (isNew) {
          const sum = await Store.createSession(meta);
          nav('#/s/' + sum.id + '/invite');
        } else {
          await Store.updateMeta(sid, meta);
          nav('#/s/' + sid + '/invite');
        }
      };
      if (loading) return <Loader label="Loading session…" />;
      return React.createElement(window.BXWizard, {
        initial: session ? sessionToMeta(session) : null,
        busy, onComplete, onCancel: () => nav('#/app'),
      });
    }

    if (loading) return <Loader label="Loading session…" />;
    if (!session) {
      return (
        <div className="bx-nebula-bg" style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 16 }}>
          <p style={{ color: 'var(--text-2)' }}>That session could not be found.</p>
          <Button onClick={() => nav('#/app')}>Back to dashboard</Button>
        </div>
      );
    }

    const shared = {
      session, project: session.project,
      names: session.names, setNames,
      keywords: session.keywords, setKeywords,
      wave: session.wave, setWave, goto,
      addMembers: async (emails) => { const m = await Store.addMembers(sid, emails); setSession((p) => ({ ...p, members: m })); return m; },
    };

    let Screen = null;
    if (stage === 'invite') Screen = React.createElement(window.BXInvite, shared);
    else if (stage === 'arena') Screen = React.createElement(window.BXArena, { ...shared, motion: tweaks.motion, density: tweaks.density });
    else if (stage === 'shortlist') Screen = React.createElement(window.BXShortlist, shared);
    else if (stage === 'report') Screen = React.createElement(window.BXReport, shared);

    return (<>
      <div key={stage} style={{ animation: tweaks.motion ? 'bxScreenIn 0.4s var(--ease-out)' : 'none' }}>{Screen}</div>
      <StageNav sid={sid} stage={stage} />
    </>);
  }

  const ACCENTS = ['#2DE2E6', '#FF3DA6', '#8A5BFF', '#A8FF4D'];

  function Prototype() {
    const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
      "accent": "#2DE2E6",
      "motion": true,
      "density": 8
    }/*EDITMODE-END*/;
    const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
    const hash = useHash();
    const route = parse(hash);
    const user = useUser();
    const demoMode = /(?:[?&])demo=1\b/.test(location.search);

    // opt-in auto-login for deep links from the test hub (?demo=1)
    useEffect(() => {
      if (demoMode && !user) Store.signIn('demo@studio.co.uk');
    }, [demoMode, user]);

    // auth gate
    useEffect(() => {
      if ((route.name === 'dashboard' || route.name === 'session') && !user && !demoMode) nav('#/login');
      if (route.name === 'login' && user) nav('#/app');
    }, [route.name, user, demoMode]);

    let View = null;
    if (route.name === 'home') View = <Landing user={user} motion={t.motion} />;
    else if (route.name === 'login') View = <Login />;
    else if (route.name === 'dashboard') View = user ? <Dashboard user={user} /> : <Loader />;
    else if (route.name === 'session') View = user ? <SessionApp key={route.sessionId} sid={route.sessionId} stage={route.stage} tweaks={t} setTweak={setTweak} /> : <Loader />;

    return (
      <div style={{ '--neon-cyan': t.accent, '--accent': t.accent, minHeight: '100vh' }}>
        {View}
        <TweaksPanel title="Tweaks">
          <TweakSection label="Theme" />
          <TweakColor label="Accent" value={t.accent} options={ACCENTS} onChange={(v) => setTweak('accent', v)} />
          <TweakSection label="Arena" />
          <TweakToggle label="Motion (float & pulse)" value={t.motion} onChange={(v) => setTweak('motion', v)} />
          <TweakSlider label="Scene density" value={t.density} min={4} max={8} step={1} unit=" names" onChange={(v) => setTweak('density', v)} />
          <TweakSection label="Prototype data" />
          <button onClick={async () => { await Store.resetDemo(); nav('#/app'); }} style={{ width: '100%', padding: '9px 12px', borderRadius: 'var(--radius-md)', cursor: 'pointer', border: '1px solid var(--line-2)', background: 'var(--surface-2)', color: 'var(--text-2)', fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600 }}>Reset demo data</button>
        </TweaksPanel>
      </div>
    );
  }

  if (!document.getElementById('bx-proto-kf')) {
    const s = document.createElement('style'); s.id = 'bx-proto-kf';
    s.textContent = '@keyframes bxScreenIn{from{transform:translateY(12px);opacity:.4}to{transform:none;opacity:1}}';
    document.head.appendChild(s);
  }

  window.BXPrototype = Prototype;
})();
