const { useState, useEffect, useRef, useMemo } = React;

// ==========================================
// COMPONENTE: VISTA DE LOGIN
// ==========================================
function LoginView({ setView, setProfile, hasUsers, allUsers }) {
    const [email, setEmail] = useState('');
    const [pass, setPass] = useState('');
    const [name, setName] = useState('');
    const [error, setError] = useState('');
    const isSetup = !hasUsers;

    const handleLogin = async (e) => {
        e.preventDefault();
        if (isSetup) {
            const admin = { 
                name, 
                email: email.toLowerCase().trim(), 
                password: pass, 
                role: 'admin', 
                status: 'activo', 
                hiringDate: window.getNICDate(), 
                vacationDaysUsed: 0, 
                overrideCheckOut: false 
            };
            const ref = await db.collection('artifacts').doc(appId).collection('public').doc('data').collection('users').add(admin);
            const p = { id: ref.id, ...admin };
            setProfile(p); 
            localStorage.setItem('shift_session_v4', JSON.stringify(p)); 
            setView('admin');
        } else {
            const found = allUsers.find(u => u.email === email.toLowerCase().trim() && u.password === pass);
            if (found) {
                if (found.status === 'baja') return setError("Cuenta desactivada por administración.");
                setProfile(found); 
                localStorage.setItem('shift_session_v4', JSON.stringify(found));
                setView(found.role === 'admin' ? 'admin' : 'dashboard');
            } else setError("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">
                    <Icon name="lock" className="w-12 h-12 text-indigo-600 mx-auto mb-4" />
                    <h1 className="text-3xl font-black text-slate-800 tracking-tighter uppercase">{isSetup ? "Setup Maestro" : "Shift Marcas"}</h1>
                    <p className="text-slate-400 text-[10px] font-black uppercase tracking-widest mt-1">Nicaragua (UTC-6)</p>
                </div>
                <form onSubmit={handleLogin} className="space-y-4">
                    {isSetup && <input type="text" placeholder="Nombre Completo Admin" value={name} onChange={e=>setName(e.target.value)} className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none" required />}
                    <input type="email" placeholder="Correo Corporativo" 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" required />
                    <input type="password" placeholder="Contraseña" 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" 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>
    );
}

// ==========================================
// COMPONENTE: DASHBOARD DEL CONSULTOR
// ==========================================
function UserDashboard({ profile, logs, reminders = [], onLogout, setView, allRoles }) {
    const [status, setStatus] = useState('fuera');
    const [showCam, setShowCam] = useState(false);
    const [purpose, setPurpose] = useState('');
    const [clientName, setClientName] = useState('');
    const [loadingMark, setLoadingMark] = useState(false);
    const videoRef = useRef(null);
    const canvasRef = useRef(null);

    const todayStr = window.getNICDate();
    const todayLogs = useMemo(() => logs.filter(l => l.date === todayStr).sort((a,b) => a.timestamp - b.timestamp), [logs, todayStr]);

    useEffect(() => {
        if (todayLogs.length > 0) setStatus(todayLogs[todayLogs.length - 1].type);
        else setStatus('fuera');
    }, [todayLogs]);

    // Filtrar notificaciones activas para este usuario
    const activeReminders = useMemo(() => {
        const now = Date.now();
        return reminders.filter(r => 
            r.targetUsers.includes(profile.id) && 
            !r.completedBy[profile.id] &&
            (!r.expiresAt || r.expiresAt > now)
        );
    }, [reminders, profile.id]);

    const markReminderCompleted = async (rId) => {
        try {
            const rRef = db.collection('artifacts').doc(appId).collection('public').doc('data').collection('reminders').doc(rId);
            const rDoc = await rRef.get();
            const completedBy = rDoc.data().completedBy || {};
            completedBy[profile.id] = Date.now();
            await rRef.update({ completedBy });
        } catch (e) { alert("Error al confirmar lectura."); }
    };

    // Obtener los permisos del rol actual (Soporta estructura antigua de strings)
    const userRoleConfig = useMemo(() => allRoles.find(r => (r.name || r) === profile.role), [allRoles, profile.role]);
    const permissions = userRoleConfig && userRoleConfig.permissions ? userRoleConfig.permissions : [];

    // Bloqueo de jornada si ya marcó salida (con bypass administrativo)
    const isShiftCompleted = useMemo(() => {
        const hasSalida = todayLogs.some(l => l.type === 'salida');
        return hasSalida && !profile.overrideCheckOut;
    }, [todayLogs, profile.overrideCheckOut]);

    const startAction = async (p) => {
        if (isShiftCompleted) return;
        
        // Acciones sin cámara (configurables)
        if (['almuerzo', 'vuelta_almuerzo', 'break', 'capacitacion', 'reunion', 'gestiones'].includes(p)) {
            return saveMark(p, null, null);
        }
        
        if (p === 'visita_in') {
            const name = prompt("Escriba el nombre del Cliente / Referencia:");
            if (!name) return;
            setClientName(name);
        }

        setPurpose(p); 
        setShowCam(true);
        
        const useRear = p.includes('visita');
        const constraints = { video: { facingMode: useRear ? 'environment' : 'user', width: { ideal: 1280 }, height: { ideal: 720 } } };

        try {
            const s = await navigator.mediaDevices.getUserMedia(constraints);
            if (videoRef.current) {
                videoRef.current.srcObject = s;
                if (!useRear) videoRef.current.classList.add('mirror');
                else videoRef.current.classList.remove('mirror');
            }
        } catch (err) { alert("Error al activar cámara."); setShowCam(false); }
    };

    const capture = () => {
        const canvas = canvasRef.current;
        const video = videoRef.current;
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        const ctx = canvas.getContext('2d');
        if (!purpose.includes('visita')) { ctx.translate(canvas.width, 0); ctx.scale(-1, 1); }
        ctx.drawImage(video, 0, 0);
        const photo = canvas.toDataURL('image/jpeg', 0.6);
        
        navigator.geolocation.getCurrentPosition(
            (pos) => saveMark(purpose, photo, { lat: pos.coords.latitude, lng: pos.coords.longitude }),
            () => { alert("GPS obligatorio para auditar ubicación."); setShowCam(false); },
            { enableHighAccuracy: true }
        );
    };

    const saveMark = async (type, photo, loc) => {
        setLoadingMark(true);
        try {
            await db.collection('artifacts').doc(appId).collection('public').doc('data').collection('logs').add({
                userId: profile.id, 
                userName: profile.name, 
                type, 
                timestamp: Date.now(), 
                location: loc, 
                photo, 
                client: clientName, 
                date: todayStr, 
                role: profile.role
            });

            // Si es salida, reseteamos el desbloqueo administrativo para el día siguiente
            if (type === 'salida' && profile.overrideCheckOut) {
                await db.collection('artifacts').doc(appId).collection('public').doc('data').collection('users').doc(profile.id).update({ overrideCheckOut: false });
            }

            if (videoRef.current?.srcObject) videoRef.current.srcObject.getTracks().forEach(t => t.stop());
            setShowCam(false);
            setClientName('');
        } catch (e) { alert("Error de red al guardar marca."); }
        finally { setLoadingMark(false); }
    };

    if (profile.status === 'subsidio' || profile.status === 'feriado') return (
        <div className="h-screen flex flex-col items-center justify-center p-8 text-center bg-indigo-50">
            <Icon name={profile.status === 'subsidio' ? 'heart-pulse' : 'calendar-days'} className="w-16 h-16 text-indigo-600 mb-6 animate-bounce" />
            <h1 className="text-3xl font-black uppercase text-indigo-900 tracking-tighter">Estado: {profile.status}</h1>
            <p className="text-slate-500 mt-4 font-medium uppercase text-[10px] tracking-widest">No habilitado para marcas hoy</p>
            <button onClick={onLogout} className="mt-10 px-8 py-3 bg-white border border-indigo-200 rounded-2xl font-black text-xs text-indigo-600 uppercase shadow-sm">Cerrar Sesión</button>
        </div>
    );

    return (
        <div className="max-w-md mx-auto p-6 space-y-6 pb-24 relative min-h-screen fade-in">
            {/* ALERTAS/NOTIFICACIONES PENDIENTES */}
            {activeReminders.length > 0 && (
                <div className="fixed inset-x-6 top-6 z-50 space-y-3">
                    {activeReminders.map(r => (
                        <div key={r.id} className="bg-white p-6 rounded-3xl shadow-2xl border-l-8 border-indigo-600 animate-bounce">
                            <h4 className="font-black text-indigo-950 uppercase text-xs tracking-widest">{r.title}</h4>
                            <p className="text-slate-500 text-[11px] mt-1 font-medium leading-relaxed">{r.message}</p>
                            <button onClick={() => markReminderCompleted(r.id)} className="mt-4 w-full py-3 bg-emerald-500 text-white rounded-2xl font-black uppercase text-[10px] flex items-center justify-center gap-2 active:scale-95 transition-all">
                                <Icon name="check-circle" className="w-4 h-4" /> Entendido / Completado
                            </button>
                        </div>
                    ))}
                </div>
            )}

            <header className="bg-white p-6 rounded-[2.5rem] shadow-sm border border-slate-100 flex items-center justify-between">
                <div className="flex items-center gap-4">
                    <div className="w-12 h-12 bg-indigo-600 rounded-2xl flex items-center justify-center text-white font-black text-xl shadow-lg shadow-indigo-100">{profile.name[0]}</div>
                    <div>
                        <h2 className="font-black text-slate-800 leading-none mb-1">{profile.name}</h2>
                        <p className="text-[10px] text-slate-400 font-black uppercase tracking-widest">{profile.role}</p>
                    </div>
                </div>
                <button onClick={onLogout} className="p-3 bg-slate-50 text-slate-300 hover:text-red-500 rounded-2xl transition-colors"><Icon name="log-out" /></button>
            </header>

            {profile.role === 'admin' && (
                <button onClick={() => setView('admin')} className="w-full py-4 bg-indigo-50 text-indigo-600 rounded-2xl font-black uppercase text-[10px] tracking-widest flex items-center justify-center gap-2 border border-indigo-200 hover:bg-indigo-100 transition-all">
                    <Icon name="settings" className="w-4 h-4" /> Volver al Panel Admin
                </button>
            )}

            <div className="grid gap-4">
                {isShiftCompleted ? (
                    <div className="h-72 bg-slate-100 rounded-[3rem] border-2 border-dashed border-slate-200 flex flex-col items-center justify-center text-slate-400 text-center p-8">
                        <Icon name="moon" className="w-12 h-12 mb-4" />
                        <span className="text-lg font-black uppercase tracking-tight">Jornada Finalizada</span>
                        <p className="text-[10px] font-bold uppercase mt-2 opacity-60">Se habilitará mañana a las 12:00 AM (NI)</p>
                    </div>
                ) : (status === 'fuera' || status === 'salida') ? (
                    <button onClick={() => startAction('entrada')} className="h-72 bg-emerald-500 rounded-[3.5rem] text-white flex flex-col items-center justify-center shadow-2xl active:scale-95 transition-all group">
                        <Icon name="camera" className="w-12 h-12 mb-4" />
                        <span className="text-xl font-black uppercase tracking-tighter">Entrada al Trabajo</span>
                        <p className="text-emerald-100 text-[10px] font-bold uppercase mt-2 opacity-60">Foto + Ubicación Requerida</p>
                    </button>
                ) : (
                    <div className="space-y-4">
                        <div className="bg-white p-10 rounded-[3.5rem] border-2 border-emerald-500/20 text-center shadow-sm relative">
                            <div className="flex items-center justify-center gap-2 text-emerald-600 mb-2 font-black text-xl tracking-widest">ACTIVO</div>
                            <p className="text-slate-400 text-[10px] font-bold uppercase tracking-widest">¡Que tengas un excelente día!</p>
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                            {/* BOTONES DINÁMICOS BASADOS EN LOS PERMISOS DEL ROL SELECCIONADO POR EL ADMIN */}
                            {permissions.includes('almuerzo') && (
                                <button onClick={() => startAction(status === 'almuerzo' ? 'vuelta_almuerzo' : 'almuerzo')} className={`h-32 rounded-3xl shadow-sm flex flex-col items-center justify-center font-black uppercase text-[10px] transition-all ${status === 'almuerzo' ? 'bg-orange-500 text-white shadow-orange-100' : 'bg-white text-slate-700 border'}`}>
                                    <Icon name="coffee" className="w-8 h-8 mb-2" /> {status === 'almuerzo' ? 'Regresar' : 'Almuerzo'}
                                </button>
                            )}
                            {permissions.includes('break') && (
                                <button onClick={() => startAction('break')} className="h-32 rounded-3xl shadow-sm flex flex-col items-center justify-center font-black uppercase text-[10px] bg-white text-slate-700 border">
                                    <Icon name="clock" className="w-8 h-8 mb-2" /> Break
                                </button>
                            )}
                            {permissions.includes('visita_in') && (
                                <button onClick={() => startAction(status === 'visita_in' ? 'visita_out' : 'visita_in')} className={`h-32 rounded-3xl shadow-sm flex flex-col items-center justify-center font-black uppercase text-[10px] transition-all ${status === 'visita_in' ? 'bg-blue-600 text-white animate-pulse' : 'bg-white text-slate-700 border'}`}>
                                    <Icon name="briefcase" className="w-8 h-8 mb-2" /> {status === 'visita_in' ? 'Terminar' : 'Visitar'}
                                </button>
                            )}
                            {permissions.includes('reunion') && (
                                <button onClick={() => startAction('reunion')} className="h-32 rounded-3xl shadow-sm flex flex-col items-center justify-center font-black uppercase text-[10px] bg-white text-slate-700 border">
                                    <Icon name="users" className="w-8 h-8 mb-2" /> Reunión
                                </button>
                            )}
                            {permissions.includes('capacitacion') && (
                                <button onClick={() => startAction('capacitacion')} className="h-32 rounded-3xl shadow-sm flex flex-col items-center justify-center font-black uppercase text-[10px] bg-white text-slate-700 border">
                                    <Icon name="graduation-cap" className="w-8 h-8 mb-2" /> Capacit.
                                </button>
                            )}
                            {permissions.includes('gestiones') && (
                                <button onClick={() => startAction('gestiones')} className="h-32 rounded-3xl shadow-sm flex flex-col items-center justify-center font-black uppercase text-[10px] bg-white text-slate-700 border">
                                    <Icon name="file-text" className="w-8 h-8 mb-2" /> Gestiones
                                </button>
                            )}
                        </div>
                        <button onClick={() => startAction('salida')} className="w-full py-6 bg-red-50 text-red-600 rounded-[2.5rem] font-black uppercase text-xs tracking-widest hover:bg-red-100 transition-all">Marcar Salida Final</button>
                    </div>
                )}
            </div>

            <div className="bg-white p-8 rounded-[3rem] border border-slate-100 shadow-sm max-h-[400px] overflow-y-auto no-scrollbar">
                <h3 className="font-black text-[10px] uppercase tracking-widest text-slate-400 mb-8 flex items-center gap-2 border-b pb-4"><Icon name="list" className="w-4 h-4" /> Mi Actividad de Hoy</h3>
                {todayLogs.length === 0 ? <p className="text-center py-10 text-[10px] font-black uppercase opacity-20 italic">No hay marcas registradas todavía</p> : (
                    <div className="space-y-6">
                        {todayLogs.map(l => (
                            <div key={l.timestamp} className="flex items-center gap-4 group">
                                <div className={`w-3 h-3 rounded-full ${l.type.includes('entrada') ? 'bg-emerald-500 shadow-lg shadow-emerald-100' : l.type.includes('salida') ? 'bg-red-500 shadow-lg shadow-red-100' : 'bg-indigo-400'}`}></div>
                                <div className="flex-1">
                                    <p className="text-[11px] font-black uppercase text-slate-800 leading-none">{l.type.replace('_',' ')} {l.client && <span className="text-indigo-600 font-bold block mt-1">@ {l.client}</span>}</p>
                                    <p className="text-[9px] text-slate-400 font-bold mt-1.5 uppercase tracking-tighter opacity-60">
                                        {new Date(l.timestamp).toLocaleTimeString('es-NI', {timeZone: 'America/Managua', hour:'2-digit', minute:'2-digit', hour12: true})}
                                    </p>
                                </div>
                                <Icon name="check-circle" className="w-4 h-4 text-slate-100 group-hover:text-emerald-500 transition-colors" />
                            </div>
                        ))}
                    </div>
                )}
            </div>

            {showCam && (
                <div className="fixed inset-0 bg-slate-950 z-50 flex flex-col items-center justify-center p-6 text-white fade-in">
                    <div className="camera-container w-full max-w-sm shadow-2xl">
                        <video ref={videoRef} autoPlay playsInline muted />
                        <canvas ref={canvasRef} className="hidden" />
                        <div className="absolute inset-0 pointer-events-none flex items-center justify-center">
                            <div className="w-[280px] h-[380px] border-2 border-dashed border-white/20 rounded-[4rem]"></div>
                        </div>
                    </div>
                    <div className="mt-12 flex flex-col items-center gap-6 w-full max-w-sm text-center">
                        <p className="text-[10px] font-black uppercase tracking-[0.3em] opacity-40">Protocolo Biométrico</p>
                        <div className="flex gap-4 w-full">
                            <button onClick={() => { if(videoRef.current?.srcObject) videoRef.current.srcObject.getTracks().forEach(t=>t.stop()); setShowCam(false); }} className="flex-1 py-5 bg-white/10 rounded-3xl font-black uppercase text-[10px]">Cancelar</button>
                            <button onClick={capture} disabled={loadingMark} className="flex-[2] py-5 bg-indigo-600 rounded-3xl font-black uppercase text-[10px] shadow-xl shadow-indigo-100 active:scale-95 transition-all">
                                {loadingMark ? "Procesando..." : "Capturar Marca"}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

// ==========================================
// COMPONENTE: PANEL DE ADMINISTRACIÓN
// ==========================================
function AdminDashboard({ globalUsers, logs, roles, reminders = [], setView, onLogout }) {
    const [tab, setTab] = useState('logs');
    const [searchName, setSearchName] = useState('');
    const [searchDate, setSearchDate] = useState(window.getNICDate());
    const [editingUser, setEditingUser] = useState(null);
    const [editingLog, setEditingLog] = useState(null);
    const [userToDelete, setUserToDelete] = useState(null);
    const [submitError, setSubmitError] = useState('');
    
    // Estados para Roles
    const [newRoleName, setNewRoleName] = useState('');
    const [selectedPermissions, setSelectedPermissions] = useState([]);
    const availableActions = [
        { id: 'almuerzo', label: 'Almuerzo' },
        { id: 'break', label: 'Break' },
        { id: 'visita_in', label: 'Visita Cliente' },
        { id: 'reunion', label: 'Reunión' },
        { id: 'capacitacion', label: 'Capacitación' },
        { id: 'gestiones', label: 'Gestiones' }
    ];

    // Estados para Notificaciones
    const [notifTitle, setNotifTitle] = useState('');
    const [notifBody, setNotifBody] = useState('');
    const [notifExpiry, setNotifExpiry] = useState('');
    const [targetUsers, setTargetUsers] = useState([]);

    const filteredLogs = useMemo(() => logs.filter(l => {
        const matchName = l.userName.toLowerCase().includes(searchName.toLowerCase());
        const matchDate = searchDate ? l.date === searchDate : true;
        return matchName && matchDate;
    }).sort((a,b) => b.timestamp - a.timestamp), [logs, searchName, searchDate]);

    const handleUserSubmit = async (e) => {
        e.preventDefault();
        setSubmitError('');
        const f = new FormData(e.target);
        const email = f.get('email').toLowerCase().trim();

        // VALIDACIÓN DE DUPLICIDAD
        if (!editingUser) {
            const existing = globalUsers.find(u => u.email === email);
            if (existing) {
                setSubmitError(`ADVERTENCIA: Correo ya asignado a ${existing.name} (${existing.status.toUpperCase()})`);
                return;
            }
        }

        const data = {
            name: f.get('name'), email,
            password: f.get('pass'), role: f.get('role'), status: f.get('status'),
            hiringDate: f.get('date'), vacationDaysUsed: parseInt(f.get('vused')) || 0,
            vacationStart: f.get('vs') || '', vacationEnd: f.get('ve') || '',
            overrideCheckOut: editingUser ? (editingUser.overrideCheckOut || false) : false
        };
        try {
            if(editingUser) await db.collection('artifacts').doc(appId).collection('public').doc('data').collection('users').doc(editingUser.id).update(data);
            else await db.collection('artifacts').doc(appId).collection('public').doc('data').collection('users').add(data);
            setEditingUser(null);
        } catch (err) { setSubmitError("Error al guardar datos."); }
    };

    const deleteUser = async () => {
        if (!userToDelete) return;
        try {
            await db.collection('artifacts').doc(appId).collection('public').doc('data').collection('users').doc(userToDelete.id).delete();
            setUserToDelete(null);
        } catch (err) { alert("Error al eliminar."); }
    };

    const unlockUser = async (uId) => {
        try {
            await db.collection('artifacts').doc(appId).collection('public').doc('data').collection('users').doc(uId).update({ overrideCheckOut: true });
            alert("Usuario habilitado para re-entrar hoy.");
        } catch (err) { alert("Error al desbloquear."); }
    };

    const updateLog = async (e) => {
        e.preventDefault();
        const f = new FormData(e.target);
        const newTimeStr = f.get('ntime');
        const newTimestamp = new Date(newTimeStr).getTime();
        const newDate = newTimeStr.split('T')[0];
        try {
            await db.collection('artifacts').doc(appId).collection('public').doc('data').collection('logs').doc(editingLog.id).update({
                timestamp: newTimestamp, type: f.get('ntype'), client: f.get('nclient'), edited: true, date: newDate
            });
            setEditingLog(null);
        } catch (err) { alert("Error al actualizar marca."); }
    };

    const togglePermission = (id) => {
        setSelectedPermissions(prev => prev.includes(id) ? prev.filter(p => p !== id) : [...prev, id]);
    };

    const addRole = async () => {
        if(!newRoleName) return;
        try {
            const newRoleObj = { name: newRoleName.toLowerCase().trim(), permissions: selectedPermissions };
            // Filtrar tanto objetos como strings antiguos para evitar errores
            const updated = [...roles.filter(r => (r.name || r) !== newRoleObj.name), newRoleObj];
            await db.collection('artifacts').doc(appId).collection('public').doc('data').collection('settings').doc('roles').set({ list: updated });
            setNewRoleName('');
            setSelectedPermissions([]);
        } catch (err) { alert("Error al guardar rol."); }
    };

    const sendNotification = async () => {
        if (!notifTitle || targetUsers.length === 0) return alert("Completa el título y elige al menos un usuario.");
        try {
            await db.collection('artifacts').doc(appId).collection('public').doc('data').collection('reminders').add({
                title: notifTitle,
                message: notifBody,
                expiresAt: notifExpiry ? new Date(notifExpiry).getTime() : null,
                targetUsers: targetUsers,
                completedBy: {},
                createdAt: Date.now(),
                createdBy: 'Admin'
            });
            setNotifTitle(''); setNotifBody(''); setNotifExpiry(''); setTargetUsers([]);
            alert("Notificación enviada correctamente.");
        } catch (e) { alert("Error al enviar."); }
    };

    return (
        <div className="flex flex-col h-screen bg-slate-50 fade-in text-xs">
            <nav className="bg-white p-5 flex justify-between items-center shadow-sm border-b sticky top-0 z-20">
                <div className="flex items-center gap-3 font-black text-indigo-600 uppercase tracking-tighter text-xl leading-none">Shift Admin</div>
                <div className="flex gap-2">
                    <button onClick={() => setView('dashboard')} className="px-5 py-2.5 bg-indigo-50 text-indigo-600 rounded-2xl text-[10px] font-black uppercase tracking-widest flex items-center gap-2">Vista App <Icon name="external-link" className="w-3 h-3"/></button>
                    <button onClick={onLogout} className="p-2.5 text-slate-300 hover:text-red-500 transition-colors"><Icon name="log-out" /></button>
                </div>
            </nav>

            <main className="flex-1 p-6 lg:p-10 max-w-7xl mx-auto w-full overflow-y-auto">
                <div className="flex gap-2 mb-10 bg-slate-200/50 p-1 rounded-2xl w-fit border border-slate-100">
                    <button onClick={()=>setTab('logs')} className={`px-8 py-3 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all ${tab==='logs' ? 'bg-white shadow-sm text-indigo-600 border-indigo-100' : 'text-slate-400'}`}>Auditoría</button>
                    <button onClick={()=>setTab('users')} className={`px-8 py-3 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all ${tab==='users' ? 'bg-white shadow-sm text-indigo-600 border-indigo-100' : 'text-slate-400'}`}>Personal</button>
                    <button onClick={()=>setTab('roles')} className={`px-8 py-3 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all ${tab==='roles' ? 'bg-white shadow-sm text-indigo-600 border-indigo-100' : 'text-slate-400'}`}>Roles</button>
                    <button onClick={()=>setTab('notif')} className={`px-8 py-3 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all ${tab==='notif' ? 'bg-white shadow-sm text-indigo-600 border-indigo-100' : 'text-slate-400'}`}>Avisos</button>
                </div>

                {tab === 'logs' && (
                    <div className="space-y-6">
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 bg-white p-8 rounded-[3.5rem] shadow-sm border border-slate-100">
                            <div className="space-y-1"><label className="text-[9px] font-black uppercase text-slate-400 ml-1">Buscar Consultor</label><input value={searchName} onChange={e=>setSearchName(e.target.value)} placeholder="Nombre..." className="w-full p-4 bg-slate-50 border rounded-xl outline-none font-bold" /></div>
                            <div className="space-y-1"><label className="text-[9px] font-black uppercase text-slate-400 ml-1">Fecha (NI)</label><input type="date" value={searchDate} onChange={e=>setSearchDate(e.target.value)} className="w-full p-4 bg-slate-50 border rounded-xl outline-none font-bold" /></div>
                            <div className="flex items-end"><button onClick={()=>{setSearchName(''); setSearchDate('');}} className="w-full py-4 bg-slate-100 text-slate-400 rounded-xl font-black uppercase">Limpiar Filtros</button></div>
                        </div>

                        <div className="bg-white rounded-[3.5rem] shadow-sm border border-slate-100 overflow-hidden">
                            <table className="w-full text-left">
                                <thead className="bg-slate-50 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b">
                                    <tr><th className="p-6">Colaborador</th><th className="p-6">Marca</th><th className="p-6">Fecha/Hora (12h)</th><th className="p-6">Auditoría</th><th className="p-6">Acción</th></tr>
                                </thead>
                                <tbody className="divide-y divide-slate-100">
                                    {filteredLogs.map(l => (
                                        <tr key={l.id} className="hover:bg-slate-50/50 transition-colors">
                                            <td className="p-6">
                                                <button onClick={()=>setSearchName(l.userName)} className="font-black text-indigo-600 text-sm hover:underline">{l.userName}</button>
                                            </td>
                                            <td className="p-6 uppercase font-black text-[9px]">
                                                <span className={`px-3 py-1 rounded-full ${l.type.includes('entrada') ? 'bg-emerald-50 text-emerald-600 border border-emerald-100' : l.type.includes('salida') ? 'bg-red-50 text-red-600 border border-red-100' : 'bg-slate-100 text-slate-500'}`}>
                                                    {l.type.replace('_',' ')} {l.client && `(${l.client})`}
                                                </span>
                                            </td>
                                            <td className="p-6 text-xs font-black text-slate-600 leading-tight">
                                                {new Date(l.timestamp).toLocaleString('es-NI', {timeZone: 'America/Managua', day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit', hour12: true})}
                                                {l.edited && <div className="text-[8px] text-orange-500 uppercase mt-1 italic font-black">Editado por Admin</div>}
                                            </td>
                                            <td className="p-6 flex items-center gap-4">
                                                {l.photo && <img src={l.photo} className="w-12 h-12 rounded-2xl object-cover border border-slate-100 shadow-md transform hover:scale-[3] transition-transform z-10" />}
                                                {l.location && <a href={`https://maps.google.com/?q=${l.location.lat},${l.location.lng}`} target="_blank" className="p-3 bg-indigo-50 text-indigo-600 rounded-xl hover:bg-indigo-100 transition-all border border-indigo-100 shadow-sm"><Icon name="map-pin" className="w-4 h-4" /></a>}
                                            </td>
                                            <td className="p-6">
                                                <button onClick={()=>setEditingLog(l)} className="p-2 text-slate-300 hover:text-indigo-600 transition-all"><Icon name="edit-2" /></button>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>
                )}

                {tab === 'users' && (
                    <div className="grid lg:grid-cols-3 gap-10">
                        <div className="bg-white p-10 rounded-[3.5rem] shadow-sm border border-slate-100 h-fit space-y-6">
                            <h3 className="font-black text-lg text-slate-800 uppercase tracking-tight">{editingUser ? "Editar Perfil" : "Nuevo Registro"}</h3>
                            <form onSubmit={handleUserSubmit} className="space-y-4 text-[10px] font-black uppercase text-slate-400">
                                <input name="name" defaultValue={editingUser?.name} placeholder="Nombre Completo" className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none text-slate-800" required />
                                <input name="email" defaultValue={editingUser?.email} type="email" placeholder="Email" className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none text-slate-800" required />
                                <input name="pass" defaultValue={editingUser?.password} placeholder="Contraseña" className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none text-slate-800" required />
                                <div className="grid grid-cols-2 gap-2">
                                    <div className="space-y-1">
                                        <label className="ml-1">Rol</label>
                                        <select name="role" defaultValue={editingUser?.role} className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none text-slate-800 font-bold uppercase">
                                            {roles.map(r => {
                                                const rName = r.name || r;
                                                return <option key={rName} value={rName}>{rName}</option>
                                            })}
                                            <option value="admin">ADMIN</option>
                                        </select>
                                    </div>
                                    <div className="space-y-1">
                                        <label className="ml-1">Estado</label>
                                        <select name="status" defaultValue={editingUser?.status || 'activo'} className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none text-slate-800 font-bold uppercase">
                                            <option value="activo">ACTIVO</option>
                                            <option value="baja">BAJA</option>
                                            <option value="subsidio">SUBSIDIO</option>
                                            <option value="feriado">FERIADO</option>
                                        </select>
                                    </div>
                                </div>
                                <div className="space-y-1"><label className="ml-1">Fecha Contratación</label><input name="date" type="date" defaultValue={editingUser?.hiringDate} className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none text-slate-800" required /></div>
                                <div className="grid grid-cols-2 gap-2">
                                    <div className="space-y-1"><label className="ml-1">Vacas Inicio</label><input name="vs" type="date" defaultValue={editingUser?.vacationStart} className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none text-slate-800" /></div>
                                    <div className="space-y-1"><label className="ml-1">Vacas Fin</label><input name="ve" type="date" defaultValue={editingUser?.vacationEnd} className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none text-slate-800" /></div>
                                </div>
                                <div className="space-y-1"><label className="ml-1">Días Tomados</label><input name="vused" type="number" defaultValue={editingUser?.vacationDaysUsed || 0} className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none text-slate-800" /></div>
                                {submitError && <div className="p-4 bg-red-50 text-red-600 rounded-2xl font-bold border border-red-100 leading-tight">{submitError}</div>}
                                <div className="flex gap-2 pt-4">
                                    {editingUser && <button type="button" onClick={()=>setEditingUser(null)} className="flex-1 py-4 bg-slate-100 text-slate-400 rounded-2xl font-black">CANCELAR</button>}
                                    <button className="flex-[2] py-5 bg-indigo-600 text-white font-black rounded-2xl shadow-xl shadow-indigo-100 uppercase">Guardar Perfil</button>
                                </div>
                            </form>
                        </div>
                        <div className="lg:col-span-2 space-y-4">
                            {globalUsers.map(u => (
                                <div key={u.id} className="bg-white p-6 rounded-[2.5rem] flex justify-between items-center shadow-sm border border-transparent hover:border-indigo-100 transition-all admin-card">
                                    <div className="flex items-center gap-4">
                                        <div className={`w-14 h-14 rounded-2xl flex items-center justify-center font-black text-white shadow-md ${u.status === 'activo' ? 'bg-indigo-600' : 'bg-slate-300'}`}>{u.name[0]}</div>
                                        <div>
                                            <h4 className="font-black text-slate-800 text-lg leading-tight">{u.name}</h4>
                                            <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest mt-1">
                                                {u.role} • {u.status} 
                                                {u.overrideCheckOut && <span className="text-emerald-500 font-bold ml-2">(DESBLOQUEADO)</span>}
                                            </p>
                                        </div>
                                    </div>
                                    <div className="flex gap-2">
                                        <button onClick={()=>unlockUser(u.id)} className="p-4 bg-emerald-50 text-emerald-600 hover:bg-emerald-100 rounded-2xl transition-all" title="Habilitar Re-entrada hoy"><Icon name="unlock" /></button>
                                        <button onClick={()=>setEditingUser(u)} className="p-4 bg-slate-50 text-slate-400 hover:text-indigo-600 rounded-2xl transition-all"><Icon name="edit-3" /></button>
                                        <button onClick={()=>setUserToDelete(u)} className="p-4 bg-red-50 text-red-500 hover:bg-red-600 hover:text-white rounded-2xl transition-all" title="Eliminar Permanentemente"><Icon name="trash-2" /></button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {tab === 'roles' && (
                    <div className="grid lg:grid-cols-2 gap-10 fade-in">
                        <div className="bg-white p-10 rounded-[3.5rem] shadow-sm border border-slate-100 space-y-6">
                            <h3 className="font-black text-lg text-slate-800 uppercase tracking-tight">Configurar Rol y Permisos</h3>
                            <div className="space-y-4">
                                <input value={newRoleName} onChange={e=>setNewRoleName(e.target.value)} placeholder="Nombre del Rol (ej: Ventas)" className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none font-bold uppercase focus:border-indigo-400" />
                                <div className="space-y-3">
                                    <p className="text-[9px] font-black uppercase text-slate-400 ml-1">Habilitar botones para este rol:</p>
                                    <div className="grid grid-cols-2 gap-2">
                                        {availableActions.map(action => (
                                            <button 
                                                key={action.id}
                                                onClick={() => togglePermission(action.id)}
                                                className={`p-4 rounded-2xl border-2 text-left transition-all flex items-center justify-between ${selectedPermissions.includes(action.id) ? 'border-indigo-600 bg-indigo-50 text-indigo-600' : 'border-slate-50 bg-slate-50 text-slate-400'}`}
                                            >
                                                <span className="font-black uppercase text-[10px]">{action.label}</span>
                                                {selectedPermissions.includes(action.id) && <Icon name="check-circle" className="w-4 h-4" />}
                                            </button>
                                        ))}
                                    </div>
                                </div>
                                <button onClick={addRole} className="w-full py-5 bg-indigo-600 text-white font-black rounded-2xl shadow-xl uppercase text-[10px]">Guardar Configuración</button>
                            </div>
                        </div>
                        <div className="space-y-4">
                            {roles.map(r => {
                                const rName = r.name || r;
                                const rPerms = r.permissions || [];
                                return (
                                    <div key={rName} className="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100 flex justify-between items-center group transition-all hover:border-indigo-100">
                                        <div>
                                            <h4 className="font-black text-slate-800 uppercase text-lg leading-none mb-3">{rName}</h4>
                                            <div className="flex flex-wrap gap-1">
                                                {rPerms.map(p => <span key={p} className="text-[8px] font-black uppercase bg-indigo-50 text-indigo-500 px-2 py-0.5 rounded-md border border-indigo-100">{p}</span>)}
                                                {rPerms.length === 0 && <span className="text-[8px] font-bold text-slate-300 uppercase italic">Sin permisos adicionales</span>}
                                            </div>
                                        </div>
                                        <button onClick={async () => {
                                            const updated = roles.filter(role => (role.name || role) !== rName);
                                            await db.collection('artifacts').doc(appId).collection('public').doc('data').collection('settings').doc('roles').set({ list: updated });
                                        }} className="p-4 text-slate-200 group-hover:text-red-500 transition-colors"><Icon name="x-circle" /></button>
                                    </div>
                                )
                            })}
                        </div>
                    </div>
                )}

                {/* TAB: NOTIFICACIONES */}
                {tab === 'notif' && (
                    <div className="grid lg:grid-cols-3 gap-10 fade-in">
                        <div className="bg-white p-10 rounded-[3.5rem] shadow-sm border border-slate-100 space-y-6">
                            <h3 className="font-black text-lg text-slate-800 uppercase tracking-tight">Nuevo Aviso</h3>
                            <div className="space-y-4">
                                <input value={notifTitle} onChange={e=>setNotifTitle(e.target.value)} placeholder="Título del aviso" className="w-full p-4 bg-slate-50 border-2 rounded-2xl font-bold outline-none" />
                                <textarea value={notifBody} onChange={e=>setNotifBody(e.target.value)} placeholder="Mensaje detallado..." className="w-full p-4 bg-slate-50 border-2 rounded-2xl h-32 outline-none" />
                                <div className="space-y-1">
                                    <label className="text-[9px] font-black uppercase text-slate-400 ml-1">Fecha de Expiración</label>
                                    <input type="datetime-local" value={notifExpiry} onChange={e=>setNotifExpiry(e.target.value)} className="w-full p-4 bg-slate-50 border-2 rounded-2xl outline-none font-bold" />
                                </div>
                                <div className="space-y-2">
                                    <p className="text-[9px] font-black uppercase text-slate-400 ml-1">Destinatarios:</p>
                                    <div className="max-h-48 overflow-y-auto space-y-2 p-2 bg-slate-50 rounded-2xl border-2 border-slate-100">
                                        {globalUsers.filter(u=>u.status==='activo').map(u => (
                                            <button key={u.id} onClick={() => setTargetUsers(prev => prev.includes(u.id) ? prev.filter(id => id !== u.id) : [...prev, u.id])} className={`w-full p-3 rounded-xl text-left flex items-center justify-between transition-all ${targetUsers.includes(u.id) ? 'bg-indigo-600 text-white shadow-md' : 'bg-white text-slate-600 shadow-sm border'}`}>
                                                <span className="font-bold text-[10px] uppercase">{u.name}</span>
                                                {targetUsers.includes(u.id) && <Icon name="check" className="w-4 h-4" />}
                                            </button>
                                        ))}
                                    </div>
                                </div>
                                <button onClick={sendNotification} className="w-full py-5 bg-indigo-600 text-white font-black rounded-2xl shadow-xl uppercase">Enviar Notificación</button>
                            </div>
                        </div>
                        <div className="lg:col-span-2 space-y-4">
                            <h3 className="font-black text-xs uppercase text-slate-400 ml-2 tracking-widest">Historial de Avisos</h3>
                            {reminders.sort((a,b)=>b.createdAt-a.createdAt).map(r => (
                                <div key={r.id} className="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100 flex justify-between items-start">
                                    <div className="space-y-2 w-full pr-4">
                                        <h4 className="font-black text-slate-800 uppercase text-lg leading-none">{r.title}</h4>
                                        <p className="text-slate-500 font-medium text-[11px] leading-relaxed">{r.message}</p>
                                        <div className="flex gap-2 items-center mt-2">
                                            <span className="text-[8px] font-black uppercase px-2 py-0.5 bg-slate-100 rounded text-slate-400">Enviado: {new Date(r.createdAt).toLocaleString('es-NI', {timeZone: 'America/Managua'})}</span>
                                            {r.expiresAt && <span className="text-[8px] font-black uppercase px-2 py-0.5 bg-red-50 rounded text-red-400">Expira: {new Date(r.expiresAt).toLocaleString('es-NI', {timeZone: 'America/Managua'})}</span>}
                                        </div>
                                        <div className="pt-4 mt-4 border-t border-slate-50 space-y-2">
                                            <p className="text-[9px] font-black text-indigo-600 uppercase tracking-widest">Confirmaciones de lectura:</p>
                                            <div className="flex flex-wrap gap-2">
                                                {Object.entries(r.completedBy || {}).map(([uId, ts]) => (
                                                    <div key={uId} className="px-3 py-1.5 bg-emerald-50 border border-emerald-100 rounded-xl flex items-center gap-2">
                                                        <Icon name="check-circle-2" className="w-3 h-3 text-emerald-500" />
                                                        <span className="text-[9px] font-bold text-emerald-700 uppercase">
                                                            {globalUsers.find(u=>u.id===uId)?.name || 'Usuario'} - {new Date(ts).toLocaleTimeString('es-NI', {timeZone: 'America/Managua', hour:'2-digit', minute:'2-digit', hour12:true})}
                                                        </span>
                                                    </div>
                                                ))}
                                                {Object.keys(r.completedBy || {}).length === 0 && <span className="text-[9px] text-slate-300 italic">Nadie ha completado este aviso.</span>}
                                            </div>
                                        </div>
                                    </div>
                                    <button onClick={async () => { if(confirm("¿Eliminar este aviso de forma permanente?")) await db.collection('artifacts').doc(appId).collection('public').doc('data').collection('reminders').doc(r.id).delete(); }} className="text-slate-200 hover:text-red-500 transition-colors"><Icon name="x-circle" className="w-6 h-6" /></button>
                                </div>
                            ))}
                        </div>
                    </div>
                )}
            </main>

            {/* MODALES DE CONFIRMACIÓN */}
            {userToDelete && (
                <div className="fixed inset-0 bg-slate-950/90 z-[60] flex items-center justify-center p-6 backdrop-blur-lg fade-in">
                    <div className="bg-white p-10 rounded-[3rem] w-full max-w-sm shadow-2xl text-center space-y-6">
                        <div className="w-20 h-20 bg-red-50 text-red-500 rounded-full flex items-center justify-center mx-auto mb-4">
                            <Icon name="alert-triangle" className="w-10 h-10" />
                        </div>
                        <h3 className="font-black text-xl text-slate-800 uppercase tracking-tighter">¿Eliminar Usuario?</h3>
                        <p className="text-slate-500 text-xs font-medium">Estás a punto de borrar a <b>{userToDelete.name}</b>. Esta acción es permanente y no se puede deshacer.</p>
                        <div className="flex gap-3 pt-4">
                            <button onClick={()=>setUserToDelete(null)} className="flex-1 py-4 bg-slate-100 text-slate-400 rounded-2xl font-black uppercase text-[10px]">Cancelar</button>
                            <button onClick={deleteUser} className="flex-1 py-4 bg-red-600 text-white rounded-2xl font-black uppercase text-[10px] shadow-lg shadow-red-200">Sí, Eliminar</button>
                        </div>
                    </div>
                </div>
            )}

            {editingLog && (
                <div className="fixed inset-0 bg-slate-950/80 z-50 flex items-center justify-center p-6 backdrop-blur-md fade-in">
                    <form onSubmit={updateLog} className="bg-white p-12 rounded-[3.5rem] w-full max-w-md shadow-2xl space-y-6">
                        <h3 className="font-black text-xl text-slate-800 uppercase text-center tracking-tighter">Corregir Marca Operativa</h3>
                        <div className="space-y-4">
                            <div className="space-y-1">
                                <label className="text-[9px] font-black uppercase text-slate-400 ml-1">Fecha y Hora Real</label>
                                <input name="ntime" type="datetime-local" className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none font-bold text-slate-800" required />
                            </div>
                            <div className="space-y-1">
                                <label className="text-[9px] font-black uppercase text-slate-400 ml-1">Acción</label>
                                <select name="ntype" defaultValue={editingLog.type} className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none font-bold text-slate-800">
                                    <option value="entrada">ENTRADA</option>
                                    <option value="salida">SALIDA</option>
                                    <option value="almuerzo">ALMUERZO</option>
                                    <option value="vuelta_almuerzo">REGRESO ALMUERZO</option>
                                    <option value="visita_in">INICIO VISITA</option>
                                    <option value="visita_out">FIN VISITA</option>
                                </select>
                            </div>
                            <div className="space-y-1">
                                <label className="text-[9px] font-black uppercase text-slate-400 ml-1">Cliente / Referencia</label>
                                <input name="nclient" defaultValue={editingLog.client} placeholder="Nombre cliente" className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none font-bold text-slate-800" />
                            </div>
                        </div>
                        <div className="flex gap-3 pt-6">
                            <button type="button" onClick={()=>setEditingLog(null)} className="flex-1 py-5 bg-slate-100 text-slate-400 rounded-[2rem] font-black uppercase text-[10px]">Cerrar</button>
                            <button className="flex-[2] py-5 bg-indigo-600 text-white rounded-[2rem] font-black uppercase text-[10px] shadow-lg shadow-indigo-100 active:scale-95 transition-all">Guardar Cambios</button>
                        </div>
                    </form>
                </div>
            )}
        </div>
    );
}

// ==========================================
// COMPONENTE: APP PRINCIPAL (ORQUESTADOR)
// ==========================================
function App() {
    const [user, setUser] = useState(null);
    const [profile, setProfile] = useState(null);
    const [view, setView] = useState('login'); 
    const [loading, setLoading] = useState(true);
    const [globalUsers, setGlobalUsers] = useState([]);
    const [logs, setLogs] = useState([]);
    const [roles, setRoles] = useState([]);
    const [reminders, setReminders] = useState([]);

    useEffect(() => {
        const unsubAuth = auth.onAuthStateChanged(async (u) => {
            if (u) {
                setUser(u);
                const saved = localStorage.getItem('shift_session_v4');
                if (saved) {
                    try {
                        const parsed = JSON.parse(saved);
                        const uDoc = await db.collection('artifacts').doc(appId).collection('public').doc('data').collection('users').doc(parsed.id).get();
                        if (uDoc.exists && uDoc.data().status !== 'baja') {
                            setProfile({ id: uDoc.id, ...uDoc.data() });
                            if (uDoc.data().role === 'admin' && view === 'login') setView('admin');
                            else if (uDoc.data().role !== 'admin') setView('dashboard');
                        } else { setView('login'); }
                    } catch (e) { setView('login'); }
                }
            } else { auth.signInAnonymously().catch(console.error); }
            setLoading(false);
        });
        return () => unsubAuth();
    }, []);

    useEffect(() => {
        if (!user) return;
        const unsubUsers = db.collection('artifacts').doc(appId).collection('public').doc('data').collection('users').onSnapshot(s => setGlobalUsers(s.docs.map(d=>({id:d.id, ...d.data()}))));
        const unsubLogs = db.collection('artifacts').doc(appId).collection('public').doc('data').collection('logs').onSnapshot(s => setLogs(s.docs.map(d=>({id:d.id, ...d.data()}))));
        
        // Maneja la conversión de roles antiguos (strings) y roles nuevos (objetos con permisos)
        const unsubRoles = db.collection('artifacts').doc(appId).collection('public').doc('data').collection('settings').doc('roles').onSnapshot(s => { 
            if(s.exists) setRoles(s.data().list || []); 
            else setRoles([]);
        });
        
        // Suscripción de Recordatorios
        const unsubReminders = db.collection('artifacts').doc(appId).collection('public').doc('data').collection('reminders').onSnapshot(s => {
            setReminders(s.docs.map(d => ({id: d.id, ...d.data()})));
        });

        return () => { unsubUsers(); unsubLogs(); unsubRoles(); unsubReminders(); };
    }, [user]);

    if (loading) return (
        <div className="h-screen flex flex-col items-center justify-center bg-indigo-950 text-white font-bold tracking-widest uppercase text-xs animate-pulse">
            Iniciando Shift Marcas Nicaragua...
        </div>
    );

    return (
        <div className="min-h-screen">
            {view === 'login' && <LoginView setView={setView} setProfile={setProfile} hasUsers={globalUsers.length > 0} allUsers={globalUsers} />}
            {view === 'dashboard' && profile && (
                <UserDashboard 
                    profile={profile} 
                    logs={logs.filter(l => l.userId === profile.id)} 
                    reminders={reminders}
                    onLogout={() => { localStorage.removeItem('shift_session_v4'); setProfile(null); setView('login'); }} 
                    setView={setView} 
                    allRoles={roles}
                />
            )}
            {view === 'admin' && profile?.role === 'admin' && (
                <AdminDashboard 
                    globalUsers={globalUsers} 
                    logs={logs} 
                    roles={roles} 
                    reminders={reminders}
                    setView={setView} 
                    onLogout={() => { localStorage.removeItem('shift_session_v4'); setProfile(null); setView('login'); }} 
                />
            )}
        </div>
    );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);