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

const AdminIcon = ({ name, className = "w-6 h-6" }) => {
    const icons = {
        'map-pin': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"></path><path strokeLinecap="round" strokeLinejoin="round" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"></path></svg>,
        'x': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"></path></svg>,
        'chevron-left': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7"></path></svg>,
        'chevron-right': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7"></path></svg>,
        'edit': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>,
        'plus': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4"></path></svg>,
        'switch': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path></svg>
    };
    return icons[name] || null;
};

function RouteMapModal({ logs, onClose }) {
    const mapRef = useRef(null);
    const mapInstance = useRef(null);

    useEffect(() => {
        const loadLeaflet = async () => {
            if (!window.L) {
                const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css'; document.head.appendChild(link);
                const script = document.createElement('script'); script.src = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js'; document.head.appendChild(script);
                await new Promise(r => script.onload = r);
            }
            initMap();
        };
        loadLeaflet();
        return () => { if (mapInstance.current) { mapInstance.current.remove(); mapInstance.current = null; } };
    }, []);

    const initMap = () => {
        if (!mapRef.current || !window.L) return;
        const validLogs = logs.filter(l => l.location && l.location.lat).sort((a,b) => a.timestamp - b.timestamp);
        
        if (validLogs.length === 0) {
            mapRef.current.innerHTML = '<div class="flex h-full items-center justify-center p-6 text-center text-slate-400 font-bold text-xs uppercase tracking-widest">El usuario no registró GPS en este(os) marcaje(s).</div>';
            return;
        }

        mapInstance.current = window.L.map(mapRef.current).setView([validLogs[0].location.lat, validLogs[0].location.lng], 15);
        window.L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap' }).addTo(mapInstance.current);

        const latlngs = [];
        validLogs.forEach((l) => {
            const pt = [l.location.lat, l.location.lng];
            latlngs.push(pt);
            const time = window.formatNICTimeFull ? window.formatNICTimeFull(l.timestamp).split(', ')[1] : new Date(l.timestamp).toLocaleTimeString();
            const color = l.type.includes('entrada') ? '#10b981' : l.type.includes('salida') ? '#ef4444' : '#6366f1';
            
            const iconHtml = `<div style="background-color: ${color}; width: 16px; height: 16px; border-radius: 50%; border: 3px solid white; box-shadow: 0 4px 6px rgba(0,0,0,0.3);"></div>`;
            const customIcon = window.L.divIcon({ html: iconHtml, className: '', iconSize: [16,16], iconAnchor: [8,8] });

            window.L.marker(pt, {icon: customIcon}).addTo(mapInstance.current)
                .bindPopup(`<div class="text-[10px] font-black uppercase text-center"><span class="text-slate-500">${l.type.replace('_',' ')}</span><br/><span class="text-indigo-600 text-xs">${time}</span>${l.client?`<br/><br/>Visita a:<br/>${l.client}`:''}</div>`);
        });

        if (latlngs.length > 1) {
            const polyline = window.L.polyline(latlngs, {color: '#4f46e5', weight: 4, dashArray: '5, 10'}).addTo(mapInstance.current);
            mapInstance.current.fitBounds(polyline.getBounds(), { padding: [50, 50] });
        }
    };

    return (
        <div className="fixed inset-0 bg-slate-900/60 z-[100] flex items-center justify-center p-4 fade-in" onClick={onClose}>
            <div className="bg-white rounded-[3rem] p-6 w-full max-w-4xl h-[85vh] flex flex-col shadow-2xl" onClick={e=>e.stopPropagation()}>
                <div className="flex justify-between items-center mb-4 px-2">
                    <div>
                        <h3 className="font-black text-xl text-indigo-900 flex items-center gap-2">Auditoría Geográfica</h3>
                        <p className="text-[10px] font-black uppercase text-slate-400 tracking-widest">{logs.length > 1 ? 'Ruta trazada durante el día' : 'Punto de marcaje exacto'}</p>
                    </div>
                    <button onClick={onClose} className="p-3 bg-slate-100 text-slate-500 rounded-full hover:bg-slate-200 transition-colors"><AdminIcon className="w-5 h-5" name="x"/></button>
                </div>
                <div ref={mapRef} className="flex-1 rounded-[2rem] overflow-hidden bg-slate-100 z-0 border-4 border-slate-100 shadow-inner"></div>
            </div>
        </div>
    );
}

window.AdminDashboard = function({ globalUsers, logs, roles, reminders = [], vacations = [], settings, actions = [], absences = [], masterClients = [], activeClientId, setActiveClientId, refreshData, setView, onLogout }) {
    const isMaster = window.SHIFT_CONFIG && window.SHIFT_CONFIG.isMaster;
    const [tab, setTab] = useState(isMaster ? 'master' : 'logs');
    const [toastMsg, setToastMsg] = useState('');

    // SaaS Maestro State
    const [showClientModal, setShowClientModal] = useState(false);
    const [editingClient, setEditingClient] = useState(null);
    
    // UI Auditoría
    const [searchName, setSearchName] = useState('');
    const [searchDate, setSearchDate] = useState(window.getNICDate());
    const [startDate, setStartDate] = useState('');
    const [endDate, setEndDate] = useState('');
    const [mapLogs, setMapLogs] = useState(null); 

    // UI Gestión General
    const [editingUser, setEditingUser] = useState(null);
    const [userToDelete, setUserToDelete] = useState(null);
    const [previewImage, setPreviewImage] = useState(null);
    const [confirmModal, setConfirmModal] = useState(null);

    // Acciones y Botones
    const [editingActionId, setEditingActionId] = useState(null);
    const [newActionLabel, setNewActionLabel] = useState('');

    // Roles & Avisos
    const [editingRoleName, setEditingRoleName] = useState(null);
    const [newRoleName, setNewRoleName] = useState('');
    const [selectedPermissions, setSelectedPermissions] = useState([]);
    const [selectedCameraActions, setSelectedCameraActions] = useState([]);
    const [editingReminderId, setEditingReminderId] = useState(null);
    const [notifTitle, setNotifTitle] = useState('');
    const [notifBody, setNotifBody] = useState('');
    const [targetUsers, setTargetUsers] = useState([]);

    // Vacaciones
    const [vacRate, setVacRate] = useState(settings?.vacationRate || 2.5);
    const [selectedUserVacation, setSelectedUserVacation] = useState(null); 
    const [managingVacation, setManagingVacation] = useState(null); 
    const [tempRevokedDates, setTempRevokedDates] = useState([]); 

    const [directVacType, setDirectVacType] = useState('full');
    const [directVacStart, setDirectVacStart] = useState('');
    const [directVacEnd, setDirectVacEnd] = useState('');
    const [directPaidDays, setDirectPaidDays] = useState(1);
    const [vacPage, setVacPage] = useState(0); 

    // Ausencias
    const [absenceUser, setAbsenceUser] = useState('');
    const [absenceDate, setAbsenceDate] = useState(window.getNICDate());
    const [absenceType, setAbsenceType] = useState('injustificada');
    const [absenceNotes, setAbsenceNotes] = useState('');

    const showToast = (msg) => { setToastMsg(msg); setTimeout(() => setToastMsg(''), 3000); };
    const confirmAction = (message, action) => setConfirmModal({ message, action });

    const currentCompanyObj = useMemo(() => {
        if (!masterClients || masterClients.length === 0) return null;
        return masterClients.find(c => c.id === activeClientId);
    }, [masterClients, activeClientId]);

    const handleSaveClient = async (e) => {
        e.preventDefault();
        const f = new FormData(e.target);
        const payload = {
            id: editingClient ? editingClient.id : null,
            company_name: f.get('company_name'),
            shift_subdomain: f.get('shift_subdomain'),
            contact_name: f.get('contact_name'),
            contact_email: f.get('contact_email'),
            contact_phone: f.get('contact_phone'),
            module_shift: f.get('module_shift') ? 1 : 0,
            admin_password: f.get('admin_password') || ''
        };

        const res = await window.apiCall('save_master_client', payload);
        if (res.success) {
            setShowClientModal(false); setEditingClient(null); 
            if (refreshData) refreshData(); 
            showToast("Empresa guardada exitosamente.");
        } else showToast(res.error || "Error al guardar empresa.");
    };

    const toggleModule = async (c) => {
        await window.apiCall('toggle_client_module', { id: c.id, module_shift: c.module_shift ? 0 : 1 });
        if (refreshData) refreshData(); 
        showToast("Estado de módulo actualizado.");
    };

    const filteredLogs = useMemo(() => {
        return logs.filter(l => {
            const matchName = (l.userName || '').toLowerCase().includes(searchName.toLowerCase());
            let matchDate = true;
            if (searchDate) { matchDate = l.date === searchDate; } 
            else if (startDate && endDate) { matchDate = l.date >= startDate && l.date <= endDate; }
            return matchName && matchDate;
        }).sort((a,b) => b.timestamp - a.timestamp);
    }, [logs, searchName, searchDate, startDate, endDate]);

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

        if (!editingUser) {
            const existingEmail = globalUsers.find(u => u.email === email);
            if (existingEmail) return showToast(`ADVERTENCIA: Correo en uso por "${existingEmail.name}"`);
        }

        const data = {
            id: editingUser ? editingUser.id : null,
            name: f.get('name'),
            alias: aliasCode,
            email, password: f.get('pass'), 
            role: f.get('role'), status: f.get('status'),
            hiringDate: f.get('date'), vacationDaysUsed: parseFloat(f.get('vused')) || 0,
            overrideCheckOut: editingUser ? (editingUser.overrideCheckOut || false) : false,
            manualLock: editingUser ? (editingUser.manualLock || false) : false
        };
        try {
            await window.apiCall('save_user', data);
            setEditingUser(null); e.target.reset(); showToast("Datos guardados.");
            if (refreshData) refreshData();
        } catch (err) { showToast("Error de red al guardar usuario."); }
    };

    const deleteUser = async (id) => {
        await window.apiCall('delete_user', { id });
        setUserToDelete(null); setConfirmModal(null); showToast("Usuario borrado.");
        if (refreshData) refreshData();
    };

    const isUserLockedToday = (user) => {
        const todayLogs = logs.filter(l => l.userId === user.id && l.date === window.getNICDate());
        const hasSalida = todayLogs.some(l => l.type === 'salida');
        return user.manualLock || (hasSalida && !user.overrideCheckOut);
    };

    const toggleLock = async (u, lockStatus) => {
        await window.apiCall('toggle_user_lock', { id: u.id, manualLock: lockStatus, overrideCheckOut: !lockStatus });
        showToast(lockStatus ? "Bloqueado." : "Desbloqueado.");
        if (refreshData) refreshData();
    };

    const saveCustomAction = async () => {
        if (!newActionLabel.trim()) return showToast("Escribe un nombre para el botón.");
        const newId = editingActionId || newActionLabel.toLowerCase().replace(/\s+/g, '_').replace(/[^a-z0-9_]/g, '') + '_' + Date.now().toString().slice(-4);
        await window.apiCall('save_action', { action_id: newId, label: newActionLabel });
        setEditingActionId(null); setNewActionLabel(''); showToast("Botón guardado exitosamente.");
        if (refreshData) refreshData();
    };

    const deleteCustomAction = async (act) => {
        confirmAction(`¿Borrar el botón "${act.label}" de todo el sistema?`, async () => {
            await window.apiCall('delete_action', { action_id: act.id });
            setConfirmModal(null); showToast("Botón eliminado.");
            if (refreshData) refreshData();
        });
    };

    const updateVacationRate = async () => {
        await window.apiCall('update_settings', { vacation_rate: parseFloat(vacRate) || 2.5 });
        showToast("Tasa mensual actualizada.");
        if (refreshData) refreshData();
    };

    const setVacationStatus = async (vId, status) => {
        await window.apiCall('update_vacation_status', { id: vId, status });
        showToast(`Actualizado a: ${status}`);
        if (refreshData) refreshData();
    };

    const handleDirectAssignment = async (e) => {
        e.preventDefault();
        if (!selectedUserVacation) return;

        let payload = {
            userId: selectedUserVacation.id, userName: selectedUserVacation.name, type: directVacType,
            status: 'approved', requestedAt: Date.now(), seenByUser: false, revokedDates: []
        };

        if (directVacType === 'paid') {
            if (!directPaidDays || directPaidDays <= 0) return showToast("Cantidad de días inválida.");
            payload.paidDays = Number(directPaidDays);
        } else {
            if (!directVacStart || (directVacType === 'range' && !directVacEnd)) return showToast("Faltan fechas.");
            const end = directVacType === 'range' ? directVacEnd : directVacStart;
            if (directVacType === 'range' && end < directVacStart) return showToast("Fecha de fin debe ser mayor.");
            payload.startDate = directVacStart;
            payload.endDate = end;
        }

        await window.apiCall('add_vacation', payload);
        setDirectVacStart(''); setDirectVacEnd(''); setDirectVacType('full'); setDirectPaidDays(1);
        showToast("Acción guardada exitosamente.");
        if (refreshData) refreshData();
    };

    const toggleRevokeDay = (dateStr) => {
        setTempRevokedDates(prev => prev.includes(dateStr) ? prev.filter(d => d !== dateStr) : [...prev, dateStr]);
    };

    const confirmRevokedDates = async () => {
        if (!managingVacation) return;
        await window.apiCall('update_revoked_dates', { id: managingVacation.id, revokedDates: tempRevokedDates });
        setManagingVacation(null); showToast("Días actualizados en el saldo del usuario.");
        if (refreshData) refreshData();
    };

    const saveAbsence = async (e) => {
        e.preventDefault();
        if (!absenceUser || !absenceDate) return showToast("Falta usuario o fecha.");
        const userObj = globalUsers.find(u => u.id == absenceUser);
        
        await window.apiCall('save_absence', {
            userId: userObj.id, userName: userObj.name, date: absenceDate,
            type: absenceType, notes: absenceNotes, createdAt: Date.now()
        });

        if (absenceType === 'descontada') {
            await window.apiCall('add_vacation', {
                userId: userObj.id, userName: userObj.name, type: 'full',
                startDate: absenceDate, endDate: absenceDate, status: 'approved',
                requestedAt: Date.now(), seenByUser: true, revokedDates: [], notes: 'Ausencia Convertida a Vacación'
            });
        }
        setAbsenceUser(''); setAbsenceNotes(''); showToast("Ausencia Registrada.");
        if (refreshData) refreshData();
    };

    const saveRole = async () => {
        if (!newRoleName) return showToast("Escribe un nombre.");
        await window.apiCall('save_role', { 
            name: newRoleName.toLowerCase().trim(), oldName: editingRoleName,
            permissions: selectedPermissions, cameraActions: selectedCameraActions 
        });
        setEditingRoleName(null); setNewRoleName(''); setSelectedPermissions([]); setSelectedCameraActions([]); showToast("Rol guardado.");
        if (refreshData) refreshData();
    };

    const saveNotification = async () => {
        if (!notifTitle || targetUsers.length === 0) return showToast("Faltan datos en el aviso.");
        await window.apiCall('save_reminder', {
            id: editingReminderId, title: notifTitle, message: notifBody, targetUsers: targetUsers, createdAt: Date.now()
        });
        setEditingReminderId(null); setNotifTitle(''); setNotifBody(''); setTargetUsers([]); showToast("Aviso enviado.");
        if (refreshData) refreshData();
    };

    const approvedVacsHistory = useMemo(() => vacations.filter(v => v.status === 'approved').sort((a,b)=>new Date(b.startDate)-new Date(a.startDate)), [vacations]);
    const totalVacPages = Math.ceil(approvedVacsHistory.length / 5);
    const paginatedVacs = approvedVacsHistory.slice(vacPage * 5, (vacPage + 1) * 5);

    return (
        <div className="flex flex-col h-screen bg-slate-50 fade-in text-xs relative">
            {toastMsg && <div className="fixed top-4 left-1/2 -translate-x-1/2 bg-slate-900 text-white px-6 py-3 rounded-2xl font-black text-[10px] uppercase tracking-widest shadow-2xl z-[120] animate-bounce whitespace-nowrap">{toastMsg}</div>}
            
            {/* MODAL CREAR / EDITAR EMPRESA SAAS */}
            {showClientModal && (
                <div className="fixed inset-0 bg-slate-900/60 z-[110] flex items-center justify-center p-6 fade-in" onClick={()=>setShowClientModal(false)}>
                    <form onSubmit={handleSaveClient} className="bg-white p-8 rounded-[3rem] w-full max-w-md shadow-2xl space-y-4" onClick={e=>e.stopPropagation()}>
                        <h3 className="font-black text-xl text-slate-900 mb-2">{editingClient ? "Editar Empresa SaaS" : "Nueva Empresa SaaS"}</h3>
                        <div>
                            <label className="text-[10px] font-black uppercase text-slate-400 ml-2">Nombre Comercial</label>
                            <input name="company_name" defaultValue={editingClient?.company_name} placeholder="Ej. CleanDent SA" className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none" required />
                        </div>
                        <div>
                            <label className="text-[10px] font-black uppercase text-slate-400 ml-2">Subdominio / Alias URL</label>
                            <input name="shift_subdomain" defaultValue={editingClient?.shift_subdomain} placeholder="cleandent" className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none lowercase" required />
                        </div>
                        <div className="grid grid-cols-2 gap-2">
                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2">Contacto</label>
                                <input name="contact_name" defaultValue={editingClient?.contact_name} placeholder="Verónica" className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none" />
                            </div>
                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2">Teléfono</label>
                                <input name="contact_phone" defaultValue={editingClient?.contact_phone} placeholder="88888888" className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none" />
                            </div>
                        </div>
                        <div>
                            <label className="text-[10px] font-black uppercase text-slate-400 ml-2">Correo Administrador</label>
                            <input name="contact_email" type="email" defaultValue={editingClient?.contact_email} placeholder="admin@cleandent.com" className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none" required />
                        </div>
                        {!editingClient && (
                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2">PIN / Clave Inicial Admin</label>
                                <input name="admin_password" placeholder="123456" className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none" required />
                            </div>
                        )}
                        <label className="flex items-center gap-3 p-4 bg-indigo-50 rounded-2xl cursor-pointer">
                            <input type="checkbox" name="module_shift" defaultChecked={editingClient ? editingClient.module_shift == 1 : true} className="w-5 h-5 accent-indigo-600" />
                            <span className="font-black text-indigo-900 text-xs uppercase">Módulo Asistencia Activo</span>
                        </label>
                        <div className="flex gap-2 pt-2">
                            <button type="button" onClick={()=>setShowClientModal(false)} className="w-1/3 py-4 bg-slate-100 text-slate-600 font-black rounded-2xl uppercase">Cancelar</button>
                            <button type="submit" className="flex-1 py-4 bg-indigo-600 text-white font-black rounded-2xl uppercase shadow-lg">Guardar Empresa</button>
                        </div>
                    </form>
                </div>
            )}

            {mapLogs && <RouteMapModal logs={mapLogs} onClose={() => setMapLogs(null)} />}

            {previewImage && (
                <div className="fixed inset-0 bg-slate-900/80 z-[110] flex items-center justify-center p-4 fade-in" onClick={() => setPreviewImage(null)}>
                    <div className="bg-white p-2 rounded-[2rem] max-w-2xl max-h-[90vh] overflow-hidden relative shadow-2xl" onClick={e=>e.stopPropagation()}>
                        <button onClick={() => setPreviewImage(null)} className="absolute top-4 right-4 bg-slate-900/50 text-white p-2 rounded-full hover:bg-slate-900 transition-colors"><AdminIcon className="w-6 h-6" name="x"/></button>
                        <img src={previewImage} className="w-full h-auto max-h-[85vh] object-contain rounded-[1.5rem]" />
                    </div>
                </div>
            )}

            {confirmModal && (
                <div className="fixed inset-0 bg-slate-900/60 z-[100] flex items-center justify-center p-6 fade-in" onClick={()=>setConfirmModal(null)}>
                    <div className="bg-white p-8 rounded-[3rem] text-center max-w-sm w-full shadow-2xl" onClick={e=>e.stopPropagation()}>
                        <h3 className="font-black text-xl text-slate-900 mb-2">Confirmación</h3>
                        <p className="text-slate-500 text-xs font-bold mb-6">{confirmModal.message}</p>
                        <div className="flex gap-3">
                            <button onClick={()=>setConfirmModal(null)} className="flex-1 py-4 bg-slate-100 text-slate-600 rounded-2xl font-black uppercase text-[10px] tracking-widest active:scale-95 transition-all">Cancelar</button>
                            <button onClick={confirmModal.action} className="flex-1 py-4 bg-indigo-600 text-white rounded-2xl font-black uppercase text-[10px] tracking-widest shadow-lg active:scale-95 transition-all">Proceder</button>
                        </div>
                    </div>
                </div>
            )}

            {selectedUserVacation && (
                <div className="fixed inset-0 bg-slate-900/40 z-[90] p-6 flex justify-center items-center fade-in" onClick={()=>setSelectedUserVacation(null)}>
                    <div className="bg-white w-full max-w-2xl max-h-[90vh] rounded-[3rem] shadow-2xl flex flex-col overflow-hidden" onClick={e=>e.stopPropagation()}>
                        <div className="p-8 border-b border-slate-100 flex justify-between items-start z-10">
                            <div>
                                <h3 className="font-black text-2xl text-slate-900">{selectedUserVacation.name}</h3>
                                <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mt-1">REPORTE VACACIONAL • SALDO: {window.calculateVacationBalance(selectedUserVacation, settings?.vacationRate||2.5, vacations)} DÍAS</p>
                            </div>
                            <button onClick={()=>setSelectedUserVacation(null)} className="p-3 bg-slate-50 text-slate-400 hover:text-slate-600 rounded-full transition-colors"><AdminIcon className="w-5 h-5" name="x"/></button>
                        </div>
                        <div className="flex-1 overflow-y-auto p-8 space-y-8">
                            <form onSubmit={handleDirectAssignment} className="bg-white p-6 rounded-[2.5rem] border border-slate-100 shadow-sm">
                                <h4 className="font-black text-[10px] uppercase text-slate-400 mb-4 tracking-widest">ASIGNACIÓN DIRECTA ADMINISTRADOR</h4>
                                <div className="grid md:grid-cols-3 gap-4 items-end">
                                    <select value={directVacType} onChange={e=>setDirectVacType(e.target.value)} className="w-full p-4 bg-slate-50 rounded-2xl font-bold text-[11px] uppercase outline-none focus:ring-2 focus:ring-indigo-100">
                                        <option value="full">DÍA COMPLETO</option><option value="half">MEDIO DÍA (0.5)</option><option value="range">RANGO FECHAS</option><option value="paid">PAGAR DÍAS</option>
                                    </select>
                                    {directVacType === 'paid' ? (
                                        <input type="number" min="0.5" step="0.5" value={directPaidDays} onChange={e=>setDirectPaidDays(e.target.value)} className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none col-span-2 md:col-span-1" placeholder="Días a pagar..." required/>
                                    ) : (
                                        <input type="date" value={directVacStart} onChange={e=>setDirectVacStart(e.target.value)} className={`w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none ${directVacType === 'range' ? 'col-span-1' : 'col-span-2 md:col-span-1'}`} required/>
                                    )}
                                    {directVacType === 'range' && <input type="date" value={directVacEnd} onChange={e=>setDirectVacEnd(e.target.value)} className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none" required min={directVacStart}/>}
                                    {directVacType !== 'range' && <button type="submit" className="w-full py-4 bg-slate-900 text-white rounded-2xl font-black uppercase text-[10px] tracking-widest active:scale-95 transition-all">GUARDAR APROBADA</button>}
                                </div>
                                {directVacType === 'range' && <button type="submit" className="w-full mt-4 py-4 bg-slate-900 text-white rounded-2xl font-black uppercase text-[10px] tracking-widest active:scale-95 transition-all">GUARDAR APROBADA</button>}
                            </form>
                            <div>
                                <h4 className="font-black text-[11px] uppercase text-slate-400 border-b border-slate-100 pb-3 mb-4 tracking-widest">HISTORIAL Y SOLICITUDES DEL USUARIO</h4>
                                <div className="space-y-4">
                                    {vacations.filter(v=>v.userId === selectedUserVacation.id).length === 0 ? <p className="text-center font-bold text-slate-300 py-6 text-xs uppercase">Sin registros en el sistema.</p> :
                                        vacations.filter(v=>v.userId === selectedUserVacation.id).sort((a,b)=>new Date(b.startDate)-new Date(a.startDate)).map(v => (
                                            <div key={v.id} className={`bg-slate-50 rounded-[2rem] p-6 flex flex-col md:flex-row justify-between items-center gap-4 relative overflow-hidden border ${v.status==='approved'?'border-emerald-100':v.status==='pending'?'border-yellow-200':'border-slate-200'}`}>
                                                <div className={`absolute left-0 top-0 bottom-0 w-2 ${v.status==='approved'?'bg-emerald-400':v.status==='pending'?'bg-yellow-400':'bg-slate-300'}`}></div>
                                                <div className="pl-4 w-full md:w-auto">
                                                    <p className="font-black text-slate-800 text-sm tracking-wide">{v.type === 'half' ? 'MEDIO DÍA (0.5)' : v.type === 'paid' ? 'PAGO VACACIONES' : 'RANGO/DÍA COMPLETO'}</p>
                                                    {v.type === 'paid' ? <p className="text-[10px] font-bold text-slate-500 mt-1 uppercase tracking-widest">DÍAS LIQUIDADOS: {v.paidDays}</p> : <p className="text-[10px] font-bold text-slate-500 mt-1 uppercase tracking-widest">FECHAS: {window.formatDateToNIC ? window.formatDateToNIC(v.startDate) : v.startDate} {v.type==='range'?` AL ${window.formatDateToNIC ? window.formatDateToNIC(v.endDate) : v.endDate}`:''}</p>}
                                                    <div className="mt-3"><span className={`text-[9px] font-black uppercase tracking-widest px-3 py-1.5 rounded-lg bg-white shadow-sm border ${v.status === 'approved' ? 'text-emerald-600 border-emerald-100' : v.status === 'pending' ? 'text-yellow-600 border-yellow-200' : 'text-slate-500 border-slate-200'}`}>{v.status === 'approved' ? 'APROBADO' : v.status === 'pending' ? 'PENDIENTE DE REVISIÓN' : 'DENEGADO / INACTIVO'}</span></div>
                                                </div>
                                                <div className="flex flex-col gap-3 w-full md:w-auto mt-4 md:mt-0 items-center md:items-end">
                                                    {v.status === 'pending' && <div className="flex gap-2 w-full justify-end"><button onClick={()=>setVacationStatus(v.id, 'approved')} className="px-6 py-3 bg-slate-900 text-white rounded-xl font-black text-[10px] uppercase tracking-widest">Aprobar</button><button onClick={()=>setVacationStatus(v.id, 'denied')} className="px-6 py-3 bg-white border border-slate-200 text-slate-600 rounded-xl font-black text-[10px] uppercase tracking-widest">Denegar</button></div>}
                                                    {v.status === 'approved' && v.type !== 'paid' && <button onClick={()=>{setManagingVacation(v); setTempRevokedDates(v.revokedDates || []);}} className="px-6 py-3 bg-slate-900 text-white rounded-xl font-black text-[10px] uppercase tracking-widest active:scale-95 transition-all">GESTIONAR / REVOCAR</button>}
                                                    <button onClick={()=>confirmAction("Borrar el registro por completo de la base de datos.", async ()=>{ await window.apiCall('delete_vacation', {id: v.id}); setConfirmModal(null); showToast('Registro borrado.'); })} className="text-slate-400 font-bold text-[9px] uppercase tracking-widest underline hover:text-red-500 transition-colors">ELIMINAR FILA</button>
                                                </div>
                                            </div>
                                        ))
                                    }
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {managingVacation && (
                <div className="fixed inset-0 bg-slate-900/60 z-[100] flex items-center justify-center p-6 fade-in" onClick={()=>{setManagingVacation(null); setTempRevokedDates([]);}}>
                    <div className="bg-white p-8 rounded-[3rem] w-full max-w-sm shadow-2xl flex flex-col max-h-[85vh]" onClick={e=>e.stopPropagation()}>
                        <div className="flex justify-between items-center mb-2">
                            <h3 className="font-black text-xl text-slate-900">Edición Quirúrgica</h3>
                            <button onClick={()=>{setManagingVacation(null); setTempRevokedDates([]);}} className="p-2 bg-slate-100 text-slate-400 rounded-full hover:bg-slate-200 transition-colors"><AdminIcon className="w-4 h-4" name="x"/></button>
                        </div>
                        <p className="text-slate-500 text-[10px] font-bold uppercase tracking-widest leading-relaxed mb-6 border-b pb-4">DESMARCA LOS DÍAS ESPECÍFICOS QUE EL USUARIO SÍ TRABAJARÁ (SE LE DEVOLVERÁN A SU SALDO).</p>
                        <div className="flex-1 overflow-y-auto space-y-3 mb-6 pr-2 no-scrollbar">
                            {window.getDatesInRange(managingVacation.startDate, managingVacation.endDate || managingVacation.startDate).map(dateStr => {
                                const isRevoked = tempRevokedDates.includes(dateStr);
                                return (
                                    <label key={dateStr} className={`flex items-center justify-between p-5 rounded-3xl cursor-pointer transition-all border-2 ${isRevoked ? 'bg-white border-slate-100' : 'bg-emerald-50 border-emerald-200'}`}>
                                        <span className={`font-black text-sm tracking-wide ${isRevoked ? 'text-slate-400 line-through' : 'text-emerald-900'}`}>{window.formatDateToNIC ? window.formatDateToNIC(dateStr) : dateStr}</span>
                                        <div className="flex items-center gap-4">
                                            <span className={`text-[10px] font-black uppercase tracking-widest ${isRevoked ? 'text-red-500' : 'text-emerald-600'}`}>{isRevoked ? 'Viene a Trabajar' : 'Día Libre'}</span>
                                            <div className={`w-6 h-6 rounded-md flex items-center justify-center border-2 transition-colors ${!isRevoked ? 'bg-emerald-500 border-emerald-500' : 'bg-white border-slate-300'}`}>
                                                {!isRevoked && <svg className="w-4 h-4 text-white" fill="none" stroke="currentColor" strokeWidth="3" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7"></path></svg>}
                                            </div>
                                            <input type="checkbox" className="hidden" checked={!isRevoked} onChange={() => toggleRevokeDay(dateStr)} />
                                        </div>
                                    </label>
                                );
                            })}
                        </div>
                        <div className="flex gap-3">
                            <button onClick={()=>{setManagingVacation(null); setTempRevokedDates([]);}} className="flex-1 py-4 bg-slate-100 text-slate-600 font-black rounded-2xl uppercase text-[10px] tracking-widest">Cancelar</button>
                            <button onClick={confirmRevokedDates} className="flex-1 py-4 bg-slate-900 text-white font-black rounded-2xl uppercase text-[10px] tracking-widest shadow-lg active:scale-95 transition-all">Aplicar Cambios</button>
                        </div>
                    </div>
                </div>
            )}

            <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-4">
                    <div className="font-black text-indigo-600 uppercase text-xl">Shift Central</div>
                    {isMaster && masterClients && masterClients.length > 0 && (
                        <div className="flex items-center gap-2 bg-slate-100 px-3 py-1.5 rounded-2xl border border-slate-200">
                            <AdminIcon name="switch" className="w-4 h-4 text-indigo-600" />
                            <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Empresa:</span>
                            <select 
                                value={activeClientId} 
                                onChange={e => setActiveClientId && setActiveClientId(Number(e.target.value))}
                                className="bg-transparent font-black text-indigo-900 text-xs outline-none cursor-pointer uppercase"
                            >
                                {masterClients.map(c => (
                                    <option key={c.id} value={c.id}>{c.company_name} (@{c.shift_subdomain})</option>
                                ))}
                            </select>
                        </div>
                    )}
                </div>
                <div className="flex gap-2">
                    <button onClick={() => setView('dashboard')} className="px-5 py-2.5 bg-indigo-50 text-indigo-600 rounded-2xl font-black uppercase text-[10px] active:scale-95 transition-all">Vista App</button>
                    <button onClick={onLogout} className="p-2.5 text-slate-400 font-black text-[10px] uppercase active:scale-95 transition-all">Salir</button>
                </div>
            </nav>

            <main className="flex-1 p-6 max-w-7xl mx-auto w-full overflow-y-auto">
                <div className="flex gap-2 mb-8 bg-slate-200/50 p-1 rounded-2xl w-fit overflow-x-auto max-w-full no-scrollbar">
                    {isMaster && (
                        <button onClick={()=>setTab('master')} className={`px-6 py-3 rounded-xl font-black uppercase text-[10px] whitespace-nowrap transition-all ${tab==='master'?'bg-indigo-600 text-white shadow-md':''}`}>Empresas SaaS</button>
                    )}
                    <button onClick={()=>setTab('logs')} className={`px-6 py-3 rounded-xl font-black uppercase text-[10px] whitespace-nowrap transition-all ${tab==='logs'?'bg-white text-indigo-600 shadow-sm':''}`}>Auditoría</button>
                    <button onClick={()=>setTab('users')} className={`px-6 py-3 rounded-xl font-black uppercase text-[10px] whitespace-nowrap transition-all ${tab==='users'?'bg-white text-indigo-600 shadow-sm':''}`}>Personal</button>
                    <button onClick={()=>setTab('vacations')} className={`px-6 py-3 rounded-xl font-black uppercase text-[10px] whitespace-nowrap transition-all ${tab==='vacations'?'bg-white text-emerald-600 shadow-sm':''}`}>Vacaciones</button>
                    <button onClick={()=>setTab('absences')} className={`px-6 py-3 rounded-xl font-black uppercase text-[10px] whitespace-nowrap transition-all ${tab==='absences'?'bg-white text-red-600 shadow-sm':''}`}>Ausencias</button>
                    <button onClick={()=>setTab('roles')} className={`px-6 py-3 rounded-xl font-black uppercase text-[10px] whitespace-nowrap transition-all ${tab==='roles'?'bg-white text-indigo-600 shadow-sm':''}`}>Roles y Botones</button>
                    <button onClick={()=>setTab('notif')} className={`px-6 py-3 rounded-xl font-black uppercase text-[10px] whitespace-nowrap transition-all ${tab==='notif'?'bg-white text-indigo-600 shadow-sm':''}`}>Avisos</button>
                </div>

                {tab === 'master' && isMaster && (
                    <div className="space-y-6 fade-in">
                        <div className="flex justify-between items-center bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100">
                            <div>
                                <h2 className="text-2xl font-black text-slate-900">Gestión de Portales Corporativos</h2>
                                <p className="text-slate-400 font-bold uppercase text-[10px] mt-1 tracking-widest">Crea subdominios y asigna administradores a cada cliente</p>
                            </div>
                            <button onClick={()=>{setEditingClient(null); setShowClientModal(true);}} className="px-6 py-4 bg-indigo-600 text-white font-black rounded-2xl uppercase tracking-widest flex items-center gap-2 shadow-lg active:scale-95 transition-all">
                                <AdminIcon name="plus" /> Nueva Empresa
                            </button>
                        </div>

                        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
                            {masterClients.map(c => (
                                <div key={c.id} className={`p-8 rounded-[3rem] bg-white border-2 shadow-sm transition-all relative ${activeClientId === c.id ? 'border-indigo-600 ring-4 ring-indigo-50' : 'border-slate-100'}`}>
                                    <div className="flex justify-between items-start mb-4">
                                        <span className={`px-3 py-1.5 rounded-xl font-black text-[9px] uppercase ${c.module_shift == 1 ? 'bg-emerald-50 text-emerald-600 border border-emerald-200' : 'bg-red-50 text-red-600'}`}>{c.module_shift == 1 ? 'MÓDULO ACTIVO' : 'INACTIVO'}</span>
                                        <button onClick={()=>{setEditingClient(c); setShowClientModal(true);}} className="p-2 bg-slate-50 text-slate-500 rounded-xl hover:bg-slate-100"><AdminIcon name="edit"/></button>
                                    </div>
                                    <h3 className="font-black text-xl text-slate-900 mb-1">{c.company_name}</h3>
                                    <p className="text-[11px] font-black text-indigo-600 underline uppercase tracking-wider mb-4">{c.shift_subdomain}.shift.marcasnicaragua.com</p>
                                    <div className="space-y-1 text-slate-500 font-bold border-t border-slate-100 pt-4 text-[10px]">
                                        <p>Contacto: <span className="text-slate-800">{c.contact_name || 'N/A'}</span></p>
                                        <p>Correo: <span className="text-slate-800">{c.contact_email}</span></p>
                                    </div>
                                    <div className="flex gap-2 mt-6">
                                        <button onClick={()=>setActiveClientId && setActiveClientId(c.id)} className={`flex-1 py-3 rounded-2xl font-black uppercase text-[10px] transition-all ${activeClientId === c.id ? 'bg-indigo-600 text-white shadow-md' : 'bg-slate-100 text-slate-600'}`}>
                                            {activeClientId === c.id ? 'Administrando Portal' : 'Inspeccionar Portal'}
                                        </button>
                                        <button onClick={()=>toggleModule(c)} className={`px-4 py-3 rounded-2xl font-black uppercase text-[10px] ${c.module_shift == 1 ? 'bg-red-50 text-red-600' : 'bg-emerald-50 text-emerald-600'}`}>
                                            {c.module_shift == 1 ? 'Pausar' : 'Activar'}
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {tab === 'logs' && (
                    <div className="space-y-6 fade-in">
                        <div className="bg-white p-6 rounded-[3rem] shadow-sm border border-slate-100 flex flex-col md:flex-row items-end gap-4">
                            <div className="w-full md:flex-1">
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block tracking-widest">Consultor / Área</label>
                                <input value={searchName} onChange={e=>setSearchName(e.target.value)} placeholder="Ej. Prueba 1" className="w-full p-4 bg-slate-50 border border-slate-100 rounded-2xl font-bold outline-none focus:border-indigo-500 transition-colors" />
                            </div>
                            <div className="w-full md:flex-1">
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block tracking-widest">Día Específico</label>
                                <input type="date" value={searchDate} onChange={e=>{setSearchDate(e.target.value); setStartDate(''); setEndDate('');}} className="w-full p-4 bg-slate-50 border border-slate-100 rounded-2xl font-bold outline-none focus:border-indigo-500 transition-colors" />
                            </div>
                            <div className="w-full md:flex-1 bg-slate-50 p-3 rounded-[1.25rem] border border-slate-100 relative">
                                <span className="absolute -top-3 left-4 bg-white px-2 py-0.5 rounded-full text-[9px] font-black uppercase tracking-widest text-indigo-400 shadow-sm border border-slate-100">O Rango de Fechas</span>
                                <div className="flex gap-2">
                                    <input type="date" value={startDate} onChange={e=>{setStartDate(e.target.value); setSearchDate('');}} className="w-full p-2 bg-white rounded-xl font-bold outline-none border border-slate-200 text-xs" />
                                    <input type="date" value={endDate} onChange={e=>{setEndDate(e.target.value); setSearchDate('');}} className="w-full p-2 bg-white rounded-xl font-bold outline-none border border-slate-200 text-xs" />
                                </div>
                            </div>
                            <div className="w-full md:w-auto">
                                <button onClick={()=>setMapLogs(filteredLogs)} className="w-full h-[52px] px-8 bg-indigo-600 text-white rounded-2xl font-black uppercase text-[10px] tracking-widest shadow-lg flex items-center justify-center gap-2 hover:bg-indigo-700 active:scale-95 transition-all">
                                    <AdminIcon className="w-4 h-4" name="map-pin" /> Ver Mapa Global
                                </button>
                            </div>
                        </div>

                        <div className="bg-white rounded-[3rem] shadow-sm overflow-hidden border border-slate-100">
                            <table className="w-full text-left">
                                <thead className="bg-slate-50 text-[10px] font-black text-slate-400 uppercase border-b border-slate-100">
                                    <tr><th className="p-6">Usuario</th><th className="p-6">Marca</th><th className="p-6">Fecha/Hora</th><th className="p-6 text-center">Acciones</th></tr>
                                </thead>
                                <tbody className="divide-y divide-slate-50">
                                    {filteredLogs.map(l => {
                                        const actionObj = actions.find(a => a.id === l.type);
                                        const displayType = actionObj ? actionObj.label : l.type.replace('_',' ');
                                        
                                        return (
                                            <tr key={l.id} className="hover:bg-slate-50/50 transition-colors">
                                                <td className="p-6 font-black text-indigo-900">{l.userName}</td>
                                                <td className="p-6 uppercase font-black text-[9px] text-slate-600">{displayType}</td>
                                                <td className="p-6 font-bold text-slate-500">{window.formatNICTimeFull ? window.formatNICTimeFull(l.timestamp) : new Date(l.timestamp).toLocaleString()}</td>
                                                <td className="p-6 text-center flex items-center justify-center gap-3">
                                                    {l.location && l.location.lat ? (
                                                        <button onClick={()=>setMapLogs([l])} className="px-4 py-2 bg-indigo-50 text-indigo-600 hover:bg-indigo-600 hover:text-white rounded-xl font-black text-[9px] uppercase tracking-widest flex items-center justify-center gap-2 active:scale-95 transition-all">
                                                            MAPA
                                                        </button>
                                                    ) : <span className="text-[9px] text-slate-300 font-bold uppercase tracking-widest">Sin GPS</span>}
                                                    {l.photo && <img src={l.photo} onClick={()=>setPreviewImage(l.photo)} className="w-10 h-10 rounded-xl object-cover cursor-pointer hover:scale-110 transition-transform border border-slate-200 shadow-sm" />}
                                                </td>
                                            </tr>
                                        )
                                    })}
                                </tbody>
                            </table>
                        </div>
                    </div>
                )}

                {tab === 'users' && (
                    <div className="grid lg:grid-cols-3 gap-6 fade-in">
                        <form onSubmit={handleUserSubmit} className="bg-white p-8 rounded-[3rem] shadow-sm space-y-4 h-fit border-t-[12px] border-indigo-600">
                            <h3 className="font-black text-lg">{editingUser ? "Editar Usuario" : "Nuevo Usuario"}</h3>
                            
                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block tracking-widest">Nombre Completo</label>
                                <input name="name" defaultValue={editingUser?.name} placeholder="Ej. Juan Pérez" className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none focus:ring-2 focus:ring-indigo-100" required />
                            </div>

                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block tracking-widest">Código / ID de Colaborador (Alias de Login)</label>
                                <input name="alias" defaultValue={editingUser?.alias} placeholder="Ej. EMP-001 o CD_Usuario1" className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none focus:ring-2 focus:ring-indigo-100" required />
                            </div>

                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block tracking-widest">Correo Electrónico</label>
                                <input name="email" defaultValue={editingUser?.email} type="email" placeholder="usuario@empresa.com" className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none focus:ring-2 focus:ring-indigo-100" required />
                            </div>

                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block tracking-widest">PIN / Contraseña</label>
                                <input name="pass" defaultValue="" placeholder={editingUser ? "Dejar vacío para mantener el actual" : "PIN o Clave de acceso"} className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none focus:ring-2 focus:ring-indigo-100" required={!editingUser} />
                            </div>

                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block tracking-widest">Rol de Usuario</label>
                                <select name="role" defaultValue={editingUser?.role || 'empleado'} className="w-full p-4 bg-slate-50 rounded-2xl font-bold uppercase outline-none focus:ring-2 focus:ring-indigo-100">
                                    <option value="empleado">EMPLEADO</option>
                                    <option value="propietario">PROPIETARIO / ADMIN</option>
                                    {roles.map(r => <option key={r.name || r} value={r.name || r}>{r.name || r}</option>)}
                                </select>
                            </div>

                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block tracking-widest">Estado</label>
                                <select name="status" defaultValue={editingUser?.status || 'activo'} className="w-full p-4 bg-slate-50 rounded-2xl font-bold uppercase outline-none focus:ring-2 focus:ring-indigo-100">
                                    <option value="activo">ACTIVO</option>
                                    <option value="baja">BAJA</option>
                                    <option value="subsidio">SUBSIDIO</option>
                                    <option value="feriado">FERIADO</option>
                                </select>
                            </div>

                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block tracking-widest">Contratación (Inicio Vacaciones)</label>
                                <input name="date" type="date" defaultValue={editingUser?.hiringDate || window.getNICDate()} className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none focus:ring-2 focus:ring-indigo-100" required />
                            </div>

                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block tracking-widest">Días Históricos Gastados</label>
                                <input name="vused" type="number" step="0.5" defaultValue={editingUser?.vacationDaysUsed || 0} className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none focus:ring-2 focus:ring-indigo-100" />
                            </div>

                            <div className="flex gap-2 pt-4">
                                {editingUser && <button type="button" onClick={()=>{setEditingUser(null); document.querySelector('form').reset();}} className="w-1/3 py-4 bg-slate-100 text-slate-500 font-black rounded-2xl uppercase">X</button>}
                                <button className="flex-1 py-4 bg-indigo-600 text-white font-black rounded-2xl uppercase shadow-lg active:scale-95 transition-all">Guardar Usuario</button>
                            </div>
                        </form>

                        <div className="lg:col-span-2 space-y-4">
                            {globalUsers.map(u => {
                                const isLocked = isUserLockedToday(u);
                                return (
                                    <div key={u.id} className="bg-white p-6 rounded-[2.5rem] flex flex-col md:flex-row justify-between items-center shadow-sm gap-4 border border-transparent hover:border-slate-100 transition-colors">
                                        <div className="w-full md:w-auto text-center md:text-left">
                                            <h4 className="font-black text-slate-800 text-sm">{u.name}</h4>
                                            <p className="text-[9px] text-slate-400 font-black uppercase tracking-widest mt-1">
                                                CÓDIGO/ALIAS: <span className="text-indigo-600 font-black">@{u.alias}</span> • ID #{u.id} • {u.role} • <span className={u.status==='activo'?'text-emerald-600':'text-red-500'}>{u.status}</span>
                                            </p>
                                        </div>
                                        <div className="flex gap-2 flex-wrap justify-center">
                                            {isLocked ? (
                                                <button onClick={()=>toggleLock(u, false)} className="px-4 py-3 bg-emerald-50 text-emerald-600 rounded-xl font-black uppercase text-[10px] active:scale-95 transition-all">Desbloquear</button>
                                            ) : (
                                                <button onClick={()=>toggleLock(u, true)} className="px-4 py-3 bg-orange-50 text-orange-600 rounded-xl font-black uppercase text-[10px] active:scale-95 transition-all">Bloquear</button>
                                            )}
                                            <button onClick={()=>setEditingUser(u)} className="px-4 py-3 bg-slate-50 text-slate-600 rounded-xl font-black uppercase text-[10px] active:scale-95 transition-all">Editar</button>
                                            <button onClick={()=>confirmAction("Borrar por completo al usuario de la base de datos.", ()=>deleteUser(u.id))} className="px-4 py-3 bg-red-50 text-red-600 rounded-xl font-black uppercase text-[10px] active:scale-95 transition-all">Borrar</button>
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                )}

                {tab === 'vacations' && (
                    <div className="grid lg:grid-cols-3 gap-6 fade-in">
                        <div className="bg-white p-8 rounded-[3rem] shadow-sm space-y-4 h-fit border-t-[12px] border-emerald-500">
                            <h3 className="font-black text-lg text-slate-900">Reglas Vacacionales</h3>
                            <p className="text-[11px] text-slate-500 font-medium leading-relaxed">Tasa maestra de acumulación mensual por cada 30 días naturales trabajados.</p>
                            <input type="number" step="0.1" value={vacRate} onChange={e=>setVacRate(e.target.value)} className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none focus:ring-2 focus:ring-emerald-100 text-slate-800" />
                            <button onClick={updateVacationRate} className="w-full py-4 bg-emerald-600 text-white font-black rounded-2xl uppercase tracking-widest text-[10px] shadow-lg active:scale-95 transition-all">Guardar Configuración</button>
                        </div>
                        
                        <div className="lg:col-span-2 space-y-10">
                            <div>
                                <h3 className="font-black text-sm uppercase tracking-widest text-slate-800 border-b border-slate-200 pb-3 mb-6">Solicitudes Entrantes</h3>
                                {vacations.filter(v => v.status === 'pending').length === 0 ? (
                                    <div className="bg-white rounded-[2.5rem] p-8 text-center border border-slate-100 shadow-sm"><p className="text-xs font-bold text-slate-400">Bandeja limpia.</p></div>
                                ) : (
                                    vacations.filter(v => v.status === 'pending').map(v => (
                                        <div key={v.id} className="bg-yellow-50 p-6 rounded-[2.5rem] flex flex-col md:flex-row justify-between items-center shadow-sm gap-4 border border-yellow-200 mb-4">
                                            <div className="text-center md:text-left">
                                                <h4 className="font-black text-slate-900 text-base">{v.userName}</h4>
                                                <p className="text-[10px] text-yellow-800 font-black uppercase tracking-widest mt-1 bg-yellow-200 px-2 py-1 rounded inline-block">Pide: {v.type === 'half' ? 'MEDIO DÍA (0.5)' : `${window.getDaysDiff(v.startDate, v.endDate || v.startDate)} DÍA(S)`}</p>
                                                <p className="text-[10px] text-slate-600 font-bold uppercase mt-2">Del {window.formatDateToNIC?window.formatDateToNIC(v.startDate):v.startDate} {v.type==='range' ? `al ${window.formatDateToNIC?window.formatDateToNIC(v.endDate):v.endDate}`:''}</p>
                                            </div>
                                            <div className="flex gap-2">
                                                <button onClick={()=>setVacationStatus(v.id, 'approved')} className="px-6 py-4 bg-emerald-500 text-white rounded-2xl font-black uppercase text-[10px] shadow-lg active:scale-95 transition-all">Aprobar</button>
                                                <button onClick={()=>setVacationStatus(v.id, 'denied')} className="px-6 py-4 bg-white text-red-600 rounded-2xl font-black uppercase text-[10px] active:scale-95 transition-all border border-red-200">Denegar</button>
                                            </div>
                                        </div>
                                    ))
                                )}
                            </div>

                            <div>
                                <div className="flex items-center justify-between border-b border-slate-200 pb-3 mb-6">
                                    <h3 className="font-black text-sm uppercase tracking-widest text-slate-800">Saldos</h3>
                                    <span className="text-[9px] text-slate-400 bg-slate-100 px-3 py-1.5 rounded-full font-black tracking-widest">TOCA EL NOMBRE PARA GESTIONAR</span>
                                </div>
                                <div className="bg-white rounded-[3rem] shadow-sm overflow-hidden border border-slate-100">
                                    <table className="w-full text-left">
                                        <thead className="bg-slate-50 text-[9px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">
                                            <tr><th className="p-6">Consultor (Perfil)</th><th className="p-6 text-center">Disponible</th><th className="p-6">Contrato</th></tr>
                                        </thead>
                                        <tbody className="divide-y divide-slate-50">
                                            {globalUsers.map(u => (
                                                <tr key={u.id} className="hover:bg-slate-50/50 transition-colors cursor-pointer group" onClick={() => setSelectedUserVacation(u)}>
                                                    <td className="p-6 font-black text-slate-800 text-xs">{u.name}</td>
                                                    <td className="p-6 font-black text-emerald-600 text-lg text-center">{window.calculateVacationBalance(u, settings?.vacationRate||2.5, vacations)}</td>
                                                    <td className="p-6 font-bold text-[10px] text-slate-400">{window.formatDateToNIC?window.formatDateToNIC(u.hiringDate):u.hiringDate}</td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <div>
                                <div className="flex justify-between items-center border-b border-slate-200 pb-3 mb-6">
                                    <h3 className="font-black text-sm uppercase tracking-widest text-slate-800">Aprobadas General</h3>
                                    <div className="flex gap-2 items-center bg-white rounded-full shadow-sm border border-slate-200 px-2 py-1">
                                        <button disabled={vacPage===0} onClick={()=>setVacPage(p=>p-1)} className={`p-2 rounded-full transition-colors ${vacPage===0?'opacity-30':'hover:bg-slate-100 text-slate-600'}`}><AdminIcon className="w-4 h-4" name="chevron-left" /></button>
                                        <span className="text-[10px] font-black text-slate-400 px-3 tracking-widest">{vacPage+1} / {totalVacPages||1}</span>
                                        <button disabled={vacPage>=(totalVacPages-1)} onClick={()=>setVacPage(p=>p+1)} className={`p-2 rounded-full transition-colors ${vacPage>=(totalVacPages-1)?'opacity-30':'hover:bg-slate-100 text-slate-600'}`}><AdminIcon className="w-4 h-4" name="chevron-right" /></button>
                                    </div>
                                </div>
                                {paginatedVacs.length === 0 ? <p className="text-xs font-bold text-slate-400">Sin registros históricos.</p> : 
                                    paginatedVacs.map(v => (
                                        <div key={v.id} className="bg-white p-6 rounded-[2.5rem] border border-slate-100 shadow-sm flex flex-col md:flex-row justify-between items-center mb-4 transition-all hover:shadow-md">
                                            <div className="text-center md:text-left">
                                                <h4 className="font-black text-slate-800 text-sm">{v.userName}</h4>
                                                <p className="text-[10px] text-slate-500 font-bold uppercase mt-1 tracking-widest">
                                                    FECHAS: {window.formatDateToNIC?window.formatDateToNIC(v.startDate):v.startDate} {v.type==='range'?` AL ${window.formatDateToNIC?window.formatDateToNIC(v.endDate):v.endDate}`:''}
                                                </p>
                                                {v.revokedDates && v.revokedDates.length > 0 && <p className="text-[9px] font-black text-orange-600 mt-2 tracking-widest">*{v.revokedDates.length} DÍAS REVOCADOS</p>}
                                                {v.type === 'paid' && <p className="text-[9px] font-black text-indigo-600 mt-2 tracking-widest">*PAGO EN EFECTIVO ({v.paidDays} DÍAS)</p>}
                                            </div>
                                        </div>
                                    ))
                                }
                            </div>
                        </div>
                    </div>
                )}

                {tab === 'absences' && (
                    <div className="grid lg:grid-cols-3 gap-6 fade-in">
                        <form onSubmit={saveAbsence} className="bg-white p-8 rounded-[3rem] shadow-sm space-y-4 h-fit border-t-[12px] border-red-500">
                            <h3 className="font-black text-lg">Registrar Ausencia</h3>
                            <p className="text-[10px] text-slate-400 font-bold uppercase leading-relaxed mb-4">Si seleccionas "Descontar", se restará automáticamente 1 día de las vacaciones del empleado.</p>
                            
                            <select value={absenceUser} onChange={e=>setAbsenceUser(e.target.value)} className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none focus:ring-2 focus:ring-red-100" required>
                                <option value="">Seleccionar Consultor...</option>
                                {globalUsers.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
                            </select>
                            
                            <input type="date" value={absenceDate} onChange={e=>setAbsenceDate(e.target.value)} className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none focus:ring-2 focus:ring-red-100" required />
                            
                            <select value={absenceType} onChange={e=>setAbsenceType(e.target.value)} className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none uppercase text-[10px] focus:ring-2 focus:ring-red-100">
                                <option value="injustificada">Falta Injustificada</option>
                                <option value="justificada">Falta Justificada</option>
                                <option value="descontada">Descontar de Vacaciones (-1 Día)</option>
                            </select>

                            <textarea value={absenceNotes} onChange={e=>setAbsenceNotes(e.target.value)} placeholder="Motivo o nota (opcional)..." className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none h-24 resize-none focus:ring-2 focus:ring-red-100" />

                            <button type="submit" className="w-full py-4 bg-red-600 text-white font-black rounded-2xl uppercase tracking-widest text-[10px] shadow-lg active:scale-95 transition-all">Aplicar Registro</button>
                        </form>
                        
                        <div className="lg:col-span-2 space-y-4">
                            <h3 className="font-black text-lg uppercase tracking-widest text-slate-800 border-b pb-2 mb-4">Historial de Ausencias</h3>
                            {absences.length === 0 ? <p className="text-xs font-bold text-slate-400">Sin registros de ausencias.</p> :
                                absences.sort((a,b)=>b.createdAt - a.createdAt).map(a => (
                                    <div key={a.id} className="bg-white p-6 rounded-[2.5rem] flex flex-col md:flex-row justify-between items-center shadow-sm border-l-8 border-red-500 gap-4 hover:border-slate-200 transition-colors">
                                        <div>
                                            <h4 className="font-black text-slate-800">{a.userName}</h4>
                                            <p className="text-[10px] text-slate-500 font-bold uppercase mt-1 tracking-widest">Fecha de falta: {window.formatDateToNIC?window.formatDateToNIC(a.date):a.date}</p>
                                            <p className={`text-[9px] font-black uppercase mt-3 tracking-widest px-3 py-1.5 inline-block rounded-lg shadow-sm border ${a.type==='injustificada'?'bg-white text-red-600 border-red-100':a.type==='justificada'?'bg-white text-emerald-600 border-emerald-100':'bg-white text-orange-600 border-orange-100'}`}>
                                                {a.type.replace('_', ' ')}
                                            </p>
                                            {a.notes && <p className="text-[11px] text-slate-600 italic mt-3 bg-slate-50 p-3 rounded-xl">"{a.notes}"</p>}
                                        </div>
                                        <button onClick={()=>confirmAction("¿Borrar este registro de ausencia?", async ()=>{ await window.apiCall('delete_absence', {id: a.id}); setConfirmModal(null); showToast("Eliminado."); })} className="text-slate-400 font-black text-[9px] uppercase tracking-widest underline hover:text-red-500 transition-colors">Borrar Registro</button>
                                    </div>
                                ))
                            }
                        </div>
                    </div>
                )}

                {tab === 'roles' && (
                    <div className="grid lg:grid-cols-2 gap-6 fade-in">
                        <div className="lg:col-span-2 bg-white p-8 rounded-[3rem] shadow-sm space-y-4 border-t-[12px] border-emerald-500 mb-2">
                            <h3 className="font-black text-lg text-slate-900">Configuración de Botones (Marcajes)</h3>
                            <p className="text-[11px] text-slate-500 font-medium leading-relaxed">Crea o renombra los botones que ven los usuarios en la aplicación. Usa el ícono de edición para modificar su nombre visible sin romper el historial.</p>
                            
                            <div className="flex flex-col md:flex-row gap-4 mb-4">
                                <input value={newActionLabel} onChange={e=>setNewActionLabel(e.target.value)} placeholder="Nombre del nuevo botón (Ej: Permiso Médico)..." className="flex-1 p-4 bg-slate-50 rounded-2xl font-bold uppercase outline-none focus:ring-2 focus:ring-emerald-100" />
                                <button onClick={saveCustomAction} className="py-4 px-8 bg-emerald-600 text-white font-black rounded-2xl uppercase tracking-widest text-[10px] shadow-lg active:scale-95 transition-all">
                                    {editingActionId ? 'Guardar Cambios' : 'Crear Botón'}
                                </button>
                                {editingActionId && <button onClick={()=>{setEditingActionId(null); setNewActionLabel('');}} className="py-4 px-8 bg-slate-100 text-slate-500 font-black rounded-2xl uppercase tracking-widest text-[10px] active:scale-95 transition-all">Cancelar</button>}
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                                {actions.map(a => (
                                    <div key={a.id} className="p-5 rounded-2xl border-2 border-slate-100 flex justify-between items-center bg-slate-50">
                                        <span className="font-black text-xs text-slate-700 uppercase">{a.label}</span>
                                        <div className="flex gap-2">
                                            <button onClick={()=>{setEditingActionId(a.id); setNewActionLabel(a.label);}} className="p-2 bg-white text-indigo-500 rounded-xl shadow-sm border border-slate-200 active:scale-95"><AdminIcon className="w-4 h-4" name="edit"/></button>
                                            <button onClick={()=>deleteCustomAction(a)} className="p-2 bg-white text-red-500 rounded-xl shadow-sm border border-slate-200 active:scale-95"><AdminIcon className="w-4 h-4" name="x"/></button>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>

                        <div className="bg-white p-8 rounded-[3rem] shadow-sm space-y-4 h-fit border-t-[12px] border-indigo-600">
                            <h3 className="font-black text-lg">{editingRoleName ? "Editar Rol" : "Nuevo Rol"}</h3>
                            <input value={newRoleName} onChange={e=>setNewRoleName(e.target.value)} placeholder="Nombre del Rol (Ej: VENTAS)" className="w-full p-4 bg-slate-50 rounded-2xl font-bold uppercase outline-none focus:ring-2" />
                            
                            <h4 className="font-black text-[10px] uppercase text-slate-400 mt-6 mb-2 tracking-widest">Permisos (Mostrar Botones)</h4>
                            <div className="grid grid-cols-2 gap-2">
                                {actions.map(a => (
                                    <button key={a.id} type="button" onClick={()=>{setSelectedPermissions(prev => prev.includes(a.id) ? prev.filter(p => p !== a.id) : [...prev, a.id]);}} className={`p-4 rounded-2xl font-black text-[10px] uppercase border active:scale-95 transition-all ${selectedPermissions.includes(a.id)?'bg-indigo-600 text-white border-indigo-600 shadow-md':'bg-slate-50 text-slate-500 hover:bg-slate-100'}`}>{a.label}</button>
                                ))}
                            </div>

                            <h4 className="font-black text-[10px] uppercase text-slate-400 mt-6 mb-2 tracking-widest">Exigir Foto al Marcar</h4>
                            <div className="grid grid-cols-2 gap-2">
                                {[{id:'entrada', label:'Entrada'}, {id:'salida', label:'Salida'}, ...actions].map(a => (
                                    <button key={'cam_'+a.id} type="button" onClick={()=>{setSelectedCameraActions(prev => prev.includes(a.id) ? prev.filter(p => p !== a.id) : [...prev, a.id]);}} className={`p-4 rounded-2xl font-black text-[10px] uppercase border active:scale-95 transition-all flex items-center justify-center gap-1 ${selectedCameraActions.includes(a.id)?'bg-emerald-500 text-white border-emerald-500 shadow-md':'bg-slate-50 text-slate-500 hover:bg-slate-100'}`}>
                                        <svg className="w-3 h-3" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"></path><path strokeLinecap="round" strokeLinejoin="round" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z"></path></svg>
                                        {a.label}
                                    </button>
                                ))}
                            </div>

                            <div className="flex gap-2 mt-6">
                                {editingRoleName && <button type="button" onClick={()=>{setEditingRoleName(null); setNewRoleName(''); setSelectedPermissions([]); setSelectedCameraActions([]);}} className="w-1/3 py-4 bg-slate-100 text-slate-500 font-black rounded-2xl uppercase">X</button>}
                                <button onClick={saveRole} className="flex-1 py-4 bg-indigo-600 text-white font-black rounded-2xl uppercase shadow-lg active:scale-95 transition-all tracking-widest text-[10px]">Guardar Perfil</button>
                            </div>
                        </div>
                        <div className="space-y-4">
                            {roles.map(r => {
                                const rName = r.name || r; const rPerms = r.permissions || []; const rCam = r.cameraActions || ['entrada', 'salida', 'visita_in'];
                                return (
                                    <div key={rName} className="bg-white p-6 rounded-[2.5rem] flex flex-col md:flex-row justify-between items-center shadow-sm gap-4 border border-transparent hover:border-slate-100 transition-colors">
                                        <div className="text-center md:text-left">
                                            <h4 className="font-black text-slate-800 uppercase">{rName}</h4>
                                            <p className="text-[9px] text-slate-400 font-bold uppercase tracking-widest mt-1 max-w-[200px] leading-relaxed">Permisos: {rPerms.join(' • ')}</p>
                                        </div>
                                        <button onClick={()=>{setEditingRoleName(rName); setNewRoleName(rName); setSelectedPermissions(rPerms); setSelectedCameraActions(rCam);}} className="px-6 py-3 bg-slate-50 text-indigo-600 rounded-xl font-black uppercase text-[10px] active:scale-95 transition-all shadow-sm">Editar</button>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                )}

                {tab === 'notif' && (
                    <div className="grid lg:grid-cols-3 gap-6 fade-in">
                        <div className="bg-white p-8 rounded-[3rem] shadow-sm space-y-4 h-fit border-t-[12px] border-indigo-600">
                            <h3 className="font-black text-lg">{editingReminderId ? "Editar Aviso" : "Nuevo Aviso General"}</h3>
                            <input value={notifTitle} onChange={e=>setNotifTitle(e.target.value)} placeholder="Título Impactante" className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none focus:ring-2" />
                            <textarea value={notifBody} onChange={e=>setNotifBody(e.target.value)} placeholder="El mensaje que leerán..." className="w-full p-4 bg-slate-50 rounded-2xl h-28 outline-none focus:ring-2 resize-none" />
                            <div className="max-h-36 overflow-y-auto space-y-1 p-2 bg-slate-50 border rounded-2xl shadow-inner">
                                {globalUsers.map(u => (
                                    <button key={u.id} type="button" onClick={()=>setTargetUsers(p=>p.includes(u.id)?p.filter(id=>id!==u.id):[...p, u.id])} className={`w-full p-3 rounded-xl text-left font-bold text-[11px] transition-colors ${targetUsers.includes(u.id)?'bg-indigo-600 text-white shadow-md':'hover:bg-slate-200 text-slate-600'}`}>{u.name}</button>
                                ))}
                            </div>
                            <div className="flex gap-2 mt-4">
                                {editingReminderId && <button type="button" onClick={()=>{setEditingReminderId(null); setNotifTitle(''); setNotifBody(''); setTargetUsers([]);}} className="w-1/3 py-4 bg-slate-100 text-slate-500 font-black rounded-2xl uppercase">X</button>}
                                <button onClick={saveNotification} className="flex-1 py-4 bg-indigo-600 text-white font-black rounded-2xl uppercase shadow-lg active:scale-95 transition-all tracking-widest text-[10px]">Difundir Aviso</button>
                            </div>
                        </div>
                        <div className="lg:col-span-2 space-y-4">
                            {reminders.map(r => (
                                <div key={r.id} className="bg-white p-6 rounded-[2.5rem] flex flex-col md:flex-row justify-between items-start shadow-sm gap-4 border-l-8 border-indigo-600 hover:border-slate-100 transition-colors">
                                    <div className="flex-1"><h4 className="font-black text-slate-800 text-base">{r.title}</h4><p className="text-[11px] font-medium text-slate-500 mt-2 leading-relaxed">{r.message}</p></div>
                                    <div className="flex gap-2">
                                        <button onClick={()=>{setEditingReminderId(r.id); setNotifTitle(r.title); setNotifBody(r.message); setTargetUsers(r.targetUsers||[]);}} className="px-5 py-3 bg-slate-50 text-slate-600 rounded-xl font-black uppercase text-[10px] active:scale-95 transition-all">Editar</button>
                                        <button onClick={()=>confirmAction("Eliminar aviso de forma permanente de todos los usuarios.", async ()=>{ await window.apiCall('delete_reminder', {id: r.id}); setConfirmModal(null); showToast('Eliminado.'); })} className="px-5 py-3 bg-red-50 text-red-600 rounded-xl font-black uppercase text-[10px] active:scale-95 transition-all">Borrar</button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}
            </main>
        </div>
    );
};