// Quiz.jsx — motor de cuestionarios del curso. window.Quiz
const { useState: useStateQ, useMemo: useMemoQ } = React;

function shuffle(arr) {
  const a = arr.slice();
  for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; }
  return a;
}
function sample(bank, n) { return shuffle(bank).slice(0, Math.min(n, bank.length)); }

function gradeOne(p, ans) {
  if (p.type === 'vf') return ans === p.correcta;
  if (p.type === 'abierta_num') {
    if (ans === '' || ans === null || ans === undefined) return false;
    const v = parseFloat(String(ans).replace(',', '.'));
    if (isNaN(v)) return false;
    const tol = p.tolerancia || 0;
    return Math.abs(v - p.correcta) <= tol + 1e-9;
  }
  return ans === p.correcta; // multiple → índice
}

function Quiz({ title, subtitle, bank, n, min, onResult, onClose }) {
  const [round, setRound] = useStateQ(0);
  const qs = useMemoQ(() => sample(bank, n), [round, bank, n]);
  const [answers, setAnswers] = useStateQ({});
  const [graded, setGraded] = useStateQ(false);
  const [result, setResult] = useStateQ(null);

  const setAns = (i, v) => { if (graded) return; setAnswers(a => ({ ...a, [i]: v })); };

  const submit = () => {
    let score = 0;
    qs.forEach((p, i) => { if (gradeOne(p, answers[i])) score++; });
    const passed = score * 2 >= qs.length; // 50% de aciertos
    setGraded(true);
    setResult({ score, total: qs.length, passed });
    if (onResult) onResult({ score, total: qs.length, passed });
    document.querySelector('#quiz-top')?.scrollIntoView({ block: 'start' });
  };

  const retry = () => { setAnswers({}); setGraded(false); setResult(null); setRound(r => r + 1); window.scrollTo(0, 0); };

  const answeredCount = Object.keys(answers).filter(k => answers[k] !== '' && answers[k] !== undefined && answers[k] !== null).length;
  const notaTxt = result ? (Math.round((result.score / result.total) * 100) / 10).toFixed(1).replace('.', ',') : '';

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(26,31,26,0.55)', zIndex: 50, overflowY: 'auto', display: 'flex', justifyContent: 'center' }}>
      <div style={{ background: 'var(--bg-canvas)', width: 'min(760px, 100%)', minHeight: '100%', padding: '0 0 80px' }}>
        {/* barra superior */}
        <div id="quiz-top" style={{ position: 'sticky', top: 0, zIndex: 2, background: 'rgba(251,248,240,0.94)', backdropFilter: 'blur(8px)', borderBottom: '1px solid var(--line)', padding: '14px 22px', display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ flex: 1 }}>
            <div style={{ font: 'var(--type-label)', letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--ink-3)' }}>{subtitle}</div>
            <div style={{ font: 'var(--type-h4)', color: 'var(--ink)' }}>{title}</div>
          </div>
          <div style={{ font: 'var(--type-ui-sm)', color: 'var(--ink-3)' }}>{qs.length} preguntas · aprobado al 50%</div>
          <button onClick={onClose} style={{ border: '1px solid var(--line)', background: 'var(--bg-surface)', borderRadius: 'var(--r-md)', padding: '7px 12px', cursor: 'pointer', font: 'var(--type-ui-sm)', color: 'var(--ink-2)' }}>Salir</button>
        </div>

        <div style={{ padding: '24px 22px 0' }}>
          {/* resultado */}
          {graded && result && (
            <div style={{ borderRadius: 'var(--r-lg)', padding: '20px 22px', marginBottom: 22, border: '1px solid', borderColor: result.passed ? 'var(--success)' : 'var(--danger)', background: result.passed ? 'var(--forest-soft)' : '#F6E2DF' }}>
              <div style={{ font: 'var(--type-h3)', color: result.passed ? 'var(--success)' : 'var(--danger)', marginBottom: 4 }}>
                {result.passed ? '¡Aprobado!' : 'No superado'}
              </div>
              <div style={{ font: 'var(--type-body)', color: 'var(--ink-2)' }}>
                {result.score} de {result.total} aciertos · nota {notaTxt} · necesitas el 50% (≥ {Math.ceil(result.total / 2)} aciertos).
              </div>
              {!result.passed && <div style={{ font: 'var(--type-body-sm)', color: 'var(--ink-2)', marginTop: 6 }}>Repasa la explicación y vuelve a intentarlo: saldrán preguntas distintas.</div>}
              {result.passed && <div style={{ font: 'var(--type-body-sm)', color: 'var(--ink-2)', marginTop: 6 }}>Se ha desbloqueado el siguiente paso. Pulsa “Continuar”.</div>}
            </div>
          )}

          {qs.map((p, i) => {
            const ok = graded && gradeOne(p, answers[i]);
            const bad = graded && !ok;
            return (
              <div key={i} style={{ background: 'var(--bg-surface)', border: '1px solid', borderColor: bad ? 'var(--danger)' : (ok ? 'var(--success)' : 'var(--line)'), borderRadius: 'var(--r-lg)', padding: '18px 20px', marginBottom: 14 }}>
                <div style={{ display: 'flex', gap: 10, marginBottom: 12 }}>
                  <span style={{ font: 'var(--type-ui-sm)', color: 'var(--ink-3)', flexShrink: 0 }}>{i + 1}.</span>
                  <span style={{ font: 'var(--type-body)', color: 'var(--ink)' }} dangerouslySetInnerHTML={{ __html: p.q }} />
                </div>

                {p.type === 'multiple' && (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {p.opciones.map((opt, oi) => {
                      const sel = answers[i] === oi;
                      const showCorrect = graded && oi === p.correcta;
                      const showWrong = graded && sel && oi !== p.correcta;
                      return (
                        <label key={oi} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 12px', borderRadius: 'var(--r-md)', border: '1px solid', cursor: graded ? 'default' : 'pointer',
                          borderColor: showCorrect ? 'var(--success)' : (showWrong ? 'var(--danger)' : (sel ? 'var(--terracotta)' : 'var(--line)')),
                          background: showCorrect ? 'var(--forest-soft)' : (showWrong ? '#F6E2DF' : (sel ? 'var(--terracotta-soft)' : 'var(--bg-surface)')) }}>
                          <input type="radio" name={'q' + i} checked={sel} onChange={() => setAns(i, oi)} disabled={graded} style={{ accentColor: 'var(--terracotta)' }} />
                          <span style={{ font: 'var(--type-body-sm)', color: 'var(--ink)' }} dangerouslySetInnerHTML={{ __html: opt }} />
                        </label>
                      );
                    })}
                  </div>
                )}

                {p.type === 'vf' && (
                  <div style={{ display: 'flex', gap: 10 }}>
                    {[['Verdadero', true], ['Falso', false]].map(([lab, val]) => {
                      const sel = answers[i] === val;
                      const showCorrect = graded && p.correcta === val;
                      const showWrong = graded && sel && p.correcta !== val;
                      return (
                        <button key={lab} onClick={() => setAns(i, val)} disabled={graded} style={{ flex: 1, padding: '10px 12px', borderRadius: 'var(--r-md)', border: '1px solid', cursor: graded ? 'default' : 'pointer', font: 'var(--type-ui)',
                          borderColor: showCorrect ? 'var(--success)' : (showWrong ? 'var(--danger)' : (sel ? 'var(--terracotta)' : 'var(--line)')),
                          background: showCorrect ? 'var(--forest-soft)' : (showWrong ? '#F6E2DF' : (sel ? 'var(--terracotta-soft)' : 'var(--bg-surface)')),
                          color: 'var(--ink)' }}>{lab}</button>
                      );
                    })}
                  </div>
                )}

                {p.type === 'abierta_num' && (
                  <input type="text" inputMode="decimal" value={answers[i] ?? ''} onChange={e => setAns(i, e.target.value)} disabled={graded}
                    placeholder="Tu respuesta…"
                    style={{ width: 160, padding: '9px 12px', borderRadius: 'var(--r-md)', border: '1px solid', borderColor: ok ? 'var(--success)' : (bad ? 'var(--danger)' : 'var(--line)'), font: 'var(--type-body)', color: 'var(--ink)', background: 'var(--bg-surface)' }} />
                )}

                {graded && (
                  <div style={{ marginTop: 12, paddingTop: 10, borderTop: '1px dashed var(--line)', font: 'var(--type-body-sm)', color: 'var(--ink-2)' }}>
                    <strong style={{ color: ok ? 'var(--success)' : 'var(--danger)', font: 'var(--type-ui-sm)' }}>{ok ? '✓ Correcto' : '✗ Incorrecto'}</strong>
                    {p.explica && <span dangerouslySetInnerHTML={{ __html: ' · ' + p.explica }} />}
                  </div>
                )}
              </div>
            );
          })}

          {/* acciones */}
          <div style={{ display: 'flex', gap: 12, marginTop: 8, position: 'sticky', bottom: 0, background: 'linear-gradient(transparent, var(--bg-canvas) 24%)', padding: '20px 0' }}>
            {!graded && (
              <button onClick={submit} style={{ background: 'var(--terracotta)', color: '#fff', border: 0, borderRadius: 'var(--r-md)', padding: '13px 24px', font: 'var(--type-ui)', cursor: 'pointer' }}>
                Corregir ({answeredCount}/{qs.length})
              </button>
            )}
            {graded && !result.passed && (
              <button onClick={retry} style={{ background: 'var(--terracotta)', color: '#fff', border: 0, borderRadius: 'var(--r-md)', padding: '13px 24px', font: 'var(--type-ui)', cursor: 'pointer' }}>Reintentar</button>
            )}
            {graded && result.passed && (
              <button onClick={onClose} style={{ background: 'var(--forest)', color: '#FBF8F0', border: 0, borderRadius: 'var(--r-md)', padding: '13px 24px', font: 'var(--type-ui)', cursor: 'pointer' }}>Continuar →</button>
            )}
            {graded && (
              <button onClick={retry} style={{ background: 'var(--bg-surface)', color: 'var(--ink-2)', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', padding: '13px 20px', font: 'var(--type-ui-sm)', cursor: 'pointer' }}>Otra vez</button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.Quiz = Quiz;
