/* GUIDKO Sécurité — vérification renforcée (step-up) pour opérations sensibles
   + page Sécurité (méthodes 2FA, mot de passe, sessions, alertes).
   StepUp : modal réutilisable rendu par la page appelante (Wallet, vente, etc.). */

function StepUp({ open, reason, amount, onConfirm, onCancel }) {
  const C = GK.colors;
  const { t } = useI18n();
  const [method, setMethod] = React.useState("face");
  const [scan, setScan] = React.useState(0);
  const [code, setCode] = React.useState("");
  if (!open) return null;
  const methods = [
    { k: "face", g: "🙂", fr: "Visage", en: "Face" },
    { k: "sms",  g: "📱", fr: "SMS",    en: "SMS" },
    { k: "auth", g: "🔑", fr: "Authenticator", en: "Authenticator" },
  ];
  return (
    <div onClick={onCancel} style={{ position: "fixed", inset: 0, background: "rgba(8,11,24,0.6)", zIndex: 9500, display: "grid", placeItems: "center", padding: 20, backdropFilter: "blur(3px)" }}>
      <div onClick={e => e.stopPropagation()} style={{ background: "#fff", borderRadius: 18, padding: 28, width: 420, maxWidth: "100%", boxShadow: "0 30px 80px rgba(0,0,0,0.4)" }}>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "5px 11px", borderRadius: 999, background: "#FCEEF1", color: "#b3163b", fontSize: 11.5, fontWeight: 600, marginBottom: 14 }}>🔐 {t("Opération sensible","Sensitive operation")}</div>
        <h3 style={{ fontFamily: "'Instrument Serif', serif", fontSize: 28, fontWeight: 400, margin: "0 0 6px" }}>{t("Confirme avec une 2ᵉ vérification","Confirm with a 2nd check")}</h3>
        <p style={{ fontSize: 13.5, color: C.slate, marginBottom: 18, lineHeight: 1.5 }}>{reason || t("Cette action nécessite une vérification supplémentaire.","This action requires extra verification.")}{amount ? ` · ${amount}` : ""}</p>

        <div style={{ display: "flex", gap: 7, marginBottom: 16 }}>
          {methods.map(m => { const on = method === m.k; return (
            <button key={m.k} onClick={() => { setMethod(m.k); setScan(0); setCode(""); }} style={{ flex: 1, padding: "11px 6px", borderRadius: 10, border: `1.5px solid ${on ? C.flame : C.softLine}`, background: on ? "#FFF1EB" : "#fff", cursor: "pointer", fontFamily: "inherit" }}>
              <div style={{ fontSize: 19 }}>{m.g}</div><div style={{ fontSize: 11.5, fontWeight: 600, marginTop: 4 }}>{t(m.fr, m.en)}</div>
            </button>
          ); })}
        </div>

        {method === "face" ? (
          <div style={{ textAlign: "center" }}>
            <div onClick={() => { if (scan === 0) { setScan(1); setTimeout(() => setScan(2), 1300); } }} style={{ width: 104, height: 104, margin: "0 auto 12px", borderRadius: "50%", border: `3px solid ${scan === 2 ? C.signal : scan === 1 ? C.flame : C.softLine}`, display: "grid", placeItems: "center", fontSize: 42, cursor: scan === 0 ? "pointer" : "default", position: "relative", overflow: "hidden" }}>
              {scan === 2 ? "✓" : "🙂"}
              {scan === 1 && <div style={{ position: "absolute", left: 0, right: 0, height: 3, background: C.flame, animation: "gkScan2 1.3s linear", boxShadow: `0 0 10px ${C.flame}` }}/>}
            </div>
            <div style={{ fontSize: 12.5, color: C.slate, marginBottom: 14 }}>{scan === 0 ? t("Touche pour scanner","Tap to scan") : scan === 1 ? t("Analyse…","Scanning…") : t("Reconnu ✓","Recognized ✓")}</div>
            <style>{`@keyframes gkScan2{0%{top:6%}100%{top:90%}}`}</style>
          </div>
        ) : (
          <>
            <div style={{ padding: 11, background: C.paper, borderRadius: 9, fontSize: 12.5, color: C.slate, marginBottom: 12, display: "flex", alignItems: "center", gap: 8 }}>
              {method === "sms" ? t("Code SMS au ···45","SMS code to ···45") : t("Code de l'app","App code")}
              <span style={{ marginLeft: "auto", fontFamily: "'Geist Mono', monospace", color: C.flame, fontWeight: 600 }}>{method === "sms" ? "519 274" : ""}</span>
            </div>
            <Input label={t("Code","Code")} value={code} onChange={setCode} placeholder="519274"/>
          </>
        )}

        <div style={{ display: "flex", gap: 10, marginTop: 16 }}>
          <Button kind="ghost" full onClick={onCancel}>{t("Annuler","Cancel")}</Button>
          <Button kind="primary" full disabled={method === "face" && scan !== 2} style={{ opacity: (method === "face" && scan !== 2) ? 0.45 : 1 }} onClick={onConfirm}>{t("Confirmer","Confirm")} →</Button>
        </div>
      </div>
    </div>
  );
}

// ============ PAGE SÉCURITÉ ============
function SecurityPage({ role }) {
  const C = GK.colors;
  const { t } = useI18n();
  const toast = useToast();
  const [methods, setMethods] = React.useState({ email: true, sms: true, face: false, auth: false });
  const [stepup, setStepup] = React.useState(true);
  const enabled = Object.values(methods).filter(Boolean).length;

  const METHOD_DEFS = [
    { k: "email", g: "✉", fr: "Code par email", en: "Email code", sub: { fr: "Vérification à chaque connexion.", en: "Verification on every sign-in." } },
    { k: "sms",   g: "📱", fr: "Code par SMS", en: "SMS code", sub: { fr: "Sur ton numéro ···45.", en: "To your number ···45." } },
    { k: "face",  g: "🙂", fr: "Reconnaissance faciale", en: "Face recognition", sub: { fr: "Caméra du téléphone (mobile).", en: "Phone camera (mobile)." } },
    { k: "auth",  g: "🔑", fr: "Application authenticator", en: "Authenticator app", sub: { fr: "Code à 6 chiffres hors-ligne.", en: "Offline 6-digit code." } },
  ];
  const SESSIONS = [
    { dev: "iPhone 15 · Paris", cur: true, last: t("Maintenant","Now") },
    { dev: "MacBook · Paris", cur: false, last: t("Il y a 2 h","2h ago") },
    { dev: "Android · Lyon", cur: false, last: t("Hier","Yesterday") },
  ];

  return (
    <>
      <Topbar subtitle={t("SÉCURITÉ","SECURITY")} title={t("Sécurité du compte","Account security")} search={false}/>
      <PageBody>
        {/* Score */}
        <div style={{ display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 14, marginBottom: 16 }}>
          <Card dark style={{ padding: 26 }}>
            <Label color="#7A82A8">{t("NIVEAU DE PROTECTION","PROTECTION LEVEL")}</Label>
            <div style={{ display: "flex", alignItems: "center", gap: 16, margin: "14px 0 8px" }}>
              <div style={{ width: 60, height: 60, borderRadius: 16, background: enabled >= 2 ? C.signal : C.flame, display: "grid", placeItems: "center", fontSize: 26 }}>{enabled >= 2 ? "🛡" : "⚠"}</div>
              <div>
                <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 30, lineHeight: 1 }}>{enabled >= 3 ? t("Maximal","Maximum") : enabled >= 2 ? t("Fort","Strong") : t("Basique","Basic")}</div>
                <div style={{ fontSize: 13, color: "#9098B5", marginTop: 4 }}>{enabled} {t("méthodes actives","active methods")}</div>
              </div>
            </div>
            <div style={{ height: 8, borderRadius: 4, background: "#1F2542", overflow: "hidden", marginTop: 10 }}><div style={{ height: "100%", width: `${Math.min(enabled / 4 * 100, 100)}%`, background: C.signal, borderRadius: 4, transition: "width .3s" }}/></div>
          </Card>
          <Card style={{ padding: 22, display: "flex", flexDirection: "column", justifyContent: "center" }}>
            <Label style={{ marginBottom: 12 }}>{t("MOT DE PASSE","PASSWORD")}</Label>
            <div style={{ fontSize: 13.5, color: C.slate, marginBottom: 14, lineHeight: 1.5 }}>{t("Dernière modification il y a 3 mois. Pense à le renouveler.","Last changed 3 months ago. Consider renewing it.")}</div>
            <Button kind="light" onClick={() => toast.push(t("Lien de réinitialisation envoyé par email.","Reset link sent by email."), "signal")}>{t("Réinitialiser le mot de passe","Reset password")}</Button>
          </Card>
        </div>

        {/* Méthodes 2FA */}
        <Card style={{ padding: 0, overflow: "hidden", marginBottom: 16 }}>
          <div style={{ padding: "15px 20px", borderBottom: `1px solid ${C.softLine}` }}><Label>{t("MÉTHODES DE VÉRIFICATION","VERIFICATION METHODS")}</Label></div>
          {METHOD_DEFS.map((m, i) => (
            <div key={m.k} style={{ display: "flex", alignItems: "center", gap: 14, padding: "15px 20px", borderTop: i === 0 ? "none" : `1px solid ${C.softLine}` }}>
              <div style={{ width: 40, height: 40, borderRadius: 11, background: methods[m.k] ? "#EAF7F0" : C.cream, display: "grid", placeItems: "center", fontSize: 18 }}>{m.g}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14.5, fontWeight: 600 }}>{t(m.fr, m.en)}</div>
                <div style={{ fontSize: 12.5, color: C.slate, marginTop: 2 }}>{m.sub[GK_lang ? GK_lang() : "fr"] || m.sub.fr}</div>
              </div>
              <Toggle on={methods[m.k]} onChange={(v) => { setMethods(s => ({ ...s, [m.k]: v })); toast.push(v ? t("Méthode activée","Method enabled") : t("Méthode désactivée","Method disabled"), v ? "signal" : "neutral"); }}/>
            </div>
          ))}
        </Card>

        {/* Step-up */}
        <Card style={{ padding: 18, marginBottom: 16, display: "flex", alignItems: "center", gap: 14, background: "#FBF8EE" }}>
          <span style={{ fontSize: 22 }}>🔐</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14.5, fontWeight: 600 }}>{t("Vérification renforcée pour les opérations sensibles","Step-up for sensitive operations")}</div>
            <div style={{ fontSize: 12.5, color: C.slate, marginTop: 2, lineHeight: 1.45 }}>{t("Retraits Wallet, vente de véhicule, gros paiements : 2ᵉ vérification exigée.","Wallet withdrawals, vehicle sale, big payments: 2nd check required.")}</div>
          </div>
          <Toggle on={stepup} onChange={setStepup}/>
        </Card>

        {/* Sessions */}
        <Card style={{ padding: 0, overflow: "hidden" }}>
          <div style={{ padding: "15px 20px", borderBottom: `1px solid ${C.softLine}`, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <Label>{t("APPAREILS CONNECTÉS","CONNECTED DEVICES")}</Label>
            <span onClick={() => toast.push(t("Toutes les autres sessions ont été fermées.","All other sessions signed out."), "signal")} style={{ fontSize: 12, color: C.flame, cursor: "pointer", fontWeight: 600 }}>{t("Tout déconnecter","Sign out all")}</span>
          </div>
          {SESSIONS.map((s, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "13px 20px", borderTop: i === 0 ? "none" : `1px solid ${C.softLine}` }}>
              <span style={{ fontSize: 17 }}>{s.dev.includes("iPhone") || s.dev.includes("Android") ? "📱" : "💻"}</span>
              <div style={{ flex: 1 }}><div style={{ fontSize: 13.5, fontWeight: 600 }}>{s.dev}</div><div style={{ fontSize: 11.5, color: C.slate }}>{s.last}</div></div>
              {s.cur ? <Pill tone="signal">{t("Cet appareil","This device")}</Pill> : <span style={{ fontSize: 12, color: C.slate, cursor: "pointer" }}>✕</span>}
            </div>
          ))}
        </Card>
      </PageBody>
    </>
  );
}

window.StepUp = StepUp;
window.SecurityPage = SecurityPage;
