const { useState } = React;

window.LoginView = function({ setView, setProfile, hasUsers }) {
    const [email, setEmail] = useState('');
    const [pass, setPass] = useState('');
    const [name, setName] = useState('');
    const [error, setError] = useState('');

    const handleLogin = async (e) => {
        e.preventDefault();
        setError('');
        
        // Llamada a la API unificada para login (soporta Alias, Email o Código de trabajador)
        const res = await window.apiCall('login', { email_or_alias: email, password: pass });
        if (res.success) {
            const found = res.profile;
            setProfile(found); 
            localStorage.setItem('shift_active_session', JSON.stringify({ profile: found, expiresAt: Date.now() + (9 * 60 * 60 * 1000) }));
            setView(found.role === 'admin' || found.role === 'dueño' || found.role === 'propietario' ? 'admin' : 'dashboard');
        } else {
            setError(res.error || "Credenciales incorrectas.");
        }
    };

    return (
        <div className="flex flex-col items-center justify-center min-h-screen p-6 bg-slate-900">
            <div className="w-full max-w-md bg-white rounded-[3rem] p-10 shadow-2xl border-t-[12px] border-indigo-600 fade-in">
                <div className="text-center mb-10">
                    <svg className="w-12 h-12 text-indigo-600 mx-auto mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002-2zm10-10V7a4 4 0 00-8 0v4h8z"/></svg>
                    <h1 className="text-3xl font-black text-slate-800 tracking-tighter uppercase">{(window.SHIFT_CONFIG ? window.SHIFT_CONFIG.companyName : "Shift Marcas")}</h1>
                    <p className="text-slate-400 text-[10px] font-black uppercase tracking-widest mt-1">Acceso a Portal de Asistencia</p>
                </div>
                <form onSubmit={handleLogin} className="space-y-4">
                    <input type="text" placeholder="Alias, Correo o Código de Trabajador" value={email} onChange={e=>setEmail(e.target.value)} className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none text-slate-800 font-bold" required />
                    <input type="password" placeholder="Contraseña / PIN" value={pass} onChange={e=>setPass(e.target.value)} className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none text-slate-800 font-bold" required />
                    {error && <div className="p-3 bg-red-50 text-red-600 text-xs font-bold rounded-xl text-center">{error}</div>}
                    <button className="w-full py-5 bg-indigo-600 text-white font-black rounded-2xl shadow-xl uppercase tracking-widest text-xs active:scale-95 transition-all">Ingresar</button>
                </form>
            </div>
        </div>
    );
};