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

window.UserDashboard = function({ profile, logs, reminders = [], 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 videoRef = useRef(null);
    const canvasRef = useRef(null);

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

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

    // --- NUEVO: Filtrar notificaciones activas para este usuario ---
    const activeReminders = useMemo(() => {
        const now = Date.now();
        return reminders.filter(r => 
            r.targetUsers?.includes(profile.id) && 
            !(r.completedBy && r.completedBy[profile.id]) &&
            (!r.expiresAt || r.expiresAt > now)
        );
    }, [reminders, profile.id]);

    // --- NUEVO: Marcar notificación como leída ---
    const markReminderCompleted = async (rId) => {
        try {
            const rRef = db.collection('artifacts').doc(appId).collection('public').doc('data').collection('reminders').doc(rId);
            const rDoc = await rRef.get();
            const completedBy = rDoc.data().completedBy || {};
            completedBy[profile.id] = Date.now();
            await rRef.update({ completedBy });
        } catch (e) { alert("Error al confirmar lectura."); }
    };

    // Obtener los permisos del rol actual (Configurados por el administrador)
    const userRoleConfig = useMemo(() => allRoles.find(r => (r.name || r) === profile.role), [allRoles, profile.role]);
    const permissions = userRoleConfig && userRoleConfig.permissions ? userRoleConfig.permissions : [];

    // Bloqueo de jornada si ya marcó salida (con bypass administrativo)
    const isShiftCompleted = useMemo(() => {
        const hasSalida = todayLogs.some(l => l.type === 'salida');
        return hasSalida && !profile.overrideCheckOut;
    }, [todayLogs, profile.overrideCheckOut]);

    const startAction = async (p) => {
        if (isShiftCompleted) return;
        
        // Acciones sin cámara (ahora incluye las nuevas opciones configurables)
        if (['almuerzo', 'vuelta_almuerzo', 'break', 'capacitacion', 'reunion', 'gestiones'].includes(p)) {
            return saveMark(p, null, null);
        }
        
        if (p === 'visita_in') {
            const name = prompt("Escriba el nombre del Cliente:");
            if (!name) return;
            setClientName(name);
        }

        setPurpose(p); 
        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) { alert("Error con la cámara."); 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 }),
            () => { alert("GPS obligatorio."); setShowCam(false); }
        );
    };

    const saveMark = async (type, photo, loc) => {
        setLoadingMark(true);
        try {
            await db.collection('artifacts').doc(appId).collection('public').doc('data').collection('logs').add({
                userId: profile.id, userName: profile.name, type, 
                timestamp: Date.now(), location: loc, photo, 
                client: clientName, date: todayStr, role: profile.role
            });

            if (type === 'salida' && profile.overrideCheckOut) {
                await db.collection('artifacts').doc(appId).collection('public').doc('data').collection('users').doc(profile.id).update({ overrideCheckOut: false });
            }

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

    if (profile.status === 'subsidio' || profile.status === 'feriado') return (
        <div className="h-screen flex flex-col items-center justify-center p-8 text-center bg-slate-50">
            <Icon name={profile.status === 'subsidio' ? 'heart-pulse' : 'calendar'} className="w-16 h-16 text-indigo-600 mb-6" />
            <h1 className="text-3xl font-black uppercase text-indigo-900">Estado: {profile.status}</h1>
            <p className="text-slate-400 mt-4 uppercase text-[10px] font-black">Acceso Inhabilitado</p>
            <button onClick={onLogout} className="mt-10 px-8 py-3 bg-indigo-600 text-white rounded-2xl font-bold uppercase text-xs">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">
            {/* --- NUEVO: UI DE NOTIFICACIONES --- */}
            {activeReminders.length > 0 && (
                <div className="fixed inset-x-6 top-6 z-50 space-y-3">
                    {activeReminders.map(r => (
                        <div key={r.id} className="bg-white p-6 rounded-3xl shadow-2xl border-l-8 border-indigo-600 animate-bounce">
                            <h4 className="font-black text-indigo-950 uppercase text-xs tracking-widest">{r.title}</h4>
                            <p className="text-slate-500 text-[11px] mt-1 font-medium leading-relaxed">{r.message}</p>
                            <button onClick={() => markReminderCompleted(r.id)} className="mt-4 w-full py-3 bg-emerald-500 text-white rounded-2xl font-black uppercase text-[10px] flex items-center justify-center gap-2 active:scale-95 transition-all">
                                <Icon name="check-circle" className="w-4 h-4" /> Entendido / Completado
                            </button>
                        </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>
                <button onClick={onLogout} className="p-3 text-slate-300 hover:text-red-500 rounded-2xl transition-colors"><Icon name="log-out" /></button>
            </header>

            {profile.role === 'admin' && (
                <button onClick={() => setView('admin')} className="w-full 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">
                    <Icon name="settings" className="w-4 h-4" /> Panel Admin
                </button>
            )}

            <div className="grid gap-4">
                {isShiftCompleted ? (
                    <div className="h-72 bg-slate-100 rounded-[3rem] border-2 border-dashed border-slate-200 flex flex-col items-center justify-center text-slate-400 text-center p-8">
                        <Icon name="moon" className="w-12 h-12 mb-4" />
                        <span className="text-lg font-black uppercase">Jornada Finalizada</span>
                        <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">
                        <Icon name="camera" className="w-12 h-12 mb-4" />
                        <span className="text-xl font-black uppercase">Entrada Trabajo</span>
                        <p className="text-emerald-100 text-[10px] font-bold uppercase mt-2 opacity-60 tracking-widest">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.formatNICFull ? window.formatNICFull(Date.now()) : new Date().toLocaleDateString()}</p>
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                            {/* --- BOTONES DINÁMICOS BASADOS EN LOS PERMISOS DEL ROL --- */}
                            {permissions.includes('almuerzo') && (
                                <button onClick={() => startAction(status === 'almuerzo' ? 'vuelta_almuerzo' : 'almuerzo')} className={`h-32 rounded-3xl shadow-sm flex flex-col items-center justify-center font-black uppercase text-[10px] ${status === 'almuerzo' ? 'bg-orange-500 text-white' : 'bg-white text-slate-700 border'}`}>
                                    <Icon name="coffee" className="w-8 h-8 mb-2" /> {status === 'almuerzo' ? 'Regresar' : 'Almuerzo'}
                                </button>
                            )}
                            {permissions.includes('break') && (
                                <button onClick={() => startAction('break')} className="h-32 rounded-3xl shadow-sm flex flex-col items-center justify-center font-black uppercase text-[10px] bg-white text-slate-700 border">
                                    <Icon name="clock" className="w-8 h-8 mb-2" /> Break
                                </button>
                            )}
                            {permissions.includes('visita_in') && (
                                <button onClick={() => startAction(status === 'visita_in' ? 'visita_out' : 'visita_in')} className={`h-32 rounded-3xl shadow-sm flex flex-col items-center justify-center font-black uppercase text-[10px] ${status === 'visita_in' ? 'bg-blue-600 text-white animate-pulse' : 'bg-white text-slate-700 border'}`}>
                                    <Icon name="briefcase" className="w-8 h-8 mb-2" /> {status === 'visita_in' ? 'Saliendo' : 'Visitando'}
                                </button>
                            )}
                            {permissions.includes('reunion') && (
                                <button onClick={() => startAction('reunion')} className="h-32 rounded-3xl shadow-sm flex flex-col items-center justify-center font-black uppercase text-[10px] bg-white text-slate-700 border">
                                    <Icon name="users" className="w-8 h-8 mb-2" /> Reunión
                                </button>
                            )}
                            {permissions.includes('capacitacion') && (
                                <button onClick={() => startAction('capacitacion')} className="h-32 rounded-3xl shadow-sm flex flex-col items-center justify-center font-black uppercase text-[10px] bg-white text-slate-700 border">
                                    <Icon name="graduation-cap" className="w-8 h-8 mb-2" /> Capacit.
                                </button>
                            )}
                            {permissions.includes('gestiones') && (
                                <button onClick={() => startAction('gestiones')} className="h-32 rounded-3xl shadow-sm flex flex-col items-center justify-center font-black uppercase text-[10px] bg-white text-slate-700 border">
                                    <Icon name="file-text" className="w-8 h-8 mb-2" /> Gestiones
                                </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">Cerrar Día</button>
                    </div>
                )}
            </div>

            {/* MANTENEMOS TU HISTORIAL INTACTO */}
            <div className="bg-white p-8 rounded-[3rem] border border-slate-100 shadow-sm max-h-[350px] overflow-y-auto no-scrollbar">
                <h3 className="font-black text-[10px] uppercase tracking-widest text-slate-400 mb-6 flex items-center gap-2 border-b pb-4"><Icon name="list" /> Bitácora de Hoy</h3>
                {todayLogs.length === 0 ? <p className="text-center py-10 text-[10px] font-black uppercase opacity-20">Sin registros aún</p> : (
                    <div className="space-y-4">
                        {todayLogs.map(l => (
                            <div key={l.timestamp} className="flex items-center gap-4 group">
                                <div className={`w-3 h-3 rounded-full ${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">{l.type.replace('_', ' ')} {l.client && <span className="text-indigo-600">- {l.client}</span>}</p>
                                    <p className="text-[9px] text-slate-400 font-bold mt-1 uppercase">{window.formatNICTime ? window.formatNICTime(l.timestamp) : new Date(l.timestamp).toLocaleTimeString()}</p>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>

            {/* MANTENEMOS TU UI DE CÁMARA INTACTA */}
            {showCam && (
                <div className="fixed inset-0 bg-slate-950 z-50 flex flex-col items-center justify-center p-6 text-white fade-in">
                    <div className="camera-container w-full max-w-sm shadow-2xl">
                        <video ref={videoRef} autoPlay playsInline muted />
                        <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">
                            {loadingMark ? <div className="w-8 h-8 border-4 border-indigo-600 border-t-transparent rounded-full animate-spin"></div> : <Icon name="camera" className="w-10 h-10" />}
                        </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">Cancelar Marca</button>
                    </div>
                </div>
            )}
        </div>
    );
};