// ============================================================
// NOMERUS · AUTH SCREENS (login / signup / forgot)
// ============================================================

// Split-screen wrapper used by all auth views
const WAuthShell = ({ children, side }) => {
  const W = window.W;
  return (
    <div className="w-stack" style={{
      minHeight: "calc(100vh - 70px)",
      display: "grid", gridTemplateColumns: "1fr 1fr",
      background: W.bg, color: W.text, fontFamily: W.sans,
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", padding: "60px 28px" }}>
        <div style={{ width: "100%", maxWidth: 420 }}>{children}</div>
      </div>

      {/* Right column — terminal flavor */}
      <div style={{
        position: "relative", overflow: "hidden",
        borderLeft: `1px solid ${W.border}`, background: W.bgAlt,
        padding: "60px 48px", display: "flex", flexDirection: "column",
      }}>
        <svg style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0.55, pointerEvents: "none" }} preserveAspectRatio="none">
          <pattern id="auth-grid" width="48" height="48" patternUnits="userSpaceOnUse">
            <path d="M 48 0 L 0 0 0 48" fill="none" stroke={W.border} strokeWidth="0.4"/>
          </pattern>
          <rect width="100%" height="100%" fill="url(#auth-grid)"/>
        </svg>
        <div style={{ position: "relative" }}>{side}</div>
      </div>
    </div>
  );
};

// ──────────────────────────────────────────────────────────────
// LOGIN
// ──────────────────────────────────────────────────────────────
const WLogin = ({ go, onLogin }) => {
  const W = window.W;
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");

  const side = <WAuthSide title="Bon retour, opérateur." subtitle="Ton journal a continué d'écrire pendant que tu dormais." />;

  const submit = async (e) => {
    if (e && e.preventDefault) e.preventDefault();
    if (busy) return;
    setErr("");
    if (!email || !password) { setErr("Email et mot de passe requis."); return; }
    setBusy(true);
    try {
      await window.nomerusAuth.signInPassword(email, password);
      await onLogin();
    } catch (e) {
      setErr(window.nomerusAuth.errorToFr(e));
    } finally {
      setBusy(false);
    }
  };

  const google = async () => {
    if (busy) return;
    setErr("");
    setBusy(true);
    try {
      // Redirige vers Google ; après retour, onAuthStateChange dans index.html
      // pousse vers le dashboard.
      await window.nomerusAuth.signInGoogle();
    } catch (e) {
      setErr(window.nomerusAuth.errorToFr(e));
      setBusy(false);
    }
  };

  return (
    <WAuthShell side={side}>
      <div style={{ fontFamily: W.mono, fontSize: 10, color: W.indigo, letterSpacing: 2, marginBottom: 14 }}>// AUTH · 01 CONNEXION</div>
      <h1 style={{ fontFamily: W.sans, fontSize: 36, fontWeight: 700, letterSpacing: -1, margin: "0 0 12px", lineHeight: 1.1 }}>
        Connecte-toi à ton terminal.
      </h1>
      <p style={{ fontFamily: W.sans, fontSize: 14, color: W.textDim, margin: "0 0 28px", lineHeight: 1.55 }}>
        Pas encore de compte ?{" "}
        <button onClick={() => go("signup")} style={{ background: "none", border: "none", color: W.indigo, cursor: "pointer", padding: 0, fontFamily: "inherit", fontSize: "inherit" }}>
          Créer ton compte →
        </button>
      </p>

      {/* SSO row */}
      <div style={{ marginBottom: 22 }}>
        <button onClick={google} disabled={busy} className="w-sso" style={{ ...ssoBtn(W), width: "100%", opacity: busy ? 0.6 : 1, cursor: busy ? "wait" : "pointer" }}>
          <span style={{ fontFamily: W.mono, fontWeight: 700, fontSize: 14 }}>G</span> Continuer avec Google
        </button>
      </div>

      <div style={{
        display: "flex", alignItems: "center", gap: 12, margin: "6px 0 20px",
        fontFamily: W.mono, fontSize: 10, color: W.textMute, letterSpacing: 1.5,
      }}>
        <div style={{ flex: 1, height: 1, background: W.border }}/>
        OU
        <div style={{ flex: 1, height: 1, background: W.border }}/>
      </div>

      <form onSubmit={submit}>
        <Field W={W} label="EMAIL" value={email} onChange={setEmail} type="email" placeholder="toi@boite.com"/>
        <Field W={W} label="MOT DE PASSE" value={password} onChange={setPassword} type="password"
          placeholder="8 caractères minimum"
          right={<button type="button" onClick={() => go("forgot")} style={linkBtn(W)}>Oublié ?</button>}
        />

        {err && (
          <div style={{
            padding: "10px 12px", marginBottom: 14, borderRadius: 4,
            background: "rgba(255, 107, 122, 0.06)", border: `1px solid rgba(255, 107, 122, 0.3)`,
            color: W.red, fontFamily: W.mono, fontSize: 11,
          }}>⚠ {err}</div>
        )}

        <button type="submit" disabled={busy} className="w-cta" style={{ ...primaryBtn(W), opacity: busy ? 0.6 : 1, cursor: busy ? "wait" : "pointer" }}>
          {busy ? "CONNEXION…" : "ACCÉDER AU DASHBOARD →"}
        </button>
      </form>

      <div style={{
        marginTop: 22, padding: 14, borderRadius: 4,
        background: W.panel, border: `1px dashed ${W.border}`,
        display: "flex", alignItems: "flex-start", gap: 10,
      }}>
        <span style={{ color: W.indigo, marginTop: 1 }}><window.Icon name="shield" size={14}/></span>
        <div style={{ fontFamily: W.mono, fontSize: 10, color: W.textDim, lineHeight: 1.6, letterSpacing: 0.4 }}>
          Connexion sécurisée Supabase · refresh token chiffré côté client · TLS 1.3.
        </div>
      </div>
    </WAuthShell>
  );
};

// ──────────────────────────────────────────────────────────────
// SIGNUP
// ──────────────────────────────────────────────────────────────
const WSignup = ({ go, onLogin }) => {
  const W = window.W;
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [pwd, setPwd] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  const [info, setInfo] = React.useState("");

  // Password strength simple : longueur + classes de caractères
  const strength = (() => {
    let s = 0;
    if (pwd.length >= 8) s++;
    if (pwd.length >= 12) s++;
    if (/[A-Z]/.test(pwd) && /[a-z]/.test(pwd)) s++;
    if (/[0-9]/.test(pwd) && /[^A-Za-z0-9]/.test(pwd)) s++;
    return s; // 0..4
  })();
  const strengthLabel = ["", "FAIBLE", "PASSABLE", "BON", "FORT"][strength];
  const strengthColor = strength >= 3 ? W.green : strength >= 2 ? W.amber : W.red;

  const side = (
    <WAuthSide
      title="Tes vraies stats. Avant la fin de ton café."
      subtitle="Importe ton CSV ou saisis tes trades · analysés par le Coach IA."
      bullets={[
        ["01", "Crée ton compte · 30 sec"],
        ["02", "Importe un CSV ou saisis tes trades · 2 min"],
        ["03", "Tes stats + le Coach IA, direct"],
      ]}
    />
  );

  const submit = async (e) => {
    if (e && e.preventDefault) e.preventDefault();
    if (busy) return;
    setErr(""); setInfo("");
    if (!name.trim()) { setErr("Nom requis."); return; }
    if (!email || !email.includes("@")) { setErr("Email invalide."); return; }
    if (pwd.length < 8) { setErr("Mot de passe trop court (8 caractères minimum)."); return; }
    setBusy(true);
    try {
      const data = await window.nomerusAuth.signUpPassword(email, pwd, name.trim());
      if (window.NomerusAnalytics) window.NomerusAnalytics.track("signed_up", { method: "email" });
      // Si confirmation email activée, data.session est null et l'utilisateur
      // doit cliquer le lien dans son mail avant de pouvoir se connecter.
      if (data && data.session) {
        await onLogin();
      } else {
        setInfo("Compte créé. Vérifie ta boîte mail pour confirmer ton email, puis reviens te connecter.");
      }
    } catch (e) {
      setErr(window.nomerusAuth.errorToFr(e));
    } finally {
      setBusy(false);
    }
  };

  const google = async () => {
    if (busy) return;
    setErr(""); setInfo("");
    setBusy(true);
    try {
      await window.nomerusAuth.signInGoogle();
    } catch (e) {
      setErr(window.nomerusAuth.errorToFr(e));
      setBusy(false);
    }
  };

  return (
    <WAuthShell side={side}>
      <div style={{ fontFamily: W.mono, fontSize: 10, color: W.indigo, letterSpacing: 2, marginBottom: 14 }}>// AUTH · 02 INSCRIPTION</div>
      <h1 style={{ fontFamily: W.sans, fontSize: 36, fontWeight: 700, letterSpacing: -1, margin: "0 0 12px", lineHeight: 1.1 }}>
        Crée ton compte.
      </h1>
      <p style={{ fontFamily: W.sans, fontSize: 14, color: W.textDim, margin: "0 0 28px", lineHeight: 1.55 }}>
        Déjà un compte ?{" "}
        <button onClick={() => go("login")} style={{ background: "none", border: "none", color: W.indigo, cursor: "pointer", padding: 0, fontFamily: "inherit", fontSize: "inherit" }}>
          Se connecter →
        </button>
      </p>

      <div style={{ marginBottom: 22 }}>
        <button onClick={google} disabled={busy} className="w-sso" style={{ ...ssoBtn(W), width: "100%", opacity: busy ? 0.6 : 1, cursor: busy ? "wait" : "pointer" }}>
          <span style={{ fontFamily: W.mono, fontWeight: 700, fontSize: 14 }}>G</span> S'inscrire avec Google
        </button>
      </div>

      <div style={{
        display: "flex", alignItems: "center", gap: 12, margin: "6px 0 20px",
        fontFamily: W.mono, fontSize: 10, color: W.textMute, letterSpacing: 1.5,
      }}>
        <div style={{ flex: 1, height: 1, background: W.border }}/>
        OU PAR EMAIL
        <div style={{ flex: 1, height: 1, background: W.border }}/>
      </div>

      <form onSubmit={submit}>
        <Field W={W} label="NOM AFFICHÉ" value={name} onChange={setName} placeholder="Ton prénom ou pseudo"/>
        <Field W={W} label="EMAIL" value={email} onChange={setEmail} type="email" placeholder="toi@boite.com"/>
        <Field W={W} label="MOT DE PASSE" value={pwd} onChange={setPwd} type="password" placeholder="8 caractères minimum"/>

        {/* Password strength */}
        <div style={{ display: "flex", gap: 4, margin: "0 0 18px", alignItems: "center" }}>
          {[0, 1, 2, 3].map(i => (
            <div key={i} style={{
              flex: 1, height: 3, borderRadius: 2,
              background: i < strength ? strengthColor : W.border,
            }}/>
          ))}
          <span style={{ fontFamily: W.mono, fontSize: 10, color: strengthColor, letterSpacing: 1.2, marginLeft: 6, minWidth: 60 }}>{strengthLabel}</span>
        </div>

        {err && (
          <div style={{
            padding: "10px 12px", marginBottom: 14, borderRadius: 4,
            background: "rgba(255, 107, 122, 0.06)", border: `1px solid rgba(255, 107, 122, 0.3)`,
            color: W.red, fontFamily: W.mono, fontSize: 11,
          }}>⚠ {err}</div>
        )}
        {info && (
          <div style={{
            padding: "10px 12px", marginBottom: 14, borderRadius: 4,
            background: "rgba(91, 217, 154, 0.06)", border: `1px solid rgba(91, 217, 154, 0.3)`,
            color: W.green, fontFamily: W.mono, fontSize: 11,
          }}>✓ {info}</div>
        )}

        <button type="submit" disabled={busy} className="w-cta" style={{ ...primaryBtn(W), opacity: busy ? 0.6 : 1, cursor: busy ? "wait" : "pointer" }}>
          {busy ? "CRÉATION…" : "CRÉER MON COMPTE →"}
        </button>
      </form>

      <div style={{ marginTop: 18, fontFamily: W.mono, fontSize: 10, color: W.textMute, letterSpacing: 1.2, textAlign: "center" }}>
        EN T'INSCRIVANT, TU ACCEPTES LES CGU · AUCUNE CB REQUISE
      </div>
    </WAuthShell>
  );
};

// ──────────────────────────────────────────────────────────────
// FORGOT
// ──────────────────────────────────────────────────────────────
const WForgot = ({ go }) => {
  const W = window.W;
  const [email, setEmail] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  const [info, setInfo] = React.useState("");

  const side = <WAuthSide title="Réinitialise. Redéploie. Reconcentre-toi." subtitle="Le lien arrive dans ta boîte mail en moins de 30 secondes." />;

  const submit = async (e) => {
    if (e && e.preventDefault) e.preventDefault();
    if (busy) return;
    setErr(""); setInfo("");
    if (!email || !email.includes("@")) { setErr("Email invalide."); return; }
    setBusy(true);
    try {
      await window.nomerusAuth.resetPassword(email);
      setInfo("Lien envoyé. Vérifie ta boîte mail.");
    } catch (e) {
      setErr(window.nomerusAuth.errorToFr(e));
    } finally {
      setBusy(false);
    }
  };

  return (
    <WAuthShell side={side}>
      <div style={{ fontFamily: W.mono, fontSize: 10, color: W.indigo, letterSpacing: 2, marginBottom: 14 }}>// AUTH · 03 RÉCUPÉRATION</div>
      <h1 style={{ fontFamily: W.sans, fontSize: 36, fontWeight: 700, letterSpacing: -1, margin: "0 0 12px", lineHeight: 1.1 }}>
        Réinitialiser le mot de passe.
      </h1>
      <p style={{ fontFamily: W.sans, fontSize: 14, color: W.textDim, margin: "0 0 28px", lineHeight: 1.55 }}>
        Entre l'email de ton compte. On t'envoie un lien de réinitialisation.
      </p>

      <form onSubmit={submit}>
        <Field W={W} label="EMAIL" value={email} onChange={setEmail} type="email" placeholder="toi@boite.com"/>

        {err && (
          <div style={{ padding: "10px 12px", marginBottom: 14, borderRadius: 4,
            background: "rgba(255, 107, 122, 0.06)", border: `1px solid rgba(255, 107, 122, 0.3)`,
            color: W.red, fontFamily: W.mono, fontSize: 11 }}>⚠ {err}</div>
        )}
        {info && (
          <div style={{ padding: "10px 12px", marginBottom: 14, borderRadius: 4,
            background: "rgba(91, 217, 154, 0.06)", border: `1px solid rgba(91, 217, 154, 0.3)`,
            color: W.green, fontFamily: W.mono, fontSize: 11 }}>✓ {info}</div>
        )}

        <button type="submit" disabled={busy} className="w-cta" style={{ ...primaryBtn(W), opacity: busy ? 0.6 : 1, cursor: busy ? "wait" : "pointer" }}>
          {busy ? "ENVOI…" : "ENVOYER LE LIEN →"}
        </button>
      </form>

      <button onClick={() => go("login")} style={{
        ...linkBtn(W), marginTop: 18, fontFamily: W.mono, fontSize: 11, letterSpacing: 1.5,
      }}>
        ← RETOUR À LA CONNEXION
      </button>
    </WAuthShell>
  );
};

// ──────────────────────────────────────────────────────────────
// RESET PASSWORD — atterrissage du lien email "mot de passe oublié".
// detectSessionInUrl consomme le code du lien et établit une session ;
// on attend qu'elle soit là, puis on laisse saisir le nouveau mot de passe.
// ──────────────────────────────────────────────────────────────
const WResetPassword = ({ go, loggedIn, onDone }) => {
  const W = window.W;
  const [pwd, setPwd] = React.useState("");
  const [pwd2, setPwd2] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  const [ready, setReady] = React.useState(!!loggedIn);
  const [expired, setExpired] = React.useState(false);
  // 2FA : si le compte a un facteur TOTP vérifié, la session issue du lien
  // email n'est qu'AAL1 — Supabase refuse updateUser tant qu'un code MFA n'a
  // pas été validé (erreur "AAL2 session is required…"). On détecte le cas et
  // on demande le code à 6 chiffres avant de changer le mot de passe.
  const [mfaFactorId, setMfaFactorId] = React.useState(null);
  const [mfaCode, setMfaCode] = React.useState("");

  const detectMfa = async () => {
    try {
      const sb = window.nomerusSb();
      if (!sb) return;
      const { data: aal } = await sb.auth.mfa.getAuthenticatorAssuranceLevel();
      if (!aal || aal.currentLevel === "aal2" || aal.nextLevel !== "aal2") return;
      const { data: f } = await sb.auth.mfa.listFactors();
      const verified =
        (f && f.totp && f.totp.find(x => x.status === "verified")) ||
        (f && f.all && f.all.find(x => x.status === "verified"));
      if (verified) setMfaFactorId(verified.id);
    } catch (e) { /* pas bloquant — le repli sur l'erreur AAL2 prendra le relais */ }
  };

  // Attend que le lien de récupération soit consommé (session établie).
  // Au-delà de 8 s sans session, on considère le lien invalide/expiré.
  React.useEffect(() => {
    if (loggedIn) { setReady(true); detectMfa(); return; }
    let cancelled = false;
    let tries = 0;
    const poll = async () => {
      if (cancelled) return;
      try {
        const session = await window.nomerusAuth.getSession();
        if (cancelled) return;
        if (session) { setReady(true); detectMfa(); return; }
      } catch (e) {}
      if (++tries < 16) setTimeout(poll, 500);
      else if (!cancelled) setExpired(true);
    };
    poll();
    return () => { cancelled = true; };
  }, [loggedIn]);

  const submit = async (e) => {
    if (e && e.preventDefault) e.preventDefault();
    if (busy) return;
    setErr("");
    if (pwd.length < 8) { setErr("Mot de passe trop court (8 caractères minimum)."); return; }
    if (pwd !== pwd2) { setErr("Les deux mots de passe ne correspondent pas."); return; }
    if (mfaFactorId && !/^\d{6}$/.test(mfaCode.trim())) {
      setErr("Entre le code à 6 chiffres de ton application d'authentification.");
      return;
    }
    setBusy(true);
    try {
      // Étape 2FA d'abord : élève la session en AAL2, condition de updateUser.
      if (mfaFactorId) {
        const sb = window.nomerusSb();
        const { error: mfaErr } = await sb.auth.mfa.challengeAndVerify({
          factorId: mfaFactorId,
          code: mfaCode.trim(),
        });
        if (mfaErr) throw mfaErr;
      }
      await window.nomerusAuth.updatePassword(pwd);
      if (window.NomerusAnalytics) window.NomerusAnalytics.track("password_reset_completed");
      onDone();
    } catch (e2) {
      const raw = ((e2 && e2.message) || "").toLowerCase();
      if (raw.includes("aal2")) {
        // Compte protégé par 2FA mais détection proactive passée à côté :
        // on affiche le champ code et on laisse l'utilisateur réessayer.
        await detectMfa();
        setErr("Ton compte est protégé par le 2FA. Entre le code à 6 chiffres de ton application d'authentification.");
      } else {
        setErr(window.nomerusAuth.errorToFr(e2));
      }
      setBusy(false);
    }
  };

  const side = <WAuthSide title="Nouveau mot de passe, nouveau départ." subtitle="Choisis un mot de passe solide — 8 caractères minimum, unique à Nomerus." />;

  return (
    <WAuthShell side={side}>
      <div style={{ fontFamily: W.mono, fontSize: 10, color: W.indigo, letterSpacing: 2, marginBottom: 14 }}>// AUTH · 04 NOUVEAU MOT DE PASSE</div>
      <h1 style={{ fontFamily: W.sans, fontSize: 36, fontWeight: 700, letterSpacing: -1, margin: "0 0 12px", lineHeight: 1.1 }}>
        Choisis ton nouveau mot de passe.
      </h1>

      {expired && !ready ? (
        <div>
          <div style={{ padding: "12px 14px", marginBottom: 18, borderRadius: 4,
            background: "rgba(255, 107, 122, 0.06)", border: `1px solid rgba(255, 107, 122, 0.3)`,
            color: W.red, fontFamily: W.mono, fontSize: 11, lineHeight: 1.6 }}>
            ⚠ Ce lien de réinitialisation est invalide ou a expiré. Demande un nouveau lien.
          </div>
          <button onClick={() => go("forgot")} className="w-cta" style={primaryBtn(W)}>
            DEMANDER UN NOUVEAU LIEN →
          </button>
        </div>
      ) : !ready ? (
        <div style={{ fontFamily: W.mono, fontSize: 11, color: W.textDim, letterSpacing: 1, padding: "18px 0" }}>
          Vérification du lien en cours…
        </div>
      ) : (
        <form onSubmit={submit}>
          <Field W={W} label="NOUVEAU MOT DE PASSE" value={pwd} onChange={setPwd} type="password" placeholder="8 caractères minimum"/>
          <Field W={W} label="CONFIRME LE MOT DE PASSE" value={pwd2} onChange={setPwd2} type="password" placeholder="Retape le même mot de passe"/>

          {mfaFactorId && (
            <>
              <div style={{
                padding: "10px 12px", marginBottom: 14, borderRadius: 4,
                background: W.indigoSoft, border: `1px solid ${W.borderStrong}`,
                color: W.textDim, fontFamily: W.sans, fontSize: 12, lineHeight: 1.55,
              }}>
                <span style={{ color: W.indigo, fontFamily: W.mono, fontSize: 10, letterSpacing: 1.5 }}>2FA ACTIVÉ · </span>
                Ton compte est protégé par la double authentification. Entre le code de ton application (Google Authenticator, Authy…).
              </div>
              <Field W={W} label="CODE 2FA (6 CHIFFRES)" value={mfaCode} onChange={setMfaCode} placeholder="123456"/>
            </>
          )}

          {err && (
            <div style={{ padding: "10px 12px", marginBottom: 14, borderRadius: 4,
              background: "rgba(255, 107, 122, 0.06)", border: `1px solid rgba(255, 107, 122, 0.3)`,
              color: W.red, fontFamily: W.mono, fontSize: 11 }}>⚠ {err}</div>
          )}

          <button type="submit" disabled={busy} className="w-cta" style={{ ...primaryBtn(W), opacity: busy ? 0.6 : 1, cursor: busy ? "wait" : "pointer" }}>
            {busy ? "ENREGISTREMENT…" : "ENREGISTRER ET ACCÉDER AU DASHBOARD →"}
          </button>
        </form>
      )}
    </WAuthShell>
  );
};

// ──────────────────────────────────────────────────────────────
// Side-panel content & small primitives
// ──────────────────────────────────────────────────────────────
const WAuthSide = ({ title, subtitle, bullets }) => {
  const W = window.W;
  return (
    <div>
      <div style={{ fontFamily: W.mono, fontSize: 10, color: W.textMute, letterSpacing: 1.8, marginBottom: 22 }}>
        <span style={{ color: W.green }}>●</span> SESSION SÉCURISÉE · TLS 1.3 · CLÉS CHIFFRÉES AU REPOS
      </div>
      <h2 style={{ fontFamily: W.sans, fontSize: 32, fontWeight: 700, letterSpacing: -0.8, color: W.text, margin: "0 0 14px", lineHeight: 1.15, maxWidth: 380 }}>
        {title}
      </h2>
      <p style={{ fontFamily: W.sans, fontSize: 15, color: W.textDim, lineHeight: 1.6, margin: "0 0 36px", maxWidth: 400 }}>
        {subtitle}
      </p>

      {bullets && (
        <div style={{ display: "flex", flexDirection: "column", gap: 14, marginBottom: 36, maxWidth: 380 }}>
          {bullets.map(([n, t]) => (
            <div key={n} style={{ display: "flex", gap: 14, alignItems: "center" }}>
              <span style={{
                width: 28, height: 28, borderRadius: 4,
                background: W.indigoSoft, color: W.indigo,
                display: "inline-flex", alignItems: "center", justifyContent: "center",
                fontFamily: W.mono, fontSize: 11, fontWeight: 700,
                border: `1px solid ${W.borderStrong}`, flexShrink: 0,
              }}>{n}</span>
              <span style={{ fontFamily: W.sans, fontSize: 14, color: W.text }}>{t}</span>
            </div>
          ))}
        </div>
      )}

      {/* Honest status strip — no fabricated uptime / trade counts. */}
      <div style={{
        background: W.panel, border: `1px solid ${W.border}`, borderRadius: 4,
        padding: "16px 18px", maxWidth: 420,
      }}>
        <div style={{ fontFamily: W.mono, fontSize: 10, color: W.textMute, letterSpacing: 1.6, marginBottom: 14 }}>
          // NOMERUS · STATUS
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, fontFamily: W.mono, fontSize: 11 }}>
          {[
            ["VERSION",      "v1.0.0",          W.indigo],
            ["PLANS",        "GRATUIT · PRO",   W.green],
            ["IMPORT",       "CSV + MANUEL",    W.text],
            ["COACH IA",     "INCLUS",          W.indigo],
          ].map(([k, v, c]) => (
            <div key={k}>
              <div style={{ color: W.textMute, letterSpacing: 1.2, marginBottom: 4 }}>{k}</div>
              <div style={{ color: c, fontSize: 16, fontWeight: 600 }}>{v}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const Field = ({ W, label, value, onChange, type = "text", placeholder, right }) => (
  <label style={{ display: "block", marginBottom: 16 }}>
    <div style={{
      display: "flex", alignItems: "center", justifyContent: "space-between",
      marginBottom: 6,
    }}>
      <span style={{ fontFamily: W.mono, fontSize: 10, color: W.textMute, letterSpacing: 1.6 }}>{label}</span>
      {right}
    </div>
    <input
      type={type}
      value={value}
      placeholder={placeholder}
      onChange={e => onChange(e.target.value)}
      style={{
        width: "100%", boxSizing: "border-box",
        background: W.panel, border: `1px solid ${W.border}`, borderRadius: 4,
        color: W.text, fontFamily: W.sans, fontSize: 14,
        padding: "11px 14px", outline: "none",
      }}
      onFocus={e => e.target.style.borderColor = W.indigo}
      onBlur={e => e.target.style.borderColor = W.border}
    />
  </label>
);

const ssoBtn = (W) => ({
  display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
  background: W.panel, color: W.text, border: `1px solid ${W.border}`,
  padding: "11px 12px", borderRadius: 4, cursor: "pointer",
  fontFamily: W.sans, fontSize: 13, fontWeight: 500,
});

const primaryBtn = (W) => ({
  width: "100%", background: W.indigo, color: W.bg, border: "none", cursor: "pointer",
  padding: "14px 18px", borderRadius: 5,
  fontFamily: W.mono, fontSize: 12, fontWeight: 700, letterSpacing: 2,
});

const linkBtn = (W) => ({
  background: "none", border: "none", padding: 0, cursor: "pointer",
  color: W.indigo, fontFamily: W.sans, fontSize: 12,
});

window.WLogin = WLogin;
window.WSignup = WSignup;
window.WForgot = WForgot;
window.WResetPassword = WResetPassword;
