/* ============================================================
   55 QUIZ — Generator (create) · Pricing / payment
   ============================================================ */
const { useState } = React;

function calcPrice({ rounds, questions, video, branded, photos }) {
  const p = PLANS.oneTime;
  let total = p.base + rounds * p.perRound + Math.max(0, Math.ceil((questions - 10) / 5)) * 1;
  if (photos) total += 2;
  if (video) total += p.video;
  if (branded) total += p.brand;
  return total;
}

/* ---------- Generator ---------- */
function CreateScreen({ onCheckout, isDesktop }) {
  const [topic, setTopic] = useState('The golden age of arcade games');
  const [questions, setQuestions] = useState(20);
  const [rounds, setRounds] = useState(3);
  const [photos, setPhotos] = useState(true);
  const [video, setVideo] = useState(false);
  const [branded, setBranded] = useState(false);
  const [generating, setGenerating] = useState(false);
  const [generated, setGenerated] = useState(false);

  const price = calcPrice({ rounds, questions, video, branded, photos });

  const generate = () => {
    setGenerating(true); setGenerated(false);
    setTimeout(() => { setGenerating(false); setGenerated(true); }, 1600);
  };

  const Toggle = ({ on, set, icon, title, sub, price }) => (
    <button onClick={() => set(!on)} style={{
      display: 'flex', alignItems: 'center', gap: 14, textAlign: 'left', width: '100%', padding: 16,
      background: on ? 'color-mix(in oklab, var(--brand) 9%, var(--surface))' : 'var(--surface)',
      border: `1.5px solid ${on ? 'var(--brand)' : 'var(--border)'}`, borderRadius: 'var(--r-md)', cursor: 'pointer',
      transition: 'all 150ms var(--ease)',
    }}>
      <span style={{ width: 40, height: 40, flexShrink: 0, borderRadius: 'var(--r-sm)', display: 'grid', placeItems: 'center', background: on ? 'var(--brand)' : 'var(--bg-2)', color: on ? '#fff' : 'var(--text-2)' }}><Icon name={icon} size={20} /></span>
      <span style={{ flex: 1 }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontWeight: 700, fontSize: 15 }}>{title} <span style={{ color: 'var(--text-3)', fontWeight: 600, fontSize: 13 }} className="tnum">+${price}</span></span>
        <span className="t-sm" style={{ color: 'var(--text-2)' }}>{sub}</span>
      </span>
      <span style={{ width: 26, height: 26, flexShrink: 0, borderRadius: 99, border: `2px solid ${on ? 'var(--brand)' : 'var(--border-2)'}`, background: on ? 'var(--brand)' : 'transparent', display: 'grid', placeItems: 'center', color: '#fff' }}>{on && <Icon name="check" size={16} />}</span>
    </button>
  );

  const Stepper = ({ label, value, set, min, max, step = 1, suffix }) => (
    <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', padding: 16, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
      <div>
        <div className="t-over" style={{ color: 'var(--text-3)' }}>{label}</div>
        <div className="tnum" style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 26 }}>{value}<span style={{ fontSize: 14, color: 'var(--text-2)', marginLeft: 4 }}>{suffix}</span></div>
      </div>
      <div style={{ display: 'flex', gap: 8 }}>
        <button onClick={() => set(Math.max(min, value - step))} style={stepBtn}><Icon name="minus" size={18} /></button>
        <button onClick={() => set(Math.min(max, value + step))} style={stepBtn}><Icon name="plus" size={18} /></button>
      </div>
    </div>
  );

  return (
    <div style={{ display: 'grid', gridTemplateColumns: isDesktop ? '1fr 340px' : '1fr', gap: 24, alignItems: 'start' }}>
      {/* left: builder */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
        <div>
          <span className="t-over" style={{ color: 'var(--text-3)' }}>Quiz builder</span>
          <h1 className="t-h1" style={{ margin: '6px 0 0', fontSize: isDesktop ? 36 : 28 }}>Make your own quiz, <span style={{ color: 'var(--brand)' }}>on any topic you like.</span></h1>
        </div>

        {/* topic */}
        <div>
          <label className="t-label" style={{ display: 'block', marginBottom: 8 }}>What’s it about?</label>
          <div style={{ display: 'flex', gap: 10, flexDirection: isDesktop ? 'row' : 'column' }}>
            <input value={topic} onChange={e => setTopic(e.target.value)} placeholder="e.g. 80s sci-fi cinema"
              style={{ flex: 1, padding: '15px 18px', fontSize: 15.5, color: 'var(--text)', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', outline: 'none' }} />
            <Btn variant="primary" icon={generating ? null : 'wand'} onClick={generate} style={{ flexShrink: 0 }}>
              {generating ? <Icon name="settings" size={18} style={{ animation: 'spin 1s linear infinite' }} /> : null}
              {generating ? 'Generating…' : 'Draft with AI'}
            </Btn>
          </div>
          <p className="t-sm" style={{ margin: '8px 2px 0', color: 'var(--text-3)' }}>Our AI quiz-writer drafts questions, answers and fun facts — you edit and approve.</p>
        </div>

        {/* generated preview */}
        {(generating || generated) && (
          <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', overflow: 'hidden' }}>
            <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 8, fontWeight: 700, fontSize: 14 }}>
              <Icon name="sparkles" size={16} style={{ color: 'var(--brand)' }} /> AI draft preview
            </div>
            {generating ? (
              [0, 1, 2].map(n => <div key={n} style={{ padding: 16, borderBottom: n < 2 ? '1px solid var(--border)' : 'none' }}>
                <div style={{ height: 12, width: `${70 - n * 12}%`, borderRadius: 99, background: 'linear-gradient(90deg, var(--bg-2), var(--surface-2), var(--bg-2))', backgroundSize: '200% 100%', animation: 'shimmer 1.2s infinite' }} />
              </div>)
            ) : (
              SAMPLE_QUESTIONS.slice(0, 3).map((q, n) => (
                <div key={n} style={{ padding: 16, borderBottom: n < 2 ? '1px solid var(--border)' : 'none', display: 'flex', gap: 12 }}>
                  <span className="tnum" style={{ color: 'var(--text-3)', fontWeight: 700, fontFamily: 'var(--font-mono)' }}>{String(n + 1).padStart(2, '0')}</span>
                  <div>
                    <div style={{ fontWeight: 600, fontSize: 14.5 }}>{q.q}</div>
                    <div className="t-sm" style={{ color: 'var(--c-green)', marginTop: 4, display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="check" size={14} /> {q.options[q.correct]}</div>
                  </div>
                </div>
              ))
            )}
          </div>
        )}

        {/* config */}
        <div style={{ display: 'grid', gridTemplateColumns: isDesktop ? '1fr 1fr' : '1fr', gap: 12 }}>
          <Stepper label="Questions" value={questions} set={setQuestions} min={10} max={55} step={5} />
          <Stepper label="Rounds" value={rounds} set={setRounds} min={1} max={6} suffix="rounds" />
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <Toggle on={photos} set={setPhotos} icon="palette" title="Picture questions" sub="Add image-based rounds with covers." price={2} />
          <Toggle on={video} set={setVideo} icon="video" title="Video formats" sub="Embed clip questions — great for film & music." price={PLANS.oneTime.video} />
          <Toggle on={branded} set={setBranded} icon="badge-check" title="Your branding" sub="Custom cover, colors and a no-watermark result card." price={PLANS.oneTime.brand} />
        </div>
      </div>

      {/* right: live price / checkout */}
      <div style={{ position: isDesktop ? 'sticky' : 'static', top: 24, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 22, boxShadow: 'var(--shadow-md)', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div className="t-over" style={{ color: 'var(--text-3)' }}>One-time price · your custom quiz</div>
        <div className="tnum" style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 54, lineHeight: 1 }}>${price}</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 9, padding: '14px 0', borderTop: '1px solid var(--border)', borderBottom: '1px solid var(--border)' }}>
          {[['Base quiz · 10 questions', `$${PLANS.oneTime.base}`],
            [`${questions} questions`, questions > 10 ? `+$${Math.ceil((questions - 10) / 5)}` : 'incl.'],
            [`${rounds} rounds`, `+$${rounds * PLANS.oneTime.perRound}`],
            ...(photos ? [['Picture questions', '+$2']] : []),
            ...(video ? [['Video formats', `+$${PLANS.oneTime.video}`]] : []),
            ...(branded ? [['Your branding', `+$${PLANS.oneTime.brand}`]] : [])].map(([l, v], idx) => (
            <div key={idx} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5, color: 'var(--text-2)' }} className="tnum"><span>{l}</span><span style={{ fontWeight: 600, color: 'var(--text)' }}>{v}</span></div>
          ))}
        </div>
        <Btn variant="primary" size="lg" full icon="sparkles" onClick={() => onCheckout({ topic, questions, rounds, video, branded, photos, price })}>Create my quiz — ${price}</Btn>
        <p className="t-sm" style={{ margin: 0, color: 'var(--text-3)', textAlign: 'center' }}>Pay once. Play it as often as you like and share with friends.</p>
      </div>
    </div>
  );
}

const stepBtn = { width: 40, height: 40, borderRadius: 'var(--r-sm)', border: '1px solid var(--border)', background: 'var(--surface-2)', color: 'var(--text)', display: 'grid', placeItems: 'center' };

/* ---------- Pricing / payment ---------- */
function PricingScreen({ quiz, sub, onSubscribe, onBuy, onCreate, isDesktop }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 26 }}>
      <div style={{ textAlign: 'center', maxWidth: 560, margin: '0 auto' }}>
        <span className="t-over" style={{ color: 'var(--text-3)' }}>Plans</span>
        <h1 className="t-h1" style={{ margin: '8px 0 8px', fontSize: isDesktop ? 38 : 30 }}>Play for free, or unlock the lot.</h1>
        <p className="t-body" style={{ margin: 0, color: 'var(--text-2)' }}>A random quiz unlocks every 55 seconds for everyone. Want them all, now? Get the 55 Pass.</p>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: isDesktop ? 'repeat(3,1fr)' : '1fr', gap: 16, alignItems: 'stretch' }}>
        {/* Free */}
        <PlanCard title="Free spin" price="$0" period="forever" tone="soft"
          features={[['shuffle', 'One random quiz unlocks every 55s'], ['list-checks', 'All free-tagged quizzes'], ['users', 'Public leaderboards']]}
          cta={<Btn variant="soft" full>Current plan</Btn>} />

        {/* 55 Pass (featured) */}
        <PlanCard title="55 Pass" price="$6" period="/ month" tone="brand" badge="Most popular"
          features={[['infinity', 'Every quiz in the catalog, unlocked'], ['bolt', 'No 55-second wait — ever'], ['crown', 'Premium & video quizzes included'], ['flag', 'Early access to new drops']]}
          cta={<Btn variant="lime" full icon="infinity" onClick={onSubscribe}>{sub ? 'Subscribed ✓' : 'Get 55 Pass'}</Btn>} />

        {/* Per quiz */}
        <PlanCard title="Single quiz" price="$7" period="one-time" tone="soft"
          features={[['unlock', 'Buy any premium quiz outright'], ['video', 'Keep video & picture rounds'], ['bookmark', 'Replay forever, no subscription']]}
          cta={<Btn variant="primary" full icon="unlock" onClick={() => onBuy(quiz || QUIZZES[1])}>Buy a quiz</Btn>} />
      </div>

      {/* create-your-own callout */}
      <div className="grain" style={{ position: 'relative', overflow: 'hidden', borderRadius: 'var(--r-xl)', background: 'var(--brand)', color: '#fff', padding: isDesktop ? '30px 34px' : '24px', display: 'flex', flexDirection: isDesktop ? 'row' : 'column', gap: 20, alignItems: isDesktop ? 'center' : 'flex-start', justifyContent: 'space-between' }}>
        <div>
          <h2 className="t-h2" style={{ color: '#fff', margin: '0 0 6px' }}>Want a quiz on your own topic?</h2>
          <p className="t-sm" style={{ margin: 0, color: 'rgba(255,255,255,.85)', maxWidth: 480 }}>Build a custom quiz with our AI writer and play it whenever you like. Pay once — add extra rounds, picture and video questions however you want.</p>
        </div>
        <Btn variant="lime" size="lg" icon="wand" style={{ flexShrink: 0 }} onClick={onCreate}>Open the builder</Btn>
      </div>
    </div>
  );
}

function PlanCard({ title, price, period, features, cta, tone, badge }) {
  const brand = tone === 'brand';
  return (
    <div style={{
      position: 'relative', display: 'flex', flexDirection: 'column', gap: 16, padding: 24,
      background: brand ? 'var(--text)' : 'var(--surface)', color: brand ? 'var(--bg)' : 'var(--text)',
      border: brand ? '1px solid transparent' : '1px solid var(--border)',
      borderRadius: 'var(--r-xl)', boxShadow: brand ? 'var(--shadow-lg)' : 'var(--shadow-sm)',
      transform: brand ? 'scale(1.0)' : 'none',
    }}>
      {badge && <span style={{ position: 'absolute', top: 18, right: 18, padding: '5px 11px', borderRadius: 'var(--r-pill)', background: 'var(--lime)', color: 'var(--lime-ink)', fontWeight: 700, fontSize: 12 }}>{badge}</span>}
      <div>
        <div className="t-over" style={{ color: brand ? 'color-mix(in oklab, var(--bg) 65%, var(--text))' : 'var(--text-3)' }}>{title}</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 8 }}>
          <span className="tnum" style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 44, lineHeight: 1 }}>{price}</span>
          <span className="t-sm" style={{ color: brand ? 'color-mix(in oklab, var(--bg) 70%, var(--text))' : 'var(--text-2)' }}>{period}</span>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 11, flex: 1 }}>
        {features.map(([ic, t], idx) => (
          <div key={idx} style={{ display: 'flex', alignItems: 'center', gap: 11, fontSize: 14 }}>
            <span style={{ width: 26, height: 26, flexShrink: 0, borderRadius: 99, display: 'grid', placeItems: 'center', background: brand ? 'var(--lime)' : 'color-mix(in oklab, var(--brand) 14%, transparent)', color: brand ? 'var(--lime-ink)' : 'var(--brand)' }}><Icon name={ic} size={15} /></span>
            <span style={{ color: brand ? 'var(--bg)' : 'var(--text)' }}>{t}</span>
          </div>
        ))}
      </div>
      {cta}
    </div>
  );
}

Object.assign(window, { CreateScreen, PricingScreen, calcPrice });
