<script setup>
    import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
    import { Head, router, usePage } from '@inertiajs/vue3';
    import { onMounted, onUnmounted, computed, reactive } from 'vue';
    
    const props = defineProps({
        queues: Array
    });
    
    // === LÓGICA DO ACORDEÃO ===
    // Usamos um Set para guardar os nomes dos setores que estão FECHADOS.
    // Por padrão começa vazio (tudo aberto).
    const collapsedSectors = reactive(new Set());
    
    const toggleSector = (sectorName) => {
        if (collapsedSectors.has(sectorName)) {
            collapsedSectors.delete(sectorName); // Se tá fechado, abre
        } else {
            collapsedSectors.add(sectorName); // Se tá aberto, fecha
        }
    };
    
    // Helper para saber se está aberto (para usar no ícone seta)
    const isExpanded = (sectorName) => !collapsedSectors.has(sectorName);
    
    // =================================================================
    // 1. LÓGICA DE AGRUPAMENTO (Core do novo Layout)
    // =================================================================
    const queuesBySector = computed(() => {
        const groups = {};
    
        props.queues.forEach(queue => {
            // Normaliza o nome do setor (maiúsculo para ficar bonito no cabeçalho)
            const rawSector = queue.sector || 'GERAL / SEM SETOR';
            const sectorName = rawSector.toUpperCase();
    
            if (!groups[sectorName]) {
                groups[sectorName] = [];
            }
    
            groups[sectorName].push(queue);
        });
    
        // TRUQUE DE MESTRE: Ordena as chaves (Setores) alfabeticamente
        // Isso garante que 'COMERCIAL' venha antes de 'SUPORTE'
        return Object.keys(groups).sort().reduce((obj, key) => {
            obj[key] = groups[key];
            return obj;
        }, {});
    });
    
    // =================================================================
    // 2. CÁLCULO DE TOTAIS (Mantido igual, lógica perfeita)
    // =================================================================
    const totalStats = computed(() => {
        let stats = {
            received: 0,
            waiting: 0,
            abandoned: 0,
            total_wait_time_seconds: 0,
            total_talk_time_seconds: 0
        };
    
        props.queues.forEach(queue => {
            const metrics = queue.daily_metrics[0] || {};
            const received = metrics.received_count || 0;
            const waiting = queue.waiting_list?.length || 0; // Adicionei ?. por segurança
            const abandoned = metrics.abandoned_count || 0;
    
            const tme = metrics.avg_wait_time || 0;
            const tma = metrics.avg_talk_time || 0;
    
            stats.received += received;
            stats.waiting += waiting;
            stats.abandoned += abandoned;
    
            // Média Ponderada
            stats.total_wait_time_seconds += (tme * received);
    
            const answered = Math.max(0, received - abandoned);
            stats.total_talk_time_seconds += (tma * answered);
        });
    
        const answeredTotal = Math.max(0, stats.received - stats.abandoned);
    
        return {
            received: stats.received,
            waiting: stats.waiting,
            abandoned: stats.abandoned,
            avg_wait_time: stats.received > 0 ? (stats.total_wait_time_seconds / stats.received) : 0,
            avg_talk_time: answeredTotal > 0 ? (stats.total_talk_time_seconds / answeredTotal) : 0
        };
    });
    
    // =================================================================
    // 3. WEBSOCKET / REALTIME
    // =================================================================
    const page = usePage();
    const userTenantId = page.props.auth.user.tenant_id;
    let channel = null;
    
    onMounted(() => {
        if (userTenantId) {
            if (window.Echo) {
                connectToChannel();
            } else {
                const checkEcho = setInterval(() => {
                    if (window.Echo) {
                        clearInterval(checkEcho);
                        connectToChannel();
                    }
                }, 100);
            }
        }
    });
    
    const connectToChannel = () => {
        console.log(`📡 Conectando ao canal dashboard.${userTenantId}...`);
    
        channel = window.Echo.private(`dashboard.${userTenantId}`)
            .listen('.metrics.updated', (e) => {
                console.log("🔔 Evento recebido! Atualizando...", e);
                // O reload atualiza as props.queues, o que dispara 
                // automaticamente os computed (queuesBySector e totalStats)
                router.reload({ only: ['queues'], preserveScroll: true });
            })
            .error((err) => {
                console.error("❌ Erro de Conexão/Auth:", err);
            });
    };
    
    onUnmounted(() => {
        if (userTenantId && window.Echo) {
            console.log(`🔌 Desconectando...`);
            window.Echo.leave(`dashboard.${userTenantId}`);
        }
    });
    
    // =================================================================
    // 4. HELPERS VISUAIS
    // =================================================================
    
    const formatDuration = (seconds) => {
        if (!seconds || isNaN(seconds)) return '00:00:00';
    
        const totalSeconds = Math.floor(seconds);
        const h = Math.floor(totalSeconds / 3600);
        const m = Math.floor((totalSeconds % 3600) / 60);
        const s = totalSeconds % 60;
    
        const hh = h.toString().padStart(2, '0');
        const mm = m.toString().padStart(2, '0');
        const ss = s.toString().padStart(2, '0');
    
        return `${hh}:${mm}:${ss}`;
    };
    
    const calculatePercentage = (part, total) => {
        if (!total || total === 0) return '0.0%';
        const percent = (part / total) * 100;
        return `${percent.toFixed(1)}%`;
    };
    </script>
    
    <template>
    
        <Head title="Filas" />
    
        <AuthenticatedLayout>
            <template #header>
                <h2 class="text-xl font-bold text-gray-800 leading-tight">
                    Monitoramento em Tempo Real
                </h2>
            </template>
    
            <div class="py-8 bg-gray-50 min-h-screen">
                <div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
    
                    <div class="bg-white shadow-xl sm:rounded-lg overflow-hidden border border-gray-200">
                        <div class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
    
                                <thead>
                                    <tr class="bg-gray-50 text-gray-500 text-xs uppercase tracking-wider font-bold">
                                        <th scope="col" class="px-6 py-3 text-left w-1/3">Fila / Canal</th>
                                        <th scope="col" class="px-6 py-3 text-center w-1/6">Total (Dia)</th>
                                        <th scope="col" class="px-6 py-3 text-center w-1/6">Na Fila</th>
                                        <th scope="col" class="px-6 py-3 text-center w-1/6">TME (Espera)</th>
                                        <th scope="col" class="px-6 py-3 text-center w-1/6">TMA (Conversa)</th>
                                        <th scope="col" class="px-6 py-3 text-center w-1/6 text-red-600">Abandonos</th>
                                    </tr>
                                </thead>
    
                                <tbody class="bg-white">
    
                                    <tr class="bg-indigo-50 border-b-2 border-indigo-100">
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <div class="flex items-center">
                                                <div
                                                    class="flex-shrink-0 h-10 w-10 flex items-center justify-center rounded-full bg-indigo-600 text-white shadow-md">
                                                    <svg class="w-6 h-6" fill="none" stroke="currentColor"
                                                        viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round"
                                                            stroke-width="2"
                                                            d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 012 2h2a2 2 0 012-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z">
                                                        </path>
                                                    </svg>
                                                </div>
                                                <div class="ml-4">
                                                    <div class="text-sm font-black text-indigo-900 uppercase">TOTAL GERAL
                                                    </div>
                                                    <div class="text-xs text-indigo-500 font-medium">Todas as operações
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
    
                                        <td class="px-6 py-4 text-center">
                                            <span class="text-lg font-black text-gray-800">{{ totalStats.received }}</span>
                                        </td>
    
                                        <td class="px-6 py-4 text-center">
                                            <div v-if="totalStats.waiting > 0"
                                                class="inline-flex items-center px-3 py-1 rounded-full text-xs font-bold bg-red-600 text-white shadow animate-pulse">
                                                {{ totalStats.waiting }}
                                            </div>
                                            <span v-else class="text-gray-400">-</span>
                                        </td>
    
                                        <td class="px-6 py-4 text-center font-mono text-sm font-bold text-gray-700">
                                            {{ formatDuration(totalStats.avg_wait_time) }}
                                        </td>
    
                                        <td class="px-6 py-4 text-center font-mono text-sm font-bold text-gray-700">
                                            {{ formatDuration(totalStats.avg_talk_time) }}
                                        </td>
    
                                        <td class="px-6 py-4 text-center">
                                            <div class="flex flex-col items-center">
                                                <span class="font-bold"
                                                    :class="totalStats.abandoned > 0 ? 'text-red-600' : 'text-gray-400'">
                                                    {{ totalStats.abandoned }}
                                                </span>
                                                <span class="text-[10px] bg-gray-200 px-1.5 rounded text-gray-600 mt-1">
                                                    {{ calculatePercentage(totalStats.abandoned, totalStats.received) }}
                                                </span>
                                            </div>
                                        </td>
                                    </tr>
    
                                    <template v-for="(sectorQueues, sectorName) in queuesBySector" :key="sectorName">
    
                                        <tr @click="toggleSector(sectorName)"
                                            class="bg-gray-100 border-t border-b border-gray-200 cursor-pointer hover:bg-gray-200 transition select-none">
                                            <td colspan="6" class="px-6 py-2 text-left">
                                                <div class="flex items-center gap-2">
    
                                                    <div class="transition-transform duration-200"
                                                        :class="{ 'rotate-180': !isExpanded(sectorName) }">
                                                        <svg class="w-4 h-4 text-gray-500" fill="none" stroke="currentColor"
                                                            viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round"
                                                                stroke-width="2" d="M19 9l-7 7-7-7"></path>
                                                        </svg>
                                                    </div>
    
                                                    <svg class="w-4 h-4 text-indigo-500" fill="none" stroke="currentColor"
                                                        viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round"
                                                            stroke-width="2"
                                                            d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z">
                                                        </path>
                                                    </svg>
    
                                                    <span
                                                        class="text-xs font-bold text-gray-700 uppercase tracking-wider">{{
                                                            sectorName }}</span>
    
                                                    <span
                                                        class="ml-auto text-[10px] font-semibold bg-white border border-gray-300 px-2 py-0.5 rounded-full text-gray-500">
                                                        {{ sectorQueues.length }} filas
                                                    </span>
                                                </div>
                                            </td>
                                        </tr>
    
                                        <tr v-for="queue in sectorQueues" :key="queue.id" v-show="isExpanded(sectorName)"
                                            class="hover:bg-blue-50 transition duration-150 border-b border-gray-50 last:border-0 group">
    
                                            <td class="px-6 py-3 whitespace-nowrap pl-12 relative">
                                                <div
                                                    class="absolute left-6 top-0 bottom-0 w-px bg-gray-200 group-hover:bg-blue-200">
                                                </div>
    
                                                <div class="flex items-center">
                                                    <div class="mr-3 text-gray-400 group-hover:text-blue-500">
                                                        <svg v-if="queue.type === 'voice'" class="w-4 h-4" fill="none"
                                                            stroke="currentColor" viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round"
                                                                stroke-width="2"
                                                                d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z">
                                                            </path>
                                                        </svg>
                                                        <svg v-else class="w-4 h-4" fill="none" stroke="currentColor"
                                                            viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round"
                                                                stroke-width="2"
                                                                d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z">
                                                            </path>
                                                        </svg>
                                                    </div>
                                                    <span
                                                        class="text-sm font-medium text-gray-700 group-hover:text-blue-700">
                                                        {{ queue.name }}
                                                    </span>
                                                </div>
                                            </td>
    
                                            <td class="px-6 py-3 text-center text-sm text-gray-600 font-medium">
                                                {{ queue.daily_metrics[0]?.received_count || 0 }}
                                            </td>
    
                                            <td class="px-6 py-3 text-center">
                                                <div v-if="(queue.waiting_list?.length || 0) > 0"
                                                    class="inline-flex items-center px-2 py-0.5 rounded text-xs font-bold bg-red-100 text-red-700 border border-red-200">
                                                    {{ queue.waiting_list.length }}
                                                </div>
                                                <span v-else class="text-gray-300 text-xs">-</span>
                                            </td>
    
                                            <td class="px-6 py-3 text-center text-sm font-mono text-gray-600">
                                                {{ formatDuration(queue.daily_metrics[0]?.avg_wait_time) }}
                                            </td>
    
                                            <td class="px-6 py-3 text-center text-sm font-mono text-gray-600">
                                                {{ formatDuration(queue.daily_metrics[0]?.avg_talk_time) }}
                                            </td>
    
                                            <td class="px-6 py-3 text-center">
                                                <span class="text-sm font-bold"
                                                    :class="(queue.daily_metrics[0]?.abandoned_count || 0) > 0 ? 'text-red-500' : 'text-gray-300'">
                                                    {{ queue.daily_metrics[0]?.abandoned_count || 0 }}
                                                </span>
                                            </td>
    
                                        </tr>
                                    </template>
    
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    </template>