/* Login screen — split layout, brand left + form right */
/* Auth real via Firebase (SF.auth.signInWithEmailAndPassword) */

// ─── Rate-limit client-side (login + recuperação de senha) ───────────────────
// Complementa o rate-limit interno do Firebase — impede automação óbvia sem
// exigir backend ou CAPTCHA.
//
// Login:  máx. 5 tentativas com FALHA por janela de 15 min por email.
// Reset:  máx. 3 envios por janela de 15 min por email.

const _SF_LOGIN_MAX    = 5;
const _SF_RESET_MAX    = 3;
const _SF_WIN_MS       = 15 * 60 * 1000; // janela de 15 minutos (ambos)

// Helpers genéricos — prefixo separa login de reset no localStorage
const _rlKey = (prefix, email) =>
  `sf_${prefix}_${btoa(email.trim().toLowerCase()).replace(/[^a-z0-9]/gi, '')}`;

const _rlGet = (prefix, email) => {
  try { return JSON.parse(localStorage.getItem(_rlKey(prefix, email))) || {}; }
  catch { return {}; }
};
const _rlSet = (prefix, email, d) => {
  try { localStorage.setItem(_rlKey(prefix, email), JSON.stringify(d)); } catch {}
};

function _rlCheck(prefix, max, email) {
  const d = _rlGet(prefix, email);
  const now = Date.now();
  if (!d.first || now - d.first > _SF_WIN_MS) return { ok: true };
  if ((d.n ?? 0) >= max) return { ok: false, waitMs: _SF_WIN_MS - (now - d.first) };
  return { ok: true };
}
function _rlRecord(prefix, email) {
  const d = _rlGet(prefix, email);
  const now = Date.now();
  if (!d.first || now - d.first > _SF_WIN_MS) _rlSet(prefix, email, { n: 1, first: now });
  else _rlSet(prefix, email, { n: (d.n ?? 0) + 1, first: d.first });
}
function _rlReset(prefix, email) {
  try { localStorage.removeItem(_rlKey(prefix, email)); } catch {}
}

// ─── Login ────────────────────────────────────────────────────────────────────
function Login({ navigate }) {
  const [view,     setView]     = React.useState('login'); // 'login' | 'reset'
  const [email,    setEmail]    = React.useState('');
  const [pass,     setPass]     = React.useState('');
  const [showPass, setShowPass] = React.useState(false);
  const [loading,  setLoading]  = React.useState(false);
  const [error,    setError]    = React.useState(null);
  const [waitSecs, setWaitSecs] = React.useState(0); // countdown rate-limit

  // Countdown ao vivo quando bloqueado
  React.useEffect(() => {
    if (waitSecs <= 0) return;
    const t = setTimeout(() => setWaitSecs(w => Math.max(0, w - 1)), 1000);
    return () => clearTimeout(t);
  }, [waitSecs]);

  // Mensagens de erro Firebase → português
  const firebaseMsg = (code) => {
    const msgs = {
      'auth/user-not-found':         'Email ou senha inválidos.',
      'auth/wrong-password':         'Email ou senha inválidos.',
      'auth/invalid-credential':     'Email ou senha inválidos.',
      'auth/invalid-email':          'Endereço de email inválido.',
      'auth/user-disabled':          'Conta desativada. Entre em contato com o suporte.',
      'auth/too-many-requests':      'Muitas tentativas. Aguarde alguns minutos e tente novamente.',
      'auth/network-request-failed': 'Sem conexão com a internet. Verifique sua rede.',
      'auth/operation-not-allowed':  'Login por email não está habilitado.',
      'blocked':                     'Sua conta está bloqueada. Fale com o suporte.',
      'no-cnpj':                     'Usuário não vinculado a nenhuma empresa. Fale com o suporte.',
    };
    return msgs[code] || 'Erro ao entrar. Tente novamente ou fale com o suporte.';
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    if (!email.trim()) { setError('Informe seu email para continuar.'); return; }
    if (!pass)         { setError('Informe sua senha para continuar.'); return; }

    // Rate-limit client-side: bloqueia antes de chegar no Firebase
    const rl = _rlCheck('login', _SF_LOGIN_MAX, email.trim());
    if (!rl.ok) {
      const secs = Math.ceil(rl.waitMs / 1000);
      setWaitSecs(secs);
      setError('Muitas tentativas incorretas.');
      return;
    }

    setLoading(true);
    try {
      await SF.auth.signInWithEmailAndPassword(email.trim(), pass);
      _rlReset('login', email.trim()); // limpa contador após login bem-sucedido
      // onAuthStateChanged no App cuida do navigate
    } catch (err) {
      console.error('[login] signIn error:', err);
      setLoading(false);
      _rlRecord('login', email.trim()); // só conta falhas
      setError(firebaseMsg(err.code || err.message));
    }
  };

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.05fr 1fr', minHeight: '100vh', background: 'var(--white)' }}>
      <LoginBrand />
      <div style={{
        display: 'flex', flexDirection: 'column',
        justifyContent: 'center', alignItems: 'center',
        padding: '40px 60px', position: 'relative',
      }}>
        <button
          className="btn btn-ghost btn-sm"
          style={{ position: 'absolute', top: 24, right: 32, color: 'var(--ink-600)' }}
          onClick={() => navigate('landing')}
        >
          ← Voltar ao site
        </button>

        <div style={{ width: '100%', maxWidth: 400 }}>
          <Logo size={32} />

          {view === 'reset'
            ? <ResetForm
                initialEmail={email}
                onBack={() => { setView('login'); setError(null); }}
              />
            : (
              <>
                <h1 style={{
                  fontSize: 30, fontWeight: 700, letterSpacing: '-0.02em',
                  margin: '32px 0 8px', color: 'var(--ink-900)'
                }}>
                  Bem-vindo de volta
                </h1>
                <p style={{ color: 'var(--ink-600)', fontSize: 15, margin: '0 0 32px' }}>
                  Acesse o painel da sua farmácia.
                </p>

                <form onSubmit={onSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                  {/* Email */}
                  <div>
                    <label className="label" htmlFor="email">Email</label>
                    <div style={{ position: 'relative' }}>
                      <div style={{ position: 'absolute', top: '50%', left: 14, transform: 'translateY(-50%)', color: 'var(--ink-400)' }}>
                        <Icon name="mail" size={17} />
                      </div>
                      <input id="email" className="input" style={{ paddingLeft: 40 }} type="email"
                        placeholder="voce@farmacia.com.br"
                        value={email} onChange={(e) => setEmail(e.target.value)}
                        autoComplete="email" autoFocus disabled={loading} />
                    </div>
                  </div>

                  {/* Senha */}
                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                      <label className="label" htmlFor="pass">Senha</label>
                      <button
                        type="button"
                        style={{
                          fontSize: 13, color: 'var(--brand-500)', fontWeight: 600,
                          background: 'none', border: 0, padding: 0, cursor: 'pointer',
                          fontFamily: 'inherit',
                        }}
                        onClick={() => { setView('reset'); setError(null); }}
                      >
                        Esqueci minha senha
                      </button>
                    </div>
                    <div style={{ position: 'relative' }}>
                      <div style={{ position: 'absolute', top: '50%', left: 14, transform: 'translateY(-50%)', color: 'var(--ink-400)' }}>
                        <Icon name="lock" size={17} />
                      </div>
                      <input id="pass" className="input" style={{ paddingLeft: 40, paddingRight: 44 }}
                        type={showPass ? 'text' : 'password'} placeholder="••••••••"
                        value={pass} onChange={(e) => setPass(e.target.value)}
                        autoComplete="current-password" disabled={loading} />
                      <button type="button" onClick={() => setShowPass(!showPass)} style={{
                        position: 'absolute', top: '50%', right: 8, transform: 'translateY(-50%)',
                        background: 'none', border: 0, padding: 8, cursor: 'pointer',
                        color: 'var(--ink-500)', display: 'flex', alignItems: 'center'
                      }} aria-label="Mostrar senha" tabIndex={-1}>
                        <Icon name={showPass ? 'eye-off' : 'eye'} size={17} />
                      </button>
                    </div>
                  </div>

                  <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13.5, color: 'var(--ink-700)', cursor: 'pointer' }}>
                    <input type="checkbox" style={{ accentColor: 'var(--brand-500)', width: 16, height: 16 }} defaultChecked />
                    Manter conectado neste dispositivo
                  </label>

                  {/* Erro / rate-limit */}
                  {error && (
                    <div style={{
                      background: waitSecs > 0 ? 'var(--warning-bg)' : 'var(--danger-bg)',
                      color:      waitSecs > 0 ? '#92400E'            : 'var(--danger)',
                      padding: '10px 14px', borderRadius: 8, fontSize: 13.5, fontWeight: 500,
                      border: `1px solid ${waitSecs > 0 ? '#FDE68A' : '#F4C2C4'}`,
                    }}>
                      {error}
                      {waitSecs > 0 && (
                        <div className="mono" style={{ marginTop: 6, fontSize: 13, fontWeight: 700 }}>
                          ⏱ Tente novamente em{' '}
                          {String(Math.floor(waitSecs / 60)).padStart(2, '0')}:{String(waitSecs % 60).padStart(2, '0')}
                        </div>
                      )}
                    </div>
                  )}

                  <button type="submit" className="btn btn-primary btn-lg" disabled={loading || waitSecs > 0} style={{ width: '100%', marginTop: 6 }}>
                    {loading
                      ? <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                          <Spinner size={16} /> Entrando…
                        </span>
                      : <><span>Entrar no painel</span><Icon name="arrow-right" size={16} /></>
                    }
                  </button>
                </form>

                <div style={{
                  marginTop: 32, paddingTop: 24,
                  borderTop: '1px solid var(--ink-200)',
                  fontSize: 13, color: 'var(--ink-500)', textAlign: 'center'
                }}>
                  Problemas para acessar?{' '}
                  <a
                    href="https://wa.me/5521997197834?text=Desejo%20falar%20com%20o%20suporte"
                    target="_blank"
                    rel="noopener noreferrer"
                    style={{ color: 'var(--brand-500)', fontWeight: 600, textDecoration: 'none' }}
                  >
                    Falar com suporte
                  </a>
                </div>
              </>
            )
          }
        </div>
      </div>
    </div>
  );
}

// ─── Formulário de recuperação de senha ──────────────────────────────────────
function ResetForm({ initialEmail, onBack }) {
  const [email,    setEmail]    = React.useState(initialEmail || '');
  const [loading,  setLoading]  = React.useState(false);
  const [sent,     setSent]     = React.useState(false);
  const [error,    setError]    = React.useState(null);
  const [waitSecs, setWaitSecs] = React.useState(0);

  // Countdown ao vivo quando rate-limited
  React.useEffect(() => {
    if (waitSecs <= 0) return;
    const t = setTimeout(() => setWaitSecs(w => Math.max(0, w - 1)), 1000);
    return () => clearTimeout(t);
  }, [waitSecs]);

  const onSubmit = async (e) => {
    e.preventDefault();
    setError(null);

    const trimmed = email.trim();
    if (!trimmed) { setError('Informe seu email.'); return; }

    // Verificação de rate limit antes de chamar o Firebase
    const rl = _rlCheck('reset', _SF_RESET_MAX, trimmed);
    if (!rl.ok) {
      const secs = Math.ceil(rl.waitMs / 1000);
      setWaitSecs(secs);
      setError('Limite de envios atingido.');
      return;
    }

    setLoading(true);
    _rlRecord('reset', trimmed); // registra tentativa antes do fetch

    try {
      await SF.auth.sendPasswordResetEmail(trimmed);
    } catch (err) {
      // Não revelamos se o email existe — resposta genérica em qualquer caso
      console.warn('[reset] sendPasswordResetEmail:', err.code);
    }

    setLoading(false);
    setSent(true); // sempre mostra "verifique seu email"
  };

  // ── Estado: email enviado ──────────────────────────────────────────────────
  if (sent) {
    return (
      <>
        <div style={{ textAlign: 'center', padding: '40px 0 32px' }}>
          <div style={{ fontSize: 44, marginBottom: 18 }}>📧</div>
          <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--ink-900)', marginBottom: 10 }}>
            Verifique seu email
          </div>
          <div style={{ fontSize: 14, color: 'var(--ink-600)', lineHeight: 1.65, marginBottom: 32 }}>
            Se o endereço <strong>{email.trim()}</strong> estiver cadastrado, você
            receberá o link de redefinição em alguns minutos.
            <br/><br/>
            Não esqueça de conferir a caixa de spam.
          </div>
          <button className="btn btn-outline btn-lg" onClick={onBack} style={{ width: '100%' }}>
            ← Voltar ao login
          </button>
        </div>
      </>
    );
  }

  // ── Estado: formulário ─────────────────────────────────────────────────────
  return (
    <>
      <h1 style={{
        fontSize: 28, fontWeight: 700, letterSpacing: '-0.02em',
        margin: '32px 0 8px', color: 'var(--ink-900)'
      }}>
        Recuperar senha
      </h1>
      <p style={{ color: 'var(--ink-600)', fontSize: 14.5, margin: '0 0 28px', lineHeight: 1.55 }}>
        Informe seu email e enviaremos um link para redefinir sua senha.
      </p>

      <form onSubmit={onSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div>
          <label className="label" htmlFor="reset-email">Email</label>
          <div style={{ position: 'relative' }}>
            <div style={{ position: 'absolute', top: '50%', left: 14, transform: 'translateY(-50%)', color: 'var(--ink-400)' }}>
              <Icon name="mail" size={17} />
            </div>
            <input
              id="reset-email" className="input" style={{ paddingLeft: 40 }}
              type="email" placeholder="voce@farmacia.com.br"
              value={email} onChange={e => setEmail(e.target.value)}
              autoComplete="email" autoFocus disabled={loading}
            />
          </div>
        </div>

        {/* Erro / rate-limit */}
        {error && (
          <div style={{
            background: 'var(--warning-bg)', color: '#92400E',
            padding: '10px 14px', borderRadius: 8, fontSize: 13.5, fontWeight: 500,
            border: '1px solid #FDE68A',
          }}>
            {error}
            {waitSecs > 0 && (
              <div className="mono" style={{ marginTop: 6, fontSize: 13, fontWeight: 700 }}>
                ⏱ Tente novamente em{' '}
                {String(Math.floor(waitSecs / 60)).padStart(2, '0')}:{String(waitSecs % 60).padStart(2, '0')}
              </div>
            )}
          </div>
        )}

        <button
          type="submit"
          className="btn btn-primary btn-lg"
          disabled={loading || waitSecs > 0}
          style={{ width: '100%' }}
        >
          {loading
            ? <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <Spinner size={16} /> Enviando…
              </span>
            : 'Enviar link de recuperação'
          }
        </button>

        <button
          type="button"
          className="btn btn-ghost"
          onClick={onBack}
          style={{ width: '100%', color: 'var(--ink-600)', fontFamily: 'inherit' }}
        >
          ← Voltar ao login
        </button>
      </form>
    </>
  );
}

// ─── Spinner ──────────────────────────────────────────────────────────────────
function Spinner({ size = 20, color = 'currentColor' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" style={{ animation: 'sf-spin 0.8s linear infinite' }}>
      <style>{`@keyframes sf-spin { to { transform: rotate(360deg); } }`}</style>
      <circle cx="12" cy="12" r="10" stroke={color} strokeWidth="3" strokeOpacity="0.25" />
      <path d="M12 2a10 10 0 0 1 10 10" stroke={color} strokeWidth="3" strokeLinecap="round" />
    </svg>
  );
}

// ─── Coluna esquerda (brand) ──────────────────────────────────────────────────
function LoginBrand() {
  return (
    <div style={{
      background: 'linear-gradient(160deg, var(--brand-700) 0%, var(--brand-900) 100%)',
      color: 'var(--white)',
      padding: '48px 56px',
      display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
      position: 'relative', overflow: 'hidden',
    }}>
      <BrandPattern />
      <Logo variant="light" size={30} />

      <div style={{ position: 'relative', zIndex: 1 }}>
        <div style={{
          fontSize: 13, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase',
          color: 'rgba(255,255,255,0.55)', marginBottom: 16
        }}>
          Painel de gestão
        </div>
        <h2 style={{
          fontSize: 46, fontWeight: 700, lineHeight: 1.1, letterSpacing: '-0.025em',
          margin: 0, maxWidth: 480, color: 'var(--white)'
        }}>
          A operação<br/>completa da sua<br/>rede em um só<br/>lugar.
        </h2>
        <p style={{
          fontSize: 16, lineHeight: 1.55, marginTop: 20,
          color: 'rgba(255,255,255,0.7)', maxWidth: 420
        }}>
          Vendas, estoque, metas e financeiro — sincronizados,
          em tempo real, em todas as lojas.
        </p>
      </div>

      <div style={{ position: 'relative', zIndex: 1, display: 'flex', gap: 36 }}>
        <BrandStat n="99,9%" l="uptime" />
        <BrandStat n="tempo real" l="atualização" />
      </div>
    </div>
  );
}

function BrandStat({ n, l }) {
  return (
    <div>
      <div className="mono" style={{ fontSize: 26, fontWeight: 700, letterSpacing: '-0.02em' }}>{n}</div>
      <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.55)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600, marginTop: 4 }}>{l}</div>
    </div>
  );
}

function BrandPattern() {
  return (
    <>
      <div style={{
        position: 'absolute', top: -120, right: -120, width: 380, height: 380,
        background: 'radial-gradient(circle, rgba(77,143,227,0.25), transparent 70%)',
        borderRadius: '50%', filter: 'blur(20px)',
      }}/>
      <div style={{
        position: 'absolute', bottom: -160, left: -100, width: 420, height: 420,
        background: 'radial-gradient(circle, rgba(11,105,199,0.4), transparent 70%)',
        borderRadius: '50%', filter: 'blur(30px)',
      }}/>
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.06 }}>
        <defs>
          <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
            <path d="M 40 0 L 0 0 0 40" fill="none" stroke="white" strokeWidth="0.5"/>
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill="url(#grid)" />
      </svg>
    </>
  );
}

Object.assign(window, { Login, Spinner });
