/* global React, ReactDOM, Icon, PageShell, useFormHardening, useIdleTimeout, usePageHardening, SecurityStancePanel */
const { useState: useS_rs } = React;

function RestritaPage() {
  usePageHardening();
  const sec = useFormHardening({ formKey: "area-restrita", botMinMs: 800 });
  const [user, setUser] = useS_rs("");
  const [pass, setPass] = useS_rs("");
  const [otp, setOtp]   = useS_rs("");
  const [step, setStep] = useS_rs(1);
  const [err, setErr]   = useS_rs(null);
  const [warning, setWarning] = useS_rs(null);

  // Idle logout — reset to step 1 after 15 min of inactivity. Active only
  // once the user has progressed past the first screen.
  useIdleTimeout({
    minutes: 15,
    warnAt: 1,
    paused: step === 1,
    onWarn: (s) => setWarning("Sessão expira em ~" + Math.round(s / 60) + " min por inatividade."),
    onTimeout: () => {
      setStep(1); setUser(""); setPass(""); setOtp("");
      setErr("Sessão encerrada por inatividade. Entre novamente.");
      setWarning(null);
    },
  });

  const onSubmit1 = (e) => {
    e.preventDefault();
    const r = sec.validate({ user, pass });
    if (!r.ok) {
      if (r.silent) { setErr("Falha na autenticação."); return; }
      if (r.reason === "rate") { setErr(`Muitas tentativas. Aguarde ${r.retryInSec}s.`); return; }
      setErr("Dados inválidos.");
      return;
    }
    if (!user || !pass) { setErr("Preencha usuário e senha."); return; }
    setErr(null); setWarning(null); setStep(2);
  };
  const onSubmit2 = (e) => {
    e.preventDefault();
    if (otp.length !== 6) { setErr("O código MFA tem 6 dígitos."); return; }
    setErr("Acesso restrito. Sua sessão será validada pela direção em até 30 minutos.");
  };

  return (
    <PageShell active={null}>
      <section className="restrict-page">
        <div className="container" style={{ display: "grid", placeItems: "center" }}>
          <div className="restrict-card">
            <span className="tick tl" /><span className="tick tr" />
            <span className="tick bl" /><span className="tick br" />
            <div className="restrict-shield"><Icon.Lock /></div>
            <h1>Área restrita</h1>
            <p className="restrict-sub">
              Portal de clientes Crime Solution. Acesso somente com credenciais ativas e dispositivo registrado.
            </p>

            {step === 1 && (
              <form onSubmit={onSubmit1} autoComplete="on" noValidate style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                <input {...sec.honeypotProps} />
                <div className="field">
                  <label className="mono">Usuário corporativo</label>
                  <input value={user} maxLength={254} inputMode="email" spellCheck={false}
                    onChange={(e) => setUser(e.target.value)}
                    placeholder="seu.usuario@empresa.com" autoComplete="username" />
                </div>
                <div className="field">
                  <label className="mono">Senha</label>
                  <input type="password" value={pass} maxLength={200}
                    onChange={(e) => setPass(e.target.value)}
                    placeholder="••••••••" autoComplete="current-password" />
                </div>
                {err && <span className="mono" style={{ color: "var(--danger)", fontSize: 12 }}>{err}</span>}
                <button type="submit" className="btn btn-primary" style={{ justifyContent: "center" }}>
                  Continuar <Icon.Arrow className="arr" />
                </button>
              </form>
            )}

            {step === 2 && (
              <form onSubmit={onSubmit2} noValidate style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                <div className="field">
                  <label className="mono">Código MFA · 6 dígitos</label>
                  <input
                    value={otp}
                    onChange={(e) => setOtp(e.target.value.replace(/[^0-9]/g, "").slice(0, 6))}
                    placeholder="••••••"
                    inputMode="numeric"
                    autoComplete="one-time-code"
                    maxLength={6}
                    style={{ letterSpacing: "0.5em", fontFamily: "var(--font-mono)", fontSize: 18, textAlign: "center" }}
                  />
                </div>
                {warning && <span className="mono" style={{ color: "var(--warning)", fontSize: 11, lineHeight: 1.5 }}>{warning}</span>}
                {err && <span className="mono" style={{ color: "var(--warning)", fontSize: 12, lineHeight: 1.5 }}>{err}</span>}
                <button type="submit" className="btn btn-primary" style={{ justifyContent: "center" }}>
                  <Icon.Shield /> Entrar
                </button>
                <button type="button" onClick={() => { setStep(1); setOtp(""); setErr(null); setWarning(null); }}
                  className="btn btn-ghost" style={{ justifyContent: "center" }}>
                  Voltar
                </button>
              </form>
            )}

            <div className="security-strip" style={{ marginTop: 18 }}>
              <span><Icon.Check /> TLS 1.3 · HSTS</span>
              <span><Icon.Check /> MFA obrigatório</span>
              <span><Icon.Check /> Logout em 15 min</span>
              <span><Icon.Check /> Rate limit anti força bruta</span>
            </div>

            <div className="restrict-foot">
              <a href="mailto:diretoria@crimesolution.net">Esqueci minha senha</a>
              <a href="https://wa.me/5561999949060" target="_blank" rel="noopener noreferrer">Não consigo entrar</a>
            </div>
          </div>
        </div>
      </section>
    </PageShell>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<RestritaPage />);
