const { useState, useMemo } = React;

window.AdminDashboard = function({ 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('');
    
    // Gestión de Roles y Permisos
    const [newRoleName, setNewRoleName] = useState('');
    const [selectedPermissions, setSelectedPermissions] = useState([]);
    
    // --- GESTIÓN DE NOTIFICACIONES (NUEVO) ---
    const [notifTitle, setNotifTitle] = useState('');
    const [notifBody, setNotifBody] = useState('');
    const [notifExpiry, setNotifExpiry] = useState('');
    const [targetUsers, setTargetUsers] = useState([]);
    
    // Acciones base configurables (Requerimiento: poder configurar qué se marca)
    const availableActions = [
        { id: 'almuerzo', label: 'Almuerzo' },
        { id: 'break', label: 'Break / Merienda' },
        { id: 'visita_in', label: 'Visita Cliente' },
        { id: 'reunion', label: 'Reunión' },
        { id: 'capacitacion', label: 'Capacitación' },
        { id: 'gestiones', label: 'Gestiones de Campo' }
    ];

    const filteredLogs = useMemo(() => {
        return 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: Verificar si el correo ya existe y mostrar estado (NUEVO)
        if (!editingUser) {
            const existing = globalUsers.find(u => u.email === email);
            if (existing) {
                setSubmitError(`ADVERTENCIA: El correo ya existe. Pertenece a "${existing.name}" y su estado actual es [${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);
            e.target.reset();
        } catch (err) { setSubmitError("Error al conectar con la base de datos."); }
    };

    const unlockUser = async (uId) => {
        try {
            await db.collection('artifacts').doc(appId).collection('public').doc('data').collection('users').doc(uId).update({ overrideCheckOut: true });
            alert("Usuario desbloqueado. Podrá volver a marcar hoy.");
        } catch (err) { alert("Error al desbloquear."); }
    };

    const deleteUser = async () => {
        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 cuenta."); }
    };

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

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

    const saveRole = async () => {
        if (!newRoleName) return;
        try {
            const newRoleObj = { name: newRoleName.toLowerCase().trim(), permissions: selectedPermissions };
            const updated = [...roles.filter(r => r.name !== 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."); }
    };

    // --- FUNCIÓN DE NOTIFICACIONES (NUEVO) ---
    const sendNotification = async () => {
        if (!notifTitle || targetUsers.length === 0) return alert("Completa el título y elige al menos un usuario destinatario.");
        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("Aviso enviado correctamente.");
        } catch (e) { alert("Error al enviar la notificación."); }
    };

    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 Central</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' : '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' : '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' : 'text-slate-400'}`}>Roles y Permisos</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' : '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">
                            <input value={searchName} onChange={e=>setSearchName(e.target.value)} placeholder="Consultor..." className="p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none font-bold" />
                            <input type="date" value={searchDate} onChange={e=>setSearchDate(e.target.value)} className="p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none font-bold" />
                            <button onClick={()=>{setSearchName(''); setSearchDate('');}} className="p-4 bg-slate-100 text-slate-400 rounded-2xl font-black uppercase">Limpiar</button>
                        </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">Usuario</th><th className="p-6">Marca</th><th className="p-6">Fecha / Hora (12h NI)</th><th className="p-6">Audit</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 font-black text-indigo-600"><button onClick={()=>setSearchName(l.userName)} className="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' : l.type.includes('salida') ? 'bg-red-50 text-red-600' : 'bg-slate-100'}`}>{l.type.replace('_',' ')} {l.client && <span className="opacity-50">({l.client})</span>}</span></td>
                                            <td className="p-6 text-xs font-black text-slate-600 leading-tight">{window.formatNICTimeFull(l.timestamp)}{l.edited && <div className="text-[8px] text-orange-500 uppercase mt-1 italic font-black">Editado</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 shadow-md 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"><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"><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" className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none text-slate-800 font-bold" 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 font-bold" 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 font-bold" required />
                                <div className="grid grid-cols-2 gap-2">
                                    <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 => <option key={r.name} value={r.name}>{r.name}</option>)}<option value="admin">ADMIN</option></select>
                                    <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 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 font-bold" 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 font-bold" /></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 font-bold" /></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 font-bold" /></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 uppercase">Guardar Datos</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-[3rem] 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-1">(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"><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-400 hover:bg-red-600 hover:text-white rounded-2xl transition-all"><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" className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none font-bold uppercase" />
                                <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={saveRole} 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 => (
                                <div key={r.name} 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">{r.name}</h4>
                                        <div className="flex flex-wrap gap-1">
                                            {r.permissions.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>)}
                                        </div>
                                    </div>
                                    <button onClick={async () => {
                                        const updated = roles.filter(role => role.name !== r.name);
                                        await db.collection('artifacts').doc(appId).collection('public').doc('data').collection('settings').doc('roles').set({ list: updated });
                                    }} className="p-4 text-slate-100 group-hover:text-red-500 transition-colors"><Icon name="x-circle" /></button>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {/* --- NUEVO 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>

            {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">
                        <Icon name="alert-triangle" className="w-16 h-16 text-red-500 mx-auto" />
                        <h3 className="font-black text-xl text-slate-800 uppercase">¿Eliminar Usuario?</h3>
                        <p className="text-slate-500 text-xs">Esta acción borrará permanentemente a <b>{userToDelete.name}</b> y todo su historial.</p>
                        <div className="flex gap-3 pt-4"><button onClick={()=>setUserToDelete(null)} className="flex-1 py-4 bg-slate-100 rounded-2xl font-black">CANCELAR</button><button onClick={deleteUser} className="flex-1 py-4 bg-red-600 text-white rounded-2xl font-black">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</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">Tipo de Evento</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><option value="break">BREAK</option></select></div><div className="space-y-1"><label className="text-[9px] font-black uppercase text-slate-400 ml-1">Referencia Cliente</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">Guardar</button></div></form></div>
            )}
        </div>
    );
};