// Screen components for the calibration tool.
// Exported to window for cross-script access.

const { useState, useEffect, useRef, useMemo } = React;

/* ----------------------------- Shared chrome ----------------------------- */

const AppHeader = ({ strings, onRestart, showRestart }) => (
  <header className="app-header">
    <div className="brand">
      <img src="assets/logos/horizontal-color-on-white.svg" alt="EA Vietnam" />
    </div>
    {showRestart ? (
      <button className="link-btn" onClick={onRestart}>{strings.results.retake}</button>
    ) : <span className="header-meta">eavn.org</span>}
  </header>
);

/* ---------------------------------- Intro -------------------------------- */

const IntroScreen = ({ strings, onStart, hasInProgress, onResume, totalQuestions, answeredCount }) => (
  <main className="intro">
    <div className="intro-grid">
      <div className="intro-copy">
        <div className="eyebrow">{strings.intro.eyebrow}</div>
        <h1 className="intro-title">
          {strings.intro.lede}
          <span className="flourish"> {strings.intro.ledeFlourish}</span>
        </h1>
        {strings.intro.paragraphs.map((p, i) => (
          <p className="intro-p" key={i}>{p}</p>
        ))}
        <div className="intro-cta-row">
          {hasInProgress ? (
            <>
              <button className="btn btn-primary" onClick={onResume}>
                Tiếp tục bài đang làm
                <span className="btn-meta">{answeredCount}/{totalQuestions}</span>
              </button>
              <button className="btn btn-ghost" onClick={onStart}>Bắt đầu lại</button>
            </>
          ) : (
            <button className="btn btn-primary" onClick={onStart}>{strings.intro.start}</button>
          )}
        </div>
        <p className="intro-source">{strings.intro.based}</p>
      </div>

      <aside className="intro-meta">
        <dl>
          {strings.intro.meta.map((m, i) => (
            <div key={i}>
              <dt>{m.k}</dt>
              <dd>{m.v}</dd>
            </div>
          ))}
        </dl>
        <div className="intro-bullets">
          <h3>Cách chấm điểm</h3>
          <ul>
            <li>Mỗi câu, bạn chọn đáp án và đặt mức tự tin từ 55%–95%.</li>
            <li>Cuối bài, ta tính tỉ lệ bạn đúng ở từng mức.</li>
            <li>Một người hiệu chuẩn tốt: 80% tự tin → đúng ~80% số câu.</li>
          </ul>
        </div>
      </aside>
    </div>
  </main>
);

/* -------------------------------- Question ------------------------------- */

const ConfidenceChip = ({ value, selected, onSelect }) => (
  <button
    className={`chip ${selected ? 'chip-on' : ''}`}
    onClick={() => onSelect(value)}
    aria-pressed={selected}
    type="button"
  >
    <span className="chip-num">{value}</span>
    <span className="chip-pct">%</span>
  </button>
);

const AnswerButton = ({ label, sub, selected, onClick, letter }) => (
  <button
    className={`answer ${selected ? 'answer-on' : ''}`}
    onClick={onClick}
    aria-pressed={selected}
    type="button"
  >
    <span className="answer-letter">{letter}</span>
    <span className="answer-label">{label}</span>
    {sub ? <span className="answer-sub">{sub}</span> : null}
  </button>
);

const QuestionScreen = ({
  strings, roundTitles, questions, idx,
  current, onPick, onConfidence, onNext, onSkip, onBack
}) => {
  const total = questions.length;
  const q = questions[idx];
  const round = q.round;
  const ready = current && current.picked && current.confidence;

  // Round progress segments — 4 rounds, 10 each.
  const segments = [1, 2, 3, 4].map((r) => {
    const inRound = questions.filter((qq, i) => qq.round === r).length;
    const passed = idx >= inRound * r ? inRound : Math.max(0, idx - inRound * (r - 1));
    return { r, total: inRound, passed: Math.min(inRound, Math.max(0, idx + 1 - (r - 1) * inRound)) };
  });

  return (
    <main className="question">
      <div className="q-top">
        <div className="q-progress">
          <div className="q-rounds">
            {segments.map((s, i) => {
              const active = q.round === s.r;
              const done = q.round > s.r;
              return (
                <div key={i} className={`seg ${active ? 'seg-active' : ''} ${done ? 'seg-done' : ''}`}>
                  <div className="seg-bar">
                    {Array.from({ length: s.total }).map((_, j) => {
                      const filled = done || (active && j < s.passed);
                      return <span key={j} className={filled ? 'tick on' : 'tick'} />;
                    })}
                  </div>
                </div>
              );
            })}
          </div>
          <div className="q-meta-row">
            <span className="q-round-label">{roundTitles[round]}</span>
            <span className="q-counter">{strings.question.progressLong(idx + 1, total)}</span>
          </div>
        </div>
      </div>

      <div className="q-stage">
        <div className="q-text-wrap">
          {q.type === 'AB' ? <span className="q-prompt-eye">Câu hỏi so sánh</span> : <span className="q-prompt-eye">Đúng hay sai</span>}
          <h2 className="q-text">{q.q}</h2>
        </div>

        <div className={`answers ${q.type === 'TF' ? 'answers-2' : 'answers-2'}`}>
          {q.type === 'TF' ? (
            <>
              <AnswerButton
                label={strings.answers.T}
                letter="T"
                selected={current?.picked === 'T'}
                onClick={() => onPick('T')}
              />
              <AnswerButton
                label={strings.answers.F}
                letter="F"
                selected={current?.picked === 'F'}
                onClick={() => onPick('F')}
              />
            </>
          ) : (
            <>
              <AnswerButton
                label={q.a}
                letter="A"
                selected={current?.picked === 'A'}
                onClick={() => onPick('A')}
              />
              <AnswerButton
                label={q.b}
                letter="B"
                selected={current?.picked === 'B'}
                onClick={() => onPick('B')}
              />
            </>
          )}
        </div>

        <div className="confidence">
          <div className="conf-prompt-row">
            <span className="conf-prompt">{strings.question.confidencePrompt}</span>
          </div>
          <div className="conf-chips">
            {window.CALIB_HELPERS.CONFIDENCES.map((v) => (
              <ConfidenceChip
                key={v}
                value={v}
                selected={current?.confidence === v}
                onSelect={onConfidence}
              />
            ))}
          </div>
          <div className="conf-hints">
            <span>{strings.question.confidenceHintLeft}</span>
            <span className="dot-sep" aria-hidden="true">·</span>
            <span>{strings.question.confidenceHintRight}</span>
          </div>
        </div>
      </div>

      <div className="q-actions">
        <button className="link-btn" onClick={onBack} disabled={idx === 0}>{strings.nav.back}</button>
        <div className="q-actions-right">
          <button className="link-btn" onClick={onSkip}>{strings.question.skip}</button>
          <button
            className="btn btn-primary"
            disabled={!ready}
            onClick={onNext}
            title={!ready ? `${strings.question.pickAnswer} · ${strings.question.pickConfidence}` : ''}
          >
            {strings.question.next}
            <span className="btn-arrow" aria-hidden="true">→</span>
          </button>
        </div>
      </div>
    </main>
  );
};

/* --------------------------------- Results ------------------------------- */

const ResultsScreen = ({ strings, questions, answers, onRestart }) => {
  const helpers = window.CALIB_HELPERS;
  const buckets = useMemo(() => helpers.computeBuckets(questions, answers), [answers]);
  const totalAnswered = answers.filter((a) => a && !a.skipped && a.picked).length;
  const totalSkipped = answers.filter((a) => a && a.skipped).length + (answers.length < questions.length ? questions.length - answers.length : 0);
  const totalCorrect = answers.reduce((acc, a, i) => {
    if (!a || a.skipped || !a.picked) return acc;
    return acc + (a.picked === questions[i].answer ? 1 : 0);
  }, 0);
  const brierVal = helpers.brier(questions, answers);
  const readoutKey = helpers.readoutKey(buckets);
  const [showMissed, setShowMissed] = useState(false);
  const [shareLabel, setShareLabel] = useState(strings.results.share);

  const missed = useMemo(() => {
    return questions.map((q, i) => {
      const a = answers[i];
      if (!a || a.skipped || !a.picked) return null;
      if (a.picked === q.answer) return null;
      return { i, q, a };
    }).filter(Boolean);
  }, [answers]);

  const handleShare = async () => {
    const text = helpers.buildShareText(buckets, strings, totalAnswered, totalCorrect, brierVal);
    try {
      await navigator.clipboard.writeText(text);
      setShareLabel(strings.results.shareCopied);
      setTimeout(() => setShareLabel(strings.results.share), 1800);
    } catch {
      // fallback
      const ta = document.createElement('textarea');
      ta.value = text; document.body.appendChild(ta); ta.select();
      try { document.execCommand('copy'); } catch {}
      document.body.removeChild(ta);
      setShareLabel(strings.results.shareCopied);
      setTimeout(() => setShareLabel(strings.results.share), 1800);
    }
  };

  const renderAnswer = (q, code) => {
    if (q.type === 'TF') return strings.answers[code];
    return code === 'A' ? q.a : q.b;
  };

  if (totalAnswered === 0) {
    return (
      <main className="results-empty">
        <div className="eyebrow">{strings.results.eyebrow}</div>
        <h1>{strings.results.notEnough}</h1>
        <button className="btn btn-primary" onClick={onRestart}>{strings.results.retake}</button>
      </main>
    );
  }

  return (
    <main className="results">
      <header className="results-head">
        <div className="eyebrow">{strings.results.eyebrow}</div>
        <h1 className="results-title">{strings.results.title}</h1>
        <p className="results-readout">
          <span className="readout-mark" aria-hidden="true" />
          {strings.results.readouts[readoutKey]}
        </p>
      </header>

      <section className="results-stats">
        <div className="stat">
          <div className="stat-num">{totalAnswered}</div>
          <div className="stat-lbl">{strings.results.summary.answered}</div>
        </div>
        <div className="stat">
          <div className="stat-num">{totalCorrect}</div>
          <div className="stat-lbl">{strings.results.summary.correct}</div>
        </div>
        <div className="stat">
          <div className="stat-num">{questions.length - totalAnswered}</div>
          <div className="stat-lbl">{strings.results.summary.skipped}</div>
        </div>
        <div className="stat stat-brier">
          <div className="stat-num">{brierVal != null ? brierVal.toFixed(3) : '—'}</div>
          <div className="stat-lbl">{strings.results.summary.brierLabel}</div>
          <div className="stat-hint">{strings.results.summary.brierHint}</div>
        </div>
      </section>

      <section className="chart-section">
        <div className="chart-head">
          <h2 className="section-title">{strings.results.chartTitle}</h2>
          <p className="chart-cap">{strings.results.chartCaption}</p>
        </div>
        <window.CalibrationChart buckets={buckets} strings={strings} />
      </section>

      <section className="table-section">
        <h2 className="section-title">{strings.results.tableTitle}</h2>
        <div className="table-wrap">
          <table className="bucket-table">
            <thead>
              <tr>
                {strings.results.tableHeaders.map((h, i) => <th key={i}>{h}</th>)}
              </tr>
            </thead>
            <tbody>
              {window.CALIB_HELPERS.CONFIDENCES.map((c) => {
                const b = buckets[c];
                if (!b || b.total === 0) return null;
                const acc = (b.correct / b.total) * 100;
                const diff = acc - c;
                return (
                  <tr key={c}>
                    <td className="td-conf"><span className="conf-pill">{c}%</span></td>
                    <td>{b.correct}</td>
                    <td>{b.total - b.correct}</td>
                    <td className="td-actual">
                      <span className="bar-cell">
                        <span className="bar-cell-track">
                          <span className="bar-cell-fill" style={{ width: `${acc}%` }} />
                          <span className="bar-cell-target" style={{ left: `${c}%` }} />
                        </span>
                        <span className="bar-cell-num">{acc.toFixed(0)}%</span>
                      </span>
                    </td>
                    <td className={`td-diff ${diff > 4 ? 'd-pos' : diff < -4 ? 'd-neg' : 'd-near'}`}>
                      {diff >= 0 ? '+' : ''}{diff.toFixed(0)} pt
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </section>

      {missed.length > 0 && (
        <section className="missed-section">
          <button
            className="missed-toggle"
            onClick={() => setShowMissed((v) => !v)}
            aria-expanded={showMissed}
          >
            <span className="m-count">{missed.length}</span>
            <span>{showMissed ? strings.results.missedHide : strings.results.missedToggle}</span>
            <span className="m-arrow" aria-hidden="true">{showMissed ? '−' : '+'}</span>
          </button>
          {showMissed && (
            <ol className="missed-list">
              {missed.map(({ i, q, a }) => (
                <li key={i} className="missed-item">
                  <div className="missed-meta">
                    <span className="missed-num">{String(i + 1).padStart(2, '0')}</span>
                    <span className="missed-conf">{strings.results.atConfidence} {a.confidence}%</span>
                  </div>
                  <p className="missed-q">{q.q}</p>
                  {q.type === 'AB' && (
                    <p className="missed-options">
                      A. {q.a} <span className="opt-sep">·</span> B. {q.b}
                    </p>
                  )}
                  <div className="missed-rows">
                    <div className="missed-row mr-yours">
                      <span className="mr-lbl">{strings.results.yourAnswer}</span>
                      <span className="mr-val">{renderAnswer(q, a.picked)}</span>
                    </div>
                    <div className="missed-row mr-correct">
                      <span className="mr-lbl">{strings.results.correctAnswer}</span>
                      <span className="mr-val">{renderAnswer(q, q.answer)}</span>
                    </div>
                  </div>
                  <p className="missed-explain">{q.explain}</p>
                </li>
              ))}
            </ol>
          )}
        </section>
      )}

      <section className="results-actions">
        <button className="btn btn-ghost" onClick={handleShare}>{shareLabel}</button>
        <button className="btn btn-primary" onClick={onRestart}>{strings.results.retake}</button>
      </section>
    </main>
  );
};

window.IntroScreen = IntroScreen;
window.QuestionScreen = QuestionScreen;
window.ResultsScreen = ResultsScreen;
window.AppHeader = AppHeader;
