
const { useState } = React;

function LoginScreen({ onLogin }) {
  const isMobile = useViewportMatch(960);
  const isCompact = useViewportMatch(640);
  const [selectedRole, setSelectedRole] = useState(null);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [showPass, setShowPass] = useState(false);
  const [error, setError] = useState('');

  const roles = [
    { id:'operator', label:'Operador', desc:'Acceso a cursos y seguimiento personal', icon: (
      <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
        <circle cx="11" cy="7" r="4.5" stroke="currentColor" strokeWidth="1.8"/>
        <path d="M2.5 19.5C2.5 15 6 13 11 13C16 13 19.5 15 19.5 19.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
      </svg>
    )},
    { id:'supervisor', label:'Supervisor', desc:'Monitoreo de equipo y cumplimiento', icon: (
      <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
        <circle cx="8" cy="7" r="3.5" stroke="currentColor" strokeWidth="1.8"/>
        <path d="M2 18C2 14.5 4.5 13 8 13" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
        <circle cx="16" cy="7" r="3.5" stroke="currentColor" strokeWidth="1.8"/>
        <path d="M14 13C16.5 13 20 14.5 20 18" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
      </svg>
    )},
    { id:'admin', label:'Administrador', desc:'Gestión completa de la plataforma', icon: (
      <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
        <path d="M11 2L19 5.5V11C19 15.5 15.5 19.5 11 21C6.5 19.5 3 15.5 3 11V5.5Z" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round"/>
        <polyline points="7.5,11.5 10,14 14.5,9" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    )},
  ];

  const defaultEmails = { operator:'jperez@soitel.cl', supervisor:'mrodriguez@soitel.cl', admin:'sadmin@soitel.cl' };
  const roleMap = { OPERATOR: 'operator', SUPERVISOR: 'supervisor', ADMIN: 'admin' };

  const handleRoleSelect = (roleId) => {
    setSelectedRole(roleId);
    setEmail(defaultEmails[roleId]);
    setError('');
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!selectedRole || !email || !password) return;
    setLoading(true);
    setError('');

    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });

      const data = await response.json();
      if (!response.ok || data.error) {
        setError(data.error || 'No fue posible iniciar sesión.');
        return;
      }

      const backendRole = roleMap[data.user?.role] || null;
      if (!backendRole) {
        setError('El usuario no tiene un rol válido.');
        return;
      }

      if (backendRole !== selectedRole) {
        setError('El rol seleccionado no coincide con tu cuenta.');
        return;
      }

      onLogin(backendRole, data.user);
    } catch (submitError) {
      console.error('Error de autenticación:', submitError);
      setError('No fue posible validar tus credenciales.');
    } finally {
      setLoading(false);
    }
  };

  // Dot pattern for left panel
  const dots = [];
  for (let r = 0; r < 18; r++) {
    for (let c = 0; c < 22; c++) {
      dots.push({ x: c * 28 + 14, y: r * 28 + 14, key: `${r}-${c}` });
    }
  }

  return (
    <div style={{ display:'flex', flexDirection:isMobile ? 'column' : 'row', minHeight:'100vh', fontFamily:'Outfit,sans-serif' }}>
      {/* LEFT PANEL */}
      <div style={{ width:isMobile ? '100%' : '50%', minHeight:isMobile ? 'auto' : '100vh', background:`linear-gradient(145deg, #0C4A36 0%, #136B4D 50%, #1B9970 100%)`,
        position:'relative', overflow:'hidden', display:'flex', flexDirection:'column', justifyContent:'center', padding:isCompact ? '36px 20px' : isMobile ? '44px 28px' : '60px 56px' }}>
        
        {/* Dot grid */}
        <svg style={{ position:'absolute', inset:0, width:'100%', height:'100%', pointerEvents:'none' }}>
          {dots.map(d => <circle key={d.key} cx={d.x} cy={d.y} r="1.2" fill="white" opacity="0.08"/>)}
        </svg>

        {/* Radial glow top right */}
        <div style={{ position:'absolute', top:'-10%', right:'-10%', width:'60%', height:'60%',
          background:'radial-gradient(circle, rgba(27,153,112,0.4) 0%, transparent 70%)', pointerEvents:'none' }}/>

        {/* Content */}
        <div style={{ position:'relative', zIndex:1 }}>
          {/* Logo */}
          <div style={{ marginBottom:48 }}>
            <Logo dark={true} />
          </div>

          {/* Headline */}
          <h1 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:800, fontSize:isCompact ? 30 : isMobile ? 34 : 38, color:'white',
            lineHeight:1.1, margin:'0 0 16px', letterSpacing:'-0.02em' }}>
            Capacitación<br/>
            <span style={{ color:'rgba(255,255,255,0.65)' }}>profesional en</span><br/>
            televigilancia
          </h1>
          <p style={{ fontSize:isCompact ? 14 : 16, color:'rgba(255,255,255,0.6)', lineHeight:1.6, maxWidth:340, margin:`0 0 ${isMobile ? 32 : 56}px` }}>
            Desarrolla las competencias técnicas y operacionales que el mercado de la seguridad electrónica requiere.
          </p>

          {/* Stats grid */}
          <div style={{ display:'grid', gridTemplateColumns:isCompact ? '1fr' : 'repeat(2, minmax(0, 1fr))', gap:isCompact ? 12 : 20 }}>
            {[
              { n:'22', label:'Cursos disponibles' },
              { n:'75h', label:'Horas de contenido' },
              { n:'4', label:'Niveles de certificación' },
              { n:'100%', label:'Online y a tu ritmo' },
            ].map(s => (
              <div key={s.label} style={{ background:'rgba(255,255,255,0.08)', borderRadius:12,
                border:'1px solid rgba(255,255,255,0.12)', padding:'16px 20px' }}>
                <div style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:800, fontSize:26, color:'white', lineHeight:1 }}>{s.n}</div>
                <div style={{ fontSize:12, color:'rgba(255,255,255,0.55)', marginTop:4 }}>{s.label}</div>
              </div>
            ))}
          </div>

          {/* Soitel branding */}
          <div style={{ marginTop:isMobile ? 32 : 56, display:'flex', alignItems:'center', gap:10 }}>
            <div style={{ width:32, height:1, background:'rgba(255,255,255,0.2)' }}/>
            <span style={{ fontSize:11, color:'rgba(255,255,255,0.35)', letterSpacing:'0.1em', textTransform:'uppercase', fontFamily:'DM Mono,monospace' }}>
              Soitel · Seguridad Electrónica
            </span>
          </div>
        </div>
      </div>

      {/* RIGHT PANEL */}
      <div style={{ flex:1, display:'flex', flexDirection:'column', justifyContent:'center', alignItems:'center',
        padding:isCompact ? '28px 20px 36px' : isMobile ? '36px 28px 44px' : '48px 56px', background:'#FAFBFA', overflowY:'auto' }}>
        <div style={{ width:'100%', maxWidth:380 }}>
          <h2 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:800, fontSize:26, color:'#0E1F18', margin:'0 0 6px' }}>
            Ingresa a tu cuenta
          </h2>
          <p style={{ fontSize:14, color:'#4A6B5E', margin:'0 0 32px' }}>
            Selecciona tu rol e ingresa con un usuario creado en la plataforma.
          </p>

          {/* Role selector */}
          <div style={{ marginBottom:24 }}>
            <label style={{ fontSize:12, fontWeight:500, color:'#2D4A3E', display:'block', marginBottom:10, letterSpacing:'0.04em', textTransform:'uppercase' }}>
              Tipo de acceso
            </label>
            <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
              {roles.map(r => (
                <button key={r.id} onClick={() => handleRoleSelect(r.id)}
                  style={{ display:'flex', alignItems:'center', gap:14, padding:'12px 16px', borderRadius:10,
                    border: selectedRole === r.id ? `2px solid #1B9970` : `1.5px solid #DCE5DF`,
                    background: selectedRole === r.id ? '#E8F5F0' : '#fff',
                    cursor:'pointer', textAlign:'left', transition:'all 0.15s',
                    color: selectedRole === r.id ? '#0C4A36' : '#4A6B5E' }}>
                  <div style={{ color: selectedRole === r.id ? '#1B9970' : '#8AAB9E', flexShrink:0 }}>
                    {r.icon}
                  </div>
                  <div>
                    <div style={{ fontSize:14, fontWeight:600, color: selectedRole === r.id ? '#0C4A36' : '#0E1F18' }}>{r.label}</div>
                    <div style={{ fontSize:11, color:'#8AAB9E', marginTop:1 }}>{r.desc}</div>
                  </div>
                  {selectedRole === r.id && (
                    <div style={{ marginLeft:'auto', flexShrink:0 }}>
                      <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
                        <circle cx="9" cy="9" r="8" fill="#1B9970"/>
                        <polyline points="5,9.5 7.5,12 13,6.5" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                    </div>
                  )}
                </button>
              ))}
            </div>
          </div>

          {/* Form */}
          <form onSubmit={handleSubmit}>
            <div style={{ marginBottom:14 }}>
              <label style={{ fontSize:12, fontWeight:500, color:'#2D4A3E', display:'block', marginBottom:6, letterSpacing:'0.04em', textTransform:'uppercase' }}>
                Correo corporativo
              </label>
              <input type="email" value={email} onChange={e => setEmail(e.target.value)}
                placeholder="usuario@soitel.cl"
                style={{ width:'100%', padding:'11px 14px', borderRadius:8,
                  border:`1.5px solid ${email ? '#1B9970' : '#DCE5DF'}`,
                  fontSize:14, fontFamily:'Outfit,sans-serif', color:'#0E1F18',
                  background:'#fff', outline:'none', transition:'border-color 0.15s',
                  boxSizing:'border-box' }}/>
            </div>
            <div style={{ marginBottom:24, position:'relative' }}>
              <label style={{ fontSize:12, fontWeight:500, color:'#2D4A3E', display:'block', marginBottom:6, letterSpacing:'0.04em', textTransform:'uppercase' }}>
                Contraseña
              </label>
              <input type={showPass ? 'text' : 'password'} value={password}
                onChange={e => setPassword(e.target.value)} placeholder="••••••••"
                style={{ width:'100%', padding:'11px 40px 11px 14px', borderRadius:8,
                  border:`1.5px solid #DCE5DF`, fontSize:14, fontFamily:'Outfit,sans-serif',
                  color:'#0E1F18', background:'#fff', outline:'none', boxSizing:'border-box' }}/>
              <button type="button" onClick={() => setShowPass(!showPass)}
                style={{ position:'absolute', right:12, top:34, background:'none', border:'none',
                  cursor:'pointer', color:'#8AAB9E', padding:0 }}>
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                  {showPass
                    ? <><path d="M1,8 C3,4 5,3 8,3 C11,3 13,4 15,8 C13,12 11,13 8,13 C5,13 3,12 1,8 Z" stroke="currentColor" strokeWidth="1.5"/><circle cx="8" cy="8" r="2.5" stroke="currentColor" strokeWidth="1.5"/></>
                    : <><path d="M1,8 C3,4 5,3 8,3 C11,3 13,4 15,8 C13,12 11,13 8,13 C5,13 3,12 1,8 Z" stroke="currentColor" strokeWidth="1.5"/><circle cx="8" cy="8" r="2.5" stroke="currentColor" strokeWidth="1.5"/><line x1="2" y1="2" x2="14" y2="14" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></>
                  }
                </svg>
              </button>
            </div>

            {error && (
              <div style={{ marginBottom:16, border:'1px solid rgba(217,79,79,0.25)', background:'#FDECEC', color:'#A83030', borderRadius:10, padding:'10px 12px', fontSize:13 }}>
                {error}
              </div>
            )}

            <button type="submit" disabled={!selectedRole || loading}
              style={{ width:'100%', padding:'13px 0', borderRadius:8, border:'none',
                background: selectedRole ? 'linear-gradient(135deg, #1B9970, #136B4D)' : '#DCE5DF',
                color: selectedRole ? 'white' : '#8AAB9E', fontSize:15, fontWeight:600,
                fontFamily:'Outfit,sans-serif', cursor: selectedRole ? 'pointer' : 'not-allowed',
                transition:'all 0.2s', boxShadow: selectedRole ? '0 4px 16px rgba(27,153,112,0.3)' : 'none',
                display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
              {loading ? (
                <>
                  <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{ animation:'spin 0.8s linear infinite' }}>
                    <circle cx="8" cy="8" r="6" stroke="rgba(255,255,255,0.3)" strokeWidth="2"/>
                    <path d="M8 2 A6 6 0 0 1 14 8" stroke="white" strokeWidth="2" strokeLinecap="round"/>
                  </svg>
                  Verificando...
                </>
              ) : 'Ingresar a la plataforma'}
            </button>
          </form>

          <p style={{ textAlign:'center', fontSize:12, color:'#8AAB9E', marginTop:20 }}>
            ¿Olvidaste tu contraseña? <a href="#" style={{ color:'#1B9970', textDecoration:'none', fontWeight:500 }}>Recuperar acceso</a>
          </p>
        </div>
      </div>

      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
}

Object.assign(window, { LoginScreen });
