// ===== ENQUIRY FUNCTIONS =====

window.openEnquiryForm = function() {
    var overlay = document.getElementById('enquiryOverlay');
    if (overlay) {
        overlay.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
};

window.closeEnquiryForm = function() {
    var overlay = document.getElementById('enquiryOverlay');
    if (overlay) {
        overlay.classList.remove('active');
        document.body.style.overflow = '';
    }
};

window.closeEnquiryOnOverlay = function(e) {
    if (e.target === document.getElementById('enquiryOverlay')) {
        window.closeEnquiryForm();
    }
};

window.submitEnquiry = async function(e) {
    e.preventDefault();
    const name      = document.getElementById('enq-name').value.trim();
    const email     = document.getElementById('enq-email').value.trim();
    const mobile    = document.getElementById('enq-mobile').value.trim();
    const service   = document.getElementById('enq-service').value.trim();
    const msgBox    = document.getElementById('enquiry-msg');
    const btnText   = document.getElementById('enq-btn-text');
    const btnLoader = document.getElementById('enq-btn-loader');
    const submitBtn = document.getElementById('enq-submit-btn');

    btnText.style.display   = 'none';
    btnLoader.style.display = 'inline';
    submitBtn.disabled      = true;

    const formData = new FormData();
    formData.append('name',    name);
    formData.append('email',   email);
    formData.append('mobile',  mobile);
    formData.append('service', service);

    try {
        const response = await fetch('send-enquiry.php', { method: 'POST', body: formData });
        const result   = await response.json();
        msgBox.style.display = 'block';
        if (result.status === 'success') {
            msgBox.className   = 'enquiry-msg success';
            msgBox.textContent = '✅ Thank you! Your enquiry has been sent. We will contact you shortly.';
            document.getElementById('enquiryForm').reset();
            setTimeout(function() {
                msgBox.style.display = 'none';
                window.closeEnquiryForm();
            }, 3000);
        } else {
            msgBox.className   = 'enquiry-msg error';
            msgBox.textContent = '❌ ' + result.message;
        }
    } catch (error) {
        msgBox.style.display = 'block';
        msgBox.className     = 'enquiry-msg error';
        msgBox.textContent   = '❌ Something went wrong. Please try again or call us directly.';
    } finally {
        btnText.style.display   = 'inline';
        btnLoader.style.display = 'none';
        submitBtn.disabled      = false;
    }
};

// ===== SEARCH FUNCTIONS =====

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 r = document.getElementById('resultsContainer');
            if (r) r.innerHTML = '';
        } else {
            searchOverlay.classList.add('active');
            if (searchInput) searchInput.focus();
        }
    }
};

window.performSearch = function() {
    const searchTerm       = document.getElementById('searchInput') ? 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;
    }
    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(function(page) {
        return page.title.toLowerCase().includes(searchTerm) ||
               page.keywords.some(function(k) { return k.includes(searchTerm); });
    });
    if (results.length === 0) {
        resultsContainer.innerHTML = '<div class="no-results">No results found for "' + searchTerm + '"</div>';
        return;
    }
    let html = '';
    results.forEach(function(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 on Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        window.closeEnquiryForm();
        window.toggleSearch();
    }
});

// ===== COMPONENTS LOADER =====

document.addEventListener('DOMContentLoaded', function() {
    loadComponents();
});

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

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

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

        initializeComponentScripts();

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

function initializeComponentScripts() {
    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');
        });
    }

    const searchOverlayEl = document.getElementById('searchOverlay');
    if (searchOverlayEl) {
        searchOverlayEl.addEventListener('click', function(e) {
            if (e.target === this) window.toggleSearch();
        });
    }
}