// Auth: AuthGate + LoginPage + SignupPage + ResetPasswordPage + UpdatePasswordPage
// Carregado antes do app.jsx no Financeiro.html

// ---------- AuthGate ----------
// Envolve <App/>. Decide entre splash, telas de auth e o app autenticado.
function AuthGate({ children }) {
  const [session, setSession] = React.useState(undefined); // undefined = loading
  // Lê ?view=signup|reset da URL (vem da landing) pra abrir a tela certa direto
  const initialView = (() => {
    const v = new URLSearchParams(window.location.search).get("view");
    return ["signup", "reset", "login"].includes(v) ? v : "login";
  })();
  const [view, setView] = React.useState(initialView);
  const [recoveryEvent, setRecoveryEvent] = React.useState(false);

  React.useEffect(() => {
    let mounted = true;
    window.db.auth.getSession().then(s => { if (mounted) setSession(s); });
    const { data: sub } = window.db.auth.onAuthStateChange((event, s) => {
      if (!mounted) return;
      if (event === "PASSWORD_RECOVERY") {
        setRecoveryEvent(true);
        setView("newpw");
        return;
      }
      setSession(s);
    });
    return () => { mounted = false; sub?.subscription?.unsubscribe(); };
  }, []);

  // Loading inicial
  if (session === undefined) return <SplashLoading />;

  // Fluxo de redefinir senha (clicou no link do email de reset)
  if (recoveryEvent && session) return <UpdatePasswordPage onDone={() => setRecoveryEvent(false)} />;

  // URL ?view=login|signup força mostrar a tela de auth, mesmo com sessão ativa
  const urlView = new URLSearchParams(window.location.search).get("view");
  const forceAuthView = ["login", "signup", "reset"].includes(urlView);

  // Não autenticado, OU veio da landing pedindo explicitamente Login/Signup
  if (!session || forceAuthView) {
    if (view === "signup") return <SignupPage onSwitch={setView} session={session} />;
    if (view === "reset")  return <ResetPasswordPage onSwitch={setView} />;
    return <LoginPage onSwitch={setView} session={session} />;
  }

  // Autenticado
  return children;
}

function SplashLoading() {
  return (
    <div style={{ height: "100vh", display: "flex", alignItems: "center", justifyContent: "center", flexDirection: "column", gap: 12, fontFamily: "Manrope, system-ui, sans-serif", color: "var(--fg-2)" }}>
      <div className="eyebrow">Carregando…</div>
    </div>
  );
}

// ---------- Layout compartilhado das telas de auth (2 colunas — form + calculadora) ----------
function AuthLayout({ title, subtitle, children, footer }) {
  return (
    <div className="auth-shell">
      {/* LEFT — form (fixo no viewport, scrolla internamente se precisar) */}
      <div className="auth-left">
        <div style={{ width: "100%", maxWidth: 400 }}>
          {/* Brand */}
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 18 }}>
            <div style={{ width: 36, height: 36, borderRadius: 10, background: "var(--green)", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "var(--glow-green)" }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                <rect x="3" y="3" width="8" height="8" rx="2" fill="var(--green-soft)" />
                <rect x="13" y="3" width="8" height="8" rx="2" fill="var(--green-soft)" opacity="0.55" />
                <rect x="3" y="13" width="8" height="8" rx="2" fill="var(--green-soft)" opacity="0.35" />
                <rect x="13" y="13" width="8" height="8" rx="2" fill="var(--green-soft)" opacity="0.75" />
              </svg>
            </div>
            <div>
              <div style={{ fontFamily: "'Fraunces', Georgia, serif", fontSize: 18, fontWeight: 400, color: "var(--fg-1)", letterSpacing: "-0.02em", lineHeight: 1 }}>Planilha IA</div>
              <div className="eyebrow" style={{ marginTop: 3, fontSize: 9.5 }}>A planilha com cérebro</div>
            </div>
          </div>

          {/* Card */}
          <div style={{ background: "var(--surface-1)", borderRadius: 24, padding: "26px 28px", border: "1px solid var(--border)", boxShadow: "var(--shadow-md)" }}>
            <h1 className="display" style={{ margin: 0, fontSize: 24, color: "var(--fg-1)" }}>{title}</h1>
            {subtitle && <p style={{ margin: "6px 0 18px", fontSize: 13, color: "var(--fg-2)", lineHeight: 1.45 }}>{subtitle}</p>}
            {!subtitle && <div style={{ height: 18 }} />}
            {children}
          </div>

          {footer && (
            <div style={{ textAlign: "center", marginTop: 14, fontSize: 12.5, color: "var(--fg-2)" }}>
              {footer}
            </div>
          )}

          <div style={{ textAlign: "center", marginTop: 14 }}>
            <a href="index.html" style={{ fontSize: 11.5, color: "var(--fg-3)", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 6 }}>
              ← Voltar para a página inicial
            </a>
          </div>
        </div>
      </div>

      {/* RIGHT — calculadora glass centralizada */}
      <aside className="auth-right">
        <div className="auth-right-bg" />
        <div className="auth-right-blend" />
        <div className="auth-right-content">
          <Calculator />
          <div className="eyebrow" style={{ color: "rgba(155,194,173,0.6)", fontSize: 10, textAlign: "center", marginTop: 4 }}>
            // teste rápido · use com mouse ou teclado
          </div>
        </div>
      </aside>

      <style>{`
        .auth-shell {
          height: 100vh;
          display: grid;
          grid-template-columns: 1fr 1fr;
          background: var(--bg);
          overflow: hidden;
        }
        .auth-left {
          height: 100vh;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 32px 40px;
          overflow-y: auto;
          /* esconde scrollbar mantendo scroll funcional */
          scrollbar-width: none;
          -ms-overflow-style: none;
        }
        .auth-left::-webkit-scrollbar { display: none; }
        .auth-right {
          position: sticky;
          top: 0;
          height: 100vh;
          overflow: hidden;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 32px 40px;
          /* Gradient horizontal — verde mais claro/iluminado na borda esquerda, escurece pra direita */
          background:
            radial-gradient(ellipse 240px 100% at 0% 50%, rgba(33,240,140,0.20), transparent 70%),
            linear-gradient(90deg, #0e4a2c 0%, #0a3a23 22%, #06120c 90%);
        }
        .auth-right-bg {
          position: absolute; inset: 0;
          background:
            radial-gradient(circle at 70% 25%, rgba(33,240,140,0.10), transparent 50%),
            radial-gradient(circle at 80% 80%, rgba(212,255,91,0.06), transparent 50%);
          pointer-events: none;
          z-index: 0;
        }
        /* Borda esquerda — linha hairline verde sutil que dá "edge lit" sem misturar cores */
        .auth-right-blend {
          position: absolute;
          top: 0; bottom: 0; left: 0;
          width: 1px;
          background: linear-gradient(180deg,
            transparent 0%,
            rgba(33,240,140,0.35) 40%,
            rgba(33,240,140,0.5) 50%,
            rgba(33,240,140,0.35) 60%,
            transparent 100%
          );
          box-shadow: 0 0 24px rgba(33,240,140,0.15);
          pointer-events: none;
          z-index: 1;
        }
        .auth-right-content {
          position: relative;
          z-index: 3;
          display: flex;
          flex-direction: column;
          align-items: stretch;
          gap: 14px;
          width: 100%;
          max-width: 360px;
        }
        @media (max-width: 1024px) {
          .auth-shell { grid-template-columns: 1fr; }
          .auth-right { display: none; }
          .auth-left { padding: 24px; }
        }
      `}</style>
    </div>
  );
}

// ---------- Calculadora glass-morphism ----------
function Calculator() {
  const [display, setDisplay] = React.useState("0");
  const [stored, setStored] = React.useState(null);
  const [op, setOp] = React.useState(null);
  const [waiting, setWaiting] = React.useState(false);

  const fmt = (s) => {
    // Limita display a 12 chars
    if (s.length > 12) {
      const n = parseFloat(s);
      return n.toExponential(5);
    }
    return s;
  };

  const inputDigit = (d) => {
    if (waiting) {
      setDisplay(String(d));
      setWaiting(false);
    } else {
      setDisplay(display === "0" ? String(d) : display + d);
    }
  };

  const inputDecimal = () => {
    if (waiting) {
      setDisplay("0.");
      setWaiting(false);
      return;
    }
    if (!display.includes(".")) setDisplay(display + ".");
  };

  const clear = () => {
    setDisplay("0");
    setStored(null);
    setOp(null);
    setWaiting(false);
  };

  const compute = (a, b, operator) => {
    switch (operator) {
      case "+": return a + b;
      case "−": return a - b;
      case "×": return a * b;
      case "÷": return b !== 0 ? a / b : 0;
      default: return b;
    }
  };

  const performOp = (nextOp) => {
    const v = parseFloat(display);
    if (stored == null) {
      setStored(v);
    } else if (op && !waiting) {
      const result = compute(stored, v, op);
      const r = Number.isInteger(result) ? String(result) : String(parseFloat(result.toFixed(8)));
      setDisplay(r);
      setStored(result);
    }
    setWaiting(true);
    setOp(nextOp);
  };

  const equals = () => {
    if (op != null && stored != null && !waiting) {
      const v = parseFloat(display);
      const result = compute(stored, v, op);
      const r = Number.isInteger(result) ? String(result) : String(parseFloat(result.toFixed(8)));
      setDisplay(r);
      setStored(null);
      setOp(null);
      setWaiting(true);
    }
  };

  const negate = () => setDisplay(display.startsWith("-") ? display.slice(1) : "-" + display);
  const percent = () => setDisplay(String(parseFloat(display) / 100));

  // Suporte a teclado
  React.useEffect(() => {
    const onKey = (e) => {
      if (/^[0-9]$/.test(e.key)) inputDigit(parseInt(e.key));
      else if (e.key === ".") inputDecimal();
      else if (e.key === "+") performOp("+");
      else if (e.key === "-") performOp("−");
      else if (e.key === "*") performOp("×");
      else if (e.key === "/") { e.preventDefault(); performOp("÷"); }
      else if (e.key === "Enter" || e.key === "=") { e.preventDefault(); equals(); }
      else if (e.key === "Escape") clear();
      else if (e.key === "Backspace") setDisplay(display.length > 1 ? display.slice(0, -1) : "0");
    };
    // Só ouve teclado quando mouse está sobre a calculadora
    const calc = document.querySelector(".calc-shell");
    if (!calc) return;
    let active = false;
    const enter = () => { active = true; window.addEventListener("keydown", onKey); };
    const leave = () => { active = false; window.removeEventListener("keydown", onKey); };
    calc.addEventListener("mouseenter", enter);
    calc.addEventListener("mouseleave", leave);
    return () => {
      calc.removeEventListener("mouseenter", enter);
      calc.removeEventListener("mouseleave", leave);
      if (active) window.removeEventListener("keydown", onKey);
    };
  });

  const Btn = ({ children, onClick, variant = "default", spanCol }) => (
    <button
      onClick={onClick}
      className={`calc-btn calc-btn-${variant}`}
      style={spanCol ? { gridColumn: `span ${spanCol}` } : undefined}
    >
      {children}
    </button>
  );

  return (
    <div className="calc-shell">
      <div className="calc-display">
        <div className="calc-display-op">
          {op && stored != null ? `${stored} ${op}` : " "}
        </div>
        <div className="calc-display-value">{fmt(display)}</div>
      </div>
      <div className="calc-grid">
        <Btn variant="util" onClick={clear}>AC</Btn>
        <Btn variant="util" onClick={negate}>±</Btn>
        <Btn variant="util" onClick={percent}>%</Btn>
        <Btn variant="op" onClick={() => performOp("÷")}>÷</Btn>

        <Btn onClick={() => inputDigit(7)}>7</Btn>
        <Btn onClick={() => inputDigit(8)}>8</Btn>
        <Btn onClick={() => inputDigit(9)}>9</Btn>
        <Btn variant="op" onClick={() => performOp("×")}>×</Btn>

        <Btn onClick={() => inputDigit(4)}>4</Btn>
        <Btn onClick={() => inputDigit(5)}>5</Btn>
        <Btn onClick={() => inputDigit(6)}>6</Btn>
        <Btn variant="op" onClick={() => performOp("−")}>−</Btn>

        <Btn onClick={() => inputDigit(1)}>1</Btn>
        <Btn onClick={() => inputDigit(2)}>2</Btn>
        <Btn onClick={() => inputDigit(3)}>3</Btn>
        <Btn variant="op" onClick={() => performOp("+")}>+</Btn>

        <Btn onClick={() => inputDigit(0)} spanCol={2}>0</Btn>
        <Btn onClick={inputDecimal}>,</Btn>
        <Btn variant="equals" onClick={equals}>=</Btn>
      </div>

      <style>{`
        .calc-shell {
          width: 100%;
          padding: 22px;
          border-radius: 28px;
          background: rgba(255,255,255,0.04);
          backdrop-filter: blur(40px) saturate(180%);
          -webkit-backdrop-filter: blur(40px) saturate(180%);
          border: 1px solid rgba(255,255,255,0.10);
          box-shadow:
            0 1px 0 rgba(255,255,255,0.06) inset,
            0 24px 48px -12px rgba(0,0,0,0.5),
            0 0 0 1px rgba(33,240,140,0.05);
          transition: transform .5s cubic-bezier(.2,.8,.2,1), box-shadow .5s cubic-bezier(.2,.8,.2,1), border-color .4s ease, background .4s ease;
        }
        .calc-shell:hover {
          transform: translateY(-6px) scale(1.015);
          background: rgba(255,255,255,0.055);
          border-color: rgba(33,240,140,0.22);
          box-shadow:
            0 1px 0 rgba(255,255,255,0.10) inset,
            0 40px 80px -20px rgba(0,0,0,0.6),
            0 0 0 1px rgba(33,240,140,0.12),
            0 0 60px rgba(33,240,140,0.18);
        }
        .calc-display {
          padding: 18px 4px 22px;
          text-align: right;
          margin-bottom: 14px;
          border-bottom: 1px solid rgba(255,255,255,0.08);
        }
        .calc-display-op {
          font-family: 'JetBrains Mono', monospace;
          font-size: 11px;
          letter-spacing: 0.1em;
          color: rgba(155,194,173,0.6);
          height: 14px;
        }
        .calc-display-value {
          font-family: 'Fraunces', Georgia, serif;
          font-weight: 400;
          font-size: 44px;
          letter-spacing: -0.02em;
          line-height: 1;
          color: #eafff3;
          margin-top: 6px;
          word-break: break-all;
        }
        .calc-grid {
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          gap: 8px;
        }
        .calc-btn {
          height: 56px;
          border: 1px solid rgba(255,255,255,0.06);
          border-radius: 18px;
          background: rgba(255,255,255,0.04);
          color: #eafff3;
          font-family: 'Manrope', sans-serif;
          font-size: 18px;
          font-weight: 500;
          cursor: pointer;
          transition: transform .15s cubic-bezier(.2,.8,.2,1), background .25s ease, box-shadow .25s ease, border-color .25s ease;
          backdrop-filter: blur(8px);
          -webkit-backdrop-filter: blur(8px);
        }
        .calc-btn:hover {
          background: rgba(255,255,255,0.08);
          border-color: rgba(255,255,255,0.14);
          transform: translateY(-1px);
          box-shadow: 0 6px 16px -4px rgba(0,0,0,0.3);
        }
        .calc-btn:active { transform: translateY(0) scale(0.96); transition-duration: .08s; }
        .calc-btn-util {
          background: rgba(33,240,140,0.06);
          color: var(--green-2);
          border-color: rgba(33,240,140,0.12);
          font-size: 15px;
        }
        .calc-btn-util:hover {
          background: rgba(33,240,140,0.12);
          border-color: rgba(33,240,140,0.25);
          color: var(--green);
        }
        .calc-btn-op {
          background: rgba(33,240,140,0.10);
          color: var(--green);
          border-color: rgba(33,240,140,0.18);
          font-size: 22px;
          font-weight: 600;
        }
        .calc-btn-op:hover {
          background: rgba(33,240,140,0.18);
          border-color: rgba(33,240,140,0.35);
          box-shadow: 0 6px 20px -4px rgba(33,240,140,0.4);
        }
        .calc-btn-equals {
          background: var(--green);
          color: #06120c;
          border-color: transparent;
          font-size: 22px;
          font-weight: 700;
          box-shadow: 0 4px 14px -2px rgba(33,240,140,0.4);
        }
        .calc-btn-equals:hover {
          background: var(--green-soft);
          box-shadow: 0 8px 24px -4px rgba(33,240,140,0.5);
          transform: translateY(-2px);
        }
      `}</style>
    </div>
  );
}

// ---------- Inputs ----------
function AuthInput({ label, type = "text", value, onChange, placeholder, autoFocus, autoComplete, error }) {
  const [show, setShow] = React.useState(false);
  const isPassword = type === "password";
  const effectiveType = isPassword && show ? "text" : type;
  return (
    <label style={{ display: "block", marginBottom: 11 }}>
      <div className="eyebrow" style={{ marginBottom: 5 }}>{label}</div>
      <div style={{ position: "relative" }}>
        <input
          type={effectiveType} value={value} onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder} autoFocus={autoFocus} autoComplete={autoComplete}
          className="input"
          style={{
            width: "100%", fontSize: 14,
            paddingRight: isPassword ? 44 : undefined,
            border: `1px solid ${error ? "var(--danger)" : "var(--border)"}`,
            boxSizing: "border-box",
          }}
        />
        {isPassword && (
          <button
            type="button"
            onClick={() => setShow(s => !s)}
            tabIndex={-1}
            aria-label={show ? "Ocultar senha" : "Mostrar senha"}
            title={show ? "Ocultar senha" : "Mostrar senha"}
            style={{
              position: "absolute", right: 6, top: "50%", transform: "translateY(-50%)",
              width: 32, height: 32, borderRadius: 999, border: "none", background: "transparent",
              color: show ? "var(--green)" : "var(--fg-3)",
              cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center",
              transition: "color .2s ease, background .2s ease",
            }}
            onMouseEnter={e => e.currentTarget.style.background = "var(--surface-2)"}
            onMouseLeave={e => e.currentTarget.style.background = "transparent"}
          >
            {show ? (
              // Olho aberto (senha visível — você ESTÁ vendo)
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                <circle cx="12" cy="12" r="3"/>
              </svg>
            ) : (
              // Olho riscado (senha oculta — você NÃO está vendo)
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/>
                <line x1="1" y1="1" x2="23" y2="23"/>
              </svg>
            )}
          </button>
        )}
      </div>
    </label>
  );
}

function AuthPrimaryButton({ children, onClick, disabled, type = "button" }) {
  return (
    <button type={type} onClick={onClick} disabled={disabled} className="btn-primary" style={{
      width: "100%", padding: "12px 22px", fontSize: 14, justifyContent: "center",
    }}>
      {children}
    </button>
  );
}

function GoogleButton({ onClick, disabled }) {
  return (
    <button onClick={onClick} disabled={disabled} className="btn-ghost" style={{
      width: "100%", padding: "11px 18px", fontSize: 14, justifyContent: "center", gap: 10,
    }}>
      <svg width="18" height="18" viewBox="0 0 24 24">
        <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
        <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
        <path fill="#FBBC05" d="M5.84 14.1A6.45 6.45 0 0 1 5.5 12c0-.73.13-1.43.34-2.1V7.07H2.18A11 11 0 0 0 1 12c0 1.78.43 3.46 1.18 4.93l3.66-2.83z"/>
        <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.55 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.83C6.71 7.31 9.14 5.38 12 5.38z"/>
      </svg>
      Continuar com Google
    </button>
  );
}

function Separator() {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, margin: "14px 0", color: "var(--fg-3)", fontSize: 11 }}>
      <div style={{ flex: 1, height: 1, background: "var(--border)" }} />
      <span className="eyebrow">ou</span>
      <div style={{ flex: 1, height: 1, background: "var(--border)" }} />
    </div>
  );
}

function AuthError({ msg }) {
  if (!msg) return null;
  return (
    <div style={{ padding: "10px 14px", background: "var(--danger-bg)", border: "1px solid color-mix(in oklab, var(--danger) 30%, transparent)", borderRadius: 12, fontSize: 13, color: "var(--danger)", marginBottom: 14 }}>
      {msg}
    </div>
  );
}

// Banner sutil mostrado em cima do form quando usuário ABRE login/signup já estando logado
// (ex: clicou em "Entrar" na landing). Dá opção de continuar pro app sem digitar credencial.
function AlreadyLoggedBanner({ session }) {
  if (!session) return null;
  const email = session.user?.email || "sua conta";
  const goToApp = () => {
    // Remove o ?view= da URL pra AuthGate enxergar como "logado normal" e renderizar o app
    window.location.href = window.location.pathname;
  };
  const signOutNow = async () => {
    await window.db.auth.signOut();
    // recarrega sem o ?view pra começar fresh
    window.location.href = window.location.pathname;
  };
  return (
    <div style={{ padding: "10px 12px", background: "var(--success-bg)", border: "1px solid color-mix(in oklab, var(--success) 28%, transparent)", borderRadius: 10, marginBottom: 11, fontSize: 12, color: "var(--fg-1)", lineHeight: 1.4 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
        <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--success)", flexShrink: 0 }} />
        <span>Logado como <strong>{email}</strong></span>
      </div>
      <div style={{ display: "flex", gap: 6 }}>
        <button onClick={goToApp} className="btn-primary" style={{ flex: 1, padding: "7px 12px", fontSize: 12, justifyContent: "center" }}>
          Entrar no app →
        </button>
        <button onClick={signOutNow} className="btn-ghost" style={{ fontSize: 11.5, padding: "7px 12px" }}>
          Trocar
        </button>
      </div>
    </div>
  );
}

function AuthSuccess({ msg }) {
  if (!msg) return null;
  return (
    <div style={{ padding: "10px 14px", background: "var(--success-bg)", border: "1px solid color-mix(in oklab, var(--success) 30%, transparent)", borderRadius: 12, fontSize: 13, color: "var(--success)", marginBottom: 14 }}>
      {msg}
    </div>
  );
}

// ---------- Translação de mensagens de erro do Supabase pra PT ----------
function translateAuthError(err) {
  const msg = (err?.message || "").toLowerCase();
  if (msg.includes("invalid login credentials")) return "Email ou senha incorretos.";
  if (msg.includes("email not confirmed")) return "Confirme seu email antes de entrar (verifique a caixa de entrada).";
  if (msg.includes("user already registered")) return "Esse email já tem uma conta. Tente entrar ou recuperar a senha.";
  if (msg.includes("password should be at least")) return "A senha precisa ter pelo menos 6 caracteres.";
  if (msg.includes("rate limit") || msg.includes("too many")) return "Muitas tentativas. Aguarde alguns minutos e tente de novo.";
  if (msg.includes("network")) return "Sem conexão com o servidor. Verifique sua internet.";
  return err?.message || "Algo deu errado. Tente de novo.";
}

// ---------- LoginPage ----------
function LoginPage({ onSwitch, session }) {
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState(null);

  const submit = async (e) => {
    e?.preventDefault();
    setErr(null); setLoading(true);
    const { error } = await window.db.auth.signInWithPassword(email, password);
    if (error) { setErr(translateAuthError(error)); setLoading(false); }
    // sucesso: AuthGate detecta sessão e re-renderiza
  };

  const google = async () => {
    setErr(null); setLoading(true);
    const { error } = await window.db.auth.signInWithGoogle();
    if (error) { setErr(translateAuthError(error)); setLoading(false); }
  };

  return (
    <AuthLayout
      title={<>Bem-<em style={{ fontStyle: "italic", fontWeight: 300, color: "var(--green)" }}>vindo</em> de volta</>}
      subtitle="Entre na sua conta pra continuar."
      footer={<>Ainda não tem conta? <a onClick={() => onSwitch("signup")} style={{ color: "var(--green)", fontWeight: 600, cursor: "pointer", textDecoration: "none" }}>Criar conta →</a></>}
    >
      <AlreadyLoggedBanner session={session} />
      <AuthError msg={err} />
      <GoogleButton onClick={google} disabled={loading} />
      <Separator />
      <form onSubmit={submit}>
        <AuthInput label="Email" type="email" value={email} onChange={setEmail} placeholder="voce@exemplo.com" autoFocus autoComplete="email" />
        <AuthInput label="Senha" type="password" value={password} onChange={setPassword} placeholder="••••••••" autoComplete="current-password" />
        <div style={{ textAlign: "right", marginBottom: 18, marginTop: -6 }}>
          <a onClick={() => onSwitch("reset")} style={{ fontSize: 12.5, color: "var(--fg-2)", cursor: "pointer", textDecoration: "underline" }}>Esqueci minha senha</a>
        </div>
        <AuthPrimaryButton type="submit" disabled={loading || !email || !password}>
          {loading ? "Entrando…" : "Entrar"}
        </AuthPrimaryButton>
      </form>
    </AuthLayout>
  );
}

// ---------- SignupPage ----------
function SignupPage({ onSwitch, session }) {
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [okMsg, setOkMsg] = React.useState(null);

  const submit = async (e) => {
    e?.preventDefault();
    setErr(null); setOkMsg(null); setLoading(true);
    if (password.length < 6) { setErr("A senha precisa ter pelo menos 6 caracteres."); setLoading(false); return; }
    const { data, error } = await window.db.auth.signUp(email, password, { full_name: name });
    if (error) { setErr(translateAuthError(error)); setLoading(false); return; }
    if (data?.session) {
      // Confirmação de email desabilitada — entra direto
      return;
    }
    setOkMsg("Conta criada! Verifique seu email pra confirmar e depois entre.");
    setLoading(false);
  };

  const google = async () => {
    setErr(null); setLoading(true);
    const { error } = await window.db.auth.signInWithGoogle();
    if (error) { setErr(translateAuthError(error)); setLoading(false); }
  };

  return (
    <AuthLayout
      title={<>Criar <em style={{ fontStyle: "italic", fontWeight: 300, color: "var(--green)" }}>conta</em></>}
      subtitle="Comece a organizar suas finanças em 30 segundos."
      footer={<>Já tem conta? <a onClick={() => onSwitch("login")} style={{ color: "var(--green)", fontWeight: 600, cursor: "pointer", textDecoration: "none" }}>Entrar →</a></>}
    >
      <AlreadyLoggedBanner session={session} />
      <AuthError msg={err} />
      <AuthSuccess msg={okMsg} />
      {!okMsg && (
        <>
          <GoogleButton onClick={google} disabled={loading} />
          <Separator />
          <form onSubmit={submit}>
            <AuthInput label="Nome" value={name} onChange={setName} placeholder="Seu nome" autoFocus autoComplete="name" />
            <AuthInput label="Email" type="email" value={email} onChange={setEmail} placeholder="voce@exemplo.com" autoComplete="email" />
            <AuthInput label="Senha" type="password" value={password} onChange={setPassword} placeholder="Mínimo 6 caracteres" autoComplete="new-password" />
            <AuthPrimaryButton type="submit" disabled={loading || !email || !password || !name}>
              {loading ? "Criando…" : "Criar conta"}
            </AuthPrimaryButton>
          </form>
          <p style={{ fontSize: 11.5, color: "var(--fg-3)", marginTop: 16, lineHeight: 1.5, textAlign: "center" }}>
            Ao criar conta você concorda com os Termos de Uso e Política de Privacidade.
          </p>
        </>
      )}
    </AuthLayout>
  );
}

// ---------- ResetPasswordPage ----------
function ResetPasswordPage({ onSwitch }) {
  const [email, setEmail] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [okMsg, setOkMsg] = React.useState(null);

  const submit = async (e) => {
    e?.preventDefault();
    setErr(null); setOkMsg(null); setLoading(true);
    const { error } = await window.db.auth.resetPassword(email);
    if (error) { setErr(translateAuthError(error)); setLoading(false); return; }
    setOkMsg("Pronto! Verifique seu email — enviamos um link pra redefinir a senha.");
    setLoading(false);
  };

  return (
    <AuthLayout
      title="Recuperar senha"
      subtitle="Digite seu email e enviaremos um link pra criar uma nova senha."
      footer={<><a onClick={() => onSwitch("login")} style={{ color: "var(--green)", fontWeight: 600, cursor: "pointer", textDecoration: "none" }}>← Voltar pra entrar</a></>}
    >
      <AuthError msg={err} />
      <AuthSuccess msg={okMsg} />
      {!okMsg && (
        <form onSubmit={submit}>
          <AuthInput label="Email" type="email" value={email} onChange={setEmail} placeholder="voce@exemplo.com" autoFocus autoComplete="email" />
          <AuthPrimaryButton type="submit" disabled={loading || !email}>
            {loading ? "Enviando…" : "Enviar link de recuperação"}
          </AuthPrimaryButton>
        </form>
      )}
    </AuthLayout>
  );
}

// ---------- UpdatePasswordPage (após clicar no link do email) ----------
function UpdatePasswordPage({ onDone }) {
  const [password, setPassword] = React.useState("");
  const [confirm, setConfirm] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [okMsg, setOkMsg] = React.useState(null);

  const submit = async (e) => {
    e?.preventDefault();
    setErr(null); setLoading(true);
    if (password.length < 6) { setErr("A senha precisa ter pelo menos 6 caracteres."); setLoading(false); return; }
    if (password !== confirm) { setErr("As senhas não conferem."); setLoading(false); return; }
    const { error } = await window.db.auth.updatePassword(password);
    if (error) { setErr(translateAuthError(error)); setLoading(false); return; }
    setOkMsg("Senha atualizada! Redirecionando…");
    setTimeout(() => { onDone(); }, 1500);
  };

  return (
    <AuthLayout title="Definir nova senha" subtitle="Digite sua nova senha abaixo.">
      <AuthError msg={err} />
      <AuthSuccess msg={okMsg} />
      {!okMsg && (
        <form onSubmit={submit}>
          <AuthInput label="Nova senha" type="password" value={password} onChange={setPassword} placeholder="Mínimo 6 caracteres" autoFocus autoComplete="new-password" />
          <AuthInput label="Confirmar senha" type="password" value={confirm} onChange={setConfirm} placeholder="••••••••" autoComplete="new-password" />
          <AuthPrimaryButton type="submit" disabled={loading || !password || !confirm}>
            {loading ? "Salvando…" : "Salvar nova senha"}
          </AuthPrimaryButton>
        </form>
      )}
    </AuthLayout>
  );
}

window.AuthGate = AuthGate;
