const DSl = window.MyBrokerPantanalDesignSystem_2460cb;

function Login({ mode, apiBase, onLoggedIn }) {
  const { Input, Button, Checkbox, Icon } = DSl;
  const m = mode === 'mobile';
  const [show, setShow] = React.useState(false);
  const [email, setEmail] = React.useState('');
  const [senha, setSenha] = React.useState('');
  const [erro, setErro] = React.useState('');
  const [carregando, setCarregando] = React.useState(false);
  // Verificador de humano (Cloudflare Turnstile) — bloqueia robôs tentando senhas no login.
  const tsRef = React.useRef(null);
  const tsId = React.useRef(null);
  const [tsToken, setTsToken] = React.useState('');
  React.useEffect(() => {
    let vivo = true;
    const montar = () => {
      if (!vivo || !tsRef.current || tsId.current !== null) return;
      if (!window.turnstile) { setTimeout(montar, 200); return; }
      tsId.current = window.turnstile.render(tsRef.current, { theme: 'light',
        sitekey: window.MB_TURNSTILE_SITEKEY,
        language: 'pt-br',
        callback: (t) => setTsToken(t),
        'expired-callback': () => setTsToken(''),
        'error-callback': () => setTsToken(''),
      });
    };
    montar();
    return () => { vivo = false; if (tsId.current !== null && window.turnstile) { try { window.turnstile.remove(tsId.current); } catch (e) {} } tsId.current = null; };
  }, []);
  const novoDesafio = () => { setTsToken(''); if (tsId.current !== null && window.turnstile) { try { window.turnstile.reset(tsId.current); } catch (e) {} } };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (carregando) return;
    if (!tsToken) { setErro('Aguarde a verificação de segurança (a caixinha abaixo da senha) terminar.'); return; }
    setErro('');
    setCarregando(true);
    try {
      const resp = await fetch(`${apiBase}/api/login`, {
        method: 'POST',
        credentials: 'include', // manda/recebe o cookie de sessão entre o protótipo e a API
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ email, senha, turnstile: tsToken }),
      });
      const data = await resp.json().catch(() => ({}));
      if (!resp.ok) {
        setErro(data.erro || 'Não foi possível entrar. Tente de novo.');
        novoDesafio();
        return;
      }
      onLoggedIn(data); // { nome, email, papel }
    } catch (err) {
      setErro('Não consegui falar com o servidor. Verifique sua conexão e tente de novo.');
      novoDesafio();
    } finally {
      setCarregando(false);
    }
  };

  const panel = (
    <div style={{ position: 'relative', background: 'var(--pattern-hatch-light), var(--action-accent)', color: '#fff', borderRadius: m ? '0 0 28px 28px' : 'var(--radius-xl)', padding: m ? '28px 20px 32px' : 40, display: 'flex', flexDirection: 'column', gap: m ? 18 : 24, overflow: 'hidden' }}>
      <img src={ASSET + 'logo-mybroker-pantanal-white.png'} alt="MyBroker Pantanal" style={{ height: m ? 26 : 32, width: 'auto', alignSelf: 'flex-start' }} />
      {!m && <div style={{ flex: 1 }} />}
      <span style={{ fontSize: 10, fontWeight: 600, fontStretch: '125%', textTransform: 'uppercase', letterSpacing: '0.04em', opacity: 0.8 }}>Sistema de locação</span>
      <h1 style={{ margin: 0, fontSize: m ? 28 : 44, fontWeight: 800, lineHeight: 0.95, textTransform: 'uppercase', letterSpacing: '-0.01em' }}>Toda a sua carteira de aluguel em um só lugar</h1>
      {!m && (
        <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {['Contratos, cobranças e repasses conectados', 'Vistorias com fotos direto do celular', 'Painel em tempo real para toda a equipe'].map((t) => (
            <li key={t} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 14, color: 'rgba(255,255,255,.88)' }}><Icon name="circle-check" size={18} />{t}</li>
          ))}
        </ul>
      )}
      {!m && <span style={{ fontSize: 11, color: 'rgba(255,255,255,.6)' }}>© 2026 MyBroker Pantanal · Cáceres, MT</span>}
    </div>
  );
  const form = (
    <form onSubmit={handleSubmit} style={{ width: '100%', maxWidth: 380, display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 6 }}>
        <h2 style={{ margin: 0, fontSize: 24, fontWeight: 600, fontStretch: '125%', textTransform: 'uppercase', color: 'var(--text-strong)' }}>Entrar</h2>
        <p style={{ margin: 0, fontSize: 13, color: 'var(--text-muted)' }}>Use o e-mail cadastrado pela sua imobiliária.</p>
      </div>
      {erro && (
        <div style={{ padding: '10px 12px', borderRadius: 10, background: 'var(--status-danger-bg)', color: 'var(--status-danger-text)', fontSize: 13 }}>{erro}</div>
      )}
      <Input label="E-mail" type="email" icon="mail" value={email} onChange={(e) => setEmail(e.target.value)} size="lg" autoFocus required />
      <Input label="Senha" type={show ? 'text' : 'password'} icon="lock" value={senha} onChange={(e) => setSenha(e.target.value)} size="lg" required
        suffix={<span role="button" onClick={() => setShow(!show)} style={{ display: 'flex', cursor: 'pointer' }}><Icon name={show ? 'eye-off' : 'eye'} size={16} /></span>} />
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Checkbox label="Manter conectado" defaultChecked />
        <a href="#" onClick={(e) => e.preventDefault()} style={{ fontSize: 13 }}>Esqueci a senha</a>
      </div>
      <div ref={tsRef} style={{ minHeight: 65 }} />
      <Button type="submit" size="lg" fullWidth iconRight="arrow-right" disabled={carregando}>{carregando ? 'Entrando...' : 'Entrar'}</Button>
    </form>
  );
  if (m) return <div style={{ minHeight: '100%', display: 'flex', flexDirection: 'column', gap: 28, background: 'var(--bg-app)' }}>{panel}<div style={{ padding: '0 20px 32px', display: 'flex', justifyContent: 'center' }}>{form}</div></div>;
  return (
    <div style={{ height: '100%', display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1fr)', gap: 12, padding: 12, background: 'var(--gradient-atmosphere)' }}>
      {panel}
      <div style={{ background: 'var(--surface-card)', borderRadius: 'var(--radius-xl)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 32, boxShadow: 'var(--shadow-sm)' }}>{form}</div>
    </div>
  );
}

window.Login = Login;
