import React, { useState, useEffect, useCallback, useRef } from 'react';
import FullCalendar from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';
import { Calendar as CalendarIcon, Plus, X, Loader2, GripVertical, Settings as GearIcon, Edit, Trash2, CalendarRange, Clock, User, Stethoscope, AlertCircle, CheckCircle2, Bell, CalendarClock, History, Download, PanelLeftClose, PanelLeftOpen } from 'lucide-react';
import { AgendaSettingsModal } from '../components/AgendaSettingsModal.tsx';
import { HorariosConfig } from '../components/HorariosConfig.tsx';
import { PedidosPendentes } from '../components/PedidosPendentes.tsx';
import { AgendaDetailModal, ScoreBadge, FamiliaChips } from '../components/AgendaDetailModal.tsx';
import { WhatsChatDrawer } from './newwhats/WhatsChatDrawer.tsx';
import { AgendaPresence } from '../components/AgendaPresence.tsx';
import { DragDropContext, Droppable, Draggable } from '@hello-pangea/dnd';
import { HybridBackend } from '../services/backend.ts';
import { Realtime } from '../services/realtime.ts';
import { Dentista, Agendamento, Paciente, DentistaHorario } from '../types.ts';
import { useGTOStore } from './LancarGTO.tsx';
import { useHybridBackend } from '../hooks/useHybridBackend.ts';
import { useToast } from '../contexts/ToastContext.tsx';

// --- Reusable Debounce Hook ---
function useDebounce(value: string, delay: number) {
    const [debouncedValue, setDebouncedValue] = useState(value);
    useEffect(() => {
        const handler = setTimeout(() => {
            setDebouncedValue(value);
        }, delay);
        return () => clearTimeout(handler);
    }, [value, delay]);
    return debouncedValue;
}

// --- Advanced Appointment Modal Component ---
const AppointmentModal: React.FC<{
    isOpen: boolean;
    onClose: () => void;
    onSave: () => void;
    dentists: Dentista[] | null;
    initialDate?: string;
    initialAppointment?: Agendamento | null;
    initialPatient?: { id?: string; nome?: string } | null;
}> = ({ isOpen, onClose, onSave, dentists, initialDate, initialAppointment, initialPatient }) => {
    const [selectedPatient, setSelectedPatient] = useState<Paciente | null>(null);
    const [searchTerm, setSearchTerm] = useState('');
    const [duration, setDuration] = useState(15);
    const [selectedDate, setSelectedDate] = useState(initialDate ? initialDate.split('T')[0] : new Date().toISOString().split('T')[0]);
    const [selectedTime, setSelectedTime] = useState(initialDate ? new Date(initialDate).toTimeString().substring(0, 5) : '');
    const [selectedDentistId, setSelectedDentistId] = useState<string | undefined>(dentists?.[0]?.id);
    const [procedimento, setProcedimento] = useState('');
    const [isSearchFocused, setIsSearchFocused] = useState(false);
    // Fase 4 — conflito de horário → painel de interesse
    const [conflito, setConflito] = useState<any | null>(null);
    const [tempoEspera, setTempoEspera] = useState(60);
    const [registrando, setRegistrando] = useState(false);

    const debouncedSearchTerm = useDebounce(searchTerm, 400);

    const fetcher = useCallback(() => HybridBackend.getPacientes(debouncedSearchTerm).then(r => Array.isArray(r.data) ? r.data : []), [debouncedSearchTerm]);
    const { data: searchResults, isLoading: isSearching } = useHybridBackend<Paciente[]>(fetcher, [debouncedSearchTerm]);

    const { data: agendamentos, refresh: refreshAgendamentos } = useHybridBackend<Agendamento[]>(HybridBackend.getAgendamentos);
    const activeWorkspace = HybridBackend.getActiveWorkspace();
    const { data: allHorarios } = useHybridBackend<DentistaHorario[]>(() =>
        selectedDentistId && activeWorkspace ? HybridBackend.getHorariosByDentista(selectedDentistId, activeWorkspace.id) : Promise.resolve([]),
        [selectedDentistId, activeWorkspace?.id]
    );
    const toast = useToast();

    useEffect(() => {
        if (isOpen) {
            setConflito(null);
            if (initialAppointment) {
                setSelectedPatient({ nome: initialAppointment.pacienteNome, cpf: '', id: 'temp' } as any);
                const startDate = new Date(initialAppointment.start);
                const endDate = new Date(initialAppointment.end);
                setSelectedDate(startDate.toISOString().split('T')[0]);
                setSelectedTime(startDate.toTimeString().substring(0, 5));
                setDuration((endDate.getTime() - startDate.getTime()) / 60000);
                setSelectedDentistId(initialAppointment.dentistaId);
                setProcedimento(initialAppointment.procedimento);
            } else {
                // Reagendar (a partir da lista "a reagendar"): pré-preenche o paciente.
                if (initialPatient?.nome) {
                    setSelectedPatient({ nome: initialPatient.nome, cpf: '', id: initialPatient.id || 'temp' } as any);
                } else {
                    setSelectedPatient(null);
                }
                setSearchTerm('');
                setSelectedDate(initialDate ? initialDate.split('T')[0] : new Date().toISOString().split('T')[0]);
                setSelectedTime(initialDate ? new Date(initialDate).toTimeString().substring(0, 5) : '');
                setProcedimento('');
                setDuration(15);
                if (dentists && dentists.length > 0) {
                    setSelectedDentistId(dentists[0].id);
                }
            }
        }
    }, [isOpen, initialDate, dentists, initialAppointment, initialPatient]);

    useEffect(() => {
        if (!isOpen) return;
        const handleKeyDown = (event: KeyboardEvent) => { if (event.key === 'Escape') onClose(); };
        document.addEventListener('keydown', handleKeyDown);
        return () => document.removeEventListener('keydown', handleKeyDown);
    }, [isOpen, onClose]);

    const selectedDentist = dentists?.find(d => d.id === selectedDentistId);

    const timeSlots = useCallback(() => {
        const slots: string[] = [];
        if (!selectedDentistId || !selectedDate) return slots;

        const existingAppointments = (agendamentos ?? []).filter(ag =>
            ag.dentistaId === selectedDentistId &&
            new Date(ag.start).toISOString().split('T')[0] === selectedDate &&
            ag.id !== initialAppointment?.id
        ).map(ag => ({
            start: new Date(ag.start).getHours() * 60 + new Date(ag.start).getMinutes(),
            end: new Date(ag.end).getHours() * 60 + new Date(ag.end).getMinutes(),
        }));

        const dayOfWeek = new Date(selectedDate).getUTCDay();
        const dayHorarios = allHorarios?.filter(h => h.dia_semana === dayOfWeek && h.ativo) || [];

        if (dayHorarios.length === 0) {
            // Default 8-18 fallback if no hours set
            for (let time = 8 * 60; time < 18 * 60; time += 15) {
                const isOccupied = existingAppointments.some(app => time >= app.start && time < app.end);
                if (!isOccupied) {
                    const hour = Math.floor(time / 60), minute = time % 60;
                    slots.push(`${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`);
                }
            }
        } else {
            for (const h of dayHorarios) {
                const [hStart, mStart] = h.hora_inicio.split(':').map(Number);
                const [hEnd, mEnd] = h.hora_fim.split(':').map(Number);
                for (let time = hStart * 60 + mStart; time < hEnd * 60 + mEnd; time += 15) {
                    const isOccupied = existingAppointments.some(app => time >= app.start && time < app.end);
                    if (!isOccupied) {
                        const hour = Math.floor(time / 60), minute = time % 60;
                        slots.push(`${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`);
                    }
                }
            }
        }

        // If current time is not on the 15m grid (like 12:03), add it as a valid slot
        if (selectedTime && !slots.includes(selectedTime)) {
            slots.push(selectedTime);
            slots.sort();
        }

        return slots;
    }, [selectedDentistId, selectedDate, agendamentos, initialAppointment, selectedTime, allHorarios])();

    const handlePatientSelect = (patient: Paciente) => {
        setSelectedPatient(patient);
        setSearchTerm('');
        setIsSearchFocused(false);
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!selectedPatient || !selectedDate || !selectedTime || !selectedDentistId || !procedimento) {
            toast.error("PREENCHA TODOS OS CAMPOS PARA AGENDAR.");
            return;
        }
        const startDateTime = new Date(`${selectedDate}T${selectedTime}:00`);
        const endDateTime = new Date(startDateTime.getTime() + duration * 60000);
        const agData: any = {
            pacienteNome: selectedPatient.nome,
            dentistaId: selectedDentistId,
            start: startDateTime.toISOString(),
            end: endDateTime.toISOString(),
            status: initialAppointment?.status || 'agendado',
            procedimento: procedimento.toUpperCase(),
        };
        // Vincula o paciente real (id != 'temp') → habilita faltas, família e auto-baixa de pendência.
        if (selectedPatient.id && selectedPatient.id !== 'temp') agData.pacienteId = selectedPatient.id;
        try {
            if (initialAppointment?.id) {
                await HybridBackend.atualizarAgendamento(initialAppointment.id, agData);
                toast.success(`AGENDAMENTO DE ${selectedPatient.nome} ATUALIZADO!`);
            } else {
                await HybridBackend.salvarAgendamento(agData);
                toast.success(`AGENDAMENTO PARA ${selectedPatient.nome} SALVO!`);
            }
            refreshAgendamentos();
            onSave();
        } catch (err: any) {
            if (err?.conflito) {
                setConflito({ ocupado: err.ocupado, agData });   // abre painel de interesse
            } else {
                toast.error(err?.message || "ERRO AO SALVAR AGENDAMENTO.");
            }
        }
    };

    const handleRegistrarInteresse = async () => {
        if (!conflito) return;
        setRegistrando(true);
        try {
            const currentUserId = (() => { try { return JSON.parse(localStorage.getItem('SCOREODONTO_USER_DATA') || '{}').id; } catch { return undefined; } })();
            await HybridBackend.registrarInteresse({
                dentistaId: conflito.agData.dentistaId,
                clinicaInteressadaId: activeWorkspace?.id,
                solicitanteUsuarioId: currentUserId,
                start: conflito.agData.start,
                end: conflito.agData.end,
                tempoEsperaMin: tempoEspera || undefined,
            });
            toast.success("INTERESSE REGISTRADO! VOCÊ SERÁ AVISADO SE O HORÁRIO LIBERAR.");
            setConflito(null);
            onSave();
        } catch (e: any) {
            toast.error(e?.message || "ERRO AO REGISTRAR INTERESSE.");
        } finally { setRegistrando(false); }
    };

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-0">
            {conflito && (
                <div className="absolute inset-0 z-[60] bg-black/40 flex items-center justify-center p-4" onClick={() => setConflito(null)}>
                    <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6" onClick={e => e.stopPropagation()}>
                        <div className="flex items-center gap-2 mb-2">
                            <AlertCircle size={20} className="text-teal-500" />
                            <h3 className="text-base font-black uppercase text-gray-900">Horário ocupado</h3>
                        </div>
                        <p className="text-sm text-gray-600 mb-4">
                            O profissional já tem compromisso nesse horário (em qualquer clínica). Você pode <strong>registrar interesse</strong> e ser avisado se o horário liberar, ou escolher outro horário.
                        </p>
                        <label className="block text-[10px] font-black text-gray-400 uppercase tracking-widest mb-1.5">Aguardar liberar por (minutos)</label>
                        <input type="number" min={0} value={tempoEspera} onChange={e => setTempoEspera(parseInt(e.target.value) || 0)}
                            className="w-full px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-sm font-bold outline-none focus:border-teal-400" />
                        <p className="text-[10px] text-gray-400 mt-1 mb-4">0 = sem expiração (aguarda até liberar).</p>
                        <div className="flex gap-3">
                            <button type="button" onClick={() => setConflito(null)}
                                className="flex-1 py-3 rounded-xl bg-gray-100 text-gray-600 font-black uppercase text-xs hover:bg-gray-200 transition-all">
                                Escolher outro horário
                            </button>
                            <button type="button" onClick={handleRegistrarInteresse} disabled={registrando}
                                className="flex-[1.4] py-3 rounded-xl bg-teal-600 text-white font-black uppercase text-xs hover:bg-teal-700 transition-all flex items-center justify-center gap-2 disabled:opacity-60">
                                {registrando ? <Loader2 size={14} className="animate-spin" /> : <Bell size={14} />} Registrar interesse
                            </button>
                        </div>
                    </div>
                </div>
            )}
            <form onSubmit={handleSubmit} className="bg-white shadow-2xl w-full h-dvh md:w-[96vw] md:h-[98vh] rounded-none md:rounded-xl flex flex-col overflow-hidden animate-in fade-in zoom-in-50 duration-200">
                <div className="px-5 py-4 border-b border-gray-200 flex justify-between items-center flex-shrink-0 bg-gradient-to-r from-teal-50 to-white">
                    <h2 className="text-lg font-bold text-gray-800 flex items-center gap-2 uppercase">
                        <CalendarIcon size={22} className="text-teal-500" /> AGENDAR CONSULTA
                    </h2>
                    <button type="button" onClick={onClose} className="text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg p-1.5 transition-colors"><X size={22} /></button>
                </div>
                <div className="flex-1 overflow-y-auto p-5 lg:p-8">
                    <div className="mb-6">
                        <label className="text-xs font-bold text-gray-500 uppercase tracking-wider">PACIENTE</label>
                        {!selectedPatient ? (
                            <div className="relative mt-2">
                                <input type="text" value={searchTerm} onChange={e => setSearchTerm(e.target.value.toUpperCase())} onFocus={() => setIsSearchFocused(true)} onBlur={() => setTimeout(() => setIsSearchFocused(false), 200)} placeholder="NOME, CPF OU TELEFONE..." className="w-full lg:w-1/2 bg-gray-100 p-3 lg:p-4 rounded-lg font-bold text-gray-800 uppercase focus:border-teal-500 outline-none border-2 border-transparent focus:border-2 text-sm lg:text-base" />
                                {isSearchFocused && debouncedSearchTerm && (
                                    <ul className="absolute z-10 w-full lg:w-1/2 bg-white border border-gray-300 rounded-lg mt-1 max-h-48 overflow-y-auto shadow-lg">
                                        {isSearching && <li className="p-3 text-sm text-gray-500">BUSCANDO...</li>}
                                        {searchResults?.map(p => (
                                            <li key={p.id} onMouseDown={() => handlePatientSelect(p)} className="p-3 hover:bg-gray-100 cursor-pointer uppercase font-semibold text-sm">
                                                {p.nome}
                                                {p.cpf && <span className="text-gray-400 font-normal ml-1">· CPF {p.cpf}</span>}
                                                {p.telefone && <span className="text-gray-400 font-normal ml-1">· TEL {p.telefone}</span>}
                                            </li>
                                        ))}
                                    </ul>
                                )}
                            </div>
                        ) : (
                            <div className="w-full lg:w-1/2 mt-2 space-y-2">
                                <div className="bg-green-50 border border-green-200 p-3 lg:p-4 rounded-lg flex justify-between items-center gap-2">
                                    <span className="font-bold text-green-800 uppercase text-sm lg:text-base truncate">{selectedPatient.nome}</span>
                                    <div className="flex items-center gap-2 shrink-0">
                                        {selectedPatient.id && selectedPatient.id !== 'temp' ? <ScoreBadge pacienteId={selectedPatient.id} /> : null}
                                        <button type="button" onClick={() => setSelectedPatient(null)} className="text-xs font-bold bg-teal-100 text-teal-700 hover:bg-teal-200 px-3 py-1.5 rounded-md transition-colors">ALTERAR</button>
                                    </div>
                                </div>
                                {selectedPatient.id && selectedPatient.id !== 'temp' ? (
                                    <FamiliaChips pacienteId={selectedPatient.id} onPick={(m) => setSelectedPatient({ nome: m.nome, cpf: '', id: m.id } as any)} />
                                ) : null}
                            </div>
                        )}
                    </div>
                    {selectedPatient && (
                        <div className="animate-in fade-in space-y-6 lg:space-y-0">
                            <div className="lg:grid lg:grid-cols-3 lg:gap-x-8 lg:gap-y-6 space-y-5 lg:space-y-0">
                                <div className="space-y-5">
                                    <div>
                                        <label className="text-xs font-bold text-gray-500 uppercase tracking-wider">DENTISTA RESPONSÁVEL</label>
                                        <div className="flex items-center gap-3 mt-2">
                                            <select value={selectedDentistId} onChange={e => setSelectedDentistId(e.target.value)} className="w-full border border-gray-300 rounded-lg p-2.5 lg:p-3 bg-white uppercase-select text-sm">
                                                {dentists?.map(d => <option key={d.id} value={d.id}>{d.nome}</option>)}
                                            </select>
                                            <div className="w-7 h-7 rounded-full flex-shrink-0 border-2 border-white shadow-md" style={{ backgroundColor: selectedDentist?.corAgenda || '#ccc' }}></div>
                                        </div>
                                    </div>
                                    <div className="grid grid-cols-2 gap-4">
                                        <div>
                                            <label className="text-xs font-bold text-gray-500 uppercase tracking-wider">DATA</label>
                                            <input type="date" value={selectedDate} onChange={e => setSelectedDate(e.target.value)} className="w-full mt-2 border border-gray-300 bg-white text-gray-800 rounded-lg p-2.5 lg:p-3 text-sm" />
                                        </div>
                                        <div>
                                            <label className="text-xs font-bold text-gray-500 uppercase tracking-wider">DURAÇÃO</label>
                                            <select value={duration} onChange={e => setDuration(Number(e.target.value))} className="w-full mt-2 border border-gray-300 rounded-lg p-2.5 lg:p-3 bg-white uppercase-select text-sm">
                                                <option value={15}>15 MIN</option>
                                                <option value={30}>30 MIN</option>
                                                <option value={45}>45 MIN</option>
                                                <option value={60}>60 MIN</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div>
                                        <label className="text-xs font-bold text-gray-500 uppercase tracking-wider">PROCEDIMENTO</label>
                                        <input type="text" value={procedimento} onChange={e => setProcedimento(e.target.value.toUpperCase())} placeholder="EX: AVALIAÇÃO, LIMPEZA..." className="w-full mt-2 border border-gray-300 bg-white text-gray-800 rounded-lg p-2.5 lg:p-3 uppercase-input placeholder-gray-400 text-sm" />
                                    </div>
                                </div>
                                <div className="lg:col-span-2">
                                    <label className="text-xs font-bold text-gray-500 uppercase tracking-wider">HORÁRIOS DISPONÍVEIS</label>
                                    <div className="grid grid-cols-6 lg:grid-cols-8 xl:grid-cols-10 gap-2 mt-3">
                                        {timeSlots.map(slot => (
                                            <button type="button" key={slot} onClick={() => setSelectedTime(slot)} className={`py-2.5 lg:py-3 rounded-lg text-sm font-bold border transition-all duration-150 ${selectedTime === slot ? 'bg-teal-600 text-white border-teal-600 shadow-md scale-105' : 'bg-white text-gray-800 border-gray-300 hover:border-teal-400 hover:bg-teal-50'}`}>{slot}</button>
                                        ))}
                                        {timeSlots.length === 0 && <p className="col-span-6 lg:col-span-8 xl:col-span-10 text-center text-sm text-gray-400 p-8 bg-gray-50 rounded-lg border border-dashed border-gray-200 uppercase font-bold">NENHUM HORÁRIO DISPONÍVEL.</p>}
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
                <div className="px-5 py-4 bg-gray-50 border-t border-gray-200 flex justify-end gap-3 flex-shrink-0">
                    <button type="button" onClick={onClose} className="px-8 py-2.5 bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold rounded-lg transition-colors text-sm uppercase">CANCELAR</button>
                    <button type="submit" disabled={!selectedPatient} className="px-10 py-2.5 bg-teal-500 hover:bg-teal-600 text-white font-bold rounded-lg shadow-sm transition-colors text-sm uppercase disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center gap-2"><CalendarIcon size={16} /> CONFIRMAR</button>
                </div>
            </form>
        </div>
    );
};

export const AgendaView: React.FC<{ onNavigate?: (view: string) => void; sidebarCollapsed?: boolean; onToggleSidebar?: () => void; controlsOpen?: boolean; onCloseControls?: () => void }> = ({ onNavigate, sidebarCollapsed, onToggleSidebar, controlsOpen = false, onCloseControls }) => {
    const { data: agendamentos, refresh } = useHybridBackend<Agendamento[]>(HybridBackend.getAgendamentos);
    const { data: dentists, refresh: refreshDentists } = useHybridBackend<Dentista[]>(HybridBackend.getDentistas);
    const { data: googleEvents, refresh: refreshGoogle } = useHybridBackend<any[]>(HybridBackend.getGoogleEvents);
    const [events, setEvents] = useState<any[]>([]);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isSettingsOpen, setIsSettingsOpen] = useState(false);
    const [showMeusHorarios, setShowMeusHorarios] = useState(false);
    const [showPedidos, setShowPedidos] = useState(false);
    const [pedidosCount, setPedidosCount] = useState(0);
    // Pedidos da zona cinza aguardando a secretária humana — badge + poll a cada 30 min.
    useEffect(() => {
        const cid = (HybridBackend.getActiveWorkspace() as any)?.id;
        const role = HybridBackend.getCurrentRole();
        if (!cid || !['admin', 'donoclinica', 'donoconsultorio', 'funcionario'].includes(role)) return;
        let alive = true;
        const poll = async () => {
            try {
                const token = localStorage.getItem('SCOREODONTO_AUTH_TOKEN');
                const r = await fetch(`/api/nw/agenda-config/clinica/${cid}/pedidos?status=pendente`, { headers: token ? { Authorization: `Bearer ${token}` } : {} });
                if (r.ok && alive) { const j = await r.json(); setPedidosCount(j.total || (j.pedidos || []).length || 0); }
            } catch { /* silencioso */ }
        };
        poll();
        const t = setInterval(poll, 30 * 60 * 1000); // 30 min
        return () => { alive = false; clearInterval(t); };
    }, []);
    const [selectedDateInfo, setSelectedDateInfo] = useState<any>(null);
    const [selectedAppointment, setSelectedAppointment] = useState<Agendamento | null>(null);
    const [showDetails, setShowDetails] = useState(false);
    const [whatsTarget, setWhatsTarget] = useState<{ pacienteId: string; pacienteNome: string } | null>(null);
    const [interesses, setInteresses] = useState<any[]>([]);
    const [showInteresses, setShowInteresses] = useState(false);
    const [pendencias, setPendencias] = useState<any[]>([]);
    const [showPendencias, setShowPendencias] = useState(false);
    const [reagendarPatient, setReagendarPatient] = useState<{ id?: string; nome?: string } | null>(null);
    const [atividade, setAtividade] = useState<any[]>([]);
    const [showAtividade, setShowAtividade] = useState(false);
    const toast = useToast();

    // Lista "a reagendar" (faltas/cancelamentos/remarcações pendentes desta clínica)
    const loadPendencias = useCallback(async () => {
        try { setPendencias(await HybridBackend.getPendenciasReagendar()); } catch { /* ignore */ }
    }, []);
    useEffect(() => { loadPendencias(); }, [loadPendencias]);
    const loadAtividade = useCallback(async () => {
        try { setAtividade(await HybridBackend.getAtividadeAgenda()); } catch { /* ignore */ }
    }, []);
    const [isMobile, setIsMobile] = useState(typeof window !== 'undefined' && window.innerWidth < 640);
    useEffect(() => {
        const onResize = () => setIsMobile(window.innerWidth < 640);
        window.addEventListener('resize', onResize);
        return () => window.removeEventListener('resize', onResize);
    }, []);
    const [importando, setImportando] = useState(false);
    const handleImportarGoogle = async () => {
        if (!confirm('Importar os agendamentos do Google (última semana + próximos) para o sistema? Eles passam a ser editáveis aqui.')) return;
        setImportando(true);
        try {
            const r = await HybridBackend.importarGoogleAgenda();
            if (!r.success) { toast.error(r.message || 'ERRO AO IMPORTAR.'); return; }
            toast.success(`IMPORTADOS: ${r.criados ?? 0} (${r.pulados ?? 0} já existiam).`);
            refresh(); refreshGoogle();
        } catch { toast.error('ERRO AO IMPORTAR.'); }
        finally { setImportando(false); }
    };

    // Fase 4 Parte 2 — o dentista vê os pedidos de interesse na própria agenda
    const meuUsuarioId = (() => { try { return JSON.parse(localStorage.getItem('SCOREODONTO_USER_DATA') || '{}').id; } catch { return undefined; } })();
    const souDentista = HybridBackend.getCurrentRole() === 'dentista';
    const loadInteresses = useCallback(async () => {
        if (!souDentista || !meuUsuarioId) return;
        try { setInteresses(await HybridBackend.getInteresses({ profissionalId: meuUsuarioId })); } catch { /* ignore */ }
    }, [souDentista, meuUsuarioId]);
    useEffect(() => { loadInteresses(); }, [loadInteresses]);
    const interessesAguardando = interesses.filter(i => i.status === 'aguardando').length;

    // Atualização quase em tempo real: refaz o fetch a cada 20s e ao voltar o foco
    // à aba/janela, para que agendamentos criados por outra pessoa apareçam sem reload.
    const liveRef = useRef({ refresh, refreshGoogle, loadPendencias, loadInteresses });
    liveRef.current = { refresh, refreshGoogle, loadPendencias, loadInteresses };

    // Tempo real (WebSocket): ao receber aviso de mudança, refaz o fetch na hora.
    // Coalesce vários avisos próximos (ex.: import em lote) num único refetch.
    const rtDebounce = useRef<ReturnType<typeof setTimeout> | null>(null);
    useEffect(() => {
        const unsub = Realtime.subscribe((msg) => {
            if (msg?.type !== 'agenda') return;
            if (rtDebounce.current) clearTimeout(rtDebounce.current);
            rtDebounce.current = setTimeout(() => {
                liveRef.current.refresh();
                liveRef.current.loadPendencias();
                liveRef.current.loadInteresses();
            }, 350);
        });
        return () => { unsub(); if (rtDebounce.current) clearTimeout(rtDebounce.current); };
    }, []);

    // Fallback (caso o WebSocket caia): refetch leve a cada 60s e ao focar a aba.
    const tickCount = useRef(0);
    useEffect(() => {
        const tick = (force?: boolean) => {
            if (document.visibilityState === 'hidden') return;
            liveRef.current.refresh();
            liveRef.current.loadPendencias();
            liveRef.current.loadInteresses();
            tickCount.current += 1;
            if (force || tickCount.current % 2 === 0) liveRef.current.refreshGoogle();
        };
        const iv = setInterval(() => tick(), 60000);
        const onFocus = () => tick(true);
        window.addEventListener('focus', onFocus);
        document.addEventListener('visibilitychange', onFocus);
        return () => { clearInterval(iv); window.removeEventListener('focus', onFocus); document.removeEventListener('visibilitychange', onFocus); };
    }, []);

    useEffect(() => {
        if (agendamentos && dentists) {
            const currentRole = HybridBackend.getCurrentRole();
            const currentUserEmail = HybridBackend.getCurrentUser();
            const isDentist = currentRole === 'dentista';
            const loginedDentistId = dentists.find(d => d.email === currentUserEmail)?.id;

            let filteredAgendamentos = agendamentos;
            if (isDentist) {
                filteredAgendamentos = agendamentos.filter(ag => ag.dentistaId === loginedDentistId);
            }

            const mappedEvents = filteredAgendamentos.map(ag => {
                const dentist = dentists.find(d => d.id === ag.dentistaId);
                const st = String(ag.status || '').toLowerCase();
                const faltou = st === 'falta' || st === 'faltou';
                const inativo = st === 'cancelado' || st === 'remarcar';
                // Prioridade: status (falta/cancelado) > cor própria do agendamento (ex.: importada do Google) > cor do dentista.
                const cor = faltou ? '#ef4444' : inativo ? '#cbd5e1' : ((ag as any).cor || (dentist ? dentist.corAgenda : '#94a3b8'));
                const nomePac = (ag as any).pacienteNome || (ag as any).pacientenome || '';
                return {
                    id: ag.id,
                    title: `${nomePac} - ${ag.procedimento}`,
                    start: ag.start,
                    end: ag.end,
                    backgroundColor: cor,
                    borderColor: cor,
                    extendedProps: { ...ag, pacienteNome: nomePac, isGoogle: false, dentistaNome: dentist?.nome }
                };
            });

            // Add Google events if any — com cores: usa a cor real (colorId/agenda) e,
            // quando não houver, escolhe uma cor NÃO usada na agenda (consistente por origem).
            if (googleEvents && googleEvents.length > 0) {
                let filteredGoogleEvents = googleEvents;
                if (isDentist) {
                    filteredGoogleEvents = googleEvents.filter(ev => ev?.extendedProps?.owner_id === currentUserEmail);
                }
                const PALETTE = ['#2563eb', '#7c3aed', '#db2777', '#059669', '#d97706', '#0891b2', '#dc2626', '#4f46e5', '#0d9488', '#ca8a04', '#9333ea', '#e11d48', '#16a34a', '#f97316'];
                const usadas = new Set<string>(mappedEvents.map(e => e.backgroundColor).filter(Boolean));
                const corPorOrigem: Record<string, string> = {};
                const proximaCor = () => PALETTE.find(c => !usadas.has(c)) || PALETTE[Object.keys(corPorOrigem).length % PALETTE.length];
                const coloridos = filteredGoogleEvents.map(ev => {
                    let cor = ev.backgroundColor || null;
                    if (cor) { usadas.add(cor); }
                    else {
                        const origem = ev.owner || 'google';
                        if (!corPorOrigem[origem]) { const c = proximaCor(); corPorOrigem[origem] = c; usadas.add(c); }
                        cor = corPorOrigem[origem];
                    }
                    return { ...ev, backgroundColor: cor, borderColor: cor };
                });
                mappedEvents.push(...coloridos);
            }

            setEvents(mappedEvents);
        }
    }, [agendamentos, dentists, googleEvents]);

    const handleDateClick = (arg: any) => { if ((HybridBackend.getActiveWorkspace() as any)?.role === 'dentista') return; setReagendarPatient(null); setSelectedAppointment(null); setSelectedDateInfo(arg); setIsModalOpen(true); };
    // Selecionar (clicar/arrastar) um intervalo livre também abre o modal de novo agendamento.
    const handleDateSelect = (info: any) => { if ((HybridBackend.getActiveWorkspace() as any)?.role === 'dentista') return; setReagendarPatient(null); setSelectedAppointment(null); setSelectedDateInfo({ dateStr: info.startStr }); setIsModalOpen(true); };

    const handleReagendarPendencia = (p: any) => {
        setShowPendencias(false);
        setSelectedAppointment(null);
        setReagendarPatient({ id: p.paciente_id || undefined, nome: p.paciente_nome });
        setSelectedDateInfo({ dateStr: new Date().toISOString() });
        setIsModalOpen(true);
    };
    const handleDispensarPendencia = async (p: any) => {
        if (!confirm(`Dispensar "${p.paciente_nome}" da lista de reagendamento?`)) return;
        try { await HybridBackend.resolverPendencia(p.id, 'dispensado'); toast.success('PENDÊNCIA DISPENSADA.'); loadPendencias(); }
        catch { toast.error('ERRO AO DISPENSAR.'); }
    };
    const handleEventClick = (info: any) => {
        if (info.event.extendedProps.isGoogle) {
            toast.info(`EVENTO DO GOOGLE CALENDAR: ${info.event.title}`);
            return;
        }

        const ag = info.event.extendedProps as Agendamento;
        setSelectedAppointment(ag);
        setShowDetails(true);
    };

    const handleUpdateStatus = async (id: string, status: Agendamento['status']) => {
        try {
            await HybridBackend.atualizarAgendamento(id, { status });
            toast.success(`STATUS ATUALIZADO PARA ${status.toUpperCase()}`);
            refresh();
            setShowDetails(false);
        } catch {
            toast.error("ERRO AO ATUALIZAR STATUS.");
        }
    };

    const handleDeleteAppointment = async (id: string) => {
        if (!confirm("DESEJA REALMENTE EXCLUIR ESTE AGENDAMENTO?")) return;
        try {
            await HybridBackend.excluirAgendamento(id);
            toast.success("AGENDAMENTO EXCLUÍDO!");
            refresh();
            setShowDetails(false);
        } catch {
            toast.error("ERRO AO EXCLUIR AGENDAMENTO.");
        }
    };

    const handleSaveAppointment = () => { refresh(); refreshGoogle(); loadPendencias(); setIsModalOpen(false); setSelectedAppointment(null); setReagendarPatient(null); };

    const onDragEnd = async (result: any) => {
        if (!result.destination || !dentists) return;

        const items = Array.from(dentists);
        const [reorderedItem] = items.splice(result.source.index, 1);
        items.splice(result.destination.index, 0, reorderedItem);

        const updatedOrders = items.map((item, index) => ({
            id: item.id,
            ordem: index
        }));

        try {
            await HybridBackend.reorderDentistas(updatedOrders);
            toast.success("ORDEM DOS DENTISTAS ATUALIZADA!");
            refreshDentists();
        } catch {
            toast.error("ERRO AO REORDENAR DENTISTAS.");
        }
    };

    const currentRole = HybridBackend.getCurrentRole();
    const currentUserEmail = HybridBackend.getCurrentUser();
    const gtoStore = useGTOStore();

    const handleAtender = async () => {
        if (!selectedAppointment || !onNavigate) return;
        try {
            const result = await HybridBackend.getPacientes(selectedAppointment.pacienteNome);
            const list = Array.isArray(result) ? result : (result?.data ?? []);
            if (list.length > 0) {
                gtoStore.setPaciente(list[0]);
            } else {
                gtoStore.setPendingSearch(selectedAppointment.pacienteNome);
            }
        } catch {
            gtoStore.setPendingSearch(selectedAppointment.pacienteNome);
        }
        setShowDetails(false);
        onNavigate('lancar-gto');
    };

    const filteredDentists = dentists?.filter(d => {
        if (currentRole === 'admin' || currentRole === 'donoclinica' || currentRole === 'funcionario') return true;
        if (currentRole === 'dentista') return d.email === currentUserEmail;
        return false;
    });

    return (
        <div className="flex flex-col lg:flex-row lg:gap-4 h-full">
            {/* Backdrop da gaveta de controles (mobile) — fecha ao tocar fora. Como a sidebar. */}
            {controlsOpen && (
                <div className="fixed inset-0 bg-black/50 z-20 lg:hidden backdrop-blur-sm transition-opacity" onClick={onCloseControls} />
            )}
            {/* Coluna de controles — desktop: lateral esquerda fixa; mobile: gaveta deslizante
                (oculta por padrão p/ dar o máximo de espaço ao calendário; abre pelo ⋯ do header). */}
            <aside className={`
                fixed inset-y-0 right-0 z-30 w-72 max-w-[85%] bg-white shadow-2xl overflow-y-auto p-4 transform transition-transform duration-300
                ${controlsOpen ? 'translate-x-0' : 'translate-x-full'}
                lg:static lg:inset-auto lg:z-auto lg:w-56 lg:max-w-none lg:translate-x-0 lg:transform-none lg:transition-none lg:shadow-none lg:bg-transparent lg:p-0 lg:overflow-y-auto lg:pr-3 lg:border-r lg:border-gray-100
                shrink-0 lg:mb-0`}>
                {/* Fechar a gaveta (só mobile) */}
                <button onClick={onCloseControls} title="Fechar"
                    className="lg:hidden absolute top-3 right-3 p-1.5 rounded-lg text-gray-400 hover:text-gray-700 hover:bg-gray-100 transition-colors z-10">
                    <X size={20} />
                </button>
                {/* Título + recolher menu (desktop, ao lado). No mobile o AGENDAR e as
                    ações ficam empilhados abaixo (dentro da gaveta). */}
                <div className="flex items-center gap-2 mb-3 pr-8 lg:pr-0">
                    {onToggleSidebar && (
                        <button onClick={onToggleSidebar} title={sidebarCollapsed ? 'Mostrar menu lateral' : 'Recolher menu lateral'}
                            className="hidden lg:flex items-center justify-center w-8 h-8 shrink-0 rounded-lg text-gray-400 hover:text-gray-700 hover:bg-gray-100 transition-colors">
                            {sidebarCollapsed ? <PanelLeftOpen size={18} /> : <PanelLeftClose size={18} />}
                        </button>
                    )}
                    <h2 className="text-xl lg:text-base font-bold text-gray-900 uppercase flex-1 min-w-0 leading-tight break-words">AGENDA CLÍNICA</h2>
                </div>
                <div className="flex gap-2 sm:gap-3 items-center flex-wrap lg:flex-col lg:items-stretch">
                    {/* AGENDAR (full-width no topo da coluna/gaveta — mobile e desktop) */}
                    {(currentRole !== 'paciente' && !souDentista) && (
                        <button onClick={() => { setReagendarPatient(null); setSelectedAppointment(null); setSelectedDateInfo({ dateStr: new Date().toISOString() }); setIsModalOpen(true); onCloseControls?.(); }} title="Agendar"
                            className="flex w-full bg-teal-600 text-white px-4 py-2.5 rounded-lg text-sm font-bold uppercase items-center justify-center gap-2 hover:bg-teal-700 shadow-sm transition-colors">
                            <Plus size={18} /> AGENDAR
                        </button>
                    )}
                    {/* Ações — mobile: empilhadas, ícone + nome, largura cheia; desktop: fileira de ícones */}
                    <div className="flex flex-col lg:flex-row gap-2 w-full">
                        {(currentRole !== 'paciente') && (
                            <button onClick={() => { setShowAtividade(true); loadAtividade(); onCloseControls?.(); }} title="Atividade da equipe hoje"
                                className="w-full lg:flex-1 flex items-center justify-start lg:justify-center gap-3 lg:gap-0 px-4 lg:px-0 py-2.5 bg-white text-gray-500 lg:text-gray-400 hover:text-teal-600 border border-gray-200 rounded-xl transition-all hover:border-teal-200 hover:shadow-sm">
                                <History size={20} className="shrink-0" />
                                <span className="lg:hidden text-sm font-bold">Atividade da equipe</span>
                            </button>
                        )}
                        {(currentRole === 'admin' || currentRole === 'donoclinica' || currentRole === 'donoconsultorio') && (
                            <button onClick={handleImportarGoogle} disabled={importando} title="Importar agendamentos do Google para o sistema"
                                className="w-full lg:flex-1 flex items-center justify-start lg:justify-center gap-3 lg:gap-0 px-4 lg:px-0 py-2.5 bg-white text-gray-500 lg:text-gray-400 hover:text-emerald-600 border border-gray-200 rounded-xl transition-all hover:border-emerald-200 hover:shadow-sm disabled:opacity-50">
                                {importando ? <Loader2 size={20} className="animate-spin shrink-0" /> : <Download size={20} className="shrink-0" />}
                                <span className="lg:hidden text-sm font-bold">Importar do Google</span>
                            </button>
                        )}
                        {['admin', 'donoclinica', 'donoconsultorio', 'funcionario'].includes(currentRole) && (
                            <button onClick={() => { setShowPedidos(true); onCloseControls?.(); }} title="Pedidos de horário aguardando confirmação (encaminhados pela Secretária IA)"
                                className="relative w-full lg:flex-1 flex items-center justify-start lg:justify-center gap-3 lg:gap-0 px-4 lg:px-0 py-2.5 bg-white text-gray-500 lg:text-gray-400 hover:text-amber-600 border border-gray-200 rounded-xl transition-all hover:border-amber-200 hover:shadow-sm">
                                <CalendarClock size={20} className="shrink-0" />
                                <span className="lg:hidden text-sm font-bold">Pedidos pendentes</span>
                                {pedidosCount > 0 && <span className="absolute -top-1 -right-1 lg:top-0 lg:right-1 bg-amber-500 text-white text-[10px] font-black rounded-full min-w-[18px] h-[18px] flex items-center justify-center px-1 shadow">{pedidosCount}</span>}
                            </button>
                        )}
                        {(currentRole === 'admin' || currentRole === 'donoclinica' || currentRole === 'donoconsultorio') && (
                            <button onClick={() => { setIsSettingsOpen(true); onCloseControls?.(); }} title="Configurações da agenda"
                                className="w-full lg:flex-1 flex items-center justify-start lg:justify-center gap-3 lg:gap-0 px-4 lg:px-0 py-2.5 bg-white text-gray-500 lg:text-gray-400 hover:text-teal-600 border border-gray-200 rounded-xl transition-all hover:border-teal-200 hover:shadow-sm">
                                <GearIcon size={20} className="shrink-0" />
                                <span className="lg:hidden text-sm font-bold">Configurações</span>
                            </button>
                        )}
                        {souDentista && (
                            <button onClick={() => { setShowMeusHorarios(true); onCloseControls?.(); }} title="Configurar meus dias e horários de atendimento"
                                className="w-full lg:flex-1 flex items-center justify-start lg:justify-center gap-3 lg:gap-0 px-4 lg:px-0 py-2.5 bg-white text-gray-500 lg:text-gray-400 hover:text-teal-600 border border-gray-200 rounded-xl transition-all hover:border-teal-200 hover:shadow-sm">
                                <Clock size={20} className="shrink-0" />
                                <span className="lg:hidden text-sm font-bold">Meus Horários</span>
                            </button>
                        )}
                        {souDentista && (
                            <button onClick={() => { setShowInteresses(true); loadInteresses(); onCloseControls?.(); }} title="Pedidos de interesse na sua agenda"
                                className="relative w-full lg:flex-1 flex items-center justify-start lg:justify-center gap-3 lg:gap-0 px-4 lg:px-0 py-2.5 bg-white text-gray-500 lg:text-gray-400 hover:text-teal-600 border border-gray-200 rounded-xl transition-all hover:border-teal-200 hover:shadow-sm">
                                <Bell size={20} className="shrink-0" />
                                <span className="lg:hidden text-sm font-bold">Interesses na agenda</span>
                                {interessesAguardando > 0 && (
                                    <span className="absolute top-1.5 left-6 lg:left-auto lg:-top-1 lg:-right-1 bg-red-500 text-white text-[9px] font-black rounded-full w-4 h-4 flex items-center justify-center">{interessesAguardando}</span>
                                )}
                            </button>
                        )}
                        {(currentRole !== 'paciente' && !souDentista) && (
                            <button onClick={() => { setShowPendencias(true); loadPendencias(); onCloseControls?.(); }} title="Pacientes a reagendar"
                                className="relative w-full lg:flex-1 flex items-center justify-start lg:justify-center gap-3 lg:gap-0 px-4 lg:px-0 py-2.5 bg-white text-gray-500 lg:text-gray-400 hover:text-amber-600 border border-gray-200 rounded-xl transition-all hover:border-amber-200 hover:shadow-sm">
                                <CalendarClock size={20} className="shrink-0" />
                                <span className="lg:hidden text-sm font-bold">Pacientes a reagendar</span>
                                {pendencias.length > 0 && (
                                    <span className="absolute top-1.5 left-6 lg:left-auto lg:-top-1 lg:-right-1 bg-amber-500 text-white text-[9px] font-black rounded-full w-4 h-4 flex items-center justify-center">{pendencias.length}</span>
                                )}
                            </button>
                        )}
                    </div>
                    <div className="w-full"><AgendaPresence /></div>
                    {/* Legenda de dentistas (desktop, no rodapé da coluna) */}
                    <DragDropContext onDragEnd={onDragEnd}>
                        <Droppable droppableId="dentists-legend" direction="horizontal">
                            {(provided) => (
                                <div {...provided.droppableProps} ref={provided.innerRef} className="hidden lg:flex lg:flex-wrap gap-2 items-center lg:w-full lg:mt-1">
                                    {filteredDentists?.map((d, index) => (
                                        <Draggable key={d.id} draggableId={d.id} index={index} isDragDisabled={currentRole === 'dentista'}>
                                            {(provided, snapshot) => (
                                                <div
                                                    ref={provided.innerRef}
                                                    {...provided.draggableProps}
                                                    {...provided.dragHandleProps}
                                                    className={`flex items-center gap-1.5 text-[10px] text-gray-700 bg-white border border-gray-200 px-3 py-1.5 rounded-full uppercase font-bold shadow-sm transition-all ${currentRole !== 'dentista' ? 'cursor-grab active:cursor-grabbing hover:border-gray-300' : ''} ${snapshot.isDragging ? 'ring-2 ring-teal-500 scale-105 shadow-lg' : ''}`}
                                                >
                                                    {currentRole !== 'dentista' && <GripVertical size={12} className="text-gray-400" />}
                                                    <div className="w-2.5 h-2.5 rounded-full shadow-inner" style={{ backgroundColor: d.corAgenda }}></div>
                                                    {d.nome}
                                                </div>
                                            )}
                                        </Draggable>
                                    ))}
                                    {provided.placeholder}
                                </div>
                            )}
                        </Droppable>
                    </DragDropContext>
                </div>
            </aside>
            <div className="flex-1 min-w-0 bg-white rounded-xl shadow-sm border border-gray-200 p-2 sm:p-4 relative min-h-[420px] lg:min-h-0">
                <FullCalendar
                    key={isMobile ? 'mobile' : 'desktop'}
                    plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
                    initialView={isMobile ? 'timeGridDay' : 'timeGridWeek'}
                    headerToolbar={isMobile
                        ? { left: 'prev,next', center: 'title', right: 'today' }
                        : { left: 'prev,next today', center: 'title', right: 'dayGridMonth,timeGridWeek,timeGridDay' }}
                    footerToolbar={isMobile ? { center: 'timeGridDay,dayGridMonth' } : undefined}
                    locale="pt-br"
                    buttonText={{ today: 'HOJE', month: 'MÊS', week: 'SEMANA', day: 'DIA' }}
                    slotMinTime="08:00:00"
                    slotMaxTime="19:00:00"
                    allDaySlot={false}
                    events={events}
                    selectable={true}
                    selectMirror={true}
                    select={handleDateSelect}
                    dateClick={handleDateClick}
                    eventClick={handleEventClick}
                    height="100%"
                    nowIndicator={true}
                    slotLabelFormat={{ hour: '2-digit', minute: '2-digit', hour12: false }}
                    eventContent={(eventInfo) => {
                        const isGoogle = eventInfo.event.extendedProps.isGoogle;
                        return (
                            <div className="p-0.5 overflow-hidden uppercase h-full">
                                <div className="text-[10px] font-bold">{eventInfo.timeText}</div>
                                {isGoogle ? (
                                    <div className="text-[10px] font-black leading-tight break-words">{eventInfo.event.title}</div>
                                ) : (
                                    <>
                                        <div className="text-xs truncate font-bold">{eventInfo.event.extendedProps.pacienteNome}</div>
                                        <div className="text-[10px] truncate opacity-90">{eventInfo.event.extendedProps.procedimento}</div>
                                    </>
                                )}
                            </div>
                        );
                    }}
                />
            </div>

            {/* Detalhes do agendamento — modal em pilha (autoria, faltas, família, histórico, ações) */}
            <AgendaDetailModal
                key={selectedAppointment?.id}
                isOpen={showDetails && !!selectedAppointment}
                onClose={() => { setShowDetails(false); setSelectedAppointment(null); }}
                appointment={selectedAppointment}
                dentists={dentists}
                onChanged={() => { refresh(); refreshGoogle(); loadPendencias(); }}
                onEditar={() => { setShowDetails(false); setIsModalOpen(true); }}
                onAtender={handleAtender}
                onVerWhats={(info) => setWhatsTarget(info)}
                // "Atender" (abre Lançar GTO) é ação CLÍNICA — atende quem trata: dentista,
                // biomédico, dono da clínica/consultório, dentista locatário, admin. A recepção
                // (funcionario) NÃO atende; ela só remarca/desmarca/agenda.
                podeAtender={!!onNavigate && currentRole !== 'paciente' && currentRole !== 'funcionario'}
                dentistaRestrito={souDentista}
            />

            {/* Drawer de WhatsApp do paciente — clone focado da área de mensagens */}
            <WhatsChatDrawer
                isOpen={!!whatsTarget}
                onClose={() => setWhatsTarget(null)}
                pacienteId={whatsTarget?.pacienteId}
                pacienteNome={whatsTarget?.pacienteNome}
                onNavigate={onNavigate}
            />

            {/* Lista "A REAGENDAR" — pendências de falta/cancelamento/remarcação */}
            {showPendencias && (
                <div className="fixed inset-0 bg-black/50 z-[60] flex items-center justify-center backdrop-blur-sm p-4" onClick={() => setShowPendencias(false)}>
                    <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[85vh] flex flex-col" onClick={e => e.stopPropagation()}>
                        <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
                            <h3 className="text-base font-black uppercase text-gray-900 flex items-center gap-2">
                                <CalendarClock size={18} className="text-amber-600" /> A reagendar
                                <span className="text-[10px] font-bold text-gray-400">({pendencias.length})</span>
                            </h3>
                            <button onClick={() => setShowPendencias(false)} className="p-1.5 hover:bg-gray-100 rounded-lg text-gray-400"><X size={18} /></button>
                        </div>
                        <div className="p-4 overflow-y-auto custom-scrollbar space-y-2">
                            {pendencias.length === 0 ? (
                                <p className="text-center text-xs text-gray-400 font-bold uppercase py-10">NENHUMA PENDÊNCIA. TUDO EM DIA!</p>
                            ) : pendencias.map(p => {
                                const ML: Record<string, string> = { falta: 'FALTOU', cancelado: 'CANCELOU', remarcar: 'PEDIU REMARCAÇÃO' };
                                return (
                                    <div key={p.id} className="flex items-center gap-3 p-3 bg-gray-50 rounded-xl">
                                        <div className="flex-1 min-w-0">
                                            <p className="font-black text-sm text-gray-800 truncate uppercase">{p.paciente_nome || 'PACIENTE'}</p>
                                            <p className="text-[10px] text-gray-400 font-bold uppercase">{ML[p.motivo] || p.motivo} · {new Date(p.created_at).toLocaleDateString('pt-BR')}</p>
                                        </div>
                                        <button onClick={() => handleReagendarPendencia(p)} className="px-3 py-2 bg-teal-600 text-white rounded-lg text-[10px] font-black uppercase hover:bg-teal-700 transition-colors">Reagendar</button>
                                        <button onClick={() => handleDispensarPendencia(p)} title="Dispensar" className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"><X size={16} /></button>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                </div>
            )}

            {/* Feed de ATIVIDADE da equipe (hoje) */}
            {showAtividade && (
                <div className="fixed inset-0 bg-black/50 z-[60] flex items-center justify-center backdrop-blur-sm p-4" onClick={() => setShowAtividade(false)}>
                    <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[85vh] flex flex-col" onClick={e => e.stopPropagation()}>
                        <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
                            <h3 className="text-base font-black uppercase text-gray-900 flex items-center gap-2">
                                <History size={18} className="text-teal-600" /> Atividade de hoje
                            </h3>
                            <button onClick={() => setShowAtividade(false)} className="p-1.5 hover:bg-gray-100 rounded-lg text-gray-400"><X size={18} /></button>
                        </div>
                        <div className="p-4 overflow-y-auto custom-scrollbar space-y-2">
                            {atividade.length === 0 ? (
                                <p className="text-center text-xs text-gray-400 font-bold uppercase py-10">NENHUMA ATIVIDADE HOJE.</p>
                            ) : atividade.map((a, i) => {
                                const AC: Record<string, string> = { criou: 'agendou', reagendou: 'reagendou', editou: 'editou', cancelou: 'cancelou', faltou: 'marcou falta de', remarcou: 'pediu remarcação de', restaurou: 'restaurou' };
                                const pac = a.pacientenome || a.detalhes?.paciente || '';
                                return (
                                    <div key={i} className="flex items-start gap-3 p-2.5 hover:bg-gray-50 rounded-xl">
                                        <div className="w-1.5 h-1.5 rounded-full bg-teal-500 mt-2 shrink-0" />
                                        <div className="flex-1 min-w-0">
                                            <p className="text-xs font-bold text-gray-700">
                                                <span className="text-teal-600">{a.actor_nome || 'Alguém'}</span> {AC[a.acao] || a.acao}{pac ? <span className="text-gray-800 uppercase"> {pac}</span> : null}
                                            </p>
                                            <p className="text-[10px] text-gray-400 font-medium">{new Date(a.at).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' })}</p>
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                </div>
            )}
            <style>{`
                .animate-in { animation: animate-in 0.2s ease-out; }
                @keyframes animate-in {
                    from { opacity: 0; transform: scale(0.95); }
                    to { opacity: 1; transform: scale(1); }
                }
                .custom-scrollbar::-webkit-scrollbar { width: 4px; }
                .custom-scrollbar::-webkit-scrollbar-track { background: #f1f1f1; }
                .custom-scrollbar::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
                /* FullCalendar — toolbar/controles compactos (todas as telas) */
                .fc .fc-toolbar.fc-header-toolbar { margin-bottom: .6rem; }
                .fc .fc-toolbar-title { font-size: 1.05rem; font-weight: 700; }
                .fc .fc-button { padding: .3rem .65rem; font-size: .8rem; box-shadow: none !important; }
                .fc .fc-button-group { gap: 0; }
                .fc .fc-col-header-cell-cushion { font-size: .72rem; padding: 4px 2px; }
                /* FullCalendar — responsividade mobile */
                @media (max-width: 639px) {
                    .fc .fc-toolbar.fc-header-toolbar { margin-bottom: .5rem; flex-wrap: wrap; gap: .4rem; }
                    .fc .fc-toolbar-title { font-size: .95rem; }
                    .fc .fc-button { padding: .25rem .55rem; font-size: .72rem; }
                    .fc .fc-toolbar-chunk { display: flex; align-items: center; }
                    .fc .fc-col-header-cell-cushion { font-size: .65rem; padding: 2px; }
                    .fc .fc-timegrid-slot-label-cushion, .fc .fc-timegrid-axis-cushion { font-size: .6rem; }
                    .fc .fc-timegrid-event .fc-event-main { padding: 1px 2px; }
                    .fc-footer-toolbar.fc-toolbar { margin-top: .5rem; }
                }
            `}</style>
            <AppointmentModal
                isOpen={isModalOpen}
                onClose={() => { setIsModalOpen(false); setSelectedAppointment(null); }}
                onSave={handleSaveAppointment}
                dentists={dentists}
                initialDate={selectedDateInfo?.dateStr}
                initialAppointment={selectedAppointment}
                initialPatient={reagendarPatient}
            />
            <AgendaSettingsModal isOpen={isSettingsOpen} onClose={() => setIsSettingsOpen(false)} dentists={dentists} />
            <HorariosConfig isOpen={showMeusHorarios} onClose={() => setShowMeusHorarios(false)} clinicaId={(HybridBackend.getActiveWorkspace() as any)?.id} initialTab="dentistas" soDentista />
            <PedidosPendentes isOpen={showPedidos} onClose={() => setShowPedidos(false)} clinicaId={(HybridBackend.getActiveWorkspace() as any)?.id}
                onChange={() => { const cid = (HybridBackend.getActiveWorkspace() as any)?.id; const token = localStorage.getItem('SCOREODONTO_AUTH_TOKEN'); if (cid) fetch(`/api/nw/agenda-config/clinica/${cid}/pedidos?status=pendente`, { headers: token ? { Authorization: `Bearer ${token}` } : {} }).then(r => r.ok ? r.json() : { total: 0 }).then(j => setPedidosCount(j.total || 0)).catch(() => {}); }} />

            {showInteresses && (
                <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center backdrop-blur-sm p-4" onClick={() => setShowInteresses(false)}>
                    <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[85vh] flex flex-col" onClick={e => e.stopPropagation()}>
                        <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
                            <h3 className="text-base font-black uppercase text-gray-900 flex items-center gap-2">
                                <Bell size={18} className="text-teal-600" /> Pedidos de interesse
                            </h3>
                            <button onClick={() => setShowInteresses(false)} className="p-1 rounded-lg hover:bg-gray-100"><X size={18} className="text-gray-400" /></button>
                        </div>
                        <div className="p-4 overflow-y-auto space-y-2">
                            {interesses.length === 0 && (
                                <p className="text-sm text-gray-400 text-center py-10">Nenhum pedido de interesse na sua agenda.</p>
                            )}
                            {interesses.map(i => (
                                <div key={i.id} className="border border-gray-100 rounded-xl p-3">
                                    <div className="flex items-center justify-between gap-2">
                                        <p className="text-sm font-bold text-gray-800">
                                            {new Date(i.start_time).toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}
                                        </p>
                                        <span className={`text-[9px] font-black uppercase px-2 py-0.5 rounded-full ${i.status === 'aguardando' ? 'bg-yellow-50 text-yellow-700' : i.status === 'liberado' ? 'bg-emerald-50 text-emerald-700' : 'bg-gray-100 text-gray-500'}`}>{i.status}</span>
                                    </div>
                                    <p className="text-[11px] text-gray-500 mt-1">Interessada: <span className="font-bold">{i.clinica_nome || i.clinica_interessada_id}</span></p>
                                    {i.expira_em && <p className="text-[10px] text-gray-400">Aguarda até: {new Date(i.expira_em).toLocaleString('pt-BR')}</p>}
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};