/* ClientBase — About, Contact, Login pages */

const AboutPage = ({ go }) => (
  <>
    <PageHeader eyebrow="À propos"
      title="Un petit projet français, au début de l'aventure."
      subtitle="ClientBase est en bêta. On cherche des indépendants pour construire l'outil avec nous."/>

    <section style={{ padding: "40px 0 80px" }}>
      <div className="container">
        <div style={{
          maxWidth: 760, margin: "0 auto",
          fontSize: 17, lineHeight: 1.7, color: "var(--ink-2)",
        }}>
          <p style={{ fontSize: 19, color: "var(--ink-2)" }}>
            ClientBase est né d'un constat simple : les outils existants pour les indépendants du service sont soit trop chers, soit trop compliqués, soit les deux. On s'est dit qu'on pouvait faire mieux, plus simple, plus juste.
          </p>
          <p style={{ marginTop: 24 }}>
            On est au tout début : l'app fonctionne, mais elle a besoin de vos retours pour grandir. C'est pour ça qu'on ouvre la bêta — vous utilisez gratuitement, vous nous dites ce qui va ou pas, et on adapte l'outil à la réalité de votre métier.
          </p>
          <p style={{ marginTop: 24 }}>
            Ce qu'on s'engage à tenir dès maintenant : un prix juste quand on lancera officiellement, une interface simple à comprendre, et un support humain — pas un bot. Pas de commission sur vos RDV, jamais.
          </p>
          <div style={{ fontFamily: "var(--ff-display)", fontSize: 18, fontWeight: 560, marginTop: 40, color: "var(--ink)" }}>
            — L'équipe ClientBase
          </div>
        </div>

        {/* Honest status */}
        <div style={{
          marginTop: 64,
          display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16,
        }} className="nums-grid">
          {[
            ["Bêta", "statut du projet"],
            ["Gratuit", "pendant toute la bêta"],
            ["< 15 min", "pour être opérationnel"],
            ["🇫🇷", "hébergé en France"],
          ].map(([v, l]) => (
            <div key={l} style={{
              padding: "28px 24px",
              background: "var(--surface)", border: "1px solid var(--line)",
              borderRadius: 14, textAlign: "left",
            }}>
              <div style={{ fontFamily: "var(--ff-display)", fontSize: 38, fontWeight: 580, letterSpacing: "-0.035em" }}>{v}</div>
              <div style={{ fontSize: 13.5, color: "var(--ink-3)", marginTop: 4 }}>{l}</div>
            </div>
          ))}
        </div>

        {/* Values */}
        <div style={{ marginTop: 96 }}>
          <h2 style={{ textAlign: "center", fontSize: 32, marginBottom: 48 }}>Ce qui nous guide</h2>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 20 }} className="values-grid">
            {[
              { icon: "shield", title: "Honnêteté", desc: "Un prix affiché, pas de frais cachés, pas de commission sur vos RDV. Ce que vous payez, c'est ce que vous payez." },
              { icon: "zap", title: "Simplicité", desc: "Chaque nouvelle fonctionnalité doit réussir le test du « ma mère peut-elle l'utiliser sans tuto ? »" },
              { icon: "heart", title: "Proximité", desc: "Un support humain, en français, qui comprend votre métier. Pas un bot qui tourne en rond." },
            ].map(v => (
              <div key={v.title} style={{
                padding: 28, border: "1px solid var(--line)", borderRadius: 14,
                background: "var(--surface)",
              }}>
                <div style={{
                  width: 40, height: 40, borderRadius: 10,
                  background: "var(--accent-soft)", color: "var(--accent-ink)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}>
                  <Icon name={v.icon} size={20}/>
                </div>
                <h3 style={{ marginTop: 14, fontSize: 19 }}>{v.title}</h3>
                <p style={{ marginTop: 8, fontSize: 14.5 }}>{v.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>

    <FinalCTA go={go}/>
  </>
);

/* ============ CONTACT PAGE ============ */
// Adresse contact globale — affichée et utilisée pour les formulaires
const CB_CONTACT_EMAIL = "clientbase.fr@gmail.com";
// Endpoint FormSubmit — zéro setup, les mails arrivent directement
const CB_FORM_ENDPOINT = `https://formsubmit.co/ajax/${CB_CONTACT_EMAIL}`;

/** Envoie un message via FormSubmit.co. Retourne { ok } ou { error }. */
const sendContactMail = async ({ subject, from, replyTo, message, meta }) => {
  try {
    const res = await fetch(CB_FORM_ENDPOINT, {
      method: "POST",
      headers: { "Content-Type": "application/json", "Accept": "application/json" },
      body: JSON.stringify({
        _subject: subject,
        _replyto: replyTo,
        _template: "table",
        _captcha: "false",
        name: from, email: replyTo,
        message,
        ...(meta || {}),
      }),
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok || data.success === "false") {
      return { error: data.message || "Erreur d'envoi. Réessayez dans un instant." };
    }
    return { ok: true };
  } catch (e) {
    return { error: "Impossible d'envoyer (réseau). Réessayez." };
  }
};

const ContactPage = () => {
  const [form, setForm] = React.useState({ name: "", email: "", subject: "Question générale", message: "" });
  const [sent, setSent] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  const isMobile = useIsMobile(760);

  const submit = async (e) => {
    e.preventDefault();
    setError(null);
    if (!form.name.trim()) return setError("Votre nom est requis.");
    if (!cbAuth.isValidEmail(form.email)) return setError("Email invalide. Exemple : prenom@exemple.fr");
    if (!form.message.trim() || form.message.trim().length < 10) return setError("Votre message est trop court.");

    setBusy(true);
    const res = await sendContactMail({
      subject: `[ClientBase — ${form.subject}] ${form.name}`,
      from: form.name,
      replyTo: form.email,
      message: form.message,
      meta: { Source: "Page vitrine /contact" },
    });
    setBusy(false);
    if (res.error) return setError(res.error);
    setSent(true);
  };

  // Carte email rapide (mobile : tout en haut pour un contact express)
  const QuickMail = () => (
    <a href={`mailto:${CB_CONTACT_EMAIL}`} style={{
      padding: "16px 18px",
      background: "linear-gradient(135deg, var(--accent-soft) 0%, var(--surface) 70%)",
      border: "1px solid var(--accent-soft-2)",
      borderRadius: 14, display: "flex", gap: 14, alignItems: "center",
      textDecoration: "none", color: "inherit",
    }}>
      <div style={{
        width: 42, height: 42, borderRadius: 11,
        background: "var(--accent)", color: "white",
        display: "flex", alignItems: "center", justifyContent: "center",
        flexShrink: 0, boxShadow: "0 6px 14px -6px var(--accent)",
      }}>
        <Icon name="mail" size={18}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12, color: "var(--ink-4)", fontWeight: 500 }}>Envoi direct</div>
        <div style={{ fontWeight: 560, fontSize: 15, color: "var(--ink)", marginTop: 2, wordBreak: "break-all" }}>
          {CB_CONTACT_EMAIL}
        </div>
        <div style={{ fontSize: 12, color: "var(--ink-4)", marginTop: 2 }}>Réponse sous 24 h ouvrées</div>
      </div>
      <Icon name="arrow" size={15} style={{ color: "var(--accent-ink)", flexShrink: 0 }}/>
    </a>
  );

  return (
    <>
      <PageHeader eyebrow="Contact"
        title="On est là, vraiment."
        subtitle="Une question, une demande spécifique, ou juste envie de dire bonjour ? Écrivez-nous, on répond en moins de 24 h."/>

      <section style={{ padding: "20px 0 96px" }}>
        <div className="container">
          {isMobile ? (
            /* ===== Mobile : carte email rapide en haut, puis formulaire ===== */
            <div style={{ maxWidth: 560, margin: "0 auto", display: "flex", flexDirection: "column", gap: 16 }}>
              <QuickMail/>
              <div style={{
                padding: "10px 14px", background: "var(--bg-alt)",
                border: "1px solid var(--line)", borderRadius: 10,
                fontSize: 12.5, color: "var(--ink-3)", lineHeight: 1.5,
                display: "flex", gap: 10, alignItems: "center",
              }}>
                <Icon name="chat" size={14} style={{ color: "var(--accent-ink)", flexShrink: 0 }}/>
                <span>Déjà inscrit·e ? Contactez-nous directement depuis <strong>Paramètres → Nous contacter</strong> dans l'app.</span>
              </div>

              <form onSubmit={submit} style={{
                padding: 20, border: "1px solid var(--line)", borderRadius: 14,
                background: "var(--surface)",
              }}>
                {sent ? (
                  <div style={{ textAlign: "center", padding: "24px 12px" }}>
                    <div style={{
                      width: 52, height: 52, borderRadius: 50, margin: "0 auto",
                      background: "var(--sage-soft)", color: "var(--sage)",
                      display: "flex", alignItems: "center", justifyContent: "center",
                    }}>
                      <Icon name="check" size={26} stroke={2.5}/>
                    </div>
                    <h3 style={{ marginTop: 14, fontSize: 20 }}>Message envoyé !</h3>
                    <p style={{ marginTop: 8, fontSize: 14 }}>Réponse sous 24 h à <strong>{form.email}</strong>.</p>
                    <button className="btn btn-ghost btn-sm" style={{ marginTop: 16 }}
                      onClick={() => { setSent(false); setForm({ name: "", email: "", subject: "Question générale", message: "" }); }}>
                      Nouveau message
                    </button>
                  </div>
                ) : (
                  <>
                    <h3 style={{ fontSize: 17, marginBottom: 4 }}>Écrivez-nous</h3>
                    <p style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 16, lineHeight: 1.5 }}>
                      Arrive directement à {CB_CONTACT_EMAIL}.
                    </p>
                    {error && (
                      <div style={{
                        marginBottom: 14, padding: "10px 14px",
                        background: "oklch(96% 0.04 25)", border: "1px solid oklch(88% 0.06 25)",
                        color: "oklch(42% 0.15 25)", borderRadius: 10, fontSize: 13,
                      }}>{error}</div>
                    )}
                    <div style={{ display: "grid", gap: 14 }}>
                      <Field label="Votre nom" value={form.name} onChange={v => setForm({...form, name: v})} placeholder="Camille Dupont"/>
                      <Field label="Email" type="email" value={form.email} onChange={v => setForm({...form, email: v})} placeholder="vous@exemple.fr"/>
                      <div>
                        <label style={labelStyle}>Sujet</label>
                        <select value={form.subject} onChange={e => setForm({...form, subject: e.target.value})} style={{...inputStyle, appearance: "none"}}>
                          {["Question générale", "Support technique", "Démo personnalisée", "Presse / partenariat"].map(s => <option key={s}>{s}</option>)}
                        </select>
                      </div>
                      <div>
                        <label style={labelStyle}>Message</label>
                        <textarea value={form.message} onChange={e => setForm({...form, message: e.target.value})} rows={5}
                          style={{...inputStyle, resize: "vertical", minHeight: 120, fontFamily: "inherit"}}
                          placeholder="Parlez-nous de votre activité, on adore les détails…"/>
                      </div>
                      <button type="submit" disabled={busy} className="btn btn-accent btn-lg"
                        style={{ width: "100%", marginTop: 2, opacity: busy ? 0.7 : 1 }}>
                        {busy ? "Envoi…" : "Envoyer le message"} <Icon name="arrow" size={14}/>
                      </button>
                    </div>
                  </>
                )}
              </form>
            </div>
          ) : (
          /* ===== Desktop : grille info | formulaire ===== */
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1.3fr", gap: 48, maxWidth: 1000, margin: "0 auto" }}>
            {/* Left — contact info */}
            <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
              {[
                { icon: "mail", title: "Email", value: CB_CONTACT_EMAIL, sub: "Réponse sous 24h ouvrées", href: `mailto:${CB_CONTACT_EMAIL}` },
                { icon: "chat", title: "Directement depuis l'app", value: "Menu Paramètres → Nous contacter", sub: "Recommandé si vous êtes inscrit·e" },
              ].map(c => (
                <a key={c.title} href={c.href || undefined}
                  style={{
                    padding: 22, border: "1px solid var(--line)", borderRadius: 12,
                    background: "var(--surface)", display: "flex", gap: 14,
                    textDecoration: "none", color: "inherit",
                  }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: 9,
                    background: "var(--accent-soft)", color: "var(--accent-ink)",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    flexShrink: 0,
                  }}>
                    <Icon name={c.icon} size={17}/>
                  </div>
                  <div>
                    <div style={{ fontSize: 13, color: "var(--ink-4)" }}>{c.title}</div>
                    <div style={{ fontWeight: 520, color: "var(--ink)", marginTop: 2, wordBreak: "break-all" }}>{c.value}</div>
                    <div style={{ fontSize: 12.5, color: "var(--ink-4)", marginTop: 2 }}>{c.sub}</div>
                  </div>
                </a>
              ))}
              <div style={{
                padding: 22, background: "var(--bg-alt)", borderRadius: 12,
                fontSize: 13, color: "var(--ink-2)", lineHeight: 1.6,
              }}>
                <div style={{ fontWeight: 520, color: "var(--ink)", fontSize: 13.5 }}>ClientBase</div>
                <div style={{ marginTop: 6, fontSize: 13 }}>Application web française · en bêta · aucune adresse physique à ce jour.</div>
              </div>
            </div>

            {/* Right — form */}
            <form onSubmit={submit} style={{
              padding: 32, border: "1px solid var(--line)", borderRadius: 14,
              background: "var(--surface)",
            }}>
              {sent ? (
                <div style={{ textAlign: "center", padding: "40px 20px" }}>
                  <div style={{
                    width: 56, height: 56, borderRadius: 50, margin: "0 auto",
                    background: "var(--sage-soft)", color: "var(--sage)",
                    display: "flex", alignItems: "center", justifyContent: "center",
                  }}>
                    <Icon name="check" size={28} stroke={2.5}/>
                  </div>
                  <h3 style={{ marginTop: 16, fontSize: 22 }}>Message envoyé !</h3>
                  <p style={{ marginTop: 8 }}>On vous répond sous 24h ouvrées à <strong>{form.email}</strong>.</p>
                  <button className="btn btn-ghost" style={{ marginTop: 20 }} onClick={() => { setSent(false); setForm({ name: "", email: "", subject: "Question générale", message: "" }); }}>
                    Nouveau message
                  </button>
                </div>
              ) : (
                <>
                  <h3 style={{ fontSize: 20, marginBottom: 6 }}>Envoyez-nous un message</h3>
                  <p style={{ fontSize: 13.5, marginBottom: 24 }}>
                    Arrive directement à <strong>{CB_CONTACT_EMAIL}</strong>.
                  </p>

                  {error && (
                    <div style={{
                      marginBottom: 16, padding: "10px 14px",
                      background: "oklch(96% 0.04 25)", border: "1px solid oklch(88% 0.06 25)",
                      color: "oklch(42% 0.15 25)", borderRadius: 10, fontSize: 13.5,
                    }}>{error}</div>
                  )}

                  <div style={{ display: "grid", gap: 16 }}>
                    <Field label="Votre nom" value={form.name} onChange={v => setForm({...form, name: v})} placeholder="Camille Dupont"/>
                    <Field label="Email" type="email" value={form.email} onChange={v => setForm({...form, email: v})} placeholder="vous@exemple.fr"/>
                    <div>
                      <label style={labelStyle}>Sujet</label>
                      <select value={form.subject} onChange={e => setForm({...form, subject: e.target.value})} style={{...inputStyle, appearance: "none"}}>
                        {["Question générale", "Support technique", "Démo personnalisée", "Presse / partenariat"].map(s => <option key={s}>{s}</option>)}
                      </select>
                    </div>
                    <div>
                      <label style={labelStyle}>Message</label>
                      <textarea value={form.message} onChange={e => setForm({...form, message: e.target.value})} rows={5} style={{...inputStyle, resize: "vertical", minHeight: 120, fontFamily: "inherit"}} placeholder="Parlez-nous de votre activité, on adore les détails…"/>
                    </div>
                    <button type="submit" disabled={busy} className="btn btn-primary btn-lg" style={{ width: "100%", marginTop: 6, opacity: busy ? 0.7 : 1 }}>
                      {busy ? "Envoi…" : "Envoyer le message"}
                    </button>
                  </div>
                </>
              )}
            </form>
          </div>
          )}
        </div>
      </section>

      {/* FAQ — déplacée depuis la page tarif */}
      <section style={{
        padding: "60px 0 96px",
        background: "var(--bg-section)", borderTop: "1px solid var(--line)",
      }}>
        <div className="container" style={{ maxWidth: 760 }}>
          <div style={{ textAlign: "center", marginBottom: 28 }}>
            <div style={{
              display: "inline-flex", alignItems: "center", gap: 8,
              padding: "5px 12px 5px 10px",
              background: "var(--accent-soft)", border: "1px solid var(--accent-soft-2)",
              borderRadius: 999, fontSize: 11.5, fontWeight: 600,
              color: "var(--accent-ink)", letterSpacing: "0.04em", textTransform: "uppercase",
            }}>
              <Icon name="chat" size={11}/>
              Questions fréquentes
            </div>
            <h2 style={{ fontSize: "clamp(24px, 3vw, 30px)", marginTop: 12, letterSpacing: "-0.025em" }}>
              On a peut-être déjà la réponse
            </h2>
          </div>
          <div style={{
            background: "var(--surface)", border: "1px solid var(--line)",
            borderRadius: 16, overflow: "hidden",
          }}>
            {(window.CONTACT_FAQ || []).map(([q, a], i, arr) => (
              <details key={i} style={{
                borderBottom: i < arr.length - 1 ? "1px solid var(--line)" : "none",
                padding: "18px 22px",
              }}>
                <summary style={{
                  fontSize: 15, fontWeight: 520, cursor: "pointer",
                  listStyle: "none", display: "flex", justifyContent: "space-between", alignItems: "center",
                  color: "var(--ink)", gap: 12,
                }}>
                  <span>{q}</span>
                  <Icon name="plus" size={15} style={{ color: "var(--ink-3)", flexShrink: 0 }}/>
                </summary>
                <p style={{ marginTop: 10, fontSize: 14, lineHeight: 1.6, color: "var(--ink-2)" }}>{a}</p>
              </details>
            ))}
          </div>
        </div>
      </section>
    </>
  );
};

const labelStyle = { display: "block", fontSize: 13, fontWeight: 500, color: "var(--ink-2)", marginBottom: 6 };
const inputStyle = {
  width: "100%", padding: "11px 14px", fontSize: 16, fontFamily: "inherit",
  background: "var(--bg)", border: "1px solid var(--line-strong)", borderRadius: 9,
  color: "var(--ink)", outline: "none",
  transition: "border-color .15s, box-shadow .15s",
};

const Field = ({ label, type = "text", value, onChange, placeholder }) => (
  <div>
    <label style={labelStyle}>{label}</label>
    <input type={type} value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder} style={inputStyle}/>
  </div>
);

/* ============ Password field with eye toggle + optional strength meter ============ */
const PasswordField = ({ value, onChange, placeholder = "••••••••", autoComplete = "current-password", showMeter = false }) => {
  const [shown, setShown] = React.useState(false);
  const score = showMeter ? cbAuth.scorePassword(value) : 0;
  const bands = [
    { label: "trop court",  color: "oklch(70% 0.18 25)"  },
    { label: "faible",      color: "oklch(70% 0.17 50)"  },
    { label: "moyen",       color: "oklch(75% 0.15 85)"  },
    { label: "bon",         color: "oklch(72% 0.14 160)" },
    { label: "excellent",   color: "oklch(62% 0.16 160)" },
  ];
  const band = bands[score];
  return (
    <div>
      <div style={{ position: "relative" }}>
        <input
          type={shown ? "text" : "password"}
          value={value}
          onChange={e => onChange(e.target.value)}
          placeholder={placeholder}
          autoComplete={autoComplete}
          style={{ ...inputStyle, paddingRight: 44 }}
        />
        <button type="button" onClick={() => setShown(!shown)}
          aria-label={shown ? "Masquer le mot de passe" : "Afficher le mot de passe"}
          style={{
            position: "absolute", right: 6, top: "50%", transform: "translateY(-50%)",
            width: 34, height: 34, background: "transparent", border: "none",
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            cursor: "pointer", color: "var(--ink-4)", borderRadius: 6,
          }}>
          <Icon name={shown ? "eyeOff" : "eye"} size={16}/>
        </button>
      </div>
      {showMeter && value && (
        <div style={{ marginTop: 6, display: "flex", alignItems: "center", gap: 8 }}>
          <div style={{ flex: 1, display: "flex", gap: 3 }}>
            {[0, 1, 2, 3].map(i => (
              <div key={i} style={{
                flex: 1, height: 4, borderRadius: 999,
                background: i < score ? band.color : "var(--line)",
                transition: "background .2s",
              }}/>
            ))}
          </div>
          <span style={{ fontSize: 11, color: band.color, fontWeight: 520, minWidth: 68, textAlign: "right" }}>
            {band.label}
          </span>
        </div>
      )}
    </div>
  );
};

/* ============ LOGIN / SIGNUP PAGE ============
   `forcedMode` est passé par le routeur (page="login" → "login",
   page="signup" → "signup"). Les modes `forgot` et `reset` sont atteints
   depuis la page login. */
const LoginPage = ({ go, forcedMode }) => {
  const existingUser = cbAuth.getCurrentUser();
  // Détecte un retour de lien "mot de passe oublié" (?reset=1 dans l'URL)
  const comingFromReset = typeof window !== "undefined"
    && new URLSearchParams(window.location.search).get("reset") === "1";

  const [mode, setMode] = React.useState(() => {
    if (comingFromReset) return "reset";
    if (forcedMode === "login" || forcedMode === "signup") return forcedMode;
    const intent = window.__cbLoginMode;
    window.__cbLoginMode = null;
    if (intent === "login" || intent === "signup") return intent;
    return existingUser ? "login" : "signup";
  });
  // Si la route change (navigation depuis la nav), on réaligne
  React.useEffect(() => {
    if (forcedMode === "login" || forcedMode === "signup") setMode(forcedMode);
    // eslint-disable-next-line
  }, [forcedMode]);
  const [form, setForm] = React.useState({
    email: existingUser ? existingUser.email : "",
    password: "",
    passwordConfirm: "",
    businessName: "",
    ownerName: "",
    rgpd: false,
  });
  const [error, setError] = React.useState(null);
  const [info, setInfo] = React.useState(null);
  const [busy, setBusy] = React.useState(false);

  const switchMode = (m) => { setError(null); setInfo(null); setMode(m); };

  const onSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    setInfo(null);
    setBusy(true);
    try {
      if (mode === "signup") {
        if (!cbAuth.isValidEmail(form.email)) { setError("Email invalide. Exemple : prenom@exemple.fr"); setBusy(false); return; }
        if (!form.rgpd) { setError("Vous devez accepter la politique de confidentialité."); setBusy(false); return; }
        const res = await cbAuth.signup(form);
        if (res.error) { setError(res.error); setBusy(false); return; }
        if (res.needsEmailConfirm) {
          // Cas peu probable : l'admin a laissé "Confirm email" ON dans Supabase.
          setInfo(`Compte créé. Pour finaliser, cliquez sur le lien envoyé à ${form.email}.`);
          setBusy(false);
          return;
        }
        // Cas normal (recommandé) : Confirm email OFF → session immédiate
        go("app");
      } else if (mode === "login") {
        const res = await cbAuth.login(form);
        if (res.error) { setError(res.error); setBusy(false); return; }
        go("app");
      } else if (mode === "forgot") {
        const res = await cbAuth.resetPassword(form.email);
        if (res.error) { setError(res.error); setBusy(false); return; }
        setInfo(`Un email vient d'être envoyé à ${form.email}. Cliquez sur le lien qu'il contient pour choisir un nouveau mot de passe.`);
      } else if (mode === "reset") {
        if (form.password !== form.passwordConfirm) { setError("Les deux mots de passe ne correspondent pas."); setBusy(false); return; }
        const res = await cbAuth.updatePassword(form.password);
        if (res.error) { setError(res.error); setBusy(false); return; }
        // Nettoie l'URL pour éviter de réappliquer au reload
        try { window.history.replaceState({}, "", window.location.pathname); } catch {}
        setInfo("Mot de passe modifié. Vous êtes maintenant connecté·e.");
        setTimeout(() => go("app"), 700);
      }
    } finally {
      setBusy(false);
    }
  };

  const title = mode === "login"   ? "Bon retour."
             : mode === "signup"   ? "Rejoindre la bêta."
             : mode === "forgot"   ? "Mot de passe oublié"
             : /* reset */           "Nouveau mot de passe";
  const subtitle = mode === "login"   ? "Connectez-vous pour retrouver votre agenda et vos clients."
                : mode === "signup"   ? "Gratuit pendant toute la bêta. Sans carte bancaire."
                : mode === "forgot"   ? "Entrez votre email — on vous envoie un lien pour réinitialiser."
                : /* reset */           "Choisissez un nouveau mot de passe sécurisé.";
  const submitLabel = mode === "login"   ? "Se connecter"
                   : mode === "signup"   ? "Créer mon compte"
                   : mode === "forgot"   ? "Envoyer le lien"
                   : /* reset */           "Enregistrer";

  // ===== Avatar live + progress + encouragement (signup uniquement) =====
  const initials = (form.ownerName || "").trim()
    .split(/\s+/).map(s => s[0]).slice(0, 2).join("").toUpperCase();
  const avatarHue = (() => {
    let h = 0;
    for (const c of (form.ownerName || "")) h = (h * 31 + c.charCodeAt(0)) >>> 0;
    return h % 360;
  })();

  const isEmailValid = cbAuth.isValidEmail(form.email);
  const isPwdValid = !cbAuth.validatePassword(form.password);
  const filledCount = (
    (form.ownerName.trim() ? 1 : 0) +
    (form.businessName.trim() ? 1 : 0) +
    (isEmailValid ? 1 : 0) +
    (isPwdValid ? 1 : 0) +
    (form.rgpd ? 1 : 0)
  );
  const progressPct = (filledCount / 5) * 100;
  const encouragement =
    filledCount === 0 ? "Allez, c'est parti — ça prend 30 secondes."
    : filledCount === 5 ? "Tout est prêt 🎉 Cliquez pour finaliser."
    : filledCount >= 3 ? `Plus que ${5 - filledCount} champ${5 - filledCount > 1 ? "s" : ""} !`
    : "On continue…";

  return (
    <section style={{ minHeight: "calc(100vh - 64px)", display: "flex", alignItems: "stretch", position: "relative", overflow: "hidden" }}>
      <style>{`
        @keyframes cbAuthFadeUp {
          from { opacity: 0; transform: translateY(10px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        @keyframes cbAuthSparkle {
          0%, 100% { transform: rotate(0) scale(1); opacity: 1; }
          50%      { transform: rotate(180deg) scale(1.15); opacity: 0.85; }
        }
        .cb-auth-field { animation: cbAuthFadeUp .5s cubic-bezier(.22,1,.36,1) both; }
        .cb-auth-field:nth-child(1) { animation-delay: 0.05s; }
        .cb-auth-field:nth-child(2) { animation-delay: 0.10s; }
        .cb-auth-field:nth-child(3) { animation-delay: 0.15s; }
        .cb-auth-field:nth-child(4) { animation-delay: 0.20s; }
        .cb-auth-field:nth-child(5) { animation-delay: 0.25s; }
      `}</style>

      {/* Aurora indigo cohérent avec le hero */}
      <div aria-hidden style={{
        position: "absolute", inset: 0, pointerEvents: "none",
        background: "radial-gradient(ellipse 50% 45% at 50% 20%, var(--accent-soft) 0%, transparent 70%)",
        opacity: 0.6,
      }}/>

      <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", padding: "40px 24px", position: "relative" }}>
        <div style={{ width: "100%", maxWidth: 420 }}>
          {/* Eyebrow */}
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "5px 14px 5px 6px",
            background: "var(--surface)", border: "1px solid var(--line-strong)",
            borderRadius: 999, fontSize: 12.5, fontWeight: 520,
            color: "var(--ink-2)", marginBottom: 18,
            boxShadow: "var(--sh-1)",
          }}>
            <span style={{
              width: 18, height: 18, borderRadius: 50,
              background: "var(--accent)", color: "white",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              fontSize: 10, fontWeight: 700,
              animation: "cbAuthSparkle 4s ease-in-out infinite",
            }}>✦</span>
            {mode === "signup" ? "Bêta gratuite · sans CB" :
             mode === "login" ? "Bon à vous revoir" :
             "Récupération de compte"}
          </div>

          <h1 style={{ fontSize: "clamp(28px, 4vw, 36px)", letterSpacing: "-0.025em", lineHeight: 1.1, margin: 0 }}>
            {title}
          </h1>
          <p style={{ marginTop: 10, fontSize: 15, color: "var(--ink-3)" }}>{subtitle}</p>

          {/* Avatar live preview + progress (signup uniquement) */}
          {mode === "signup" && (
            <div style={{
              marginTop: 22, padding: "16px 18px",
              background: "var(--surface)", border: "1px solid var(--line)",
              borderRadius: 14, display: "flex", alignItems: "center", gap: 14,
              animation: "cbAuthFadeUp .5s cubic-bezier(.22,1,.36,1) both",
            }}>
              <div style={{
                width: 52, height: 52, borderRadius: 50, flexShrink: 0,
                background: initials
                  ? `linear-gradient(135deg, oklch(78% 0.14 ${avatarHue}), oklch(65% 0.18 ${(avatarHue + 40) % 360}))`
                  : "var(--bg-alt)",
                color: initials ? "white" : "var(--ink-4)",
                display: "flex", alignItems: "center", justifyContent: "center",
                fontFamily: "var(--ff-display)", fontWeight: 600, fontSize: 20,
                boxShadow: initials ? "0 6px 16px -6px var(--accent)" : "none",
                transition: "background .35s ease, box-shadow .35s ease",
              }}>
                {initials || "?"}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, color: "var(--ink-3)", fontWeight: 500, marginBottom: 6 }}>
                  {encouragement}
                </div>
                <div style={{
                  height: 5, background: "var(--bg-alt)",
                  borderRadius: 999, overflow: "hidden",
                }}>
                  <div style={{
                    width: `${progressPct}%`, height: "100%",
                    background: "linear-gradient(90deg, var(--accent), oklch(60% 0.22 300))",
                    borderRadius: 999,
                    transition: "width .35s cubic-bezier(.22,1,.36,1)",
                  }}/>
                </div>
                <div style={{ marginTop: 4, fontSize: 11, color: "var(--ink-4)", fontVariantNumeric: "tabular-nums" }}>
                  {filledCount}/5 informations remplies
                </div>
              </div>
            </div>
          )}

          {error && (
            <div style={{
              marginTop: 20, padding: "10px 14px",
              background: "oklch(96% 0.04 25)", border: "1px solid oklch(88% 0.06 25)",
              color: "oklch(42% 0.15 25)", borderRadius: 10, fontSize: 13.5,
            }}>{error}</div>
          )}
          {info && (
            <div style={{
              marginTop: 20, padding: "12px 14px",
              background: "var(--sage-soft)", border: "1px solid oklch(88% 0.03 160)",
              color: "oklch(38% 0.08 160)", borderRadius: 10, fontSize: 13.5,
              display: "flex", gap: 10, alignItems: "flex-start",
            }}>
              <Icon name="mail" size={16} style={{ flexShrink: 0, marginTop: 2 }}/>
              <div>{info}</div>
            </div>
          )}

          <form onSubmit={onSubmit} style={{ marginTop: 22, display: "grid", gap: 14 }}>
            {mode === "signup" && (
              <>
                <div className="cb-auth-field">
                  <Field label="Votre nom" value={form.ownerName} onChange={v => setForm({ ...form, ownerName: v })} placeholder="Léa Bernard"/>
                </div>
                <div className="cb-auth-field">
                  <Field label="Nom de votre activité" value={form.businessName} onChange={v => setForm({ ...form, businessName: v })} placeholder="Ongles by Léa"/>
                </div>
              </>
            )}
            {mode !== "reset" && (
              <div className="cb-auth-field" style={{ position: "relative" }}>
                <Field label="Email" type="email" value={form.email}
                  onChange={v => setForm({ ...form, email: v })}
                  placeholder="vous@exemple.fr"/>
                {/* Indicateur live email valide */}
                {form.email.length > 3 && (
                  <span style={{
                    position: "absolute", right: 14, top: 36,
                    fontSize: 14,
                    color: isEmailValid ? "var(--sage)" : "var(--ink-4)",
                    transition: "color .2s ease",
                  }}>
                    {isEmailValid ? "✓" : "…"}
                  </span>
                )}
              </div>
            )}
            {(mode === "login" || mode === "signup" || mode === "reset") && (
              <div className="cb-auth-field">
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                  <label style={labelStyle}>
                    {mode === "reset" ? "Nouveau mot de passe" : "Mot de passe"}
                  </label>
                  {mode === "login" && (
                    <a href="#" onClick={(e) => { e.preventDefault(); switchMode("forgot"); }}
                      style={{ fontSize: 12.5, color: "var(--accent-ink)", fontWeight: 520 }}>
                      Oublié ?
                    </a>
                  )}
                  {(mode === "signup" || mode === "reset") && (
                    <span style={{ fontSize: 12, color: "var(--ink-4)" }}>8 car., 1 lettre, 1 chiffre</span>
                  )}
                </div>
                <PasswordField
                  value={form.password}
                  onChange={v => setForm({ ...form, password: v })}
                  autoComplete={mode === "login" ? "current-password" : "new-password"}
                  showMeter={mode === "signup" || mode === "reset"}
                />
              </div>
            )}
            {mode === "reset" && (
              <div>
                <label style={labelStyle}>Confirmer le mot de passe</label>
                <PasswordField
                  value={form.passwordConfirm}
                  onChange={v => setForm({ ...form, passwordConfirm: v })}
                  autoComplete="new-password"
                />
              </div>
            )}

            {mode === "signup" && (
              <label className="cb-auth-field" style={{ display: "flex", gap: 10, alignItems: "flex-start", fontSize: 12.5, color: "var(--ink-3)", lineHeight: 1.5, cursor: "pointer" }}>
                <input type="checkbox" checked={form.rgpd} onChange={e => setForm({ ...form, rgpd: e.target.checked })} style={{ accentColor: "var(--accent)", width: 16, height: 16, flexShrink: 0, marginTop: 2 }}/>
                <span>
                  J'accepte la <a onClick={(e) => { e.preventDefault(); go("legal"); }} href="#" style={{ color: "var(--accent-ink)", fontWeight: 520 }}>politique de confidentialité</a> et les <a onClick={(e) => { e.preventDefault(); go("legal"); }} href="#" style={{ color: "var(--accent-ink)", fontWeight: 520 }}>conditions d'utilisation</a>.
                </span>
              </label>
            )}

            <button type="submit" disabled={busy} className="btn btn-primary btn-lg" style={{ width: "100%", marginTop: 6, opacity: busy ? 0.7 : 1 }}>
              {busy ? "…" : submitLabel}
            </button>
          </form>

          <div style={{ marginTop: 24, fontSize: 13.5, textAlign: "center", color: "var(--ink-3)" }}>
            {mode === "login" && (<>Pas encore de compte ? <a href="#signup" onClick={(e) => { e.preventDefault(); go("signup"); }} style={{ color: "var(--accent-ink)", fontWeight: 520 }}>Créer un compte</a></>)}
            {mode === "signup" && (<>Déjà inscrit·e ? <a href="#login" onClick={(e) => { e.preventDefault(); go("login"); }} style={{ color: "var(--accent-ink)", fontWeight: 520 }}>Se connecter</a></>)}
            {mode === "forgot" && (<>Retour à la <a href="#login" onClick={(e) => { e.preventDefault(); go("login"); switchMode("login"); }} style={{ color: "var(--accent-ink)", fontWeight: 520 }}>connexion</a></>)}
            {mode === "reset"  && (<>Retour à la <a href="#login" onClick={(e) => { e.preventDefault(); go("login"); }} style={{ color: "var(--accent-ink)", fontWeight: 520 }}>connexion</a></>)}
          </div>

          {/* Trust badges — alignées avec la réalité Supabase */}
          <div style={{
            marginTop: 28, display: "flex", flexWrap: "wrap", gap: 6, justifyContent: "center",
          }}>
            {[
              "🇫🇷 Hébergé en France",
              "🔒 RGPD & chiffré",
              "🤝 Sans engagement",
              "💳 Pas de carte bancaire",
            ].map(t => (
              <span key={t} style={{
                display: "inline-flex", alignItems: "center", gap: 5,
                padding: "5px 11px",
                background: "var(--surface)", border: "1px solid var(--line)",
                borderRadius: 999, fontSize: 11.5, fontWeight: 500, color: "var(--ink-2)",
              }}>{t}</span>
            ))}
          </div>
        </div>
      </div>
      <div style={{
        flex: 1, background: "var(--bg-section)",
        borderLeft: "1px solid var(--line)",
        display: "flex", alignItems: "center", justifyContent: "center", padding: 40,
        position: "relative", overflow: "hidden",
      }} className="login-aside">
        <div aria-hidden style={{
          position: "absolute", inset: 0,
          backgroundImage: "radial-gradient(circle at 1px 1px, var(--line) 1px, transparent 0)",
          backgroundSize: "28px 28px", opacity: 0.6,
        }}/>
        <div style={{ position: "relative", maxWidth: 420 }}>
          <div className="card" style={{ padding: 28, boxShadow: "var(--sh-3)" }}>
            <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "4px 10px 4px 8px", background: "var(--accent-soft)", color: "var(--accent-ink)", borderRadius: 999, fontSize: 12, fontWeight: 520 }}>
              <Icon name="sparkle" size={12}/> Programme bêta
            </div>
            <h3 style={{ marginTop: 14, fontSize: 22 }}>Ce que vous obtenez en rejoignant maintenant</h3>
            <ul style={{ listStyle: "none", padding: 0, margin: "20px 0 0", display: "flex", flexDirection: "column", gap: 12 }}>
              {[
                "Toutes les fonctionnalités, gratuitement, pendant toute la bêta",
                "Accès direct à l'équipe pour vos retours et demandes",
                "On fait évoluer l'outil selon vos vrais besoins du quotidien",
              ].map(t => (
                <li key={t} style={{ display: "flex", gap: 10, alignItems: "flex-start", fontSize: 14, color: "var(--ink-2)", lineHeight: 1.5 }}>
                  <span style={{ width: 20, height: 20, borderRadius: 50, background: "var(--sage-soft)", color: "var(--sage)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0, marginTop: 1 }}>
                    <Icon name="check" size={12} stroke={2.6}/>
                  </span>
                  {t}
                </li>
              ))}
            </ul>
          </div>

          <div style={{
            marginTop: 20, padding: 18,
            background: "var(--surface)", border: "1px solid var(--line)",
            borderRadius: 12, fontSize: 13, color: "var(--ink-3)", lineHeight: 1.6,
          }}>
            <div style={{ fontWeight: 520, color: "var(--ink)", fontSize: 13.5 }}>💬 Une question avant de vous inscrire ?</div>
            <div style={{ marginTop: 6 }}>
              Écrivez à <strong style={{ color: "var(--ink-2)" }}>{CB_CONTACT_EMAIL}</strong> — on répond toujours sous 24 h.
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

/* Page d'atterrissage après clic sur le lien de confirmation email.
   Le client Supabase a déjà avalé le token dans l'URL et créé une session
   automatiquement — on attend juste qu'il signale SIGNED_IN puis on
   propose de continuer vers l'espace pro. */
const EmailConfirmedPage = ({ go }) => {
  const user = cbAuth.getCurrentUser();
  const [loading, setLoading] = React.useState(!user);

  React.useEffect(() => {
    if (user) { setLoading(false); return; }
    // Petite attente : Supabase finit de valider le token et fire SIGNED_IN
    const t = setInterval(() => {
      const u = cbAuth.getCurrentUser();
      if (u) { setLoading(false); clearInterval(t); }
    }, 200);
    // Si rien après 5s, on arrête le spinner et on propose la connexion manuelle
    const timeout = setTimeout(() => { setLoading(false); clearInterval(t); }, 5000);
    return () => { clearInterval(t); clearTimeout(timeout); };
  }, [user]);

  // Nettoie l'URL (vire #access_token=… ou ?type=signup) une fois chargé
  React.useEffect(() => {
    try { window.history.replaceState({}, "", window.location.pathname); } catch {}
  }, []);

  return (
    <section style={{ padding: "80px 20px", minHeight: "60vh", display: "flex", alignItems: "center", justifyContent: "center" }}>
      <div className="container" style={{ maxWidth: 520 }}>
        <div style={{
          background: "var(--surface)", border: "1px solid var(--line)",
          borderRadius: 20, padding: "48px 32px", textAlign: "center",
          boxShadow: "var(--sh-2)",
        }}>
          {loading ? (
            <>
              <div style={{
                width: 64, height: 64, borderRadius: 50, margin: "0 auto 18px",
                background: "var(--accent-soft)", color: "var(--accent-ink)",
                display: "flex", alignItems: "center", justifyContent: "center",
                fontSize: 32,
              }}>⏳</div>
              <h1 style={{ fontSize: "clamp(24px, 3vw, 32px)", letterSpacing: "-0.025em", marginBottom: 10 }}>
                Vérification en cours…
              </h1>
              <p style={{ fontSize: 14.5, color: "var(--ink-3)", lineHeight: 1.55 }}>
                On termine de confirmer votre adresse, ce ne sera qu'une seconde.
              </p>
            </>
          ) : (
            <>
              <div style={{
                width: 72, height: 72, borderRadius: 50, margin: "0 auto 20px",
                background: "var(--sage-soft)", color: "var(--sage)",
                display: "flex", alignItems: "center", justifyContent: "center",
                fontSize: 38, fontWeight: 700,
                boxShadow: "0 0 0 8px color-mix(in oklab, var(--sage-soft) 60%, transparent)",
              }}>✓</div>
              <h1 style={{ fontSize: "clamp(26px, 3.4vw, 36px)", letterSpacing: "-0.025em", marginBottom: 12 }}>
                Compte confirmé !
              </h1>
              <p style={{ fontSize: 15, color: "var(--ink-2)", lineHeight: 1.55, marginBottom: 8 }}>
                {user
                  ? <>Bienvenue <strong>{user.ownerName || user.email}</strong>. Votre adresse <strong>{user.email}</strong> est désormais vérifiée.</>
                  : <>Votre adresse email a été confirmée. Vous pouvez maintenant vous connecter.</>
                }
              </p>
              <p style={{ fontSize: 13, color: "var(--ink-4)", lineHeight: 1.5, marginBottom: 28 }}>
                Le badge <strong style={{ color: "var(--accent-ink)" }}>✓ Vérifié</strong> apparaît maintenant
                sur votre page de réservation publique — un signal de confiance pour vos clients.
              </p>
              <button onClick={() => go(user ? "app" : "login")} className="btn btn-accent btn-lg">
                {user ? "Aller à mon espace pro" : "Me connecter"} →
              </button>
            </>
          )}
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { AboutPage, ContactPage, LoginPage, EmailConfirmedPage, CB_CONTACT_EMAIL, sendContactMail });
