/* ============================================================
   55 QUIZ — composite components (covers, cards, countdown)
   ============================================================ */
const { useState, useEffect } = React;

/* helper: short play counts */
function fmtPlays(n) {
  if (n >= 1000) return (n / 1000).toFixed(n >= 10000 ? 0 : 1).replace('.0', '') + 'k';
  return '' + n;
}

/* ---------- QuizCover: color-coded illustrated placeholder ---------- */
function QuizCover({ quiz, h = 150, big }) {
  const cat = catById(quiz.cat);
  const hue = quiz.hue || cat.color;
  return (
    <div className="grain" style={{
      position: 'relative', height: h, borderRadius: 'calc(var(--r-md) * var(--tw-radius-scale))',
      overflow: 'hidden', flexShrink: 0,
      background: `radial-gradient(120% 120% at 18% 12%, color-mix(in oklab, ${hue} 92%, white 8%), color-mix(in oklab, ${hue} 64%, black 18%))`,
    }}>
      {/* concentric arcs motif */}
      <svg viewBox="0 0 200 150" preserveAspectRatio="xMidYMid slice" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: .5 }}>
        <g fill="none" stroke="rgba(255,255,255,.5)" strokeWidth="1.5">
          <circle cx="168" cy="20" r="20" /><circle cx="168" cy="20" r="34" /><circle cx="168" cy="20" r="50" />
        </g>
        <g fill="rgba(0,0,0,.07)">
          <circle cx="26" cy="128" r="46" />
        </g>
      </svg>
      {/* big category glyph */}
      <div style={{ position: 'absolute', right: -8, bottom: -14, color: 'rgba(255,255,255,.9)', transform: 'rotate(-8deg)' }}>
        <Icon name={cat.icon} size={big ? 96 : 74} stroke={1.4} />
      </div>
      {/* top row: category tag + lock/premium */}
      <div style={{ position: 'absolute', top: 12, left: 12, right: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
        <span className="t-over" style={{
          display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 10px', borderRadius: 'var(--r-pill)',
          background: 'rgba(0,0,0,.22)', color: '#fff', backdropFilter: 'blur(4px)', letterSpacing: '.1em',
        }}>
          <Icon name={cat.icon} size={13} /> {cat.label}
        </span>
        {quiz.premium && (
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '6px 10px', borderRadius: 'var(--r-pill)', background: 'var(--lime)', color: 'var(--lime-ink)', fontWeight: 700, fontSize: 12 }}>
            <Icon name="crown" size={13} fill="var(--lime-ink)" stroke={0} /> Premium
          </span>
        )}
      </div>
      {/* number of questions, bottom-left, big editorial */}
      {big && (
        <div style={{ position: 'absolute', left: 16, bottom: 12, color: '#fff' }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 52, lineHeight: .9, letterSpacing: '-.03em' }} className="tnum">{quiz.q}</div>
          <div className="t-over" style={{ opacity: .9 }}>questions</div>
        </div>
      )}
    </div>
  );
}

/* ---------- meta row: questions / rounds / time / difficulty ---------- */
function MetaRow({ quiz, compact }) {
  const dots = DIFF[quiz.diff];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: compact ? 12 : 16, flexWrap: 'wrap', color: 'var(--text-2)', fontSize: 13, fontWeight: 600 }}>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }} className="tnum"><Icon name="list-checks" size={15} />{quiz.q}</span>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }} className="tnum"><Icon name="layers" size={15} />{quiz.rounds} rounds</span>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }} className="tnum"><Icon name="clock" size={15} />{quiz.mins} min</span>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, textTransform: 'capitalize' }}>
        <span style={{ display: 'inline-flex', gap: 2 }}>
          {[1, 2, 3].map(i => <span key={i} style={{ width: 5, height: 5, borderRadius: 99, background: i <= dots ? 'var(--text)' : 'var(--border-2)' }} />)}
        </span>
        {quiz.diff}
      </span>
    </div>
  );
}

/* ---------- QuizCard (catalog grid) ---------- */
function QuizCard({ quiz, onOpen, locked }) {
  const [hover, setHover] = useState(false);
  const isLocked = locked && !quiz.free;
  return (
    <div onClick={() => onOpen(quiz)} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        background: 'var(--surface)', border: '1px solid var(--border)',
        borderRadius: 'calc(var(--r-lg) * var(--tw-radius-scale))', padding: 12, cursor: 'pointer',
        boxShadow: hover ? 'var(--shadow-md)' : 'var(--shadow-sm)',
        transform: hover ? 'translateY(-3px)' : 'none', transition: 'all 200ms var(--ease)',
        display: 'flex', flexDirection: 'column', gap: 12,
      }}>
      <div style={{ position: 'relative' }}>
        <QuizCover quiz={quiz} h={148} />
        <div style={{ position: 'absolute', left: 10, bottom: 10, display: 'flex', gap: 6 }}>
          {quiz.free
            ? <span style={{ padding: '5px 11px', borderRadius: 'var(--r-pill)', background: 'var(--lime)', color: 'var(--lime-ink)', fontWeight: 700, fontSize: 12 }}>Free</span>
            : isLocked
              ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '5px 11px', borderRadius: 'var(--r-pill)', background: 'rgba(0,0,0,.34)', color: '#fff', fontWeight: 700, fontSize: 12, backdropFilter: 'blur(4px)' }}><Icon name="lock" size={12} />Locked</span>
              : null}
        </div>
      </div>
      <div style={{ padding: '0 4px 4px', display: 'flex', flexDirection: 'column', gap: 9 }}>
        <h3 className="t-h3" style={{ margin: 0 }}>{quiz.title}</h3>
        <p className="t-sm" style={{ margin: 0, color: 'var(--text-2)', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{quiz.blurb}</p>
        <MetaRow quiz={quiz} compact />
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 2 }}>
          <Stars value={quiz.rating} />
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, color: 'var(--text-3)', fontSize: 12.5, fontWeight: 600 }} className="tnum">
            <Icon name="users" size={14} />{fmtPlays(quiz.plays)} plays
          </span>
        </div>
      </div>
    </div>
  );
}

/* ---------- QuizRow (compact list item) ---------- */
function QuizRow({ quiz, onOpen, index }) {
  const cat = catById(quiz.cat);
  const [hover, setHover] = useState(false);
  return (
    <div onClick={() => onOpen(quiz)} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        display: 'flex', alignItems: 'center', gap: 14, padding: 10, cursor: 'pointer',
        background: hover ? 'var(--surface-2)' : 'transparent', borderRadius: 'var(--r-md)',
        transition: 'background 150ms var(--ease)',
      }}>
      {index != null && <span className="t-mono tnum" style={{ width: 22, textAlign: 'center', color: 'var(--text-3)', fontWeight: 700, fontSize: 14 }}>{String(index).padStart(2, '0')}</span>}
      <div style={{ width: 56, height: 56, flexShrink: 0 }}><QuizCover quiz={quiz} h={56} /></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="t-label" style={{ fontWeight: 700, fontSize: 15, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{quiz.title}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'var(--text-2)', fontSize: 12.5, marginTop: 3 }}>
          <span style={{ color: cat.color, fontWeight: 700 }}>{cat.label}</span>
          <span className="tnum">{quiz.q} Q · {quiz.mins} min</span>
        </div>
      </div>
      {quiz.free
        ? <span style={{ padding: '4px 10px', borderRadius: 'var(--r-pill)', background: 'color-mix(in oklab, var(--lime) 30%, transparent)', color: 'var(--text)', fontWeight: 700, fontSize: 12 }}>Free</span>
        : <Icon name="lock" size={15} style={{ color: 'var(--text-3)' }} />}
      <Icon name="chevron-right" size={18} style={{ color: 'var(--text-3)' }} />
    </div>
  );
}

/* ---------- Countdown55: the signature unlock ring ---------- */
function Countdown55({ onUnlock, onTick, compact }) {
  const [t, setT] = useState(55);
  useEffect(() => {
    const id = setInterval(() => setT(prev => (prev <= 1 ? 55 : prev - 1)), 1000);
    return () => clearInterval(id);
  }, []);
  useEffect(() => {
    onTick && onTick(t);
    if (t === 55) onUnlock && onUnlock();
  }, [t]);
  const pct = t / 55;
  const R = compact ? 19 : 26;
  const C = 2 * Math.PI * R;
  const sz = compact ? 48 : 64;
  return (
    <div style={{ position: 'relative', width: sz, height: sz, flexShrink: 0 }}>
      <svg width={sz} height={sz} viewBox={`0 0 ${sz} ${sz}`} style={{ transform: 'rotate(-90deg)' }}>
        <circle cx={sz / 2} cy={sz / 2} r={R} fill="none" stroke="var(--border-2)" strokeWidth={compact ? 4 : 5} />
        <circle cx={sz / 2} cy={sz / 2} r={R} fill="none" stroke="var(--lime)" strokeWidth={compact ? 4 : 5}
          strokeLinecap="round" strokeDasharray={C} strokeDashoffset={C * (1 - pct)}
          style={{ transition: 'stroke-dashoffset 1s linear' }} />
      </svg>
      <div className="tnum" style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: compact ? 14 : 18, color: 'var(--text)' }}>
        {t}
      </div>
    </div>
  );
}

/* ---------- Theme toggle pill ---------- */
function ThemeToggle({ theme, onToggle }) {
  return (
    <button onClick={onToggle} aria-label="Toggle theme" style={{
      display: 'inline-flex', alignItems: 'center', gap: 6, padding: 5,
      background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 'var(--r-pill)',
    }}>
      {['light', 'moon'].map((_, i) => {
        const isActive = (i === 0 && theme === 'light') || (i === 1 && theme === 'dark');
        return (
          <span key={i} style={{
            width: 30, height: 30, display: 'grid', placeItems: 'center', borderRadius: 'var(--r-pill)',
            background: isActive ? 'var(--text)' : 'transparent', color: isActive ? 'var(--bg)' : 'var(--text-3)',
            transition: 'all 160ms var(--ease)',
          }}>
            <Icon name={i === 0 ? 'sun' : 'moon'} size={16} />
          </span>
        );
      })}
    </button>
  );
}

Object.assign(window, { QuizCover, MetaRow, QuizCard, QuizRow, Countdown55, ThemeToggle, fmtPlays });
