const UiIconAdmin = ({ name, className = "w-5 h-5" }) => {
    const icons = {
        'dashboard': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"></path></svg>,
        'users': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"></path></svg>,
        'contracts': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg>,
        'shield': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path></svg>,
        'file-text': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg>,
        'bell': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"></path></svg>,
        'dollar': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>,
        'sun': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"></path></svg>,
        'x-circle': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>,
        'settings': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path><path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path></svg>
    };
    return icons[name] || null;
};

window.AdminDashboard = function({ 
    currentUser,
    globalUsers = [], 
    logs = [], 
    roles = [], 
    reminders = [], 
    vacations = [], 
    settings = {}, 
    actions = [], 
    absences = [], 
    masterClients = [], 
    activeClientId, 
    setActiveClientId, 
    refreshData, 
    setView, 
    onLogout 
}) {
    const isMaster = window.SHIFT_CONFIG && window.SHIFT_CONFIG.isMaster;
    
    // Inicia siempre en Auditoría ('logs') por defecto
    const [tab, setTab] = React.useState(isMaster && activeClientId === 0 ? 'master' : 'logs');
    const [toastMsg, ReactSetToastMsg] = React.useState('');
    const [isPunching, setIsPunching] = React.useState(false);

    // Identificar permisos de Sólo Lectura
    const currentRoleObj = (roles || []).find(r => (r.name || '').toLowerCase() === (currentUser?.role || currentUser?.role_name || '').toLowerCase());
    const isReadOnly = (currentUser?.accessLevel === 'readonly' || currentUser?.accessLevel === 'read_only' || currentRoleObj?.accessLevel === 'readonly' || currentRoleObj?.accessLevel === 'read_only');

    const [confirmModal, setConfirmModal] = React.useState(null);
    const [previewImage, setPreviewImage] = React.useState(null);

    const [showClientModal, setShowClientModal] = React.useState(false);
    const [editingClient, setEditingClient] = React.useState(null);

    const [mapLogs, setMapLogs] = React.useState(null); 
    const mapContainerRef = React.useRef(null);
    const mapInstanceRef = React.useRef(null);
    const liveMarkersRef = React.useRef({});

    const [editingUser, setEditingUser] = React.useState(null);

    const [companyLogoUrl, setCompanyLogoUrl] = React.useState(settings?.logoUrl || '');
    const [showCompanyLogo, setShowCompanyLogo] = React.useState(settings?.showCompanyLogo !== false);
    const [inssRate, setInssRate] = React.useState(settings?.inssPatronalRate || 22.5);
    const [lunchLimitMinutes, setLunchLimitMinutes] = React.useState(settings?.lunchLimitMinutes || 60);
    const [gracePeriodMinutes, setGracePeriodMinutes] = React.useState(settings?.gracePeriodMinutes || 5);
    const [maxTardinessAllowed, setMaxTardinessAllowed] = React.useState(settings?.maxTardinessAllowed || 3);
    const [tardinessPenaltyAction, setTardinessPenaltyAction] = React.useState(settings?.tardinessPenaltyAction || 'deduct_minutes');
    const [reasonsList, setReasonsList] = React.useState(settings?.exceptionReasons || ['Horas extras autorizadas', 'Solicitud de gerencia', 'Cobertura de turno especial']);
    const [newReasonInput, setNewReasonInput] = React.useState('');

    const [vacRate, setVacRate] = React.useState(settings?.vacationRate || 2.5);
    const [selectedUserVacation, setSelectedUserVacation] = React.useState(null); 

    const showToast = (msg) => { ReactSetToastMsg(msg); setTimeout(() => ReactSetToastMsg(''), 3000); };
    const confirmAction = (message, action) => {
        if (isReadOnly) return alert("Modo supervisión: no tienes permisos para realizar esta acción.");
        setConfirmModal({ message, action });
    };

    // Último estado de marcaje del Administrador hoy
    const todayAdminLogs = React.useMemo(() => {
        const todayStr = window.getNICDate ? window.getNICDate() : new Date().toISOString().split('T')[0];
        return (logs || []).filter(l => Number(l.userId) === Number(currentUser?.id) && l.date === todayStr);
    }, [logs, currentUser]);

    const lastAdminLog = todayAdminLogs.length > 0 ? todayAdminLogs[0] : null;
    const isCurrentlyCheckedIn = lastAdminLog && lastAdminLog.type !== 'salida';

    // MARCAJE RÁPIDO PARA ADMINS/SUPERVISORES
    const handleQuickPunch = async (punchType) => {
        setIsPunching(true);
        let coords = { lat: 0, lng: 0 };
        
        try {
            if (navigator.geolocation) {
                const pos = await new Promise((resolve) => {
                    navigator.geolocation.getCurrentPosition(resolve, () => resolve(null), { timeout: 4000 });
                });
                if (pos && pos.coords) {
                    coords = { lat: pos.coords.latitude, lng: pos.coords.longitude };
                }
            }
        } catch (eGeo) {}

        const now = Date.now();
        const dateStr = window.getNICDate ? window.getNICDate() : new Date().toISOString().split('T')[0];

        try {
            const res = await window.apiCall('save_log', {
                userId: currentUser.id,
                type: punchType,
                timestamp: now,
                date: dateStr,
                location: coords,
                client: 'Marcaje Rápido',
                justification: null
            });

            if (res && res.success) {
                showToast(`¡${punchType.toUpperCase()} registrada con éxito!`);
                if (refreshData) await refreshData();
            } else {
                showToast("Error al registrar marcaje: " + (res?.error || ""));
            }
        } catch (err) {
            showToast("Error de conexión al marcar.");
        } finally {
            setIsPunching(false);
        }
    };

    React.useEffect(() => {
        setCompanyLogoUrl(settings?.logoUrl || '');
        setShowCompanyLogo(settings?.showCompanyLogo !== false);
        setInssRate(settings?.inssPatronalRate || 22.5);
        setLunchLimitMinutes(settings?.lunchLimitMinutes || 60);
        setGracePeriodMinutes(settings?.gracePeriodMinutes || 5);
        setMaxTardinessAllowed(settings?.maxTardinessAllowed || 3);
        setTardinessPenaltyAction(settings?.tardinessPenaltyAction || 'deduct_minutes');
        setReasonsList(settings?.exceptionReasons || ['Horas extras autorizadas', 'Solicitud de gerencia', 'Cobertura de turno especial']);
        setVacRate(settings?.vacationRate || 2.5);
    }, [settings]);

    // MAPA GPS
    React.useEffect(() => {
        if (!mapLogs || mapLogs.length === 0 || !mapContainerRef.current) return;

        if (mapInstanceRef.current) {
            mapInstanceRef.current.remove();
            mapInstanceRef.current = null;
        }
        liveMarkersRef.current = {};

        const validCoords = mapLogs.filter(l => l.location && l.location.lat && l.location.lng);
        if (validCoords.length === 0) {
            showToast("Los registros seleccionados no contienen coordenadas GPS.");
            setMapLogs(null);
            return;
        }

        const initialPoint = [validCoords[0].location.lat, validCoords[0].location.lng];
        const map = L.map(mapContainerRef.current).setView(initialPoint, 14);
        mapInstanceRef.current = map;

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap'
        }).addTo(map);

        const latLngs = [];
        const sortedPoints = [...validCoords].sort((a, b) => a.timestamp - b.timestamp);

        sortedPoints.forEach((log, index) => {
            const pos = [log.location.lat, log.location.lng];
            latLngs.push(pos);

            const isStart = log.type === 'entrada';
            const isEnd = log.type === 'salida';
            const color = isStart ? '#10b981' : isEnd ? '#ef4444' : '#6366f1';
            const userInitial = (log.userName || 'U')[0].toUpperCase();

            const avatarHtml = log.avatarUrl
                ? `<div style="width:38px; height:38px; border-radius:50%; border:3px solid ${color}; overflow:hidden; box-shadow:0 4px 10px rgba(0,0,0,0.3); background:#fff;"><img src="${log.avatarUrl}" style="width:100%; height:100%; object-fit:cover;" /></div>`
                : `<div style="width:38px; height:38px; border-radius:50%; border:3px solid ${color}; background:${color}; color:#fff; display:flex; align-items:center; justify-content:center; font-weight:900; font-size:14px; box-shadow:0 4px 10px rgba(0,0,0,0.3);">${userInitial}</div>`;

            const customIcon = L.divIcon({
                html: avatarHtml,
                className: 'custom-avatar-marker',
                iconSize: [38, 38],
                iconAnchor: [19, 19]
            });

            const marker = L.marker(pos, { icon: customIcon }).addTo(map);
            const timeStr = window.formatNICTimeFull ? window.formatNICTimeFull(log.timestamp) : new Date(log.timestamp).toLocaleTimeString();
            
            marker.bindPopup(`
                <div style="font-family:sans-serif; font-size:11px; padding:4px;">
                    <strong style="color:#0f172a; font-size:12px;">${log.userName || 'Colaborador'}</strong><br/>
                    <span style="display:inline-block; margin-top:3px; padding:2px 6px; background:${color}; color:#fff; border-radius:4px; font-weight:bold; font-size:9px;">
                        #${index + 1} • ${log.type.toUpperCase()}
                    </span><br/>
                    <div style="margin-top:4px; color:#64748b;"><strong>Hora:</strong> ${timeStr}</div>
                </div>
            `);

            liveMarkersRef.current[log.id] = marker;
        });

        if (latLngs.length > 1) {
            L.polyline(latLngs, { color: '#4f46e5', weight: 4, opacity: 0.75, dashArray: '8, 8' }).addTo(map);
            map.fitBounds(L.latLngBounds(latLngs), { padding: [40, 40] });
        }

        setTimeout(() => {
            if (mapInstanceRef.current) mapInstanceRef.current.invalidateSize();
        }, 300);
    }, [mapLogs]);

    const handlePortalChange = (newId) => {
        const idNum = Number(newId);
        if (setActiveClientId) setActiveClientId(idNum);
        if (idNum === 0) setTab('master');
        else if (tab === 'master') setTab('logs');
    };

    const handleUserSubmit = async (e) => {
        e.preventDefault();
        if (isReadOnly) return showToast("Modo supervisión: no tienes permisos de edición.");

        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') || 'activo',
            hiringDate: f.get('date') || window.getNICDate(), 
            vacationDaysUsed: parseFloat(f.get('vused')) || 0,
            scheduleDays: JSON.parse(f.get('scheduleDays') || '["lun","mar","mie","jue","vie"]'),
            scheduleStart: f.get('schedule_start') || '08:00',
            scheduleEnd: f.get('schedule_end') || '17:00',
            scheduleCustom: JSON.parse(f.get('scheduleCustom') || '{}'),
            hasInss: f.get('hasInss') === '1' || f.get('hasInss') === 1,
            inssNumber: f.get('inssNumber') || null,
            baseSalary: parseFloat(f.get('base_salary')) || 0,
            appliesInss: f.get('applies_inss') ? 1 : 0,
            appliesIr: f.get('applies_ir') ? 1 : 0,
            gpsTrackingEnabled: f.get('gps_tracking_enabled') ? 1 : 0,
            avatar_base64: f.get('avatar_base64') || null,
            idCard: f.get('id_card') || null,
            civilStatus: f.get('civil_status') || 'Soltero(a)',
            profession: f.get('profession') || 'Trabajador(a)',
            homeAddress: f.get('home_address') || null,
            positionTitle: f.get('position_title') || null,
            paymentFrequency: f.get('payment_frequency') || 'Quincenal',
            overrideCheckOut: editingUser ? (editingUser.overrideCheckOut || false) : false,
            manualLock: editingUser ? (editingUser.manualLock || false) : false
        };
        try {
            const res = await window.apiCall('save_user', data);
            if(res.success) {
                setEditingUser(null); 
                showToast("Usuario guardado exitosamente.");
                if (refreshData) await refreshData();
            } else {
                showToast("Error al guardar: " + (res.error || "Desconocido"));
            }
        } catch (err) { showToast("Error de conexión al guardar usuario."); }
    };

    const deleteUser = async (id) => {
        if (isReadOnly) return showToast("Modo supervisión: no tienes permisos para eliminar.");
        await window.apiCall('delete_user', { id });
        setConfirmModal(null); showToast("Usuario borrado.");
        if (refreshData) await refreshData();
    };

    const toggleLock = async (u, lockStatus) => {
        if (isReadOnly) return showToast("Modo supervisión: no tienes permisos de bloqueo.");
        await window.apiCall('toggle_user_lock', { id: u.id, manualLock: lockStatus, overrideCheckOut: !lockStatus });
        showToast(lockStatus ? "Bloqueado." : "Desbloqueado.");
        if (refreshData) await refreshData();
    };

    const saveCompanySettings = async (extraPayload = {}) => {
        if (isReadOnly) return showToast("Modo supervisión: no tienes permisos de configuración.");
        const res = await window.apiCall('update_settings', {
            vacation_rate: parseFloat(vacRate) || 2.5,
            exception_reasons: reasonsList,
            inss_patronal_rate: parseFloat(inssRate) || 22.5,
            lunch_limit_minutes: parseInt(lunchLimitMinutes) || 60,
            grace_period_minutes: parseInt(gracePeriodMinutes) || 5,
            max_tardiness_allowed: parseInt(maxTardinessAllowed) || 3,
            tardiness_penalty_action: tardinessPenaltyAction || 'deduct_minutes',
            show_company_logo: showCompanyLogo ? 1 : 0,
            ...extraPayload
        });
        if (res.success && res.logo_url) {
            setCompanyLogoUrl(res.logo_url);
        }
        showToast("Configuración de empresa actualizada.");
        if (refreshData) await refreshData();
    };

    const exportPayrollReport = () => {
        const headers = ["ID", "Empleado", "Correo", "Salario Base (C$)", "Faltas Deducidas", "Días Efectivos", "Salario Bruto", "INSS Laboral (7%)", "IR DGI", "Salario Neto", "INSS Patronal"];
        const rows = globalUsers.map(u => {
            const calc = window.calculatePayrollRow(u, 30, 0, settings?.inssPatronalRate || 22.5, absences);
            return [u.id, u.name, u.email, u.baseSalary || 0, calc.deductedDays, calc.effectiveWorkedDays, calc.grossSalary, calc.inssLaboral, calc.irDGI, calc.netSalary, calc.inssPatronal];
        });
        window.exportToCSV(`Planilla_${window.SHIFT_CONFIG?.companyName || 'Empresa'}_${window.getNICDate()}`, headers, rows);
    };

    const setVacationStatus = async (vId, status) => {
        if (isReadOnly) return showToast("Modo supervisión: no puedes cambiar estados.");
        await window.apiCall('update_vacation_status', { id: vId, status });
        showToast(`Actualizado a: ${status}`);
        if (refreshData) await refreshData();
    };

    const revokeEntireVacation = async (vac) => {
        if (isReadOnly) return showToast("Modo supervisión: no tienes permisos de revocación.");
        confirmAction(`¿Revocar vacaciones de ${vac.userName}? Se reintegrarán sus días.`, async () => {
            await window.apiCall('delete_vacation', { id: vac.id });
            setConfirmModal(null);
            showToast("Vacaciones revocadas con éxito.");
            if (refreshData) await refreshData();
        });
    };

    const calculateUsedDaysBreakdown = (user) => {
        if (!user) return 0;
        const manualUsed = parseFloat(user.vacationDaysUsed) || 0;
        const systemApproved = (vacations || [])
            .filter(v => v.userId === user.id && v.status === 'approved')
            .reduce((acc, v) => {
                if (v.type === 'paid') return acc + (v.paidDays || 0);
                const totalReq = v.type === 'half' ? 0.5 : window.getDaysDiff(v.startDate, v.endDate || v.startDate);
                const revoked = v.revokedDates ? v.revokedDates.length : 0;
                return acc + Math.max(0, totalReq - revoked);
            }, 0);
        return (manualUsed + systemApproved).toFixed(2);
    };

    const renderNavItems = () => {
        if (isMaster && activeClientId === 0) {
            return (
                <button onClick={()=>setTab('master')} className={`w-full flex items-center gap-3 px-5 py-4 rounded-2xl font-bold text-[13px] transition-all ${tab === 'master' ? 'bg-indigo-600 text-white shadow-lg' : 'text-slate-500 hover:bg-slate-100 hover:text-indigo-600'}`}>
                    <UiIconAdmin name="dashboard" /> Empresas SaaS
                </button>
            );
        }
        return (
            <React.Fragment>
                <button onClick={()=>setTab('logs')} className={`w-full flex items-center gap-3 px-5 py-3.5 rounded-2xl font-bold text-xs uppercase tracking-wider transition-all ${tab === 'logs' ? 'bg-indigo-600 text-white shadow-md' : 'text-slate-500 hover:bg-slate-100 hover:text-indigo-600'}`}>
                    <UiIconAdmin name="file-text" /> Auditoría
                </button>
                <button onClick={()=>setTab('users')} className={`w-full flex items-center gap-3 px-5 py-3.5 rounded-2xl font-bold text-xs uppercase tracking-wider transition-all ${tab === 'users' ? 'bg-indigo-600 text-white shadow-md' : 'text-slate-500 hover:bg-slate-100 hover:text-indigo-600'}`}>
                    <UiIconAdmin name="users" /> Personal
                </button>
                <button onClick={()=>setTab('contracts')} className={`w-full flex items-center gap-3 px-5 py-3.5 rounded-2xl font-bold text-xs uppercase tracking-wider transition-all ${tab === 'contracts' ? 'bg-indigo-600 text-white shadow-md' : 'text-slate-500 hover:bg-slate-100 hover:text-indigo-600'}`}>
                    <UiIconAdmin name="contracts" /> Contratos
                </button>
                <button onClick={()=>setTab('notices')} className={`w-full flex items-center gap-3 px-5 py-3.5 rounded-2xl font-bold text-xs uppercase tracking-wider transition-all ${tab === 'notices' ? 'bg-indigo-600 text-white shadow-md' : 'text-slate-500 hover:bg-slate-100 hover:text-indigo-600'}`}>
                    <UiIconAdmin name="bell" /> Avisos
                </button>
                <button onClick={()=>setTab('payroll')} className={`w-full flex items-center gap-3 px-5 py-3.5 rounded-2xl font-bold text-xs uppercase tracking-wider transition-all ${tab === 'payroll' ? 'bg-emerald-500 text-white shadow-md' : 'text-slate-500 hover:bg-emerald-50 hover:text-emerald-600'}`}>
                    <UiIconAdmin name="dollar" /> Planilla (NI)
                </button>
                <button onClick={()=>setTab('vacations')} className={`w-full flex items-center gap-3 px-5 py-3.5 rounded-2xl font-bold text-xs uppercase tracking-wider transition-all ${tab === 'vacations' ? 'bg-emerald-500 text-white shadow-md' : 'text-slate-500 hover:bg-emerald-50 hover:text-emerald-600'}`}>
                    <UiIconAdmin name="sun" /> Vacaciones
                </button>
                <button onClick={()=>setTab('absences')} className={`w-full flex items-center gap-3 px-5 py-3.5 rounded-2xl font-bold text-xs uppercase tracking-wider transition-all ${tab === 'absences' ? 'bg-red-500 text-white shadow-md' : 'text-slate-500 hover:bg-red-50 hover:text-red-600'}`}>
                    <UiIconAdmin name="x-circle" /> Ausencias
                </button>
                {!isReadOnly && (
                    <button onClick={()=>setTab('roles')} className={`w-full flex items-center gap-3 px-5 py-3.5 rounded-2xl font-bold text-xs uppercase tracking-wider transition-all ${tab === 'roles' ? 'bg-indigo-600 text-white shadow-md' : 'text-slate-500 hover:bg-slate-100 hover:text-indigo-600'}`}>
                        <UiIconAdmin name="shield" /> Roles & Acceso
                    </button>
                )}
                {!isReadOnly && (
                    <button onClick={()=>setTab('settings')} className={`w-full flex items-center gap-3 px-5 py-3.5 rounded-2xl font-bold text-xs uppercase tracking-wider transition-all ${tab === 'settings' ? 'bg-slate-800 text-white shadow-md' : 'text-slate-500 hover:bg-slate-200 hover:text-slate-800'}`}>
                        <UiIconAdmin name="settings" /> Ajustes
                    </button>
                )}
            </React.Fragment>
        );
    };

    return (
        <div className="flex h-screen bg-slate-50 overflow-hidden font-sans">
            {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-[130] animate-bounce whitespace-nowrap">{toastMsg}</div>}
            
            {previewImage && (
                <div className="fixed inset-0 bg-slate-900/80 z-[120] 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"><svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"></path></svg></button>
                        <img src={previewImage} className="w-full h-auto max-h-[85vh] object-contain rounded-[1.5rem]" />
                    </div>
                </div>
            )}

            {mapLogs && (
                <div className="fixed inset-0 bg-slate-900/70 z-[115] flex items-center justify-center p-4 fade-in" onClick={() => setMapLogs(null)}>
                    <div className="bg-white rounded-[3rem] max-w-4xl w-full max-h-[90vh] overflow-hidden shadow-2xl flex flex-col" onClick={e=>e.stopPropagation()}>
                        <div className="p-6 border-b border-slate-100 flex justify-between items-center bg-white z-10">
                            <div>
                                <h3 className="font-black text-xl text-slate-900">Ruta y Marcajes GPS</h3>
                                <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mt-0.5">
                                    {mapLogs.length} punto(s) registrado(s) • Monitoreo interactivo
                                </p>
                            </div>
                            <button onClick={() => setMapLogs(null)} className="p-3 bg-slate-50 text-slate-400 hover:text-slate-600 rounded-full transition-colors">
                                <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"></path></svg>
                            </button>
                        </div>
                        <div className="flex-1 w-full min-h-[450px] relative bg-slate-100" ref={mapContainerRef}></div>
                    </div>
                </div>
            )}

            {confirmModal && (
                <div className="fixed inset-0 bg-slate-900/60 z-[125] 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 • INICIO: {window.formatDateToNIC(selectedUserVacation.hiringDate)}</p>
                            </div>
                            <button onClick={()=>setSelectedUserVacation(null)} className="p-3 bg-slate-50 text-slate-400 hover:text-slate-600 rounded-full transition-colors"><svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"></path></svg></button>
                        </div>
                        <div className="flex-1 overflow-y-auto p-8 space-y-8">
                            <div className="grid grid-cols-3 gap-4 text-center">
                                <div className="bg-indigo-50 p-4 rounded-2xl border border-indigo-100">
                                    <p className="text-[9px] font-black text-indigo-400 uppercase">Acumuladas Ley</p>
                                    <p className="text-2xl font-black text-indigo-600 mt-1">{window.calculateVacationAccrued(selectedUserVacation, settings?.vacationRate||2.5).toFixed(2)}</p>
                                </div>
                                <div className="bg-orange-50 p-4 rounded-2xl border border-orange-100">
                                    <p className="text-[9px] font-black text-orange-400 uppercase">Gozados / Aprobados</p>
                                    <p className="text-2xl font-black text-orange-600 mt-1">{calculateUsedDaysBreakdown(selectedUserVacation)}</p>
                                </div>
                                <div className="bg-emerald-50 p-4 rounded-2xl border border-emerald-100">
                                    <p className="text-[9px] font-black text-emerald-400 uppercase">Saldo Disponible</p>
                                    <p className="text-2xl font-black text-emerald-600 mt-1">{window.calculateVacationBalance(selectedUserVacation, settings?.vacationRate||2.5, vacations)}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* BARRA LATERAL CON MARCAJE RÁPIDO INTEGRADO */}
            <aside className="w-64 bg-white border-r border-slate-200 flex flex-col shadow-sm z-20 print:hidden h-full flex-shrink-0">
                <div className="p-6 border-b border-slate-100">
                    <h1 className="font-black text-2xl text-indigo-700 tracking-tight leading-none mb-4">Shift<br/>Central</h1>
                    
                    {isReadOnly && (
                        <div className="mb-3 px-3 py-1.5 bg-amber-50 border border-amber-200 rounded-xl text-center">
                            <span className="text-[9px] font-black uppercase text-amber-700 tracking-wider">Modo Supervisión</span>
                        </div>
                    )}

                    {isMaster && (
                        <div className="bg-indigo-50 p-2.5 rounded-xl border border-indigo-100">
                            <label className="text-[9px] font-black text-indigo-400 uppercase tracking-widest block px-1 mb-1">Empresa Activa:</label>
                            <select 
                                value={activeClientId} 
                                onChange={e => handlePortalChange(e.target.value)}
                                className="w-full bg-transparent font-black text-indigo-900 text-xs outline-none cursor-pointer uppercase truncate"
                            >
                                <option value={0}>❖ PORTAL MAESTRO</option>
                                {masterClients.map(c => (
                                    <option key={c.id} value={c.id}>{c.company_name}</option>
                                ))}
                            </select>
                        </div>
                    )}
                </div>

                <div className="flex-1 overflow-y-auto p-4 space-y-1.5 no-scrollbar">
                    {renderNavItems()}
                </div>

                {/* SECCIÓN INFERIOR: MARCAJE RÁPIDO & ACCESO A MARCADAS */}
                <div className="p-4 border-t border-slate-100 space-y-2.5 bg-slate-50">
                    {activeClientId !== 0 && (
                        <div className="bg-white p-3 rounded-2xl border border-slate-200/80 shadow-sm space-y-2">
                            <div className="flex items-center justify-between">
                                <span className="text-[9px] font-black uppercase text-slate-400">Mi Turno Hoy</span>
                                <span className={`text-[8px] font-black uppercase px-2 py-0.5 rounded-md ${
                                    isCurrentlyCheckedIn ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-500'
                                }`}>
                                    {isCurrentlyCheckedIn ? 'En Turno' : 'Sin Turno'}
                                </span>
                            </div>

                            <div className="flex gap-1.5">
                                {!isCurrentlyCheckedIn ? (
                                    <button 
                                        onClick={() => handleQuickPunch('entrada')}
                                        disabled={isPunching}
                                        className="flex-1 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl text-[9px] font-black uppercase tracking-wider shadow-sm active:scale-95 transition-all"
                                    >
                                        {isPunching ? "Marcando..." : "Marcar Entrada"}
                                    </button>
                                ) : (
                                    <button 
                                        onClick={() => handleQuickPunch('salida')}
                                        disabled={isPunching}
                                        className="flex-1 py-2 bg-red-600 hover:bg-red-700 text-white rounded-xl text-[9px] font-black uppercase tracking-wider shadow-sm active:scale-95 transition-all"
                                    >
                                        {isPunching ? "Marcando..." : "Marcar Salida"}
                                    </button>
                                )}
                            </div>
                        </div>
                    )}

                    {/* BOTÓN DESTACADO IR A MARCADAS */}
                    <button 
                        onClick={() => setView('dashboard')} 
                        className="w-full py-3 bg-gradient-to-r from-indigo-600 to-indigo-700 hover:from-indigo-700 hover:to-indigo-800 text-white rounded-2xl font-black uppercase text-[10px] tracking-widest shadow-md hover:shadow-lg transition-all active:scale-95 flex items-center justify-center gap-2"
                    >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                        IR A MARCADAS
                    </button>

                    <button 
                        onClick={onLogout} 
                        className="w-full py-2.5 bg-red-50 text-red-600 hover:bg-red-100 rounded-xl font-black uppercase text-[9px] tracking-widest transition-all active:scale-95 text-center"
                    >
                        Cerrar Sesión
                    </button>
                </div>
            </aside>

            <main className="flex-1 h-full overflow-y-auto bg-slate-50 relative">
                <div className="w-full p-6 md:p-10 pb-24">
                    {tab === 'master' && isMaster && window.AdminSaaS && (
                        <window.AdminSaaS 
                            masterClients={masterClients} activeClientId={activeClientId} setActiveClientId={handlePortalChange} 
                            editingClient={editingClient} setEditingClient={setEditingClient} 
                            showClientModal={showClientModal} setShowClientModal={setShowClientModal} refreshData={refreshData}
                        />
                    )}
                    {tab === 'logs' && window.AdminAuditoria && (
                        <window.AdminAuditoria 
                            logs={logs} globalUsers={globalUsers} absences={absences} settings={settings}
                            actions={actions} setMapLogs={setMapLogs} setPreviewImage={setPreviewImage} refreshData={refreshData} 
                        />
                    )}
                    {tab === 'users' && window.AdminPersonal && (
                        <window.AdminPersonal 
                            globalUsers={globalUsers} roles={roles} logs={logs} handleUserSubmit={handleUserSubmit} 
                            editingUser={editingUser} setEditingUser={setEditingUser} deleteUser={deleteUser} 
                            toggleLock={toggleLock} confirmAction={confirmAction} isReadOnly={isReadOnly}
                        />
                    )}
                    {tab === 'contracts' && window.AdminContratos && (
                        <window.AdminContratos 
                            globalUsers={globalUsers} settings={settings} currentUser={currentUser} 
                            isMaster={isMaster} isReadOnly={isReadOnly} refreshData={refreshData} showToast={showToast} 
                        />
                    )}
                    {tab === 'notices' && window.AdminAvisos && (
                        <window.AdminAvisos globalUsers={globalUsers} reminders={reminders} isReadOnly={isReadOnly} showToast={showToast} refreshData={refreshData} />
                    )}
                    {tab === 'payroll' && window.AdminPlanilla && (
                        <window.AdminPlanilla globalUsers={globalUsers} absences={absences} logs={logs} settings={settings} exportPayrollReport={exportPayrollReport} />
                    )}
                    {tab === 'vacations' && window.AdminVacaciones && (
                        <window.AdminVacaciones 
                            globalUsers={globalUsers} vacations={vacations} settings={settings} 
                            updateVacationRate={(rate) => { setVacRate(rate); saveCompanySettings(); }} 
                            setVacationStatus={setVacationStatus} revokeEntireVacation={revokeEntireVacation} setSelectedUserVacation={setSelectedUserVacation} 
                            isReadOnly={isReadOnly}
                        />
                    )}
                    {tab === 'absences' && window.AdminAusencias && (
                        <window.AdminAusencias globalUsers={globalUsers} absences={absences} saveAbsence={()=>{}} confirmAction={confirmAction} isReadOnly={isReadOnly} showToast={showToast} />
                    )}
                    {!isReadOnly && tab === 'roles' && window.AdminRoles && (
                        <window.AdminRoles actions={actions} roles={roles} showToast={showToast} refreshData={refreshData} />
                    )}
                    {!isReadOnly && tab === 'settings' && window.AdminAjustes && (
                        <window.AdminAjustes 
                            isMaster={isMaster} companyLogoUrl={companyLogoUrl} setCompanyLogoUrl={setCompanyLogoUrl} 
                            showCompanyLogo={showCompanyLogo} setShowCompanyLogo={setShowCompanyLogo}
                            inssRate={inssRate} setInssRate={setInssRate} vacRate={vacRate} setVacRate={setVacRate} 
                            lunchLimitMinutes={lunchLimitMinutes} setLunchLimitMinutes={setLunchLimitMinutes} 
                            gracePeriodMinutes={gracePeriodMinutes} setGracePeriodMinutes={setGracePeriodMinutes}
                            maxTardinessAllowed={maxTardinessAllowed} setMaxTardinessAllowed={setMaxTardinessAllowed}
                            tardinessPenaltyAction={tardinessPenaltyAction} setTardinessPenaltyAction={setTardinessPenaltyAction}
                            saveCompanySettings={saveCompanySettings} newReasonInput={newReasonInput} setNewReasonInput={setNewReasonInput} setReasonsList={setReasonsList} reasonsList={reasonsList} 
                        />
                    )}
                </div>
            </main>

            {/* ASISTENTE INTELIGENTE COPILOT AI (WIDGET FLOTANTE MULTI-TENANT) */}
            {window.AdminAICopilot && (
                <window.AdminAICopilot 
                    companyName={settings?.companyName || window.SHIFT_CONFIG?.companyName}
                    globalUsers={globalUsers}
                    logs={logs}
                    contracts={vacations}
                    vacations={vacations}
                    absences={absences}
                    settings={settings}
                    currentTab={tab}
                />
            )}
        </div>
    );
};