// Components Loader - Loads header, footer, and WhatsApp button
document.addEventListener('DOMContentLoaded', function() {
    loadComponents();
});

async function loadComponents() {
    try {
        // Load Header
        const headerPlaceholder = document.getElementById('header-placeholder');
        if (headerPlaceholder) {
            const headerResponse = await fetch('header.html');
            const headerHTML = await headerResponse.text();
            headerPlaceholder.innerHTML = headerHTML;
        }

        // Load Footer
        const footerPlaceholder = document.getElementById('footer-placeholder');
        if (footerPlaceholder) {
            const footerResponse = await fetch('footer.html');
            const footerHTML = await footerResponse.text();
            footerPlaceholder.innerHTML = footerHTML;
        }

        // Load WhatsApp Button
        const whatsappPlaceholder = document.getElementById('whatsapp-placeholder');
        if (whatsappPlaceholder) {
            const whatsappResponse = await fetch('whatsapp-button.html');
            const whatsappHTML = await whatsappResponse.text();
            whatsappPlaceholder.innerHTML = whatsappHTML;
        }

        // Re-initialize any scripts that might be needed after loading components
        initializeComponentScripts();

    } catch (error) {
        console.error('Error loading components:', error);
    }
}

function initializeComponentScripts() {
    // Re-initialize mobile menu functionality
    const mobileMenuToggle = document.querySelector('.mobile-menu-toggle');
    const mobileNav = document.querySelector('.mobile-nav');
    const mobileNavClose = document.querySelector('.mobile-nav-close');
    const mobileNavOverlay = document.querySelector('.mobile-nav-overlay');

    if (mobileMenuToggle && mobileNav) {
        mobileMenuToggle.addEventListener('click', function() {
            mobileNav.classList.add('active');
            mobileNavOverlay.classList.add('active');
        });
    }

    if (mobileNavClose && mobileNav) {
        mobileNavClose.addEventListener('click', function() {
            mobileNav.classList.remove('active');
            mobileNavOverlay.classList.remove('active');
        });
    }

    if (mobileNavOverlay && mobileNav) {
        mobileNavOverlay.addEventListener('click', function() {
            mobileNav.classList.remove('active');
            mobileNavOverlay.classList.remove('active');
        });
    }

    // Make toggleSearch function globally available
    if (typeof toggleSearch === 'undefined') {
        window.toggleSearch = function() {
            const searchOverlay = document.getElementById('searchOverlay');
            const searchInput = document.getElementById('searchInput');
            
            if (searchOverlay) {
                if (searchOverlay.classList.contains('active')) {
                    searchOverlay.classList.remove('active');
                    if (searchInput) searchInput.value = '';
                    const resultsContainer = document.getElementById('resultsContainer');
                    if (resultsContainer) resultsContainer.innerHTML = '';
                } else {
                    searchOverlay.classList.add('active');
                    if (searchInput) searchInput.focus();
                }
            }
        };
    }

    // Make performSearch function globally available
    if (typeof performSearch === 'undefined') {
        window.performSearch = function() {
            const searchTerm = document.getElementById('searchInput')?.value.toLowerCase().trim() || '';
            const resultsContainer = document.getElementById('resultsContainer');
            
            if (!resultsContainer) return;
            
            if (searchTerm.length < 1) {
                resultsContainer.innerHTML = '<div class="no-results">Type at least 1 character to search</div>';
                return;
            }
            
            // Simple search implementation - you can enhance this
            const pages = [
                { title: "Home", page: "index.html", keywords: ["home", "loan", "business", "financial"] },
                { title: "About Us", page: "about.html", keywords: ["about", "corporate", "advisory"] },
                { title: "Services", page: "service.html", keywords: ["service", "financial", "advisory"] },
                { title: "Teams", page: "teams.html", keywords: ["team", "professional", "financial"] },
                { title: "Contact Us", page: "contact.html", keywords: ["contact", "email", "phone"] }
            ];
            
            const results = pages.filter(page => 
                page.title.toLowerCase().includes(searchTerm) ||
                page.keywords.some(keyword => keyword.includes(searchTerm))
            );
            
            if (results.length === 0) {
                resultsContainer.innerHTML = '<div class="no-results">No results found for "' + searchTerm + '"</div>';
                return;
            }
            
            let html = '';
            results.forEach(result => {
                html += `
                    <div class="search-result-item" onclick="window.location.href='${result.page}'">
                        <div class="search-result-title">${result.title}</div>
                        <div class="search-result-page">${result.page}</div>
                    </div>
                `;
            });
            
            resultsContainer.innerHTML = html;
        };
    }

    // Close search on Escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const searchOverlay = document.getElementById('searchOverlay');
            if (searchOverlay && searchOverlay.classList.contains('active')) {
                if (typeof toggleSearch !== 'undefined') {
                    toggleSearch();
                }
            }
        }
    });

    // Close search on overlay click
    const searchOverlayEl = document.getElementById('searchOverlay');
    if (searchOverlayEl) {
        searchOverlayEl.addEventListener('click', function(e) {
            if (e.target === this) {
                if (typeof toggleSearch !== 'undefined') {
                    toggleSearch();
                }
            }
        });
    }
}
