/* ============================================================
   55 QUIZ — Catalog (start screen) + Home / landing
   ============================================================ */
const { useState, useMemo } = React;

/* ---------- The "55 unlock" hero banner ---------- */
function UnlockBanner({ freeQuiz, onOpen, onSub, isDesktop }) {
  const [t, setT] = useState(55);
  return (
    <div className="grain" style={{
      position: 'relative', overflow: 'hidden',
      borderRadius: 'calc(var(--r-xl) * var(--tw-radius-scale))',
      background: 'linear-gradient(120deg, var(--brand), color-mix(in oklab, var(--brand) 55%, #1a0f55))',
      color: '#fff', padding: isDesktop ? '26px 28px' : '20px',
      display: 'flex', flexDirection: isDesktop ? 'row' : 'column', gap: isDesktop ? 28 : 18,
      alignItems: isDesktop ? 'center' : 'stretch',
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <span className="t-over" style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '6px 11px', borderRadius: 'var(--r-pill)', background: 'rgba(255,255,255,.16)' }}>
          <Icon name="shuffle" size={13} /> Free spin
        </span>
        <h2 className="t-display" style={{ margin: '12px 0 6px', fontSize: isDesktop ? 30 : 24, color: '#fff' }}>
          A random quiz unlocks <span style={{ color: 'var(--lime)' }}>every 55 seconds.</span>
        </h2>
        <p className="t-sm" style={{ margin: 0, color: 'rgba(255,255,255,.82)', maxWidth: 460 }}>
          Right now it’s <strong style={{ color: '#fff' }}>“{freeQuiz.title}”</strong>. Catch it before the timer flips — or skip the wait.
        </p>
        <div style={{ display: 'flex', gap: 10, marginTop: 16, flexWrap: 'wrap' }}>
          <Btn variant="lime" icon="play" onClick={() => onOpen(freeQuiz)}>Play it now</Btn>
          <Btn variant="ghost" icon="infinity" onClick={onSub} style={{ color: '#fff', borderColor: 'rgba(255,255,255,.4)' }}>Unlock all — 55 Pass</Btn>
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, justifyContent: isDesktop ? 'flex-end' : 'space-between',
        background: 'rgba(0,0,0,.18)', borderRadius: 'var(--r-lg)', padding: '14px 18px' }}>
        <div>
          <div className="t-over" style={{ color: 'rgba(255,255,255,.7)' }}>Unlocks in</div>
          <div className="tnum t-mono" style={{ fontSize: 30, fontWeight: 700, color: 'var(--lime)' }}>0:{String(t).padStart(2, '0')}</div>
        </div>
        <Countdown55 onUnlock={() => {}} onTick={setT} />
      </div>
    </div>
  );
}

/* ---------- Category strip ---------- */
function CategoryStrip({ active, onPick }) {
  return (
    <div style={{ display: 'flex', gap: 9, overflowX: 'auto', paddingBottom: 4, scrollbarWidth: 'none', WebkitOverflowScrolling: 'touch' }}>
      <Chip active={active === 'all'} onClick={() => onPick('all')} icon="sparkles">All</Chip>
      {CATEGORIES.map(c => (
        <Chip key={c.id} active={active === c.id} color={c.color} icon={c.icon} onClick={() => onPick(c.id)}>{c.label}</Chip>
      ))}
    </div>
  );
}

/* ---------- Catalog (START SCREEN) ---------- */
function CatalogScreen({ onOpen, onSub, isDesktop, subscribed }) {
  const [cat, setCat] = useState('all');
  const [query, setQuery] = useState('');
  const [sort, setSort] = useState('popular');
  const freeQuiz = QUIZZES.find(q => q.id === 'q4');

  const list = useMemo(() => {
    let r = QUIZZES.filter(q =>
      (cat === 'all' || q.cat === cat) &&
      (q.title.toLowerCase().includes(query.toLowerCase()) || q.blurb.toLowerCase().includes(query.toLowerCase()))
    );
    if (sort === 'popular') r = [...r].sort((a, b) => b.plays - a.plays);
    if (sort === 'top') r = [...r].sort((a, b) => b.rating - a.rating);
    if (sort === 'quick') r = [...r].sort((a, b) => a.mins - b.mins);
    return r;
  }, [cat, query, sort]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      {/* heading + search */}
      <div style={{ display: 'flex', flexDirection: isDesktop ? 'row' : 'column', gap: 14, alignItems: isDesktop ? 'flex-end' : 'stretch', justifyContent: 'space-between' }}>
        <div>
          <span className="t-over" style={{ color: 'var(--text-3)' }}>The catalog</span>
          <h1 className="t-h1" style={{ margin: '6px 0 0', fontSize: isDesktop ? 38 : 30 }}>
            Pick a quiz. <span style={{ color: 'var(--brand)' }}>Beat the clock.</span>
          </h1>
        </div>
        <div style={{ position: 'relative', width: isDesktop ? 320 : '100%' }}>
          <Icon name="search" size={18} style={{ position: 'absolute', left: 16, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)' }} />
          <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search 12 quizzes…"
            style={{ width: '100%', padding: '13px 16px 13px 44px', fontSize: 15, color: 'var(--text)',
              background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-pill)', outline: 'none' }} />
        </div>
      </div>

      {!subscribed && <UnlockBanner freeQuiz={freeQuiz} onOpen={onOpen} onSub={onSub} isDesktop={isDesktop} />}

      {/* categories + sort */}
      <div style={{ display: 'flex', flexDirection: isDesktop ? 'row' : 'column', gap: 12, alignItems: isDesktop ? 'center' : 'stretch', justifyContent: 'space-between' }}>
        <CategoryStrip active={cat} onPick={setCat} />
        <div style={{ display: 'flex', gap: 7, flexShrink: 0 }}>
          {[['popular', 'Popular'], ['top', 'Top rated'], ['quick', 'Quickest']].map(([k, l]) => (
            <Chip key={k} size="sm" active={sort === k} onClick={() => setSort(k)}>{l}</Chip>
          ))}
        </div>
      </div>

      {/* grid */}
      <div style={{ display: 'grid', gridTemplateColumns: isDesktop ? 'repeat(auto-fill, minmax(300px, 1fr))' : '1fr', gap: 16 }}>
        {list.map(q => <QuizCard key={q.id} quiz={q} onOpen={onOpen} locked={!subscribed} />)}
      </div>
      {list.length === 0 && (
        <div style={{ textAlign: 'center', padding: 48, color: 'var(--text-2)' }}>
          <Icon name="search" size={32} style={{ margin: '0 auto 10px' }} />
          <p>No quiz matches “{query}”. Try another topic — or make your own.</p>
        </div>
      )}
    </div>
  );
}

/* ---------- Home / landing ---------- */
function HomeScreen({ onOpen, go, isDesktop }) {
  const trending = [...QUIZZES].sort((a, b) => b.plays - a.plays).slice(0, isDesktop ? 6 : 4);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 32 }}>
      {/* hero */}
      <div className="grain" style={{
        position: 'relative', overflow: 'hidden', borderRadius: 'calc(var(--r-xl) * var(--tw-radius-scale))',
        background: 'var(--text)', color: 'var(--bg)', padding: isDesktop ? '52px 48px' : '34px 24px',
      }}>
        <div style={{ position: 'absolute', right: isDesktop ? -30 : -60, top: -40, fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: isDesktop ? 280 : 200, color: 'var(--brand)', opacity: .9, lineHeight: 1, letterSpacing: '-.05em' }}>55</div>
        <div style={{ position: 'relative', maxWidth: 560 }}>
          <span className="t-over" style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '7px 12px', borderRadius: 'var(--r-pill)', background: 'var(--lime)', color: 'var(--lime-ink)' }}>
            <Icon name="bolt" size={13} fill="var(--lime-ink)" stroke={0} /> Smart trivia, built to share
          </span>
          <h1 className="t-display" style={{ margin: '18px 0 14px', fontSize: isDesktop ? 60 : 40, color: 'var(--bg)' }}>
            Quizzes worth<br /><span style={{ color: 'var(--lime)' }}>fifty-five seconds.</span>
          </h1>
          <p className="t-body" style={{ margin: 0, color: 'color-mix(in oklab, var(--bg) 78%, var(--text))', maxWidth: 460, fontSize: isDesktop ? 17 : 15 }}>
            Play a curated catalog of modular quizzes across ten subjects — or build your own on any topic and play it whenever you like.
          </p>
          <div style={{ display: 'flex', gap: 12, marginTop: 26, flexWrap: 'wrap' }}>
            <Btn variant="lime" size="lg" icon="compass" onClick={() => go('catalog')}>Browse catalog</Btn>
            <Btn variant="ghost" size="lg" icon="wand" onClick={() => go('create')} style={{ color: 'var(--bg)', borderColor: 'color-mix(in oklab, var(--bg) 40%, transparent)' }}>Build a quiz</Btn>
          </div>
        </div>
      </div>

      {/* stat strip */}
      <div style={{ display: 'grid', gridTemplateColumns: isDesktop ? 'repeat(3,1fr)' : '1fr', gap: 14 }}>
        {[['list-checks', '12 modular quizzes', 'Curated across 10 subjects, from history to tech.'],
          ['shuffle', 'A free quiz every 55s', 'The catalog opens a random unlock on a loop.'],
          ['wand', 'Build your own', 'Generate a custom quiz on any topic in minutes.']].map(([ic, t, d]) => (
          <div key={t} style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 22, boxShadow: 'var(--shadow-sm)' }}>
            <div style={{ width: 42, height: 42, borderRadius: 'var(--r-sm)', display: 'grid', placeItems: 'center', background: 'color-mix(in oklab, var(--brand) 14%, transparent)', color: 'var(--brand)', marginBottom: 14 }}>
              <Icon name={ic} size={22} />
            </div>
            <h3 className="t-h3" style={{ margin: '0 0 5px' }}>{t}</h3>
            <p className="t-sm" style={{ margin: 0, color: 'var(--text-2)' }}>{d}</p>
          </div>
        ))}
      </div>

      {/* categories */}
      <section>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 14 }}>
          <h2 className="t-h2">Browse by subject</h2>
          <button onClick={() => go('catalog')} style={{ background: 'none', border: 'none', color: 'var(--brand)', fontWeight: 700, fontSize: 14, display: 'inline-flex', alignItems: 'center', gap: 4 }}>See all <Icon name="arrow-right" size={15} /></button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: isDesktop ? 'repeat(5,1fr)' : 'repeat(2,1fr)', gap: 12 }}>
          {CATEGORIES.map(c => (
            <button key={c.id} onClick={() => go('catalog')} className="grain" style={{
              position: 'relative', overflow: 'hidden', textAlign: 'left', cursor: 'pointer',
              border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 16, background: 'var(--surface)',
              display: 'flex', flexDirection: 'column', gap: 30, transition: 'transform 180ms var(--ease)',
            }}
              onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-3px)'}
              onMouseLeave={e => e.currentTarget.style.transform = 'none'}>
              <div style={{ width: 40, height: 40, borderRadius: 'var(--r-sm)', display: 'grid', placeItems: 'center', background: c.color, color: '#fff' }}>
                <Icon name={c.icon} size={22} />
              </div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16, color: 'var(--text)' }}>{c.label}</div>
            </button>
          ))}
        </div>
      </section>

      {/* trending */}
      <section>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 14 }}>
          <Icon name="flame" size={22} style={{ color: 'var(--c-coral)' }} />
          <h2 className="t-h2">Trending now</h2>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: isDesktop ? 'repeat(auto-fill, minmax(300px,1fr))' : '1fr', gap: 16 }}>
          {trending.map(q => <QuizCard key={q.id} quiz={q} onOpen={onOpen} locked />)}
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { CatalogScreen, HomeScreen, UnlockBanner, CategoryStrip });
