/* ============================================================
   55 QUIZ — Quiz detail · Play flow · Result
   ============================================================ */
const { useState, useEffect } = React;

/* ---------- Quiz detail / preview ---------- */
function QuizDetail({ quiz, onBack, onPlay, onBuy, isDesktop, subscribed }) {
  const cat = catById(quiz.cat);
  const locked = !quiz.free && !subscribed;
  const rounds = Array.from({ length: quiz.rounds }, (_, i) => i);
  const roundNames = ['Warm-up', 'The deep cut', 'Picture round', 'Speed fire', 'Final flourish', 'Bonus'];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      <button onClick={onBack} style={{ alignSelf: 'flex-start', display: 'inline-flex', alignItems: 'center', gap: 7, background: 'none', border: 'none', color: 'var(--text-2)', fontWeight: 600, fontSize: 14 }}>
        <Icon name="arrow-left" size={17} /> Back to catalog
      </button>

      <div style={{ display: 'grid', gridTemplateColumns: isDesktop ? '1.1fr .9fr' : '1fr', gap: 22, alignItems: 'start' }}>
        <QuizCover quiz={quiz} h={isDesktop ? 300 : 200} big />

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div>
            <span style={{ color: cat.color, fontWeight: 700, fontSize: 14, display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name={cat.icon} size={16} /> {cat.label}</span>
            <h1 className="t-h1" style={{ margin: '8px 0 0', fontSize: isDesktop ? 34 : 28 }}>{quiz.title}</h1>
          </div>
          <p className="t-body" style={{ margin: 0, color: 'var(--text-2)' }}>{quiz.blurb}</p>
          <MetaRow quiz={quiz} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <Stars value={quiz.rating} size={15} />
            <span style={{ color: 'var(--text-3)', fontSize: 13, fontWeight: 600 }} className="tnum"><Icon name="users" size={14} style={{ verticalAlign: -2 }} /> {fmtPlays(quiz.plays)} plays</span>
          </div>

          {locked ? (
            <div style={{ background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 18, display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontWeight: 700 }}><Icon name="lock" size={17} style={{ color: 'var(--text-2)' }} /> Premium quiz</div>
                <div className="tnum" style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 24 }}>$7</div>
              </div>
              <Btn variant="primary" size="lg" full icon="unlock" onClick={() => onBuy(quiz)}>Buy this quiz — $7</Btn>
              <Btn variant="soft" full icon="infinity" onClick={() => onBuy(quiz, true)}>Or get the 55 Pass — all quizzes</Btn>
            </div>
          ) : (
            <Btn variant="primary" size="lg" full icon="play" onClick={() => onPlay(quiz)}>Start quiz — {quiz.mins} min</Btn>
          )}
        </div>
      </div>

      {/* rounds breakdown */}
      <section>
        <h2 className="t-h2" style={{ marginBottom: 12 }}>Inside this quiz</h2>
        <div style={{ display: 'grid', gridTemplateColumns: isDesktop ? 'repeat(auto-fill,minmax(220px,1fr))' : '1fr', gap: 12 }}>
          {rounds.map(i => (
            <div key={i} style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', padding: 16, display: 'flex', gap: 12, alignItems: 'center' }}>
              <span className="tnum" style={{ width: 38, height: 38, flexShrink: 0, display: 'grid', placeItems: 'center', borderRadius: 'var(--r-sm)', background: cat.color, color: '#fff', fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 17 }}>{i + 1}</span>
              <div>
                <div style={{ fontWeight: 700, fontSize: 14.5 }}>{roundNames[i] || `Round ${i + 1}`}</div>
                <div className="t-sm tnum" style={{ color: 'var(--text-2)' }}>{Math.round(quiz.q / quiz.rounds)} questions</div>
              </div>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
}

/* ---------- Play flow ---------- */
function PlayScreen({ quiz, onExit, onFinish, isDesktop }) {
  const qs = SAMPLE_QUESTIONS;
  const [i, setI] = useState(0);
  const [picked, setPicked] = useState(null);
  const [score, setScore] = useState(0);
  const [time, setTime] = useState(55);
  const cat = catById(quiz.cat);
  const cur = qs[i];
  const answered = picked !== null;

  useEffect(() => {
    if (answered) return;
    setTime(55);
    const id = setInterval(() => setTime(t => { if (t <= 1) { clearInterval(id); setPicked(-1); return 0; } return t - 1; }), 1000);
    return () => clearInterval(id);
  }, [i]);

  const pick = (idx) => {
    if (answered) return;
    setPicked(idx);
    if (idx === cur.correct) setScore(s => s + 1);
  };
  const next = () => {
    if (i + 1 >= qs.length) { onFinish({ score: picked === cur.correct ? score : score, total: qs.length }); return; }
    setI(i + 1); setPicked(null);
  };

  const progress = (i + (answered ? 1 : 0)) / qs.length;

  return (
    <div style={{ maxWidth: 680, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 20, minHeight: '70vh' }}>
      {/* top: exit, progress, timer */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <button onClick={onExit} aria-label="Exit" style={{ width: 40, height: 40, borderRadius: 'var(--r-pill)', border: '1px solid var(--border)', background: 'var(--surface)', display: 'grid', placeItems: 'center', color: 'var(--text-2)' }}><Icon name="x" size={18} /></button>
        <div style={{ flex: 1 }}>
          <div style={{ height: 9, borderRadius: 99, background: 'var(--bg-2)', overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${progress * 100}%`, background: cat.color, borderRadius: 99, transition: 'width .4s var(--ease)' }} />
          </div>
        </div>
        <div className="tnum t-mono" style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontWeight: 700, fontSize: 16, color: time <= 10 ? 'var(--c-coral)' : 'var(--text)' }}>
          <Icon name="clock" size={17} /> 0:{String(time).padStart(2, '0')}
        </div>
      </div>

      <div className="tnum t-over" style={{ color: 'var(--text-3)' }}>Question {i + 1} of {qs.length} · {cat.label}</div>

      <h2 className="t-h2" style={{ fontSize: isDesktop ? 28 : 23, lineHeight: 1.15 }}>{cur.q}</h2>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {cur.options.map((opt, idx) => {
          const isCorrect = idx === cur.correct;
          const isPicked = idx === picked;
          let bg = 'var(--surface)', bd = 'var(--border)', fg = 'var(--text)', badge = null;
          if (answered) {
            if (isCorrect) { bg = 'color-mix(in oklab, var(--c-green) 16%, var(--surface))'; bd = 'var(--c-green)'; badge = 'check'; }
            else if (isPicked) { bg = 'color-mix(in oklab, var(--c-coral) 14%, var(--surface))'; bd = 'var(--c-coral)'; badge = 'x'; }
            else { fg = 'var(--text-3)'; }
          }
          return (
            <button key={idx} onClick={() => pick(idx)} disabled={answered} style={{
              display: 'flex', alignItems: 'center', gap: 14, textAlign: 'left', padding: '16px 18px',
              background: bg, border: `2px solid ${bd}`, borderRadius: 'var(--r-md)', color: fg,
              fontSize: 16, fontWeight: 600, cursor: answered ? 'default' : 'pointer',
              transition: 'all 160ms var(--ease)', boxShadow: !answered ? 'var(--shadow-sm)' : 'none',
            }}>
              <span style={{ width: 30, height: 30, flexShrink: 0, borderRadius: 'var(--r-xs)', display: 'grid', placeItems: 'center', background: answered && (isCorrect || isPicked) ? bd : 'var(--bg-2)', color: answered && (isCorrect || isPicked) ? '#fff' : 'var(--text-2)', fontWeight: 700, fontSize: 14 }}>
                {badge ? <Icon name={badge} size={17} /> : String.fromCharCode(65 + idx)}
              </span>
              {opt}
            </button>
          );
        })}
      </div>

      {answered && (
        <div style={{ animation: 'pop-in .3s var(--ease)', display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ display: 'flex', gap: 12, padding: 16, background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)' }}>
            <Icon name="sparkles" size={20} style={{ color: 'var(--brand)', flexShrink: 0, marginTop: 1 }} />
            <p className="t-sm" style={{ margin: 0, color: 'var(--text-2)' }}><strong style={{ color: 'var(--text)' }}>{picked === cur.correct ? 'Nice.' : 'Good try.'}</strong> {cur.fact}</p>
          </div>
          <Btn variant="primary" size="lg" full iconRight="arrow-right" onClick={next}>{i + 1 >= qs.length ? 'See your result' : 'Next question'}</Btn>
        </div>
      )}
    </div>
  );
}

/* ---------- Result ---------- */
function ResultScreen({ quiz, result, onRetry, onCatalog, onOpen, isDesktop }) {
  const pct = Math.round((result.score / result.total) * 100);
  const cat = catById(quiz.cat);
  const tier = pct >= 80 ? { label: 'Quiz master', ic: 'crown', col: 'var(--lime)' } : pct >= 50 ? { label: 'Solid run', ic: 'badge-check', col: 'var(--c-green)' } : { label: 'Keep going', ic: 'flame', col: 'var(--c-coral)' };
  const more = QUIZZES.filter(q => q.cat === quiz.cat && q.id !== quiz.id).slice(0, isDesktop ? 3 : 2);
  const R = 70, C = 2 * Math.PI * R;
  return (
    <div style={{ maxWidth: 680, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 24 }}>
      <div className="grain" style={{ position: 'relative', overflow: 'hidden', textAlign: 'center', padding: isDesktop ? '40px 32px' : '32px 20px', borderRadius: 'var(--r-xl)', background: 'var(--text)', color: 'var(--bg)' }}>
        <span className="t-over" style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '7px 12px', borderRadius: 'var(--r-pill)', background: tier.col, color: 'var(--lime-ink)' }}>
          <Icon name={tier.ic} size={14} fill="var(--lime-ink)" stroke={0} /> {tier.label}
        </span>
        <div style={{ position: 'relative', width: 180, height: 180, margin: '20px auto 6px' }}>
          <svg width="180" height="180" viewBox="0 0 180 180" style={{ transform: 'rotate(-90deg)' }}>
            <circle cx="90" cy="90" r={R} fill="none" stroke="color-mix(in oklab, var(--bg) 22%, transparent)" strokeWidth="14" />
            <circle cx="90" cy="90" r={R} fill="none" stroke="var(--lime)" strokeWidth="14" strokeLinecap="round" strokeDasharray={C} strokeDashoffset={C * (1 - pct / 100)} style={{ transition: 'stroke-dashoffset 1s var(--ease)' }} />
          </svg>
          <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center' }}>
            <div>
              <div className="tnum" style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 48, lineHeight: 1, color: 'var(--bg)' }}>{pct}%</div>
              <div className="t-over tnum" style={{ color: 'color-mix(in oklab, var(--bg) 70%, var(--text))' }}>{result.score} / {result.total}</div>
            </div>
          </div>
        </div>
        <h1 className="t-h2" style={{ color: 'var(--bg)', margin: '0 0 6px' }}>{quiz.title}</h1>
        <p className="t-sm" style={{ margin: 0, color: 'color-mix(in oklab, var(--bg) 72%, var(--text))' }}>You beat the 55-second clock on {result.score} of {result.total}.</p>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'center', marginTop: 22, flexWrap: 'wrap' }}>
          <Btn variant="lime" icon="shuffle" onClick={onRetry}>Play again</Btn>
          <Btn variant="ghost" icon="compass" onClick={onCatalog} style={{ color: 'var(--bg)', borderColor: 'color-mix(in oklab, var(--bg) 40%, transparent)' }}>Back to catalog</Btn>
        </div>
      </div>

      {more.length > 0 && (
        <section>
          <h2 className="t-h3" style={{ marginBottom: 12, display: 'flex', alignItems: 'center', gap: 8 }}><Icon name={cat.icon} size={18} style={{ color: cat.color }} /> More {cat.label.toLowerCase()}</h2>
          <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 8 }}>
            {more.map((q, idx) => <QuizRow key={q.id} quiz={q} onOpen={onOpen} index={idx + 1} />)}
          </div>
        </section>
      )}
    </div>
  );
}

Object.assign(window, { QuizDetail, PlayScreen, ResultScreen });
