/* FoxBot Pro — Auth wizard (design ZIP câblé sur les vrais endpoints).
   Flux : auth(login/signup) -> [signup] okx -> telegram -> webauthn -> recap -> app.
   Le login entre direct dans l'app. Le signup lance l'onboarding (flag STORE.ONBOARDING
   qui retient le wizard monté malgré l'auto-login). Exposé en window.AuthWizard. */
(function () {
  const { useState, useEffect, useRef } = React;

  const I = {
    Mail:  () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-10 7L2 7"/></svg>,
    Lock:  () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>,
    User:  () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>,
    Key:   () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><circle cx="7.5" cy="15.5" r="4.5"/><path d="m21 2-9.6 9.6"/><path d="m15.5 7.5 3 3L22 7l-3-3"/></svg>,
    Eye:   () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg>,
    EyeOff:() => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" y1="2" x2="22" y2="22"/></svg>,
    Arrow: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>,
    ArrowL:() => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>,
    Shield:() => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>,
    Check: () => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>,
    Copy:  () => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>,
    Tg:    () => <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M21.5 4.2 18.5 19c-.2 1-.8 1.2-1.7.7l-4.6-3.4-2.2 2.2c-.3.3-.5.5-1 .5l.4-5L18.4 6c.4-.4-.1-.5-.6-.2L7.5 12.1l-4.7-1.5c-1-.3-1-1 .2-1.5L20.2 3c.9-.3 1.6.2 1.3 1.2z"/></svg>,
    Finger:() => <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s2-2 2-6"/><path d="M16 22a14.78 14.78 0 0 0 2-7"/><path d="M9 9a3 3 0 1 1 6 0c0 4.5-3 8-3 12"/><path d="M5 18c0-2 1.5-4 1.5-9a5.5 5.5 0 0 1 11 0c0 .87-.06 1.7-.14 2.5"/><path d="M3 14a16 16 0 0 1 1.5-7"/></svg>,
  };

  function Field({ label, type = "text", placeholder, icon, value, onChange, autoComplete, noFill }) {
    const [show, setShow] = useState(false);
    const [ro, setRo] = useState(!!noFill);   // readonly au montage = bloque l'autofill du navigateur
    const isPwd = type === "password";
    const guard = noFill
      ? { autoComplete: "off", readOnly: ro, onFocus: () => setRo(false),
          name: "fld_" + String(label || "x").replace(/[^a-z]/gi, ""),
          "data-lpignore": "true", "data-1p-ignore": "true" }
      : { autoComplete };
    return (
      <div className="aw-field">
        <label className="aw-label">{label}</label>
        <div className="aw-input-wrap">
          {icon && <span className="aw-ficon">{icon}</span>}
          <input className="aw-input" type={isPwd ? (show ? "text" : "password") : type}
            placeholder={placeholder} value={value} {...guard}
            onChange={(e) => onChange(e.target.value)} style={isPwd ? { paddingRight: 44 } : undefined} />
          {isPwd && <button type="button" className="aw-ftoggle" onClick={() => setShow((s) => !s)} aria-label="Afficher/masquer">{show ? <I.EyeOff /> : <I.Eye />}</button>}
        </div>
      </div>
    );
  }

  const Skip = ({ children, onClick }) => <button type="button" className="aw-skip" onClick={onClick}>{children}</button>;

  function Stepper({ current }) {
    return (
      <div className="aw-stepper">
        {[1, 2, 3].map((n, i) => (
          <React.Fragment key={n}>
            <div className={`aw-step-dot ${n < current ? "done" : n === current ? "active" : ""}`}>{n < current ? <I.Check /> : n}</div>
            {i < 2 && <div className={`aw-step-line ${n < current ? "done" : ""}`} />}
          </React.Fragment>
        ))}
      </div>
    );
  }

  const StepHeader = ({ badge, title, sub }) => (
    <div className="aw-step-head">
      {badge && <div className="aw-badge">{badge}</div>}
      <h2 className="aw-step-title">{title}</h2>
      {sub && <p className="aw-sub">{sub}</p>}
    </div>
  );

  /* ─── STEP 1 : OKX ─── */
  function StepOKX({ onNext, onSkip }) {
    const [apiKey, setApiKey] = useState("");
    const [secret, setSecret] = useState("");
    const [pass, setPass]     = useState("");
    const [mode, setMode]     = useState("paper");
    const [loading, setLoad]  = useState(false);
    const [err, setErr]       = useState("");
    const canSubmit = apiKey.length > 4 && secret.length > 4 && pass.length > 0 && !loading;

    async function save(e) {
      e.preventDefault();
      setErr(""); setLoad(true);
      try {
        const j = await fetch("/api/okx/credentials", {
          method: "POST", credentials: "include", headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ api_key: apiKey, secret, passphrase: pass, is_demo: mode === "paper" }),
        }).then((r) => r.json());
        if (j.ok) onNext("configured");
        else setErr(j.msg || "Connexion OKX échouée");
      } catch (e2) { setErr(e2.message || "Erreur réseau"); }
      setLoad(false);
    }

    return (
      <>
        <Stepper current={1} />
        <StepHeader badge="ÉTAPE 1 SUR 3" title="Connecte ton compte OKX" sub="3 clés API et le bot commence à scanner les marchés pour toi." />
        <div className="aw-mode-toggle">
          <div className={`aw-mode-ind ${mode === "live" ? "right" : ""}`} />
          <button type="button" className={`aw-mode-tab ${mode === "paper" ? "active" : ""}`} onClick={() => setMode("paper")}>PAPER · SIMULATION</button>
          <button type="button" className={`aw-mode-tab ${mode === "live" ? "active" : ""}`} onClick={() => setMode("live")}>RÉEL · CAPITAL</button>
        </div>
        <form onSubmit={save}>
          <Field label="API Key" placeholder="ec3a2f4b-1234-..." icon={<I.Key />} value={apiKey} onChange={setApiKey} noFill />
          <Field label="Secret Key" type="password" placeholder="••••••••••••" icon={<I.Lock />} value={secret} onChange={setSecret} noFill />
          <Field label="Passphrase" type="password" placeholder="••••••••" icon={<I.Lock />} value={pass} onChange={setPass} noFill />
          <div className="aw-note"><span style={{ color: "var(--aw-green)" }}><I.Shield /></span><span>Chiffrement <b>AES-256</b> · Permissions <b>Read + Trade</b> uniquement, jamais Withdraw.</span></div>
          {err && <div className="aw-err" style={{ marginTop: 12 }}>{err}</div>}
          <div style={{ marginTop: 14 }}>
            <button type="submit" className="aw-btn-primary" disabled={!canSubmit}>{loading ? "Vérification…" : "Sauvegarder et continuer"}{!loading && <I.Arrow />}</button>
            <div style={{ textAlign: "center" }}><Skip onClick={() => onSkip("skipped")}>Configurer plus tard</Skip></div>
          </div>
        </form>
      </>
    );
  }

  /* ─── STEP 2 : Telegram ─── */
  function StepTelegram({ onNext, onSkip }) {
    const [code, setCode]   = useState(null);   // {value, bot}
    const [linked, setLink] = useState(false);
    const [copied, setCop]  = useState(false);
    const [loading, setLoad]= useState(false);
    const [err, setErr]     = useState("");
    const pollRef = useRef(null);

    async function generate() {
      setErr(""); setLoad(true);
      try {
        const j = await fetch("/api/telegram/link/generate", { method: "POST", credentials: "include" }).then((r) => r.json());
        if (j.ok) setCode({ value: j.code, bot: j.bot_username || "Fox_pro75_bot" });
        else setErr(j.msg || "Erreur");
      } catch (e2) { setErr(e2.message); }
      setLoad(false);
    }

    useEffect(() => {
      if (!code || linked) return;
      pollRef.current = setInterval(async () => {
        try {
          const s = await fetch("/api/telegram/link/status", { credentials: "include" }).then((r) => r.json());
          if (s && s.linked) { setLink(true); clearInterval(pollRef.current); }
        } catch {}
      }, 3000);
      return () => clearInterval(pollRef.current);
    }, [code, linked]);

    function copy() { try { navigator.clipboard.writeText(code.value); } catch {} setCop(true); setTimeout(() => setCop(false), 1600); }

    return (
      <>
        <Stepper current={2} />
        <StepHeader badge="ÉTAPE 2 SUR 3" title="Reçois tes signaux sur Telegram" sub="Alertes en temps réel à chaque trade ouvert ou fermé." />
        {!code ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {err && <div className="aw-err">{err}</div>}
            <button type="button" className="aw-btn-primary" onClick={generate} disabled={loading}>{loading ? "…" : "Générer mon code de liaison"}</button>
            <div style={{ textAlign: "center" }}><Skip onClick={() => onSkip("skipped")}>Configurer plus tard</Skip></div>
          </div>
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <div className="aw-code-box">
              <span className="aw-code-cap">TON CODE DE LIAISON</span>
              <div className="aw-code">{code.value}</div>
              <button type="button" className={`aw-code-copy ${copied ? "ok" : ""}`} onClick={copy}>{copied ? <><I.Check /> COPIÉ</> : <><I.Copy /> COPIER</>}</button>
            </div>
            <ol className="aw-tg-steps">
              <li>Ouvre Telegram et cherche <b>@{code.bot}</b>.</li>
              <li>Envoie-lui <b style={{ fontFamily: "var(--aw-mono, monospace)", color: "var(--aw-accent-2)" }}>/link {code.value}</b></li>
              <li>Reviens ici, la connexion se fait toute seule.</li>
            </ol>
            <a href={`https://t.me/${code.bot}`} target="_blank" rel="noreferrer" style={{ textDecoration: "none" }}><div className="aw-btn-secondary"><I.Tg /> Ouvrir Telegram</div></a>
            <div className={`aw-tg-status ${linked ? "ok" : ""}`}>{linked ? <><I.Check /> Telegram connecté !</> : "En attente de ta connexion Telegram…"}</div>
            <div>
              <button type="button" className="aw-btn-primary" onClick={() => onNext("linked")} disabled={!linked}>Continuer <I.Arrow /></button>
              <div style={{ textAlign: "center" }}><Skip onClick={() => onSkip("skipped")}>Passer pour l'instant</Skip></div>
            </div>
          </div>
        )}
      </>
    );
  }

  /* ─── STEP 3 : WebAuthn ─── */
  function StepWebAuthn({ onNext, onSkip }) {
    const supported = typeof window.isWebauthnSupported === "function" ? window.isWebauthnSupported() : !!window.PublicKeyCredential;
    const [state, setState] = useState("idle"); // idle|requesting|enabled|error
    const [err, setErr]     = useState("");
    const ua = navigator.userAgent || "";
    const label = /iPhone|iPad/.test(ua) ? "Face ID" : /Mac/.test(ua) ? "Touch ID" : /Windows/.test(ua) ? "Windows Hello" : "biométrie";

    async function activate() {
      if (!supported) return;
      setErr(""); setState("requesting");
      try {
        const j = await window.fbWebauthnRegister(label);
        if (j && j.ok) { setState("enabled"); setTimeout(() => onNext("enabled"), 900); }
        else { setState("error"); setErr((j && j.msg) || "Activation impossible"); }
      } catch (e2) { setState("error"); setErr(e2.message || "Activation annulée"); }
    }

    return (
      <>
        <Stepper current={3} />
        <StepHeader badge="ÉTAPE 3 SUR 3" title={`Connecte-toi avec ${label}`} sub="Plus sûr et plus rapide qu'un mot de passe. La clé reste sur ton appareil." />
        <div className="aw-bio-wrap"><div className={`aw-bio ${state === "enabled" ? "ok" : ""}`}>{state === "enabled" ? <I.Check /> : <I.Finger />}</div></div>
        {!supported && <div className="aw-note" style={{ borderColor: "rgba(242,169,59,0.24)", background: "rgba(242,169,59,0.06)", color: "#F2A93B" }}>Pas disponible sur cet appareil. Tu peux continuer avec ton mot de passe.</div>}
        {err && <div className="aw-err" style={{ marginTop: 12 }}>{err}</div>}
        <div style={{ marginTop: 16 }}>
          <button type="button" className="aw-btn-primary" onClick={activate} disabled={!supported || state === "enabled" || state === "requesting"}>
            {state === "enabled" ? <><I.Check /> Activé</> : state === "requesting" ? "En attente…" : <>Activer {label} <I.Arrow /></>}
          </button>
          <div style={{ textAlign: "center" }}><Skip onClick={() => onSkip(supported ? "skipped" : "unsupported")}>Plus tard</Skip></div>
        </div>
      </>
    );
  }

  /* ─── RECAP ─── */
  function StepRecap({ progress, onFinish }) {
    const items = [
      { k: "account", l: "Compte créé", done: true, sub: "Profil actif" },
      { k: "okx", l: "OKX connecté", done: progress.okx === "configured", sub: progress.okx === "configured" ? "Clés chiffrées AES-256" : "Non configuré" },
      { k: "telegram", l: "Telegram lié", done: progress.telegram === "linked", sub: progress.telegram === "linked" ? "Alertes activées" : "Non lié" },
      { k: "webauthn", l: "Biométrie activée", done: progress.webauthn === "enabled", sub: progress.webauthn === "enabled" ? "Connexion rapide" : "Non activée" },
    ];
    return (
      <>
        <div className="aw-bio-wrap"><div className="aw-bio ok" style={{ width: 72, height: 72 }}><I.Check /></div></div>
        <StepHeader title="Tout est prêt !" sub="Ton bot est en place. Bienvenue dans la meute." />
        <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 18 }}>
          {items.map((it) => (
            <div key={it.k} className={`aw-recap ${it.done ? "done" : ""}`}>
              <span className="aw-recap-ic">{it.done ? <I.Check /> : "○"}</span>
              <div><div className="aw-recap-l">{it.l}</div><div className="aw-recap-s">{it.sub}</div></div>
            </div>
          ))}
        </div>
        <button type="button" className="aw-btn-primary" onClick={onFinish}>Accéder à mon dashboard <I.Arrow /></button>
      </>
    );
  }

  /* ─── AuthCard (login/signup) ─── */
  function AuthCard({ onSignupSuccess }) {
    const [mode, setMode]   = useState("login");
    const [first, setFirst] = useState("");
    const [last, setLast]   = useState("");
    const [email, setEmail] = useState("");
    const [pwd, setPwd]     = useState("");
    const [agree, setAgree] = useState(false);
    const [loading, setLoad]= useState(false);
    const [err, setErr]     = useState("");
    const isSignup = mode === "signup";
    const webauthnOK = typeof window.isWebauthnSupported === "function" ? window.isWebauthnSupported() : !!window.PublicKeyCredential;

    async function submit(e) {
      e.preventDefault();
      setErr(""); setLoad(true);
      try {
        if (isSignup) {
          const display_name = `${first} ${last}`.trim() || undefined;
          window.fbSetOnboarding(true);            // AVANT le signup : retient le wizard malgré l'auto-login
          const res = await window.fbSignup(email, pwd, display_name);
          if (res && res.ok) onSignupSuccess();
          else { window.fbSetOnboarding(false); setErr((res && res.msg) || "Création échouée"); }
        } else {
          const res = await window.fbLogin(email, pwd);
          if (!res || !res.ok) setErr((res && res.msg) || "Identifiants invalides");
        }
      } catch (e2) { window.fbSetOnboarding(false); setErr(e2.message || "Erreur réseau"); }
      setLoad(false);
    }

    async function webauthn() {
      setErr(""); setLoad(true);
      try {
        const j = await window.fbWebauthnLogin(email);
        if (j && j.ok) { await window.fbAuthRefresh(); await window.fbRefresh(); }
        else setErr((j && j.msg) || "Échec biométrique");
      } catch (e2) { setErr(e2.message || "Échec biométrique"); }
      setLoad(false);
    }

    const canSubmit = email && pwd && (!isSignup || agree) && !loading;

    return (
      <>
        <div className="aw-brand">
          <img src="/static/foxbot-logo-mail.png" alt="FoxBot Pro" />
          <div>
            <h1 className="aw-title">{isSignup ? "Créez votre compte" : "Re-bonjour, trader."}</h1>
            <p className="aw-sub">{isSignup ? "Vos clés, votre exchange, votre contrôle." : "Connectez-vous pour accéder à vos signaux et positions."}</p>
          </div>
        </div>
        <div className="aw-tabs">
          <div className={`aw-tab-ind ${isSignup ? "right" : ""}`} />
          <button type="button" className={`aw-tab ${!isSignup ? "active" : ""}`} onClick={() => { setMode("login"); setErr(""); }}>Connexion</button>
          <button type="button" className={`aw-tab ${isSignup ? "active" : ""}`} onClick={() => { setMode("signup"); setErr(""); }}>Créer un compte</button>
        </div>
        <form onSubmit={submit}>
          {isSignup && (
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <Field label="Prénom" placeholder="Marc" icon={<I.User />} value={first} onChange={setFirst} autoComplete="given-name" />
              <Field label="Nom" placeholder="Dupont" icon={<I.User />} value={last} onChange={setLast} autoComplete="family-name" />
            </div>
          )}
          <Field label="Email" type="email" placeholder="vous@email.com" icon={<I.Mail />} value={email} onChange={setEmail} autoComplete={isSignup ? "email" : "username"} />
          <Field label="Mot de passe" type="password" placeholder={isSignup ? "Min. 8 caractères" : "Votre mot de passe"} icon={<I.Lock />} value={pwd} onChange={setPwd} autoComplete={isSignup ? "new-password" : "current-password"} />
          {isSignup && (
            <label className="aw-check" style={{ marginBottom: 16 }}>
              <input type="checkbox" checked={agree} onChange={(e) => setAgree(e.target.checked)} />
              <span>J'accepte les <a className="aw-link" href="#" onClick={(e) => e.preventDefault()}>conditions générales</a> et la <a className="aw-link" href="#" onClick={(e) => e.preventDefault()}>politique de confidentialité</a>.</span>
            </label>
          )}
          {err && <div className="aw-err">{err}</div>}
          <button type="submit" className="aw-btn-primary" disabled={!canSubmit}>{loading ? "…" : (isSignup ? "Créer mon compte" : "Se connecter")}{!loading && <I.Arrow />}</button>
        </form>
        {!isSignup && webauthnOK && (
          <>
            <div className="aw-divider"><span className="ln" /><span className="tx">OU</span><span className="ln" /></div>
            <button type="button" className="aw-btn-secondary" onClick={webauthn} disabled={loading}><I.Finger /> Se connecter avec Face ID / Touch ID</button>
          </>
        )}
        <div className="aw-foot">
          {isSignup ? "Déjà un compte ? " : "Pas encore de compte ? "}
          <a className="aw-link" href="#" onClick={(e) => { e.preventDefault(); setMode(isSignup ? "login" : "signup"); setErr(""); }}>{isSignup ? "Se connecter" : "Créer un compte"}</a>
        </div>
      </>
    );
  }

  /* ─── Routeur ─── */
  function AuthWizard() {
    const [step, setStep] = useState("auth");   // auth|okx|telegram|webauthn|recap
    const [progress, setProgress] = useState({ okx: null, telegram: null, webauthn: null });
    const prog = (k, v) => setProgress((p) => ({ ...p, [k]: v }));

    function finish() {
      if (typeof window.fbSetOnboarding === "function") window.fbSetOnboarding(false);
      if (typeof window.fbRefresh === "function") window.fbRefresh();
    }

    return (
      <div className="auth-wiz">
        <div className="aw-orb aw-orb-1" />
        <div className="aw-orb aw-orb-2" />
        <div className="aw-main">
          <div className="aw-card">
            {step === "auth" && <AuthCard onSignupSuccess={() => setStep("okx")} />}
            {step === "okx" && <StepOKX onNext={(s) => { prog("okx", s); setStep("telegram"); }} onSkip={(s) => { prog("okx", s); setStep("telegram"); }} />}
            {step === "telegram" && <StepTelegram onNext={(s) => { prog("telegram", s); setStep("webauthn"); }} onSkip={(s) => { prog("telegram", s); setStep("webauthn"); }} />}
            {step === "webauthn" && <StepWebAuthn onNext={(s) => { prog("webauthn", s); setStep("recap"); }} onSkip={(s) => { prog("webauthn", s); setStep("recap"); }} />}
            {step === "recap" && <StepRecap progress={progress} onFinish={finish} />}
          </div>
        </div>
        {step === "auth" && (
          <div className="aw-pagefoot">
            <span>· CHIFFREMENT AES-256</span>
            <span>· PERMISSIONS NO-WITHDRAW</span>
            <span>· VOS CLÉS, VOTRE EXCHANGE</span>
          </div>
        )}
      </div>
    );
  }

  window.AuthWizard = AuthWizard;
})();
