/* login.jsx — Entrar OU Criar conta. Sem Discord. */

function Sparks() {
  const pts = React.useMemo(() => [...Array(22)].map(() => ({
    left: Math.random()*100 + "%", top: Math.random()*100 + "%",
    delay: (Math.random()*4).toFixed(2) + "s", dur: (2.5 + Math.random()*3).toFixed(2) + "s",
    scale: (0.5 + Math.random()*1.4).toFixed(2),
  })), []);
  return (<>
    {pts.map((p, i) => (
      <span key={i} className="login-spark" style={{
        left: p.left, top: p.top, transform: `scale(${p.scale})`,
        animation: `heroFloat ${p.dur} ease-in-out ${p.delay} infinite, fade 1s ease ${p.delay} both`,
      }} />
    ))}
  </>);
}

function LoginScreen({ onLogin }) {
  const { Ic, FX } = window;
  const [mode, setMode] = React.useState("login");
  const [leaving, setLeaving] = React.useState(false);

  const [email, setEmail] = React.useState("");
  const [pw, setPw] = React.useState("");
  const [show, setShow] = React.useState(false);

  const [rName, setRName] = React.useState("");
  const [rEmail, setREmail] = React.useState("");
  const [rPw, setRPw] = React.useState("");
  const [rPw2, setRPw2] = React.useState("");

  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  const [okMsg, setOkMsg] = React.useState("");

  const doLogin = async (e) => {
    if (e) e.preventDefault();
    if (leaving || busy) return;
    setErr("");
    if (!email.trim() || pw.length < 4) { setErr("Informe e-mail e senha."); return; }
    setBusy(true);
    try {
      const res = await window.Api.login(email.trim(), pw);
      FX.sfx.play("complete");
      setLeaving(true);
      setTimeout(() => onLogin(res.user), 520);
    } catch (e) {
      setErr(e.message || "Falha no login");
      FX.sfx.play("click");
      setBusy(false);
    }
  };

  const doRegister = async (e) => {
    if (e) e.preventDefault();
    if (busy) return;
    setErr("");
    if (!rName.trim() || rName.trim().length < 2) { setErr("Informe seu nome (mínimo 2 letras)."); return; }
    if (!rEmail.trim() || !/.+@.+\..+/.test(rEmail)) { setErr("E-mail inválido."); return; }
    if (rPw.length < 12) { setErr("A senha precisa de no mínimo 12 caracteres."); return; }
    if (rPw !== rPw2) { setErr("As senhas não coincidem."); return; }

    setBusy(true);
    try {
      const res = await window.Api.register(rName.trim(), rEmail.trim(), rPw);
      FX.sfx.play("complete");
      setOkMsg(res.message || "Solicitação enviada. Aguarde aprovação do administrador.");
      setMode("submitted");
      setRName(""); setREmail(""); setRPw(""); setRPw2("");
    } catch (e) {
      setErr(e.message || "Falha no cadastro");
      FX.sfx.play("click");
    } finally {
      setBusy(false);
    }
  };

  const Tabs = () => (
    <div className="login-tabs" role="tablist">
      <button type="button" role="tab" aria-selected={mode === "login"}
        className={"login-tab" + (mode === "login" ? " on" : "")}
        onClick={() => { setMode("login"); setErr(""); }}>Entrar</button>
      <button type="button" role="tab" aria-selected={mode === "register"}
        className={"login-tab" + (mode === "register" ? " on" : "")}
        onClick={() => { setMode("register"); setErr(""); }}>Criar conta</button>
    </div>
  );

  return (
    <div className={"login" + (leaving ? " leaving" : "")}>
      <div className="login-left">
        {mode === "login" && (
          <form className="login-card" onSubmit={doLogin}>
            <img className="login-logo-img" src="assets/logo.png" alt="Mil Grau RP" />
            <h1>Bem-vindo de volta</h1>
            <p className="sub">Entre para ver suas tarefas</p>
            <Tabs />
            <div className="login-field">
              <Ic.Mail />
              <input type="email" placeholder="E-mail" value={email}
                onChange={e => setEmail(e.target.value)} autoComplete="email" disabled={busy} required />
            </div>
            <div className="login-field">
              <Ic.Lock />
              <input type={show ? "text" : "password"} placeholder="Senha" value={pw}
                onChange={e => setPw(e.target.value)} autoComplete="current-password" disabled={busy} required />
              <button type="button" className="eye" aria-label="Mostrar senha"
                onClick={() => setShow(s => !s)}>{show ? <Ic.EyeOff /> : <Ic.Eye />}</button>
            </div>
            {err && <p className="form-err" style={{ margin: "8px 0 0" }}>{err}</p>}
            <button type="submit" className="login-btn" disabled={busy}>
              {busy ? "Entrando…" : "Entrar"}
            </button>
            <p className="login-foot" style={{ marginTop: 18 }}>
              Sem acesso? <a href="#" onClick={(e) => { e.preventDefault(); setMode("register"); setErr(""); }}>Criar conta</a>
            </p>
          </form>
        )}

        {mode === "register" && (
          <form className="login-card" onSubmit={doRegister}>
            <img className="login-logo-img" src="assets/logo.png" alt="Mil Grau RP" />
            <h1>Criar conta</h1>
            <p className="sub">Após o cadastro, um administrador precisa aprovar seu acesso.</p>
            <Tabs />
            <div className="login-field">
              <Ic.User />
              <input type="text" placeholder="Nome" value={rName}
                onChange={e => setRName(e.target.value)} autoComplete="name" disabled={busy} required />
            </div>
            <div className="login-field">
              <Ic.Mail />
              <input type="email" placeholder="E-mail" value={rEmail}
                onChange={e => setREmail(e.target.value)} autoComplete="email" disabled={busy} required />
            </div>
            <div className="login-field">
              <Ic.Lock />
              <input type="password" placeholder="Senha (mín. 12)" value={rPw}
                onChange={e => setRPw(e.target.value)} autoComplete="new-password" disabled={busy} required />
            </div>
            <div className="login-field">
              <Ic.Lock />
              <input type="password" placeholder="Confirmar senha" value={rPw2}
                onChange={e => setRPw2(e.target.value)} autoComplete="new-password" disabled={busy} required />
            </div>
            {err && <p className="form-err" style={{ margin: "8px 0 0" }}>{err}</p>}
            <button type="submit" className="login-btn" disabled={busy}>
              {busy ? "Enviando…" : "Solicitar acesso"}
            </button>
            <p className="login-foot" style={{ marginTop: 18 }}>
              Já tem conta? <a href="#" onClick={(e) => { e.preventDefault(); setMode("login"); setErr(""); }}>Entrar</a>
            </p>
          </form>
        )}

        {mode === "submitted" && (
          <div className="login-card">
            <img className="login-logo-img" src="assets/logo.png" alt="Mil Grau RP" />
            <div style={{ textAlign: "center", padding: "12px 0" }}>
              <div style={{ fontSize: 56, lineHeight: 1, marginBottom: 8 }}>📨</div>
              <h1 style={{ marginBottom: 6 }}>Solicitação enviada</h1>
              <p className="sub">{okMsg}</p>
            </div>
            <button type="button" className="login-btn" onClick={() => { setMode("login"); setOkMsg(""); }}>
              Voltar para o login
            </button>
          </div>
        )}
      </div>

      <div className="login-right">
        <Sparks />
        <div className="login-hero">
          <img className="login-hero-img" src="assets/logo.png" alt="Mil Grau RP" />
          <h1>Mil Grau RP</h1>
          <p>Organize seus projetos e bugs em um só lugar</p>
        </div>
      </div>
    </div>
  );
}

window.LoginScreen = LoginScreen;
