// Caririaçu Guincho — Login Screen

const { useState: useStateL, useEffect: useEffectL } = React;

const LoginScreen = ({ onLogin }) => {
  const [email, setEmail] = useStateL('');
  const [pass, setPass] = useStateL('');
  const [loading, setLoading] = useStateL(false);
  const [err, setErr] = useStateL('');
  const [isMobile, setIsMobile] = useStateL(window.innerWidth < 768);
  useEffectL(() => {
    const h = () => setIsMobile(window.innerWidth < 768);
    window.addEventListener('resize', h);
    return () => window.removeEventListener('resize', h);
  }, []);

  const handleLogin = async () => {
    if (!email || !pass) { setErr('Informe e-mail e senha.'); return; }
    setLoading(true); setErr('');
    const { error } = await auth.signIn(email.trim(), pass);
    setLoading(false);
    if (error) {
      const msg = error.message?.includes('Invalid login') ? 'E-mail ou senha inválidos' : (error.message || 'Erro ao entrar');
      setErr(msg);
      return;
    }
    showToast('Bem-vindo!', 'success');
    if (onLogin) onLogin();
  };

  const handleForgot = async () => {
    if (!email) { setErr('Informe seu e-mail no campo acima primeiro.'); return; }
    const { error } = await sb.auth.resetPasswordForEmail(email.trim());
    if (error) showToast(error.message, 'error');
    else showToast('Link de recuperação enviado para seu e-mail!', 'success');
  };

  return (
    <div style={{
      minHeight: '100vh', minHeight: '100dvh',
      display: 'flex', flexDirection: isMobile ? 'column' : 'row',
      fontFamily: 'Inter, sans-serif', background: 'linear-gradient(135deg, #0F172A 0%, #1E3A5F 60%, #0F4C75 100%)',
      paddingTop: isMobile ? 'env(safe-area-inset-top)' : 0,
      paddingBottom: isMobile ? 'env(safe-area-inset-bottom)' : 0
    }}>
      {/* Left panel — desktop only com slogan completo, mobile só com logo compacto */}
      <div style={{
        flex: isMobile ? 'none' : 1,
        background: isMobile ? 'transparent' : 'linear-gradient(135deg, #0F172A 0%, #1E3A5F 60%, #0F4C75 100%)',
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        padding: isMobile ? '32px 24px 16px' : 48,
        position: 'relative', overflow: 'hidden', minWidth: 0
      }}>
        {!isMobile && [[320, -60, 320, '0.06'], [200, 60, 200, '0.04'], [-80, 400, 300, '0.05']].map(([x,y,s,o],i)=>(
          <div key={i} style={{ position:'absolute', left:x, top:y, width:s, height:s, borderRadius:'50%', border:`1px solid rgba(245,158,11,${o})`, pointerEvents:'none' }}/>
        ))}
        <img src="logo.png" alt="Caririaçu Guincho" style={{
          width: isMobile ? 130 : 220, height: isMobile ? 130 : 220,
          borderRadius: '50%', objectFit: 'cover', transform: 'scale(1.06)',
          marginBottom: isMobile ? 16 : 24,
          boxShadow: '0 0 0 4px rgba(245,158,11,0.5), 0 12px 40px rgba(0,0,0,0.45)'
        }} />
        <div style={{ maxWidth: 420, textAlign: 'center' }}>
          <div style={{ fontSize: isMobile ? 22 : 30, fontWeight: 800, color: '#fff', fontFamily: 'DM Sans, sans-serif', letterSpacing: '-0.5px', marginBottom: 6 }}>Caririaçu Guincho</div>
          <div style={{ fontSize: isMobile ? 11 : 13, color: '#F59E0B', fontWeight: 600, letterSpacing: '2px', marginBottom: isMobile ? 0 : 28 }}>RAPIDEZ · SEGURANÇA · CONFIANÇA</div>
          {!isMobile && (
            <>
              <div style={{ fontSize: 22, fontWeight: 700, color: '#fff', fontFamily: 'DM Sans, sans-serif', marginBottom: 14, lineHeight: 1.3 }}>
                Centraliza. Organiza.<br/>Cresce com você.
              </div>
              <div style={{ fontSize: 14, color: '#94A3B8', lineHeight: 1.7 }}>
                Gestão completa de assistências veiculares, frota, vistoria digital, financeiro e relatórios — tudo em um único painel.
              </div>
            </>
          )}
        </div>
        {!isMobile && (
          <div style={{ display: 'flex', gap: 20, marginTop: 36, flexWrap: 'wrap', justifyContent: 'center' }}>
            {['Vistoria Digital','Checklist','Assinatura','Relatórios PDF'].map(f=>(
              <div key={f} style={{ display:'flex', alignItems:'center', gap:6, fontSize:12, color:'rgba(255,255,255,0.6)' }}>
                <Icon name="check" size={13} color="#F59E0B"/>{f}
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Right panel — formulário de login */}
      <div style={{
        width: isMobile ? '100%' : 440,
        flex: isMobile ? 1 : 'none',
        background: '#F8FAFC',
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        padding: isMobile ? '24px 24px 60px' : 48,
        flexShrink: 0, position: 'relative',
        borderTopLeftRadius: isMobile ? 24 : 0,
        borderTopRightRadius: isMobile ? 24 : 0
      }}>
        <div style={{ width:'100%', maxWidth:360 }}>
          <div style={{ marginBottom:32 }}>
            <div style={{ fontSize:24, fontWeight:700, color:'#0F172A', fontFamily:'DM Sans, sans-serif', marginBottom:6 }}>Entrar na sua conta</div>
            <div style={{ fontSize:14, color:'#64748B' }}>Use suas credenciais para acessar o painel</div>
          </div>

          <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
            <Input label="E-mail" type="email" placeholder="seu@email.com" value={email} onChange={e=>setEmail(e.target.value)}/>
            <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
              <Input label="Senha" type="password" placeholder="••••••••" value={pass} onChange={e=>setPass(e.target.value)}/>
              <button style={{ background:'none', border:'none', cursor:'pointer', fontSize:13, color:'#3B82F6', alignSelf:'flex-end', padding:0, fontFamily:'Inter, sans-serif' }}
                onClick={handleForgot}>
                Esqueci minha senha
              </button>
            </div>

            {err && <div style={{ background:'#FEF2F2', color:'#DC2626', borderRadius:8, padding:'10px 14px', fontSize:13, border:'1px solid #FCA5A5' }}>{err}</div>}

            <button onClick={handleLogin} disabled={loading} style={{
              padding:'13px', borderRadius:10, background: loading ? '#FCD34D' : '#F59E0B',
              border:'none', cursor: loading ? 'wait' : 'pointer',
              fontSize:15, fontWeight:700, color:'#0F172A', fontFamily:'DM Sans, sans-serif',
              boxShadow:'0 2px 8px rgba(245,158,11,0.3)', transition:'all 0.2s',
              display:'flex', alignItems:'center', justifyContent:'center', gap:8
            }}>
              {loading ? (
                <><span style={{ display:'inline-block', width:16, height:16, border:'2px solid #0F172A', borderTopColor:'transparent', borderRadius:'50%', animation:'spin 0.7s linear infinite' }}/> Entrando...</>
              ) : 'Entrar'}
            </button>

            <div style={{ textAlign:'center', fontSize:12, color:'#94A3B8', marginTop:4 }}>
              Acesso seguro via Supabase Auth
            </div>
          </div>
        </div>
        <div style={{
          position:'absolute', bottom:20, left:0, right:0, textAlign:'center',
          fontSize:11, color:'#94A3B8', fontFamily:'Inter, sans-serif', letterSpacing:'0.3px'
        }}>
          © 2026 · Desenvolvido por <span style={{ color:'#F59E0B', fontWeight:600 }}>JuFlow Digital</span>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { LoginScreen });
