/* ClientBase — Dossier de prospection personnalisé
   URL : /?invite=1&for=Lea&metier=coiffeuse&ville=Bordeaux
   Format : un mini-dossier sur-mesure (cover + 3 cartes-pages numérotées),
   coloré selon le métier, vocabulaire adapté.
   Sans aucun param : générateur admin avec auto-extraction depuis bio Insta. */

/* ============ Données métier ============ */
/* hue = teinte oklch principale du dossier
   vocab = comment on appelle leur clientèle (genré au mieux)
   emoji = glyph affiché en grand sur la cover
   prestations = exemples affichés dans la preview de page de RDV */
const METIER_PRESETS = {
  coiffeuse:       { label: "coiffeuses",     clients: 100, ticket: 40,  presta: "Coupe + brushing",        hue: 25,  vocab: "clients",    emoji: "✂️",  prestations: ["Coupe + brushing", "Couleur racines", "Balayage long"] },
  coiffeur:        { label: "coiffeurs",      clients: 100, ticket: 35,  presta: "Coupe homme",             hue: 25,  vocab: "client·es",   emoji: "✂️",  prestations: ["Coupe homme", "Coupe + barbe", "Dégradé américain"] },
  barbier:         { label: "barbiers",       clients: 120, ticket: 28,  presta: "Taille de barbe",         hue: 35,  vocab: "client·es",   emoji: "🪒",  prestations: ["Taille de barbe", "Rasage traditionnel", "Coupe + barbe"] },
  estheticienne:   { label: "esthéticiennes", clients: 60,  ticket: 55,  presta: "Soin visage anti-âge",    hue: 15,  vocab: "clients",    emoji: "✨",  prestations: ["Soin visage anti-âge", "Épilation jambes", "Pose de cils"] },
  ongulaire:       { label: "ongulaires",     clients: 70,  ticket: 45,  presta: "Pose gel semi-perm.",     hue: 340, vocab: "clients",    emoji: "💅",  prestations: ["Pose gel semi-perm.", "Remplissage", "Nail art"] },
  nailiste:        { label: "nailistes",      clients: 70,  ticket: 45,  presta: "Pose gel semi-perm.",     hue: 340, vocab: "clients",    emoji: "💅",  prestations: ["Pose gel semi-perm.", "Remplissage", "Nail art"] },
  maquilleuse:     { label: "maquilleuses",   clients: 35,  ticket: 80,  presta: "Maquillage mariée",       hue: 5,   vocab: "clients",    emoji: "💄",  prestations: ["Maquillage mariée", "Maquillage de soirée", "Cours d'auto-maquillage"] },
  masseur:         { label: "masseurs",       clients: 40,  ticket: 70,  presta: "Massage relaxant 1 h",    hue: 160, vocab: "client·es",   emoji: "🌿",  prestations: ["Massage relaxant 1 h", "Massage sportif", "Massage prénatal"] },
  masseuse:        { label: "masseuses",      clients: 40,  ticket: 70,  presta: "Massage relaxant 1 h",    hue: 160, vocab: "clients",    emoji: "🌿",  prestations: ["Massage relaxant 1 h", "Massage sportif", "Massage prénatal"] },
  tatoueuse:       { label: "tatoueuses",     clients: 20,  ticket: 150, presta: "Projet 2 h",              hue: 280, vocab: "modèles",     emoji: "🖋️", prestations: ["Projet 2 h", "Petit motif (≤ 1 h)", "Cover-up"] },
  tatoueur:        { label: "tatoueurs",      clients: 20,  ticket: 150, presta: "Projet 2 h",              hue: 280, vocab: "modèles",     emoji: "🖋️", prestations: ["Projet 2 h", "Petit motif (≤ 1 h)", "Cover-up"] },
  sophrologue:     { label: "sophrologues",   clients: 50,  ticket: 65,  presta: "Séance 1 h",              hue: 180, vocab: "patient·es",  emoji: "🌬️", prestations: ["Séance individuelle 1 h", "Pack 5 séances", "Séance enfant"] },
  naturopathe:     { label: "naturopathes",   clients: 40,  ticket: 75,  presta: "Bilan initial",           hue: 150, vocab: "patient·es",  emoji: "🌱",  prestations: ["Bilan initial 1h30", "Suivi 45 min", "Programme nutritionnel"] },
  osteopathe:      { label: "ostéopathes",    clients: 80,  ticket: 60,  presta: "Séance 45 min",           hue: 220, vocab: "patient·es",  emoji: "🦴",  prestations: ["Séance 45 min", "Séance bébé", "Séance sportif"] },
  kine:            { label: "kinés",          clients: 150, ticket: 30,  presta: "Séance rééducation",      hue: 220, vocab: "patient·es",  emoji: "🩺",  prestations: ["Séance rééducation", "Drainage lymphatique", "Séance à domicile"] },
  podologue:       { label: "podologues",     clients: 90,  ticket: 50,  presta: "Soin complet",            hue: 200, vocab: "patient·es",  emoji: "🦶",  prestations: ["Soin complet", "Semelles orthopédiques", "Suivi mensuel"] },
  dieteticienne:   { label: "diététiciennes", clients: 50,  ticket: 60,  presta: "Bilan nutritionnel",      hue: 140, vocab: "patient·es",  emoji: "🥗",  prestations: ["Bilan nutritionnel", "Suivi mensuel", "Pack 3 mois"] },
  diététicien:     { label: "diététiciens",   clients: 50,  ticket: 60,  presta: "Bilan nutritionnel",      hue: 140, vocab: "patient·es",  emoji: "🥗",  prestations: ["Bilan nutritionnel", "Suivi mensuel", "Pack 3 mois"] },
  "coach-sportif": { label: "coachs sportifs",clients: 45,  ticket: 65,  presta: "Séance 1 h",              hue: 40,  vocab: "élèves",      emoji: "🏋️", prestations: ["Séance 1 h", "Pack 10 séances", "Programme sur-mesure"] },
  "prof-yoga":     { label: "profs de yoga",  clients: 80,  ticket: 20,  presta: "Cours collectif",         hue: 130, vocab: "élèves",      emoji: "🧘",  prestations: ["Cours collectif", "Cours privé 1h", "Stage week-end"] },
  toiletteur:      { label: "toiletteurs",    clients: 60,  ticket: 50,  presta: "Toilettage chien",        hue: 50,  vocab: "client·es",   emoji: "🐩",  prestations: ["Toilettage chien", "Toilettage chat", "Coupe griffes"] },
  couturiere:      { label: "couturières",    clients: 40,  ticket: 45,  presta: "Retouche complète",       hue: 310, vocab: "client·es",   emoji: "🪡",  prestations: ["Retouche complète", "Création sur-mesure", "Réparation"] },
  photographe:     { label: "photographes",   clients: 15,  ticket: 220, presta: "Shooting 1 h",            hue: 260, vocab: "client·es",   emoji: "📷",  prestations: ["Shooting portrait 1 h", "Mariage demi-journée", "Shooting famille"] },
  therapeute:      { label: "thérapeutes",    clients: 45,  ticket: 70,  presta: "Séance 1 h",              hue: 270, vocab: "patient·es",  emoji: "🕊️", prestations: ["Séance individuelle 1 h", "Séance de couple", "Pack 5 séances"] },
};

const DEFAULT_PRESET = { label: "indépendant·e", clients: 50, ticket: 50, presta: "Prestation type", hue: 278, vocab: "client·es", emoji: "✦", prestations: ["Prestation 1", "Prestation 2", "Prestation 3"] };

/* Petit dictionnaire de villes pour l'auto-extraction depuis bio Insta */
const CITIES_HINT = ["Paris","Lyon","Marseille","Bordeaux","Toulouse","Lille","Nantes","Nice","Strasbourg","Rennes","Montpellier","Reims","Le Havre","Saint-Étienne","Toulon","Grenoble","Dijon","Angers","Nîmes","Villeurbanne","Aix-en-Provence","Brest","Le Mans","Tours","Amiens","Limoges","Annecy","Perpignan","Boulogne","Metz","Besançon","Orléans","Rouen","Caen","Mulhouse","Nancy","Argenteuil","Roubaix","Tourcoing","Nanterre","Avignon","Vitry","Créteil","Dunkerque","Poitiers","Asnières","Versailles","Colombes","Aulnay","Pau","Courbevoie","La Rochelle","Calais","Cannes","Antibes","Béziers","Ajaccio","Bourges","Cherbourg","Saint-Denis","Hyères","Chambéry"];

/* Templates de "mot perso" — 3 par métier ou génériques */
const NOTE_TEMPLATES = {
  default: [
    "J'ai vu votre travail sur Insta, vraiment beau — j'ai pensé à vous en construisant cette page.",
    "Votre activité m'a marqué·e, alors j'ai préparé cette page rien que pour vous.",
    "Je suis tombé·e sur votre profil, j'ai trouvé ça génial — voici ce que ClientBase pourrait apporter à votre rythme.",
  ],
  coiffeuse: [
    "J'ai vu vos balayages, magnifiques — j'ai pensé à vous en construisant cette page.",
    "Votre feed coiffure m'a tapé dans l'œil, voici une page faite pour vous.",
  ],
  ongulaire: [
    "J'ai vu vos poses, elles sont incroyables — j'ai préparé cette page rien que pour vous.",
    "Vos nail arts m'ont impressionné·e, voici ce que ClientBase pourrait vous simplifier.",
  ],
  estheticienne: [
    "J'ai parcouru votre feed, on sent le soin et la précision — j'ai pensé à vous en construisant cette page.",
  ],
  tatoueuse: [
    "J'ai vu votre style, c'est très fort — j'ai préparé cette page rien que pour vous.",
  ],
  osteopathe: [
    "J'ai vu votre approche, vraiment qualitative — j'ai pensé à vous pour cette page.",
  ],
};

const _slugifyKey = (s) => (s || "").toLowerCase()
  .normalize("NFD").replace(/[̀-ͯ]/g, "")
  .replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");

const _getInviteParams = () => {
  try {
    const u = new URLSearchParams(window.location.search);
    return {
      forName:   (u.get("for") || "").trim(),
      metier:    (u.get("metier") || "").trim(),
      ville:     (u.get("ville") || "").trim(),
      insta:     (u.get("insta") || "").trim().replace(/^@/, ""),
      salon:     (u.get("salon") || "").trim(),
      specialty: (u.get("specialty") || u.get("specialite") || "").trim(),
      note:      (u.get("note") || "").trim(),
      signature: (u.get("signature") || u.get("presta") || "").trim(),
      goal:      (u.get("goal") || u.get("objectif") || "").trim(),
    };
  } catch {
    return { forName: "", metier: "", ville: "", insta: "", salon: "", specialty: "", note: "", signature: "", goal: "" };
  }
};

const _getInviteFromLocation = () => {
  const p = _getInviteParams();
  return (p.forName || p.metier || p.ville) ? p : null;
};

/* Resolve métier → preset (avec fallback sympa) */
const _resolvePreset = (metier) => {
  const k = _slugifyKey(metier);
  return METIER_PRESETS[k] || DEFAULT_PRESET;
};

/* Thème unifié — couleurs du site (accent indigo ClientBase).
   La fonction garde sa signature pour ne pas casser les appels existants. */
const _themeFromHue = (_hue) => ({
  hue:    278,
  ink:    "var(--accent-ink)",
  base:   "var(--accent)",
  soft:   "var(--accent-soft)",
  soft2:  "var(--accent-soft-2)",
  deep:   "var(--accent-ink)",       // indigo accent (au lieu d'un bleu sombre)
  deepGrad: "linear-gradient(135deg, var(--accent) 0%, oklch(45% 0.22 300) 100%)",
  paper:  "var(--bg-section)",
});

/* ============ Page d'entrée ============ */
const InvitePage = ({ go }) => {
  const params = _getInviteParams();
  const preset = _resolvePreset(params.metier);
  const theme = _themeFromHue(preset.hue);

  if (!params.forName && !params.metier) {
    return <InviteGenerator go={go}/>;
  }

  return <Dossier params={params} preset={preset} theme={theme} go={go}/>;
};

/* ============ DOSSIER (vue prospecte) ============ */
const Dossier = ({ params, preset, theme, go }) => {
  const { forName, ville, salon, insta, specialty, note, signature, goal } = params;
  const metierLabel = preset.label;
  const vocab = preset.vocab;
  const displayName = forName || salon || "vous";
  const presta = signature || preset.presta;
  const slug = _slugifyKey((forName || salon || "pro") + "-" + (params.metier || ""));

  /* Numéro pseudo-aléatoire stable basé sur le nom */
  const dossierNum = String(((forName || salon || "x").length * 17 + (params.metier || "y").length * 31) % 900 + 100);

  /* État du diagnostic */
  const [diag, setDiag] = React.useState({
    clients: preset.clients,
    ticket:  preset.ticket,
    tool:    "",
    pain:    "",
  });

  return (
    <div style={{
      minHeight: "100vh",
      background: theme.paper,
      color: "var(--ink)",
      fontFamily: "var(--ff-text)",
    }}>
      <style>{`
        @keyframes cbDosFade { from { opacity:0; transform: translateY(10px); } to { opacity:1; transform:none; } }
        .cb-dos-card { animation: cbDosFade .55s cubic-bezier(.22,1,.36,1) both; }
        .cb-dos-card:nth-child(2) { animation-delay: .08s; }
        .cb-dos-card:nth-child(3) { animation-delay: .16s; }
        .cb-dos-card:nth-child(4) { animation-delay: .24s; }
        @media (max-width: 720px) {
          .cb-dos-cover-name { font-size: clamp(48px, 14vw, 90px) !important; }
          .cb-dos-meta { gap: 6px !important; }
          .cb-dos-card { padding: 22px 18px !important; }
          .cb-dos-cover { padding: 50px 18px 42px !important; }
          .cb-dos-main { padding: 0 14px 60px !important; }
          .cb-dos-pageheader-num { font-size: 42px !important; }
          .cb-dos-pageheader-label { font-size: 19px !important; }
          .cb-dos-bar-cta { padding: 7px 11px !important; font-size: 11.5px !important; }
        }
      `}</style>

      {/* BANDEAU SOMBRE — barre dossier */}
      <DossierBar dossierNum={dossierNum} forName={forName} theme={theme} go={go}/>

      {/* COVER — magazine cover */}
      <DossierCover
        forName={forName} salon={salon} ville={ville} insta={insta} specialty={specialty}
        metierLabel={metierLabel} preset={preset} theme={theme}
      />

      {/* CORPS — 3 cartes-pages */}
      <main className="cb-dos-main" style={{ maxWidth: 780, margin: "0 auto", padding: "0 20px 80px" }}>
        {note && <DossierNote note={note} theme={theme}/>}

        <DossierPage01
          forName={forName} ville={ville} signature={signature} presta={presta}
          vocab={vocab} preset={preset} theme={theme}
          diag={diag} setDiag={setDiag}
        />

        <DossierPage02
          forName={forName || displayName} vocab={vocab} theme={theme}
          clients={diag.clients} ticket={diag.ticket} pain={diag.pain} tool={diag.tool} goal={goal}
        />

        <DossierPageSales
          forName={forName} vocab={vocab} theme={theme}
          diag={diag} setDiag={setDiag}
        />

        <DossierPage04
          forName={forName} salon={salon} ville={ville} insta={insta}
          metierLabel={metierLabel} preset={preset} theme={theme}
          presta={presta} ticket={diag.ticket} slug={slug}
          go={go}
        />

        <DossierClose forName={forName} theme={theme} go={go}/>
      </main>

      <DossierFooter theme={theme}/>
    </div>
  );
};

/* ---- Bandeau haut de dossier (clair, comme la nav du site) ---- */
const DossierBar = ({ dossierNum, forName, theme, go }) => {
  const [progress, setProgress] = React.useState(0);
  React.useEffect(() => {
    const onScroll = () => {
      const max = document.documentElement.scrollHeight - window.innerHeight;
      setProgress(max > 0 ? Math.min(100, (window.scrollY / max) * 100) : 0);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
  <div style={{
    position: "sticky", top: 0, zIndex: 30,
    background: "color-mix(in oklab, var(--bg) 88%, transparent)",
    backdropFilter: "saturate(140%) blur(14px)",
    WebkitBackdropFilter: "saturate(140%) blur(14px)",
    borderBottom: "1px solid var(--line)",
    padding: "10px 20px",
  }}>
    <div style={{
      maxWidth: 980, margin: "0 auto",
      display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
    }} className="cb-dos-meta">
      {/* Gauche — signature Noah (preuve d'humain) */}
      <div style={{ display: "inline-flex", alignItems: "center", gap: 10, minWidth: 0 }}>
        <div style={{
          width: 32, height: 32, borderRadius: 50, flexShrink: 0,
          background: theme.deepGrad, color: "white",
          display: "flex", alignItems: "center", justifyContent: "center",
          fontFamily: "var(--ff-display)", fontWeight: 600, fontSize: 13,
          boxShadow: "0 2px 6px -1px rgba(90,80,230,0.35)",
        }}>N</div>
        <div style={{ minWidth: 0, lineHeight: 1.15 }}>
          <div style={{ fontSize: 12.5, color: "var(--ink)", fontWeight: 580 }}>
            Préparé par Noah
          </div>
          <div style={{ fontSize: 11, color: "var(--ink-4)" }}>
            Dossier nº {dossierNum}{forName ? ` · pour ${forName}` : ""}
          </div>
        </div>
      </div>
      <button className="cb-dos-bar-cta" onClick={() => go && go("home")} style={{
        background: "var(--accent)", border: "none",
        color: "white", padding: "8px 14px", borderRadius: 999,
        fontSize: 12.5, fontWeight: 560, cursor: "pointer",
        fontFamily: "inherit", display: "inline-flex", alignItems: "center", gap: 6,
        whiteSpace: "nowrap",
        boxShadow: "0 2px 8px -2px color-mix(in oklab, var(--accent) 60%, transparent)",
      }}>
        Découvrir ClientBase <span style={{ fontSize: 14 }}>→</span>
      </button>
    </div>
    {/* Reading progress — subtil */}
    <div style={{
      position: "absolute", left: 0, right: 0, bottom: -1, height: 2,
      background: "transparent", pointerEvents: "none",
    }}>
      <div style={{
        width: `${progress}%`, height: "100%",
        background: theme.base,
        transition: "width .15s ease-out",
      }}/>
    </div>
  </div>
  );
};

/* ---- Cover façon couverture de magazine ---- */
const DossierCover = ({ forName, salon, ville, insta, specialty, metierLabel, preset, theme }) => (
  <section className="cb-dos-cover" style={{
    padding: "70px 20px 60px",
    position: "relative", overflow: "hidden",
    borderBottom: `1px solid ${theme.soft2}`,
    background: `linear-gradient(180deg, ${theme.soft} 0%, ${theme.paper} 100%)`,
  }}>
    {/* glyph métier en filigrane */}
    <div aria-hidden style={{
      position: "absolute", right: -40, top: -20,
      fontSize: "min(48vw, 380px)", lineHeight: 1, opacity: 0.06,
      pointerEvents: "none", userSelect: "none",
      transform: "rotate(-8deg)",
    }}>
      {preset.emoji}
    </div>

    <div style={{ maxWidth: 780, margin: "0 auto", position: "relative" }}>
      <div style={{
        display: "inline-flex", alignItems: "center", gap: 8,
        padding: "6px 14px 6px 10px",
        background: "white", border: `1px solid ${theme.soft2}`,
        borderRadius: 999, fontSize: 13, color: theme.ink,
        fontWeight: 520, marginBottom: 22,
      }}>
        <span style={{ width: 7, height: 7, borderRadius: 50, background: theme.base }}/>
        Étude personnalisée · {metierLabel}{ville ? ` · ${ville}` : ""}
      </div>

      <h1 className="cb-dos-cover-name" style={{
        fontFamily: "var(--ff-display)", fontWeight: 600,
        fontSize: "clamp(56px, 9vw, 120px)", lineHeight: 0.92,
        letterSpacing: "-0.045em", margin: 0, color: theme.deep,
      }}>
        {forName || salon || "Votre"}
      </h1>

      {salon && forName && (
        <div style={{
          marginTop: 8, fontFamily: "var(--ff-display)", fontSize: 22,
          fontWeight: 500, color: "var(--ink-2)", letterSpacing: "-0.02em",
        }}>
          {salon}
        </div>
      )}

      <div style={{
        marginTop: 28, display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center",
      }}>
        {insta && (
          <a href={`https://instagram.com/${insta}`} target="_blank" rel="noopener noreferrer" style={{
            padding: "6px 12px", background: "white",
            border: `1px solid ${theme.soft2}`, borderRadius: 999,
            fontSize: 13, color: theme.ink, fontWeight: 500,
            textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 6,
          }}>
            <span style={{ opacity: 0.55 }}>@</span>{insta}
          </a>
        )}
        {ville && (
          <span style={{
            padding: "6px 12px", background: "white",
            border: `1px solid ${theme.soft2}`, borderRadius: 999,
            fontSize: 13, color: "var(--ink-2)", fontWeight: 500,
          }}>
            📍 {ville}
          </span>
        )}
        {specialty && (
          <span style={{
            padding: "6px 12px", background: theme.deep, color: "white",
            borderRadius: 999, fontSize: 13, fontWeight: 500,
          }}>
            {specialty}
          </span>
        )}
      </div>

      <p style={{
        marginTop: 32, fontSize: 17, color: "var(--ink-2)",
        maxWidth: 540, lineHeight: 1.6, fontWeight: 400,
      }}>
        {forName ? `${forName}, ce` : "Ce"} dossier a été assemblé pour vous. Il contient une étude rapide de votre activité,
        une estimation chiffrée de ce que ClientBase pourrait vous rapporter, des arguments concrets
        face à votre outil actuel, et un aperçu de votre future page de réservation.
      </p>

      {/* Trust badges — petits gages de confiance alignés site */}
      <div style={{
        marginTop: 24, display: "flex", flexWrap: "wrap", gap: 6,
      }}>
        {[
          "Gratuit pendant la bêta",
          "Sans carte bancaire",
          "Annulable à tout moment",
          "Données hébergées en France 🇫🇷",
        ].map(b => (
          <span key={b} style={{
            display: "inline-flex", alignItems: "center", gap: 5,
            padding: "5px 10px",
            background: "white", border: `1px solid ${theme.soft2}`,
            borderRadius: 999, fontSize: 12, color: "var(--ink-2)", fontWeight: 500,
          }}>
            <span style={{ color: theme.base, fontWeight: 700 }}>✓</span>{b}
          </span>
        ))}
      </div>
    </div>
  </section>
);

/* ---- Note manuscrite (mot de l'équipe) ---- */
const DossierNote = ({ note, theme }) => (
  <div className="cb-dos-card" style={{
    margin: "32px 0 0", padding: "22px 24px",
    background: "white", border: `1px solid ${theme.soft2}`,
    borderRadius: 14, position: "relative",
    boxShadow: "0 1px 3px rgba(0,0,0,0.04)",
  }}>
    <div style={{
      fontSize: 13, fontWeight: 580, color: theme.ink, marginBottom: 8,
    }}>
      ✦ Mot de l'équipe
    </div>
    <div style={{
      fontSize: 16, color: "var(--ink)", lineHeight: 1.55,
      fontStyle: "italic",
    }}>
      « {note} »
    </div>
    <div style={{ marginTop: 12, fontSize: 12.5, color: "var(--ink-4)", textAlign: "right" }}>
      — Noah, fondateur
    </div>
  </div>
);

/* ---- En-tête de page de dossier (numéro + titre) ---- */
const DossierSubHeader = ({ n, label, theme }) => (
  <div style={{ display: "flex", alignItems: "baseline", gap: 14, marginBottom: 18 }}>
    <span className="cb-dos-pageheader-num" style={{
      fontFamily: "var(--ff-display)", fontWeight: 600,
      fontSize: 56, lineHeight: 1, letterSpacing: "-0.04em",
      color: theme.base, fontVariantNumeric: "tabular-nums",
    }}>
      {n}
    </span>
    <div>
      <div style={{ fontSize: 12, color: "var(--ink-4)", fontWeight: 500 }}>
        Page {n}
      </div>
      <div className="cb-dos-pageheader-label" style={{
        fontFamily: "var(--ff-display)", fontSize: 22,
        fontWeight: 580, letterSpacing: "-0.02em", color: theme.deep,
      }}>
        {label}
      </div>
    </div>
  </div>
);

/* ============ Page 01 — Activité (sliders + pills) ============ */
const DossierPage01 = ({ forName, ville, presta, vocab, theme, diag, setDiag }) => (
  <section className="cb-dos-card" style={{
    marginTop: 28, padding: "30px 28px",
    background: "white", border: `1px solid ${theme.soft2}`,
    borderRadius: 18,
  }}>
    <DossierSubHeader n="01" label="Votre activité" theme={theme}/>
    <p style={{ margin: "0 0 24px", color: "var(--ink-3)", fontSize: 14.5, lineHeight: 1.55 }}>
      {forName ? `${forName}, ` : ""}ajustez deux curseurs pour qu'on parle de votre vraie réalité,
      pas de moyennes nationales.
    </p>

    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      <DSlider
        label={`Combien de ${vocab} par mois${ville ? ` à ${ville}` : ""} ?`}
        value={diag.clients} min={5} max={250} step={5}
        onChange={v => setDiag({ ...diag, clients: v })}
        format={v => `${v} ${vocab} / mois`}
        theme={theme}
      />
      <DSlider
        label="Votre panier moyen, toutes prestations confondues ?"
        value={diag.ticket} min={15} max={300} step={5}
        onChange={v => setDiag({ ...diag, ticket: v })}
        format={v => `${v} € en moyenne`}
        theme={theme}
      />
      <DPills
        label="Et votre plus gros souci au quotidien ?"
        value={diag.pain}
        onChange={v => setDiag({ ...diag, pain: v })}
        options={["No-show", "Temps au tél", "Facturation", "Fidéliser", "Préférences oubliées"]}
        theme={theme}
      />
    </div>
  </section>
);

const DSlider = ({ label, value, min, max, step, onChange, format, theme }) => (
  <div>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", flexWrap: "wrap", gap: 6 }}>
      <div style={{ fontSize: 14, color: "var(--ink-2)", fontWeight: 520 }}>{label}</div>
      <div style={{
        fontFamily: "var(--ff-display)", fontSize: 22, fontWeight: 600,
        color: theme.ink, letterSpacing: "-0.02em", fontVariantNumeric: "tabular-nums",
      }}>
        {format(value)}
      </div>
    </div>
    <input type="range" min={min} max={max} step={step} value={value}
      onChange={e => onChange(+e.target.value)}
      style={{ width: "100%", accentColor: theme.base, cursor: "pointer", marginTop: 8 }}/>
  </div>
);

const DPills = ({ label, value, onChange, options, theme }) => (
  <div>
    <div style={{ fontSize: 14, color: "var(--ink-2)", fontWeight: 520, marginBottom: 8 }}>{label}</div>
    <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
      {options.map(o => {
        const active = value === o;
        return (
          <button key={o} onClick={() => onChange(active ? "" : o)} style={{
            padding: "8px 14px", fontSize: 13, fontWeight: 500,
            background: active ? theme.base : "white",
            color: active ? "white" : "var(--ink-2)",
            border: `1px solid ${active ? theme.base : theme.soft2}`,
            borderRadius: 999, cursor: "pointer", fontFamily: "inherit",
            transition: "all .18s",
          }}>
            {o}
          </button>
        );
      })}
    </div>
  </div>
);

/* ============ Page 02 — Potentiel ============ */
const DossierPage02 = ({ forName, vocab, theme, clients, ticket, pain, tool, goal }) => {
  const hoursPerYear = (clients * 3 / 60) * 12;
  const daysWon = hoursPerYear / 7;
  const retentionRev = clients * 3 * 0.12 * ticket;
  const noShowRev = clients * 12 * 0.05 * ticket;
  const toolsRepl = 12 * 50;
  const total = Math.round(retentionRev + noShowRev + toolsRepl);

  const painMessage = {
    "No-show":              "Les rappels SMS automatiques font tomber le no-show de 7 % à 2 %.",
    "Temps au tél":         "40 % des RDV se prennent via votre lien public — fini le téléphone pendant les prestations.",
    "Facturation":          `Chaque RDV "fait" génère automatiquement une facture conforme française.`,
    "Fidéliser":            `Carte de fidélité numérique — chaque ${vocab.replace("·es", "e").replace("·e", "e")} voit sa progression en temps réel.`,
    "Préférences oubliées": "Chaque fiche garde préférences, allergies, notes et historique complet.",
  }[pain];

  return (
    <section className="cb-dos-card" style={{
      marginTop: 22, padding: "0", borderRadius: 18,
      overflow: "hidden", border: `1px solid ${theme.soft2}`,
    }}>
      {/* Bande accent = "verdict" du dossier */}
      <div style={{
        background: theme.deepGrad, color: "white",
        padding: "30px 28px",
      }}>
        <DossierSubHeader n="02" label="Votre potentiel" theme={{ ...theme, deep: "white", base: "rgba(255,255,255,0.7)" }}/>
        <div style={{
          fontSize: 13, color: "rgba(255,255,255,0.65)", fontWeight: 500, marginTop: 4,
        }}>
          Estimation annuelle
        </div>
        <div style={{
          fontFamily: "var(--ff-display)", fontWeight: 600,
          fontSize: "clamp(56px, 11vw, 96px)", lineHeight: 1, letterSpacing: "-0.045em",
          marginTop: 8, fontVariantNumeric: "tabular-nums",
        }}>
          + {total.toLocaleString("fr-FR")} €
          <span style={{ fontSize: "0.32em", opacity: 0.7, fontWeight: 500, marginLeft: 10 }}>
            / an
          </span>
        </div>
        <div style={{ marginTop: 14, fontSize: 14, color: "rgba(255,255,255,0.78)", lineHeight: 1.55, maxWidth: 480 }}>
          Sur la base de {clients} {vocab}/mois à {ticket} € en moyenne :{" "}
          <strong style={{ color: "white" }}>{daysWon.toFixed(1)} journées</strong> libérées et{" "}
          <strong style={{ color: "white" }}>{Math.round(retentionRev + noShowRev).toLocaleString("fr-FR")} €</strong> de CA en plus
          (fidélisation + absences évitées).
        </div>
      </div>

      {/* Encarts contextuels */}
      <div style={{ padding: "20px 28px 26px", background: "white", display: "flex", flexDirection: "column", gap: 12 }}>
        {painMessage && (
          <div style={{
            padding: "14px 16px", background: theme.soft, borderRadius: 12,
            border: `1px solid ${theme.soft2}`,
            display: "flex", gap: 12, alignItems: "flex-start",
          }}>
            <div style={{ fontSize: 18, lineHeight: 1, marginTop: 1 }}>✦</div>
            <div>
              <div style={{ fontSize: 13, color: theme.ink, fontWeight: 580 }}>
                Pour votre « {pain} »
              </div>
              <div style={{ fontSize: 14.5, color: "var(--ink)", marginTop: 4, lineHeight: 1.5 }}>
                {painMessage}
              </div>
            </div>
          </div>
        )}

        {tool && tool !== "Carnet papier" && (
          <div style={{
            padding: "12px 16px", background: "var(--bg-alt)",
            border: "1px dashed var(--line-strong)", borderRadius: 10,
            fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.5,
          }}>
            Vous utilisez <strong>{tool}</strong> ? ClientBase remplace l'agenda + la fidélité + la facturation en un seul outil.
            Économie directe estimée : <strong>~600 €/an</strong>.
          </div>
        )}

        {goal && (
          <div style={{
            padding: "14px 16px", background: "var(--sage-soft)",
            border: "1px solid oklch(88% 0.03 160)", borderRadius: 10,
            fontSize: 14, color: "oklch(38% 0.08 160)", lineHeight: 1.5,
          }}>
            <div style={{ fontSize: 13, fontWeight: 580, opacity: 0.85 }}>
              Votre objectif
            </div>
            <div style={{ marginTop: 4 }}>
              {goal}. ClientBase est l'outil pour y arriver en vous libérant le temps et la tête.
            </div>
          </div>
        )}
      </div>
    </section>
  );
};

/* ============ Page 03 — Sales arguments dynamiques (selon outil + souci) ============ */

/* Pour chaque outil, des arguments concrets contre + ce que ClientBase fait à la place */
const TOOL_ARGS = {
  "Carnet papier": {
    title: "Le carnet papier vous coûte plus que ce qu'il rapporte",
    intro: "C'est tactile, c'est rassurant — et c'est aussi votre plus gros frein invisible.",
    cons: [
      { icon: "📵", title: "Aucun rappel automatique",       desc: "Vos clients oublient leur RDV. C'est la première cause des no-show (~7 % en moyenne)." },
      { icon: "📊", title: "Aucune stat, aucun pilotage",    desc: "Combien de RDV ce mois-ci ? Quelle est votre meilleur client ? Impossible sans tout recompter." },
      { icon: "📞", title: "Vous prenez les RDV vous-même",  desc: "Au téléphone, pendant les prestations. Chaque appel coupe le client du moment." },
      { icon: "💧", title: "Un café renversé = tout perdu",  desc: "Pas de sauvegarde possible. Votre carnet est votre point de défaillance unique." },
    ],
    pros: "Avec ClientBase, votre carnet devient un agenda intelligent qui envoie les rappels seul, calcule vos stats automatiquement, et accepte les RDV pendant que vous travaillez.",
  },
  "Planity": {
    title: "Planity prend une commission sur chacune de vos clients",
    intro: "C'est pratique pour démarrer, mais à votre volume ça coûte cher et ça vous fragilise.",
    cons: [
      { icon: "💸", title: "1 à 2 € de commission par RDV",        desc: "Sur 100 RDV/mois, c'est 1 200 à 2 400 €/an versés à Planity. ClientBase = 0 € de commission." },
      { icon: "👀", title: "Vos clients voient les concurrents",  desc: "Sur Planity, juste à côté de votre profil, il y a 50 autres salons. Vous payez pour les exposer." },
      { icon: "🔒", title: "Vos données ne sont pas à vous",       desc: "Si vous quittez Planity, vous repartez de zéro — pas d'export propre du fichier client." },
      { icon: "🧰", title: "Que de l'agenda — rien d'autre",       desc: "Pas de fidélité, pas de facture, pas de stock. Vous payez encore 2 ou 3 abonnements à côté." },
    ],
    pros: "Avec ClientBase, ZÉRO commission sur vos RDV, vous restez 100 % propriétaire de votre fichier, et vous avez l'agenda + la fidélité + la facture + le stock dans un seul outil.",
  },
  "Agenda Google": {
    title: "Google Agenda n'est pas un outil de prise de RDV",
    intro: "C'est pratique pour vous, mais vos clients ne peuvent rien en faire.",
    cons: [
      { icon: "🚫", title: "Vos clients ne peuvent pas réserver", desc: "Elles doivent vous appeler ou DM. C'est toujours vous qui notez, donc aucun gain de temps." },
      { icon: "🗂️", title: "Pas de fiche client",                desc: "Préférences, allergies, historique : tout repose sur votre mémoire ou des notes éparpillées." },
      { icon: "🧾", title: "Pas de facturation",                   desc: "Chaque facture est tapée à la main. Erreurs, oublis, conformité fiscale incertaine." },
      { icon: "🔕", title: "Pas de rappel à le client",           desc: "Le rappel Google ne va qu'à vous. Vos clients oublient quand même." },
    ],
    pros: "ClientBase fait tout ce que Google Agenda ne fait pas : page de RDV publique, fiche client complète, facture auto, rappel SMS — tout en gardant la simplicité d'un agenda.",
  },
  "Insta + DM": {
    title: "Insta + DM, c'est le pire scénario à votre volume",
    intro: "Ça marche au début, puis ça vous mange tout votre temps et vous fait perdre des clients en silence.",
    cons: [
      { icon: "📨", title: "30 % des DM finissent dans « Demandes »", desc: "Vous ne les voyez jamais. Ce sont des clients potentielles qui n'auront jamais de réponse." },
      { icon: "🔄", title: "10 à 15 messages pour 1 seul RDV",       desc: "« T'es dispo quand ? » — « Mardi 14h ? » — « Non, jeudi… » Multipliez par 100 RDV/mois." },
      { icon: "🚨", title: "Vous dépendez de l'algorithme Meta",     desc: "Si Insta change ses règles ou suspend votre compte, vous perdez tout votre fichier client." },
      { icon: "📵", title: "Aucun rappel = no-show garantis",        desc: "Un client qui prend RDV par DM 3 semaines à l'avance ne s'en souviendra pas le jour J." },
    ],
    pros: "Avec ClientBase, 1 lien dans votre bio Insta : vos clients prennent leur RDV en 30 secondes, sans message, sans aller-retour, et vous ne touchez plus votre téléphone pendant vos prestations.",
  },
  "Autre": {
    title: "Quel que soit votre outil, ClientBase remplace tout",
    intro: "La plupart des outils du marché font une chose. ClientBase est conçu pour faire le tour complet de votre métier.",
    cons: [
      { icon: "💸", title: "Probablement payant chaque mois",      desc: "La plupart des outils coûtent 30 à 80 €/mois. ClientBase est offert pendant toute la bêta." },
      { icon: "🧩", title: "Probablement spécialisé sur une chose", desc: "Soit agenda, soit fidélité, soit facture. Jamais les trois ensemble dans la même app." },
      { icon: "🏢", title: "Pensé pour les grosses structures",     desc: "Les outils du marché visent les chaînes. Pas votre quotidien d'indépendant·e." },
    ],
    pros: "ClientBase est conçu spécifiquement pour les indépendant·es de la beauté et du bien-être, par quelqu'un qui a vu de près les frustrations du quotidien.",
  },
};

const TOOL_OPTIONS = ["Carnet papier", "Planity", "Agenda Google", "Insta + DM", "Autre"];

const DossierPageSales = ({ forName, vocab, theme, diag, setDiag }) => {
  const tArg = TOOL_ARGS[diag.tool] || null;

  return (
    <section className="cb-dos-card" style={{
      marginTop: 22, padding: "30px 28px",
      background: "white", border: `1px solid ${theme.soft2}`,
      borderRadius: 18,
    }}>
      <DossierSubHeader n="03" label="Pourquoi passer à ClientBase ?" theme={theme}/>

      <p style={{ margin: "0 0 18px", color: "var(--ink-3)", fontSize: 14.5, lineHeight: 1.55 }}>
        {forName ? `${forName}, ` : ""}dites-nous quel outil vous utilisez aujourd'hui — on vous montre concrètement
        ce qui change pour vous.
      </p>

      <DPills
        label="Quel outil utilisez-vous aujourd'hui ?"
        value={diag.tool}
        onChange={v => setDiag({ ...diag, tool: v })}
        options={TOOL_OPTIONS}
        theme={theme}
      />

      {!tArg && (
        <div style={{
          marginTop: 18, padding: "20px 22px",
          background: theme.soft, border: `1px dashed ${theme.soft2}`,
          borderRadius: 12, textAlign: "center",
          fontSize: 14, color: "var(--ink-3)", lineHeight: 1.5,
        }}>
          ↑ Choisissez votre outil ci-dessus pour voir les arguments précis face à votre situation.
        </div>
      )}

      {tArg && (
        <div style={{ marginTop: 22 }}>
          <h3 style={{
            margin: "0 0 6px", fontSize: 20, fontWeight: 580,
            letterSpacing: "-0.02em", color: theme.ink, lineHeight: 1.3,
          }}>
            {tArg.title}
          </h3>
          <p style={{ margin: "0 0 18px", fontSize: 14.5, color: "var(--ink-3)", lineHeight: 1.55 }}>
            {tArg.intro}
          </p>

          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {tArg.cons.map((c, i) => (
              <div key={i} style={{
                padding: "14px 16px",
                background: "var(--bg-alt)", border: "1px solid var(--line)",
                borderRadius: 12,
                display: "flex", gap: 12, alignItems: "flex-start",
                animation: "cbDosFade .4s cubic-bezier(.22,1,.36,1) both",
                animationDelay: `${i * 0.05}s`,
              }}>
                <div style={{ fontSize: 22, lineHeight: 1, flexShrink: 0 }}>{c.icon}</div>
                <div>
                  <div style={{ fontSize: 14.5, fontWeight: 580, color: "var(--ink)", lineHeight: 1.35 }}>
                    {c.title}
                  </div>
                  <div style={{ fontSize: 13.5, color: "var(--ink-3)", marginTop: 4, lineHeight: 1.5 }}>
                    {c.desc}
                  </div>
                </div>
              </div>
            ))}
          </div>

          <div style={{
            marginTop: 16, padding: "16px 18px",
            background: theme.soft, border: `1px solid ${theme.soft2}`,
            borderRadius: 12,
          }}>
            <div style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
              <div style={{ fontSize: 18, lineHeight: 1, marginTop: 1 }}>✦</div>
              <div>
                <div style={{ fontSize: 13, fontWeight: 580, color: theme.ink }}>
                  Avec ClientBase
                </div>
                <div style={{ fontSize: 14.5, color: "var(--ink)", marginTop: 4, lineHeight: 1.5 }}>
                  {tArg.pros}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </section>
  );
};

/* ============ Page 04 — Démo téléphone (page de RDV client, vraie) + features pro listées honnêtement ============ */
const DossierPage04 = ({ forName, salon, ville, metierLabel, preset, theme, presta, ticket, slug, go }) => {
  const salonName = salon || forName || "Votre salon";

  return (
    <section className="cb-dos-card" style={{
      marginTop: 22, padding: "30px 28px",
      background: "white", border: `1px solid ${theme.soft2}`,
      borderRadius: 18,
    }}>
      <DossierSubHeader n="04" label="Votre future page de réservation" theme={theme}/>
      <p style={{ margin: "0 0 6px", color: "var(--ink-3)", fontSize: 14.5, lineHeight: 1.55 }}>
        Voici exactement ce que vos clients verront sur leur téléphone. Démo cliquable —
        prise de RDV en 3 étapes.
      </p>
      <p style={{ margin: "0 0 22px", fontSize: 13, color: "var(--ink-4)" }}>
        Lien à partager : <strong style={{ color: "var(--ink-3)" }}>clientbase.fr/?book={slug}</strong>
      </p>

      <PhoneFrame theme={theme}>
        <ClientBookingScreen theme={theme} preset={preset} salonName={salonName}
          metierLabel={metierLabel} ville={ville} ticket={ticket} presta={presta}
          forName={forName} salon={salon}/>
      </PhoneFrame>

      {/* Côté pro — 3 groupes thématiques (plus de respiration que la grille 8 items) */}
      <ProSideGroups theme={theme}/>
    </section>
  );
};

/* ---- Côté pro : 3 groupes thématiques avec sous-features en pills ---- */
const PRO_GROUPS = [
  {
    icon: "⏱️",
    title: "Votre temps libéré",
    tagline: "Plus de coups de fil pendant les prestations, plus de RDV oubliés.",
    items: [
      { e: "📅", t: "Agenda intelligent" },
      { e: "🔔", t: "SMS de rappel auto" },
      { e: "🌍", t: "Page publique de RDV" },
    ],
  },
  {
    icon: "💛",
    title: "Vos clients choyées",
    tagline: "Rien n'est oublié, chacune se sent reconnue à chaque visite.",
    items: [
      { e: "👤", t: "Fiches détaillées" },
      { e: "🎁", t: "Carte de fidélité numérique" },
      { e: "📸", t: "Photos avant / après" },
    ],
  },
  {
    icon: "📈",
    title: "Votre business piloté",
    tagline: "Vous savez où vous en êtes, sans vous prendre la tête.",
    items: [
      { e: "🧾", t: "Factures conformes auto" },
      { e: "📊", t: "Statistiques claires" },
      { e: "📦", t: "Stock & matériel" },
    ],
  },
];

const ProSideGroups = ({ theme }) => (
  <div style={{ marginTop: 28 }}>
    <div style={{ marginBottom: 14 }}>
      <h3 style={{
        margin: 0, fontSize: 18, fontWeight: 600,
        letterSpacing: "-0.02em", color: theme.deep,
      }}>
        Et de votre côté, dans l'espace pro
      </h3>
      <p style={{ margin: "4px 0 0", fontSize: 13.5, color: "var(--ink-3)", lineHeight: 1.5 }}>
        Trois piliers qui couvrent tout votre quotidien.
      </p>
    </div>

    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      {PRO_GROUPS.map((g, i) => (
        <div key={i} style={{
          padding: "16px 18px",
          background: "white", border: `1px solid ${theme.soft2}`,
          borderRadius: 14,
          display: "flex", gap: 14, alignItems: "flex-start",
        }}>
          <div style={{
            width: 44, height: 44, borderRadius: 12, flexShrink: 0,
            background: theme.soft, color: theme.ink,
            display: "flex", alignItems: "center", justifyContent: "center",
            fontSize: 22,
          }}>{g.icon}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontFamily: "var(--ff-display)", fontSize: 15, fontWeight: 600,
              letterSpacing: "-0.015em", color: "var(--ink)",
            }}>{g.title}</div>
            <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 2, lineHeight: 1.45 }}>
              {g.tagline}
            </div>
            <div style={{ marginTop: 10, display: "flex", flexWrap: "wrap", gap: 5 }}>
              {g.items.map((it, j) => (
                <span key={j} style={{
                  display: "inline-flex", alignItems: "center", gap: 5,
                  padding: "4px 9px",
                  background: theme.soft, border: `1px solid ${theme.soft2}`,
                  borderRadius: 999, fontSize: 11.5, fontWeight: 500,
                  color: theme.ink,
                }}>
                  <span>{it.e}</span>{it.t}
                </span>
              ))}
            </div>
          </div>
        </div>
      ))}
    </div>
  </div>
);

/* ---- Châssis téléphone réaliste (boutons latéraux, Dynamic Island) ---- */
const PhoneFrame = ({ children, theme }) => (
  <div style={{
    position: "relative",
    width: "100%", maxWidth: 320, margin: "0 auto",
    aspectRatio: "9 / 19.5",
    padding: 9,
    background: "linear-gradient(140deg, #2a2a2c 0%, #1a1a1c 50%, #0e0e10 100%)",
    borderRadius: 48,
    boxShadow: "0 30px 60px -20px rgba(15,18,30,0.35), 0 10px 24px -8px rgba(15,18,30,0.20), inset 0 0 0 1.5px rgba(255,255,255,0.06)",
  }}>
    {/* Boutons latéraux gauche : mute, volume + et − */}
    <div style={{ position: "absolute", left: -2, top: "12%", width: 3, height: 28, background: "#0e0e10", borderRadius: "2px 0 0 2px", boxShadow: "inset 1px 0 0 rgba(255,255,255,0.05)" }}/>
    <div style={{ position: "absolute", left: -3, top: "20%", width: 4, height: 50, background: "#1a1a1c", borderRadius: "2px 0 0 2px", boxShadow: "inset 1px 0 0 rgba(255,255,255,0.06)" }}/>
    <div style={{ position: "absolute", left: -3, top: "29%", width: 4, height: 50, background: "#1a1a1c", borderRadius: "2px 0 0 2px", boxShadow: "inset 1px 0 0 rgba(255,255,255,0.06)" }}/>
    {/* Bouton droit : power */}
    <div style={{ position: "absolute", right: -3, top: "23%", width: 4, height: 80, background: "#1a1a1c", borderRadius: "0 2px 2px 0", boxShadow: "inset -1px 0 0 rgba(255,255,255,0.06)" }}/>

    {/* Écran intérieur */}
    <div style={{
      width: "100%", height: "100%",
      background: "white", borderRadius: 40,
      overflow: "hidden", position: "relative",
      display: "flex", flexDirection: "column",
    }}>
      {/* Dynamic Island */}
      <div style={{
        position: "absolute", top: 9, left: "50%", transform: "translateX(-50%)",
        width: 105, height: 30, background: "#000",
        borderRadius: 22, zIndex: 5,
      }}/>
      {/* Status bar */}
      <div style={{
        position: "absolute", top: 14, left: 22, right: 22, zIndex: 6,
        display: "flex", justifyContent: "space-between", alignItems: "center",
        color: "#000", fontSize: 12, fontWeight: 600, fontVariantNumeric: "tabular-nums",
        pointerEvents: "none",
      }}>
        <span>9:41</span>
        <span style={{ width: 105 }}/>
        <span style={{ display: "inline-flex", gap: 5, alignItems: "center", fontSize: 11 }}>
          <span>📶</span><span>📡</span><span>🔋</span>
        </span>
      </div>

      {/* Container app — décalé sous l'island */}
      <div style={{
        flex: 1, display: "flex", flexDirection: "column",
        paddingTop: 50, minHeight: 0,
      }}>
        {children}
      </div>
    </div>
  </div>
);

/* ============ Côté client — page de réservation 3 étapes ============ */
const ClientBookingScreen = ({ theme, preset, salonName, metierLabel, ville, ticket, presta, forName, salon }) => {
  const initials = (forName || salon || "??").slice(0, 2).toUpperCase();
  const prestations = (preset.prestations || [presta]).slice(0, 3);
  const prices = prestations.map((_, i) => Math.round(ticket * (i === 0 ? 1 : i === 1 ? 0.7 : 1.4)));
  const durations = ["1 h", "45 min", "1 h 30"];

  const [step, setStep] = React.useState(0);
  const [picked, setPicked] = React.useState(0);
  const [slot, setSlot] = React.useState(null);

  const days = React.useMemo(() => {
    const dn = ["dim", "lun", "mar", "mer", "jeu", "ven", "sam"];
    const mn = ["janv.", "févr.", "mars", "avril", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."];
    return Array.from({ length: 5 }).map((_, i) => {
      const d = new Date(); d.setDate(d.getDate() + i + 1);
      return { dayName: dn[d.getDay()], num: d.getDate(), month: mn[d.getMonth()] };
    });
  }, []);
  const [dayIdx, setDayIdx] = React.useState(1);
  const slots = ["09:00", "10:30", "14:00", "15:30", "17:00"];
  const reset = () => { setStep(0); setSlot(null); };

  return (
    <>
      {/* Header salon */}
      <div style={{ padding: "8px 16px 12px", borderBottom: "1px solid var(--line)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{
            width: 38, height: 38, borderRadius: 50,
            background: theme.deepGrad, color: "white",
            display: "flex", alignItems: "center", justifyContent: "center",
            fontWeight: 600, fontSize: 13.5, fontFamily: "var(--ff-display)", flexShrink: 0,
          }}>{initials}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: "var(--ff-display)", fontSize: 14.5, fontWeight: 580, letterSpacing: "-0.02em", lineHeight: 1.15, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
              {salonName}
            </div>
            <div style={{ fontSize: 11, color: "var(--ink-4)" }}>
              {metierLabel.charAt(0).toUpperCase() + metierLabel.slice(1)}{ville ? ` · ${ville}` : ""}
            </div>
          </div>
          {step > 0 && step < 2 && (
            <button onClick={() => setStep(step - 1)} style={{
              background: "var(--bg-alt)", border: "none", borderRadius: 999,
              width: 26, height: 26, cursor: "pointer", fontSize: 13,
              color: "var(--ink-2)", display: "flex", alignItems: "center", justifyContent: "center",
            }}>←</button>
          )}
        </div>
        <div style={{ marginTop: 10, display: "flex", gap: 4 }}>
          {[0, 1, 2].map(i => (
            <div key={i} style={{
              flex: 1, height: 3, borderRadius: 999,
              background: i <= step ? theme.base : "var(--line)",
              transition: "background .25s",
            }}/>
          ))}
        </div>
      </div>

      <div style={{ flex: 1, overflow: "auto", padding: "14px 16px" }}>
        {step === 0 && (
          <div style={{ animation: "cbDosFade .35s both" }}>
            <div style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 580, marginBottom: 8 }}>
              CHOISISSEZ UNE PRESTATION
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {prestations.map((p, i) => {
                const active = picked === i;
                return (
                  <button key={i} onClick={() => setPicked(i)} style={{
                    padding: "10px 12px", textAlign: "left",
                    background: active ? theme.soft : "white",
                    border: `1.5px solid ${active ? theme.base : "var(--line)"}`,
                    borderRadius: 11, cursor: "pointer", fontFamily: "inherit",
                    display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8,
                  }}>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontWeight: 580, fontSize: 13, color: "var(--ink)", overflow: "hidden", textOverflow: "ellipsis" }}>{p}</div>
                      <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 1 }}>{durations[i] || "1 h"}</div>
                    </div>
                    <div style={{ fontWeight: 600, fontSize: 13.5, color: theme.ink, fontVariantNumeric: "tabular-nums", flexShrink: 0 }}>
                      {prices[i]} €
                    </div>
                  </button>
                );
              })}
            </div>
          </div>
        )}

        {step === 1 && (
          <div style={{ animation: "cbDosFade .35s both" }}>
            <div style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 580, marginBottom: 8 }}>CHOISISSEZ UN JOUR</div>
            <div style={{ display: "flex", gap: 5, overflowX: "auto", paddingBottom: 4, marginBottom: 12 }}>
              {days.map((d, i) => {
                const active = dayIdx === i;
                return (
                  <button key={i} onClick={() => setDayIdx(i)} style={{
                    flexShrink: 0, padding: "7px 9px",
                    background: active ? theme.base : "white",
                    color: active ? "white" : "var(--ink-2)",
                    border: `1px solid ${active ? theme.base : "var(--line)"}`,
                    borderRadius: 9, cursor: "pointer", fontFamily: "inherit",
                    textAlign: "center", minWidth: 46,
                  }}>
                    <div style={{ fontSize: 10, opacity: active ? 0.85 : 0.65, textTransform: "uppercase" }}>{d.dayName}</div>
                    <div style={{ fontSize: 14, fontWeight: 600, fontVariantNumeric: "tabular-nums", marginTop: 1 }}>{d.num}</div>
                  </button>
                );
              })}
            </div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 580, marginBottom: 8 }}>ET UN CRÉNEAU</div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 5 }}>
              {slots.map((t, i) => {
                const active = slot === i;
                return (
                  <button key={i} onClick={() => setSlot(i)} style={{
                    padding: "9px 4px", textAlign: "center",
                    background: active ? theme.base : "white",
                    color: active ? "white" : "var(--ink-2)",
                    border: `1px solid ${active ? theme.base : "var(--line)"}`,
                    borderRadius: 8, fontSize: 12.5, fontWeight: 520, cursor: "pointer",
                    fontVariantNumeric: "tabular-nums", fontFamily: "inherit",
                  }}>{t}</button>
                );
              })}
            </div>
          </div>
        )}

        {step === 2 && (
          <div style={{
            animation: "cbDosFade .4s both",
            display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center", padding: "16px 0",
          }}>
            <div style={{
              width: 56, height: 56, borderRadius: 50,
              background: theme.soft, color: theme.ink,
              display: "flex", alignItems: "center", justifyContent: "center",
              fontSize: 28, marginBottom: 12,
            }}>✓</div>
            <div style={{ fontFamily: "var(--ff-display)", fontSize: 16, fontWeight: 580, letterSpacing: "-0.02em" }}>
              RDV confirmé !
            </div>
            <div style={{ marginTop: 12, padding: "10px 12px", background: theme.soft, borderRadius: 10, width: "100%", textAlign: "left" }}>
              <div style={{ fontSize: 11, color: "var(--ink-4)", fontWeight: 500 }}>Prestation</div>
              <div style={{ fontSize: 12.5, fontWeight: 580 }}>{prestations[picked]}</div>
              <div style={{ fontSize: 11, color: "var(--ink-4)", fontWeight: 500, marginTop: 6 }}>Quand</div>
              <div style={{ fontSize: 12.5, fontWeight: 580 }}>
                {days[dayIdx].dayName} {days[dayIdx].num} {days[dayIdx].month} · {slots[slot ?? 0]}
              </div>
              <div style={{ fontSize: 11, color: "var(--ink-4)", fontWeight: 500, marginTop: 6 }}>Prix</div>
              <div style={{ fontSize: 12.5, fontWeight: 580, color: theme.ink }}>{prices[picked]} €</div>
            </div>
            <div style={{ marginTop: 10, fontSize: 10.5, color: "var(--ink-4)", lineHeight: 1.4 }}>
              SMS de rappel envoyé 24 h avant le RDV.
            </div>
          </div>
        )}
      </div>

      <div style={{ padding: "10px 14px 14px", borderTop: "1px solid var(--line)" }}>
        {step === 0 && (
          <button onClick={() => setStep(1)} style={{
            width: "100%", padding: "11px 14px", fontSize: 13.5, fontWeight: 580,
            background: theme.base, color: "white", border: "none",
            borderRadius: 11, cursor: "pointer", fontFamily: "inherit",
          }}>Continuer →</button>
        )}
        {step === 1 && (
          <button onClick={() => slot !== null && setStep(2)} disabled={slot === null} style={{
            width: "100%", padding: "11px 14px", fontSize: 13.5, fontWeight: 580,
            background: slot !== null ? theme.base : "var(--bg-alt)",
            color: slot !== null ? "white" : "var(--ink-4)",
            border: "none", borderRadius: 11,
            cursor: slot !== null ? "pointer" : "not-allowed", fontFamily: "inherit",
          }}>{slot !== null ? "Réserver →" : "Choisissez un créneau"}</button>
        )}
        {step === 2 && (
          <button onClick={reset} style={{
            width: "100%", padding: "11px 14px", fontSize: 13.5, fontWeight: 580,
            background: "white", color: theme.ink,
            border: `1px solid ${theme.soft2}`, borderRadius: 11,
            cursor: "pointer", fontFamily: "inherit",
          }}>↻ Recommencer</button>
        )}
      </div>
    </>
  );
};


/* ============ Clôture du dossier ============ */
const DossierClose = ({ forName, theme, go }) => (
  <section className="cb-dos-card" style={{
    marginTop: 28, padding: "32px 28px",
    background: theme.deepGrad, color: "white",
    borderRadius: 18, textAlign: "center",
  }}>
    <div style={{
      fontSize: 13, color: "rgba(255,255,255,0.65)", fontWeight: 500,
    }}>
      ✦ Dossier — fin
    </div>
    <h2 style={{
      color: "white", marginTop: 12,
      fontSize: "clamp(26px, 4vw, 38px)", letterSpacing: "-0.03em", fontWeight: 580,
    }}>
      {forName ? `${forName}, on est prêts` : "On est prêts"}.
    </h2>
    <p style={{ marginTop: 12, color: "rgba(255,255,255,0.82)", fontSize: 15, maxWidth: 460, margin: "12px auto 0", lineHeight: 1.55 }}>
      Compte prêt en 10 minutes. Pendant toute la bêta, le plan <strong>Business</strong> est offert —
      vous ne payez rien avant le lancement officiel.
    </p>
    <div style={{ marginTop: 22, display: "flex", gap: 10, justifyContent: "center", flexWrap: "wrap" }}>
      <button onClick={() => go("signup")} style={{
        background: "white", color: theme.deep,
        padding: "12px 22px", borderRadius: 999, border: "none",
        fontSize: 15, fontWeight: 560, cursor: "pointer", fontFamily: "inherit",
        display: "inline-flex", alignItems: "center", gap: 8,
      }}>
        Je rejoins la bêta <span style={{ fontSize: 16 }}>→</span>
      </button>
      <button onClick={() => go("contact")} style={{
        background: "transparent", color: "white",
        padding: "12px 22px", borderRadius: 999, border: "1px solid rgba(255,255,255,0.3)",
        fontSize: 15, fontWeight: 500, cursor: "pointer", fontFamily: "inherit",
      }}>
        J'ai une question
      </button>
    </div>
    <div style={{
      marginTop: 24, padding: "12px 16px",
      background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.12)",
      borderRadius: 12, fontSize: 13.5, color: "rgba(255,255,255,0.78)",
      maxWidth: 460, margin: "24px auto 0", lineHeight: 1.5, textAlign: "left",
    }}>
      <strong style={{ color: "white" }}>PS — </strong>
      On accompagne au maximum 12 indépendant·es par mois pour rester dispo. Si ce dossier vous parle,
      mieux vaut ne pas attendre.
    </div>
  </section>
);

const DossierFooter = ({ theme }) => (
  <footer style={{
    padding: "32px 20px 36px", borderTop: `1px solid ${theme.soft2}`,
    background: theme.paper, textAlign: "center",
  }}>
    <div style={{
      display: "inline-flex", alignItems: "center", gap: 14,
      padding: "14px 22px",
      background: "white", border: `1px solid ${theme.soft2}`,
      borderRadius: 999, boxShadow: "0 6px 18px -10px rgba(15,18,30,0.10)",
      maxWidth: "100%", flexWrap: "wrap", justifyContent: "center",
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 50, flexShrink: 0,
        background: theme.deepGrad, color: "white",
        display: "flex", alignItems: "center", justifyContent: "center",
        fontFamily: "var(--ff-display)", fontWeight: 600, fontSize: 14,
      }}>N</div>
      <div style={{ textAlign: "left" }}>
        <div style={{ fontSize: 14, color: "var(--ink)", fontWeight: 580, letterSpacing: "-0.01em" }}>
          Dossier préparé par Noah
        </div>
        <a href="mailto:clientbase.fr@gmail.com" style={{
          fontSize: 13, color: theme.ink, fontWeight: 520,
          textDecoration: "none",
        }}>
          clientbase.fr@gmail.com
        </a>
      </div>
    </div>
  </footer>
);

/* ================================================================ */
/* ============ GÉNÉRATEUR ADMIN — saisie ultra-rapide ============ */
/* ================================================================ */

const HISTORY_KEY = "cb-invite-history-v1";

const _loadHistory = () => {
  try { return JSON.parse(localStorage.getItem(HISTORY_KEY) || "[]"); } catch { return []; }
};
const _saveHistory = (list) => {
  try { localStorage.setItem(HISTORY_KEY, JSON.stringify(list.slice(0, 12))); } catch {}
};

/* Auto-extraction depuis une bio Instagram collée */
const _extractFromBio = (text) => {
  const out = { forName: "", metier: "", ville: "", insta: "", specialty: "" };
  if (!text) return out;
  const t = text.trim();

  const handleMatch = t.match(/@([a-zA-Z0-9._]{2,30})/);
  if (handleMatch) out.insta = handleMatch[1];

  const lower = " " + t.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "") + " ";
  for (const key of Object.keys(METIER_PRESETS)) {
    const needle = " " + key.replace(/-/g, " ") + " ";
    if (lower.includes(needle) || lower.includes(" " + key + " ")) {
      out.metier = key; break;
    }
  }
  if (!out.metier) {
    const fuzz = [
      ["coiff", "coiffeuse"], ["barbe", "barbier"], ["esthet", "estheticienne"],
      ["ongle", "ongulaire"], ["nail", "nailiste"], ["mass", "masseuse"],
      ["maquill", "maquilleuse"], ["tatou", "tatoueuse"], ["sophro", "sophrologue"],
      ["naturo", "naturopathe"], ["osteo", "osteopathe"], ["kine", "kine"],
      ["podo", "podologue"], ["diet", "dieteticienne"], ["coach", "coach-sportif"],
      ["yoga", "prof-yoga"], ["toilett", "toiletteur"], ["coutur", "couturiere"],
      ["photo", "photographe"], ["therap", "therapeute"],
    ];
    for (const [n, k] of fuzz) if (lower.includes(n)) { out.metier = k; break; }
  }

  for (const city of CITIES_HINT) {
    const re = new RegExp("\\b" + city.replace(/[-]/g, "[- ]") + "\\b", "i");
    if (re.test(t)) { out.ville = city; break; }
  }

  /* prénom : première ligne courte sans @ ni emoji ni "." */
  const lines = t.split(/[\n\r]+/).map(s => s.trim()).filter(Boolean);
  for (const line of lines) {
    const clean = line.replace(/[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/gu, "").trim();
    if (clean.length >= 2 && clean.length <= 22 && !/[@.,]/.test(clean) && /^[A-ZÀ-Ý]/.test(clean)) {
      const word = clean.split(/\s+/)[0];
      if (word.length >= 2 && word.length <= 18) { out.forName = word; break; }
    }
  }

  return out;
};

const InviteGenerator = ({ go }) => {
  const [form, setForm] = React.useState({
    forName: "", metier: "", ville: "",
    salon: "", insta: "", specialty: "", signature: "", goal: "", note: "",
  });
  const [bio, setBio] = React.useState("");
  const [copied, setCopied] = React.useState(false);
  const [moreOpen, setMoreOpen] = React.useState(false);
  const [history, setHistory] = React.useState(_loadHistory);
  const linkInputRef = React.useRef(null);

  const preset = _resolvePreset(form.metier);
  const theme = _themeFromHue(preset.hue);

  /* URL générée */
  const params = new URLSearchParams();
  params.set("invite", "1");
  if (form.forName)   params.set("for", form.forName);
  if (form.metier)    params.set("metier", form.metier);
  if (form.ville)     params.set("ville", form.ville);
  if (form.salon)     params.set("salon", form.salon);
  if (form.insta)     params.set("insta", form.insta.replace(/^@/, ""));
  if (form.specialty) params.set("specialty", form.specialty);
  if (form.signature) params.set("signature", form.signature);
  if (form.goal)      params.set("goal", form.goal);
  if (form.note)      params.set("note", form.note);
  const url = `${window.location.origin}/?${params.toString()}`;

  const copy = React.useCallback(async () => {
    try {
      await navigator.clipboard.writeText(url);
      setCopied(true);
      setTimeout(() => setCopied(false), 1600);
      /* Ajout à l'historique si form valide */
      if (form.forName || form.metier) {
        const entry = { id: Date.now(), form: { ...form } };
        const next = [entry, ..._loadHistory().filter(h => JSON.stringify(h.form) !== JSON.stringify(form))].slice(0, 12);
        _saveHistory(next);
        setHistory(next);
      }
    } catch {}
  }, [url, form]);

  /* Cmd+Enter / Ctrl+Enter pour copier */
  React.useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === "Enter") { e.preventDefault(); copy(); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [copy]);

  const applyExtraction = () => {
    const ex = _extractFromBio(bio);
    setForm(f => ({
      ...f,
      forName:   f.forName   || ex.forName,
      metier:    f.metier    || ex.metier,
      ville:     f.ville     || ex.ville,
      insta:     f.insta     || ex.insta,
      specialty: f.specialty || ex.specialty,
    }));
  };

  /* Quand on clique sur un métier-chip : pré-remplit signature avec presta type */
  const pickMetier = (key) => {
    const p = METIER_PRESETS[key];
    setForm(f => ({
      ...f,
      metier: key,
      signature: f.signature || p.presta,
    }));
  };

  const loadFromHistory = (h) => setForm(h.form);
  const deleteFromHistory = (id) => {
    const next = _loadHistory().filter(h => h.id !== id);
    _saveHistory(next);
    setHistory(next);
  };

  const noteSuggestions = NOTE_TEMPLATES[_slugifyKey(form.metier)] || NOTE_TEMPLATES.default;

  return (
    <div style={{
      minHeight: "100vh", background: "var(--bg-alt)",
      padding: "32px 16px 80px",
    }}>
      <div style={{ maxWidth: 720, margin: "0 auto" }}>
        {/* En-tête admin */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, marginBottom: 24 }}>
          <div>
            <div style={{
              fontSize: 12.5, color: "var(--ink-3)", fontWeight: 500,
            }}>
              Admin — prospection
            </div>
            <h1 style={{
              fontSize: "clamp(26px, 3.4vw, 36px)", letterSpacing: "-0.03em",
              marginTop: 4, fontWeight: 600,
            }}>
              Nouveau dossier d'invitation
            </h1>
          </div>
          <button onClick={() => go && go("home")} style={{
            background: "white", border: "1px solid var(--line)",
            padding: "8px 14px", borderRadius: 999, cursor: "pointer",
            fontSize: 12.5, color: "var(--ink-2)", fontFamily: "inherit",
            display: "inline-flex", alignItems: "center", gap: 6, whiteSpace: "nowrap",
          }}>
            ← Accueil
          </button>
        </div>

        {/* 1. PASTE BIO */}
        <Card title="Coller la bio Insta (raccourci)" theme={theme}>
          <p style={{ margin: "0 0 10px", fontSize: 13.5, color: "var(--ink-3)", lineHeight: 1.5 }}>
            Colle la bio Insta entière. On extrait automatiquement <strong>prénom, @, ville, métier</strong>.
          </p>
          <textarea value={bio} onChange={e => setBio(e.target.value)}
            rows={4} placeholder={"Léa • Coiffeuse à Bordeaux ✂️\n@leaby_coiffure\nBalayages & couleurs naturelles"}
            style={{
              width: "100%", padding: "12px 14px", fontSize: 14,
              background: "white", border: "1px solid var(--line-strong)",
              borderRadius: 10, fontFamily: "inherit", outline: "none",
              resize: "vertical", minHeight: 90,
            }}/>
          <button onClick={applyExtraction} disabled={!bio.trim()} style={{
            marginTop: 8, padding: "9px 16px", fontSize: 13.5, fontWeight: 520,
            background: bio.trim() ? theme.base : "var(--bg-alt)",
            color: bio.trim() ? "white" : "var(--ink-4)",
            border: "none", borderRadius: 999, cursor: bio.trim() ? "pointer" : "not-allowed",
            fontFamily: "inherit",
          }}>
            ✦ Auto-remplir les champs
          </button>
        </Card>

        {/* 2. MÉTIER (chips visuelles + champ libre) */}
        <Card title="Métier" theme={theme}>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
            {Object.keys(METIER_PRESETS).map(k => {
              const p = METIER_PRESETS[k];
              const active = form.metier === k;
              const t = _themeFromHue(p.hue);
              return (
                <button key={k} onClick={() => pickMetier(k)} style={{
                  padding: "8px 12px", fontSize: 13, fontWeight: 500,
                  background: active ? t.base : "white",
                  color: active ? "white" : "var(--ink-2)",
                  border: `1px solid ${active ? t.base : "var(--line)"}`,
                  borderRadius: 999, cursor: "pointer", fontFamily: "inherit",
                  display: "inline-flex", alignItems: "center", gap: 6,
                  transition: "all .15s",
                }}>
                  <span>{p.emoji}</span> {p.label}
                </button>
              );
            })}
          </div>
          <div style={{ marginTop: 12 }}>
            <label style={{ fontSize: 12.5, color: "var(--ink-3)", fontWeight: 500 }}>
              Ou tape un métier libre (si pas dans la liste) :
            </label>
            <input type="text" value={form.metier} onChange={e => setForm({ ...form, metier: e.target.value })}
              placeholder="ex. décoratrice d'intérieur, prof de piano…"
              style={{
                marginTop: 6, width: "100%", padding: "10px 12px", fontSize: 14,
                background: "white", border: "1px solid var(--line-strong)",
                borderRadius: 9, fontFamily: "inherit", outline: "none",
              }}/>
          </div>
        </Card>

        {/* 3. INFOS DE BASE */}
        <Card title="Infos" theme={theme}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }} className="app-split">
            <DossierField label="Prénom" value={form.forName} onChange={v => setForm({ ...form, forName: v })} placeholder="Léa"/>
            <DossierField label="Ville" value={form.ville} onChange={v => setForm({ ...form, ville: v })} placeholder="Bordeaux"/>
          </div>
          <div style={{ marginTop: 10, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }} className="app-split">
            <DossierField label="Salon / entreprise" value={form.salon} onChange={v => setForm({ ...form, salon: v })} placeholder="Ongles by Léa"/>
            <DossierField label="Handle Insta" value={form.insta} onChange={v => setForm({ ...form, insta: v })} placeholder="leabyongles"/>
          </div>

          <button onClick={() => setMoreOpen(!moreOpen)} style={{
            marginTop: 12, alignSelf: "flex-start",
            padding: "6px 12px", background: "transparent",
            border: "1px solid var(--line)", borderRadius: 999, cursor: "pointer",
            fontSize: 12.5, color: "var(--ink-2)", fontFamily: "inherit",
          }}>
            {moreOpen ? "− Moins de détails" : "+ Détails bonus (spécialité, objectif, mot perso)"}
          </button>

          {moreOpen && (
            <div style={{
              marginTop: 12, padding: 14,
              background: theme.soft, border: `1px dashed ${theme.soft2}`,
              borderRadius: 10, display: "flex", flexDirection: "column", gap: 10,
            }}>
              <DossierField label="Spécialité / niche" value={form.specialty} onChange={v => setForm({ ...form, specialty: v })} placeholder="Balayage blond & ombrés"/>
              <DossierField label="Prestation signature" value={form.signature} onChange={v => setForm({ ...form, signature: v })} placeholder={preset.presta}/>
              <DossierField label="Objectif" value={form.goal} onChange={v => setForm({ ...form, goal: v })} placeholder="Doubler votre CA avant fin 2026"/>
              <div>
                <label style={{ fontSize: 13, fontWeight: 520, color: "var(--ink-2)" }}>Petit mot perso</label>
                <textarea value={form.note} onChange={e => setForm({ ...form, note: e.target.value })}
                  rows={3} placeholder="J'ai vu vos balayages, magnifiques…"
                  style={{
                    marginTop: 6, width: "100%", padding: "10px 12px", fontSize: 14,
                    background: "white", border: "1px solid var(--line-strong)",
                    borderRadius: 9, fontFamily: "inherit", outline: "none",
                    resize: "vertical", minHeight: 70,
                  }}/>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 8 }}>
                  {noteSuggestions.map((s, i) => (
                    <button key={i} onClick={() => setForm({ ...form, note: s })} style={{
                      padding: "5px 10px", fontSize: 11.5, color: "var(--ink-2)",
                      background: "white", border: "1px solid var(--line)",
                      borderRadius: 999, cursor: "pointer", fontFamily: "inherit",
                      maxWidth: "100%", textAlign: "left",
                      whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
                    }} title={s}>
                      ✦ Suggestion {i + 1}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}
        </Card>

        {/* 4. LIEN GÉNÉRÉ */}
        <Card title="Lien à envoyer" theme={theme}>
          <input ref={linkInputRef} readOnly value={url} onClick={e => e.target.select()} style={{
            width: "100%", padding: "10px 12px", fontSize: 13,
            background: "var(--bg-alt)", color: "var(--ink-2)",
            border: "1px solid var(--line-strong)",
            borderRadius: 8, fontFamily: "inherit",
            outline: "none", letterSpacing: "-0.005em",
          }}/>
          <div style={{ marginTop: 10, display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
            <button onClick={copy} style={{
              padding: "9px 16px", fontSize: 13.5, fontWeight: 560,
              background: copied ? "var(--sage-soft)" : theme.base,
              color: copied ? "oklch(38% 0.08 160)" : "white",
              border: "none", borderRadius: 999, cursor: "pointer", fontFamily: "inherit",
            }}>
              {copied ? "✓ Copié" : "Copier le lien"}
            </button>
            <a href={url} target="_blank" rel="noopener noreferrer" style={{
              padding: "9px 16px", fontSize: 13.5, fontWeight: 500,
              background: "white", color: "var(--ink-2)",
              border: "1px solid var(--line)", borderRadius: 999,
              fontFamily: "inherit", textDecoration: "none",
            }}>
              Aperçu ↗
            </a>
            <span style={{ marginLeft: "auto", fontSize: 12, color: "var(--ink-4)" }}>
              ⌘ + Entrée pour copier
            </span>
          </div>
        </Card>

        {/* 5. HISTORIQUE */}
        {history.length > 0 && (
          <Card title={`Historique (${history.length})`} theme={theme}>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {history.map(h => {
                const p = _resolvePreset(h.form.metier);
                return (
                  <div key={h.id} style={{
                    display: "flex", alignItems: "center", gap: 10,
                    padding: "8px 12px",
                    background: "var(--bg-alt)", border: "1px solid var(--line)",
                    borderRadius: 10,
                  }}>
                    <span style={{ fontSize: 18 }}>{p.emoji}</span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 530, color: "var(--ink)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                        {h.form.forName || "(sans prénom)"}{h.form.salon ? ` — ${h.form.salon}` : ""}
                      </div>
                      <div style={{ fontSize: 11.5, color: "var(--ink-4)" }}>
                        {p.label}{h.form.ville ? ` · ${h.form.ville}` : ""}
                      </div>
                    </div>
                    <button onClick={() => loadFromHistory(h)} style={{
                      padding: "5px 10px", fontSize: 12, fontWeight: 500,
                      background: "white", border: "1px solid var(--line)",
                      borderRadius: 999, cursor: "pointer", fontFamily: "inherit", color: "var(--ink-2)",
                    }}>
                      Charger
                    </button>
                    <button onClick={() => deleteFromHistory(h.id)} style={{
                      padding: "5px 8px", fontSize: 14, lineHeight: 1,
                      background: "transparent", border: "none",
                      color: "var(--ink-4)", cursor: "pointer", fontFamily: "inherit",
                    }} title="Supprimer">×</button>
                  </div>
                );
              })}
            </div>
          </Card>
        )}
      </div>
    </div>
  );
};

const Card = ({ title, children, theme }) => (
  <div style={{
    marginTop: 14, padding: "18px 20px",
    background: "white", border: "1px solid var(--line)",
    borderRadius: 14,
  }}>
    <div style={{
      fontFamily: "var(--ff-display)", fontSize: 15, fontWeight: 580,
      color: "var(--ink)", marginBottom: 12, letterSpacing: "-0.015em",
    }}>
      {title}
    </div>
    {children}
  </div>
);

const DossierField = ({ label, value, onChange, placeholder }) => (
  <div>
    <label style={{ fontSize: 13, fontWeight: 520, color: "var(--ink-2)" }}>{label}</label>
    <input type="text" value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder}
      style={{
        marginTop: 6, width: "100%", padding: "10px 12px", fontSize: 14.5,
        background: "white", border: "1px solid var(--line-strong)",
        borderRadius: 9, fontFamily: "inherit", outline: "none",
      }}/>
  </div>
);

Object.assign(window, { InvitePage, _getInviteFromLocation });
