/**
 * SINAGEM — Sistema de Gestão de Mercados
 * app.js v3.0 — Compatível com Bootstrap 5
 */

(function() {
    'use strict';

    // =====================================================
    // SIDEBAR TOGGLE (Funciona com Bootstrap)
    // =====================================================
    function initSidebar() {
        const sidebar = document.getElementById('sidebar-wrapper');
        const toggleBtn = document.getElementById('sidebarToggle');

        if (!sidebar || !toggleBtn) {
            console.warn('Sidebar ou botão toggle não encontrados');
            return;
        }

        // Verificar se estamos no mobile (< 992px)
        function isMobile() {
            return window.innerWidth < 992;
        }

        // Verificar se o sidebar está collapsed
        function isCollapsed() {
            return sidebar.classList.contains('collapsed');
        }

        // Criar overlay se não existir
        let overlay = document.getElementById('sb-overlay');
        if (!overlay) {
            overlay = document.createElement('div');
            overlay.id = 'sb-overlay';
            overlay.className = 'sb-overlay';
            document.body.appendChild(overlay);
        }

        // Abrir sidebar (mobile)
        function openSidebar() {
            sidebar.classList.add('sb-open');
            overlay.classList.add('show');
            document.body.style.overflow = 'hidden';
        }

        // Fechar sidebar (mobile)
        function closeSidebar() {
            sidebar.classList.remove('sb-open');
            overlay.classList.remove('show');
            document.body.style.overflow = '';
        }

        // Colapsar sidebar (desktop)
        function collapseSidebar() {
            sidebar.classList.add('collapsed');
            const pageContent = document.getElementById('page-content-wrapper');
            if (pageContent) {
                pageContent.classList.remove('sidebar-expanded');
                pageContent.classList.add('sidebar-collapsed');
            }
            // Salvar estado no localStorage
            localStorage.setItem('sidebarCollapsed', 'true');
        }

        // Expandir sidebar (desktop)
        function expandSidebar() {
            sidebar.classList.remove('collapsed');
            const pageContent = document.getElementById('page-content-wrapper');
            if (pageContent) {
                pageContent.classList.remove('sidebar-collapsed');
                pageContent.classList.add('sidebar-expanded');
            }
            // Salvar estado no localStorage
            localStorage.setItem('sidebarCollapsed', 'false');
        }

        // Toggle sidebar baseado no dispositivo
        function toggleSidebar() {
            if (isMobile()) {
                // Mobile: abrir/fechar overlay
                if (sidebar.classList.contains('sb-open')) {
                    closeSidebar();
                } else {
                    openSidebar();
                }
            } else {
                // Desktop: colapsar/expandir
                if (isCollapsed()) {
                    expandSidebar();
                } else {
                    collapseSidebar();
                }
            }
        }

        // Evento do botão toggle
        if (toggleBtn) {
            toggleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                toggleSidebar();
            });
        }

        // Fechar ao clicar no overlay (mobile)
        if (overlay) {
            overlay.addEventListener('click', closeSidebar);
        }

        // Fechar com ESC (mobile)
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && sidebar.classList.contains('sb-open')) {
                closeSidebar();
            }
        });

        // Ao redimensionar, ajustar comportamento
        window.addEventListener('resize', function() {
            if (isMobile()) {
                // Mobile: fechar se estiver aberto
                if (sidebar.classList.contains('sb-open')) {
                    closeSidebar();
                }
                // Remover collapsed se estiver no mobile
                sidebar.classList.remove('collapsed');
                const pageContent = document.getElementById('page-content-wrapper');
                if (pageContent) {
                    pageContent.style.marginLeft = '';
                }
            } else {
                // Desktop: restaurar estado salvo
                const wasCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
                if (wasCollapsed && !isCollapsed()) {
                    collapseSidebar();
                } else if (!wasCollapsed && isCollapsed()) {
                    expandSidebar();
                }
            }
        });

        // Restaurar estado salvo ao carregar página
        if (!isMobile()) {
            const wasCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
            if (wasCollapsed) {
                collapseSidebar();
            }
        }

        // Botão de fechar mobile (se existir)
        const closeMobileBtn = document.getElementById('sidebarCloseMobile');
        if (closeMobileBtn) {
            closeMobileBtn.addEventListener('click', closeSidebar);
        }

        console.log('Sidebar inicializada com sucesso!');
    }

    // =====================================================
    // BOOTSTRAP COLLAPSE - Garantir que funciona
    // =====================================================
    function initBootstrapCollapse() {
        const collapseElements = document.querySelectorAll('.collapse');
        collapseElements.forEach(element => {
            if (!element.hasAttribute('data-bs-toggle')) {
                try {
                    new bootstrap.Collapse(element, {
                        toggle: false
                    });
                } catch(e) {
                    console.warn('Erro ao inicializar collapse:', e);
                }
            }
        });
    }

    // =====================================================
    // ACTIVE LINK DETECTION
    // =====================================================
    function initActiveLinks() {
        const currentPath = window.location.pathname;

        document.querySelectorAll('.sb-link, .sb-sub-link').forEach(link => {
            const href = link.getAttribute('href');
            if (href && href !== '#' && href !== '/') {
                if (currentPath === href ||
                    currentPath.startsWith(href + '/') ||
                    (href !== '/' && currentPath === href) ||
                    (link.classList.contains('sb-sub-link') && currentPath.includes(href))) {
                    link.classList.add('active');

                    const parentSubmenu = link.closest('.sb-submenu');
                    if (parentSubmenu) {
                        parentSubmenu.classList.add('show');
                        const triggerBtn = document.querySelector(`[data-bs-target="#${parentSubmenu.id}"]`);
                        if (triggerBtn) {
                            triggerBtn.setAttribute('aria-expanded', 'true');
                        }
                    }
                }
            }
        });
    }

    // =====================================================
    // FLASH ALERTS AUTO-DISMISS
    // =====================================================
    function initFlashAlerts() {
        const alerts = document.querySelectorAll('.sinagem-flash-alert');
        alerts.forEach(alert => {
            setTimeout(() => {
                alert.style.transition = 'opacity 0.3s ease';
                alert.style.opacity = '0';
                setTimeout(() => alert.remove(), 300);
            }, 5000);

            const closeBtn = alert.querySelector('.flash-close');
            if (closeBtn) {
                closeBtn.addEventListener('click', () => {
                    alert.style.opacity = '0';
                    setTimeout(() => alert.remove(), 300);
                });
            }
        });
    }

    // =====================================================
    // TABLE ROW CLICK
    // =====================================================
    function initTableRows() {
        document.querySelectorAll('.s-table tbody tr[data-href]').forEach(row => {
            row.style.cursor = 'pointer';
            row.addEventListener('click', (e) => {
                if (e.target.tagName !== 'A' && e.target.tagName !== 'BUTTON') {
                    window.location.href = row.dataset.href;
                }
            });
        });
    }

    // =====================================================
    // DELETE CONFIRMATION
    // =====================================================
    function initDeleteConfirm() {
        document.querySelectorAll('[data-confirm-delete]').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const message = btn.dataset.confirmMessage || 'Tem certeza que deseja eliminar este registo?';
                if (!confirm(message)) {
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                }
            });
        });
    }

    // =====================================================
    // TOOLTIPS
    // =====================================================
    function initTooltips() {
        if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip) {
            const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            tooltipTriggerList.map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
        }
    }

    // =====================================================
    // DROPDOWNS
    // =====================================================
    function initDropdowns() {
        if (typeof bootstrap !== 'undefined') {
            const dropdownElementList = [].slice.call(document.querySelectorAll('.dropdown-toggle'));
            dropdownElementList.map(dropdownToggleEl => new bootstrap.Dropdown(dropdownToggleEl));
        }
    }

    // =====================================================
    // CSRF TOKEN
    // =====================================================
    function initCsrf() {
        const token = document.querySelector('meta[name="csrf-token"]');
        window.csrfToken = token ? token.content : '';
    }

    // =====================================================
    // MODAL FIX - CORREÇÃO DO PROBLEMA DO MODAL
    // =====================================================
    function initModals() {
        // Inicializar todos os modais
        const modalElements = document.querySelectorAll('.modal');
        modalElements.forEach(modal => {
            // Remover instâncias duplicadas se existirem
            if (bootstrap.Modal.getInstance(modal)) {
                bootstrap.Modal.getInstance(modal).dispose();
            }
            // Criar nova instância
            new bootstrap.Modal(modal, {
                backdrop: true,
                keyboard: true,
                focus: true
            });
        });

        // Limpar backdrops duplicados ao fechar qualquer modal
        document.addEventListener('hidden.bs.modal', function() {
            const backdrops = document.querySelectorAll('.modal-backdrop');
            backdrops.forEach(backdrop => backdrop.remove());
            document.body.classList.remove('modal-open');
            document.body.style.overflow = '';
            document.body.style.paddingRight = '';
        });
    }

    // =====================================================
    // INITIALIZE ALL
    // =====================================================
    function init() {
        console.log('SINAGEM: Inicializando sistema...');

        if (typeof bootstrap === 'undefined') {
            console.error('Bootstrap não está carregado!');
            return;
        }

        initSidebar();
        initBootstrapCollapse();
        initActiveLinks();
        initFlashAlerts();
        initTableRows();
        initDeleteConfirm();
        initTooltips();
        initDropdowns();
        initCsrf();
        initModals(); // <-- Adicionado para corrigir modais

        console.log('SINAGEM: Sistema inicializado com sucesso!');
    }

    // Aguardar DOM pronto
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

    // Exportar API global
    window.SINAGEM = {
        refreshAlerts: initFlashAlerts,
        closeSidebar: () => {
            const sidebar = document.getElementById('sidebar-wrapper');
            const overlay = document.getElementById('sb-overlay');
            if (sidebar) sidebar.classList.remove('sb-open');
            if (overlay) overlay.classList.remove('show');
            document.body.style.overflow = '';
        },
        openSidebar: () => {
            const sidebar = document.getElementById('sidebar-wrapper');
            const overlay = document.getElementById('sb-overlay');
            if (sidebar) sidebar.classList.add('sb-open');
            if (overlay) overlay.classList.add('show');
            document.body.style.overflow = 'hidden';
        },
        toast: (message, type = 'success') => {
            console.log(`Toast [${type}]:`, message);
        }
    };

})();
// Previne conflito de scroll quando modal abre
document.addEventListener('show.bs.modal', function () {
  document.querySelector('.sb-overlay')?.classList.remove('show');
});
