// Sports IQ Mini-Game — email gate, 30s timer, 10 randomized questions

const STORAGE_KEY = 'sportscred_email';
const QUIZ_LENGTH = 10;

const getRandomQuestions = (sportId) => {
  const pool = [...(window.QUIZ_DATA[sportId] || [])];
  for (let i = pool.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [pool[i], pool[j]] = [pool[j], pool[i]];
  }
  return pool.slice(0, Math.min(QUIZ_LENGTH, pool.length));
};

const IQGame = ({ accent }) => {
  // phases: 'gate' | 'ready' | 'play' | 'done'
  const [phase, setPhase] = React.useState('gate');
  const [sport, setSport] = React.useState('football');
  const [email, setEmail] = React.useState('');
  const [emailLocked, setEmailLocked] = React.useState(false);
  const [questionIdx, setQuestionIdx] = React.useState(0);
  const [answers, setAnswers] = React.useState([]);
  const [questions, setQuestions] = React.useState(() => getRandomQuestions('football'));
  const [picked, setPicked] = React.useState(null); // index briefly highlighted
  const [timeLeft, setTimeLeft] = React.useState(60);
  const [expanded, setExpanded] = React.useState(false); // quiz collapsed by default

  // Restore email if previously entered
  React.useEffect(() => {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (saved) { setEmail(saved); setEmailLocked(true); }
    } catch (e) {}
  }, []);

  const currentQ = questions[questionIdx];
  const score = answers.filter(a => a.correct).length;
  const quizTotal = questions.length || QUIZ_LENGTH;

  // Timer
  React.useEffect(() => {
    if (phase !== 'play') return;
    if (timeLeft <= 0) { setPhase('done'); return; }
    const t = setTimeout(() => setTimeLeft(s => s - 1), 1000);
    return () => clearTimeout(t);
  }, [phase, timeLeft]);

  const submitEmail = async (e) => {
    e.preventDefault();
    if (!email || !email.includes('@')) return;
    try { localStorage.setItem(STORAGE_KEY, email); } catch (err) {}
    await window.saveWaitlistLead?.({ email, source: 'quiz_gate', sport: sportLabel });
    setEmailLocked(true);
    setPhase('ready');
  };

  const startGame = () => {
    setQuestions(getRandomQuestions(sport));
    setQuestionIdx(0);
    setAnswers([]);
    setPicked(null);
    setTimeLeft(60);
    setPhase('play');
  };

  const switchSport = (id) => {
    if (id === sport) return;
    setSport(id);
    if (phase === 'play') {
      setQuestions(getRandomQuestions(id));
      setQuestionIdx(0);
      setAnswers([]);
      setPicked(null);
      setTimeLeft(60);
    }
  };

  const pick = (optionIdx) => {
    if (picked !== null) return;
    const correct = optionIdx === currentQ.correct;
    setPicked(optionIdx);
    setTimeout(() => {
      const newAnswers = [...answers, { correct, picked: optionIdx }];
      setAnswers(newAnswers);
      setPicked(null);
      if (questionIdx + 1 >= quizTotal) {
        setPhase('done');
      } else {
        setQuestionIdx(prev => prev + 1);
      }
    }, 450);
  };

  const reset = () => {
    setPhase('ready');
    setQuestionIdx(0);
    setAnswers([]);
    setPicked(null);
    setTimeLeft(60);
  };

  const verdict = (s, total) => {
    const pct = total > 0 ? s / total : 0;
    if (pct >= 0.9) return { tag: "Certified Cred — Elite", note: "You watch the tape. SportsCred was built for you.", grade: 'A+' };
    if (pct >= 0.75) return { tag: "Sharp Take", note: "You see the game. Real fan energy.", grade: 'A' };
    if (pct >= 0.5) return { tag: "Solid Fan", note: "Real fans go deeper. We'll get you there.", grade: 'B' };
    if (pct >= 0.3) return { tag: "Casual Energy", note: "There's room to grow your cred. Start now.", grade: 'C' };
    return { tag: "Box Score Reader", note: "No shame — but the tape is calling.", grade: 'D' };
  };

  const sportLabel = window.SPORTS.find(x => x.id === sport)?.label || '';
  const totalAnswered = answers.length;

  return (
    <section id="game" className="sc-game-section" data-screen-label="01 Hero" style={{
      padding: '64px 56px 100px',
      borderBottom: '1px solid rgba(255,255,255,0.06)',
      background: '#0A0A0A',
      position: 'relative'
    }}>
      <BlueprintBg />
      <div style={{ maxWidth: 1240, margin: '0 auto', position: 'relative', zIndex: 1 }}>
        <div style={{ textAlign: 'center', marginBottom: 56, maxWidth: 1040, marginLeft: 'auto', marginRight: 'auto' }}>
          <div className="sc-hero-kicker" style={{
            fontFamily: 'var(--mono)', fontSize: 12, letterSpacing: '0.28em',
            color: accent, textTransform: 'uppercase', marginBottom: 24
          }}>Every fan has a score.</div>
          <h1 className="sc-hero-heading" style={{
            fontFamily: 'var(--display)',
            fontSize: 'clamp(44px, 7.4vw, 122px)',
            lineHeight: 0.92,
            letterSpacing: '0.005em',
            color: '#fff',
            margin: '0 0 22px',
            textTransform: 'uppercase',
            fontWeight: 400
          }}>
            Opinions<span className="sc-mobile-break"></span> <span style={{ whiteSpace: 'nowrap' }}>are free.</span><br/><span style={{ color: accent, fontStyle: 'italic' }}>Credibility<span className="sc-mobile-break"></span> isn't.</span>
          </h1>
          <p className="sc-hero-copy" style={{
            fontFamily: 'var(--body)',
            fontSize: 'clamp(13px, 1.4vw, 19px)',
            color: 'var(--muted)',
            maxWidth: 'none',
            margin: '0 auto',
            lineHeight: 1.5,
            whiteSpace: 'normal'
          }}>
            Anyone can have a take. <br className="sc-mobile-break" />SportsCred is where you earn it.
          </p>
        </div>

        {!expanded && (
          <div style={{ maxWidth: 820, margin: '0 auto' }}>
            <QuizLauncher accent={accent} onStart={() => setExpanded(true)} />
          </div>
        )}

        {expanded && (
        <div className="q-fade">
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 18 }}>
            <button onClick={() => setExpanded(false)} style={{
              background: 'transparent',
              border: '1px solid rgba(255,255,255,0.14)',
              color: 'var(--muted)',
              fontFamily: 'var(--mono)',
              fontSize: 11,
              letterSpacing: '0.16em',
              textTransform: 'uppercase',
              padding: '8px 16px',
              cursor: 'pointer'
            }}>↑ Hide Quiz</button>
          </div>
        {/* App card */}
        <div className="sc-quiz-card" style={{
          border: '1px solid rgba(255,255,255,0.08)',
          background: '#0E0E0E',
          boxShadow: '0 40px 80px -40px rgba(0,0,0,0.8)',
          position: 'relative',
          overflow: 'hidden'
        }}>
          {/* tabs */}
          <div style={{ position: 'relative', borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
            <div className="sc-quiz-tabs" style={{
              display: 'flex',
              overflowX: 'auto',
              overflowY: 'hidden',
              WebkitOverflowScrolling: 'touch'
            }}>
              {window.SPORTS.map((s) => {
                const active = sport === s.id;
                return (
                  <button
                    key={s.id}
                    onClick={() => switchSport(s.id)}
                    style={{
                      flex: '1 0 auto',
                      background: 'transparent',
                      border: 'none',
                      borderBottom: active ? `2px solid ${accent}` : '2px solid transparent',
                      color: active ? '#fff' : 'var(--muted)',
                      fontFamily: 'var(--display)',
                      fontSize: 18,
                      letterSpacing: '0.06em',
                      padding: '22px 12px',
                      cursor: 'pointer',
                      transition: 'all 200ms',
                      textTransform: 'uppercase',
                      fontWeight: 400,
                      minWidth: 100
                    }}
                  >
                    {s.label}
                  </button>
                );
              })}
            </div>
            <div className="sc-quiz-tabs-more" aria-hidden style={{
              display: 'none',
              position: 'absolute',
              top: 0,
              right: 0,
              bottom: 0,
              width: 54,
              alignItems: 'center',
              justifyContent: 'flex-end',
              paddingRight: 10,
              pointerEvents: 'none',
              background: 'linear-gradient(90deg, rgba(14,14,14,0), #0E0E0E 62%)',
              color: accent,
              fontFamily: 'var(--mono)',
              fontSize: 18
            }}>›</div>
            <div className="sc-quiz-tabs-more" aria-hidden style={{
              display: 'none',
              position: 'absolute',
              right: 13,
              bottom: 5,
              pointerEvents: 'none',
              color: 'rgba(255,255,255,0.42)',
              fontFamily: 'var(--mono)',
              fontSize: 8,
              letterSpacing: '0.12em',
              textTransform: 'uppercase'
            }}>Swipe</div>
          </div>

          {/* HUD: timer + progress */}
          <div className="sc-quiz-hud" style={{
            display: 'flex',
            alignItems: 'center',
            gap: 20,
            padding: '20px 32px 0'
          }}>
            <Timer timeLeft={timeLeft} accent={accent} active={phase === 'play'} />
            <div className="sc-quiz-progress" style={{ flex: 1, display: 'flex', gap: 4 }}>
              {Array.from({ length: quizTotal }).map((_, i) => {
                let bg = 'rgba(255,255,255,0.06)';
                if (phase === 'done') bg = accent;
                else if (answers[i]) bg = answers[i].correct ? accent : '#7A2A2A';
                else if (i === questionIdx && phase === 'play') bg = 'rgba(255,255,255,0.3)';
                return <div key={i} style={{
                  flex: 1, height: 2, background: bg, transition: 'background 250ms'
                }}></div>;
              })}
            </div>
            <span style={{
              fontFamily: 'var(--mono)',
              fontSize: 11,
              letterSpacing: '0.18em',
              color: 'var(--muted)'
            }}>
              {phase === 'play' ? `${Math.min(questionIdx + 1, quizTotal)}/${quizTotal}` : phase === 'done' ? 'COMPLETE' : `—/${quizTotal}`}
            </span>
          </div>

          {/* Body */}
          <div className="sc-quiz-card-body" style={{ padding: '36px 32px 44px', minHeight: 460 }}>
            {phase === 'gate' && (
              <EmailGate
                accent={accent}
                email={email}
                setEmail={setEmail}
                onSubmit={submitEmail}
              />
            )}

            {phase === 'ready' && (
              <ReadyScreen
                accent={accent}
                sport={sportLabel}
                email={email}
                onStart={startGame}
                onChangeEmail={() => { setEmailLocked(false); setPhase('gate'); }}
              />
            )}

            {phase === 'play' && currentQ && (
              <QuestionView
                accent={accent}
                question={currentQ}
                idx={questionIdx}
                sport={sportLabel}
                picked={picked}
                onPick={pick}
              />
            )}

            {phase === 'done' && (
              <ResultsView
                accent={accent}
                score={score}
                quizTotal={quizTotal}
                totalAnswered={totalAnswered}
                verdict={verdict(score, quizTotal)}
                sport={sportLabel}
                onReset={reset}
                email={email}
              />
            )}
          </div>

          {/* footer */}
          <div className="sc-quiz-footer" style={{
            borderTop: '1px solid rgba(255,255,255,0.06)',
            padding: '14px 32px',
            display: 'flex',
            justifyContent: 'space-between',
            fontFamily: 'var(--mono)',
            fontSize: 10,
            letterSpacing: '0.18em',
            color: '#444',
            textTransform: 'uppercase'
          }}>
            <span>SC · A.C.S. PROTOCOL</span>
            <span>Live Demo · v0.1</span>
          </div>
        </div>

        </div>
        )}
      </div>
    </section>
  );
};

const QuizLauncher = ({ accent, onStart }) => (
  <div className="sc-quiz-launcher" style={{
    border: '1px solid rgba(255,255,255,0.1)',
    background: 'linear-gradient(180deg, #0E0E0E, #070707)',
    padding: '52px 56px 48px',
    position: 'relative',
    overflow: 'hidden',
    textAlign: 'center'
  }}>
    <CredGradient height={3} style={{ position: 'absolute', top: 0, left: 0, right: 0 }} />

    <div className="sc-quiz-kicker" style={{
      fontFamily: 'var(--mono)',
      fontSize: 12,
      letterSpacing: '0.22em',
      color: accent,
      textTransform: 'uppercase'
    }}>Sports IQ Test · 60 Seconds</div>

    <h3 style={{
      fontFamily: 'var(--display)',
      fontSize: 'clamp(34px, 4.4vw, 60px)',
      color: '#fff',
      margin: '22px 0 16px',
      fontWeight: 400,
      lineHeight: 0.96,
      letterSpacing: '0.01em',
      textTransform: 'uppercase'
    }}>Get your<span className="sc-mobile-break"></span> SportsCred<span className="sc-mobile-break"></span> Score</h3>

    <p style={{
      fontFamily: 'var(--body)',
      fontSize: 16,
      color: 'var(--muted)',
      margin: '0 auto 32px',
      lineHeight: 1.55,
      maxWidth: 480
    }}>Ten questions. Sixty seconds. Prove you know ball.</p>

    <button className="sc-cta-button" onClick={onStart} style={{
      background: accent,
      color: '#0A0A0A',
      border: 'none',
      padding: '18px 44px',
      fontFamily: 'var(--display)',
      fontSize: 24,
      letterSpacing: '0.06em',
      cursor: 'pointer',
      textTransform: 'uppercase',
      display: 'inline-flex',
      alignItems: 'center',
      gap: 10,
      whiteSpace: 'nowrap',
      transition: 'transform 150ms, filter 150ms'
    }}
    onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.filter = 'brightness(1.08)'; }}
    onMouseLeave={(e) => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.filter = 'brightness(1)'; }}
    >
      Take the Quiz →
    </button>

  </div>
);

const Timer = ({ timeLeft, accent, active }) => {
  const r = 18;
  const c = 2 * Math.PI * r;
  const pct = Math.max(0, timeLeft) / 60;
  const dash = c * pct;
  const danger = timeLeft <= 15;
  const color = danger ? '#E53E3E' : accent;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <svg width="44" height="44" viewBox="0 0 44 44" style={{ flexShrink: 0 }}>
        <circle cx="22" cy="22" r={r} fill="none" stroke="rgba(255,255,255,0.08)" strokeWidth="2.5" />
        <circle
          cx="22" cy="22" r={r}
          fill="none"
          stroke={active ? color : 'rgba(255,255,255,0.18)'}
          strokeWidth="2.5"
          strokeDasharray={`${dash} ${c}`}
          strokeLinecap="round"
          transform="rotate(-90 22 22)"
          style={{ transition: 'stroke-dasharray 1s linear, stroke 200ms' }}
        />
        <text x="22" y="22" textAnchor="middle" dominantBaseline="central"
          fontFamily="var(--mono)" fontSize="13" fontWeight="500"
          fill={active ? '#fff' : '#555'}>
          {active ? timeLeft : '60'}
        </text>
      </svg>
      <div style={{
        fontFamily: 'var(--mono)',
        fontSize: 10,
        letterSpacing: '0.18em',
        color: 'var(--muted)',
        textTransform: 'uppercase',
        lineHeight: 1.3
      }}>
        Time<br/>Left
      </div>
    </div>
  );
};

const EmailGate = ({ accent, email, setEmail, onSubmit }) => (
  <div className="q-fade" style={{ maxWidth: 560, margin: '40px auto', textAlign: 'center' }}>
    <div style={{
      fontFamily: 'var(--mono)',
      fontSize: 11,
      letterSpacing: '0.22em',
      color: accent,
      marginBottom: 14,
      textTransform: 'uppercase'
    }}>Step 01 — Identify Yourself</div>
    <h3 style={{
      fontFamily: 'var(--display)',
      fontSize: 'clamp(28px, 3.5vw, 44px)',
      color: '#fff',
      margin: '0 0 14px',
      fontWeight: 400,
      letterSpacing: '0.01em',
      lineHeight: 1.05
    }}>
      Drop your email to take the test.
    </h3>
    <p style={{
      fontFamily: 'var(--body)',
      fontSize: 14,
      color: 'var(--muted)',
      margin: '0 0 28px',
      lineHeight: 1.5
    }}>
      Your IQ score gets tied to your email so you can track and share it. You don't have to join the waitlist —
      but if you score high, we'll know.
    </p>
    <form className="sc-email-form" onSubmit={onSubmit} style={{
      display: 'flex',
      border: '1px solid rgba(255,255,255,0.14)',
      background: 'rgba(255,255,255,0.02)',
      transition: 'border-color 200ms'
    }}
    onFocusCapture={(e) => e.currentTarget.style.borderColor = accent}
    onBlurCapture={(e) => e.currentTarget.style.borderColor = 'rgba(255,255,255,0.14)'}
    >
      <input
        type="email"
        required
        autoFocus
        placeholder="you@email.com"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        style={{
          flex: 1,
          background: 'transparent',
          border: 'none',
          outline: 'none',
          color: '#fff',
          fontFamily: 'var(--body)',
          fontSize: 15,
          padding: '18px 22px'
        }}
      />
      <button className="sc-email-submit" type="submit" style={{
        background: accent,
        color: '#0A0A0A',
        border: 'none',
        padding: '0 26px',
        fontFamily: 'var(--display)',
        fontSize: 16,
        letterSpacing: '0.06em',
        cursor: 'pointer'
      }}>
        Continue →
      </button>
    </form>
    <p style={{
      marginTop: 16,
      fontFamily: 'var(--mono)',
      fontSize: 10,
      letterSpacing: '0.16em',
      color: '#555',
      textTransform: 'uppercase'
    }}>
      No spam. Required for share + leaderboard.
    </p>
  </div>
);

const ReadyScreen = ({ accent, sport, email, onStart, onChangeEmail }) => (
  <div className="q-fade" style={{ textAlign: 'center', padding: '40px 0' }}>
    <div style={{
      fontFamily: 'var(--mono)',
      fontSize: 11,
      letterSpacing: '0.22em',
      color: accent,
      marginBottom: 18,
      textTransform: 'uppercase'
    }}>Step 02 — Pick a Sport, Press Start</div>
    <h3 style={{
      fontFamily: 'var(--display)',
      fontSize: 'clamp(40px, 6vw, 80px)',
      color: '#fff',
      margin: '0 0 20px',
      fontWeight: 400,
      lineHeight: 1
    }}>
      Ready, <span style={{ color: accent, fontStyle: 'italic' }}>{sport}</span>?
    </h3>
    <div style={{
      display: 'flex',
      gap: 36,
      justifyContent: 'center',
      flexWrap: 'wrap',
      margin: '32px 0',
      fontFamily: 'var(--mono)',
      fontSize: 12,
      letterSpacing: '0.16em',
      textTransform: 'uppercase',
      color: 'var(--muted)'
    }}>
      <div><span style={{ color: '#fff', fontSize: 24, fontFamily: 'var(--display)', display: 'block' }}>10</span>Questions</div>
      <div><span style={{ color: '#fff', fontSize: 24, fontFamily: 'var(--display)', display: 'block' }}>60s</span>On the clock</div>
      <div><span style={{ color: '#fff', fontSize: 24, fontFamily: 'var(--display)', display: 'block' }}>4</span>Choices each</div>
    </div>
    <button
      className="sc-cta-button"
      onClick={onStart}
      style={{
        background: accent,
        color: '#0A0A0A',
        border: 'none',
        padding: '20px 48px',
        fontFamily: 'var(--display)',
        fontSize: 22,
        letterSpacing: '0.1em',
        cursor: 'pointer',
        boxShadow: `0 0 40px -10px ${accent}`,
        transition: 'transform 150ms'
      }}
      onMouseEnter={(e) => e.currentTarget.style.transform = 'scale(1.02)'}
      onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}
    >
      ▶ Start the Clock
    </button>
    <div className="sc-playing-as" style={{
      marginTop: 28,
      fontFamily: 'var(--mono)',
      fontSize: 11,
      letterSpacing: '0.14em',
      color: '#555',
      textTransform: 'uppercase'
    }}>
      Playing as <span style={{ color: accent }}>{email}</span> · <button onClick={onChangeEmail} style={{
        background: 'none', border: 'none', color: 'var(--muted)', cursor: 'pointer',
        fontFamily: 'inherit', fontSize: 'inherit', letterSpacing: 'inherit', textTransform: 'inherit',
        textDecoration: 'underline', padding: 0
      }}>change</button>
    </div>
  </div>
);

const QuestionView = ({ accent, question, idx, sport, picked, onPick }) => (
  <div key={idx} className="q-fade">
    <div style={{
      fontFamily: 'var(--mono)',
      fontSize: 11,
      letterSpacing: '0.2em',
      color: 'var(--muted)',
      marginBottom: 14,
      textTransform: 'uppercase'
    }}>
      {sport} · Question {idx + 1}
    </div>
    <h3 style={{
      fontFamily: 'var(--display)',
      fontSize: 'clamp(22px, 2.4vw, 32px)',
      lineHeight: 1.2,
      color: '#fff',
      margin: '0 0 28px',
      fontWeight: 400,
      letterSpacing: '0.005em',
      maxWidth: 760
    }}>
      {question.q}
    </h3>
    <div className="sc-question-options" style={{
      display: 'grid',
      gridTemplateColumns: 'repeat(2, 1fr)',
      gap: 12
    }}>
      {question.options.map((opt, i) => {
        let state = 'idle';
        if (picked !== null) {
          if (i === question.correct) state = 'correct';
          else if (i === picked) state = 'wrong';
          else state = 'dimmed';
        }
        const styles = {
          idle: {
            border: '1px solid rgba(255,255,255,0.1)',
            color: '#fff',
            background: 'rgba(255,255,255,0.015)'
          },
          correct: {
            border: `1px solid ${accent}`,
            color: accent,
            background: `${accent}15`,
            boxShadow: `0 0 0 1px ${accent}, 0 0 30px -5px ${accent}80`
          },
          wrong: {
            border: '1px solid #B84A4A',
            color: '#FF8888',
            background: '#B84A4A15'
          },
          dimmed: {
            border: '1px solid rgba(255,255,255,0.06)',
            color: '#555',
            background: 'transparent'
          }
        }[state];
        return (
          <button
            key={i}
            onClick={() => onPick(i)}
            disabled={picked !== null}
            style={{
              ...styles,
              padding: '18px 22px',
              fontFamily: 'var(--body)',
              fontSize: 14,
              textAlign: 'left',
              cursor: picked !== null ? 'default' : 'pointer',
              transition: 'all 200ms',
              display: 'flex',
              alignItems: 'center',
              gap: 14,
              lineHeight: 1.4
            }}
            onMouseEnter={(e) => {
              if (picked === null) {
                e.currentTarget.style.borderColor = accent;
                e.currentTarget.style.background = `${accent}08`;
              }
            }}
            onMouseLeave={(e) => {
              if (picked === null) {
                e.currentTarget.style.borderColor = 'rgba(255,255,255,0.1)';
                e.currentTarget.style.background = 'rgba(255,255,255,0.015)';
              }
            }}
          >
            <span style={{
              fontFamily: 'var(--mono)',
              fontSize: 11,
              letterSpacing: '0.15em',
              opacity: 0.7,
              minWidth: 18
            }}>{String.fromCharCode(65 + i)}</span>
            <span style={{ flex: 1 }}>{opt}</span>
          </button>
        );
      })}
    </div>
  </div>
);

const ACS_BY_CORRECT = [140, 235, 330, 425, 510, 590, 665, 735, 805, 870, 955];
const ACS_TIERS = [
  { lo: 100, hi: 400,  name: 'Bench', color: '#E5403E' },
  { lo: 400, hi: 700,  name: 'Rookie', color: '#F08A3C' },
  { lo: 700, hi: 800,  name: 'Pro', color: '#10B981' },
  { lo: 800, hi: 1000, name: 'Expert', color: '#D6AF4B' }
];
const ACS_TAGLINE = {
  Bench:  "No shame — but the tape is calling.",
  Rookie: "Real fans go deeper. We'll get you there.",
  Pro:    "You see the game. Real fan energy.",
  Expert: "You watch the tape. SportsCred was built for you."
};

const buildShareUrl = ({ acs, tier, sport }) => {
  const url = new URL(window.location.href);
  url.search = '';
  url.hash = 'game';
  url.searchParams.set('acs', acs);
  url.searchParams.set('tier', tier.name.toLowerCase());
  url.searchParams.set('sport', sport.toLowerCase());
  return url.toString();
};

const createScoreCardFile = ({ acs, tier, sport, score, quizTotal, accent }) => {
  const canvas = document.createElement('canvas');
  const w = 1200;
  const h = 630;
  canvas.width = w;
  canvas.height = h;
  const ctx = canvas.getContext('2d');

  ctx.fillStyle = '#080808';
  ctx.fillRect(0, 0, w, h);

  const grad = ctx.createLinearGradient(0, 0, w, h);
  grad.addColorStop(0, 'rgba(229,64,62,0.22)');
  grad.addColorStop(0.52, 'rgba(201,162,75,0.18)');
  grad.addColorStop(1, 'rgba(25,209,122,0.16)');
  ctx.fillStyle = grad;
  ctx.fillRect(0, 0, w, h);

  ctx.strokeStyle = 'rgba(255,255,255,0.1)';
  ctx.lineWidth = 2;
  ctx.strokeRect(44, 44, w - 88, h - 88);

  const bar = ctx.createLinearGradient(80, 98, w - 80, 98);
  bar.addColorStop(0, '#E5403E');
  bar.addColorStop(0.5, '#E8C547');
  bar.addColorStop(1, '#19D17A');
  ctx.fillStyle = bar;
  ctx.fillRect(80, 94, w - 160, 6);

  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';

  ctx.fillStyle = '#FFFFFF';
  ctx.font = '700 48px Impact, Anton, Arial Black, sans-serif';
  ctx.letterSpacing = '4px';
  ctx.fillText('SPORTSCRED', w / 2, 148);

  ctx.fillStyle = accent;
  ctx.font = '700 170px Impact, Anton, Arial Black, sans-serif';
  ctx.fillText(String(acs), w / 2 - 50, 292);

  ctx.fillStyle = 'rgba(255,255,255,0.38)';
  ctx.font = '700 70px Impact, Anton, Arial Black, sans-serif';
  ctx.fillText('/ 1000', w / 2 + 205, 320);

  ctx.strokeStyle = accent;
  ctx.lineWidth = 3;
  ctx.strokeRect(w / 2 - 150, 386, 300, 78);
  ctx.fillStyle = '#FFFFFF';
  ctx.font = '700 58px Impact, Anton, Arial Black, sans-serif';
  ctx.fillText(tier.name.toUpperCase(), w / 2, 427);

  ctx.fillStyle = 'rgba(255,255,255,0.72)';
  ctx.font = '500 28px Inter, Arial, sans-serif';
  ctx.fillText(`${score} / ${quizTotal} correct · ${sport}`, w / 2, 505);

  ctx.fillStyle = 'rgba(255,255,255,0.48)';
  ctx.font = '500 24px JetBrains Mono, Menlo, monospace';
  ctx.fillText('Take the test at SportsCred', w / 2, 560);

  return new Promise((resolve) => {
    canvas.toBlob((blob) => {
      if (!blob) return resolve(null);
      resolve(new File([blob], 'sportscred-score.png', { type: 'image/png' }));
    }, 'image/png', 0.95);
  });
};

const ResultsView = ({ accent, score, quizTotal = QUIZ_LENGTH, totalAnswered, sport, onReset, email }) => {
  const acs = ACS_BY_CORRECT[Math.max(0, Math.min(10, score))];
  const [waitlistStatus, setWaitlistStatus] = React.useState(() => window.getSportsCredWaitlistEmail?.() ? 'saved' : 'idle');
  const activeIdx = (() => {
    const i = ACS_TIERS.findIndex(t => acs < t.hi);
    return i === -1 ? ACS_TIERS.length - 1 : i;
  })();
  const tier = ACS_TIERS[activeIdx];
  const resultAccent = tier.color || accent;

  React.useEffect(() => {
    window.saveWaitlistLead?.({
      email,
      source: 'quiz_result',
      sport,
      acsScore: acs,
      tier: tier.name,
      quizScore: score,
      quizTotal
    });
  }, [email, sport, acs, tier.name, score, quizTotal]);

  React.useEffect(() => {
    const handleJoined = () => setWaitlistStatus('saved');
    window.addEventListener('sportscred:waitlist-joined', handleJoined);
    return () => window.removeEventListener('sportscred:waitlist-joined', handleJoined);
  }, []);

  const handleJoinWaitlist = async () => {
    if (waitlistStatus === 'saving' || waitlistStatus === 'saved') return;
    setWaitlistStatus('saving');
    const result = await window.saveWaitlistLead?.({
      email,
      source: 'waitlist_form',
      sport,
      acsScore: acs,
      tier: tier.name,
      quizScore: score,
      quizTotal
    });
    setWaitlistStatus(result?.ok === true ? 'saved' : 'error');
  };

  const handleShare = async () => {
    const shareUrl = buildShareUrl({ acs, tier, sport });
    const text = `My SportsCred ACS: ${acs} / 1000 (${tier.name}) — ${sport}. Take the test:`;
    const title = `SportsCred ACS: ${acs} / 1000`;
    const card = await createScoreCardFile({ acs, tier, sport, score, quizTotal, accent: resultAccent });

    try {
      if (card && navigator.canShare?.({ files: [card] })) {
        await navigator.share({ title, text, url: shareUrl, files: [card] });
        window.saveWaitlistLead?.({ email, source: 'score_share', sport, acsScore: acs, tier: tier.name, quizScore: score, quizTotal });
        return;
      }
      if (navigator.share) {
        await navigator.share({ title, text, url: shareUrl });
        window.saveWaitlistLead?.({ email, source: 'score_share', sport, acsScore: acs, tier: tier.name, quizScore: score, quizTotal });
        return;
      }
      await navigator.clipboard?.writeText(`${text} ${shareUrl}`);
      window.saveWaitlistLead?.({ email, source: 'score_share', sport, acsScore: acs, tier: tier.name, quizScore: score, quizTotal });
    } catch (err) {}
  };

  return (
    <div className="q-fade" style={{ textAlign: 'center', padding: '8px 0' }}>
      {/* eyebrow */}
      <div style={{
        fontFamily: 'var(--mono)',
        fontSize: 11,
        letterSpacing: '0.22em',
        color: resultAccent,
        marginBottom: 6,
        textTransform: 'uppercase'
      }}>
        A.C.S. Result · {sport} · <span style={{ color: 'var(--muted)' }}>{email}</span>
      </div>

      {/* hero number — the star */}
      <div style={{
        display: 'flex',
        alignItems: 'baseline',
        justifyContent: 'center',
        gap: 6,
        margin: '14px 0 10px'
      }}>
        <span style={{
          fontFamily: 'var(--display)',
          fontSize: 'clamp(96px, 15vw, 168px)',
          color: resultAccent,
          lineHeight: 0.84,
          letterSpacing: '0.005em',
          textShadow: `0 0 40px ${resultAccent}30`
        }}>{acs}</span>
        <span style={{
          fontFamily: 'var(--display)',
          fontSize: 'clamp(30px, 4.5vw, 52px)',
          color: 'rgba(255,255,255,0.22)',
          lineHeight: 1,
          letterSpacing: '0.02em',
          whiteSpace: 'nowrap'
        }}>/ 1000</span>
      </div>

      {/* tier chip */}
      <div style={{
        display: 'inline-block',
        fontFamily: 'var(--display)',
        fontSize: 'clamp(30px, 4.4vw, 50px)',
        color: '#fff',
        letterSpacing: '0.06em',
        textTransform: 'uppercase',
        border: `1px solid ${resultAccent}`,
        padding: '6px 24px',
        marginBottom: 16,
        lineHeight: 1.1
      }}>{tier.name}</div>

      {/* supporting line */}
      <div style={{
        fontFamily: 'var(--mono)',
        fontSize: 12,
        letterSpacing: '0.14em',
        color: 'var(--muted)',
        textTransform: 'uppercase',
        marginBottom: 10
      }}>
        {score} / {quizTotal} correct · {sport}{totalAnswered < quizTotal ? ` · time expired (${totalAnswered} answered)` : ''}
      </div>

      {/* tagline */}
      <div style={{
        fontFamily: 'var(--body)',
        fontSize: 16,
        color: '#bbb',
        maxWidth: 440,
        margin: '0 auto 30px',
        lineHeight: 1.5
      }}>
        {ACS_TAGLINE[tier.name]}
      </div>

      {/* tier ladder */}
      <div className="sc-tier-ladder" style={{
        display: 'flex',
        gap: 8,
        justifyContent: 'center',
        maxWidth: 620,
        margin: '0 auto 34px',
        overflowX: 'auto'
      }}>
        {ACS_TIERS.map((t, i) => {
          const isActive = i === activeIdx;
          return (
            <div key={t.name} style={{
              flex: '1 1 0',
              minWidth: 120,
              padding: '12px 6px 14px',
              borderTop: `2px solid ${isActive ? t.color : 'rgba(255,255,255,0.12)'}`,
              background: isActive ? `${t.color}14` : 'transparent'
            }}>
              <div style={{
                fontFamily: 'var(--mono)',
                fontSize: 11,
                letterSpacing: '0.1em',
                color: isActive ? t.color : '#666',
                marginBottom: 6
              }}>{t.lo}–{t.hi}</div>
              <div style={{
                fontFamily: 'var(--display)',
                fontSize: 20,
                letterSpacing: '0.06em',
                textTransform: 'uppercase',
                color: isActive ? '#fff' : '#555'
              }}>{t.name}</div>
            </div>
          );
        })}
      </div>

      {/* CTA row */}
      <div style={{
        display: 'flex',
        gap: 12,
        justifyContent: 'center',
        flexWrap: 'wrap',
        alignItems: 'center'
      }}>
        <button onClick={handleShare} style={{
          background: resultAccent,
          color: '#0A0A0A',
          border: 'none',
          padding: '16px 30px',
          fontFamily: 'var(--display)',
          fontSize: 18,
          letterSpacing: '0.06em',
          cursor: 'pointer',
          textTransform: 'uppercase'
        }}>
          Share my Sports IQ
        </button>
        <button onClick={handleJoinWaitlist} disabled={waitlistStatus === 'saving' || waitlistStatus === 'saved'} style={{
          background: 'transparent',
          color: waitlistStatus === 'error' ? '#E53E3E' : resultAccent,
          border: `1px solid ${waitlistStatus === 'error' ? '#E53E3E' : resultAccent}`,
          padding: '15px 30px',
          fontFamily: 'var(--display)',
          fontSize: 18,
          letterSpacing: '0.06em',
          cursor: waitlistStatus === 'saving' || waitlistStatus === 'saved' ? 'default' : 'pointer',
          opacity: waitlistStatus === 'saving' ? 0.72 : 1,
          textTransform: 'uppercase'
        }}>
          {waitlistStatus === 'saving'
            ? 'Joining...'
            : waitlistStatus === 'saved'
              ? 'Joined Waitlist'
              : waitlistStatus === 'error'
                ? 'Try Again'
                : 'Join the Waitlist →'}
        </button>
        <button onClick={onReset} style={{
          background: 'transparent',
          color: 'var(--muted)',
          border: 'none',
          padding: '15px 12px',
          fontFamily: 'var(--mono)',
          fontSize: 12,
          letterSpacing: '0.14em',
          textTransform: 'uppercase',
          cursor: 'pointer'
        }}>
          Try Again ↺
        </button>
      </div>
    </div>
  );
};

// Faint blueprint-style background (echoing the inspiration's data-grid feel)
const BlueprintBg = () => (
  <div aria-hidden style={{
    position: 'absolute',
    inset: 0,
    pointerEvents: 'none',
    opacity: 0.06,
    backgroundImage: `
      linear-gradient(rgba(255,255,255,0.4) 1px, transparent 1px),
      linear-gradient(90deg, rgba(255,255,255,0.4) 1px, transparent 1px)
    `,
    backgroundSize: '64px 64px',
    maskImage: 'radial-gradient(ellipse at center, black 30%, transparent 70%)',
    WebkitMaskImage: 'radial-gradient(ellipse at center, black 30%, transparent 70%)'
  }}></div>
);

Object.assign(window, { IQGame });
