/* ============================================================
   TechManager — EXAM FLOW (gate -> timed runner -> results)
   ============================================================ */

/* ---- Password gate (verified against the mock BE) ---- */
const ExamGate = ({ cert, go, onStart }) => {
  const [pw, setPw] = useState('');
  const [err, setErr] = useState('');
  const [checking, setChecking] = useState(false);
  const submit = () => {
    setErr(''); setChecking(true);
    // simulate a backend round-trip
    setTimeout(() => {
      const res = TM.verifyExamPassword(cert.id, pw);
      setChecking(false);
      if (res.ok) onStart(); else setErr(res.reason);
    }, 650);
  };
  return (
    <div className="fadein wrap" style={{ maxWidth: 520, paddingTop: 70, paddingBottom: 70 }}>
      <button className="btn btn-soft btn-sm" onClick={() => go('learn', { certId: cert.id })}><Icon name="arrowL" size={15} /> Back to learning path</button>
      <div className="card" style={{ padding: 34, marginTop: 22, textAlign: 'center' }}>
        <div style={{ width: 70, height: 70, margin: '0 auto 18px', borderRadius: 18, background: `linear-gradient(135deg, ${cert.color}, ${cert.color2})`, display: 'grid', placeItems: 'center' }}>
          <Icon name="lock" size={28} style={{ color: '#fff' }} />
        </div>
        <h1 className="display" style={{ fontSize: 28 }}>Secure exam access</h1>
        <p className="muted" style={{ marginTop: 8 }}>Enter the unique access password for <strong style={{ color: 'var(--text)' }}>{cert.name}</strong>. It is verified with the server before your exam begins.</p>

        <div className="grid" style={{ gridTemplateColumns: 'repeat(3,1fr)', gap: 10, margin: '24px 0' }}>
          {[['book', cert.examConfig.numQuestions, 'Questions'], ['clock', cert.examConfig.timeMinutes + ' min', 'Time limit'], ['checkCircle', cert.examConfig.passGrade + '%', 'To pass']].map(([ic, v, l]) => (
            <div key={l} className="card" style={{ padding: '14px 8px', background: 'var(--bg-soft)' }}>
              <Icon name={ic} size={18} style={{ color: 'var(--blue-2)' }} />
              <div style={{ fontWeight: 800, fontSize: 18, marginTop: 6 }}>{v}</div>
              <div className="dim" style={{ fontSize: 11.5, textTransform: 'uppercase', letterSpacing: '.06em' }}>{l}</div>
            </div>
          ))}
        </div>

        <Field label="Exam access password">
          <input className="input" value={pw} placeholder="e.g. CLOUD-2026" autoFocus
            onChange={(e) => setPw(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && submit()} style={{ textAlign: 'center', letterSpacing: '.08em', fontWeight: 600 }} />
        </Field>
        {err && <div style={{ color: 'var(--red)', fontSize: 13.5, marginTop: 10 }} className="center gap-8"><Icon name="xCircle" size={16} /> {err}</div>}
        <button className="btn btn-primary btn-block" style={{ marginTop: 18 }} onClick={submit} disabled={checking}>
          {checking ? <><span className="spin" style={{ width: 15, height: 15, border: '2px solid rgba(255,255,255,0.4)', borderTopColor: '#fff', borderRadius: '50%', display: 'inline-block' }} /> Verifying with server…</> : <>Begin exam <Icon name="arrow" size={15} /></>}
        </button>
        <p className="dim" style={{ fontSize: 12, marginTop: 14 }}>Tip — this demo's password is <code style={{ color: 'var(--blue-2)' }}>{cert.examConfig.password}</code> (set in the admin panel).</p>
      </div>
    </div>
  );
};

/* ---- Timed runner ---- */
const ExamRunner = ({ cert, paper, onSubmit, onAbort }) => {
  const [answers, setAnswers] = useState({});
  const [idx, setIdx] = useState(0);
  const [left, setLeft] = useState(paper.timeMinutes * 60);
  const submittedRef = useRef(false);

  const finish = useCallback(() => {
    if (submittedRef.current) return;
    submittedRef.current = true;
    onSubmit(answers);
  }, [answers, onSubmit]);

  useEffect(() => {
    const t = setInterval(() => setLeft((s) => {
      if (s <= 1) { clearInterval(t); finish(); return 0; }
      return s - 1;
    }), 1000);
    return () => clearInterval(t);
  }, [finish]);

  const q = paper.questions[idx] || paper.questions[paper.questions.length - 1];
  const answered = Object.keys(answers).length;
  const mm = String(Math.floor(left / 60)).padStart(2, '0');
  const ss = String(left % 60).padStart(2, '0');
  const low = left < 60;

  return (
    <div className="fadein wrap" style={{ maxWidth: 820, paddingTop: 34, paddingBottom: 60 }}>
      {/* top bar */}
      <div className="card between" style={{ padding: '14px 20px', position: 'sticky', top: 80, zIndex: 20, flexWrap: 'wrap', gap: 12 }}>
        <div className="center gap-12">
          <Orb cert={cert} size={36} />
          <div><div style={{ fontWeight: 700, fontSize: 14.5 }}>{cert.name}</div><div className="dim" style={{ fontSize: 12 }}>Question {idx + 1} of {paper.questions.length}</div></div>
        </div>
        <div className="center gap-16">
          <span className="muted" style={{ fontSize: 13 }}>{answered}/{paper.questions.length} answered</span>
          <span className="chip" style={{ fontWeight: 800, color: low ? 'var(--red)' : 'var(--text)', borderColor: low ? 'rgba(248,113,113,0.4)' : 'var(--border-strong)' }}>
            <Icon name="clock" size={15} /> {mm}:{ss}
          </span>
        </div>
      </div>

      {/* progress dots */}
      <div className="flex gap-8" style={{ flexWrap: 'wrap', margin: '20px 0' }}>
        {paper.questions.map((qq, i) => (
          <button key={qq.id} onClick={() => setIdx(i)} title={'Question ' + (i + 1)}
            style={{ width: 30, height: 30, borderRadius: 8, fontSize: 12.5, fontWeight: 700, border: '1px solid var(--border-strong)',
              background: i === idx ? 'var(--blue)' : answers[qq.id] !== undefined ? 'rgba(52,211,153,0.16)' : 'var(--panel-2)',
              color: i === idx ? '#fff' : answers[qq.id] !== undefined ? '#6ee7b7' : 'var(--muted)' }}>{i + 1}</button>
        ))}
      </div>

      {/* question */}
      <div className="card" style={{ padding: 30 }}>
        <div className="dim" style={{ fontSize: 12.5, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase' }}>{q.area}</div>
        <h2 className="display" style={{ fontSize: 23, marginTop: 10, lineHeight: 1.3 }}>{q.prompt}</h2>
        <div className="grid gap-12" style={{ marginTop: 22 }}>
          {q.options.map((o, i) => {
            const sel = answers[q.id] === i;
            return (
              <button key={i} onClick={() => setAnswers((a) => ({ ...a, [q.id]: i }))}
                style={{ textAlign: 'left', padding: '15px 18px', borderRadius: 12, fontSize: 15.5,
                  border: '1.5px solid ' + (sel ? 'var(--blue)' : 'var(--border-strong)'),
                  background: sel ? 'rgba(47,125,246,0.12)' : 'var(--bg-soft)', color: sel ? '#fff' : 'var(--text-2)',
                  display: 'flex', alignItems: 'center', gap: 14, transition: 'all .12s' }}>
                <span style={{ width: 24, height: 24, flex: '0 0 24px', borderRadius: '50%', border: '1.5px solid ' + (sel ? 'var(--blue-2)' : 'var(--dim)'), display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 700, background: sel ? 'var(--blue)' : 'transparent', color: '#fff' }}>{String.fromCharCode(65 + i)}</span>
                {o}
              </button>
            );
          })}
        </div>
      </div>

      {/* nav */}
      <div className="between" style={{ marginTop: 22 }}>
        <button className="btn btn-soft" onClick={() => setIdx((i) => Math.max(0, i - 1))} disabled={idx === 0}><Icon name="arrowL" size={15} /> Previous</button>
        <div className="flex gap-12">
          <button className="btn btn-soft" onClick={onAbort}>Quit</button>
          {idx < paper.questions.length - 1
            ? <button className="btn btn-primary" onClick={() => setIdx((i) => Math.min(paper.questions.length - 1, i + 1))}>Next <Icon name="arrow" size={15} /></button>
            : <button className="btn btn-primary" onClick={finish}>Submit exam <Icon name="checkCircle" size={15} /></button>}
        </div>
      </div>
      <p className="dim" style={{ fontSize: 12.5, textAlign: 'center', marginTop: 18 }}>You can revisit any question using the numbers above. The exam auto-submits when the timer reaches zero.</p>
    </div>
  );
};

/* ---- Results: score + areas to study (never the questions) ---- */
const ExamResults = ({ cert, attempt, go }) => {
  const weak = attempt.areaBreakdown.filter((a) => a.weak);
  return (
    <div className="fadein wrap" style={{ maxWidth: 760, paddingTop: 50, paddingBottom: 70 }}>
      <div className="card" style={{ padding: 36, textAlign: 'center', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, background: `radial-gradient(500px 220px at 50% -40%, ${attempt.passed ? 'rgba(52,211,153,0.22)' : 'rgba(248,113,113,0.18)'}, transparent)`, pointerEvents: 'none' }} />
        <div style={{ position: 'relative' }}>
          <span className={'badge ' + (attempt.passed ? 'badge-pass' : 'badge-fail')} style={{ fontSize: 13 }}>
            {attempt.passed ? <><Icon name="check" size={13} /> Passed</> : <><Icon name="x" size={13} /> Not passed</>}
          </span>
          <div style={{ margin: '22px 0' }}><ScoreRing pct={attempt.score} pass={attempt.passed} size={150} /></div>
          <h1 className="display" style={{ fontSize: 30 }}>{attempt.passed ? `You're certified.` : 'So close — keep going.'}</h1>
          <p className="muted" style={{ marginTop: 8 }}>
            You scored <strong style={{ color: 'var(--text)' }}>{attempt.score}%</strong> ({attempt.correctCount}/{attempt.total} correct). Pass mark is {attempt.passGrade}%.
            {attempt.passed && ' Your credential has been added to your profile.'}
          </p>
          <div className="flex gap-12" style={{ justifyContent: 'center', marginTop: 22 }}>
            {attempt.passed
              ? <button className="btn btn-primary" onClick={() => go('profile')}><Icon name="award" size={16} /> View my credential</button>
              : <button className="btn btn-primary" onClick={() => go('exam', { certId: cert.id })}><Icon name="refresh" size={16} /> Retake exam</button>}
            <button className="btn btn-ghost" onClick={() => go('learn', { certId: cert.id })}>Back to modules</button>
          </div>
        </div>
      </div>

      {/* area breakdown */}
      <div className="card" style={{ padding: 30, marginTop: 22 }}>
        <h2 className="display" style={{ fontSize: 22 }}>Where to focus next</h2>
        <p className="muted" style={{ marginTop: 6 }}>Your performance by domain. We show the areas to study — never which specific questions you got right or wrong.</p>
        <div className="grid gap-16" style={{ marginTop: 22 }}>
          {attempt.areaBreakdown.map((a) => (
            <div key={a.area}>
              <div className="between" style={{ marginBottom: 7 }}>
                <span className="center gap-8" style={{ fontSize: 14.5, fontWeight: 600 }}>
                  {a.weak ? <Icon name="target" size={15} style={{ color: 'var(--amber)' }} /> : <Icon name="checkCircle" size={15} style={{ color: 'var(--green)' }} />}
                  {a.area}
                </span>
                <span style={{ fontWeight: 700, color: a.weak ? 'var(--amber)' : 'var(--green)' }}>{a.pct}%</span>
              </div>
              <div className="bar-track"><div className="bar-fill" style={{ width: a.pct + '%', background: a.weak ? 'linear-gradient(90deg,#d39a14,var(--amber))' : 'linear-gradient(90deg,#0e9488,var(--green))' }} /></div>
            </div>
          ))}
        </div>
        {weak.length > 0 && (
          <div className="card" style={{ padding: 18, marginTop: 22, background: 'rgba(245,196,81,0.07)', borderColor: 'rgba(245,196,81,0.25)' }}>
            <div className="center gap-8" style={{ fontWeight: 700, marginBottom: 8 }}><Icon name="book" size={16} style={{ color: 'var(--amber)' }} /> Recommended study areas</div>
            <div className="flex gap-8" style={{ flexWrap: 'wrap' }}>{weak.map((a) => <span key={a.area} className="chip" style={{ borderColor: 'rgba(245,196,81,0.4)', color: '#fcd34d' }}>{a.area}</span>)}</div>
            <button className="btn btn-soft btn-sm" style={{ marginTop: 14 }} onClick={() => go('learn', { certId: cert.id })}>Review these modules <Icon name="arrow" size={14} /></button>
          </div>
        )}
      </div>
    </div>
  );
};

/* ---- Orchestrator ---- */
const ExamFlow = ({ cert, db, go }) => {
  const [phase, setPhase] = useState('gate'); // gate | runner | results
  const [paper, setPaper] = useState(null);
  const [attempt, setAttempt] = useState(null);

  const begin = () => { setPaper(TM.buildExam(cert.id)); setPhase('runner'); };
  const submit = (answers) => { const att = TM.submitExam(cert.id, paper, answers); setAttempt(att); setPhase('results'); };

  if (phase === 'gate') return <ExamGate cert={cert} go={go} onStart={begin} />;
  if (phase === 'runner') return <ExamRunner cert={cert} paper={paper} onSubmit={submit} onAbort={() => go('learn', { certId: cert.id })} />;
  return <ExamResults cert={cert} attempt={attempt} go={go} />;
};

Object.assign(window, { ExamGate, ExamRunner, ExamResults, ExamFlow });
