/* ============================================================
   auth.jsx — login + recover password
   ============================================================ */

function Login(){
  const { setUser, setRoute, pushToast } = useApp();
  const [mode, setMode] = React.useState("login"); // login | recover | recover-sent
  const [email, setEmail] = React.useState("");
  const [pwd, setPwd] = React.useState("");
  const [showPwd, setShowPwd] = React.useState(false);
  const [remember, setRemember] = React.useState(true);
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState("");

  const submit = async (e) => {
    e.preventDefault();
    setErr("");
    if (!email.includes("@")) { setErr("E-mail inválido."); return; }
    if (!pwd || pwd.length < 6) { setErr("Senha deve ter ao menos 6 caracteres."); return; }
    setLoading(true);
    try {
      const r = await window.api.login(email, pwd);
      setUser({ name: r.user.name, email: r.user.email, role: r.user.role });
      pushToast("Bem-vindo de volta.");
      setRoute("/dashboard");
    } catch (ex) {
      if (ex.code === "invalid_credentials") setErr("E-mail ou senha incorretos.");
      else if (ex.code === "rate_limited")   setErr("Muitas tentativas. Aguarde um pouco.");
      else                                   setErr(ex.message || "Falha ao entrar.");
    } finally {
      setLoading(false);
    }
  };

  const recover = async (e) => {
    e.preventDefault();
    setLoading(true);
    try {
      await window.api.recover(email);
      setMode("recover-sent");
    } catch (ex) {
      setErr(ex.message || "Falha ao solicitar recuperação.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="auth-wrap">
      <div className="auth-form-side">
        <div className="auth-form in">
          <div style={{ marginBottom: 12 }}>
            <BrandLogo theme="dark" height={22} />
          </div>

          {mode === "login" && <>
            <h1>Entre no seu <em className="serif-em">painel.</em></h1>
            <p className="lead">
              Gerencie cobranças, checkouts e order bumps com a presença que sua marca merece.
            </p>
            <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 8 }}>
              <div className="field">
                <label>E-mail</label>
                <input className="input" type="email" autoComplete="email"
                  value={email} onChange={(e) => setEmail(e.target.value)} placeholder="seu@email.com" />
              </div>
              <div className="field">
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <label>Senha</label>
                  <a href="#" onClick={(e) => { e.preventDefault(); setMode("recover"); }}
                    style={{ fontSize: 12, color: "var(--mute)", textTransform: "uppercase", letterSpacing: ".12em" }}>
                    esqueci
                  </a>
                </div>
                <div style={{ position: "relative" }}>
                  <input className="input" type={showPwd ? "text" : "password"} autoComplete="current-password"
                    value={pwd} onChange={(e) => setPwd(e.target.value)} placeholder="••••••••" />
                  <button type="button" className="btn-icon"
                    onClick={() => setShowPwd((s) => !s)}
                    style={{ position: "absolute", right: 6, top: 5 }} aria-label="Mostrar senha">
                    <Icon name={showPwd ? "eye-off" : "eye"} />
                  </button>
                </div>
              </div>

              <label className="checkbox" style={{ marginTop: 2 }}>
                <input type="checkbox" checked={remember} onChange={(e) => setRemember(e.target.checked)} />
                <span className="box"><Icon name="check" size={12}/></span>
                Manter sessão ativa
              </label>

              {err && <div className="err" style={{ color: "var(--bad)", fontSize: 13 }}>{err}</div>}

              <button className="btn btn-lg" type="submit" disabled={loading}>
                {loading ? "Entrando…" : "Acessar painel"} <span className="arrow">→</span>
              </button>
            </form>

            <div style={{
              display: "flex", alignItems: "center", gap: 10, color: "var(--graphite)",
              fontSize: 12.5, marginTop: 18,
            }}>
              <Icon name="shield" size={14}/> Conexão criptografada · token do Mercado Pago no servidor
            </div>
          </>}

          {mode === "recover" && <>
            <h1>Recuperar <em className="serif-em">acesso.</em></h1>
            <p className="lead">
              Informe seu e-mail. Em segundos enviamos um link seguro para você redefinir a senha.
            </p>
            <form onSubmit={recover} style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 8 }}>
              <div className="field">
                <label>E-mail</label>
                <input className="input" type="email" value={email}
                  onChange={(e) => setEmail(e.target.value)} placeholder="seu@email.com" />
              </div>
              <button className="btn btn-lg" type="submit" disabled={loading}>
                {loading ? "Enviando…" : "Enviar link de recuperação"}
              </button>
              <button type="button" className="btn btn-light" onClick={() => setMode("login")}>
                Voltar para o login
              </button>
            </form>
          </>}

          {mode === "recover-sent" && <>
            <h1>Link <em className="serif-em">enviado.</em></h1>
            <p className="lead">
              Caso o e-mail <b>{email}</b> esteja cadastrado, em poucos segundos chegará uma mensagem com instruções para redefinir sua senha.
            </p>
            <button className="btn" onClick={() => setMode("login")}>
              Voltar ao login <span className="arrow">→</span>
            </button>
          </>}
        </div>
      </div>

      <div className="auth-art" aria-hidden="true">
        <div className="stamp">
          <BrandLogo theme="light" height={20} />
        </div>

        <div style={{
          position: "relative", zIndex: 2,
          display: "grid", placeItems: "center",
          width: "100%",
        }}>
          <img src="assets/blackx-logo-light.png" alt=""
            style={{
              maxWidth: "min(64%, 420px)", width: "100%", height: "auto",
              display: "block",
              filter: "drop-shadow(0 30px 60px rgba(0,0,0,.5))",
            }} />
        </div>

        <div className="sig">
          <span>Studio — Rio de Janeiro</span>
          <span>v.2026.05</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Login });
