/* ============================================================
   Tela de Login — design RECO64
   Layout dividido: painel de marca (esq.) + formulário (dir.)
   ============================================================ */
function LoginScreen() {
  const [usuario,   setUsuario]   = React.useState("");
  const [senha,     setSenha]     = React.useState("");
  const [showPw,    setShowPw]    = React.useState(false);
  const [lembrar,   setLembrar]   = React.useState(true);
  const [loading,   setLoading]   = React.useState(false);
  const [erro,      setErro]      = React.useState("");

  async function handleSubmit(e) {
    e.preventDefault();
    if (!usuario.trim()) { setErro("Informe o usuário."); return; }
    if (!senha)          { setErro("Informe a senha."); return; }
    setLoading(true);
    setErro("");
    try {
      await DB.login(usuario.trim(), senha);
    } catch (err) {
      setErro(err.message || "Usuário ou senha inválidos.");
      setLoading(false);
    }
  }

  /* ---- SVGs ---- */
  const IconUser = (
    <svg className="lead-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="8" r="3.6"/><path d="M5 20c.8-4 3.8-6 7-6s6.2 2 7 6"/>
    </svg>
  );
  const IconLock = (
    <svg className="lead-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="4" y="10.5" width="16" height="10" rx="2"/><path d="M8 10.5V7a4 4 0 0 1 8 0v3.5"/>
    </svg>
  );
  const IconEyeOpen = (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/>
    </svg>
  );
  const IconEyeOff = (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 3l18 18M10.6 10.6a3 3 0 0 0 4.2 4.2M9.4 5.2A9.8 9.8 0 0 1 12 5c6.4 0 10 7 10 7a17 17 0 0 1-3.1 3.9M6.1 6.1A17 17 0 0 0 2 12s3.6 7 10 7a9.7 9.7 0 0 0 3-.5"/>
    </svg>
  );
  const IconArrow = (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M4 12h14M13 6l6 6-6 6"/>
    </svg>
  );
  const IconAlert = (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 3 2 20h20L12 3Z"/><path d="M12 10v4M12 17.5v.5"/>
    </svg>
  );
  const IconCheck = (
    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
      <path d="m5 12 4.5 4.5L19 7"/>
    </svg>
  );

  return (
    <div className="auth">

      {/* ── Painel de marca (esquerda) ── */}
      <aside className="brandside">
        <div className="brandside-texture" />
        <div className="brand-login-top">
          <span className="brand-login-mark"><Logo size={22} /></span>
          <span>
            <strong>ACRE GESSO</strong>
            <em>Clube de Recompensas</em>
          </span>
        </div>

        <div className="brand-mid">
          <h1>Gerencie pontos, prêmios e clientes <em>em um só lugar.</em></h1>
          <p>Lance vendas do ERP, acompanhe categorias Bronze, Prata e Ouro e registre resgates com poucos cliques.</p>
          <div className="brand-stats">
            <div className="bstat"><strong>1.2K+</strong><span>clientes ativos</span></div>
            <div className="bstat"><strong>3</strong><span>categorias</span></div>
            <div className="bstat"><strong>98%</strong><span>satisfação</span></div>
          </div>
        </div>

        <div className="brand-foot">© 2026 8Bits Tecnologia · Painel do administrador</div>
      </aside>

      {/* ── Formulário (direita) ── */}
      <main className="formside">
        <form className="formcard" onSubmit={handleSubmit} noValidate>

          <div className="form-head">
            {/* Logo só no mobile */}
            <div className="logo-mobile"><Logo size={22} /></div>
            <h2>Bem-vindo de volta</h2>
            <p>Entre com suas credenciais para acessar o painel.</p>
          </div>

          {/* Erro */}
          {erro && (
            <div className="login-error" key={erro}>
              {IconAlert}
              <span>{erro}</span>
            </div>
          )}

          {/* Campo usuário */}
          <div className="login-field">
            <label htmlFor="login-user">Usuário</label>
            <div className="input-wrap">
              <input
                className="login-input"
                id="login-user"
                type="text"
                placeholder="seu.usuario"
                autoComplete="username"
                autoFocus
                value={usuario}
                onChange={e => { setUsuario(e.target.value); setErro(""); }}
                disabled={loading}
              />
              {IconUser}
            </div>
          </div>

          {/* Campo senha */}
          <div className="login-field">
            <label htmlFor="login-pw">Senha</label>
            <div className="input-wrap">
              <input
                className="login-input"
                id="login-pw"
                type={showPw ? "text" : "password"}
                placeholder="••••••••"
                autoComplete="current-password"
                value={senha}
                onChange={e => { setSenha(e.target.value); setErro(""); }}
                disabled={loading}
              />
              {IconLock}
              <button
                type="button"
                className="toggle-pw"
                onClick={() => setShowPw(v => !v)}
                aria-label={showPw ? "Ocultar senha" : "Mostrar senha"}
              >
                {showPw ? IconEyeOff : IconEyeOpen}
              </button>
            </div>
          </div>

          {/* Lembrar + esqueci */}
          <div className="row-between">
            <span
              className="cb-wrap"
              onClick={() => setLembrar(v => !v)}
              role="checkbox"
              aria-checked={lembrar}
              tabIndex={0}
              onKeyDown={e => e.key === " " && setLembrar(v => !v)}
            >
              <span className={"cb-box" + (lembrar ? " checked" : "")}>{lembrar ? IconCheck : null}</span>
              Manter conectado
            </span>
            <a className="login-link" href="#">Esqueci a senha</a>
          </div>

          {/* Botão entrar */}
          <button type="submit" className="btn-login" disabled={loading}>
            <span>{loading ? "Entrando..." : "Entrar"}</span>
            {!loading && IconArrow}
          </button>

        </form>
      </main>
    </div>
  );
}
