// Parcours 2 — Interface examen (CRITIQUE) + soumission

const ExamInterface = () => {
  const D = window.STUDYHUB_DATA;
  const questions = D.examQuestions;
  const [qIdx, setQIdx] = React.useState(0);
  const [answers, setAnswers] = React.useState({});
  const [marked, setMarked] = React.useState({});
  const [timeLeft, setTimeLeft] = React.useState(2700); // 45 min
  const [savedAt, setSavedAt] = React.useState(0);
  const [tabAlert, setTabAlert] = React.useState(false);
  const [showSubmitModal, setShowSubmitModal] = React.useState(false);
  const [transition, setTransition] = React.useState(null);

  React.useEffect(() => {
    const t = setInterval(() => setTimeLeft(x => Math.max(0, x - 8)), 1000); // accelerated for demo
    return () => clearInterval(t);
  }, []);

  React.useEffect(() => {
    const t = setInterval(() => setSavedAt(s => s + 1), 3000);
    return () => clearInterval(t);
  }, []);

  // simulate tab-change alert once
  React.useEffect(() => {
    const t = setTimeout(() => { setTabAlert(true); setTimeout(() => setTabAlert(false), 4500); }, 14000);
    return () => clearTimeout(t);
  }, []);

  const fmt = (s) => `${String(Math.floor(s/60)).padStart(2,'0')}:${String(s%60).padStart(2,'0')}`;
  const timerColor = timeLeft < 60 ? '#EF4444' : timeLeft < 300 ? '#F59E0B' : '#6ECFB5';
  const timerPulse = timeLeft < 60 ? { animation: 'pulse 1s infinite' } : {};

  const q = questions[qIdx];
  const goTo = (newIdx) => {
    if (newIdx === qIdx) return;
    setTransition(newIdx > qIdx ? 'right' : 'left');
    setTimeout(() => { setQIdx(newIdx); setTransition(null); }, 180);
  };
  const setAnswer = (val) => setAnswers({ ...answers, [q.id]: val });

  // Question status
  const statusOf = (i) => {
    const qq = questions[i];
    if (i === qIdx) return 'current';
    if (marked[qq.id]) return 'marked';
    if (answers[qq.id] !== undefined) return 'answered';
    return 'unseen';
  };

  return (
    <div className="exam-bg" style={{ position: 'relative' }}>
      {/* Tab alert */}
      {tabAlert && (
        <div style={{ position: 'fixed', top: 0, left: 0, right: 0, background: '#7F1D1D', color: 'white', padding: '10px 20px', textAlign: 'center', zIndex: 999, animation: 'fadeIn 0.2s', borderBottom: '2px solid #EF4444' }}>
          <Icon name="warn" size={16} style={{ display: 'inline', verticalAlign: 'middle', marginRight: 8 }}/>
          <b>Sortie d'onglet détectée.</b> Un rapport a été transmis à l'enseignant. Cette infraction est enregistrée.
        </div>
      )}

      {/* Header */}
      <div style={{ background: 'linear-gradient(180deg, #1E2640 0%, rgba(30,38,64,0.85) 100%)', borderBottom: '1px solid rgba(99,102,241,0.2)', padding: '14px 32px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', position: 'sticky', top: 0, zIndex: 10 }}>
        <div className="flex items-center gap-3">
          <Logo size="sm" variant="stud"/>
          <div style={{ width: 1, height: 24, background: 'rgba(255,255,255,0.1)' }}/>
          <div>
            <div style={{ fontFamily: 'Poppins', fontWeight: 600, fontSize: 13, color: 'white' }}>Algorithmique — Complexité & récursivité</div>
            <div style={{ fontSize: 11, color: '#94A3B8' }}>INF201 · Lucas Benhamou</div>
          </div>
        </div>
        <div className="flex items-center gap-4">
          <div style={{ fontFamily: 'JetBrains Mono', fontSize: 13, color: '#94A3B8' }}>
            Question <span style={{ color: 'white', fontWeight: 700 }}>{qIdx + 1}</span> / {questions.length}
          </div>
          <div style={{ fontFamily: 'JetBrains Mono', fontSize: 36, fontWeight: 700, color: timerColor, letterSpacing: '0.02em', minWidth: 140, textAlign: 'center', ...timerPulse }}>
            {fmt(timeLeft)}
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 220px', gap: 32, padding: '32px 32px 60px', maxWidth: 1280, margin: '0 auto' }}>
        {/* Main */}
        <div style={{ maxWidth: 900, margin: '0 auto', width: '100%' }}>
          <div key={qIdx} className="fade-in" style={{ opacity: transition ? 0.3 : 1, transform: transition === 'right' ? 'translateX(-20px)' : transition === 'left' ? 'translateX(20px)' : 'translateX(0)', transition: 'all 0.18s ease-out' }}>
            <div className="flex items-center gap-2" style={{ marginBottom: 16 }}>
              <span className="badge badge-f1">{{
                'qcm-single': 'QCM simple', 'qcm-multi': 'QCM multiple', 'matching': 'Association',
                'cloze': 'Texte à trous', 'essay': 'Question ouverte', 'short': 'Réponse courte', 'ordering': 'Ordonnancement'
              }[q.type]}</span>
              <span style={{ fontFamily: 'JetBrains Mono', fontSize: 11, color: '#94A3B8' }}>Q{qIdx + 1} · {q.points} pt{q.points > 1 ? 's' : ''}</span>
              <button onClick={() => setMarked({ ...marked, [q.id]: !marked[q.id] })} className="btn btn-sm" style={{ marginLeft: 'auto', background: marked[q.id] ? '#F59E0B' : 'rgba(255,255,255,0.06)', color: marked[q.id] ? 'white' : '#94A3B8' }}>
                <Icon name="flag" size={12}/> {marked[q.id] ? 'Marquée à revoir' : 'Marquer à revoir'}
              </button>
            </div>
            <h2 style={{ fontFamily: 'Poppins', fontWeight: 700, fontSize: 24, lineHeight: 1.4, color: 'white', marginBottom: 24 }}>{q.text}</h2>

            {/* Render by type */}
            {(q.type === 'qcm-multi' || q.type === 'qcm-single') && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {q.options.map((opt, i) => {
                  const sel = q.type === 'qcm-single' ? answers[q.id] === opt.id : (answers[q.id] || []).includes(opt.id);
                  return (
                    <div key={opt.id} onClick={() => {
                      if (q.type === 'qcm-single') setAnswer(opt.id);
                      else {
                        const cur = answers[q.id] || [];
                        setAnswer(cur.includes(opt.id) ? cur.filter(x => x !== opt.id) : [...cur, opt.id]);
                      }
                    }} className={'exam-option' + (sel ? ' selected' : '')}>
                      <div style={{ width: 28, height: 28, borderRadius: q.type === 'qcm-single' ? 999 : 8, border: '2px solid ' + (sel ? '#8B7CF6' : 'rgba(255,255,255,0.2)'), background: sel ? '#8B7CF6' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                        {sel && <Icon name="check" size={14} style={{ color: 'white' }}/>}
                      </div>
                      <div style={{ flex: 1, fontSize: 15 }}>{opt.text}</div>
                      <div style={{ fontFamily: 'JetBrains Mono', fontSize: 11, color: '#64748B' }}>{String.fromCharCode(65 + i)}</div>
                    </div>
                  );
                })}
              </div>
            )}

            {q.type === 'cloze' && (
              <div style={{ fontSize: 18, lineHeight: 2, color: '#E2E8F0' }}>
                {q.parts.map((p, i) => p.type === 'text' ? <span key={i}>{p.value}</span> : (
                  <input key={i} className="input-dark input" style={{ display: 'inline-block', width: 160, margin: '0 6px', background: 'rgba(139,124,246,0.1)', border: '1px solid #8B7CF6', color: '#C4B5FD', fontFamily: 'JetBrains Mono', fontWeight: 600 }}
                    value={(answers[q.id] || {})[p.id] || ''} onChange={e => setAnswer({ ...(answers[q.id] || {}), [p.id]: e.target.value })}/>
                ))}
              </div>
            )}

            {q.type === 'ordering' && <OrderingQ q={q} answers={answers} setAnswer={setAnswer}/>}
            {q.type === 'matching' && <MatchingQ q={q} answers={answers} setAnswer={setAnswer}/>}

            {q.type === 'essay' && (
              <div>
                <textarea className="input input-dark" rows="8" placeholder="Rédige ta réponse ici…" value={answers[q.id] || ''} onChange={e => setAnswer(e.target.value)} style={{ resize: 'vertical', fontFamily: 'Inter', fontSize: 15, lineHeight: 1.6, padding: 16 }}/>
                <div className="flex items-center justify-between t-small" style={{ color: '#94A3B8', marginTop: 8 }}>
                  <span>Limite : <b style={{ color: '#E2E8F0' }}>800</b> caractères</span>
                  <span style={{ fontFamily: 'JetBrains Mono' }}>{(answers[q.id] || '').length} / 800</span>
                </div>
              </div>
            )}

            {q.type === 'short' && (
              <input className="input input-dark" placeholder="Ta réponse…" value={answers[q.id] || ''} onChange={e => setAnswer(e.target.value)} style={{ fontSize: 16, padding: 14 }}/>
            )}
          </div>

          {/* Saved indicator */}
          <div style={{ textAlign: 'center', marginTop: 24, fontSize: 11, color: '#64748B', fontFamily: 'JetBrains Mono' }}>
            <Icon name="check" size={11} style={{ display: 'inline', verticalAlign: 'middle', marginRight: 4, color: '#10B981' }}/>
            Réponse sauvegardée il y a {savedAt % 4 + 1}s
          </div>

          {/* Footer nav */}
          <div className="flex items-center justify-between" style={{ marginTop: 32, paddingTop: 24, borderTop: '1px solid rgba(255,255,255,0.1)' }}>
            <button onClick={() => qIdx > 0 && goTo(qIdx - 1)} className="btn btn-ghost" style={{ color: '#94A3B8', opacity: qIdx === 0 ? 0.3 : 1 }} disabled={qIdx === 0}>
              <Icon name="arrowLeft" size={14}/> Question précédente
            </button>
            {qIdx === questions.length - 1 ? (
              <button onClick={() => setShowSubmitModal(true)} className="btn btn-primary-stud">Terminer et soumettre <Icon name="send" size={14}/></button>
            ) : (
              <button onClick={() => goTo(qIdx + 1)} className="btn btn-primary-stud">Question suivante <Icon name="arrowRight" size={14}/></button>
            )}
          </div>
        </div>

        {/* Side minimap */}
        <div style={{ position: 'sticky', top: 96, alignSelf: 'flex-start' }}>
          <div className="t-label" style={{ color: '#64748B', marginBottom: 10 }}>Progression</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6, marginBottom: 16 }}>
            {questions.map((qq, i) => {
              const st = statusOf(i);
              const styles = {
                current: { bg: '#8B7CF6', color: 'white', border: '2px solid #C4B5FD' },
                answered: { bg: 'rgba(16,185,129,0.15)', color: '#6EE7B7', border: '1px solid rgba(16,185,129,0.3)' },
                marked: { bg: 'rgba(245,158,11,0.15)', color: '#FBBF24', border: '1px solid rgba(245,158,11,0.4)' },
                unseen: { bg: 'rgba(255,255,255,0.04)', color: '#64748B', border: '1px solid rgba(255,255,255,0.08)' },
              }[st];
              return (
                <button key={qq.id} onClick={() => goTo(i)} style={{ aspectRatio: '1', borderRadius: 8, fontFamily: 'JetBrains Mono', fontSize: 12, fontWeight: 700, cursor: 'pointer', ...styles, transition: 'all 0.15s' }}>
                  {i + 1}
                  {marked[qq.id] && st !== 'current' && <div style={{ position: 'absolute', top: -4, right: -4, width: 8, height: 8, background: '#F59E0B', borderRadius: 999 }}/>}
                </button>
              );
            })}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 11, color: '#94A3B8' }}>
            <div className="flex items-center gap-2"><div style={{ width: 12, height: 12, borderRadius: 3, background: '#8B7CF6' }}/> En cours</div>
            <div className="flex items-center gap-2"><div style={{ width: 12, height: 12, borderRadius: 3, background: 'rgba(16,185,129,0.3)' }}/> Répondue</div>
            <div className="flex items-center gap-2"><div style={{ width: 12, height: 12, borderRadius: 3, background: 'rgba(245,158,11,0.3)' }}/> Marquée</div>
            <div className="flex items-center gap-2"><div style={{ width: 12, height: 12, borderRadius: 3, background: 'rgba(255,255,255,0.06)' }}/> Non vue</div>
          </div>
          <div style={{ marginTop: 20, padding: 14, borderRadius: 12, background: 'rgba(139,124,246,0.08)', border: '1px solid rgba(139,124,246,0.2)' }}>
            <div className="t-label" style={{ color: '#A78BFA', marginBottom: 4 }}>Répondues</div>
            <div style={{ fontFamily: 'Poppins', fontSize: 22, fontWeight: 800, color: 'white' }}>{Object.keys(answers).length}<span style={{ fontSize: 14, color: '#64748B' }}>/{questions.length}</span></div>
          </div>
        </div>
      </div>

      {/* Submit modal */}
      {showSubmitModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', backdropFilter: 'blur(4px)' }} onClick={() => setShowSubmitModal(false)}>
          <div className="fade-in" style={{ background: '#1E2640', color: 'white', maxWidth: 460, width: '90%', padding: 32, borderRadius: 20, border: '1px solid rgba(99,102,241,0.3)' }} onClick={e => e.stopPropagation()}>
            <div style={{ width: 56, height: 56, margin: '0 auto 16px', borderRadius: 16, background: 'rgba(245,158,11,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="warn" size={28} style={{ color: '#F59E0B' }}/>
            </div>
            <h2 className="t-h2" style={{ textAlign: 'center', marginBottom: 8 }}>Soumettre l'évaluation ?</h2>
            <p className="t-small" style={{ color: '#94A3B8', textAlign: 'center', marginBottom: 20 }}>
              Tu as répondu à <b style={{ color: 'white' }}>{Object.keys(answers).length}/{questions.length}</b> questions.
              {Object.keys(answers).length < questions.length && <><br/><span style={{ color: '#F59E0B' }}>Attention : {questions.length - Object.keys(answers).length} question(s) sans réponse.</span></>}
            </p>
            <p className="t-small" style={{ color: '#94A3B8', textAlign: 'center', marginBottom: 24 }}>Cette action est <b>définitive</b>. Tu ne pourras plus modifier tes réponses.</p>
            <div className="flex gap-3">
              <button onClick={() => setShowSubmitModal(false)} className="btn btn-secondary" style={{ flex: 1, background: 'rgba(255,255,255,0.06)', color: 'white', border: '1px solid rgba(255,255,255,0.12)' }}>Continuer l'évaluation</button>
              <a href="#/etudiant/soumis" className="btn btn-primary-stud" style={{ flex: 1 }}>Oui, soumettre</a>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// Drag-and-drop ordering
const OrderingQ = ({ q, answers, setAnswer }) => {
  const current = answers[q.id] || q.items.map(it => it.id);
  const [draggedIdx, setDraggedIdx] = React.useState(null);
  const items = current.map(id => q.items.find(it => it.id === id));
  const reorder = (from, to) => {
    const newIds = [...current];
    const [m] = newIds.splice(from, 1);
    newIds.splice(to, 0, m);
    setAnswer(newIds);
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {items.map((it, i) => (
        <div key={it.id} draggable onDragStart={() => setDraggedIdx(i)} onDragOver={e => e.preventDefault()} onDrop={() => { if (draggedIdx !== null) reorder(draggedIdx, i); setDraggedIdx(null); }}
          className="exam-option" style={{ cursor: 'grab', opacity: draggedIdx === i ? 0.4 : 1, padding: '14px 18px' }}>
          <div style={{ width: 32, height: 32, borderRadius: 8, background: 'linear-gradient(135deg, #8B7CF6, #7C3AED)', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'JetBrains Mono', fontWeight: 700, fontSize: 13 }}>{i + 1}</div>
          <div style={{ flex: 1, fontSize: 15 }}>{it.label}</div>
          <Icon name="grip" size={16} style={{ color: '#64748B' }}/>
        </div>
      ))}
    </div>
  );
};

// Drag-drop matching
const MatchingQ = ({ q, answers, setAnswer }) => {
  const pairs = answers[q.id] || {};
  const [dragging, setDragging] = React.useState(null);
  const assign = (leftId, rightId) => setAnswer({ ...pairs, [leftId]: rightId });
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', gap: 24, alignItems: 'center' }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {q.left.map(L => (
          <div key={L.id} draggable onDragStart={() => setDragging(L.id)} className="exam-option" style={{ cursor: 'grab' }}>
            <div style={{ width: 24, height: 24, borderRadius: 999, background: '#8B7CF6', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'JetBrains Mono', fontWeight: 700, fontSize: 11 }}>{L.id}</div>
            <div style={{ flex: 1 }}>{L.label}</div>
            {pairs[L.id] && <span className="badge" style={{ background: 'rgba(16,185,129,0.2)', color: '#6EE7B7' }}>→ {pairs[L.id]}</span>}
          </div>
        ))}
      </div>
      <div style={{ color: '#64748B', fontSize: 20 }}>⇌</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {q.right.map(R => (
          <div key={R.id} onDragOver={e => e.preventDefault()} onDrop={() => { if (dragging) { assign(dragging, R.id); setDragging(null); } }}
            className="exam-option" style={{ cursor: 'pointer' }} onClick={() => dragging && (assign(dragging, R.id), setDragging(null))}>
            <div style={{ flex: 1, fontFamily: 'JetBrains Mono', fontWeight: 600 }}>{R.label}</div>
            <div style={{ width: 24, height: 24, borderRadius: 6, border: '2px dashed rgba(255,255,255,0.2)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'JetBrains Mono', fontSize: 10, color: '#64748B' }}>{R.id}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

const ExamSubmitted = () => {
  return (
    <div style={{ minHeight: '100vh', background: 'linear-gradient(135deg, #0F1729, #1E1B4B, #4C1D95)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, position: 'relative', overflow: 'hidden' }}>
      <Confetti/>
      <div style={{ position: 'absolute', inset: 0 }}>
        <div style={{ position: 'absolute', top: '20%', left: '10%', width: 300, height: 300, borderRadius: 999, background: 'radial-gradient(circle, rgba(110,207,181,0.2), transparent 70%)' }}/>
        <div style={{ position: 'absolute', bottom: '15%', right: '10%', width: 340, height: 340, borderRadius: 999, background: 'radial-gradient(circle, rgba(139,124,246,0.2), transparent 70%)' }}/>
      </div>
      <div className="card fade-in" style={{ maxWidth: 520, width: '100%', padding: 40, textAlign: 'center', borderRadius: 24, zIndex: 2, boxShadow: '0 40px 100px rgba(0,0,0,0.4)' }}>
        <div style={{ width: 80, height: 80, margin: '0 auto 20px', borderRadius: 999, background: 'linear-gradient(135deg, #6ECFB5, #4DB8A0)', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 20px 40px rgba(110,207,181,0.4)' }}>
          <Icon name="check" size={40} style={{ color: 'white' }} stroke={3}/>
        </div>
        <h1 className="t-h1" style={{ marginBottom: 8 }}>Évaluation soumise ✓</h1>
        <p className="t-body" style={{ color: '#64748B', marginBottom: 24 }}>
          Bravo Lucas ! Ta copie d'<b>Algorithmique — Complexité & récursivité</b> a bien été transmise.
        </p>
        <div style={{ padding: 18, borderRadius: 14, background: '#F5F0FF', border: '1px solid #EDE9FE', textAlign: 'left', marginBottom: 20 }}>
          <div className="flex items-center gap-2" style={{ marginBottom: 10 }}>
            <Icon name="clock" size={14} style={{ color: '#8B7CF6' }}/>
            <span style={{ fontFamily: 'Poppins', fontWeight: 600, fontSize: 13 }}>Et maintenant ?</span>
          </div>
          <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, color: '#475569', lineHeight: 1.8 }}>
            <li>Les questions QCM sont corrigées automatiquement</li>
            <li>Ta·ton enseignant·e relit les questions ouvertes (assisté·e par l'IA)</li>
            <li>Résultat détaillé disponible <b>sous 48h</b></li>
          </ul>
        </div>
        <div className="flex gap-2">
          <a href="#/etudiant" className="btn btn-secondary" style={{ flex: 1 }}>Retour au tableau de bord</a>
          <a href="#/" className="btn btn-primary-stud" style={{ flex: 1 }}>Terminer</a>
        </div>
      </div>
    </div>
  );
};

// Mobile wrappers
const MobileFrame = ({ children, label }) => (
  <div style={{ minHeight: '100vh', background: 'linear-gradient(135deg, #E0E7FF, #FCE7F3)', padding: 40, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 20 }}>
    <div className="flex items-center gap-3">
      <a href="#/" className="btn btn-secondary btn-sm">← Accueil</a>
      <div className="t-label" style={{ color: '#64748B' }}>{label}</div>
    </div>
    <div className="mobile-frame">
      <div className="mobile-notch"/>
      <div className="mobile-inner">{children}</div>
    </div>
    <div className="t-small" style={{ color: '#64748B' }}>375 × 760 · iPhone viewport</div>
  </div>
);

Object.assign(window, { ExamInterface, ExamSubmitted, MobileFrame });
