function LoginPage() {
  const { AppBootstrap } = window.__CRM__;
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [csrf, setCsrf] = React.useState("");
  const [err, setErr] = React.useState("");

  React.useEffect(() => {
    (async () => {
      try {
        const r = await fetch("/auth/login.php", { credentials: "include", cache: "no-store" });
        const j = await r.json();
        setCsrf(j.csrf || "");
      } catch { setErr("Falha ao iniciar sessão segura."); }
    })();
  }, []);

  const valid = email.includes("@") && password.length >= 6;

  return (
    <AppBootstrap>
      <MaterialUI.Container maxWidth="xs" sx={{ mt: 10 }}>
        <MaterialUI.Paper sx={{ p: 3 }}>
          <MaterialUI.Typography variant="h5" sx={{ mb: 2, fontWeight: 700, color: "primary.main" }}>
            Acesso
          </MaterialUI.Typography>
          {err && <MaterialUI.Alert severity="error" sx={{ mb: 2 }}>{err}</MaterialUI.Alert>}
          <form method="post" action="/auth/do_login.php"
            onSubmit={(e)=>{ if(!valid || !csrf){ e.preventDefault(); setErr("Preencha os campos. CSRF ausente."); } }}>
            <input type="hidden" name="csrf" value={csrf} />
            <MaterialUI.TextField fullWidth label="Email" type="email" name="email"
              value={email} onChange={e=>setEmail(e.target.value)} margin="normal" required />
            <MaterialUI.TextField fullWidth label="Senha" type="password" name="password"
              value={password} onChange={e=>setPassword(e.target.value)} margin="normal" required inputProps={{ minLength: 6 }} />
            <MaterialUI.Button type="submit" variant="contained" fullWidth sx={{ mt: 2 }}>Entrar</MaterialUI.Button>
          </form>
        </MaterialUI.Paper>
      </MaterialUI.Container>
    </AppBootstrap>
  );
}
window.LoginPage = LoginPage;
