
document.addEventListener('DOMContentLoaded', function () {
    const searchInput = document.getElementById('global-search-input');
    const searchType = document.getElementById('global-search-type');
    const searchResults = document.getElementById('global-search-results');
    const searchResultsContent = document.getElementById('search-results-content');
    const searchLoading = document.getElementById('search-loading');
    let debounceTimer;

    if (searchInput) {
        searchInput.addEventListener('input', function () {
            clearTimeout(debounceTimer);
            const query = this.value.trim();
            const type = searchType.value;

            if (query.length < 2) {
                searchResults.classList.add('d-none');
                return;
            }

            searchResults.classList.remove('d-none');
            searchLoading.classList.remove('d-none');
            searchResultsContent.innerHTML = '';

            debounceTimer = setTimeout(() => {
                fetch(`${window.APP_URL}/global-search?query=${encodeURIComponent(query)}&type=${type}`)
                    .then(response => response.json())
                    .then(data => {
                        searchLoading.classList.add('d-none');
                        displayResults(data);
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        searchLoading.classList.add('d-none');
                        searchResultsContent.innerHTML = '<div class="p-3 text-center text-danger">Error fetching results</div>';
                    });
            }, 500);
        });

        // Search Type Change
        searchType.addEventListener('change', function () {
            if (searchInput.value.trim().length >= 2) {
                searchInput.dispatchEvent(new Event('input'));
            }
        });

        // Close on Click Outside
        document.addEventListener('click', function (e) {
            if (!searchInput.contains(e.target) && !searchResults.contains(e.target) && !searchType.contains(e.target)) {
                searchResults.classList.add('d-none');
            }
        });
    }

    function displayResults(results) {
        if (results.length === 0) {
            searchResultsContent.innerHTML = '<div class="p-3 text-center text-muted">No results found</div>';
            return;
        }

        let html = '';
        results.forEach(item => {
            html += `
                <a href="${item.url}" class="search-result-item">
                    <div class="search-icon bg-${item.color}-soft text-${item.color}">
                        <i class="${item.icon}"></i>
                    </div>
                    <div class="search-info">
                        <div class="search-title">${item.title}</div>
                        <div class="search-subtitle">${item.subtitle}</div>
                    </div>
                    <i class="fas fa-chevron-right text-muted small ms-2"></i>
                </a>
            `;
        });

        searchResultsContent.innerHTML = html;
    }

    // Mobile Toggle
    const mobileToggle = document.getElementById('mobile-search-toggle');
    const searchContainer = document.querySelector('.search-container');

    if (mobileToggle) {
        mobileToggle.addEventListener('click', function () {
            searchContainer.classList.toggle('d-none');
            searchContainer.classList.toggle('d-block');
            searchContainer.classList.toggle('w-100');
            searchContainer.classList.toggle('position-absolute');
            searchContainer.style.top = '100%';
            searchContainer.style.left = '0';
            searchContainer.style.background = 'var(--card-bg)';
            searchContainer.style.padding = '10px';
            searchContainer.style.zIndex = '1060';

            if (!searchContainer.classList.contains('d-none')) {
                searchInput.focus();
            }
        });
    }
});
