// app/carnet.jsx — Le Carnet scellé : capsules datées (texte/voix/photo)
// Stockage local en attendant le backend.
//
// Note : le concours d'anecdotes est maintenant un onglet à part entière
// (★ Anecdotes), pas un sous-onglet du Carnet. Cf. app/anecdotes.jsx.

const CARNET_KEY        = "ea-app:carnet:capsules";
const CARNET_AUTHOR_KEY = "ea-app:carnet:author";

// ─── Définition des dates d'ouverture ───
const OPEN_DATES = [
  { id: "jminus1", label: "J-1",      title: "Le matin du mariage",  date: "20 août 2027",
    desc: "Lu en privé par Enora & Antoine, au réveil, avant la journée.",
    eyebrow: "Un mot pour les rassurer", color: "#B85A4E" },
  { id: "jourJ",   label: "Jour J",   title: "Pendant la soirée",    date: "21 août 2027",
    desc: "Lu pendant le repas ou la soirée, à voix haute si vous le souhaitez.",
    eyebrow: "Un mot pour la fête", color: "#BE9A48" },
  { id: "un_an",   label: "+ 1 an",   title: "Premier anniversaire", date: "21 août 2028",
    desc: "Ouvert un an après — vous serez surpris·e de ce que vous aurez écrit.",
    eyebrow: "Pour le premier tour de soleil", color: "#7E8F75" },
  { id: "dix_ans", label: "+ 10 ans", title: "Dixième anniversaire", date: "21 août 2037",
    desc: "Une lettre du futur — qui sera-t-on tous en 2037 ?",
    eyebrow: "Pour les noces d'étain", color: "#8C3A2E" },
];

const CONTENT_TYPES = [
  { id: "text",  icon: "✎", label: "Texte",   desc: "Quelques lignes, un mot, un poème." },
  { id: "audio", icon: "♪", label: "Voix",    desc: "Jusqu'à 30 secondes en audio." },
  { id: "photo", icon: "☐", label: "Photo",   desc: "Une image accompagnée d'une légende." },
];

// ─────────────────────────────────────────────────────────
// PAGE PRINCIPALE — capsules scellées uniquement
// ─────────────────────────────────────────────────────────
function CarnetPage() {
  return (
    <div style={{ position: "relative", overflow: "hidden", minHeight: "100vh" }}>
      <WashBg hue={45} opacity={0.18}/>
      <Page padding="20px 0 120px">
        <AppHeader eyebrow="Le Carnet scellé" title="Un mot pour nous" />
        <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 }}>
          Écrivez-nous, à scellement immédiat, à ouvrir plus tard. <br/>
          Le 21 août 2027, dans un an, ou dans dix.
        </div>
        <div style={{ marginTop: 28 }}>
          <CapsulesView />
        </div>
      </Page>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// CAPSULES VIEW — state machine de création + liste
// ─────────────────────────────────────────────────────────
function CapsulesView() {
  // Pré-remplit l'auteur depuis l'identité globale (fallback localStorage)
  const { identity } = useGuest();
  const [capsules, setCapsules] = React.useState(() => Store.get(CARNET_KEY, []));
  const [author, setAuthor]     = React.useState(() => identity?.name || Store.get(CARNET_AUTHOR_KEY, ""));
  React.useEffect(() => { if (identity?.name && !author) setAuthor(identity.name); }, [identity?.name]);
  const [step, setStep] = React.useState("intro"); // intro · date · type · compose · confirm · done
  const [dateOpen, setDateOpen] = React.useState(null);
  const [contentType, setContentType] = React.useState(null);
  const [content, setContent] = React.useState("");
  const [caption, setCaption] = React.useState("");

  const myCapsules = capsules.filter((c) => c.author.toLowerCase() === author.toLowerCase());

  const reset = () => {
    setStep("intro");
    setDateOpen(null); setContentType(null);
    setContent(""); setCaption("");
  };

  const seal = () => {
    if (!author.trim()) return;
    const entry = {
      id: "cap-" + Date.now() + "-" + Math.random().toString(36).slice(2, 7),
      author: author.trim(),
      type: contentType,
      content,
      caption: caption.trim(),
      dateOpen,
      sealed_at: new Date().toISOString(),
    };
    const next = [...capsules, entry];
    setCapsules(next);
    Store.set(CARNET_KEY, next);
    Store.set(CARNET_AUTHOR_KEY, author.trim());
    setStep("done");
  };

  // ── Routeur ──
  if (step === "date")     return <StepDate    selected={dateOpen}     onSelect={(d) => { setDateOpen(d); setStep("type"); }} onBack={() => setStep("intro")} />;
  if (step === "type")     return <StepType    selected={contentType}  onSelect={(t) => { setContentType(t); setStep("compose"); }} onBack={() => setStep("date")} />;
  if (step === "compose")  return <StepCompose type={contentType} content={content} caption={caption} onContent={setContent} onCaption={setCaption} onBack={() => setStep("type")} onNext={() => setStep("confirm")} />;
  if (step === "confirm")  return <StepConfirm author={author} setAuthor={setAuthor} dateOpen={dateOpen} type={contentType} content={content} caption={caption} onBack={() => setStep("compose")} onSeal={seal} />;
  if (step === "done")     return <StepDone dateOpen={dateOpen} onCreateAnother={reset} />;

  // ── INTRO ──
  return (
    <div className="anim-up">
      {/* Visuel : enveloppe scellée */}
      <div style={{
        margin: "20px auto", maxWidth: 320,
        background: `linear-gradient(135deg, ${A.white} 0%, ${A.paper} 100%)`,
        border: `1.5px solid ${A.rule}`, borderRadius: 4,
        padding: "44px 28px 40px",
        boxShadow: A.shadowCard, position: "relative", overflow: "hidden",
        textAlign: "center",
      }}>
        <div style={{ position: "absolute", top: 14, left: 16, color: A.or, fontSize: 18, opacity: 0.45 }}>♥</div>
        <div style={{ position: "absolute", top: 14, right: 16, color: A.or, fontSize: 18, opacity: 0.45 }}>♥</div>
        <div style={{ position: "absolute", bottom: 14, left: 16, color: A.or, fontSize: 18, opacity: 0.45, transform: "rotate(180deg)" }}>♥</div>
        <div style={{ position: "absolute", bottom: 14, right: 16, color: A.or, fontSize: 18, opacity: 0.45, transform: "rotate(180deg)" }}>♥</div>

        <div className="eyebrow" style={{ fontSize: 9, letterSpacing: 3 }}>Pour Enora &amp; Antoine</div>
        <div style={{
          fontFamily: A.display, fontStyle: "italic", fontSize: 42,
          color: A.ink, letterSpacing: -1, lineHeight: 0.9,
          margin: "16px 0 14px",
        }}>
          Scellez<br/>un message.
        </div>
        <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 14, color: A.inkSoft, lineHeight: 1.5, maxWidth: 240, margin: "0 auto 26px" }}>
          Texte, voix ou photo. Choisissez quand il sera ouvert : avant le mariage, le jour J, dans 1 an, dans 10 ans.
        </div>
        <div style={{
          display: "inline-block", padding: "4px 12px",
          background: A.rouge, color: A.white,
          fontFamily: A.mono, fontSize: 9, letterSpacing: 2.5, textTransform: "uppercase",
          borderRadius: 2,
        }}>
          ♥ SCELLÉ À VIE ♥
        </div>
      </div>

      <div style={{ marginTop: 26, textAlign: "center" }}>
        <ButtonA primary onClick={() => setStep("date")}>
          ✎ Sceller un nouveau message
        </ButtonA>
      </div>

      {/* Liste capsules existantes de l'utilisateur */}
      {myCapsules.length > 0 && (
        <div style={{ marginTop: 40 }}>
          <div className="eyebrow" style={{ textAlign: "center", marginBottom: 14 }}>
            Vos {myCapsules.length} capsule{myCapsules.length > 1 ? "s" : ""} scellée{myCapsules.length > 1 ? "s" : ""}
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {myCapsules.map((c) => <CapsuleSealedCard key={c.id} capsule={c} />)}
          </div>
        </div>
      )}

      {/* Comment ça marche */}
      <div style={{ marginTop: 36, padding: "20px 22px", background: A.ink, color: A.white }}>
        <div className="eyebrow" style={{ marginBottom: 12, color: A.or }}>Comment ça marche</div>
        <ol style={{ paddingLeft: 22, fontFamily: A.sans, fontSize: 13.5, lineHeight: 1.7, color: "rgba(255,255,255,0.78)", margin: 0 }}>
          <li>Choisissez <em style={{ color: A.white }}>quand</em> le message sera ouvert.</li>
          <li>Choisissez le <em style={{ color: A.white }}>format</em> : texte, voix ou photo.</li>
          <li><em style={{ color: A.white }}>Composez</em>. Vous pouvez fermer l'app, on garde votre brouillon.</li>
          <li><em style={{ color: A.white }}>Scellez</em>. C'est définitif.</li>
        </ol>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Cartes "capsule scellée" (preview only)
// ─────────────────────────────────────────────────────────
function CapsuleSealedCard({ capsule }) {
  const date = OPEN_DATES.find((d) => d.id === capsule.dateOpen);
  const type = CONTENT_TYPES.find((t) => t.id === capsule.type);
  return (
    <div style={{
      background: A.card, border: `1px solid ${A.ruleSoft}`, padding: "16px 18px",
      display: "flex", alignItems: "center", gap: 14,
      position: "relative", overflow: "hidden",
    }}>
      <div style={{
        width: 42, height: 42, borderRadius: "50%",
        border: `1.5px solid ${date.color}`, background: date.color + "11",
        display: "flex", alignItems: "center", justifyContent: "center",
        fontFamily: A.display, fontWeight: 700, fontSize: 14, color: date.color,
        flexShrink: 0, textAlign: "center", lineHeight: 1.1,
      }}>
        {date.label.replace("+ ", "+")}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: A.mono, fontSize: 9, letterSpacing: 2, color: A.inkMute, textTransform: "uppercase" }}>
          {type.icon} {type.label} · scellé{capsule.type === "photo" ? "e" : ""}
        </div>
        <div style={{ fontFamily: A.display, fontWeight: 700, fontSize: 15, color: A.ink, marginTop: 2 }}>
          S'ouvre le {date.date}
        </div>
      </div>
      <div style={{ color: A.or, fontSize: 18 }}>🔒</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// STEP 1 — Choisir la date
// ─────────────────────────────────────────────────────────
function StepDate({ selected, onSelect, onBack }) {
  return (
    <div className="anim-up">
      <StepHeader step={1} total={4} title="Quand voulez-vous qu'on l'ouvre ?" sub="Choisissez votre fenêtre temporelle. Chaque message attend sa date." onBack={onBack} />

      <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 26 }}>
        {OPEN_DATES.map((d) => {
          const isSel = selected === d.id;
          return (
            <button key={d.id} onClick={() => onSelect(d.id)} style={{
              textAlign: "left", padding: "20px 22px", cursor: "pointer",
              background: isSel ? A.ink : A.white,
              color: isSel ? A.white : A.ink,
              border: `1.5px solid ${isSel ? A.ink : A.ruleSoft}`,
              borderLeft: `4px solid ${d.color}`,
              fontFamily: A.sans,
              display: "flex", gap: 16, alignItems: "center",
              transition: "all .15s",
            }}>
              <div style={{
                width: 56, height: 56, borderRadius: 4,
                background: d.color, color: A.white,
                display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
                flexShrink: 0,
              }}>
                <div style={{ fontFamily: A.display, fontWeight: 700, fontSize: 17, lineHeight: 1 }}>
                  {d.label.replace("+ ", "+")}
                </div>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: A.mono, fontSize: 9, letterSpacing: 2, color: isSel ? A.or : d.color, textTransform: "uppercase" }}>{d.eyebrow}</div>
                <div style={{ fontFamily: A.display, fontWeight: 700, fontSize: 18, marginTop: 2, lineHeight: 1.2 }}>{d.title}</div>
                <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 13, color: isSel ? "rgba(255,255,255,0.7)" : A.inkSoft, marginTop: 4, lineHeight: 1.4 }}>
                  {d.date} · {d.desc}
                </div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// STEP 2 — Choisir le type de contenu
// ─────────────────────────────────────────────────────────
function StepType({ selected, onSelect, onBack }) {
  return (
    <div className="anim-up">
      <StepHeader step={2} total={4} title="Comment voulez-vous l'écrire ?" sub="Choisissez le format de votre message." onBack={onBack} />

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10, marginTop: 26 }}>
        {CONTENT_TYPES.map((t) => {
          const isSel = selected === t.id;
          return (
            <button key={t.id} onClick={() => onSelect(t.id)} style={{
              padding: "22px 12px 18px", cursor: "pointer",
              background: isSel ? A.ink : A.white,
              color: isSel ? A.white : A.ink,
              border: `1.5px solid ${isSel ? A.ink : A.ruleSoft}`,
              fontFamily: A.sans, textAlign: "center",
              transition: "all .15s",
              display: "flex", flexDirection: "column", alignItems: "center", gap: 8,
            }}>
              <div style={{
                fontFamily: A.display, fontSize: 36, color: isSel ? A.or : A.rouge,
                lineHeight: 1, fontStyle: "italic",
              }}>{t.icon}</div>
              <div style={{ fontFamily: A.display, fontWeight: 700, fontSize: 17, lineHeight: 1 }}>{t.label}</div>
              <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 11, color: isSel ? "rgba(255,255,255,0.7)" : A.inkSoft, lineHeight: 1.4 }}>
                {t.desc}
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// STEP 3 — Composer le contenu (selon type)
// ─────────────────────────────────────────────────────────
function StepCompose({ type, content, caption, onContent, onCaption, onBack, onNext }) {
  const canProceed = (type === "text" && content.trim().length >= 10)
                  || (type === "audio" && content)
                  || (type === "photo" && content);
  return (
    <div className="anim-up">
      <StepHeader step={3} total={4} title="Composez votre message" sub="Prenez le temps qu'il vous faut. Vous pouvez fermer l'app sans tout perdre." onBack={onBack} />

      <div style={{ marginTop: 26 }}>
        {type === "text"  && <ComposeText  content={content} onContent={onContent} />}
        {type === "audio" && <ComposeAudio content={content} onContent={onContent} />}
        {type === "photo" && <ComposePhoto content={content} onContent={onContent} caption={caption} onCaption={onCaption} />}
      </div>

      <div style={{ display: "flex", gap: 10, marginTop: 26 }}>
        <ButtonA onClick={onBack}>← Précédent</ButtonA>
        <ButtonA primary onClick={onNext} style={{
          flex: 1,
          opacity: canProceed ? 1 : 0.5,
          pointerEvents: canProceed ? "auto" : "none",
        }}>
          Aperçu →
        </ButtonA>
      </div>
    </div>
  );
}

// ─── Sous-composant TEXTE ───
function ComposeText({ content, onContent }) {
  const max = 800;
  return (
    <div>
      <textarea
        value={content} onChange={(e) => onContent(e.target.value.slice(0, max))}
        rows="8"
        placeholder="Cher Enora, cher Antoine,&#10;&#10;Je voulais vous dire que…"
        style={{
          width: "100%", padding: "18px 18px",
          background: A.white, border: `1.5px solid ${A.ruleSoft}`,
          fontFamily: A.italic, fontStyle: "italic", fontSize: 16, color: A.ink, outline: "none",
          resize: "vertical", minHeight: 200, lineHeight: 1.6,
        }}
      />
      <div style={{ marginTop: 8, fontFamily: A.mono, fontSize: 10, color: A.inkMute, textAlign: "right" }}>
        {content.length} / {max} caractères
      </div>
    </div>
  );
}

// ─── Sous-composant AUDIO ───
function ComposeAudio({ content, onContent }) {
  const [recording, setRecording] = React.useState(false);
  const [elapsed, setElapsed] = React.useState(0);
  const [error, setError] = React.useState("");
  const recRef   = React.useRef(null);
  const chunksRef = React.useRef([]);
  const streamRef = React.useRef(null);
  const timerRef  = React.useRef(null);

  const MAX_SEC = 30;

  const startRecord = async () => {
    setError("");
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      streamRef.current = stream;
      const rec = new MediaRecorder(stream);
      recRef.current = rec;
      chunksRef.current = [];
      rec.ondataavailable = (e) => chunksRef.current.push(e.data);
      rec.onstop = () => {
        const blob = new Blob(chunksRef.current, { type: "audio/webm" });
        const reader = new FileReader();
        reader.onload = () => onContent(reader.result);
        reader.readAsDataURL(blob);
        stream.getTracks().forEach((t) => t.stop());
      };
      rec.start();
      setRecording(true);
      setElapsed(0);
      timerRef.current = setInterval(() => {
        setElapsed((e) => {
          if (e + 1 >= MAX_SEC) {
            clearInterval(timerRef.current);
            rec.stop();
            setRecording(false);
            return MAX_SEC;
          }
          return e + 1;
        });
      }, 1000);
    } catch (err) {
      setError("Accès au micro refusé. Vérifiez les permissions de votre navigateur.");
    }
  };
  const stopRecord = () => {
    if (recRef.current && recRef.current.state !== "inactive") recRef.current.stop();
    if (timerRef.current) clearInterval(timerRef.current);
    setRecording(false);
  };
  const reset = () => { onContent(""); setElapsed(0); };

  React.useEffect(() => () => stopRecord(), []); // cleanup

  return (
    <div style={{
      background: A.white, border: `1.5px solid ${A.ruleSoft}`,
      padding: "32px 24px 28px", textAlign: "center",
    }}>
      {error && (
        <div style={{ marginBottom: 18, padding: "12px 16px", background: A.rougePale, border: `1px solid ${A.rouge}`, fontFamily: A.italic, fontStyle: "italic", fontSize: 13, color: A.rougeDeep }}>
          {error}
        </div>
      )}

      {/* Display state */}
      <div style={{
        fontFamily: A.display, fontStyle: "italic", fontWeight: 700,
        fontSize: 64, color: recording ? A.rouge : (content ? A.sage : A.inkMute),
        lineHeight: 1, letterSpacing: -2, fontVariantNumeric: "tabular-nums",
      }}>
        {String(Math.floor(elapsed / 60)).padStart(2, "0")}:{String(elapsed % 60).padStart(2, "0")}
      </div>
      <div style={{ fontFamily: A.mono, fontSize: 10, letterSpacing: 2.5, color: A.inkMute, marginTop: 6, textTransform: "uppercase" }}>
        {recording ? "● ENREGISTREMENT" : (content ? "ENREGISTREMENT PRÊT" : "PRÊT À ENREGISTRER")}
      </div>

      {/* Waveform stylisé */}
      <div style={{ display: "flex", justifyContent: "center", gap: 3, margin: "22px 0", height: 36, alignItems: "center" }}>
        {Array.from({ length: 24 }).map((_, i) => {
          const h = recording
            ? (8 + Math.abs(Math.sin(i + elapsed)) * 28)
            : (content ? (8 + Math.abs(Math.sin(i * 0.6)) * 22) : 6);
          return (
            <div key={i} style={{
              width: 3, height: h, borderRadius: 2,
              background: recording ? A.rouge : (content ? A.sage : A.inkMute),
              opacity: recording ? 1 : (content ? 1 : 0.4),
              transition: "height .2s",
            }}/>
          );
        })}
      </div>

      {/* Controls */}
      {!recording && !content && (
        <ButtonA primary onClick={startRecord}>● Lancer l'enregistrement</ButtonA>
      )}
      {recording && (
        <ButtonA primary onClick={stopRecord} style={{ background: A.rougeDeep }}>■ Arrêter</ButtonA>
      )}
      {content && !recording && (
        <div style={{ display: "flex", flexDirection: "column", gap: 12, alignItems: "center" }}>
          <audio src={content} controls style={{ width: "100%", maxWidth: 320 }}/>
          <ButtonA onClick={reset}>↺ Refaire</ButtonA>
        </div>
      )}

      <div style={{ marginTop: 18, fontFamily: A.italic, fontStyle: "italic", fontSize: 12, color: A.inkMute, lineHeight: 1.4 }}>
        Durée max : 30 secondes. L'enregistrement reste dans votre navigateur.
      </div>
    </div>
  );
}

// ─── Sous-composant PHOTO ───
function ComposePhoto({ content, onContent, caption, onCaption }) {
  const [busy, setBusy] = React.useState(false);
  const fileRef = React.useRef(null);

  const handleFile = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setBusy(true);
    const reader = new FileReader();
    reader.onload = () => {
      const img = new Image();
      img.onload = () => {
        // Resize si > 1200px côté
        const max = 1200;
        const r = Math.min(1, max / Math.max(img.width, img.height));
        const w = Math.round(img.width * r);
        const h = Math.round(img.height * r);
        const canvas = document.createElement("canvas");
        canvas.width = w; canvas.height = h;
        canvas.getContext("2d").drawImage(img, 0, 0, w, h);
        onContent(canvas.toDataURL("image/jpeg", 0.85));
        setBusy(false);
      };
      img.src = reader.result;
    };
    reader.readAsDataURL(file);
  };

  return (
    <div>
      {!content ? (
        <button onClick={() => fileRef.current?.click()} style={{
          width: "100%", padding: "60px 30px",
          background: A.white, border: `1.5px dashed ${A.rule}`,
          textAlign: "center", cursor: "pointer", color: A.inkSoft,
          fontFamily: A.italic, fontStyle: "italic", fontSize: 16,
          display: "flex", flexDirection: "column", alignItems: "center", gap: 10,
        }}>
          <span style={{ fontFamily: A.display, fontSize: 48, color: A.rouge, opacity: 0.4 }}>☐</span>
          <span>{busy ? "Préparation…" : "Choisir une photo"}</span>
          <span style={{ fontSize: 12, color: A.inkMute }}>jpg, png, heic — jusqu'à 5 Mo</span>
        </button>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div style={{ position: "relative", background: A.paper, border: `1px solid ${A.ruleSoft}` }}>
            <img src={content} style={{ width: "100%", maxHeight: 400, objectFit: "contain", display: "block" }} alt=""/>
          </div>
          <ButtonA onClick={() => { onContent(""); onCaption(""); }}>↺ Changer de photo</ButtonA>
          <input
            type="text" value={caption} onChange={(e) => onCaption(e.target.value)}
            placeholder="Légende (facultative)"
            style={{
              padding: "12px 14px", background: A.white,
              border: `1.5px solid ${A.ruleSoft}`,
              fontFamily: A.italic, fontStyle: "italic", fontSize: 14, color: A.ink, outline: "none",
            }}
          />
        </div>
      )}
      <input ref={fileRef} type="file" accept="image/*" onChange={handleFile} style={{ display: "none" }} />
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// STEP 4 — Confirmer / sceller
// ─────────────────────────────────────────────────────────
function StepConfirm({ author, setAuthor, dateOpen, type, content, caption, onBack, onSeal }) {
  const date = OPEN_DATES.find((d) => d.id === dateOpen);
  const t = CONTENT_TYPES.find((t) => t.id === type);
  const [error, setError] = React.useState("");

  const handleSeal = () => {
    if (author.trim().length < 2) {
      setError("Indiquez votre prénom et nom.");
      return;
    }
    onSeal();
  };

  return (
    <div className="anim-up">
      <StepHeader step={4} total={4} title="Sceller votre message" sub="Une fois scellé, vous ne pourrez plus modifier le contenu. C'est ça, le principe." onBack={onBack} />

      {/* Récap */}
      <div style={{ marginTop: 26, background: A.card, border: `1px solid ${A.ruleSoft}`, padding: 0 }}>
        {/* Date */}
        <div style={{ padding: "16px 18px", borderLeft: `4px solid ${date.color}` }}>
          <div className="eyebrow" style={{ fontSize: 9, letterSpacing: 2.5, color: A.inkMute }}>S'OUVRE LE</div>
          <div style={{ fontFamily: A.display, fontWeight: 700, fontSize: 22, color: A.ink, marginTop: 2, lineHeight: 1.1 }}>
            {date.date}
          </div>
          <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 13, color: A.inkSoft, marginTop: 4 }}>
            {date.title} · {date.desc}
          </div>
        </div>
        {/* Type + contenu */}
        <div style={{ padding: "16px 18px", borderTop: `1px solid ${A.ruleSoft}` }}>
          <div className="eyebrow" style={{ fontSize: 9, letterSpacing: 2.5, color: A.inkMute }}>VOTRE MESSAGE · {t.label.toUpperCase()}</div>
          {type === "text" && (
            <div style={{ marginTop: 10, padding: "14px 16px", background: A.paper, fontFamily: A.italic, fontStyle: "italic", fontSize: 15, color: A.ink, lineHeight: 1.55, whiteSpace: "pre-wrap" }}>
              {content || "(message vide)"}
            </div>
          )}
          {type === "audio" && (
            <audio src={content} controls style={{ width: "100%", marginTop: 10 }}/>
          )}
          {type === "photo" && (
            <div style={{ marginTop: 10 }}>
              <img src={content} style={{ maxWidth: "100%", maxHeight: 280, display: "block", margin: "0 auto", border: `1px solid ${A.ruleSoft}` }}/>
              {caption && <div style={{ marginTop: 8, fontFamily: A.italic, fontStyle: "italic", fontSize: 14, color: A.inkSoft, textAlign: "center" }}>{caption}</div>}
            </div>
          )}
        </div>
      </div>

      {/* Auteur */}
      <div style={{ marginTop: 24 }}>
        <div className="eyebrow" style={{ marginBottom: 10 }}>Signé par</div>
        <input
          type="text" value={author} onChange={(e) => { setAuthor(e.target.value); setError(""); }}
          placeholder="Prénom et nom"
          style={{
            width: "100%", padding: "13px 16px", background: A.white,
            border: `1.5px solid ${error ? A.rouge : A.ruleSoft}`,
            fontFamily: A.sans, fontSize: 15, color: A.ink, outline: "none",
          }}
        />
        {error && <div style={{ marginTop: 6, fontFamily: A.italic, fontStyle: "italic", fontSize: 12, color: A.rouge }}>{error}</div>}
      </div>

      <div style={{ display: "flex", gap: 10, marginTop: 26 }}>
        <ButtonA onClick={onBack}>← Modifier</ButtonA>
        <ButtonA primary onClick={handleSeal} style={{ flex: 1 }}>
          ♥ Sceller définitivement
        </ButtonA>
      </div>
      <div style={{ marginTop: 14, fontFamily: A.italic, fontStyle: "italic", fontSize: 12, color: A.inkMute, textAlign: "center", lineHeight: 1.4 }}>
        Vous pourrez sceller autant de capsules que vous voulez.
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// STEP 5 — Sealed
// ─────────────────────────────────────────────────────────
function StepDone({ dateOpen, onCreateAnother }) {
  const date = OPEN_DATES.find((d) => d.id === dateOpen);
  return (
    <div className="anim-up" style={{ textAlign: "center", padding: "32px 12px" }}>
      <div style={{
        margin: "0 auto 22px", width: 90, height: 90, borderRadius: "50%",
        background: A.rouge, border: `3px solid ${A.rougeDeep}`,
        display: "flex", alignItems: "center", justifyContent: "center",
        boxShadow: `0 4px 24px ${A.rouge}66`,
        animation: "seal-stamp 0.6s ease-out both",
      }}>
        <div style={{ fontFamily: A.display, fontStyle: "italic", fontSize: 36, color: A.white, lineHeight: 1 }}>♥</div>
      </div>

      <div className="display-bold" style={{ fontSize: 36, color: A.ink, lineHeight: 1, letterSpacing: -0.5 }}>
        Scellé.
      </div>
      <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 17, color: A.inkSoft, marginTop: 16, lineHeight: 1.55, maxWidth: 380, margin: "16px auto 0" }}>
        Votre message attendra patiemment le <strong style={{ color: A.ink, fontStyle: "normal" }}>{date.date}</strong> pour s'ouvrir.
        <br/>
        Merci, c'est précieux.
      </div>

      <div style={{ marginTop: 32, display: "flex", gap: 10, justifyContent: "center", flexWrap: "wrap" }}>
        <ButtonA primary onClick={onCreateAnother}>+ Sceller un autre message</ButtonA>
      </div>

      <style>{`
        @keyframes seal-stamp {
          0%   { transform: scale(0.3) rotate(-12deg); opacity: 0; }
          60%  { transform: scale(1.15) rotate(2deg); opacity: 1; }
          100% { transform: scale(1) rotate(0deg); opacity: 1; }
        }
      `}</style>
    </div>
  );
}

// ─────────────────────────────────────────────────────────
// Step header partagé
// ─────────────────────────────────────────────────────────
function StepHeader({ step, total, title, sub, onBack }) {
  return (
    <div className="anim-up">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <button onClick={onBack} style={{
          background: "none", border: "none", cursor: "pointer", padding: 0,
          fontFamily: A.mono, fontSize: 10, letterSpacing: 2, color: A.inkSoft, textTransform: "uppercase",
        }}>
          ← Retour
        </button>
        <div style={{ fontFamily: A.mono, fontSize: 10, letterSpacing: 2, color: A.inkMute, textTransform: "uppercase" }}>
          Étape {step} / {total}
        </div>
      </div>
      <div style={{ height: 2, background: A.ruleSoft, marginTop: 10, marginBottom: 22, overflow: "hidden" }}>
        <div style={{ width: `${(step / total) * 100}%`, height: "100%", background: A.rouge, transition: "width .35s ease" }}/>
      </div>
      <div className="display-bold" style={{ fontSize: 26, color: A.ink, lineHeight: 1.1, letterSpacing: -0.5 }}>{title}</div>
      <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 15, color: A.inkSoft, marginTop: 6, lineHeight: 1.4 }}>{sub}</div>
    </div>
  );
}

Object.assign(window, { CarnetPage });
