// Auth gate — login / signup form. Mounts before main app when no session.

const authInputStyle = {
  padding: "11px 13px", fontSize: 15, borderRadius: 10,
  border: "1px solid rgba(13,20,48,0.16)",
  background: "var(--bx-bg, #f6f7fb)",
  color: "var(--bx-ink-1, #0d1430)",
  fontFamily: "inherit", outline: "none",
};

function FinanzasAuthGate({ onAuthed }) {
  const [mode, setMode]   = React.useState("login"); // login | signup | reset
  const [email, setEmail] = React.useState("");
  const [pwd, setPwd]     = React.useState("");
  const [busy, setBusy]   = React.useState(false);
  const [err, setErr]     = React.useState(null);
  const [info, setInfo]   = React.useState(null);

  async function submit(e) {
    e.preventDefault();
    setErr(null); setInfo(null); setBusy(true);
    try {
      const s = window.finanzasStorage;
      if (mode === "signup") {
        const { data, error } = await s.signUp(email.trim(), pwd);
        if (error) throw error;
        if (data.session) {
          // Email confirmation disabled → instant session
          await s.bootstrap();
          onAuthed();
        } else {
          setInfo("Cuenta creada. Revisa tu correo para confirmar e inicia sesión.");
          setMode("login");
        }
      } else if (mode === "reset") {
        const { error } = await s.resetPassword(email.trim(), location.origin);
        if (error) throw error;
        setInfo("Si la dirección existe, te enviamos un enlace para restablecer la contraseña.");
      } else {
        const { error } = await s.signIn(email.trim(), pwd);
        if (error) throw error;
        await s.bootstrap();
        onAuthed();
      }
    } catch (e) {
      setErr(e.message || "Error desconocido");
    } finally {
      setBusy(false);
    }
  }

  const isSignup = mode === "signup";
  const isReset = mode === "reset";

  return (
    <div style={{
      minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center",
      background: "var(--bx-bg)", padding: 24,
    }}>
      <form onSubmit={submit} style={{
        width: "100%", maxWidth: 380,
        background: "var(--bx-surface, #fff)", borderRadius: 16, padding: 28,
        boxShadow: "0 12px 40px rgba(13,20,48,0.18)",
        display: "flex", flexDirection: "column", gap: 14,
      }}>
        <div style={{ textAlign: "center", marginBottom: 8 }}>
          <div style={{ fontFamily: "Bebas Neue, sans-serif", fontSize: 36, letterSpacing: 2, color: "var(--bx-ink-1, #0d1430)" }}>
            FINANZAS
          </div>
          <div style={{ fontSize: 13, color: "var(--bx-ink-2, #5a6486)", marginTop: 4 }}>
            {isSignup ? "Crear cuenta" : isReset ? "Recuperar contraseña" : "Iniciar sesión"}
          </div>
        </div>

        <label style={{ display: "flex", flexDirection: "column", gap: 6, fontSize: 13, color: "var(--bx-ink-2, #5a6486)" }}>
          Correo
          <input
            type="email" required autoComplete="email"
            value={email} onChange={e => setEmail(e.target.value)}
            style={authInputStyle}
            placeholder="tu@correo.com"
          />
        </label>

        {!isReset && (
          <label style={{ display: "flex", flexDirection: "column", gap: 6, fontSize: 13, color: "var(--bx-ink-2, #5a6486)" }}>
            Contraseña
            <input
              type="password" required minLength={6}
              autoComplete={isSignup ? "new-password" : "current-password"}
              value={pwd} onChange={e => setPwd(e.target.value)}
              style={authInputStyle}
              placeholder={isSignup ? "Mínimo 6 caracteres" : "••••••••"}
            />
          </label>
        )}

        {err && (
          <div style={{ background: "#fde8e8", color: "#9b1c1c", padding: "10px 12px", borderRadius: 8, fontSize: 13 }}>
            {err}
          </div>
        )}
        {info && (
          <div style={{ background: "#e6f4ea", color: "#1a5e3a", padding: "10px 12px", borderRadius: 8, fontSize: 13 }}>
            {info}
          </div>
        )}

        <button type="submit" disabled={busy} style={{
          background: "var(--bx-ink-1, #0d1430)", color: "#fff",
          border: "none", borderRadius: 10, padding: "12px 16px",
          fontSize: 15, fontWeight: 600, cursor: busy ? "wait" : "pointer",
          opacity: busy ? 0.7 : 1, marginTop: 4,
        }}>
          {busy ? "..." : (isSignup ? "Crear cuenta" : isReset ? "Enviar enlace" : "Entrar")}
        </button>

        <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
          <button
            type="button"
            onClick={() => { setMode(isSignup || isReset ? "login" : "signup"); setErr(null); setInfo(null); }}
            style={{
              background: "transparent", border: "none", padding: "8px",
              color: "var(--bx-ink-2, #5a6486)", fontSize: 13, cursor: "pointer",
            }}>
            {isSignup ? "¿Ya tienes cuenta? Entra"
              : isReset ? "Volver"
              : "¿Sin cuenta? Regístrate"}
          </button>
          {!isSignup && !isReset && (
            <button
              type="button"
              onClick={() => { setMode("reset"); setErr(null); setInfo(null); }}
              style={{
                background: "transparent", border: "none", padding: "8px",
                color: "var(--bx-ink-2, #5a6486)", fontSize: 13, cursor: "pointer",
              }}>
              ¿Olvidaste contraseña?
            </button>
          )}
        </div>
      </form>
    </div>
  );
}

window.FinanzasAuthGate = FinanzasAuthGate;
