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

const UiIcon = ({ name, className = "w-6 h-6" }) => {
    const icons = {
        'camera': <svg className={className} 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>,
        'moon': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"></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>,
        'coffee': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M18 10h-1.26A8 8 0 109 20h9a1 1 0 001-1v-8a1 1 0 00-1-1z"></path></svg>,
        'clock': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" 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>,
        'briefcase': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M21 13.255A23.931 23.931 0 0112 15c-3.183 0-6.22-.62-9-1.745M16 6V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v2m4 6h.01M5 20h14a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path></svg>,
        'users': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path></svg>,
        'graduation-cap': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M12 14l9-5-9-5-9 5 9 5z"></path><path strokeLinecap="round" strokeLinejoin="round" d="M12 14l6.16-3.422a12.083 12.083 0 01.665 6.479A11.952 11.952 0 0012 20.055a11.952 11.952 0 00-6.824-2.998 12.078 12.078 0 01.665-6.479L12 14z"></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 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>,
        '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>,
        'check-circle': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>,
        'log-out': <svg className={className} fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></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>,
        '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>
    };
    return icons[name] || null;
};

window.UserDashboard = function({ profile, logs, reminders = [], vacations = [], settings, actions = [], onLogout, setView, allRoles }) {
    const [status, setStatus] = useState('fuera');
    const [showCam, setShowCam] = useState(false);
    const [purpose, setPurpose] = useState('');
    const [clientName, setClientName] = useState('');
    const [loadingMark, setLoadingMark] = useState(false);
    const [localLock, setLocalLock] = useState(false); 
    
    const [showClientModal, setShowClientModal] = useState(false);
    const [showNotifications, setShowNotifications] = useState(false);
    const [showVacationModal, setShowVacationModal] = useState(false);
    const [vacReqType, setVacReqType] = useState('full');
    const [vacReqStart, setVacReqStart] = useState('');
    const [vacReqEnd, setVacReqEnd] = useState('');
    const [toastMsg, setToastMsg] = useState('');

    const videoRef = useRef(null);
    const canvasRef = useRef(null);
    const todayStr = window.getNICDate();
    
    const showToast = (msg) => { setToastMsg(msg); setTimeout(() => setToastMsg(''), 3000); };

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

    const activeVacationToday = useMemo(() => {
        return vacations.find(v => v.userId === profile.id && v.status === 'approved' && v.startDate <= todayStr && (v.endDate || v.startDate) >= todayStr && !(v.revokedDates||[]).includes(todayStr));
    }, [vacations, profile.id, todayStr]);

    const effectiveVacation = useMemo(() => {
        if (!activeVacationToday) return null;
        let lastDay = todayStr;
        let dt = new Date(todayStr);
        let endDt = new Date(activeVacationToday.endDate || activeVacationToday.startDate);
        while(dt <= endDt) {
            const y = dt.getFullYear(); const m = String(dt.getMonth() + 1).padStart(2, '0'); const d = String(dt.getDate()).padStart(2, '0');
            const dStr = `${y}-${m}-${d}`;
            if ((activeVacationToday.revokedDates || []).includes(dStr)) {
                break; 
            }
            lastDay = dStr;
            dt.setDate(dt.getDate() + 1);
        }
        return { ...activeVacationToday, effectiveEndDate: lastDay };
    }, [activeVacationToday, todayStr]);

    const startsVacationTomorrow = useMemo(() => {
        let tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1);
        const y = tomorrow.getFullYear(); const m = String(tomorrow.getMonth() + 1).padStart(2, '0'); const d = String(tomorrow.getDate()).padStart(2, '0');
        const tomorrowStr = `${y}-${m}-${d}`;
        return vacations.find(v => v.userId === profile.id && v.status === 'approved' && v.startDate <= tomorrowStr && (v.endDate || v.startDate) >= tomorrowStr && !(v.revokedDates||[]).includes(tomorrowStr));
    }, [vacations, profile.id]);

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

    const myNotifications = useMemo(() => {
        const now = Date.now();
        const activeAvisos = reminders.filter(r => r.targetUsers?.includes(profile.id) && !(r.completedBy && r.completedBy[profile.id]) && (!r.expiresAt || r.expiresAt > now)).map(r => ({ ...r, notifType: 'aviso' }));
        const vacUpdates = vacations.filter(v => v.userId === profile.id && (v.status === 'approved' || v.status === 'denied') && !v.seenByUser).map(v => ({
            id: v.id, title: `Vacaciones ${v.status === 'approved' ? 'Aprobadas' : 'Denegadas'}`,
            message: v.type === 'paid' ? `Se te ha pagado el equivalente a ${v.paidDays} día(s).` : `Tu solicitud del ${v.startDate} fue ${v.status === 'approved' ? 'aprobada' : 'denegada'}.`,
            notifType: 'vacation', status: v.status
        }));
        return [...activeAvisos, ...vacUpdates];
    }, [reminders, vacations, profile.id]);

    const markNotificationSeen = async (notif) => {
        try {
            await window.apiCall('mark_notification_seen', { id: notif.id, notifType: notif.notifType, userId: profile.id });
        } catch (e) { showToast("Error al confirmar."); }
    };

    const userRoleConfig = useMemo(() => allRoles.find(r => (r.name || r) === profile.role), [allRoles, profile.role]);
    const permissions = userRoleConfig && userRoleConfig.permissions ? userRoleConfig.permissions : [];

    const isShiftCompleted = useMemo(() => {
        const hasSalida = todayLogs.some(l => l.type === 'salida');
        return profile.manualLock || ((hasSalida || localLock) && !profile.overrideCheckOut);
    }, [todayLogs, profile.overrideCheckOut, profile.manualLock, localLock]);

    const executeActionWithCheck = (p) => {
        const baseP = p.startsWith('vuelta_') ? p.replace('vuelta_', '') : p.replace('_out', '_in');
        let requiresCam = true;
        
        if (userRoleConfig && userRoleConfig.cameraActions) {
            requiresCam = userRoleConfig.cameraActions.includes(baseP) || userRoleConfig.cameraActions.includes(p);
        } else {
            requiresCam = !['almuerzo', 'vuelta_almuerzo', 'break', 'capacitacion', 'reunion', 'gestiones'].includes(p);
        }

        if (requiresCam) {
            proceedWithCam(p);
        } else {
            setLoadingMark(true);
            if (['entrada', 'salida', 'visita_in', 'visita_out'].includes(p)) {
                navigator.geolocation.getCurrentPosition(
                    (pos) => saveMark(p, null, { lat: pos.coords.latitude, lng: pos.coords.longitude }),
                    () => { showToast("GPS obligatorio."); setLoadingMark(false); }
                );
            } else {
                saveMark(p, null, null);
            }
        }
    };

    const startAction = async (p) => {
        if (isShiftCompleted || activeVacationToday) return;
        
        if (p.includes('visita') && !clientName) {
            setPurpose(p);
            setShowClientModal(true); 
            return;
        }
        executeActionWithCheck(p);
    };

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

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

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

    const saveMark = async (type, photo, loc) => {
        setLoadingMark(true);
        try {
            await window.apiCall('save_log', {
                userId: profile.id, userName: profile.name, type, 
                timestamp: Date.now(), location: loc, photo, 
                client: clientName, date: todayStr, role: profile.role,
                update_user_override: type === 'salida' ? true : false
            });

            if (type === 'salida') setLocalLock(true);

            if (videoRef.current?.srcObject) videoRef.current.srcObject.getTracks().forEach(t => t.stop());
            setShowCam(false); setClientName('');
            showToast("Marca registrada exitosamente.");
        } catch (e) { showToast("Error al guardar."); }
        finally { setLoadingMark(false); }
    };

    const submitVacation = async () => {
        if (!vacReqStart || (vacReqType === 'range' && !vacReqEnd)) return showToast("Revisa las fechas.");
        const end = vacReqType === 'range' ? vacReqEnd : vacReqStart;
        if (vacReqType === 'range' && end < vacReqStart) return showToast("Fecha de fin inválida.");
        
        const daysReq = vacReqType === 'half' ? 0.5 : window.getDaysDiff(vacReqStart, end);
        const currentBal = window.calculateVacationBalance(profile, settings?.vacationRate||2.5, vacations);
        
        if (daysReq > currentBal) return showToast(`Saldo insuficiente. Pides ${daysReq} y tienes ${currentBal}`);
        
        try {
            await window.apiCall('add_vacation', {
                userId: profile.id, userName: profile.name, type: vacReqType,
                startDate: vacReqStart, endDate: end, status: 'pending',
                requestedAt: Date.now(), seenByUser: false
            });
            setShowVacationModal(false); setVacReqStart(''); setVacReqEnd(''); setVacReqType('full');
            showToast("Solicitud enviada a revisión.");
        } catch(e) { showToast("Error al solicitar."); }
    };

    if (profile.status === 'subsidio' || profile.status === 'feriado' || activeVacationToday) {
        const isVac = !!activeVacationToday;
        return (
            <div className="h-screen flex flex-col items-center justify-center p-8 text-center bg-slate-50">
                <UiIcon name={isVac ? 'sun' : profile.status === 'subsidio' ? 'heart-pulse' : 'calendar'} className="w-16 h-16 text-indigo-600 mb-6 animate-bounce" />
                <h1 className="text-3xl font-black uppercase text-indigo-900">Estado: {isVac ? 'De Vacaciones' : profile.status}</h1>
                <p className="text-slate-500 mt-4 uppercase text-[10px] font-black tracking-widest leading-relaxed max-w-[250px]">
                    {isVac ? `Tu acceso se habilitará a tu regreso el día hábil posterior al ${effectiveVacation?.effectiveEndDate || activeVacationToday.startDate}` : 'Acceso Inhabilitado temporalmente'}
                </p>
                <button onClick={onLogout} className="mt-10 px-8 py-4 bg-indigo-600 shadow-xl text-white rounded-2xl font-black uppercase text-[10px] active:scale-95 transition-all">Cerrar Sesión</button>
            </div>
        );
    }

    return (
        <div className="max-w-md mx-auto p-6 space-y-6 pb-24 relative min-h-screen fade-in">
            {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>}

            {showClientModal && (
                <div className="fixed inset-0 bg-slate-900/60 z-[70] flex items-center justify-center p-6" onClick={() => setShowClientModal(false)}>
                    <div className="bg-white p-8 rounded-[3rem] w-full max-w-sm shadow-2xl" onClick={e=>e.stopPropagation()}>
                        <h3 className="font-black text-lg text-slate-800 mb-2">Visita Cliente</h3>
                        <p className="text-[10px] uppercase font-bold text-slate-400 mb-6">Ingresa la empresa que vas a visitar.</p>
                        <input type="text" placeholder="Ej. Empresa SA..." value={clientName} onChange={e=>setClientName(e.target.value)} className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none mb-4 focus:ring-2 focus:ring-indigo-100" autoFocus />
                        <div className="flex gap-2">
                            <button onClick={()=>setShowClientModal(false)} className="flex-1 py-4 bg-slate-100 text-slate-500 rounded-2xl font-black uppercase text-[10px]">Cancelar</button>
                            <button onClick={()=>{ if(!clientName) return showToast("El nombre es requerido."); executeActionWithCheck(purpose); setShowClientModal(false); }} className="flex-1 py-4 bg-indigo-600 text-white rounded-2xl font-black uppercase text-[10px] shadow-lg">Continuar</button>
                        </div>
                    </div>
                </div>
            )}

            {showNotifications && (
                <div className="fixed inset-0 bg-slate-900/40 z-50 p-6 flex flex-col justify-end" onClick={()=>setShowNotifications(false)}>
                    <div className="bg-slate-50 w-full max-h-[70vh] rounded-[3rem] p-6 overflow-y-auto space-y-4 shadow-2xl" onClick={e=>e.stopPropagation()}>
                        <h3 className="font-black text-lg text-slate-800 border-b pb-4 flex items-center gap-2"><UiIcon name="bell"/> Avisos y Alertas</h3>
                        {myNotifications.length === 0 ? <p className="text-slate-400 text-xs font-bold text-center py-6">Todo limpio.</p> : 
                            myNotifications.map(n => (
                                <div key={n.id} className={`p-6 rounded-3xl shadow-sm border-l-8 ${n.notifType === 'vacation' ? (n.status==='approved'?'border-emerald-500 bg-emerald-50':'border-red-500 bg-red-50') : 'border-indigo-600 bg-white'}`}>
                                    <h4 className="font-black text-slate-900 uppercase text-xs tracking-widest">{n.title}</h4>
                                    <p className="text-slate-600 text-[11px] mt-1 font-medium leading-relaxed">{n.message}</p>
                                    <button onClick={() => markNotificationSeen(n)} className="mt-4 w-full py-3 bg-slate-900 text-white rounded-2xl font-black uppercase text-[10px] flex items-center justify-center gap-2 active:scale-95 transition-all">
                                        <UiIcon name="check-circle" className="w-4 h-4" /> Entendido
                                    </button>
                                </div>
                            ))
                        }
                        <button onClick={()=>setShowNotifications(false)} className="w-full py-4 bg-slate-200 text-slate-600 font-black rounded-2xl uppercase text-[10px] mt-4">Cerrar</button>
                    </div>
                </div>
            )}

            {showVacationModal && (
                <div className="fixed inset-0 bg-slate-900/60 z-50 p-6 flex items-center justify-center fade-in" onClick={()=>setShowVacationModal(false)}>
                    <div className="bg-white w-full max-w-sm rounded-[3rem] p-8 space-y-6 shadow-2xl" onClick={e=>e.stopPropagation()}>
                        <div className="flex justify-between items-center">
                            <h3 className="font-black text-xl text-indigo-900 flex items-center gap-2"><UiIcon name="sun" /> Mis Vacaciones</h3>
                            <button onClick={()=>setShowVacationModal(false)} className="text-slate-400 bg-slate-100 p-2 rounded-full"><UiIcon name="x" className="w-4 h-4" /></button>
                        </div>
                        <div className="bg-indigo-50 border border-indigo-100 p-6 rounded-3xl text-center shadow-inner">
                            <p className="text-[10px] font-black uppercase tracking-widest text-indigo-400">Saldo Disponible</p>
                            <p className="text-4xl font-black text-indigo-600 mt-2">{window.calculateVacationBalance(profile, settings?.vacationRate||2.5, vacations)} <span className="text-lg">Días</span></p>
                        </div>
                        <div className="space-y-4">
                            <select value={vacReqType} onChange={e=>setVacReqType(e.target.value)} className="w-full p-4 bg-slate-50 rounded-2xl font-bold text-[10px] uppercase outline-none focus:ring-2 focus:ring-indigo-100">
                                <option value="full">Día Completo Libre (1)</option>
                                <option value="half">Medio Día Libre (0.5)</option>
                                <option value="range">Rango de Fechas</option>
                            </select>
                            <div className="grid grid-cols-2 gap-4">
                                <div className="col-span-2 md:col-span-1">
                                    <label className="text-[9px] font-black uppercase tracking-widest text-slate-400 ml-2">Desde / Día</label>
                                    <input type="date" value={vacReqStart} onChange={e=>setVacReqStart(e.target.value)} className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none" min={todayStr} />
                                </div>
                                {vacReqType === 'range' && (
                                    <div className="col-span-2 md:col-span-1">
                                        <label className="text-[9px] font-black uppercase tracking-widest text-slate-400 ml-2">Hasta</label>
                                        <input type="date" value={vacReqEnd} onChange={e=>setVacReqEnd(e.target.value)} className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none" min={vacReqStart || todayStr} />
                                    </div>
                                )}
                            </div>
                            <button onClick={submitVacation} className="w-full py-4 bg-indigo-600 text-white font-black rounded-2xl uppercase text-[10px] tracking-widest mt-2 active:scale-95 transition-all shadow-lg">Enviar a Revisión</button>
                        </div>
                    </div>
                </div>
            )}

            <header className="bg-white p-6 rounded-[2.5rem] shadow-sm border border-slate-100 flex items-center justify-between">
                <div className="flex items-center gap-4">
                    <div className="w-12 h-12 bg-indigo-600 rounded-2xl flex items-center justify-center text-white font-black text-xl shadow-lg">{profile.name[0]}</div>
                    <div>
                        <h2 className="font-black text-slate-800 leading-none mb-1">{profile.name}</h2>
                        <p className="text-[10px] text-slate-400 font-black uppercase tracking-widest">{profile.role}</p>
                    </div>
                </div>
                <div className="flex gap-2">
                    <button onClick={()=>setShowNotifications(true)} className="p-3 bg-slate-50 text-slate-400 rounded-2xl relative transition-colors hover:text-indigo-600 active:scale-95">
                        <UiIcon name="bell" />
                        {myNotifications.length > 0 && <span className="absolute top-2 right-2 w-3 h-3 bg-red-500 rounded-full border-2 border-white animate-pulse"></span>}
                    </button>
                    <button onClick={onLogout} className="p-3 text-slate-300 hover:text-red-500 rounded-2xl transition-colors active:scale-95"><UiIcon name="log-out" /></button>
                </div>
            </header>

            <div className="flex gap-2">
                {(profile.role === 'admin' || profile.role === 'propietario') && (
                    <button onClick={() => setView('admin')} className="flex-1 py-4 bg-indigo-50 text-indigo-600 rounded-2xl font-black uppercase text-[10px] tracking-widest flex items-center justify-center gap-2 border border-indigo-200 active:scale-95 transition-all">
                        <UiIcon name="settings" className="w-4 h-4" /> Admin
                    </button>
                )}
                <button onClick={() => setShowVacationModal(true)} className="flex-1 py-4 bg-emerald-50 text-emerald-600 rounded-2xl font-black uppercase text-[10px] tracking-widest flex items-center justify-center gap-2 border border-emerald-200 active:scale-95 transition-all">
                    <UiIcon name="sun" className="w-4 h-4" /> Vacaciones
                </button>
            </div>

            <div className="grid gap-4">
                {isShiftCompleted ? (
                    <div className={`h-72 rounded-[3rem] border-2 border-dashed flex flex-col items-center justify-center text-center p-8 transition-all ${startsVacationTomorrow ? 'bg-orange-50 border-orange-200 text-orange-600' : 'bg-slate-100 border-slate-200 text-slate-400'}`}>
                        <UiIcon name={startsVacationTomorrow ? 'sun' : 'moon'} className={`w-12 h-12 mb-4 ${startsVacationTomorrow ? 'animate-spin-slow' : ''}`} />
                        <span className="text-lg font-black uppercase">Jornada Finalizada</span>
                        {startsVacationTomorrow ? (
                            <p className="text-[10px] font-black uppercase tracking-widest mt-3 opacity-80 leading-relaxed max-w-[200px]">
                                ¡Descanso merecido! Tu acceso se habilitará el día hábil posterior al {startsVacationTomorrow.endDate || startsVacationTomorrow.startDate}.
                            </p>
                        ) : (
                            <p className="text-[10px] font-bold uppercase mt-2 opacity-60">Se habilitará mañana a las 12:00 AM</p>
                        )}
                    </div>
                ) : (status === 'fuera' || status === 'salida') ? (
                    <button onClick={() => startAction('entrada')} className="h-72 bg-emerald-500 rounded-[3rem] text-white flex flex-col items-center justify-center shadow-2xl active:scale-95 transition-all group relative overflow-hidden">
                        <div className="absolute inset-0 bg-emerald-400/20 group-hover:scale-150 rounded-full transition-transform duration-500"></div>
                        <UiIcon name="camera" className="w-12 h-12 mb-4 z-10" />
                        <span className="text-xl font-black uppercase z-10">Entrada Trabajo</span>
                        <p className="text-emerald-100 text-[10px] font-bold uppercase mt-2 opacity-60 tracking-widest z-10">Selfie + GPS (NI)</p>
                    </button>
                ) : (
                    <div className="space-y-4">
                        <div className="bg-white p-10 rounded-[3rem] border-2 border-emerald-500/20 text-center shadow-sm relative">
                            <div className="flex items-center justify-center gap-2 text-emerald-600 mb-2 font-black text-xl tracking-widest">ACTIVO</div>
                            <p className="text-slate-400 text-[10px] font-bold uppercase tracking-widest">{window.formatNICTimeFull ? window.formatNICTimeFull(Date.now()).split(',')[0] : new Date().toLocaleDateString()}</p>
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                            {actions.map(a => {
                                if (!permissions.includes(a.id)) return null;

                                let btnAction = a.id;
                                let btnLabel = a.label;
                                let isActiveToggle = false;

                                if (a.id === 'almuerzo') {
                                    btnAction = status === 'almuerzo' ? 'vuelta_almuerzo' : 'almuerzo';
                                    btnLabel = status === 'almuerzo' ? 'Regresar' : a.label;
                                    isActiveToggle = status === 'almuerzo';
                                } else if (a.id === 'visita_in') {
                                    btnAction = status === 'visita_in' ? 'visita_out' : 'visita_in';
                                    btnLabel = status === 'visita_in' ? 'Saliendo' : a.label;
                                    isActiveToggle = status === 'visita_in';
                                }

                                const iconMap = { 'almuerzo': 'coffee', 'break': 'clock', 'visita_in': 'briefcase', 'reunion': 'users', 'capacitacion': 'graduation-cap', 'gestiones': 'file-text' };
                                const iconName = iconMap[a.id] || 'check-circle';

                                return (
                                    <button key={a.id} onClick={() => startAction(btnAction)} 
                                            className={`h-32 rounded-3xl shadow-sm flex flex-col items-center justify-center font-black uppercase text-[10px] active:scale-95 transition-all ${isActiveToggle ? (a.id === 'visita_in' ? 'bg-blue-600 text-white animate-pulse shadow-lg' : 'bg-orange-500 text-white') : 'bg-white text-slate-700 border'}`}>
                                        <UiIcon name={iconName} className="w-8 h-8 mb-2" /> {btnLabel}
                                    </button>
                                );
                            })}
                        </div>
                        <button onClick={() => startAction('salida')} className="w-full py-6 bg-red-50 text-red-600 rounded-[2.5rem] font-black uppercase text-xs tracking-widest hover:bg-red-100 active:scale-95 transition-all">Cerrar Día</button>
                    </div>
                )}
            </div>

            <div className="bg-white p-6 rounded-[2.5rem] border border-slate-100 shadow-sm">
                <h3 className="font-black text-[10px] uppercase tracking-widest text-slate-400 mb-4 flex items-center gap-2 border-b pb-3"><UiIcon name="list" className="w-4 h-4"/> Bitácora de Hoy</h3>
                {todayLogs.length === 0 ? <p className="text-center py-6 text-[10px] font-black uppercase opacity-20">Sin registros aún</p> : (
                    <div className="space-y-4 max-h-[250px] overflow-y-auto pr-2 no-scrollbar">
                        {todayLogs.map(l => {
                            const actionObj = actions.find(a => a.id === l.type.replace('vuelta_', '').replace('_out', '_in'));
                            let displayType = l.type.replace('_', ' ');
                            if (actionObj) {
                                if (l.type.startsWith('vuelta_')) displayType = `Regreso ${actionObj.label}`;
                                else if (l.type.endsWith('_out')) displayType = `Saliendo ${actionObj.label}`;
                                else displayType = actionObj.label;
                            }

                            return (
                                <div key={l.timestamp} className="flex items-center gap-4 group">
                                    <div className={`w-3 h-3 rounded-full flex-shrink-0 ${l.type.includes('entrada') ? 'bg-emerald-500' : l.type.includes('salida') ? 'bg-red-500' : 'bg-indigo-400'}`}></div>
                                    <div className="flex-1">
                                        <p className="text-[11px] font-black uppercase text-slate-800 leading-none">{displayType} {l.client && <span className="text-indigo-600">- {l.client}</span>}</p>
                                        <p className="text-[9px] text-slate-400 font-bold mt-1 uppercase">{window.formatNICTimeFull ? window.formatNICTimeFull(l.timestamp).split(', ')[1] : new Date(l.timestamp).toLocaleTimeString()}</p>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                )}
            </div>

            {showCam && (
                <div className="fixed inset-0 bg-slate-950/95 z-[80] flex flex-col items-center justify-center p-6 text-white fade-in">
                    <div className="camera-container w-full max-w-sm shadow-2xl rounded-[3rem] overflow-hidden border-4 border-slate-800 relative bg-black aspect-[3/4]">
                        <video ref={videoRef} autoPlay playsInline muted className="w-full h-full object-cover" />
                        <canvas ref={canvasRef} className="hidden" />
                    </div>
                    <div className="mt-12 flex flex-col items-center gap-6 w-full max-w-sm">
                        <button onClick={capture} disabled={loadingMark} className="w-24 h-24 bg-white text-slate-950 rounded-full flex items-center justify-center shadow-2xl active:scale-90 transition-all focus:outline-none relative">
                            <span className={`absolute inset-0 flex items-center justify-center transition-opacity ${loadingMark ? 'opacity-100' : 'opacity-0'}`}>
                                <div className="w-8 h-8 border-4 border-indigo-600 border-t-transparent rounded-full animate-spin"></div>
                            </span>
                            <span className={`absolute inset-0 flex items-center justify-center transition-opacity ${!loadingMark ? 'opacity-100' : 'opacity-0'}`}>
                                <UiIcon name="camera" className="w-10 h-10" />
                            </span>
                        </button>
                        <button onClick={() => { if(videoRef.current?.srcObject) videoRef.current.srcObject.getTracks().forEach(t=>t.stop()); setShowCam(false); }} className="text-white/40 font-black uppercase text-[10px] tracking-widest underline p-4">Cancelar Marca</button>
                    </div>
                </div>
            )}
        </div>
    );
};