/* Page — Devenir client (gestion de portefeuille) : inscription réelle.
   Enregistre le client dans naboo:gestion-clients (visible dans l'app pro,
   onglet Gestion) + carte bancaire pour le débit de fin d'année si
   l'objectif est atteint (0 € débité aujourd'hui). */
const { Button, Card, Badge, Icon } = window.NabooDesignSystem_955dca;
const S = window.NabooSite;
const B = window.NabooBilling;
const { useState } = React;
const HOME = "Accueil.html";

const dcInp = { height: 48, padding: "0 14px", background: "#fff", border: "1.5px solid var(--border-default)", borderRadius: "var(--radius-md)", fontFamily: "var(--font-body)", fontSize: 15, fontWeight: 600, color: "var(--text-strong)", outline: "none", width: "100%", boxSizing: "border-box" };
const dcSel = { ...dcInp, appearance: "auto" };

function DcFld({ label, children, flex }) {
  return (
    <label style={{ display: "block", marginBottom: 15, flex }}>
      <span style={{ display: "block", fontSize: 12.5, fontWeight: 700, color: "var(--text-body)", marginBottom: 7 }}>{label}</span>
      {children}
    </label>
  );
}

const fmtNum = (v) => v.replace(/\D/g, "").slice(0, 16).replace(/(\d{4})(?=\d)/g, "$1 ");
const fmtExp = (v) => { const d = v.replace(/\D/g, "").slice(0, 4); return d.length > 2 ? d.slice(0, 2) + "/" + d.slice(2) : d; };

function PageDevenirClient() {
  const [step, setStep] = useState(1); // 1 identité · 2 projet · 3 carte · 4 confirmation
  const [err, setErr] = useState("");
  const [f, setF] = useState({
    nom: "", email: "", tel: "",
    capital: "", objectif: "8", commission: "10", horizon: "3 à 5 ans", profil: "Équilibré", compte: "À ouvrir (accompagné)", notes: "",
    cardNum: "", cardExp: "", cardCvc: "", cardName: "",
  });
  const [receipt, setReceipt] = useState(null);
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));

  const submit1 = () => {
    if (f.nom.trim().length < 2) return setErr("Indiquez votre prénom et votre nom.");
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f.email.trim())) return setErr("Cette adresse e-mail ne semble pas valide.");
    setErr(""); setStep(2);
  };
  const submit2 = () => {
    const cap = parseFloat(String(f.capital).replace(/[^\d.,]/g, "").replace(",", "."));
    if (!cap || cap < 500) return setErr("Indiquez le capital confié (minimum 500 €).");
    setErr(""); setStep(3);
  };
  const submit3 = () => {
    const v = B.validateCard({ num: f.cardNum, exp: f.cardExp, cvc: f.cardCvc, name: f.cardName });
    if (!v.ok) return setErr(v.err);
    const cap = parseFloat(String(f.capital).replace(/[^\d.,]/g, "").replace(",", "."));
    const client = B.registerGestionClient({
      nom: f.nom.trim(), email: f.email.trim().toLowerCase(), tel: f.tel.trim(),
      capital: cap, objectif: f.objectif, commission: f.commission,
      profil: f.profil, horizon: f.horizon, compte: f.compte, notes: f.notes.trim(), carte: v.card,
    });
    const pay = B.recordPayment({
      type: "gestion-mandat",
      label: "Gestion de portefeuille · enregistrement du mandat et de la carte (débit en fin d'année uniquement sur les gains nets, au-dessus du plus-haut historique, si l'objectif est atteint)",
      montant: 0, carte: v.card,
      client: { nom: f.nom.trim(), email: f.email.trim().toLowerCase() },
      meta: { gestionClientId: client && client.id, capital: cap, objectif: f.objectif + " %", commission: f.commission + " %" },
    });
    setReceipt(pay); setErr(""); setStep(4);
  };
  const submit = step === 1 ? submit1 : step === 2 ? submit2 : submit3;
  const onKey = (e) => { if (e.key === "Enter" && step < 4) submit(); };

  const STEPS = [["1", "Vous"], ["2", "Votre projet"], ["3", "Carte"], ["4", "Confirmation"]];

  return (
    <div id="top" data-screen-label="Devenir client">
      <S.SiteNav dark active="gestion" home={HOME} />

      <header className="mk-dark" style={{ position: "relative", overflow: "hidden", padding: "72px 0 56px" }}>
        <div className="mk-glow"></div>
        <S.Cosmos />
        <div className="mk-container" style={{ position: "relative" }}>
          <p className="mk-overline">Gestion de portefeuille</p>
          <h1 className="mk-h1" style={{ maxWidth: 720 }}>Devenir client, en 3 minutes.</h1>
          <p className="mk-lead">
            Aucun frais aujourd'hui : votre carte est simplement enregistrée. Elle ne sera débitée
            qu'en fin d'année, uniquement si l'objectif fixé dans votre mandat est atteint.
          </p>
        </div>
      </header>

      <section className="mk-section-tight">
        <div className="mk-container" style={{ maxWidth: 720 }}>
          <div style={{ marginBottom: 20 }}>
            <S.AdvisorMini note="C'est Sébastien qui gérera votre portefeuille. Une question avant de commencer ? Écrivez-lui." />
          </div>
          <Card className="mk-form-card" padding={30}>
            <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 24 }}>
              {STEPS.map((s, i) => (
                <React.Fragment key={s[0]}>
                  {i > 0 && <span style={{ flex: 1, height: 2, borderRadius: 2, background: step > i ? "var(--accent)" : "var(--border-default)" }}></span>}
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                    <span style={{ width: 24, height: 24, borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 800, background: step >= i + 1 ? "var(--brand-gradient)" : "var(--surface-sunken)", color: step >= i + 1 ? "#fff" : "var(--text-faint)" }}>{step > i + 1 ? "✓" : s[0]}</span>
                    <span className="mk-step-label" style={{ fontSize: 12, fontWeight: 700, color: step === i + 1 ? "var(--text-strong)" : "var(--text-faint)" }}>{s[1]}</span>
                  </span>
                </React.Fragment>
              ))}
            </div>

            {step === 1 && (
              <div>
                <DcFld label="Prénom Nom *"><input value={f.nom} onChange={set("nom")} onKeyDown={onKey} placeholder="Jean Dupont" autoComplete="name" style={dcInp} /></DcFld>
                <DcFld label="Adresse e-mail *"><input value={f.email} onChange={set("email")} onKeyDown={onKey} placeholder="vous@exemple.fr" type="email" autoComplete="email" style={dcInp} /></DcFld>
                <DcFld label="Téléphone (optionnel)"><input value={f.tel} onChange={set("tel")} onKeyDown={onKey} placeholder="06 12 34 56 78" type="tel" autoComplete="tel" style={dcInp} /></DcFld>
              </div>
            )}

            {step === 2 && (
              <div>
                <DcFld label="Capital confié en gestion (€) *"><input value={f.capital} onChange={set("capital")} onKeyDown={onKey} placeholder="10 000" inputMode="decimal" className="naboo-num" style={dcInp} /></DcFld>
                <div style={{ display: "flex", gap: 14, flexWrap: "wrap" }}>
                  <DcFld label="Objectif annuel" flex="1 1 150px">
                    <select value={f.objectif} onChange={set("objectif")} style={dcSel}><option value="6">+6 %</option><option value="8">+8 %</option><option value="10">+10 %</option></select>
                  </DcFld>
                  <DcFld label="Horizon" flex="1 1 150px">
                    <select value={f.horizon} onChange={set("horizon")} style={dcSel}><option>Moins de 3 ans</option><option>3 à 5 ans</option><option>Plus de 5 ans</option></select>
                  </DcFld>
                </div>
                <div style={{ display: "flex", gap: 14, flexWrap: "wrap" }}>
                  <DcFld label="Profil de risque" flex="1 1 150px">
                    <select value={f.profil} onChange={set("profil")} style={dcSel}><option>Prudent</option><option>Équilibré</option><option>Dynamique</option></select>
                  </DcFld>
                  <DcFld label="Compte à confier" flex="1 1 150px">
                    <select value={f.compte} onChange={set("compte")} style={dcSel}><option>PEA existant</option><option>CTO existant</option><option>À ouvrir (accompagné)</option></select>
                  </DcFld>
                </div>
                <DcFld label="Un mot sur votre situation (optionnel)"><textarea value={f.notes} onChange={set("notes")} rows={3} placeholder="Vos objectifs, vos questions…" style={{ ...dcInp, height: "auto", padding: "12px 14px", resize: "none", lineHeight: 1.5 }} /></DcFld>
                <div style={{ display: "flex", gap: 10, alignItems: "flex-start", background: "var(--surface-sunken)", borderRadius: "var(--radius-md)", padding: "11px 13px", marginBottom: 4 }}>
                  <Icon name="info" size={16} color="var(--text-muted)" style={{ flex: "none", marginTop: 2 }} />
                  <span style={{ fontSize: 12.5, lineHeight: 1.55, color: "var(--text-body)" }}>La commission au résultat ({f.commission} % des plus-values nettes, calculées au-dessus de votre plus-haut historique) et l'objectif de déclenchement seront repris noir sur blanc dans votre lettre de mission, avant tout démarrage.</span>
                </div>
              </div>
            )}

            {step === 3 && (
              <div>
                <div style={{ display: "flex", gap: 10, alignItems: "flex-start", background: "var(--brand-violet-050)", border: "1px solid var(--brand-violet-100)", borderRadius: "var(--radius-md)", padding: "12px 14px", marginBottom: 18 }}>
                  <Icon name="shield-check" size={18} color="var(--accent)" style={{ flex: "none", marginTop: 1 }} />
                  <span style={{ fontSize: 13, lineHeight: 1.55, color: "var(--text-body)" }}><strong style={{ color: "var(--text-strong)" }}>0 € débité aujourd'hui.</strong> Votre carte est enregistrée pour la commission de fin d'année, prélevée <b>uniquement sur vos gains nets, au-dessus de votre plus-haut historique, et si l'objectif de +{f.objectif} % est atteint</b>. Pas de gain, pas de commission.</span>
                </div>
                <DcFld label="Numéro de carte"><S.AcceptedCards style={{ marginBottom: 8 }} /><input value={f.cardNum} onChange={(e) => setF((s) => ({ ...s, cardNum: fmtNum(e.target.value) }))} onKeyDown={onKey} placeholder="4242 4242 4242 4242" inputMode="numeric" autoComplete="cc-number" className="naboo-num" style={dcInp} /></DcFld>
                <div style={{ display: "flex", gap: 14 }}>
                  <DcFld label="Expiration" flex={1}><input value={f.cardExp} onChange={(e) => setF((s) => ({ ...s, cardExp: fmtExp(e.target.value) }))} onKeyDown={onKey} placeholder="MM/AA" inputMode="numeric" autoComplete="cc-exp" className="naboo-num" style={dcInp} /></DcFld>
                  <DcFld label="Cryptogramme" flex={1}><input value={f.cardCvc} onChange={(e) => setF((s) => ({ ...s, cardCvc: e.target.value.replace(/\D/g, "").slice(0, 4) }))} onKeyDown={onKey} placeholder="CVC" inputMode="numeric" autoComplete="cc-csc" type="password" className="naboo-num" style={dcInp} /></DcFld>
                </div>
                <DcFld label="Titulaire de la carte"><input value={f.cardName} onChange={set("cardName")} onKeyDown={onKey} placeholder="Jean Dupont" autoComplete="cc-name" style={dcInp} /></DcFld>
              </div>
            )}

            {step === 4 && receipt && (
              <div style={{ textAlign: "center", padding: "8px 0 4px" }}>
                <span style={{ width: 62, height: 62, borderRadius: "50%", background: "var(--positive-bg, #e4f6ee)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 16 }}><Icon name="check" size={30} color="var(--positive, #12A06A)" /></span>
                <h2 style={{ fontFamily: "var(--font-display)", fontSize: 24, fontWeight: 700, letterSpacing: "-0.02em", color: "var(--text-strong)", margin: "0 0 10px" }}>Bienvenue, {f.nom.trim().split(" ")[0]}.</h2>
                <p style={{ fontSize: 14.5, color: "var(--text-body)", lineHeight: 1.65, maxWidth: 480, margin: "0 auto 18px" }}>
                  Votre inscription est enregistrée ({receipt.no}). <b>Débit du jour : 0,00 €.</b> Votre carte •••• {receipt.carte.last4} sera
                  débitée en fin d'année uniquement sur vos gains nets, si l'objectif de +{f.objectif} % est atteint.
                  Votre conseiller vous contacte sous 48 h à <b>{f.email.trim()}</b> pour la lettre de mission.
                </p>
                <div style={{ display: "flex", gap: 10, justifyContent: "center", flexWrap: "wrap" }}>
                  <Button variant="ghost" onClick={() => B.openReceipt(receipt)} leadingIcon={<Icon name="file-text" size={16} color="var(--text-muted)" />}>Télécharger mon reçu (PDF)</Button>
                  <a href="espace-client/desktop-client.html"><Button trailingIcon={<Icon name="arrow-right" size={16} color="#fff" />}>Créer mon espace client</Button></a>
                </div>
              </div>
            )}

            {err && <div style={{ fontSize: 13, color: "var(--negative)", margin: "2px 0 14px", lineHeight: 1.45 }}>{err}</div>}

            {step < 4 && (
              <div style={{ display: "flex", gap: 10, marginTop: 8 }}>
                {step > 1 && <Button variant="ghost" onClick={() => { setStep(step - 1); setErr(""); }}>← Retour</Button>}
                <Button onClick={submit} style={{ flex: 1 }} trailingIcon={<Icon name={step === 3 ? "lock" : "arrow-right"} size={16} color="#fff" />}>
                  {step === 3 ? "Enregistrer ma carte · 0,00 € aujourd'hui" : "Continuer"}
                </Button>
              </div>
            )}
          </Card>

          <p style={{ fontSize: 12.5, color: "var(--text-muted)", textAlign: "center", marginTop: 18, lineHeight: 1.6 }}>
            <Icon name="lock" size={13} color="var(--text-faint)" style={{ verticalAlign: "-2px" }} /> Paiement simulé (maquette) : aucune vraie carte n'est débitée.
            Mandat résiliable à tout moment, sans préavis ni pénalité.
          </p>
        </div>
      </section>

      <S.SiteFooter />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("site-root")).render(<PageDevenirClient />);
