/* 2FA Login flow + Settings/Security page */

const TwoFactorModal = ({ open, onClose }) => {
  const [me, setMe] = useCurrentUser();
  const toast = useToast();
  const [step, setStep] = useState("email"); // email | code | success
  const [email, setEmail] = useState(() => localStorage.getItem("kcc_last_email") || "benoitclarens123@gmail.com");
  const [pwd, setPwd] = useState("");
  const [code, setCode] = useState(["", "", "", "", "", ""]);
  const [attempts, setAttempts] = useState(0);
  const [ttl, setTtl] = useState(600);
  const [token, setToken] = useState(null);
  const [loading, setLoading] = useState(false);
  const [emailsDisabled, setEmailsDisabled] = useState(false);
  const inputsRef = useRef([]);

  useEffect(() => {
    if (step === "code" && ttl > 0) {
      const t = setTimeout(() => setTtl((s) => s - 1), 1000);
      return () => clearTimeout(t);
    }
  }, [step, ttl]);

  useEffect(() => {
    if (!open) {
      setStep("email"); setCode(["","","","","",""]); setAttempts(0);
      setTtl(600); setPwd(""); setToken(null); setLoading(false); setEmailsDisabled(false);
    }
  }, [open]);

  // Map email → user (used on success to switch the active cofounder)
  const matchUserFromEmail = (em) => {
    const e = (em || "").toLowerCase().trim();
    const local = e.split("@")[0];
    return USERS.find(u =>
      (u.email && u.email.toLowerCase() === e) ||
      u.id === local ||
      u.name.toLowerCase() === local
    ) || null;
  };

  const goCode = async (e) => {
    if (e && e.preventDefault) e.preventDefault();
    if (!pwd) { toast({ message: "Mot de passe requis", tone: "red" }); return; }
    localStorage.setItem("kcc_last_email", email);
    setLoading(true);

    // SHA-256 of password — never sent in clear
    let pwd_hash = "";
    try {
      const buf = new TextEncoder().encode(pwd);
      const hashBuf = await crypto.subtle.digest("SHA-256", buf);
      pwd_hash = Array.from(new Uint8Array(hashBuf))
        .map(b => b.toString(16).padStart(2, "0")).join("");
    } catch (_) { /* fallback below */ }

    try {
      const res = await fetch("/api/auth/code", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, pwd_hash }),
      });

      if (res.status === 503) {
        // Kill-switch ON → bypass 2FA gracefully, log user in directly
        const match = matchUserFromEmail(email);
        if (match) setMe(match.id);
        setEmailsDisabled(true);
        setStep("success");
        toast({ message: "Emails désactivés · session ouverte (mode dev)", tone: "blue" });
        setTimeout(onClose, 1400);
        return;
      }

      const data = await res.json().catch(() => ({}));
      if (res.ok && data.ok && data.token) {
        setToken(data.token);
        if (typeof data.expires_in === "number") setTtl(data.expires_in);
        setStep("code");
        toast({ message: `Code envoyé à ${data.sent_to || email}`, tone: "blue" });
        setTimeout(() => inputsRef.current[0]?.focus(), 60);
      } else {
        toast({ message: data.error || "Échec de l'envoi du code", tone: "red" });
      }
    } catch (err) {
      // Network failure → fallback to demo mode so dev work isn't blocked
      toast({ message: "Mode démo (backend indisponible)", tone: "blue" });
      setStep("code");
      setTimeout(() => inputsRef.current[0]?.focus(), 60);
    } finally {
      setLoading(false);
    }
  };

  const verifyCode = async (fullCode) => {
    // Demo fallback when there's no token (offline / backend down)
    if (!token) {
      if (fullCode === "428931") {
        const match = matchUserFromEmail(email);
        if (match) setMe(match.id);
        setStep("success");
        toast({ message: "Session ouverte · 2FA validé (démo)", tone: "green" });
        setTimeout(onClose, 1400);
      } else {
        setAttempts((a) => a + 1);
        toast({ message: `Code invalide · essai ${attempts+1}/5`, tone: "red" });
        setCode(["","","","","",""]);
        inputsRef.current[0]?.focus();
      }
      return;
    }

    try {
      const res = await fetch("/api/auth/code", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "verify", token, code: fullCode }),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.ok) {
        const match = matchUserFromEmail(email);
        if (match) setMe(match.id);
        setStep("success");
        toast({ message: "Session ouverte · 2FA validé", tone: "green" });
        setTimeout(onClose, 1400);
      } else {
        const a = typeof data.attempts === "number" ? data.attempts : attempts + 1;
        setAttempts(a);
        toast({ message: `Code invalide · essai ${a}/5`, tone: "red" });
        setCode(["","","","","",""]);
        inputsRef.current[0]?.focus();
      }
    } catch (_) {
      toast({ message: "Vérification impossible · réseau", tone: "red" });
    }
  };

  const updateCode = (i, v) => {
    const c = [...code]; c[i] = v.replace(/\D/g, "").slice(-1); setCode(c);
    if (v && i < 5) inputsRef.current[i + 1]?.focus();
    if (c.every((d) => d) && c.join("").length === 6) {
      setTimeout(() => verifyCode(c.join("")), 200);
    }
  };

  const resendCode = async () => {
    if (loading) return;
    setLoading(true);
    try {
      const res = await fetch("/api/auth/code", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, resend: true }),
      });
      if (res.status === 503) {
        toast({ message: "Emails désactivés · code démo: 428931", tone: "blue" });
      } else {
        const data = await res.json().catch(() => ({}));
        if (res.ok && data.ok && data.token) {
          setToken(data.token);
          setTtl(data.expires_in || 600);
          toast({ message: "Nouveau code envoyé", tone: "blue" });
        }
      }
    } catch (_) {
      toast({ message: "Renvoi impossible", tone: "red" });
    } finally {
      setLoading(false);
    }
  };

  const fmtTtl = `${Math.floor(ttl/60)}:${(ttl%60).toString().padStart(2,"0")}`;

  return (
    <Modal open={open} onClose={onClose} width={420}>
      <div style={{ padding: 26, position: "relative" }}>
        <button className="icon-btn" onClick={onClose} style={{ position: "absolute", top: 14, right: 14 }}>
          <Icon name="x" />
        </button>

        {/* Header */}
        <div className="row" style={{ gap: 10, marginBottom: 6 }}>
          <div className="logo" style={{ width: 36, height: 36, fontSize: 14 }}>KC</div>
          <div>
            <div style={{ fontSize: 14, fontWeight: 600 }}>KCC Holdings</div>
            <div className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)" }}>kcc-admin.pages.dev</div>
          </div>
        </div>

        {step === "email" && (
          <form
            method="post"
            action="/api/auth/login"
            onSubmit={goCode}
            autoComplete="on"
          >
            <div style={{ fontSize: 20, fontWeight: 600, marginTop: 18, letterSpacing: "-0.02em" }}>Connexion sécurisée</div>
            <div className="muted" style={{ fontSize: 12.5, marginTop: 4 }}>Étape 1 / 2 · Vérification du mot de passe</div>

            <div className="stack" style={{ gap: 10, marginTop: 18 }}>
              <label htmlFor="kcc-email" style={{ fontSize: 11.5, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Adresse email</label>
              <div className="input"><Icon name="mail" size={13} style={{ marginRight: 6, color: "var(--text-dim)" }}/>
                <input
                  id="kcc-email"
                  name="email"
                  type="email"
                  autoComplete="username email"
                  inputMode="email"
                  autoCapitalize="none"
                  autoCorrect="off"
                  spellCheck={false}
                  required
                  value={email}
                  onChange={(e)=>setEmail(e.target.value)}
                  style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)" }}
                />
              </div>
              <label htmlFor="kcc-password" style={{ fontSize: 11.5, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: "0.06em", marginTop: 4 }}>Mot de passe</label>
              <div className="input"><Icon name="lock" size={13} style={{ marginRight: 6, color: "var(--text-dim)" }}/>
                <input
                  id="kcc-password"
                  name="password"
                  type="password"
                  autoComplete="current-password"
                  required
                  minLength={8}
                  value={pwd}
                  onChange={(e)=>setPwd(e.target.value)}
                  placeholder="••••••••••••"
                  style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)" }}
                />
              </div>
              <div className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)", marginTop: 4 }}>
                Hash SHA-256 calculé côté client · jamais transmis en clair
              </div>
            </div>

            <button type="submit" className="btn" data-variant="primary" disabled={loading} style={{ width: "100%", marginTop: 18, height: 36, justifyContent: "center" }}>
              {loading ? "Envoi du code…" : "Continuer →"}
            </button>

            <div style={{ marginTop: 12, fontSize: 11, color: "var(--text-faint)", textAlign: "center" }}>
              <Icon name="shield" size={11} style={{ verticalAlign: "-1px", marginRight: 4 }}/>
              Compatible iCloud Keychain · Google Password Manager · 1Password · Bitwarden
            </div>
          </form>
        )}

        {step === "code" && (
          <>
            <div style={{ fontSize: 20, fontWeight: 600, marginTop: 18, letterSpacing: "-0.02em" }}>Code de vérification</div>
            <div className="muted" style={{ fontSize: 12.5, marginTop: 4 }}>
              Étape 2 / 2 · Code à 6 chiffres envoyé à <span className="mono" style={{ color: "var(--text)" }}>{email}</span>
            </div>

            <div className="row" style={{ gap: 8, marginTop: 22, justifyContent: "center" }}>
              {code.map((d, i) => (
                <input
                  key={i}
                  ref={(el) => inputsRef.current[i] = el}
                  value={d}
                  onChange={(e) => updateCode(i, e.target.value)}
                  onKeyDown={(e) => e.key === "Backspace" && !d && i > 0 && inputsRef.current[i-1]?.focus()}
                  inputMode="numeric"
                  maxLength={1}
                  style={{
                    width: 44, height: 52, textAlign: "center",
                    background: "var(--bg-2)", border: `1px solid ${d ? "var(--accent)" : "var(--border)"}`,
                    borderRadius: 8, fontSize: 22, fontWeight: 600, fontFamily: "var(--font-mono)",
                    color: "var(--text)", outline: "none",
                    boxShadow: d ? "0 0 0 3px var(--accent-soft)" : "none",
                    transition: "all 100ms"
                  }}
                />
              ))}
            </div>

            <div className="between" style={{ marginTop: 18, fontSize: 11.5, color: "var(--text-dim)" }}>
              <span>Expire dans <span className="mono" style={{ color: ttl < 60 ? "var(--red)" : "var(--text)" }}>{fmtTtl}</span></span>
              <span>Essais <span className="mono" style={{ color: attempts >= 3 ? "var(--red)" : "var(--text)" }}>{attempts}/5</span></span>
            </div>

            <button className="btn" data-variant="ghost" onClick={resendCode} disabled={loading} style={{ width: "100%", marginTop: 14, justifyContent: "center" }}>
              <Icon name="refresh" size={12} /> {loading ? "Envoi…" : "Renvoyer le code"}
            </button>

            {!token && (
              <div style={{ marginTop: 14, padding: 10, background: "var(--accent-soft)", border: "1px solid oklch(0.72 0.17 248 / 0.25)", borderRadius: 8, fontSize: 11, color: "var(--accent)" }}>
                <span className="mono">Mode démo :</span> tapez <span className="mono" style={{ fontWeight: 600 }}>428931</span>
              </div>
            )}
          </>
        )}

        {step === "success" && (
          <div style={{ padding: "40px 0", textAlign: "center" }}>
            <div style={{ width: 56, height: 56, borderRadius: "50%", background: "var(--green-soft)", display: "grid", placeItems: "center", margin: "0 auto 14px", boxShadow: "0 0 0 4px oklch(0.74 0.16 156 / 0.08)" }}>
              <Icon name="check" size={26} style={{ color: "var(--green)" }} strokeWidth={2.5}/>
            </div>
            <div style={{ fontSize: 16, fontWeight: 600 }}>Session ouverte</div>
            <div className="muted" style={{ fontSize: 12.5, marginTop: 4 }}>Bienvenue {me.name} · expiration dans 24h</div>
          </div>
        )}
      </div>
    </Modal>
  );
};

const SettingsView = ({ onOpenAuth, theme, accent, onSetTheme, onSetAccent }) => {
  const toast = useToast();
  const [killSwitch, setKillSwitch] = useState(true);
  const ACCENTS = ["#5fa8ff", "#7c3aed", "#10b981", "#f59e0b", "#ec4899"];
  return (
    <div className="page" style={{ maxWidth: 1100 }}>
      <div className="page-head">
        <div>
          <div className="page-title">Paramètres & Sécurité</div>
          <div className="page-sub">Authentification 2FA · sync multi-appareils · gestion utilisateurs</div>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div className="card" style={{ gridColumn: "span 2" }}>
          <div className="card-head">
            <div><div className="card-title">Apparence</div><div className="card-sub">Thème et couleur d'accent · synchronisé multi-appareils via KV</div></div>
          </div>
          <div className="card-body" style={{ display: "flex", gap: 28, flexWrap: "wrap" }}>
            <div>
              <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 8, letterSpacing: ".04em", textTransform: "uppercase" }}>Thème</div>
              <div style={{ display: "flex", gap: 10 }}>
                {[
                  { id: "dark",  label: "Sombre", bg: "#11141a", fg: "#e4e7ee", accent: "#5fa8ff" },
                  { id: "light", label: "Clair",  bg: "#ffffff", fg: "#1a1d23", accent: "#3b82f6" },
                ].map((opt) => (
                  <button key={opt.id}
                    onClick={() => { onSetTheme(opt.id); toast({ message: `Thème ${opt.label.toLowerCase()} activé`, tone: "blue" }); }}
                    style={{
                      width: 168, padding: 0, borderRadius: 10, overflow: "hidden",
                      border: theme === opt.id ? `2px solid var(--accent)` : `1px solid var(--border)`,
                      background: "transparent", cursor: "pointer",
                      boxShadow: theme === opt.id ? "0 0 0 4px color-mix(in oklch, var(--accent) 20%, transparent)" : "none",
                      transition: "box-shadow 120ms, border-color 120ms",
                    }}>
                    <div style={{ height: 84, background: opt.bg, padding: 10, display: "flex", flexDirection: "column", gap: 6, alignItems: "flex-start" }}>
                      <div style={{ width: 38, height: 6, borderRadius: 2, background: opt.fg, opacity: 0.85 }}/>
                      <div style={{ width: 64, height: 4, borderRadius: 2, background: opt.fg, opacity: 0.35 }}/>
                      <div style={{ display: "flex", gap: 4, marginTop: "auto" }}>
                        <div style={{ width: 22, height: 8, borderRadius: 2, background: opt.accent }}/>
                        <div style={{ width: 22, height: 8, borderRadius: 2, background: opt.fg, opacity: 0.2 }}/>
                      </div>
                    </div>
                    <div style={{ padding: "8px 12px", display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, fontWeight: 550 }}>
                      <Icon name={opt.id === "dark" ? "moon" : "sun"} size={13}/>
                      {opt.label}
                      {theme === opt.id && <span style={{ marginLeft: "auto", color: "var(--accent)", fontSize: 11 }}>✓ Actif</span>}
                    </div>
                  </button>
                ))}
              </div>
            </div>
            <div>
              <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 8, letterSpacing: ".04em", textTransform: "uppercase" }}>Couleur d'accent</div>
              <div style={{ display: "flex", gap: 8 }}>
                {ACCENTS.map((c) => (
                  <button key={c} onClick={() => onSetAccent(c)} title={c}
                    style={{
                      width: 32, height: 32, borderRadius: 8, border: "none", cursor: "pointer",
                      background: c, padding: 0, position: "relative",
                      boxShadow: accent === c ? `0 0 0 2px var(--bg-1), 0 0 0 4px ${c}` : "none",
                      transition: "box-shadow 120ms",
                    }}/>
                ))}
              </div>
              <div className="mono" style={{ marginTop: 10, fontSize: 10.5, color: "var(--text-faint)" }}>
                KV key: <span style={{ color: "var(--text-muted)" }}>kcc:prefs:theme</span>, <span style={{ color: "var(--text-muted)" }}>kcc:prefs:accent</span>
              </div>
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <div><div className="card-title">Authentification 2FA</div><div className="card-sub">Code email · TTL 10 min · max 5 essais</div></div>
            <Badge tone="green" dot style={{ marginLeft: "auto" }}>2FA actif</Badge>
          </div>
          <div className="card-body stack" style={{ gap: 12 }}>
            <div className="between" style={{ padding: 10, background: "var(--bg-2)", borderRadius: 8 }}>
              <div><div style={{ fontSize: 13, fontWeight: 550 }}>Session courante</div>
                <div className="mono" style={{ fontSize: 11, color: "var(--text-dim)" }}>iPhone Safari · Montréal, QC · expire dans 23h 47min</div></div>
              <button className="btn" data-size="sm" data-variant="danger">Révoquer</button>
            </div>
            <div className="between" style={{ padding: 10, background: "var(--bg-2)", borderRadius: 8 }}>
              <div><div style={{ fontSize: 13, fontWeight: 550 }}>MacBook Pro · Chrome</div>
                <div className="mono" style={{ fontSize: 11, color: "var(--text-dim)" }}>Dernière activité il y a 2 min</div></div>
              <Badge tone="muted">Approuvé</Badge>
            </div>
            <button className="btn" onClick={onOpenAuth} style={{ alignSelf: "flex-start" }}><Icon name="shield" size={13} /> Tester le flow 2FA</button>
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <div><div className="card-title">Kill-switch emails</div><div className="card-sub">Coupe tous les envois Resend (Daily Digest, alertes…)</div></div>
            <Badge tone={killSwitch ? "green" : "red"} dot style={{ marginLeft: "auto" }}>{killSwitch ? "Emails ON" : "Emails OFF"}</Badge>
          </div>
          <div className="card-body">
            <button onClick={() => { setKillSwitch(!killSwitch); toast({ message: killSwitch ? "Envois email DÉSACTIVÉS" : "Envois email réactivés", tone: killSwitch ? "red" : "green" }); }}
              style={{
                width: "100%", height: 56,
                background: killSwitch ? "var(--green-soft)" : "var(--red-soft)",
                border: `1px solid ${killSwitch ? "var(--green)" : "var(--red)"}`,
                color: killSwitch ? "var(--green)" : "var(--red)",
                borderRadius: 10, fontSize: 14, fontWeight: 600,
                display: "flex", alignItems: "center", justifyContent: "center", gap: 10,
              }}>
              <div style={{ width: 32, height: 18, background: killSwitch ? "var(--green)" : "var(--red)", borderRadius: 999, position: "relative", transition: "background 200ms" }}>
                <div style={{ position: "absolute", top: 2, left: killSwitch ? 16 : 2, width: 14, height: 14, borderRadius: "50%", background: "white", transition: "left 200ms" }}/>
              </div>
              {killSwitch ? "Emails activés · cliquer pour kill" : "Emails coupés · cliquer pour réactiver"}
            </button>
            <div className="mono" style={{ marginTop: 10, fontSize: 10.5, color: "var(--text-faint)" }}>
              KV key: <span style={{ color: "var(--text-muted)" }}>kcc:email:killswitch</span> · TTL persistant
            </div>
          </div>
        </div>

        <div className="card" style={{ gridColumn: "span 2" }}>
          <div className="card-head"><div><div className="card-title">Audit log</div><div className="card-sub">5 dernières actions · {USERS.length} utilisateurs actifs</div></div></div>
          <table className="table">
            <thead><tr><th>Quand</th><th>Qui</th><th>Action</th><th>Cible</th><th>IP</th></tr></thead>
            <tbody>
              {[
                { d:"14:32",  who:"clarens",  act:"Connexion réussie",        target:"2FA · iPhone Safari", ip:"24.114.x.x" },
                { d:"14:18",  who:"carly",    act:"Modifié statut produit",   target:"Distributeur croquettes → Commandé", ip:"108.172.x.x" },
                { d:"13:55",  who:"kevin",    act:"Créé RFQ",                 target:"Yiwu OutdoorPro · RFQ-0042", ip:"66.130.x.x" },
                { d:"13:21",  who:"clarens",  act:"Réconciliation banque",    target:"CIBC · 18 transactions matchées", ip:"24.114.x.x" },
                { d:"12:04",  who:"carly",    act:"Import CSV",                target:"Seller Central · 142 lignes", ip:"108.172.x.x" },
              ].map((r,i) => (
                <tr key={i}>
                  <td className="mono muted">{r.d}</td>
                  <td><span className="row" style={{gap:6}}><Avatar user={r.who} size="sm"/><span style={{textTransform:"capitalize"}}>{r.who}</span></span></td>
                  <td>{r.act}</td>
                  <td className="muted">{r.target}</td>
                  <td><span className="mono" style={{ fontSize: 11, color: "var(--text-faint)" }}>{r.ip}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

window.TwoFactorModal = TwoFactorModal;
window.SettingsView = SettingsView;
