/* Bootstrap 5 Native Implementation for WHP */
/* This replaces all Bootstrap 3 compatibility hacks with proper Bootstrap 5 components */

(function() {
    'use strict';
    
    // Wait for DOM to be ready
    document.addEventListener('DOMContentLoaded', function() {
        
        // Initialize all Bootstrap 5 components
        initializeBootstrap5Components();
        
        // Handle splash screen removal
        hideSplashScreen();
        
        // Initialize any custom functionality
        initializeCustomFeatures();
        
    });
    
    // Initialize Bootstrap 5 components
    function initializeBootstrap5Components() {
        
        // Initialize Tooltips
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
        
        // Initialize Popovers
        var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
        var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
            return new bootstrap.Popover(popoverTriggerEl);
        });
        
        // Initialize Dropdowns (should work automatically, but ensure they're working)
        var dropdownElementList = [].slice.call(document.querySelectorAll('[data-bs-toggle="dropdown"]'));
        var dropdownList = dropdownElementList.map(function (dropdownToggleEl) {
            return new bootstrap.Dropdown(dropdownToggleEl);
        });
        
        // Initialize Modals (should work automatically)
        var modalElementList = [].slice.call(document.querySelectorAll('.modal'));
        var modalList = modalElementList.map(function (modalEl) {
            return new bootstrap.Modal(modalEl);
        });
        
        // Initialize Offcanvas (Sidebar)
        var offcanvasElementList = [].slice.call(document.querySelectorAll('[data-bs-toggle="offcanvas"]'));
        var offcanvasList = offcanvasElementList.map(function (offcanvasEl) {
            return new bootstrap.Offcanvas(document.querySelector(offcanvasEl.getAttribute('data-bs-target') || offcanvasEl.getAttribute('href')));
        });
        
        console.log('Bootstrap 5 components initialized:', {
            tooltips: tooltipList.length,
            popovers: popoverList.length,
            dropdowns: dropdownList.length,
            modals: modalList.length,
            offcanvas: offcanvasList.length
        });
    }
    
    // Handle splash screen removal
    function hideSplashScreen() {
        var splash = document.querySelector('.splash');
        
        function removeSplash() {
            console.log('Removing splash screen...'); // Debug log
            if (splash) {
                splash.style.opacity = '0';
                splash.style.transition = 'opacity 0.3s ease-out';
                setTimeout(function() {
                    splash.style.display = 'none';
                    splash.remove();
                    console.log('Splash screen removed successfully'); // Debug log
                }, 300);
            } else {
                console.log('Splash screen element not found'); // Debug log
            }
        }
        
        // Multiple methods to ensure splash screen is removed
        
        // Method 1: Remove immediately if DOM is ready and content exists
        if (document.readyState === 'complete' || document.readyState === 'interactive') {
            var mainContent = document.querySelector('#wrapper');
            if (mainContent) {
                console.log('Page ready, removing splash screen immediately');
                setTimeout(removeSplash, 100);
                return;
            }
        }
        
        // Method 2: Remove when window load event fires
        window.addEventListener('load', function() {
            console.log('Window load event fired');
            removeSplash();
        });
        
        // Method 3: Remove after DOM content loaded with a short delay
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', function() {
                console.log('DOM content loaded');
                setTimeout(removeSplash, 500);
            });
        } else {
            // DOM already loaded
            setTimeout(removeSplash, 500);
        }
        
        // Method 4: Emergency fallback - remove after 3 seconds regardless
        setTimeout(function() {
            console.log('Emergency fallback: forcing splash screen removal');
            removeSplash();
        }, 3000);
        
        // Method 5: Check for page content and remove when found
        var contentCheckInterval = setInterval(function() {
            var pageContent = document.querySelector('#wrapper .content-wrapper');
            if (pageContent && pageContent.children.length > 0) {
                console.log('Page content detected, removing splash screen');
                clearInterval(contentCheckInterval);
                removeSplash();
            }
        }, 100);
        
        // Clear the interval after 5 seconds to prevent infinite checking
        setTimeout(function() {
            clearInterval(contentCheckInterval);
        }, 5000);
    }
    
    // Initialize any custom features
    function initializeCustomFeatures() {
        
        // Handle active navigation state
        setActiveNavigationItem();
        
        // Set minimum height for wrapper
        setWrapperHeight();
        
        // Handle window resize
        window.addEventListener('resize', function() {
            setWrapperHeight();
        });
        
    }
    
    // Set active navigation item based on current page.
    // The server-side PHP already adds .active to the correct row; this client
    // pass exists as a fallback if a page is reached without that markup. Match
    // the ?page= value EXACTLY — substring matching here previously highlighted
    // every page whose key started with the current page (e.g. on page=ai-monitor
    // it also lit up page=ai-monitor-customer and page=ai-monitor-ignore-rules).
    function setActiveNavigationItem() {
        var currentPage = new URLSearchParams(window.location.search).get('page') || 'dashboard';
        var navItems = document.querySelectorAll('#sidebarMenu .list-group-item');

        navItems.forEach(function(item) {
            var href = item.getAttribute('href');
            if (!href) return;
            try {
                var url = new URL(href, window.location.origin);
                var hrefPage = url.searchParams.get('page');
                if (hrefPage === currentPage) {
                    item.classList.add('active');
                }
            } catch (_e) { /* non-URL hrefs (anchors, etc.) skip silently */ }
        });
    }
    
    // Set wrapper minimum height
    function setWrapperHeight() {
        var wrapper = document.getElementById('wrapper');
        if (wrapper) {
            var height = window.innerHeight;
            wrapper.style.minHeight = height + 'px';
        }
    }
    
    // Export functions for external use if needed
    window.WHPBootstrap5 = {
        initializeComponents: initializeBootstrap5Components,
        hideSplashScreen: hideSplashScreen,
        setActiveNavigation: setActiveNavigationItem
    };
    
})(); 