// auth.jsx — AFEX PAY authentication & onboarding
const { useState: useS } = React;

// Carries {email, pw} from the login screen to the 2FA screen (same tab).
let pendingLogin = null;

function AuthShell({ children, foot }) {
  return (
    <div style={{ minHeight: "100%", display: "grid", gridTemplateColumns: "1.05fr 1fr" }} className="auth-grid">
      {/* Brand panel */}
      <div className="auth-brand hide-mobile" style={{
        position: "relative", overflow: "hidden", padding: "48px 56px",
        backgroundImage: "linear-gradient(180deg, rgba(5,5,5,0.78) 0%, rgba(5,5,5,0.32) 38%, rgba(5,5,5,0.86) 100%), url('assets/afex-hero.png')",
        backgroundSize: "cover", backgroundPosition: "center 30%",
        borderRight: "1px solid var(--line)", display: "flex", flexDirection: "column", justifyContent: "space-between"
      }}>
        <div style={{ height: 38 }}></div>
        <div className="col gap-20" style={{ maxWidth: 460 }}>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 44, fontWeight: 600, letterSpacing: "-0.035em", lineHeight: 1.06, textShadow: "0 2px 30px rgba(0,0,0,0.6)" }}>
            De seller<br />para seller.
          </div>
          <p style={{ fontSize: 16, lineHeight: 1.55, margin: 0, color: "rgba(255,255,255,0.82)", textShadow: "0 1px 12px rgba(0,0,0,0.6)" }}>
            Mais aprovação. Menos taxas. Mais crescimento. Pagamentos simples, justos e eficientes para o seu e‑commerce.
          </p>
          <div className="row gap-28" style={{ marginTop: 10 }}>
            {[["99,2%", "Aprovação média"], ["D+0", "Antecipação"], ["R$ 4,8 bi", "Processados"]].map(([a, b]) => (
              <div key={b} className="col gap-3">
                <div className="num" style={{ fontSize: 25, fontWeight: 600 }}>{a}</div>
                <div style={{ fontSize: 12, color: "rgba(255,255,255,0.6)" }}>{b}</div>
              </div>
            ))}
          </div>
        </div>
        <div className="row gap-16" style={{ fontSize: 12.5, color: "rgba(255,255,255,0.6)" }}>
          <span className="row gap-6"><I.shield size={14} /> PCI‑DSS Nível 1</span>
          <span className="row gap-6"><I.lock size={14} /> Criptografia ponta a ponta</span>
        </div>
      </div>
      {/* Form panel */}
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "40px 24px", background: "var(--bg)" }}>
        <div className="col gap-24 fade-up" style={{ width: "100%", maxWidth: 400 }}>
          {children}
        </div>
        {foot && <div className="faint" style={{ fontSize: 13, marginTop: 28 }}>{foot}</div>}
      </div>
    </div>
  );
}

function Pw({ value, onChange, placeholder = "••••••••" }) {
  const [show, setShow] = useS(false);
  return (
    <div className="input-affix">
      <input className="input" type={show ? "text" : "password"} value={value} placeholder={placeholder}
        onChange={e => onChange(e.target.value)} style={{ paddingRight: 42 }} />
      <button className="affix affix-r" onClick={() => setShow(!show)} style={{ background: "none", border: "none", color: "var(--ink-faint)", cursor: "pointer", display: "flex" }}>
        {show ? <I.eyeOff size={18} /> : <I.eye size={18} />}
      </button>
    </div>
  );
}

function AuthLogin({ go }) {
  const demo = (window.AFEX_CONFIG && window.AFEX_CONFIG.demo && window.AFEX_CONFIG.demo.seller) || {};
  const [email, setEmail] = useS(demo.email || "");
  const [pw, setPw] = useS(demo.password || "");
  const [err, setErr] = useS("");
  const [busy, setBusy] = useS(false);

  async function submit() {
    if (busy) return;
    setErr(""); setBusy(true);
    try {
      const r = await api.auth.login(email, pw);
      go(r.user.role === "admin" ? "a/dashboard" : "s/dashboard");
    } catch (e) {
      if (e.code === "TOTP_REQUIRED") { pendingLogin = { email, pw }; go("auth/2fa"); }
      else setErr(e.message || "Não foi possível entrar.");
    } finally { setBusy(false); }
  }

  return (
    <AuthShell foot={<span>Não tem conta? <a onClick={() => go("onboarding")} style={{ color: "var(--accent)", cursor: "pointer", fontWeight: 600 }}>Criar conta grátis</a></span>}>
      <div style={{ marginBottom: 6 }}><Wordmark height={26} /></div>
      <div className="col gap-6">
        <h1 style={{ fontSize: 28 }}>Entrar na sua conta</h1>
        <p className="muted" style={{ margin: 0, fontSize: 14.5 }}>Bem‑vindo de volta. Acesse seu painel AFEX Pay.</p>
      </div>
      {err && <div style={{ color: "var(--red)", background: "var(--red-wash)", fontSize: 13.5, padding: "10px 12px", borderRadius: 8 }}>{err}</div>}
      <div className="field">
        <label className="label">E‑mail</label>
        <div className="input-affix"><I.mail size={18} className="affix affix-l" /><input className="input" value={email} onChange={e => setEmail(e.target.value)} onKeyDown={e => e.key === "Enter" && submit()} placeholder="voce@empresa.com" /></div>
      </div>
      <div className="field">
        <div className="row between"><label className="label">Senha</label><a onClick={() => go("auth/forgot")} style={{ fontSize: 13, color: "var(--accent)", cursor: "pointer", fontWeight: 600 }}>Esqueci a senha</a></div>
        <div onKeyDown={e => e.key === "Enter" && submit()}><Pw value={pw} onChange={setPw} /></div>
      </div>
      <button className="btn btn-primary btn-lg btn-block" onClick={submit} disabled={busy}>{busy ? "Entrando…" : <>Entrar <I.arrowRight size={18} /></>}</button>
      <div className="row gap-12" style={{ margin: "2px 0" }}><div className="divider" /><span className="faint" style={{ fontSize: 12.5, whiteSpace: "nowrap" }}>ou continue com</span><div className="divider" /></div>
      <div className="row gap-12">
        <button className="btn btn-ghost btn-block" onClick={() => setErr("Login com Google/SSO ainda não está disponível.")}>Google</button>
        <button className="btn btn-ghost btn-block" onClick={() => setErr("Login com Google/SSO ainda não está disponível.")}>SSO</button>
      </div>
    </AuthShell>
  );
}

function AuthSignup({ go }) {
  const [f, setF] = useS({ company: "", cnpj: "", owner: "", email: "", phone: "", pw: "" });
  const up = (k, v) => setF(s => ({ ...s, [k]: v }));
  return (
    <AuthShell foot={<span>Já tem conta? <a onClick={() => go("auth/login")} style={{ color: "var(--accent)", cursor: "pointer", fontWeight: 600 }}>Entrar</a></span>}>
      <div className="col gap-6">
        <h1 style={{ fontSize: 28 }}>Criar conta de seller</h1>
        <p className="muted" style={{ margin: 0, fontSize: 14.5 }}>Comece a vender em minutos. Sem mensalidade.</p>
      </div>
      <div className="field"><label className="label">Nome da empresa</label><div className="input-affix"><I.building size={18} className="affix affix-l" /><input className="input" value={f.company} onChange={e => up("company", e.target.value)} placeholder="Minha Loja LTDA" /></div></div>
      <div className="row gap-12">
        <div className="field grow"><label className="label">CNPJ</label><input className="input" value={f.cnpj} onChange={e => up("cnpj", e.target.value)} placeholder="00.000.000/0001-00" /></div>
        <div className="field grow"><label className="label">Responsável</label><input className="input" value={f.owner} onChange={e => up("owner", e.target.value)} placeholder="Nome completo" /></div>
      </div>
      <div className="field"><label className="label">E‑mail</label><div className="input-affix"><I.mail size={18} className="affix affix-l" /><input className="input" value={f.email} onChange={e => up("email", e.target.value)} placeholder="voce@empresa.com" /></div></div>
      <div className="row gap-12">
        <div className="field grow"><label className="label">Telefone</label><div className="input-affix"><I.phone size={18} className="affix affix-l" /><input className="input" value={f.phone} onChange={e => up("phone", e.target.value)} placeholder="(11) 99999‑9999" /></div></div>
        <div className="field grow"><label className="label">Senha</label><Pw value={f.pw} onChange={v => up("pw", v)} /></div>
      </div>
      <label className="row gap-10" style={{ fontSize: 13, color: "var(--ink-soft)", cursor: "pointer", alignItems: "flex-start" }}>
        <input type="checkbox" defaultChecked style={{ accentColor: "var(--accent)", marginTop: 2 }} />
        <span>Li e aceito os <a style={{ color: "var(--accent)" }}>Termos de Uso</a> e a <a style={{ color: "var(--accent)" }}>Política de Privacidade</a>.</span>
      </label>
      <button className="btn btn-primary btn-lg btn-block" onClick={() => go("onboarding")}>Criar conta <I.arrowRight size={18} /></button>
    </AuthShell>
  );
}

function AuthForgot({ go }) {
  const [email, setEmail] = useS("");
  const [sent, setSent] = useS(false);
  const [busy, setBusy] = useS(false);

  async function submit() {
    if (busy) return;
    setBusy(true);
    try { await api.auth.forgot(email); } catch (e) { /* same UX whether or not the email exists */ }
    finally { setBusy(false); setSent(true); }
  }

  return (
    <AuthShell foot={<a onClick={() => go("auth/login")} style={{ color: "var(--accent)", cursor: "pointer", fontWeight: 600 }}>← Voltar para o login</a>}>
      <div style={{ width: 52, height: 52, borderRadius: 14, background: "var(--accent-wash)", color: "var(--accent)", display: "flex", alignItems: "center", justifyContent: "center" }}><I.lock size={24} /></div>
      {sent ? (
        <div className="col gap-6">
          <h1 style={{ fontSize: 28 }}>Verifique seu e‑mail</h1>
          <p className="muted" style={{ margin: 0, fontSize: 14.5 }}>Se existir uma conta para <b style={{ color: "var(--ink)" }}>{email}</b>, enviamos um link para redefinir a senha. O link expira em alguns minutos.</p>
        </div>
      ) : (
        <>
          <div className="col gap-6"><h1 style={{ fontSize: 28 }}>Recuperar senha</h1><p className="muted" style={{ margin: 0, fontSize: 14.5 }}>Informe seu e‑mail e enviaremos um link para redefinir sua senha.</p></div>
          <div className="field"><label className="label">E‑mail</label><div className="input-affix"><I.mail size={18} className="affix affix-l" /><input className="input" value={email} onChange={e => setEmail(e.target.value)} onKeyDown={e => e.key === "Enter" && submit()} placeholder="voce@empresa.com" /></div></div>
          <button className="btn btn-primary btn-lg btn-block" onClick={submit} disabled={busy}>{busy ? "Enviando…" : "Enviar link de recuperação"}</button>
        </>
      )}
    </AuthShell>
  );
}

function CodeInput({ onDone, onChange }) {
  const [vals, setVals] = useS(["", "", "", "", "", ""]);
  const refs = React.useRef([]);
  const set = (i, v) => {
    if (!/^\d?$/.test(v)) return;
    const nv = [...vals]; nv[i] = v; setVals(nv);
    onChange && onChange(nv.join(""));
    if (v && i < 5) refs.current[i + 1]?.focus();
    if (nv.every(Boolean)) onDone && onDone(nv.join(""));
  };
  return (
    <div className="row gap-10" style={{ justifyContent: "space-between" }}>
      {vals.map((v, i) => (
        <input key={i} ref={el => refs.current[i] = el} value={v} maxLength={1}
          onChange={e => set(i, e.target.value)}
          onKeyDown={e => { if (e.key === "Backspace" && !v && i > 0) refs.current[i - 1]?.focus(); }}
          className="input mono" style={{ width: 52, height: 60, textAlign: "center", fontSize: 24, fontWeight: 600, fontFamily: "var(--font-display)", padding: 0 }} />
      ))}
    </div>
  );
}

function AuthVerify({ go }) {
  return (
    <AuthShell foot={<span>Não recebeu? <a style={{ color: "var(--accent)", cursor: "pointer", fontWeight: 600 }}>Reenviar código</a></span>}>
      <div style={{ width: 52, height: 52, borderRadius: 14, background: "var(--accent-wash)", color: "var(--accent)", display: "flex", alignItems: "center", justifyContent: "center" }}><I.mail size={24} /></div>
      <div className="col gap-6"><h1 style={{ fontSize: 28 }}>Verifique seu e‑mail</h1><p className="muted" style={{ margin: 0, fontSize: 14.5 }}>Enviamos um código de 6 dígitos para <b style={{ color: "var(--ink)" }}>voce@empresa.com</b>.</p></div>
      <CodeInput onDone={() => setTimeout(() => go("onboarding"), 350)} />
      <button className="btn btn-primary btn-lg btn-block" onClick={() => go("onboarding")}>Confirmar e continuar</button>
    </AuthShell>
  );
}

function Auth2FA({ go }) {
  const [code, setCode] = useS("");
  const [err, setErr] = useS("");
  const [busy, setBusy] = useS(false);

  async function verify(c) {
    const useCode = c || code;
    if (!pendingLogin) { go("auth/login"); return; }
    if (busy) return;
    setErr(""); setBusy(true);
    try {
      const r = await api.auth.login(pendingLogin.email, pendingLogin.pw, useCode);
      pendingLogin = null;
      go(r.user.role === "admin" ? "a/dashboard" : "s/dashboard");
    } catch (e) {
      setErr("Código inválido. Tente de novo.");
    } finally { setBusy(false); }
  }

  return (
    <AuthShell foot={<a onClick={() => { pendingLogin = null; go("auth/login"); }} style={{ color: "var(--accent)", cursor: "pointer", fontWeight: 600 }}>← Usar outra conta</a>}>
      <div style={{ width: 52, height: 52, borderRadius: 14, background: "var(--green-wash)", color: "var(--green)", display: "flex", alignItems: "center", justifyContent: "center" }}><I.shield size={24} /></div>
      <div className="col gap-6"><h1 style={{ fontSize: 28 }}>Autenticação em 2 fatores</h1><p className="muted" style={{ margin: 0, fontSize: 14.5 }}>Digite o código gerado pelo seu app autenticador.</p></div>
      {err && <div style={{ color: "var(--red)", background: "var(--red-wash)", fontSize: 13.5, padding: "10px 12px", borderRadius: 8 }}>{err}</div>}
      <CodeInput onChange={setCode} onDone={verify} />
      <button className="btn btn-primary btn-lg btn-block" onClick={() => verify()} disabled={busy}>{busy ? "Verificando…" : <>Verificar e entrar <I.arrowRight size={18} /></>}</button>
    </AuthShell>
  );
}

function AuthReset({ go }) {
  const token = new URLSearchParams(window.location.search).get("token") || "";
  const [pw, setPw] = useS("");
  const [pw2, setPw2] = useS("");
  const [err, setErr] = useS("");
  const [ok, setOk] = useS(false);
  const [busy, setBusy] = useS(false);

  async function submit() {
    setErr("");
    if (pw.length < 8) { setErr("A senha precisa de ao menos 8 caracteres."); return; }
    if (pw !== pw2) { setErr("As senhas não conferem."); return; }
    setBusy(true);
    try { await api.auth.reset(token, pw); setOk(true); }
    catch (e) { setErr(e.message || "Link inválido ou expirado."); }
    finally { setBusy(false); }
  }

  return (
    <AuthShell foot={<a onClick={() => go("auth/login")} style={{ color: "var(--accent)", cursor: "pointer", fontWeight: 600 }}>← Voltar para o login</a>}>
      <div style={{ width: 52, height: 52, borderRadius: 14, background: "var(--accent-wash)", color: "var(--accent)", display: "flex", alignItems: "center", justifyContent: "center" }}><I.lock size={24} /></div>
      {ok ? (
        <>
          <div className="col gap-6"><h1 style={{ fontSize: 28 }}>Senha redefinida</h1><p className="muted" style={{ margin: 0, fontSize: 14.5 }}>Tudo certo. Você já pode entrar com a nova senha.</p></div>
          <button className="btn btn-primary btn-lg btn-block" onClick={() => go("auth/login")}>Ir para o login</button>
        </>
      ) : (
        <>
          <div className="col gap-6"><h1 style={{ fontSize: 28 }}>Definir nova senha</h1><p className="muted" style={{ margin: 0, fontSize: 14.5 }}>Escolha uma senha forte (mín. 8 caracteres).</p></div>
          {err && <div style={{ color: "var(--red)", background: "var(--red-wash)", fontSize: 13.5, padding: "10px 12px", borderRadius: 8 }}>{err}</div>}
          <div className="field"><label className="label">Nova senha</label><Pw value={pw} onChange={setPw} /></div>
          <div className="field"><label className="label">Confirmar senha</label><Pw value={pw2} onChange={setPw2} /></div>
          <button className="btn btn-primary btn-lg btn-block" onClick={submit} disabled={busy}>{busy ? "Salvando…" : "Redefinir senha"}</button>
        </>
      )}
    </AuthShell>
  );
}

Object.assign(window, { AuthLogin, AuthSignup, AuthForgot, AuthVerify, Auth2FA, AuthReset });
