/* ANISAN — Login gate. Warm centered card. Valida credenciais de verdade via
   window.getAuth() (LocalAuth hoje; SupabaseAuth quando injetado). Em caso de
   sucesso, entra no painel com o id do usuário autenticado. */

function Login({ onEnter }) {
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });
  const store = window.useStore();
  const usuarios = (store.data.usuarios || []);
  const master = usuarios.find((u) => u.role === "master") || usuarios[0];
  // e-mail do Master pré-preenchido só por conveniência; senha sempre vazia.
  const [email, setEmail] = React.useState(master ? master.email : "");
  const [senha, setSenha] = React.useState("");
  const [erro, setErro] = React.useState("");
  const [busy, setBusy] = React.useState(false);

  const entrar = async () => {
    if (busy) return;
    setErro(""); setBusy(true);
    try {
      const res = await window.getAuth().signIn(email, senha);
      if (res && res.ok) {
        // já com sessão → recarrega os dados sob o RLS (no modo local é no-op leve).
        if (window.ANISANStore && window.ANISANStore.rehydrate) { try { await window.ANISANStore.rehydrate(); } catch (e) {} }
        onEnter(res.user ? res.user.id : null);
      } else setErro((res && res.error) || "Não foi possível entrar.");
    } catch (e) { setErro("Não foi possível entrar."); }
    setBusy(false);
  };
  const onKey = (e) => { if (e.key === "Enter") entrar(); };

  return (
    <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", background: "var(--bg-page-glow)", padding: 24 }}>
      <div style={{ width: "100%", maxWidth: 360, background: "var(--surface)", border: "1px solid var(--hairline)", borderRadius: "var(--radius)", padding: "34px 32px", boxSizing: "border-box" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 11, marginBottom: 26 }}>
          <span style={{ width: 38, height: 38, borderRadius: 10, background: "var(--brass)", display: "grid", placeItems: "center", fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 20, color: "var(--ink)" }}>あ</span>
          <span>
            <span style={{ display: "block", fontFamily: "var(--font-display)", fontWeight: 500, fontSize: 21, letterSpacing: "0.5px", color: "var(--paper)", lineHeight: 1 }}>ANISAN</span>
            <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 9.5, letterSpacing: "0.22em", color: "var(--brass)", marginTop: 3 }}>SISTEMA FINANCEIRO</span>
          </span>
        </div>

        <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 500, fontSize: 24, color: "var(--paper)", margin: "0 0 6px" }}>Entrar no painel</h1>
        <p style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "var(--muted)", margin: "0 0 24px", lineHeight: 1.6 }}>Controle de caixa, faturamento e metas do grupo.</p>

        <LoginField label="E-mail" value={email} onChange={setEmail} onKeyDown={onKey} icon="mail" type="email" placeholder="email@anisan.com.br" autoFocus={!email} />
        <LoginField label="Senha" value={senha} onChange={setSenha} onKeyDown={onKey} icon="lock" type="password" placeholder="••••••••" autoFocus={!!email} />

        {erro && (
          <div role="alert" style={{ display: "flex", alignItems: "center", gap: 8, background: "var(--clay-tint, rgba(192,86,60,0.12))", border: "1px solid var(--clay)", borderRadius: "var(--radius-sm)", padding: "9px 12px", marginBottom: 14 }}>
            <i data-lucide="alert-circle" style={{ width: 15, height: 15, strokeWidth: 1.8, color: "var(--clay)", flexShrink: 0 }}></i>
            <span style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: "var(--paper)" }}>{erro}</span>
          </div>
        )}

        <button onClick={entrar} disabled={busy} style={{
          width: "100%", marginTop: 4, padding: "13px", cursor: busy ? "default" : "pointer", opacity: busy ? 0.7 : 1,
          background: "var(--brass)", border: "none", borderRadius: "var(--radius-pill)",
          fontFamily: "var(--font-mono)", fontSize: 13, letterSpacing: "0.04em", color: "var(--ink)", fontWeight: 600,
        }}>{busy ? "Entrando…" : "Entrar →"}</button>

        <p style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--muted-2)", textAlign: "center", marginTop: 18, letterSpacing: "0.04em" }}>Acesso restrito · Grupo Anisan</p>
      </div>
    </div>
  );
}

function LoginField({ label, value, onChange, onKeyDown, icon, type = "text", placeholder, autoFocus }) {
  return (
    <label style={{ display: "block", marginBottom: 16 }}>
      <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 7 }}>{label}</span>
      <span style={{ display: "flex", alignItems: "center", gap: 10, background: "var(--ink)", border: "1px solid var(--hairline-strong)", borderRadius: "var(--radius-sm)", padding: "11px 14px" }}>
        <i data-lucide={icon} style={{ width: 16, height: 16, strokeWidth: 1.6, color: "var(--muted-2)" }}></i>
        <input value={value} onChange={(e) => onChange(e.target.value)} onKeyDown={onKeyDown} type={type} placeholder={placeholder} autoFocus={autoFocus}
          style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--paper)", fontFamily: "var(--font-body)", fontSize: 14 }} />
      </span>
    </label>
  );
}

window.Login = Login;
