/**
 * App Module
 * Módulo principal que coordena a aplicação
 */

const App = {
    // Site atualmente selecionado (filtro global)
    currentSiteId: null,

    /**
     * Inicializa a aplicação
     */
    async init() {
        this.setupEventListeners();
    },

    /**
     * Configura event listeners globais
     */
    setupEventListeners() {
        // Navegação da sidebar
        const menuLinks = document.querySelectorAll('.menu-link[data-page]');

        menuLinks.forEach(link => {
            link.addEventListener('click', (e) => {
                this.handleNavigation(e, link);
            });
        });
        
        // Seletor de site global
        const siteSelector = document.getElementById('site-selector');
        if (siteSelector) {
            siteSelector.addEventListener('change', (e) => {
                this.currentSiteId = e.target.value || null;
                
                const siteName = this.currentSiteId 
                    ? Sites.getById(this.currentSiteId)?.name 
                    : 'Visão geral';
                    
                const currentSiteEl = document.getElementById('current-site');
                if (currentSiteEl) currentSiteEl.textContent = siteName;
                Dashboard.load();
            });
        }
        
        // Form de API Token
        const apiTokenForm = document.getElementById('api-token-form');
        if (apiTokenForm) {
            apiTokenForm.addEventListener('submit', (e) => this.handleApiTokenSubmit(e));
        }
        
        // Atualizar seletores de API quando modal de novo site for aberto
        const modalNewSite = document.getElementById('modal-new-site');
        if (modalNewSite) {
            modalNewSite.addEventListener('show.bs.modal', () => {
                if (typeof ApiTokens !== 'undefined') {
                    ApiTokens.updateSelectors();
                }
            });
        }
    },
    
    /**
     * Handler de navegação
     */
    handleNavigation(e, link) {
        e.preventDefault();
        const page = link.dataset.page;
        console.log('[App] Navegando para:', page);

        // Atualizar estado ativo (Corrigido para .menu-link)
        document.querySelectorAll('.menu-link').forEach(a => a.classList.remove('active'));
        link.classList.add('active');

        // Mostrar página
        const pageElement = document.getElementById(`page-${page}`);

        // Esconder todas as páginas
        document.querySelectorAll('.page-content').forEach(p => p.classList.add('hidden'));
        
        // Mostrar a página alvo
        if (pageElement) {
            pageElement.classList.remove('hidden');
        } else {
            console.error('[App] Página não encontrada:', `page-${page}`);
        }

        // Atualizar título (se o elemento existir)
        const titleEl = document.getElementById('page-title');
        if (titleEl) {
            titleEl.innerHTML = link.innerHTML;
        }

        // Carregar dados da página
        this.loadPageData(page);
    },
    
    /**
     * Carrega dados de acordo com a página
     */
    loadPageData(page) {
        const currentUser = Auth.getCurrentUser();
        
        switch(page) {
            case 'dashboard':
                Dashboard.load(true);
                break;
                
            case 'sites':
                Sites.load();
                break;
                
            case 'events':
                Events.loadTypes();
                Events.load(1);
                break;
                
            case 'pix':
                PIX.updateSiteSelector();
                if (currentUser && currentUser.site_id && !currentUser.is_super_admin) {
                    PIX.loadConfig(currentUser.site_id);
                }
                break;
                
            case 'pix-history':
                PIX.loadHistory();
                break;
                
            case 'notif-config':
                loadNotifConfig();
                break;

            case 'ip-control':
                if (typeof Sites !== 'undefined') Sites.load();
                loadIpRules();
                break;
                
            case 'api-token':
                this.loadApiToken();
                break;
            
            case 'api-tokens':
                ApiTokens.load();
                break;
                
            case 'users':
                Users.populateSiteSelectors();
                Users.load();
                break;

            case 'security':
                if (typeof Security !== 'undefined') {
                    // Se usuário tem site específico, carregar config
                    if (currentUser && currentUser.site_id && !currentUser.is_super_admin) {
                        Security.loadConfig(currentUser.site_id);
                    }
                }
                break;
        }
    },
    
    /**
     * Carrega token da API (Detran)
     */
    async loadApiToken() {
        try {
            const data = await Api.get('api-token');

            if (data.status === 'success' && data.data) {
                document.getElementById('api-token-value').value = data.data.token || '';
                document.getElementById('api-token-updated').textContent = data.data.updated_at
                    ? `${new Date(data.data.updated_at).toLocaleString('pt-BR')} por ${data.data.updated_by || 'Sistema'}`
                    : 'Nunca configurado';
            } else {
                document.getElementById('api-token-value').value = '';
                document.getElementById('api-token-updated').textContent = 'Nunca configurado';
            }
        } catch (error) {
            // Silenciar em produção
        }
    },
    
    /**
     * Toggle de visibilidade do token
     */
    toggleTokenVisibility() {
        const input = document.getElementById('api-token-value');
        const icon = document.getElementById('token-eye-icon');
        
        if (input.type === 'password') {
            input.type = 'text';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        } else {
            input.type = 'password';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        }
    },
    
    /**
     * Handler de submit do form de API Token
     */
    async handleApiTokenSubmit(e) {
        e.preventDefault();
        
        const token = document.getElementById('api-token-value').value.trim();
        
        if (!token) {
            alert('Por favor, insira um token válido');
            return;
        }
        
        try {
            const data = await Api.post('api-token', { token });
            
            if (data.status === 'success') {
                const status = document.getElementById('api-token-save-status');
                status.classList.remove('hidden');
                setTimeout(() => status.classList.add('hidden'), 3000);
                this.loadApiToken();
            } else {
                alert('Erro ao salvar token: ' + (data.message || 'Erro desconhecido'));
            }
        } catch (error) {
            console.error('Save token error:', error);
            alert('Erro ao salvar token');
        }
    },
    
    /**
     * Copia texto para clipboard
     */
    copyToClipboard(elementId) {
        const input = document.getElementById(elementId);
        input.select();
        document.execCommand('copy');
        alert('Copiado!');
    },
    
    /**
     * Atualiza todos os dados
     */
    refreshData() {
        Dashboard.load();
        Sites.load();
    }
};

// Funções globais para compatibilidade com HTML inline
// Estas funções delegam para os módulos apropriados

// Sites
function createSite() { Sites.create(); }
function openSiteDetails(id) { Sites.openDetails(id); }
function saveSiteDetails() { Sites.saveDetails(); }
function saveSitePixConfig() { Sites.savePixConfig(); }
function confirmDeleteSite() { Sites.confirmDelete(); }
function deleteSite(id) { Sites.delete(id); }
function quickDeleteSite(id, name) { Sites.quickDelete(id, name); }
function clearSiteEvents(siteId, siteName, eventCount) { Sites.clearEvents(siteId, siteName, eventCount); }
function testSiteConnection() { Sites.testConnection(); }

// Users
function createUser() { Users.create(); }
function editUser(userId) { Users.edit(userId); }
function updateUser() { Users.update(); }
function deleteUser() { Users.delete(); }
function toggleSiteSelector() { Users.toggleSiteSelector(); }
function toggleEditSiteSelector() { Users.toggleEditSiteSelector(); }
function generatePassword(inputId) {
    const password = Helpers.generatePassword(12);
    const input = document.getElementById(inputId);
    if (input) {
        input.value = password;
        input.type = 'text';
        setTimeout(() => { input.type = 'password'; }, 3000);
    }
}
function populateUserSiteSelectors() { Users.populateSiteSelectors(); }
function loadUsers() { Users.load(); }
function filterUsersBySite() { Users.load(); }

// PIX
function generateTestPixQrCode() { PIX.generateTestQrCode(); }
function copyPixCode() { PIX.copyCode(); }
function generateModalTestPixQrCode() { PIX.generateModalTestQrCode(); }
function copyModalPixCode() { PIX.copyModalCode(); }
function loadPixHistory() { PIX.loadHistory(); }

// Events
function loadEvents(page) { Events.load(page); }
function clearEventFilters() { Events.clearFilters(); }
function loadEventTypes() { Events.loadTypes(); }

// Dashboard
function refreshData() { App.refreshData(); }

// Auth
function login() { Auth.login(); }
function logout() { Auth.logout(); }

// App
function toggleTokenVisibility() { App.toggleTokenVisibility(); }
function copyToClipboard(elementId) { App.copyToClipboard(elementId); }

// Security
function loadSecurityConfig(siteId) { Security.loadConfig(siteId); }
function saveSecurityConfig(siteId) { Security.saveConfig(siteId); }
function showAddIpModal() { Security.showAddIpModal(); }
function addIpRule() { Security.addIpRule(); }
function removeIpRule(ruleId) { Security.removeIpRule(ruleId); }
function loadSecurityLogs(siteId) { Security.loadLogs(siteId); }
function filterSecurityLogs() { Security.filterLogs(); }
function clearSecurityLogs() { Security.clearLogs(); }
function toggleSecurityTokenVisibility() { Security.toggleTokenVisibility(); }

// API Tokens
function openNewApiToken() { ApiTokens.openNew(); }
function openEditApiToken(id) { ApiTokens.openEdit(id); }
function saveApiToken() { ApiTokens.save(); }
function testApiToken(id) { ApiTokens.test(id); }
function deleteApiToken(id, name) { ApiTokens.delete(id, name); }
function loadApiTokens() { ApiTokens.load(); }

// Notificações Externas
async function loadNotifConfig() {
    UI.showLoading('Carregando configurações...');
    try {
        const res = await Api.get('get-notif-config');
        if (res.status === 'success') {
            const wa = res.data.whatsapp || {};
            const tg = res.data.telegram || {};

            // WhatsApp
            document.getElementById('wa-instance-id').value = wa.instance_id || '';
            document.getElementById('wa-admin-number').value = wa.admin_number || '';
            document.getElementById('wa-active').checked = wa.active === true;

            // Telegram
            document.getElementById('tg-bot-token').value = tg.bot_token || '';
            document.getElementById('tg-chat-id').value = tg.chat_id || '';
            document.getElementById('tg-active').checked = tg.active === true;
        }
    } catch (e) {
        console.error('Erro ao carregar configs:', e);
    } finally {
        UI.hideLoading();
    }
}

async function saveNotifConfig(type) {
    const config = {};
    if (type === 'whatsapp') {
        config.instance_id = document.getElementById('wa-instance-id').value;
        config.admin_number = document.getElementById('wa-admin-number').value;
        config.active = document.getElementById('wa-active').checked;
    } else {
        config.bot_token = document.getElementById('tg-bot-token').value;
        config.chat_id = document.getElementById('tg-chat-id').value;
        config.active = document.getElementById('tg-active').checked;
    }

    UI.showLoading('Salvando...');
    try {
        const res = await Api.post('save-notif-config', { type, config });
        if (res.status === 'success') {
            Swal.fire('Salvo!', 'Configuração atualizada com sucesso.', 'success');
        } else {
            Swal.fire('Erro', res.message || 'Falha ao salvar.', 'error');
        }
    } catch (e) {
        Swal.fire('Erro', 'Falha na comunicação.', 'error');
    } finally {
        UI.hideLoading();
    }
}

// Inicializar app quando DOM estiver pronto
document.addEventListener('DOMContentLoaded', () => {
    // Inicializar autenticação primeiro
    if (typeof Auth !== 'undefined' && Auth.init) {
        Auth.init();
    } else {
        // Fallback: registrar evento de login diretamente
        document.getElementById('login-form')?.addEventListener('submit', (e) => {
            e.preventDefault();
            const username = document.getElementById('login-username')?.value;
            const password = document.getElementById('login-password')?.value;
            Auth.login(username, password);
        });
    }
});

/**
 * Controle de IPs
 */
async function loadIpRules() {
    const list = document.getElementById('ip-rules-list');
    if (!list) return;
    
    // Popular seletor de sites no form
    const siteSelect = document.getElementById('ip-rule-site-id');
    if (siteSelect && typeof Sites !== 'undefined') {
        const sites = Sites.getData();
        siteSelect.innerHTML = '<option value="">GLOBAL (Todos)</option>';
        sites.forEach(s => {
            siteSelect.innerHTML += `<option value="${s.id}">${s.name}</option>`;
        });
    }

    list.innerHTML = '<tr><td colspan="6" class="text-center p-4"><i class="fas fa-spinner fa-spin"></i> Carregando...</td></tr>';
    
    try {
        const res = await Api.get('get-ip-rules');
        if (res.status === 'success') {
            if (res.data.length === 0) {
                list.innerHTML = '<tr><td colspan="6" class="text-center p-4 text-muted">Nenhuma regra encontrada.</td></tr>';
                return;
            }
            
            list.innerHTML = res.data.map(rule => `
                <tr>
                    <td class="font-mono">${rule.ip_address}</td>
                    <td>
                        <span class="badge ${rule.rule_type === 'blacklist' ? 'bg-danger' : 'bg-success'}">
                            ${rule.rule_type.toUpperCase()}
                        </span>
                    </td>
                    <td class="small">${rule.site_name || '<span class="text-primary fw-bold">GLOBAL</span>'}</td>
                    <td class="text-muted small">${rule.reason || '-'}</td>
                    <td class="small">${new Date(rule.created_at).toLocaleString('pt-BR')}</td>
                    <td class="text-end">
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteIpRule(${rule.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `).join('');
        }
    } catch (e) {
        console.error('Erro ao carregar regras de IP:', e);
    }
}

async function addIpRule() {
    const ip = document.getElementById('ip-rule-address').value.trim();
    const siteId = document.getElementById('ip-rule-site-id').value;
    const type = document.getElementById('ip-rule-type').value;
    const reason = document.getElementById('ip-rule-reason').value.trim();

    if (!ip) {
        Swal.fire('Erro', 'Informe um endereço IP válido.', 'error');
        return;
    }

    UI.showLoading('Adicionando...');
    try {
        const res = await Api.post('add-ip-rule', { 
            ip_address: ip, 
            site_id: siteId,
            rule_type: type, 
            reason 
        });
        if (res.status === 'success') {
            Swal.fire('Sucesso!', 'Regra adicionada.', 'success');
            document.getElementById('form-add-ip-rule').reset();
            loadIpRules();
        } else {
            Swal.fire('Erro', res.message || 'Falha ao adicionar.', 'error');
        }
    } catch (e) {
        Swal.fire('Erro', 'Falha na comunicação.', 'error');
    } finally {
        UI.hideLoading();
    }
}

async function deleteIpRule(id) {
    const result = await Swal.fire({
        title: 'Tem certeza?',
        text: "Esta regra será removida permanentemente!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Sim, excluir!',
        cancelButtonText: 'Cancelar'
    });

    if (result.isConfirmed) {
        UI.showLoading('Excluindo...');
        try {
            const res = await Api.post('delete-ip-rule', { id });
            if (res.status === 'success') {
                Swal.fire('Removido!', 'A regra foi excluída.', 'success');
                loadIpRules();
            } else {
                Swal.fire('Erro', res.message || 'Falha ao excluir.', 'error');
            }
        } catch (e) {
            Swal.fire('Erro', 'Falha na comunicação.', 'error');
        } finally {
            UI.hideLoading();
        }
    }
}

App.init();
