/**
 * Dashboard Module
 * Gerencia o painel principal, estatísticas e gráficos
 */
const Dashboard = {
    // Referências dos gráficos
    sitesChart: null,
    eventsChart: null,

    // Cache e controle de loading
    _loading: false,
    _lastLoad: 0,
    _cacheTime: 10000, // 10 segundos de cache
    _abortController: null,
    _lastEventId: 0,
    _notifSound: new Audio('https://assets.mixkit.co/active_storage/sfx/2358/2358-preview.mp3'),

    /**
     * Exibe o dashboard e carrega dados
     */
    async show() {
        UI.showLoading('Carregando painel...');

        const loginPage = document.getElementById('login-page');
        if (loginPage) loginPage.classList.add('hidden');

        const dashboardPage = document.getElementById('dashboard-page');
        if (dashboardPage) dashboardPage.classList.remove('hidden');

        // Carregar usuário logado (se ainda não foi carregado)
        if (!AdminState.currentUser) {
            await Auth.loadCurrentUser();
        }

        // Inicializar gráficos primeiro (vazios)
        this.initCharts();

        try {
            // Carregar dados em paralelo
            await Promise.all([this.load(true), Sites.load()]);

            // Popular seletores após sites carregados
            Users.populateSiteSelectors();

            // Carregar API Tokens para seletores
            if (typeof ApiTokens !== 'undefined' && ApiTokens.loadForSelectors) {
                ApiTokens.loadForSelectors();
            }
        } catch (error) {
            // Silenciar em produção
        } finally {
            UI.hideLoading();
        }
    },

    /**
     * Carrega dados do dashboard
     * OTIMIZADO: Evita chamadas duplicadas com cache e AbortController
     */
    async load(force = false) {
        const now = Date.now();
        if (!force && (now - this._lastLoad) < this._cacheTime) {
            console.log('[Dashboard] Usando cache');
            return;
        }

        if (this._loading && !force) return;

        this._loading = true;
        try {
            console.log('[Dashboard] Buscando dados da API...');
            const response = await Api.get('dashboard&_t=' + Date.now());

            if (response.status === 'success') {
                console.log('[Dashboard] Dados recebidos:', response.data);
                
                // Verificar se há novos eventos para notificação
                if (response.data.recent_events && response.data.recent_events.length > 0) {
                    const newestEvent = response.data.recent_events[0];
                    const newestId = parseInt(newestEvent.id);
                    
                    if (this._lastEventId > 0 && newestId > this._lastEventId) {
                        this.notifyNewActivity(newestEvent);
                    }
                    this._lastEventId = newestId;
                }

                this._lastLoad = Date.now();

                // Inicializar e atualizar
                this.initCharts();
                this.renderStats(response.data);
                this.updateCharts(response.data);
                this.renderRecentEvents(response.data.recent_events || []);
            } else {
                console.error('[Dashboard] Resposta de erro:', response.message);
            }
        } catch (error) {
            console.error('[Dashboard] Falha na requisição:', error);
        } finally {
            this._loading = false;
        }
    },

    /**
     * Notifica nova atividade
     */
    notifyNewActivity(event) {
        // Toca som
        try {
            this._notifSound.play().catch(e => console.warn('Autoplay blocked'));
        } catch (e) {}

        // Efeito visual no sino
        const bell = document.querySelector('.fa-bell');
        const dot = bell?.parentElement.querySelector('span.bg-red-500');
        if (dot) {
            dot.classList.add('notif-pulse');
        }
        
        if (bell) {
            bell.parentElement.classList.add('animate-bounce', 'text-cyan-400');
            setTimeout(() => {
                bell.parentElement.classList.remove('animate-bounce');
            }, 2000);
        }

        // Toast notification
        UI.toast(`Nova atividade: ${event.site_name} - ${event.placa || 'Visita'}`, 'success');
    },

    /**
     * Prompt para adicionar IP à whitelist
     */
    async promptWhitelist(ip, siteId) {
        Swal.fire({
            title: 'Liberar Acesso?',
            text: `Deseja adicionar o IP ${ip} à Lista Branca (Whitelist)? Isso removerá qualquer bloqueio existente para este IP neste site.`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#10b981',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Sim, Liberar IP!',
            cancelButtonText: 'Cancelar',
            background: '#0a101a',
            color: '#fff'
        }).then(async (result) => {
            if (result.isConfirmed) {
                try {
                    const response = await Api.post('security-config', {
                        action: 'add-ip-rule', // Compatibilidade com router
                        site_id: siteId,
                        ip_address: ip,
                        rule_type: 'whitelist',
                        reason: 'Liberado via Dashboard'
                    });
                    
                    // Fallback para rota direta se o router não aceitar o acima
                    if (response.status !== 'success') {
                        await Api.post('ip-rules', {
                            site_id: siteId,
                            ip_address: ip,
                            rule_type: 'whitelist',
                            reason: 'Liberado via Dashboard'
                        });
                    }

                    Swal.fire('Liberado!', `O IP ${ip} foi adicionado à Lista Branca.`, 'success');
                    this.load(true);
                } catch (error) {
                    Swal.fire('Erro!', 'Não foi possível processar a liberação.', 'error');
                }
            }
        });
    },

    /**
     * Remove qualquer regra de IP (Whitelist ou Blacklist)
     */
    async clearIpRules(ip, siteId) {
        Swal.fire({
            title: 'Limpar Regras?',
            text: `Deseja remover todas as regras (Lista Branca e Negra) para o IP ${ip}?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Sim, Limpar Tudo!',
            cancelButtonText: 'Cancelar',
            background: '#0a101a',
            color: '#fff'
        }).then(async (result) => {
            if (result.isConfirmed) {
                try {
                    // Busca a regra para pegar o ID (o router deleta por ID)
                    const rulesRes = await Api.get(`ip-rules&site_id=${siteId}`);
                    if (rulesRes.status === 'success') {
                        const rule = rulesRes.data.find(r => r.ip_address === ip);
                        if (rule) {
                            await Api.delete(`ip-rules&site_id=${siteId}&rule_id=${rule.id}`);
                            Swal.fire('Limpo!', `Todas as regras para o IP ${ip} foram removidas.`, 'success');
                            this.load(true);
                        } else {
                            Swal.fire('Info', 'Nenhuma regra encontrada para este IP.', 'info');
                        }
                    }
                } catch (error) {
                    Swal.fire('Erro!', 'Falha ao remover regras.', 'error');
                }
            }
        });
    },

    /**
     * Renderiza estatísticas do dashboard
     */
    renderStats(data) {
        console.log('[Dashboard] Renderizando estatísticas', data);
        if (!data || !data.summary) return;

        const summary = data.summary;

        const setVal = (id, val) => {
            const el = document.getElementById(id);
            if (el) {
                el.textContent = val !== undefined && val !== null ? val : 0;
            }
        };

        // Card 1: Audiência & Consultas
        setVal('stat-visits-total', summary.events_today);
        setVal('stat-visits-unique', summary.unique_visitors_today);
        setVal('stat-consultas', summary.consultas_today);

        // Card 2: Sistemas Ativos
        setVal('stat-active-sites', summary.active_sites);
        
        const waEl = document.getElementById('stat-wa-status');
        if (waEl) {
            waEl.textContent = summary.wa_active ? 'WTPP: ON' : 'WTPP: OFF';
            waEl.className = `text-[9px] font-bold px-2 py-0.5 rounded border ${summary.wa_active ? 'border-green-500/20 text-green-400 bg-green-500/5' : 'border-red-500/20 text-red-400 bg-red-500/5'}`;
        }

        const tgEl = document.getElementById('stat-tg-status');
        if (tgEl) {
            tgEl.textContent = summary.tg_active ? 'TGRM: ON' : 'TGRM: OFF';
            tgEl.className = `text-[9px] font-bold px-2 py-0.5 rounded border ${summary.tg_active ? 'border-blue-500/20 text-blue-400 bg-blue-500/5' : 'border-red-500/20 text-red-400 bg-red-500/5'}`;
        }

        // Card 3: PIX
        setVal('stat-pix', summary.pix_today);
        setVal('stat-pix-value', Format.brl(summary.pix_value_today));
        
        const keysList = document.getElementById('stat-pix-keys-list');
        if (keysList && summary.pix_keys) {
            if (summary.pix_keys.length > 0) {
                keysList.innerHTML = summary.pix_keys.map(k => `
                    <div class="flex items-center gap-2 text-[8px] text-gray-400 font-mono">
                        <span class="w-1.5 h-1.5 rounded-full bg-green-500"></span>
                        <span class="truncate" title="${k}">${k}</span>
                    </div>
                `).join('');
            } else {
                keysList.innerHTML = '<div class="text-[8px] text-gray-600 italic">Nenhuma chave ativa</div>';
            }
        }

        // Card 4: Bloqueios
        setVal('stat-blocked', summary.blocked_today);
        setVal('stat-redirects', summary.redirected_today);

        const lastUpdateEl = document.getElementById('last-update');
        if (lastUpdateEl) lastUpdateEl.textContent = new Date().toLocaleTimeString('pt-BR');
    },

    /**
     * Renderiza eventos recentes
     */
    renderRecentEvents(events) {
        console.log('[Dashboard] Renderizando log de atividades:', events.length, 'eventos');
        const tbody = document.getElementById('recent-events-body');
        if (!tbody) {
            console.error('[Dashboard] Elemento recent-events-body não encontrado');
            return;
        }

        if (!events || events.length === 0) {
            tbody.innerHTML = '<tr><td colspan="9" class="text-center py-8 text-gray-500">Nenhuma atividade recente.</td></tr>';
            return;
        }

        tbody.innerHTML = events.slice(0, 15).map(e => {
            const time = e.updated_at ? new Date(e.updated_at).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '--:--:--';
            const date = e.updated_at ? new Date(e.updated_at).toLocaleDateString('pt-BR') : '--/--/----';
            const location = e.geo_city ? `${e.geo_city}` : 'Desconhecido';

            // Coluna #Empresa
            const name = (e.site_name || '').toUpperCase();
            let stateBadge = '';

            if (name.includes('MG')) { stateBadge = 'MG'; }
            else if (name.includes('RJ')) { stateBadge = 'RJ'; }
            else if (name.includes('DF')) { stateBadge = 'DF'; }
            else if (name.includes('GO')) { stateBadge = 'GO'; }
            else if (name.includes('MS')) { stateBadge = 'MS'; }
            else if (name.includes('PR')) { stateBadge = 'PR'; }
            else if (name.includes('RS')) { stateBadge = 'RS'; }
            else if (name.includes('MT')) { stateBadge = 'MT'; }
            else if (name.includes('SC')) { stateBadge = 'SC'; }

            const siteInfo = `
                <div class="d-flex align-items-center gap-2 justify-content-center">
                    <span class="badge bg-slate-800 text-cyan-400 border border-cyan-500/20 px-2 py-1" style="font-size: 10px; font-family: 'Orbitron';">${stateBadge}</span>
                    <span class="text-xs font-medium text-slate-300">${e.site_name}</span>
                </div>`;

            // Coluna Dados
            const meta = typeof e.metadata === 'string' ? JSON.parse(e.metadata) : (e.metadata || {});
            const modelo = e.modelo || meta.modelo || '';
            const proprietario = e.proprietario || meta.proprietario || '';
            const whatsapp = e.whatsapp || '';
            
            let waLink = '';
            if (whatsapp) {
                const cleanWa = whatsapp.replace(/\D/g, '');
                const itensPagos = (meta.extrato || []).map(i => i.descricao).join(', ') || 'DARJ';
                const itensPendentes = (meta.debitos_ignorados || []).join(', ');
                
                let msg = `Olá ${proprietario || 'Contribuinte'}, recebemos o pagamento de ${itensPagos} do veículo de placa ${e.placa || 'N/A'}.`;
                if (itensPendentes) {
                    msg += ` Identificamos que ainda restam débitos pendentes: ${itensPendentes}. Gostaria de aproveitar um desconto especial para regularizar o restante agora?`;
                } else {
                    msg += ` Seu veículo está em processo de regularização. Em breve você receberá o comprovante.`;
                }
                
                const encodedMsg = encodeURIComponent(msg);
                waLink = `<a href="https://wa.me/55${cleanWa}?text=${encodedMsg}" target="_blank" class="text-[10px] text-green-400 mt-1 font-bold d-block hover:text-green-300">
                    <i class="fab fa-whatsapp me-1"></i>${whatsapp}
                </a>`;
            }

            const dados = `
                <div class="cursor-pointer" onclick="copy(this); UI.showToast('Dados copiados!')">
                    <h6 class="text-sm mb-0 font-bold text-white">${e.placa || 'SEM PLACA'}</h6>
                    <div class="text-[10px] text-gray-500">${e.renavam || 'S/ REN'}</div>
                    ${modelo ? `<div class="text-[10px] text-cyan-400 mt-1 uppercase">${modelo}</div>` : ''}
                    ${proprietario ? `<div class="text-[9px] text-gray-400 truncate max-w-[150px]" title="${proprietario}">${proprietario}</div>` : ''}
                    ${waLink}
                </div>`;

            // Status Consulta
            let statusConsultaBadge = `<span class="badge rounded-pill bg-success mt-1 border-0" style="font-size: 11px;"><font dir="auto" style="vertical-align: inherit;"><font dir="auto" style="vertical-align: inherit;">${e.status_consulta || 'N/A'}</font></font></span>`;
            if (e.status_consulta && e.status_consulta.includes('bloqueado')) {
                statusConsultaBadge = `<span class="badge rounded-pill bg-danger mt-1 border-0 cursor-pointer" onclick="Dashboard.promptWhitelist('${e.ip_address}', ${e.site_id})" title="Clique para Liberar (Whitelist)" style="font-size: 11px;"><font dir="auto" style="vertical-align: inherit;"><font dir="auto" style="vertical-align: inherit;">${e.status_consulta.toUpperCase()}</font></font></span>`;
            } else if (e.status_consulta === 'concluido') {
                statusConsultaBadge = `<span class="badge rounded-pill bg-primary mt-1 border-0" style="font-size: 11px; background-color: #0d6efd !important;"><font dir="auto" style="vertical-align: inherit;"><font dir="auto" style="vertical-align: inherit;">CONCLUIDO</font></font></span>`;
            } else if (e.status_consulta === 'redirecionado') {
                statusConsultaBadge = `<span class="badge rounded-pill bg-secondary mt-1 border-0 cursor-pointer" onclick="Dashboard.promptWhitelist('${e.ip_address}', ${e.site_id})" title="Clique para Liberar (Whitelist)" style="font-size: 11px; background-color: #6c757d !important;"><font dir="auto" style="vertical-align: inherit;"><font dir="auto" style="vertical-align: inherit;">REDIRECIONADO</font></font></span>`;
            }

            // Status Pagamento
            let statusPagamentoBadge = `<span class="badge rounded-pill bg-warning mt-1 border-0" style="font-size: 11px;"><font dir="auto" style="vertical-align: inherit;"><font dir="auto" style="vertical-align: inherit;">${e.status_pagamento || 'N/A'}</font></font></span>`;
            if (e.status_pagamento === 'pix_gerado') {
                statusPagamentoBadge = `<span class="badge rounded-pill bg-info mt-1 border-0" style="font-size: 11px;"><font dir="auto" style="vertical-align: inherit;"><font dir="auto" style="vertical-align: inherit;">PIX Gerado</font></font></span>`;
            } else if (e.status_pagamento === 'pix_confirmado') {
                statusPagamentoBadge = `<span class="badge rounded-pill bg-success mt-1 border-0" style="font-size: 11px;"><font dir="auto" style="vertical-align: inherit;"><font dir="auto" style="vertical-align: inherit;">PIX Confirmado</font></font></span>`;
            } else if (e.status_pagamento === 'pago') {
                statusPagamentoBadge = `<span class="badge rounded-pill bg-primary mt-1 border-0" style="font-size: 11px;"><font dir="auto" style="vertical-align: inherit;"><font dir="auto" style="vertical-align: inherit;">Pago</font></font></span>`;
            }
            
            // Adiciona badge de Upsell se houver débitos ignorados
            if (meta.debitos_ignorados && meta.debitos_ignorados.length > 0) {
                const listaPendentes = meta.debitos_ignorados.join(', ');
                statusPagamentoBadge += `<br><span class="badge bg-danger mt-1" style="font-size: 9px; opacity: 0.8;" title="Pendentes: ${listaPendentes}">INCOMPLETO</span>`;
                statusPagamentoBadge += `<div class="text-[8px] text-red-400 mt-1 truncate max-w-[100px] mx-auto" title="${listaPendentes}">${listaPendentes}</div>`;
            }

            // Coluna Valor
            const valor = e.valor ? Format.brl(e.valor) : '-';

            // Coluna Ações
            let actions = `<button class="btn btn-sm btn-outline-info me-1" onclick="viewConsulta(${e.id})" title="Ver Detalhes"><i class="fas fa-eye"></i></button>`;
            if (e.status_pagamento === 'pix_gerado') {
                actions += `<button class="btn btn-sm btn-primary" onclick="confirmPix(${e.id})" title="Confirmar PIX"><i class="fas fa-check"></i></button>`;
            }

            return `
                <tr>
                    <td class="text-start px-3">${siteInfo}</td>
                    <td class="text-center">${dados}</td>
                    <td class="text-center">${statusConsultaBadge}</td>
                    <td class="text-center">${statusPagamentoBadge}</td>
                    <td class="text-center"><h6 class="text-sm mb-0">${valor}</h6></td>
                    <td class="text-center">${time} ${date}</td>
                    <td class="text-center">${e.device || 'N/A'}</td>
                    <td class="text-center">${location}</td>
                    <td class="text-center"><div class="d-flex justify-content-center">${actions}</div></td>
                </tr>
            `;
        }).join('');
    },

    /**
     * Inicializa os gráficos Chart.js com estilo Nexus
     */
    initCharts() {
        if (this.mainChart) return;

        Chart.defaults.color = 'rgba(148, 163, 184, 0.6)';
        Chart.defaults.font.family = '"Inter", sans-serif';

        // 1. Gráfico Principal (Timeline Robusta)
        const ctxMain = document.getElementById('main-traffic-chart')?.getContext('2d');
        if (ctxMain) {
            this.mainChart = new Chart(ctxMain, {
                type: 'line',
                data: {
                    labels: Array.from({ length: 24 }, (_, i) => `${i}h`),
                    datasets: [
                        {
                            label: 'FLOW',
                            data: new Array(24).fill(0),
                            borderColor: '#00e5ff',
                            backgroundColor: (context) => {
                                const chart = context.chart;
                                const { ctx, chartArea } = chart;
                                if (!chartArea) return null;
                                const gradient = ctx.createLinearGradient(0, chartArea.bottom, 0, chartArea.top);
                                gradient.addColorStop(0, 'rgba(0, 229, 255, 0)');
                                gradient.addColorStop(1, 'rgba(0, 229, 255, 0.15)');
                                return gradient;
                            },
                            fill: true,
                            tension: 0.4,
                            borderWidth: 3,
                            pointRadius: 0,
                            pointHoverRadius: 6,
                            z: 3
                        },
                        {
                            label: 'SUCCESS',
                            data: new Array(24).fill(0),
                            borderColor: '#10b981',
                            borderWidth: 2,
                            tension: 0.4,
                            pointRadius: 0,
                            z: 2
                        },
                        {
                            label: 'BLOCKED',
                            data: new Array(24).fill(0),
                            borderColor: '#ef4444',
                            borderWidth: 2,
                            tension: 0.4,
                            pointRadius: 0,
                            z: 1
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: { mode: 'index', intersect: false },
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            backgroundColor: 'rgba(5, 7, 10, 0.95)',
                            titleFont: { family: 'Orbitron', size: 11 },
                            bodyFont: { size: 12 },
                            padding: 15,
                            borderColor: 'rgba(0, 229, 255, 0.2)',
                            borderWidth: 1,
                            cornerRadius: 12
                        }
                    },
                    scales: {
                        x: {
                            grid: { color: 'rgba(255, 255, 255, 0.02)', drawBorder: false },
                            ticks: { maxRotation: 0, autoSkip: true, maxTicksLimit: 12 }
                        },
                        y: {
                            grid: { color: 'rgba(255, 255, 255, 0.02)', drawBorder: false },
                            beginAtZero: true,
                            ticks: { precision: 0 }
                        }
                    }
                }
            });
        }

        // 2. Gráfico de Dispositivos (Mini Doughnut)
        const ctxDevices = document.getElementById('devices-chart')?.getContext('2d');
        if (ctxDevices) {
            this.devicesChart = new Chart(ctxDevices, {
                type: 'doughnut',
                data: {
                    labels: [],
                    datasets: [{
                        data: [],
                        backgroundColor: ['#00e5ff', '#3b82f6', '#a855f7'],
                        borderWidth: 0,
                        hoverOffset: 10
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '80%',
                    plugins: {
                        legend: { display: false }
                    }
                }
            });
        }
    },

    /**
     * Atualiza os gráficos e listas
     */
    updateCharts(data) {
        console.log('[Dashboard] Atualizando Analytics Hub', data);

        // Timeline Unificada
        if (this.mainChart && data.hourly) {
            const trafficData = new Array(24).fill(0);
            const successData = new Array(24).fill(0);
            const securityData = new Array(24).fill(0);

            data.hourly.forEach(item => {
                const h = parseInt(item.hour);
                if (h >= 0 && h < 24) {
                    trafficData[h] = parseInt(item.total) || 0;
                    successData[h] = parseInt(item.success) || 0;
                    securityData[h] = parseInt(item.security) || 0;
                }
            });

            this.mainChart.data.datasets[0].data = trafficData;
            this.mainChart.data.datasets[1].data = successData;
            this.mainChart.data.datasets[2].data = securityData;
            this.mainChart.update('none');
        }

        // Dispositivos
        if (this.devicesChart && data.devices) {
            this.devicesChart.data.labels = data.devices.map(d => d.device || 'N/A');
            this.devicesChart.data.datasets[0].data = data.devices.map(d => parseInt(d.count));
            this.devicesChart.update();
        }

        // Cidades (Lista Progressiva Robusta com Efeito Cascata)
        const citiesList = document.getElementById('top-cities-list');
        if (citiesList && data.cities && data.cities.length > 0) {
            const maxVal = Math.max(...data.cities.map(c => parseInt(c.count) || 1));

            const cityItems = data.cities.map(c => {
                const perc = Math.round((parseInt(c.count) / maxVal) * 100);
                return `
                    <div class="city-item shrink-0">
                        <div class="flex justify-between items-center mb-1">
                            <span class="text-[10px] text-cyan-400/80 font-medium tracking-tight">${c.geo_city}</span>
                            <span class="text-[9px] text-gray-600 font-mono">${c.count} HITS</span>
                        </div>
                        <div class="w-full bg-white/5 h-[1px] rounded-full overflow-hidden">
                            <div class="bg-cyan-500/30 h-full" style="width: ${perc}%"></div>
                        </div>
                    </div>
                `;
            }).join('');

            citiesList.innerHTML = cityItems;

            if (data.cities.length > 4) {
                this.startCityCascade();
            }
        }
    },

    /**
     * Inicia o efeito de scroll infinito na lista de cidades
     */
    startCityCascade() {
        if (this._cascadeInterval) clearInterval(this._cascadeInterval);

        const container = document.getElementById('top-cities-list');
        let offset = 0;

        this._cascadeInterval = setInterval(() => {
            offset += 1;
            if (offset > 40) {
                const first = container.firstElementChild;
                container.appendChild(first);
                offset = 0;
                container.style.transition = 'none';
                container.style.transform = `translateY(0)`;
            } else {
                container.style.transition = 'transform 0.5s linear';
                container.style.transform = `translateY(-${offset}px)`;
            }
        }, 100);
    },

    /**
     * Atualiza todos os dados do dashboard
     */
    refresh() {
        this.load(true);
        if (typeof Sites !== 'undefined' && Sites.load) Sites.load(true);
    }
};

setInterval(() => {
    const dashboardPage = document.getElementById('page-dashboard');
    if (dashboardPage && !dashboardPage.classList.contains('hidden')) {
        Dashboard.load(true);
    }
}, 15000);
