const { useState } = React;

window.LoginView = function({ setProfile, setView, onLogin, setUser }) {
    const [emailOrAlias, setEmailOrAlias] = useState('');
    const [password, setPassword] = useState('');
    const [loading, setLoading] = useState(false);
    const [errorMsg, setErrorMsg] = useState('');

    const isLogoEnabled = window.SHIFT_CONFIG?.showCompanyLogo !== false && window.SHIFT_CONFIG?.showCompanyLogo !== 0;
    const logoToDisplay = isLogoEnabled ? (window.SHIFT_CONFIG?.companyLogo || '') : '';
    const companyTitle = window.SHIFT_CONFIG?.companyName || 'Shift Central';

    const handleSubmit = async (e) => {
        e.preventDefault();
        setErrorMsg('');
        setLoading(true);

        try {
            const res = await window.apiCall('login', {
                email_or_alias: emailOrAlias,
                password: password
            });

            if (res && res.success && res.profile) {
                const profile = res.profile;

                // 1. Guardar sesión y estampa de tiempo
                try {
                    localStorage.setItem('shift_user', JSON.stringify(profile));
                    localStorage.setItem('shift_session_time', Date.now().toString());
                } catch (eStorage) {}

                // 2. Asignar perfil al estado central
                const loginFn = setProfile || onLogin || setUser;
                if (typeof loginFn === 'function') {
                    loginFn(profile);
                }

                if (typeof setView === 'function') {
                    const r = (profile.role || profile.role_name || '').toLowerCase();
                    const isOwnerOrAdmin = r === 'propietario' || r === 'admin' || r === 'dueño' || window.SHIFT_CONFIG?.isMaster;
                    setView(isOwnerOrAdmin ? 'admin' : 'dashboard');
                }
            } else {
                setErrorMsg(res?.error || "Credenciales incorrectas.");
            }
        } catch (err) {
            setErrorMsg("Error de conexión con el servidor: " + err.message);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="min-h-screen bg-slate-950 flex items-center justify-center p-4 sm:p-6 relative overflow-hidden">
            <div className="absolute top-1/4 left-1/4 w-96 h-96 bg-indigo-600/10 rounded-full blur-3xl pointer-events-none"></div>
            <div className="absolute bottom-1/4 right-1/4 w-96 h-96 bg-emerald-600/10 rounded-full blur-3xl pointer-events-none"></div>

            <div className="bg-white w-full max-w-md rounded-[3rem] p-8 sm:p-10 shadow-2xl space-y-6 relative z-10 border border-slate-100 fade-in">
                <div className="text-center space-y-2">
                    {logoToDisplay ? (
                        <div className="flex justify-center mb-4">
                            <img 
                                src={logoToDisplay} 
                                alt={companyTitle} 
                                className="h-16 sm:h-20 w-auto object-contain max-w-[240px] transition-all" 
                            />
                        </div>
                    ) : (
                        <div className="w-16 h-16 bg-indigo-50 text-indigo-600 rounded-3xl flex items-center justify-center mx-auto mb-4 shadow-inner">
                            <svg className="w-8 h-8" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" 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"></path>
                            </svg>
                        </div>
                    )}

                    <h1 className="text-2xl font-black text-slate-900 tracking-tight uppercase">
                        {companyTitle}
                    </h1>
                    <p className="text-[10px] font-black uppercase tracking-widest text-slate-400">
                        Acceso a Portal de Asistencia y Turnos
                    </p>
                </div>

                {errorMsg && (
                    <div className="p-3.5 bg-red-50 border border-red-200 text-red-600 rounded-2xl text-xs font-bold text-center">
                        {errorMsg}
                    </div>
                )}

                <form onSubmit={handleSubmit} className="space-y-4">
                    <div>
                        <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Usuario / Alias / Correo</label>
                        <input 
                            type="text" 
                            value={emailOrAlias} 
                            onChange={e => setEmailOrAlias(e.target.value)} 
                            placeholder="Ej. varguello o correo@empresa.com" 
                            className="w-full p-4 bg-slate-50 border rounded-2xl font-bold text-xs outline-none focus:border-indigo-500 transition-colors" 
                            required 
                            autoFocus
                        />
                    </div>

                    <div>
                        <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Contraseña / PIN</label>
                        <input 
                            type="password" 
                            value={password} 
                            onChange={e => setPassword(e.target.value)} 
                            placeholder="••••••••" 
                            className="w-full p-4 bg-slate-50 border rounded-2xl font-bold text-xs outline-none focus:border-indigo-500 transition-colors" 
                            required 
                        />
                    </div>

                    <button 
                        type="submit" 
                        disabled={loading}
                        className="w-full py-4 bg-indigo-600 hover:bg-indigo-700 text-white font-black rounded-2xl uppercase tracking-widest text-xs shadow-xl active:scale-95 transition-all flex items-center justify-center"
                    >
                        {loading ? (
                            <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                        ) : (
                            "Ingresar"
                        )}
                    </button>
                </form>

                <div className="text-center pt-2">
                    <p className="text-[9px] text-slate-400 font-bold uppercase tracking-widest">
                        Shift Marcas • Control Operativo Empresarial
                    </p>
                </div>
            </div>
        </div>
    );
};