// app/quiz.jsx — Le Grand Quiz : 2 manches, scoring, badges, classement.
// Stockage local (migration backend prévue ultérieurement).

const QUIZ_STATE_KEY   = "ea-app:quiz:state";
const QUIZ_RESULTS_KEY = "ea-app:quiz:results";

// ─────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────
function computeScore(answers1, answers2, bonusAnswer) {
  let score = 0;
  QUIZ_DATA.questions.forEach((q) => {
    if (q.correctIdx != null && answers1[q.id] === q.correctIdx) score++;
  });
  QUIZ_DATA.qld.forEach((p) => {
    if (p.whoSaid && answers2[p.id] === p.whoSaid) score++;
  });
  // Bonus Phila (n'affecte pas le score officiel)
  return score;
}

function getBadge(score) {
  const b = QUIZ_DATA.badges;
  if (score >= b[2].threshold) return b[2];
  if (score >= b[1].threshold) return b[1];
  return b[0];
}

function abbrevName(full) {
  // "Madenn Quenet" → "Madenn Q."
  const parts = (full || "").trim().split(/\s+/);
  if (parts.length === 1) return parts[0];
  return `${parts[0]} ${parts[parts.length - 1][0]}.`;
}

// ─────────────────────────────────────────────────────────
// PAGE PRINCIPALE — state machine
// ─────────────────────────────────────────────────────────
function QuizPage() {
  const saved = Store.get(QUIZ_STATE_KEY, null);
  const [state, setState] = React.useState(() => saved || {
    step: "intro",        // intro · manche1 · transition · bonus · manche2 · result
    index: 0,
    name: "",
    answers1: {},
    answers2: {},
    bonusAnswer: null,
    bonusUnlocked: false,
  });
  const [resumePrompt, setResumePrompt] = React.useState(
    !!saved && saved.step !== "intro" && saved.step !== "result"
  );

  // Persistance
  React.useEffect(() => {
    if (state.step === "result") {
      Store.set(QUIZ_STATE_KEY, null); // on efface l'état en cours
    } else {
      Store.set(QUIZ_STATE_KEY, state);
    }
  }, [state]);

  const update = (patch) => setState((s) => ({ ...s, ...patch }));

  const restart = () => {
    Store.set(QUIZ_STATE_KEY, null);
    setState({
      step: "intro", index: 0, name: "",
      answers1: {}, answers2: {}, bonusAnswer: null, bonusUnlocked: false,
    });
    setResumePrompt(false);
  };

  // — INTRO → manche 1
  const handleStart = (name) => {
    update({ step: "manche1", index: 0, name: name.trim() });
  };

  // — Sélection réponse Manche 1
  const handleAnswer1 = (qId, optIdx) => {
    const next = { ...state.answers1, [qId]: optIdx };
    update({ answers1: next });
  };

  // — Navigation Manche 1
  const handleNext1 = () => {
    if (state.index < QUIZ_DATA.questions.length - 1) {
      update({ index: state.index + 1 });
    } else {
      update({ step: "transition" });
    }
  };
  const handlePrev1 = () => {
    if (state.index > 0) update({ index: state.index - 1 });
  };

  // — Easter egg activé → bonus Phila
  const handleBonusUnlock = () => {
    update({ step: "bonus", bonusUnlocked: true });
  };
  const handleBonusAnswer = (optIdx) => {
    update({ bonusAnswer: optIdx, step: "manche2", index: 0 });
  };
  const handleSkipBonus = () => {
    update({ step: "manche2", index: 0 });
  };

  // — Transition normale (sans easter egg)
  const handleContinueToManche2 = () => {
    update({ step: "manche2", index: 0 });
  };

  // — Sélection réponse Manche 2
  const handleAnswer2 = (pId, side) => {
    const next = { ...state.answers2, [pId]: side };
    update({ answers2: next });
  };

  // — Navigation Manche 2
  const handleNext2 = () => {
    if (state.index < QUIZ_DATA.qld.length - 1) {
      update({ index: state.index + 1 });
    } else {
      // Final → enregistre + result
      const score = computeScore(state.answers1, state.answers2, state.bonusAnswer);
      const all = Store.get(QUIZ_RESULTS_KEY, []);
      // Une seule entrée par nom
      const filtered = all.filter((r) => r.name.toLowerCase() !== state.name.toLowerCase());
      filtered.push({
        name: state.name,
        score,
        bonusUnlocked: state.bonusUnlocked,
        completedAt: new Date().toISOString(),
      });
      Store.set(QUIZ_RESULTS_KEY, filtered);
      update({ step: "result" });
    }
  };
  const handlePrev2 = () => {
    if (state.index > 0) update({ index: state.index - 1 });
  };

  // ─── Resume prompt ───
  if (resumePrompt) {
    return (
      <div style={{ position: "relative", overflow: "hidden", minHeight: "100vh" }}>
        <WashBg hue={210} opacity={0.16} />
        <Page>
          <div style={{ marginTop: 60, textAlign: "center" }}>
            <div style={{ fontFamily: A.display, fontStyle: "italic", color: A.or, fontSize: 64, lineHeight: 0.9 }}>♥</div>
            <div className="display-bold" style={{ fontSize: 30, color: A.ink, margin: "16px 0 10px" }}>
              Reprendre où vous en étiez ?
            </div>
            <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 16, color: A.inkSoft, marginBottom: 28, maxWidth: 360, margin: "0 auto" }}>
              {state.name && <>Bonjour <strong style={{ color: A.ink }}>{state.name}</strong>, </>}
              vous avez commencé le quiz. On peut reprendre à la question {state.index + 1} ?
            </div>
            <div style={{ display: "flex", gap: 10, justifyContent: "center", flexWrap: "wrap" }}>
              <ButtonA primary onClick={() => setResumePrompt(false)}>♥ Reprendre</ButtonA>
              <ButtonA onClick={restart}>↺ Recommencer</ButtonA>
            </div>
          </div>
        </Page>
      </div>
    );
  }

  // ─── Routeur écrans ───
  switch (state.step) {
    case "intro":
      return <QuizIntro onStart={handleStart} />;
    case "manche1":
      return (
        <QuizQuestionScreen
          index={state.index}
          question={QUIZ_DATA.questions[state.index]}
          selected={state.answers1[QUIZ_DATA.questions[state.index].id]}
          total={QUIZ_DATA.questions.length}
          onSelect={(idx) => handleAnswer1(QUIZ_DATA.questions[state.index].id, idx)}
          onPrev={state.index > 0 ? handlePrev1 : null}
          onNext={handleNext1}
        />
      );
    case "transition":
      return (
        <QuizTransition
          name={state.name}
          onContinue={handleContinueToManche2}
          onUnlockBonus={handleBonusUnlock}
        />
      );
    case "bonus":
      return (
        <QuizBonusScreen
          question={QUIZ_DATA.bonusQuestion}
          onAnswer={handleBonusAnswer}
          onSkip={handleSkipBonus}
        />
      );
    case "manche2":
      return (
        <QuizQldScreen
          index={state.index}
          phrase={QUIZ_DATA.qld[state.index]}
          selected={state.answers2[QUIZ_DATA.qld[state.index].id]}
          total={QUIZ_DATA.qld.length}
          onSelect={(side) => handleAnswer2(QUIZ_DATA.qld[state.index].id, side)}
          onPrev={state.index > 0 ? handlePrev2 : null}
          onNext={handleNext2}
        />
      );
    case "result":
      return (
        <QuizResult
          name={state.name}
          score={computeScore(state.answers1, state.answers2, state.bonusAnswer)}
          bonusUnlocked={state.bonusUnlocked}
          onRestart={restart}
        />
      );
    default:
      return <QuizIntro onStart={handleStart} />;
  }
}

// ─────────────────────────────────────────────────────────
// SCREEN — INTRO
// ─────────────────────────────────────────────────────────
function QuizIntro({ onStart }) {
  const [name, setName] = React.useState(Store.get("ea-app:quiz:lastName", "") || "");
  const [error, setError] = React.useState("");

  const handleSubmit = () => {
    if (name.trim().length < 2) {
      setError("Indiquez votre prénom et nom.");
      return;
    }
    Store.set("ea-app:quiz:lastName", name.trim());
    onStart(name.trim());
  };

  return (
    <div style={{ position: "relative", overflow: "hidden", minHeight: "100vh" }}>
      <WashBg hue={350} opacity={0.20} />
      <Page>
        <AppHeader eyebrow="Le Grand Quiz" title="Tu nous connais ?" />
        <div style={{ textAlign: "center", fontFamily: A.italic, fontStyle: "italic", fontSize: 16, color: A.inkSoft, marginTop: 6, maxWidth: 480, margin: "8px auto 0", lineHeight: 1.55 }}>
          Trente cartes. Deux manches. Cinq minutes. <br/>
          Vérifions si vous nous connaissez aussi bien que vous le prétendez.
        </div>

        {/* Carte d'illustration de la couverture du quiz */}
        <div style={{
          margin: "36px auto 28px", maxWidth: 320, aspectRatio: "5/7",
          background: A.white, border: `1px solid ${A.rule}`, borderRadius: 6,
          boxShadow: A.shadowCard, padding: "24px 20px",
          display: "flex", flexDirection: "column", justifyContent: "space-between",
          position: "relative", overflow: "hidden",
        }}>
          <div style={{ position: "absolute", top: 12, left: 14, color: A.rouge, fontSize: 18, opacity: 0.7 }}>♥</div>
          <div style={{ position: "absolute", bottom: 12, right: 14, color: A.rouge, fontSize: 18, opacity: 0.7, transform: "rotate(180deg)" }}>♥</div>

          <div style={{ textAlign: "center", marginTop: 24 }}>
            <div className="eyebrow" style={{ fontSize: 9, letterSpacing: 3 }}>Édition unique</div>
            <div style={{ fontFamily: A.display, fontStyle: "italic", fontSize: 36, color: A.ink, lineHeight: 0.95, margin: "10px 0 4px", letterSpacing: -1 }}>
              Le Grand<br/>Quiz
            </div>
            <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 14, color: A.or, margin: "8px 0" }}>
              E <span style={{ fontSize: 16 }}>&amp;</span> A
            </div>
          </div>

          <div style={{ textAlign: "center" }}>
            <div style={{ fontSize: 50, color: A.rouge, lineHeight: 0.9, fontFamily: A.display, fontStyle: "italic" }}>♥</div>
            <div className="eyebrow" style={{ fontSize: 8, letterSpacing: 2.5, marginTop: 6 }}>30 cartes · 2 manches</div>
          </div>
        </div>

        <div style={{ background: A.card, padding: "22px 22px", border: `1px solid ${A.ruleSoft}`, boxShadow: A.shadow }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Votre identité</div>
          <input
            type="text" value={name} onChange={(e) => { setName(e.target.value); setError(""); }}
            placeholder="Prénom et nom"
            onKeyDown={(e) => { if (e.key === "Enter") handleSubmit(); }}
            style={{
              width: "100%", padding: "14px 16px", background: A.paper,
              border: `1.5px solid ${error ? A.rouge : A.ruleSoft}`,
              fontFamily: A.sans, fontSize: 15, color: A.ink, outline: "none",
              marginBottom: error ? 8 : 16,
            }}
          />
          {error && <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 13, color: A.rouge, marginBottom: 12 }}>{error}</div>}

          <ButtonA primary full onClick={handleSubmit}>
            ♥ Tirer ma première carte
          </ButtonA>

          <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 12, color: A.inkMute, textAlign: "center", marginTop: 14, lineHeight: 1.5 }}>
            Vous ne pouvez répondre qu'<em>une seule fois</em>. <br/>
            Les bonnes réponses seront révélées après le mariage.
          </div>
        </div>

        {/* Aperçu badges */}
        <div style={{ marginTop: 32, textAlign: "center" }}>
          <div className="eyebrow" style={{ marginBottom: 14 }}>Badges à débloquer</div>
          <div style={{ display: "flex", gap: 8, justifyContent: "center", flexWrap: "wrap" }}>
            {QUIZ_DATA.badges.slice().reverse().map((b, i) => (
              <div key={b.name} style={{
                fontFamily: A.italic, fontStyle: "italic", fontSize: 13,
                padding: "8px 12px", background: A.paper,
                border: `1px solid ${i === 0 ? A.rouge : A.ruleSoft}`,
                color: i === 0 ? A.rougeDeep : A.inkSoft,
                fontWeight: i === 0 ? 600 : 400,
              }}>
                {b.name}
              </div>
            ))}
          </div>
        </div>
      </Page>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// SCREEN — QUESTION MANCHE 1 (QCM)
// ─────────────────────────────────────────────────────────
function QuizQuestionScreen({ index, question, selected, total, onSelect, onPrev, onNext }) {
  const progress = ((index + 1) / total) * 100;
  return (
    <div style={{ position: "relative", overflow: "hidden", minHeight: "100vh" }}>
      <WashBg hue={350} opacity={0.16} />
      <Page>
        {/* Header */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8 }}>
          <span style={{ fontFamily: A.mono, fontSize: 10, letterSpacing: 2.5, color: A.orDeep, textTransform: "uppercase" }}>
            Manche 1 · Connaissance
          </span>
          <span style={{ fontFamily: A.mono, fontSize: 11, color: A.ink, fontWeight: 600 }}>
            {String(index + 1).padStart(2, "0")} / {String(total).padStart(2, "0")}
          </span>
        </div>
        <div style={{ height: 2, background: A.ruleSoft, marginTop: 10, marginBottom: 24, overflow: "hidden" }}>
          <div style={{ width: `${progress}%`, height: "100%", background: A.rouge, transition: "width .35s ease" }}/>
        </div>

        {/* Carte question */}
        <QuestionCard key={question.id} question={question} selected={selected} onSelect={onSelect} />

        {/* Nav */}
        <div style={{ display: "flex", gap: 10, marginTop: 22 }}>
          <ButtonA onClick={onPrev} style={{ opacity: onPrev ? 1 : 0.3, pointerEvents: onPrev ? "auto" : "none" }}>
            ← Précédent
          </ButtonA>
          <ButtonA primary onClick={onNext} style={{
            flex: 1,
            opacity: selected != null ? 1 : 0.5,
            pointerEvents: selected != null ? "auto" : "none",
          }}>
            {index === total - 1 ? "Fin de Manche 1 →" : "Suivante →"}
          </ButtonA>
        </div>
      </Page>
    </div>
  );
}

// Composant Carte question (réutilisé pour bonus aussi)
function QuestionCard({ question, selected, onSelect }) {
  return (
    <div className="anim-up" style={{
      background: A.white, border: `1px solid ${A.rule}`, borderRadius: 6,
      padding: "30px 26px 26px", boxShadow: A.shadowCard,
      position: "relative", overflow: "hidden",
    }}>
      <div style={{ position: "absolute", top: 14, left: 16, color: A.rouge, fontSize: 22, opacity: 0.55, lineHeight: 1 }}>♥</div>
      <div style={{ position: "absolute", bottom: 14, right: 16, color: A.rouge, fontSize: 22, opacity: 0.55, lineHeight: 1, transform: "rotate(180deg)" }}>♥</div>

      <div className="eyebrow" style={{ fontSize: 9, letterSpacing: 2.5, textAlign: "center", marginBottom: 8 }}>
        {question.category} · <span style={{ color: A.inkMute }}>{question.difficulty}</span>
      </div>

      <div style={{
        fontFamily: A.display, fontStyle: "italic", fontWeight: 400,
        fontSize: "clamp(22px, 5.5vw, 30px)", lineHeight: 1.2, letterSpacing: -0.5,
        color: A.ink, textAlign: "center",
        margin: "18px 0 26px",
        textWrap: "balance",
      }}>
        {question.text}
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {question.options.map((opt, idx) => {
          const isSelected = selected === idx;
          const isPlaceholder = opt === "—";
          return (
            <button
              key={idx}
              onClick={() => !isPlaceholder && onSelect(idx)}
              disabled={isPlaceholder}
              style={{
                textAlign: "left", padding: "13px 16px",
                background: isSelected ? A.ink : (isPlaceholder ? "transparent" : A.paper),
                color: isSelected ? A.white : (isPlaceholder ? A.inkMute : A.ink),
                border: `1.5px solid ${isSelected ? A.ink : (isPlaceholder ? A.ruleSoft : A.ruleSoft)}`,
                fontFamily: A.sans, fontSize: 14, fontWeight: isSelected ? 600 : 400,
                cursor: isPlaceholder ? "not-allowed" : "pointer",
                transition: "all .15s",
                display: "flex", alignItems: "center", gap: 12,
                fontStyle: isPlaceholder ? "italic" : "normal",
              }}
            >
              <span style={{
                width: 22, height: 22, flexShrink: 0,
                border: `1.5px solid ${isSelected ? A.white : A.inkMute}`,
                background: isSelected ? A.or : "transparent",
                display: "flex", alignItems: "center", justifyContent: "center",
                fontFamily: A.display, fontSize: 11, fontWeight: 700,
                color: isSelected ? A.ink : A.inkMute,
                borderRadius: 2,
              }}>
                {String.fromCharCode(65 + idx)}
              </span>
              <span>{isPlaceholder ? "(à compléter par le couple)" : opt}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// SCREEN — TRANSITION (avec easter egg Phila)
// ─────────────────────────────────────────────────────────
function QuizTransition({ name, onContinue, onUnlockBonus }) {
  const [taps, setTaps] = React.useState(0);
  const [showHint, setShowHint] = React.useState(false);

  const handleHeartTap = () => {
    const next = taps + 1;
    setTaps(next);
    if (next >= 3) {
      // Easter egg unlock
      setTimeout(onUnlockBonus, 300);
    } else if (next === 2) {
      setShowHint(true);
    }
  };

  return (
    <div style={{ position: "relative", overflow: "hidden", minHeight: "100vh" }}>
      <WashBg hue={45} opacity={0.20} />
      <Page padding="60px 0 120px">
        <div style={{ textAlign: "center", animation: "a-up 0.6s ease both" }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Pause</div>
          <div className="display-bold" style={{ fontSize: 38, lineHeight: 1, color: A.ink, marginBottom: 16 }}>
            Manche 1<br/>terminée.
          </div>
          <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 17, color: A.inkSoft, maxWidth: 400, margin: "0 auto 36px", lineHeight: 1.5 }}>
            Vous avez fait le tour de ce que vous <em>savez</em>. <br/>
            Place à ce que vous <em>devinez</em>.
          </div>

          {/* Heart tapable (easter egg) */}
          <div
            onClick={handleHeartTap}
            style={{
              fontFamily: A.display, fontSize: 100, color: A.rouge,
              lineHeight: 0.9, cursor: "pointer", userSelect: "none",
              transition: "transform .15s, color .15s",
              transform: taps > 0 ? `scale(${1 + taps * 0.05})` : "scale(1)",
              filter: taps >= 3 ? "drop-shadow(0 0 12px " + A.rouge + ")" : "none",
            }}
            title="..."
          >
            ♥
          </div>

          {showHint && taps < 3 && (
            <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 12, color: A.inkMute, marginTop: 8, opacity: 0.7 }}>
              … encore une fois ?
            </div>
          )}

          <div style={{ marginTop: 36 }}>
            <ButtonA primary onClick={onContinue}>
              ♣ Manche 2 · Qui l'a dit ?
            </ButtonA>
          </div>

          <div style={{ marginTop: 24, fontFamily: A.italic, fontStyle: "italic", fontSize: 13, color: A.inkMute }}>
            {name && <>Courage {name.split(" ")[0]} — encore 15 cartes.</>}
          </div>
        </div>
      </Page>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// SCREEN — BONUS PHILA
// ─────────────────────────────────────────────────────────
function QuizBonusScreen({ question, onAnswer, onSkip }) {
  const [selected, setSelected] = React.useState(null);
  return (
    <div style={{ position: "relative", overflow: "hidden", minHeight: "100vh" }}>
      <WashBg hue={45} opacity={0.22} />
      <Page>
        <div style={{ textAlign: "center", marginTop: 8 }}>
          <span style={{ fontFamily: A.mono, fontSize: 10, letterSpacing: 2.5, color: A.or, textTransform: "uppercase" }}>
            <Phila variant="head" size={14} style={{ marginRight: 6, verticalAlign: "-3px" }} />Question secrète déverrouillée
          </span>
        </div>
        <div style={{ height: 2, background: A.or, marginTop: 10, marginBottom: 24, opacity: 0.5 }}/>

        <div className="anim-up" style={{
          background: A.ink, color: A.white, borderRadius: 6,
          padding: "32px 26px 28px", boxShadow: A.shadowCard,
          position: "relative", overflow: "hidden",
        }}>
          <Phila variant="head" size={30} style={{ position: "absolute", top: 14, left: 16, opacity: 0.7, transform: "rotate(-8deg)" }} />
          <Phila variant="head" size={30} style={{ position: "absolute", bottom: 14, right: 16, opacity: 0.7, transform: "scaleX(-1) rotate(-8deg)" }} />

          <div style={{ fontFamily: A.mono, fontSize: 9, letterSpacing: 2.5, textAlign: "center", color: A.or, marginBottom: 8 }}>
            {question.category}
          </div>
          <div style={{
            fontFamily: A.display, fontStyle: "italic", fontWeight: 400,
            fontSize: 26, lineHeight: 1.2, color: A.white, textAlign: "center",
            margin: "16px 0 26px", textWrap: "balance",
          }}>
            {question.text}
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {question.options.map((opt, idx) => {
              const isSelected = selected === idx;
              return (
                <button
                  key={idx}
                  onClick={() => setSelected(idx)}
                  style={{
                    textAlign: "left", padding: "13px 16px",
                    background: isSelected ? A.or : "rgba(255,255,255,0.06)",
                    color: isSelected ? A.ink : A.white,
                    border: `1.5px solid ${isSelected ? A.or : "rgba(255,255,255,0.15)"}`,
                    fontFamily: A.sans, fontSize: 14, fontWeight: isSelected ? 600 : 400,
                    cursor: "pointer", transition: "all .15s",
                  }}
                >
                  {opt}
                </button>
              );
            })}
          </div>
        </div>

        <div style={{ marginTop: 24, display: "flex", gap: 10 }}>
          <ButtonA onClick={onSkip} style={{ borderColor: "rgba(0,0,0,0.3)" }}>Passer</ButtonA>
          <ButtonA primary onClick={() => onAnswer(selected)} style={{
            flex: 1,
            opacity: selected != null ? 1 : 0.5,
            pointerEvents: selected != null ? "auto" : "none",
          }}>
            <Phila variant="head" size={16} style={{ marginRight: 6, verticalAlign: "-3px" }} />Valider et continuer
          </ButtonA>
        </div>

        <div style={{ marginTop: 18, fontFamily: A.italic, fontStyle: "italic", fontSize: 12, color: A.inkMute, textAlign: "center", lineHeight: 1.55 }}>
          La bonne réponse à cette question secrète ne compte pas pour le classement, <br/>
          mais débloque une surprise sur l'écran final.
        </div>
      </Page>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// SCREEN — MANCHE 2 (QUI L'A DIT)
// ─────────────────────────────────────────────────────────
function QuizQldScreen({ index, phrase, selected, total, onSelect, onPrev, onNext }) {
  const progress = ((index + 1) / total) * 100;
  return (
    <div style={{ position: "relative", overflow: "hidden", minHeight: "100vh" }}>
      <WashBg hue={120} opacity={0.16} />
      <Page>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8 }}>
          <span style={{ fontFamily: A.mono, fontSize: 10, letterSpacing: 2.5, color: A.orDeep, textTransform: "uppercase" }}>
            Manche 2 · Intuition
          </span>
          <span style={{ fontFamily: A.mono, fontSize: 11, color: A.ink, fontWeight: 600 }}>
            {String(index + 1).padStart(2, "0")} / {String(total).padStart(2, "0")}
          </span>
        </div>
        <div style={{ height: 2, background: A.ruleSoft, marginTop: 10, marginBottom: 24, overflow: "hidden" }}>
          <div style={{ width: `${progress}%`, height: "100%", background: A.sage, transition: "width .35s ease" }}/>
        </div>

        <div key={phrase.id} className="anim-up" style={{
          background: `linear-gradient(135deg, ${A.paper} 0%, #F0EBDF 100%)`,
          borderRadius: 6, padding: "40px 30px 32px",
          boxShadow: A.shadowCard, textAlign: "center",
          minHeight: 280, display: "flex", flexDirection: "column", justifyContent: "center",
        }}>
          <div style={{ fontFamily: A.display, fontStyle: "italic", fontSize: 80, color: A.or, lineHeight: 0.4, marginBottom: 8 }}>"</div>
          <div style={{
            fontFamily: A.italic, fontStyle: "italic", fontWeight: 400,
            fontSize: "clamp(18px, 4.8vw, 22px)", lineHeight: 1.4,
            color: A.ink, margin: "0 auto", maxWidth: 460, textWrap: "balance",
          }}>
            {phrase.text}
          </div>
          <div style={{ fontFamily: A.display, fontStyle: "italic", fontSize: 80, color: A.or, lineHeight: 0.4, marginTop: 20, transform: "rotate(180deg)" }}>"</div>
        </div>

        {/* Choix Enora / Antoine */}
        <div style={{ display: "flex", gap: 12, marginTop: 26 }}>
          {[
            { side: "E", label: "Enora",   color: A.rouge },
            { side: "A", label: "Antoine", color: A.sage  },
          ].map((c) => {
            const isSelected = selected === c.side;
            return (
              <button
                key={c.side}
                onClick={() => onSelect(c.side)}
                style={{
                  flex: 1, padding: "20px 14px",
                  background: isSelected ? c.color : A.white,
                  color: isSelected ? A.white : A.ink,
                  border: `1.5px solid ${isSelected ? c.color : A.rule}`,
                  cursor: "pointer", transition: "all .15s",
                  borderRadius: 4,
                  display: "flex", flexDirection: "column", alignItems: "center", gap: 6,
                }}
              >
                <span style={{ fontFamily: A.display, fontStyle: "italic", fontSize: 28, fontWeight: 400, letterSpacing: -0.5 }}>
                  {c.label}
                </span>
                <span style={{ fontFamily: A.mono, fontSize: 9, letterSpacing: 2, opacity: 0.8 }}>
                  {c.side === "E" ? "Côté pelouse" : "Côté tatami"}
                </span>
              </button>
            );
          })}
        </div>

        <div style={{ display: "flex", gap: 10, marginTop: 22 }}>
          <ButtonA onClick={onPrev} style={{ opacity: onPrev ? 1 : 0.3, pointerEvents: onPrev ? "auto" : "none" }}>
            ← Précédent
          </ButtonA>
          <ButtonA primary onClick={onNext} style={{
            flex: 1,
            opacity: selected != null ? 1 : 0.5,
            pointerEvents: selected != null ? "auto" : "none",
          }}>
            {index === total - 1 ? "✦ Voir mon résultat" : "Suivante →"}
          </ButtonA>
        </div>
      </Page>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// SCREEN — RÉSULTAT FINAL
// ─────────────────────────────────────────────────────────
function QuizResult({ name, score, bonusUnlocked, onRestart }) {
  const total = QUIZ_DATA.questions.length + QUIZ_DATA.qld.length; // 30
  const badge = getBadge(score);
  const allResults = Store.get(QUIZ_RESULTS_KEY, []);

  // Leaderboard : merge real results + fake demo data
  const merged = [
    ...allResults.map((r) => ({ name: r.name, score: r.score, isMe: r.name.toLowerCase() === name.toLowerCase() })),
    ...QUIZ_DATA.fakeLeaderboard.filter(
      (f) => !allResults.some((r) => r.name.toLowerCase() === f.name.toLowerCase())
    ),
  ];
  const sorted = merged.sort((a, b) => b.score - a.score);
  const myRank = sorted.findIndex((r) => r.isMe) + 1 || sorted.findIndex((r) => r.name === name) + 1;
  const top10 = sorted.slice(0, 10);

  return (
    <div style={{ position: "relative", overflow: "hidden", minHeight: "100vh" }}>
      <WashBg hue={45} opacity={0.24} />
      <Page>
        <div style={{ textAlign: "center", marginTop: 16 }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Votre résultat</div>
          <div style={{
            fontFamily: A.display, fontStyle: "italic", fontWeight: 400,
            fontSize: "clamp(40px, 11vw, 60px)", lineHeight: 0.95,
            color: A.ink, letterSpacing: -1.5, margin: "8px 0",
            textWrap: "balance",
          }}>
            {badge.name}
          </div>
          <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 17, color: A.inkSoft, lineHeight: 1.45, maxWidth: 380, margin: "8px auto 0" }}>
            {badge.desc}
          </div>
        </div>

        {/* Score géant */}
        <div className="anim-up" style={{
          margin: "32px auto", background: A.ink, color: A.white,
          padding: "30px 24px", textAlign: "center",
          position: "relative", overflow: "hidden",
        }}>
          <div style={{ position: "absolute", top: 12, left: 14, color: A.or, fontSize: 16, opacity: 0.4 }}>♥</div>
          <div style={{ position: "absolute", bottom: 12, right: 14, color: A.or, fontSize: 16, opacity: 0.4, transform: "rotate(180deg)" }}>♥</div>
          <div style={{ fontFamily: A.mono, fontSize: 9, letterSpacing: 3, color: A.or, marginBottom: 12 }}>SCORE TOTAL</div>
          <div style={{
            fontFamily: A.display, fontStyle: "italic", fontWeight: 700,
            fontSize: 84, lineHeight: 0.9, color: A.or, letterSpacing: -2,
          }}>{score}</div>
          <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 15, color: "rgba(255,255,255,0.7)", marginTop: 4 }}>
            sur {total} cartes tirées
          </div>
          {myRank > 0 && (
            <div style={{ fontFamily: A.mono, fontSize: 10, letterSpacing: 2, color: A.or, marginTop: 14, textTransform: "uppercase" }}>
              Vous êtes {myRank}<sup>{myRank === 1 ? "er" : "e"}</sup> sur {sorted.length}
            </div>
          )}
        </div>

        {/* Bonus Phila unlocked */}
        {bonusUnlocked && (
          <div className="anim-up" style={{
            background: A.or, color: A.ink, padding: "22px 22px",
            margin: "28px 0", borderRadius: 4, textAlign: "center",
            border: `1px solid ${A.orDeep}`,
          }}>
            <Phila variant="wide" size={78} style={{ display: "block", margin: "0 auto 10px" }} />
            <div className="display-bold" style={{ fontSize: 22, color: A.ink, marginBottom: 6 }}>
              Club Phila
            </div>
            <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 14, color: A.ink, lineHeight: 1.5, maxWidth: 320, margin: "0 auto" }}>
              "Vous avez l'œil. Bienvenue dans le club secret des amis de Phila."
            </div>
            <div style={{ marginTop: 14, padding: "8px 12px", background: "rgba(0,0,0,0.08)", display: "inline-block", borderRadius: 2 }}>
              <span style={{ fontFamily: A.mono, fontSize: 9, letterSpacing: 2, color: A.ink }}>
                🐱 Photo bonus de Phila à venir
              </span>
            </div>
          </div>
        )}

        {/* Top 10 */}
        <div style={{ marginTop: 32 }}>
          <div className="eyebrow" style={{ textAlign: "center", marginBottom: 16 }}>Classement · Top 10</div>
          <div style={{ background: A.card, border: `1px solid ${A.ruleSoft}`, padding: "12px 0" }}>
            {top10.map((r, i) => {
              const isMe = r.isMe || r.name === name;
              return (
                <div key={r.name + i} style={{
                  display: "flex", gap: 12, alignItems: "center",
                  padding: "10px 18px",
                  background: isMe ? A.rougePale : "transparent",
                  borderTop: i > 0 ? `1px solid ${A.ruleSoft}` : "none",
                }}>
                  <div style={{
                    fontFamily: A.display, fontStyle: "italic",
                    fontSize: 18, width: 26, textAlign: "center",
                    color: i === 0 ? A.or : (i === 1 || i === 2 ? A.rouge : A.inkMute),
                    fontWeight: i < 3 ? 700 : 400,
                  }}>
                    {String(i + 1).padStart(2, "0")}
                  </div>
                  <div style={{
                    flex: 1, fontFamily: A.sans, fontSize: 14,
                    color: isMe ? A.rougeDeep : A.ink,
                    fontWeight: isMe ? 700 : 500,
                  }}>
                    {abbrevName(r.name)}
                    {isMe && <span style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 12, color: A.rougeDeep, marginLeft: 6 }}>· vous</span>}
                  </div>
                  <div style={{ fontFamily: A.mono, fontSize: 14, color: A.or, fontWeight: 600 }}>
                    {r.score}
                  </div>
                </div>
              );
            })}
          </div>
          <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 12, color: A.inkMute, textAlign: "center", marginTop: 12, lineHeight: 1.5 }}>
            Les classements affichés sont une démonstration. <br/>
            Le vrai scoreboard sera mis à jour en temps réel après le branchement backend.
          </div>
        </div>

        {/* Actions */}
        <div style={{ marginTop: 32, display: "flex", gap: 10, justifyContent: "center", flexWrap: "wrap" }}>
          <ButtonA onClick={onRestart}>↺ Refaire le quiz</ButtonA>
          <a href="App invité Enora & Antoine.html" style={{
            display: "inline-flex", alignItems: "center", padding: "12px 22px",
            background: A.ink, color: A.white, textDecoration: "none",
            fontFamily: A.mono, fontSize: 11, letterSpacing: 2.5, textTransform: "uppercase", fontWeight: 600,
          }}>
            ♥ Retour à l'app
          </a>
        </div>

        <div style={{ marginTop: 28, padding: "16px 18px", background: A.paper, textAlign: "center", border: `1px solid ${A.ruleSoft}` }}>
          <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 13, color: A.inkSoft, lineHeight: 1.55 }}>
            Les bonnes réponses seront révélées <br/>après le mariage, le <strong style={{ color: A.ink }}>22 août 2027</strong>.
          </div>
        </div>
      </Page>
    </div>
  );
}

Object.assign(window, { QuizPage });
