/* screens/Quiz.jsx — Pop Quiz: 5 fresh trivia questions per team playing today.
   New questions every matchday (keyed `${teamCode}-${md}` in QUIZ_QUESTIONS).
   Answers are picked locally and only revealed (correct/wrong) after the
   day's "Submit answers" button is pressed.
   window.QuizScreen */

function QuizQuestion({ question, qIdx, submitted, picked, onPick }) {
  return (
    <div className="quizq">
      <div className="quizq__text">{question.q}</div>
      <div className="quizq__choices">
        {question.choices.map((choice, i) => {
          const isCorrect = i === question.correct;
          const isPicked = i === picked;
          let state;
          if (submitted) state = isCorrect ? 'correct' : (isPicked ? 'wrong' : undefined);
          else if (isPicked) state = 'picked';
          return (
            <button key={i} type="button" className="quizq__choice" data-state={state}
              disabled={submitted} onClick={() => onPick(qIdx, i)}>
              {choice}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function TeamQuizBlock({ team, quizKey, questions, quizLog, picks, submitted, onPick }) {
  const t = window.WC.team(team);
  const log = quizLog[quizKey] || {};
  const logValues = Object.values(log);
  const correct = logValues.reduce((sum, v) => sum + Number(v), 0);
  const allCorrect = logValues.length > 0 && logValues.every(v => Number(v) > 0);

  return (
    <div className="quizteam">
      <div className="quizteam__head">
        <Team code={team} strong />
        {submitted && questions.length > 0 && (
          <Pill tone={allCorrect ? 'green' : 'gold'}>{correct}/{questions.length}</Pill>
        )}
      </div>
      {questions.length === 0 ? (
        <p className="muted" style={{ fontSize: 'var(--fs-sm)' }}>Quiz coming soon for {t.name}.</p>
      ) : (
        <div className="quizteam__qs">
          {questions.map((q, i) => (
            <QuizQuestion key={i} question={q} qIdx={i} submitted={submitted}
              picked={(picks || {})[i]} onPick={(idx, choiceIdx) => onPick(quizKey, idx, choiceIdx)} />
          ))}
        </div>
      )}
    </div>
  );
}

function QuizGate({ store }) {
  const { useState } = React;
  const [nameVal, setNameVal] = useState(store.state.name || '');
  const [emailVal, setEmailVal] = useState(store.state.email || '');
  const [status, setStatus] = useState('idle'); // idle | busy | error

  const valid = nameVal.length > 0 && emailVal.includes('@');

  const submit = async () => {
    if (!valid) return;
    setStatus('busy');
    try {
      store.setName(nameVal);
      await store.saveEmail(emailVal);
      window.bwcpTrack?.('bwcp_email_captured', { source: 'quiz' });
    } catch (_) { setStatus('error'); }
  };

  return (
    <div className="livehead" style={{ justifyContent: 'center', textAlign: 'center' }}>
      <div style={{ maxWidth: 380, margin: '0 auto' }}>
        <div className="livehead__sub">📬 Enter your name & email to unlock the quiz</div>
        <p className="muted" style={{ margin: 'var(--sp-3) 0 var(--sp-5)' }}>
          One-time setup gets you in for the whole tournament — come back every matchday for fresh questions, and your name shows up on the quiz leaderboard.
        </p>
        <input
          className="nameinput"
          type="text"
          placeholder="Name / handle"
          value={nameVal}
          onChange={e => setNameVal(e.target.value.replace(/[^a-z0-9_]/gi, '').slice(0, 18))}
          onKeyDown={e => e.key === 'Enter' && submit()}
          style={{ width: '100%', marginBottom: 'var(--sp-3)' }}
        />
        <input
          className="nameinput"
          type="email"
          placeholder="your@email.com"
          value={emailVal}
          onChange={e => setEmailVal(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && submit()}
          style={{ width: '100%', marginBottom: 'var(--sp-3)' }}
        />
        <Btn block onClick={submit} disabled={status === 'busy' || !valid}>
          {status === 'busy' ? 'Unlocking…' : 'Unlock the quiz'}
        </Btn>
        {status === 'error' && <p style={{ fontSize: 12, color: '#f87171', margin: 'var(--sp-3) 0 0' }}>Something went wrong — try again.</p>}
      </div>
    </div>
  );
}

function CatchUpFixture({ fixture, quizLog, store }) {
  const { useState, useMemo } = React;
  const { home, away } = window.WCLogic.getQuizForFixture(fixture);
  const blocks = [home, away].filter(b => b.questions.length > 0);
  const isSubmitted = (b) => Object.keys(quizLog[b.key] || {}).length === b.questions.length;
  const pendingBlocks = blocks.filter(b => !isSubmitted(b));
  const [picks, setPicks] = useState({});
  const onPick = (key, qIdx, choiceIdx) => setPicks(p => ({ ...p, [key]: { ...(p[key] || {}), [qIdx]: choiceIdx } }));
  const canSubmit = pendingBlocks.length > 0 && pendingBlocks.every(
    b => Object.keys(picks[b.key] || {}).length === b.questions.length
  );
  const submit = () => {
    let correct = 0, total = 0;
    pendingBlocks.forEach(b => {
      b.questions.forEach((q, i) => {
        const isCorrect = picks[b.key]?.[i] === q.correct;
        if (isCorrect) correct++;
        total++;
        store.setQuizAnswer(b.key, i, isCorrect ? 0.5 : 0); // catch-up answers earn half credit
      });
    });
    window.bwcpTrack?.('bwcp_quiz_submitted', { correct, total, source: 'catchup', weight: 0.5 });
  };
  return (
    <div className="quizmatch" style={{ marginBottom: 'var(--sp-6)' }}>
      <div className="quizmatch__head">
        <span className="quizmatch__vs"><Flag code={fixture.home} size={18} /> v <Flag code={fixture.away} size={18} /></span>
        <span className="muted">{fixture.date} · Group {fixture.group} · MD{fixture.md}</span>
      </div>
      <div className="quizmatch__teams">
        {blocks.map(b => (
          <TeamQuizBlock key={b.key} team={b.team} quizKey={b.key} questions={b.questions}
            quizLog={quizLog} picks={picks[b.key]} submitted={isSubmitted(b)} onPick={onPick} />
        ))}
      </div>
      {pendingBlocks.length > 0 && (
        <div style={{ textAlign: 'center', marginTop: 'var(--sp-4)' }}>
          <Btn size="sm" onClick={submit} disabled={!canSubmit}>Submit answers</Btn>
          {!canSubmit && <p className="muted" style={{ fontSize: 12, marginTop: 'var(--sp-2)' }}>Answer every question to submit.</p>}
        </div>
      )}
    </div>
  );
}

function QuizScreen({ store }) {
  const { useEffect, useMemo, useState } = React;

  useEffect(() => { window.bwcpTrack?.('bwcp_quiz_viewed'); }, []);

  const fixtures = useMemo(() => window.WCLogic.getTodaysFixtures(), []);
  const quizLog = store.state.quiz_log || {};
  const gated = !store.isShared && (!store.state.email || !store.state.name);

  const catchUpFixtures = useMemo(() => {
    const todayIds = new Set(fixtures.map(f => f.id));
    return window.WC.fixtures.filter(f => {
      if (todayIds.has(f.id)) return false;
      const { home, away } = window.WCLogic.getQuizForFixture(f);
      const blocks = [home, away].filter(b => b.questions.length > 0);
      return blocks.some(b => Object.keys(quizLog[b.key] || {}).length < b.questions.length);
    });
  }, [fixtures, quizLog]);

  useEffect(() => { if (gated) window.bwcpTrack?.('bwcp_quiz_email_gate_viewed'); }, [gated]);

  // this-session picks, not yet submitted: { [quizKey]: { [qIdx]: choiceIdx } }
  const [picks, setPicks] = useState({});

  const onPick = (key, qIdx, choiceIdx) => {
    setPicks(p => ({ ...p, [key]: { ...(p[key] || {}), [qIdx]: choiceIdx } }));
  };

  // every team block playing today that has questions authored
  const teamBlocks = useMemo(() => {
    const blocks = [];
    fixtures.forEach(f => {
      const { home, away } = window.WCLogic.getQuizForFixture(f);
      [home, away].forEach(side => { if (side.questions.length > 0) blocks.push(side); });
    });
    return blocks;
  }, [fixtures]);

  const isSubmitted = (b) => Object.keys(quizLog[b.key] || {}).length === b.questions.length;
  const pendingBlocks = teamBlocks.filter(b => !isSubmitted(b));
  const allDone = teamBlocks.length > 0 && pendingBlocks.length === 0;
  const canSubmit = pendingBlocks.length > 0 && pendingBlocks.every(
    b => Object.keys(picks[b.key] || {}).length === b.questions.length
  );

  const submitQuiz = () => {
    let correct = 0, total = 0;
    pendingBlocks.forEach(b => {
      b.questions.forEach((q, i) => {
        const isCorrect = picks[b.key]?.[i] === q.correct;
        if (isCorrect) correct++;
        total++;
        store.setQuizAnswer(b.key, i, isCorrect);
      });
    });
    window.bwcpTrack?.('bwcp_quiz_submitted', { correct, total });
  };

  return (
    <div className="page">
      <header className="phead">
        <div>
          <div className="eyebrow">Today's matchday</div>
          <h1 className="section-h">Pop Quiz</h1>
          <p className="muted phead__sub">5 fresh trivia questions for each team playing today — new questions every time they take the pitch. Pick your answers, then submit to see how you did.</p>
        </div>
      </header>

      {gated ? (
        <QuizGate store={store} />
      ) : fixtures.length === 0 ? (
        <div className="livehead" style={{ justifyContent: 'center', textAlign: 'center' }}>
          <div>
            <div className="livehead__sub">No matches today</div>
            <p className="muted" style={{ marginTop: 4 }}>Check back on the next matchday for fresh questions.</p>
          </div>
        </div>
      ) : (
        <>
          <div className="quizgrid">
            {fixtures.map(f => {
              const { home, away } = window.WCLogic.getQuizForFixture(f);
              return (
                <div key={f.id} className="quizmatch">
                  <div className="quizmatch__head">
                    <span className="quizmatch__vs"><Flag code={f.home} size={18} /> v <Flag code={f.away} size={18} /></span>
                    <span className="muted">{f.date} · Group {f.group} · MD{f.md}</span>
                  </div>
                  <div className="quizmatch__teams">
                    <TeamQuizBlock team={f.home} quizKey={home.key} questions={home.questions} quizLog={quizLog}
                      picks={picks[home.key]} submitted={isSubmitted(home)} onPick={onPick} />
                    <TeamQuizBlock team={f.away} quizKey={away.key} questions={away.questions} quizLog={quizLog}
                      picks={picks[away.key]} submitted={isSubmitted(away)} onPick={onPick} />
                  </div>
                </div>
              );
            })}
          </div>

          {teamBlocks.length > 0 && (
            allDone ? (
              <div className="urlbox" style={{ borderColor: 'var(--win)', background: 'var(--win-dim)', marginTop: 'var(--sp-7)', textAlign: 'center' }}>
                <div className="urlbox__lbl" style={{ color: 'var(--win)' }}>Submitted ✅</div>
                <p className="muted" style={{ fontSize: 13, margin: 0 }}>Come back on the next matchday for fresh questions.</p>
              </div>
            ) : (
              <div style={{ textAlign: 'center', marginTop: 'var(--sp-7)' }}>
                <Btn onClick={submitQuiz} disabled={!canSubmit}>Submit answers</Btn>
                {!canSubmit && <p className="muted" style={{ fontSize: 12, marginTop: 'var(--sp-3)' }}>Answer every question to submit.</p>}
              </div>
            )
          )}

          <div className="urlbox" style={{ borderColor: 'var(--gold-deep)', background: 'var(--gold-dim)', marginTop: 'var(--sp-7)', textAlign: 'center' }}>
            <div className="urlbox__lbl" style={{ color: 'var(--gold)' }}>Enjoying the quiz?</div>
            <p className="muted" style={{ fontSize: 13, margin: '0 0 var(--sp-4)' }}>If you're having fun, a coffee keeps the floodlights on.</p>
            <Btn size="sm" onClick={() => { window.bwcpTrack?.('bwcp_tip_clicked', { source: 'quiz' }); window.open('https://ko-fi.com/beram', '_blank', 'noopener,noreferrer'); }}>☕ Buy me a coffee</Btn>
          </div>

          {catchUpFixtures.length > 0 && (
            <div style={{ marginTop: 'var(--sp-10)' }}>
              <h2 className="section-h" style={{ marginBottom: 'var(--sp-2)' }}>Catch up</h2>
              <p className="muted" style={{ marginBottom: 'var(--sp-6)', fontSize: 'var(--fs-sm)' }}>Matchdays you haven't answered yet — submit each one when you're ready. Worth half points (0.5 per question) since they're after the fact — answer live next time for full credit!</p>
              {catchUpFixtures.map(f => (
                <CatchUpFixture key={f.id} fixture={f} quizLog={quizLog} store={store} />
              ))}
            </div>
          )}
        </>
      )}
    </div>
  );
}
window.QuizScreen = QuizScreen;
