(function ($, w, d) {
    // ensure global
    w.clientexec = w.clientexec || {};
    w.clientexec.globalSearch = {};

    let results, searchInput, clearButton;
    let searchTimeout = null;
    let currentQuery = '';

    // Initialize after DOM is ready
    $(function () {
        results = d.getElementById("search-results");
        searchInput = d.getElementById("searchInput");
        clearButton = d.querySelector('#clear-search');

        if (!searchInput || !results) return;

        // attach input listener
        $('#searchInput').on('input', function (e) {
            w.clientexec.globalSearch.search($(this).val());
        });

        $('#clear-search').on('click', function(e) {
            w.clientexec.globalSearch.clearSearch();
        });
    });

    // define search method
    w.clientexec.globalSearch.search = function (value) {
        clearTimeout(searchTimeout);
        currentQuery = value.trim();

        if (!results) return;

        if (currentQuery === "") {
            results.classList.add("hideResults");
            if (clearButton) clearButton.style.display = 'none';
            results.innerHTML = '';
            return;
        }

        if (clearButton) clearButton.style.display = 'block';

        searchTimeout = setTimeout(() => {
            $.ajax({
                url: 'index.php?fuse=admin&action=getsearchresults',
                data: { query: currentQuery, limit: -1 },
                dataType: 'json',
                success: function (response) {
                    if (!response || !response.success || !response.matches || response.matches.length === 0) {
                        results.innerHTML = `<div class="result-heading"><h6>No results found</h6></div>`;
                        results.classList.remove("hideResults");
                        return;
                    }

                    const matches = response.matches;
                    const grouped = {};
                    matches.forEach(m => {
                        if (!grouped[m.type]) grouped[m.type] = [];
                        grouped[m.type].push(m);
                    });

                    let html = `
                        <div class="result-heading">
                            <h6>${response.total} Result${response.total !== 1 ? 's' : ''} found</h6>
                        </div>
                        <div class="result-body">
                            <div class="accordion" id="accordionResults">
                    `;

                    let index = 0;
                    for (const [type, items] of Object.entries(grouped)) {
                        const collapseId = 'collapse_' + index++;
                        html += `
                            <div class="list-card">
                                <h4 data-bs-toggle="collapse" data-bs-target="#${collapseId}" aria-expanded="true">
                                    ${type} (${items.length})
                                </h4>
                                <div id="${collapseId}" class="collapse ms-collapse" data-bs-parent="#accordionResults">
                                    <div class="list-body">
                        `;
                        items.forEach(item => {
                            const statusClass = item.status
                                ? item.status.toLowerCase().replace(/\s+/g, '-')
                                : '';
                            const avatarHTML = item.avatar && item.avatar.trim() !== ''
                                ? `<img class="list-icon" src="${item.avatar}" alt="">`
                                : `<div class="list-icon" style="width:32px;height:32px;flex-shrink:0;"></div>`;
                            html += `
                                <div class="list-body-item" title="${item.tooltip || ''}">
                                    ${avatarHTML}
                                    <div class="list-details">
                                        <h6><a href="${item.url}">${item.name}</a></h6>
                                        ${item.extra ? `<p>${item.extra}</p>` : ''}
                                        ${item.status ? `<span class="status-label ${statusClass}">${item.status}</span>` : ''}
                                    </div>
                                </div>
                            `;
                        });
                        html += `
                                    </div>
                                </div>
                            </div>
                        `;
                    }

                    html += `
                            </div>
                        </div>
                        <div class="result-footer d-flex justify-content-between align-items-center">
                            <div>
                                <button class="action-collapse" id="expandAll">Expand All</button>
                                <button class="action-collapse" id="collapesAll" style="display:none;">Collapse All</button>
                            </div>
                        </div>
                    `;

                    results.innerHTML = html;
                    results.classList.remove("hideResults");
                    w.clientexec.globalSearch.bindCollapseButtons ();
                },
                error: function () {
                    results.innerHTML = `<div class="result-heading"><h6>Error fetching results</h6></div>`;
                    results.classList.remove("hideResults");
                }
            });
        }, 300);
    };

    w.clientexec.globalSearch.bindCollapseButtons = function() {
        $('#expandAll').off('click').on('click', function () {
            $('.collapse').each(function () {
                $(this).collapse('show');
            });
            $(this).hide();
            $('#collapesAll').show();
        });

        $('#collapesAll').off('click').on('click', function () {
            $('.collapse').each(function () {
                $(this).collapse('hide');
            });
            $(this).hide();
            $('#expandAll').show();
        });
    }

    w.clientexec.globalSearch.clearSearch = function(event) {
        if (event) event.preventDefault();
        if (searchInput) searchInput.value = '';
        if (results) results.classList.add("hideResults");
        if (clearButton) clearButton.style.display = 'none';
        if (results) results.innerHTML = '';
    }

})(jQuery, window, document);
