const { useState, useMemo } = React;

window.AdminAuditoria = function({ logs = [], globalUsers = [], absences = [], actions = [], setMapLogs, setPreviewImage, refreshData }) {
    const [searchName, setSearchName] = useState('');
    const [searchDate, setSearchDate] = useState(window.getNICDate());
    const [startDate, setStartDate] = useState('');
    const [endDate, setEndDate] = useState('');
    const [selectedActionType, setSelectedActionType] = useState('ALL');

    const [editingLog, setEditingLog] = useState(null);
    const [showNewMarkModal, setShowNewMarkModal] = useState(false);
    
    const [formUser, setFormUser] = useState('');
    const [formType, setFormType] = useState('entrada');
    const [formDate, setFormDate] = useState(window.getNICDate());
    const [formTime, setFormTime] = useState('08:00');
    const [formJustification, setFormJustification] = useState('');

    const applyQuickFilter = (type) => {
        const today = new Date();
        const y = today.getFullYear();
        const m = String(today.getMonth() + 1).padStart(2, '0');
        const d = String(today.getDate()).padStart(2, '0');
        
        if (type === 'today') {
            setSearchDate(`${y}-${m}-${d}`);
            setStartDate(''); setEndDate('');
        } else if (type === 'this_week') {
            const firstDay = new Date(today.setDate(today.getDate() - today.getDay() + 1));
            const lastDay = new Date(today.setDate(today.getDate() - today.getDay() + 7));
            setSearchDate('');
            setStartDate(window.getNICDateFromObj(firstDay));
            setEndDate(window.getNICDateFromObj(lastDay));
        } else if (type === 'this_month') {
            const firstDay = new Date(y, today.getMonth(), 1);
            const lastDay = new Date(y, today.getMonth() + 1, 0);
            setSearchDate('');
            setStartDate(window.getNICDateFromObj(firstDay));
            setEndDate(window.getNICDateFromObj(lastDay));
        }
    };

    const formatLogType = (typeStr) => {
        if (!typeStr) return { label: 'MARCA', isStart: false, isEnd: false };
        if (typeStr === 'entrada') return { label: 'Entrada Trabajo', isStart: true, isEnd: false };
        if (typeStr === 'salida') return { label: 'Cierre de Día (Salida)', isStart: false, isEnd: true };

        const isStart = typeStr.endsWith('_in');
        const isEnd = typeStr.endsWith('_out') || typeStr.startsWith('vuelta_');

        let cleanId = typeStr.replace('_in', '').replace('_out', '').replace('vuelta_', '').toLowerCase();
        const matchedAction = (actions || []).find(a => (a.id || '').toLowerCase() === cleanId);

        let baseName = matchedAction ? matchedAction.label : cleanId.replace(/_\d+/g, '').replace(/_/g, ' ').toUpperCase();
        let finalLabel = baseName;
        if (isStart) finalLabel = `Inicio ${baseName}`;
        else if (isEnd) finalLabel = `Fin ${baseName}`;

        return { label: finalLabel, isStart, isEnd };
    };

    const combinedAuditList = useMemo(() => {
        const mappedLogs = (logs || []).map(l => ({ ...l, isAbsenceRecord: false }));
        const mappedAbsences = (absences || []).map(a => ({
            id: `abs_${a.id}`,
            realAbsenceId: a.id,
            userId: a.userId,
            userName: a.userName,
            type: a.type === 'injustificada' ? 'Falta Injustificada' : 'Falta Justificada',
            date: a.date,
            timestamp: a.createdAt || Date.now(),
            justification: a.notes ? `Observación: ${a.notes}` : 'Sin nota',
            isAbsenceRecord: true,
            absenceType: a.type
        }));
        return [...mappedLogs, ...mappedAbsences];
    }, [logs, absences]);

    const filteredLogs = useMemo(() => {
        const result = combinedAuditList.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; }

            let matchType = true;
            if (selectedActionType === 'ENTRADA_SALIDA') {
                matchType = l.type === 'entrada' || l.type === 'salida';
            } else if (selectedActionType === 'ALMUERZO') {
                matchType = String(l.type).includes('almuerzo');
            } else if (selectedActionType === 'AUSENCIAS') {
                matchType = l.isAbsenceRecord;
            } else if (selectedActionType === 'ALERTAS') {
                matchType = (l.justification && l.justification.startsWith('ALERTA:')) || window.isUserOffDay(globalUsers.find(u=>u.id===l.userId)?.scheduleDays, l.date);
            } else if (selectedActionType !== 'ALL') {
                matchType = String(l.type).includes(selectedActionType);
            }

            return matchName && matchDate && matchType;
        });

        return result.sort((a,b) => {
            if (a.date !== b.date) return a.date > b.date ? -1 : 1;
            if (a.userName !== b.userName) return a.userName.localeCompare(b.userName);
            return a.timestamp - b.timestamp;
        });
    }, [combinedAuditList, searchName, searchDate, startDate, endDate, selectedActionType, globalUsers]);

   // MONITOREO GPS EN VIVO ESTRICTO (SOLO POSICIONES REALES DE HOY)
    const handleOpenLiveTrackingMap = () => {
        const todayNIC = window.getNICDate();
        
        // Filtrar colaboradores con GPS activo que hayan emitido señal real hoy
        const activeTrackers = (globalUsers || []).filter(u => {
            if (!u.gpsTrackingEnabled || !u.lastLat || !u.lastLng || !u.lastGpsTime) return false;
            
            // Validar que la última señal emitida pertenezca a la fecha de hoy
            const signalDate = window.getNICDateFromObj(new Date(u.lastGpsTime));
            return signalDate === todayNIC;
        });

        if (activeTrackers.length === 0) {
            alert("No hay vendedores o colaboradores transmitiendo posición GPS en tiempo real en este momento.");
            return;
        }

        const mapItems = activeTrackers.map(u => ({
            id: `live_${u.id}`,
            userName: `${u.name} (@${u.alias})`,
            type: 'visita_in',
            timestamp: u.lastGpsTime,
            location: { lat: u.lastLat, lng: u.lastLng },
            justification: `Última transmisión en vivo: ${window.formatNICTimeFull(u.lastGpsTime)}`
        }));

        setMapLogs(mapItems);
    };

    const handleOpenEdit = (log) => {
        setEditingLog(log);
        setFormUser(log.userId);
        setFormType(log.type);
        setFormDate(log.date);
        
        const dateObj = new Date(log.timestamp);
        const hours = String(dateObj.getHours()).padStart(2, '0');
        const mins = String(dateObj.getMinutes()).padStart(2, '0');
        setFormTime(`${hours}:${mins}`);
        setFormJustification(log.justification || '');
    };

    const handleSaveLogAudit = async (e) => {
        e.preventDefault();
        const [h, m] = formTime.split(':').map(Number);
        const [y, mon, d] = formDate.split('-').map(Number);
        const targetTimestamp = new Date(y, mon - 1, d, h, m, 0).getTime();

        const userObj = globalUsers.find(u => Number(u.id) === Number(formUser));
        if (!userObj) return alert("Selecciona un colaborador.");

        const payload = {
            id: editingLog ? editingLog.id : null,
            userId: userObj.id,
            userName: userObj.name,
            type: formType,
            date: formDate,
            timestamp: targetTimestamp,
            justification: `${formJustification ? formJustification + ' | ' : ''}Ajuste Manual por Administrador (${new Date().toLocaleDateString()})`
        };

        const res = await window.apiCall(editingLog ? 'update_log' : 'save_log', payload);
        if (res && res.success) {
            setEditingLog(null);
            setShowNewMarkModal(false);
            if (refreshData) await refreshData();
        } else {
            alert("Error al procesar marca.");
        }
    };

    const handleDeleteLog = async (logId) => {
        if (!confirm("¿Eliminar este registro de marcaje de la auditoría?")) return;
        const res = await window.apiCall('delete_log', { id: logId });
        if (res && res.success && refreshData) await refreshData();
    };

    const printReport = () => window.print();

    return (
        <div className="space-y-6 fade-in">
            {(editingLog || showNewMarkModal) && (
                <div className="fixed inset-0 bg-slate-900/60 z-[120] flex items-center justify-center p-4 fade-in" onClick={() => { setEditingLog(null); setShowNewMarkModal(false); }}>
                    <div className="bg-white p-8 rounded-[3rem] w-full max-w-lg shadow-2xl space-y-4 border-t-[10px] border-indigo-600" onClick={e=>e.stopPropagation()}>
                        <h3 className="font-black text-xl text-slate-900">{editingLog ? 'Corregir Registro de Marcaje' : 'Registrar Marca Manual (Olvido)'}</h3>
                        <p className="text-slate-400 font-bold text-[10px] uppercase tracking-widest">Quedará asentado en auditoría quién realizó el ajuste</p>

                        <form onSubmit={handleSaveLogAudit} className="space-y-4 pt-2">
                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Colaborador</label>
                                <select value={formUser} onChange={e=>setFormUser(e.target.value)} className="w-full p-3.5 bg-slate-50 rounded-2xl font-bold text-xs outline-none border focus:ring-2 focus:ring-indigo-200" required>
                                    <option value="">Seleccionar...</option>
                                    {globalUsers.map(u => <option key={u.id} value={u.id}>{u.name} (@{u.alias})</option>)}
                                </select>
                            </div>

                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Tipo de Marca</label>
                                    <select value={formType} onChange={e=>setFormType(e.target.value)} className="w-full p-3.5 bg-slate-50 rounded-2xl font-bold text-xs outline-none border focus:ring-2 focus:ring-indigo-200">
                                        <option value="entrada">Entrada Trabajo</option>
                                        <option value="salida">Salida (Cierre de Día)</option>
                                        <option value="almuerzo_in">Inicio Almuerzo</option>
                                        <option value="almuerzo_out">Fin Almuerzo</option>
                                        {actions.map(a => (
                                            <React.Fragment key={a.id}>
                                                <option value={`${a.id}_in`}>Inicio {a.label}</option>
                                                <option value={`${a.id}_out`}>Fin {a.label}</option>
                                            </React.Fragment>
                                        ))}
                                    </select>
                                </div>
                                <div>
                                    <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Hora Exacta</label>
                                    <input type="time" value={formTime} onChange={e=>setFormTime(e.target.value)} className="w-full p-3.5 bg-slate-50 rounded-2xl font-bold text-xs outline-none border focus:ring-2 focus:ring-indigo-200" required />
                                </div>
                            </div>

                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Fecha</label>
                                <input type="date" value={formDate} onChange={e=>setFormDate(e.target.value)} className="w-full p-3.5 bg-slate-50 rounded-2xl font-bold text-xs outline-none border focus:ring-2 focus:ring-indigo-200" required />
                            </div>

                            <div>
                                <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block">Motivo / Justificación</label>
                                <input value={formJustification} onChange={e=>setFormJustification(e.target.value)} placeholder="Ej. Olvidó marcar entrada por corte de luz..." className="w-full p-3.5 bg-slate-50 rounded-2xl font-bold text-xs outline-none border focus:ring-2 focus:ring-indigo-200" required />
                            </div>

                            <div className="flex gap-3 pt-4">
                                <button type="button" onClick={() => { setEditingLog(null); setShowNewMarkModal(false); }} className="flex-1 py-4 bg-slate-100 hover:bg-slate-200 text-slate-600 rounded-2xl font-black uppercase text-[10px] transition-colors">Cancelar</button>
                                <button type="submit" className="flex-1 py-4 bg-indigo-600 hover:bg-indigo-700 text-white rounded-2xl font-black uppercase text-[10px] shadow-lg transition-colors">Guardar Ajuste</button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            <div className="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100 flex flex-col space-y-4 print:hidden">
                <div className="flex items-center justify-between pb-2 border-b border-slate-100">
                    <div>
                        <h3 className="text-xl font-black text-slate-900">Auditoría Operativa</h3>
                        <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mt-1">Busca, filtra, exporta y corrige marcajes del personal</p>
                    </div>
                    <div className="flex gap-2">
                        <button onClick={()=>applyQuickFilter('today')} className="px-4 py-2 bg-slate-50 hover:bg-indigo-50 text-slate-500 hover:text-indigo-600 rounded-xl font-black text-[9px] uppercase tracking-widest transition-colors border">Hoy</button>
                        <button onClick={()=>applyQuickFilter('this_week')} className="px-4 py-2 bg-slate-50 hover:bg-indigo-50 text-slate-500 hover:text-indigo-600 rounded-xl font-black text-[9px] uppercase tracking-widest transition-colors border">Esta Semana</button>
                        <button onClick={()=>applyQuickFilter('this_month')} className="px-4 py-2 bg-slate-50 hover:bg-indigo-50 text-slate-500 hover:text-indigo-600 rounded-xl font-black text-[9px] uppercase tracking-widest transition-colors border">Este Mes</button>
                    </div>
                </div>

                <div className="flex flex-col lg:flex-row items-end gap-4">
                    <div className="w-full lg:w-1/4">
                        <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block tracking-widest">Colaborador</label>
                        <input value={searchName} onChange={e=>setSearchName(e.target.value)} placeholder="Buscar nombre..." className="w-full p-4 bg-slate-50 border rounded-2xl font-bold outline-none focus:border-indigo-500 transition-colors text-xs" />
                    </div>

                    <div className="w-full lg:w-1/4">
                        <label className="text-[10px] font-black uppercase text-slate-400 ml-2 mb-1 block tracking-widest">Filtrar Marcas</label>
                        <select value={selectedActionType} onChange={e=>setSelectedActionType(e.target.value)} className="w-full p-4 bg-slate-50 border rounded-2xl font-bold outline-none focus:border-indigo-500 text-xs uppercase">
                            <option value="ALL">TODAS LAS MARCAS</option>
                            <option value="ENTRADA_SALIDA">SOLO ENTRADA Y SALIDA</option>
                            <option value="ALMUERZO">SOLO ALMUERZOS</option>
                            <option value="AUSENCIAS">SOLO AUSENCIAS (FALTAS)</option>
                            <option value="ALERTAS">SOLO EXCESOS / DÍAS LIBRES</option>
                        </select>
                    </div>

                    <div className="w-full lg:w-1/4">
                        <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 rounded-2xl font-bold outline-none focus:border-indigo-500 transition-colors text-xs" />
                    </div>

                    <div className="w-full lg:w-1/4 bg-slate-50 p-2.5 rounded-2xl border relative">
                        <span className="text-[9px] font-black uppercase tracking-widest text-indigo-500 block mb-1">Rango Opcional</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 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 text-xs" />
                        </div>
                    </div>
                </div>

                <div className="flex flex-wrap justify-end gap-3 pt-2">
                    <button onClick={handleOpenLiveTrackingMap} className="px-5 py-4 bg-emerald-500 hover:bg-emerald-600 text-white rounded-2xl font-black uppercase text-[10px] tracking-widest shadow-lg flex items-center gap-2 transition-all">
                        <span className="w-2 h-2 rounded-full bg-white animate-ping"></span> 📡 Monitoreo en Vivo
                    </button>
                    <button onClick={() => { setFormUser(''); setFormType('entrada'); setFormDate(window.getNICDate()); setFormTime('08:00'); setFormJustification(''); setShowNewMarkModal(true); }} className="px-5 py-4 bg-indigo-600 hover:bg-indigo-700 text-white rounded-2xl font-black uppercase text-[10px] tracking-widest shadow-lg flex items-center gap-2 transition-all">
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4"></path></svg>
                        Marca Manual
                    </button>
                    <button onClick={()=>setMapLogs(filteredLogs.filter(l=>!l.isAbsenceRecord))} className="px-5 py-4 bg-indigo-50 text-indigo-700 hover:bg-indigo-100 rounded-2xl font-black uppercase text-[10px] tracking-widest shadow-sm flex items-center gap-2 transition-all border border-indigo-200">
                        Ruta Filtro
                    </button>
                    <button onClick={printReport} className="px-5 py-4 bg-slate-900 hover:bg-black text-white rounded-2xl font-black uppercase text-[10px] tracking-widest shadow-lg flex items-center gap-2 transition-all">
                        Imprimir / PDF
                    </button>
                </div>
            </div>

            {/* TABLA DE AUDITORÍA */}
            <div className="bg-white rounded-[3rem] shadow-sm overflow-hidden border border-slate-100 print:rounded-none print:shadow-none print:border-none">
                <div className="hidden print:block mb-6 border-b-2 border-black pb-3">
                    <h2 className="text-xl font-black uppercase tracking-widest">{window.SHIFT_CONFIG?.companyName || 'Shift'} - Reporte de Asistencia y Auditoría</h2>
                    <p className="text-sm font-bold text-gray-600 mt-1">
                        Impreso el: {new Date().toLocaleDateString()} a las {new Date().toLocaleTimeString()} | Filtro: {selectedActionType} | Mostrando {filteredLogs.length} registros.
                    </p>
                </div>

                <table className="w-full text-left print-table">
                    <thead className="bg-slate-50 text-[10px] font-black text-slate-500 uppercase border-b border-slate-100 print:text-[8pt] print:bg-gray-100">
                        <tr>
                            <th className="p-5 print:p-2">Colaborador / Usuario</th>
                            <th className="p-5 print:p-2">Actividad Registrada</th>
                            <th className="p-5 print:p-2">Fecha y Hora</th>
                            <th className="p-5 print:p-2">Observación de Auditoría</th>
                            <th className="p-5 print:p-2 text-center print:hidden">Pruebas Físicas</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-50 print:divide-gray-400">
                        {filteredLogs.length === 0 ? (
                            <tr>
                                <td colSpan="5" className="p-8 text-center text-sm font-bold text-slate-400 print:p-4">
                                    No se encontraron registros en la fecha seleccionada.
                                </td>
                            </tr>
                        ) : (
                            filteredLogs.map((l) => {
                                if (l.isAbsenceRecord) {
                                    return (
                                        <tr key={l.id} className="bg-red-50/60 hover:bg-red-50 text-xs">
                                            <td className="p-5 font-black text-red-900 print:p-2">{l.userName}</td>
                                            <td className="p-5 uppercase font-bold text-[10px] print:p-2">
                                                <span className={`inline-block px-3 py-1.5 rounded-xl text-[9px] font-black uppercase tracking-wider ${l.absenceType === 'injustificada' ? 'bg-red-600 text-white print-badge' : 'bg-orange-500 text-white print-badge'}`}>
                                                    {l.type}
                                                </span>
                                            </td>
                                            <td className="p-5 font-bold text-slate-700 print:p-2">{window.formatDateToNIC(l.date)}</td>
                                            <td className="p-5 print:p-2">
                                                <span className="p-1.5 bg-white border border-red-200 rounded-lg text-[10px] font-black text-red-700">
                                                    {l.justification} {l.absenceType === 'injustificada' ? '(Deduce Séptimo Día en Nómina)' : ''}
                                                </span>
                                            </td>
                                            <td className="p-5 text-center print:hidden"><span className="text-[10px] font-black uppercase text-red-400 tracking-widest">Ausencia</span></td>
                                        </tr>
                                    );
                                }

                                const { label: displayType, isStart, isEnd } = formatLogType(l.type);
                                const userObj = globalUsers.find(u => u.id === l.userId);
                                const isOffDay = userObj ? window.isUserOffDay(userObj.scheduleDays, l.date) : false;
                                const isAlert = l.justification && l.justification.startsWith('ALERTA:');
                                const isMissedOut = l.justification === 'SALIDA NO REGISTRADA (OLVIDO)';

                                return (
                                    <tr key={l.id || l.timestamp} className={`transition-colors text-xs ${isAlert || isMissedOut ? 'bg-red-50/30' : 'hover:bg-slate-50/50'}`}>
                                        <td className="p-5 font-black text-indigo-950 print:p-2 print:text-black">
                                            {l.userName || 'Usuario'}
                                            {l.client && <span className="block text-[10px] text-slate-500 font-bold mt-1 print:inline print:ml-2">({l.client})</span>}
                                        </td>
                                        <td className="p-5 uppercase font-bold text-[10px] print:p-2">
                                            <span className={`inline-block px-3 py-1.5 rounded-xl text-[9px] font-black uppercase tracking-wider ${
                                                l.type === 'entrada' ? 'bg-emerald-50 text-emerald-700 border border-emerald-200' :
                                                l.type === 'salida' ? 'bg-red-50 text-red-700 border border-red-200' :
                                                isStart ? 'bg-orange-50 text-orange-700 border border-orange-200' :
                                                isEnd ? 'bg-blue-50 text-blue-700 border border-blue-200' :
                                                'bg-indigo-50 text-indigo-700 border border-indigo-200'
                                            } print-badge`}>
                                                {displayType}
                                            </span>
                                        </td>
                                        <td className="p-5 font-bold text-slate-700 print:p-2">
                                            {window.formatNICTimeFull ? window.formatNICTimeFull(l.timestamp) : new Date(l.timestamp).toLocaleString()}
                                        </td>
                                        <td className="p-5 print:p-2">
                                            {isOffDay && (
                                                <span className="px-2.5 py-1 bg-orange-100 text-orange-800 font-black text-[9px] rounded-lg uppercase mr-2 inline-block mb-1 print:border">
                                                    ★ Marca en Día Libre
                                                </span>
                                            )}
                                            {isAlert || isMissedOut ? (
                                                <div className="p-1.5 bg-red-100 border border-red-200 rounded-lg text-[10px] font-black text-red-700 inline-block">
                                                    {l.justification}
                                                </div>
                                            ) : l.justification ? (
                                                <span className="text-[10px] font-bold text-indigo-700 bg-indigo-50 px-2 py-1 rounded-lg border border-indigo-100 inline-block">
                                                    {l.justification}
                                                </span>
                                            ) : (
                                                <span className="text-slate-400 text-[10px] font-medium italic">Normal</span>
                                            )}
                                        </td>
                                        <td className="p-5 text-center print:hidden">
                                            <div className="flex items-center justify-center gap-2">
                                                <button onClick={()=>handleOpenEdit(l)} className="p-2 bg-slate-50 hover:bg-indigo-100 text-slate-500 hover:text-indigo-700 rounded-xl transition-colors shadow-sm" title="Editar Marca">
                                                    <svg className="w-4 h-4" 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>
                                                </button>
                                                {l.location && l.location.lat ? (
                                                    <button onClick={()=>setMapLogs([l])} className="px-3 py-1.5 bg-indigo-50 text-indigo-700 hover:bg-indigo-600 hover:text-white rounded-xl font-black text-[9px] uppercase tracking-widest transition-all shadow-sm">
                                                        GPS
                                                    </button>
                                                ) : <span className="text-[9px] text-slate-300 font-bold uppercase w-10 text-center">N/A</span>}
                                                {l.photo ? (
                                                    <img src={l.photo} onClick={()=>setPreviewImage(l.photo)} onError={(e) => { e.target.style.display = 'none'; }} className="w-8 h-8 rounded-xl object-cover cursor-pointer hover:scale-110 transition-transform border border-slate-200 shadow-sm" />
                                                ) : <div className="w-8 h-8 rounded-xl border border-dashed border-slate-300 flex items-center justify-center text-slate-300 text-[8px] font-black">X</div>}
                                                <button onClick={()=>handleDeleteLog(l.id)} className="p-2 bg-slate-50 hover:bg-red-100 text-slate-400 hover:text-red-700 rounded-xl transition-colors shadow-sm" title="Eliminar Registro">
                                                    <svg className="w-4 h-4" 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>
                                        </td>
                                    </tr>
                                );
                            })
                        )}
                    </tbody>
                </table>
            </div>
        </div>
    );
};