/**
 * CRS.HybridSearch - Async KI result merge for InstantSearch.
 * Loads KI (vector search) results after Lucene results are displayed,
 * then inserts KI-only products at the TOP of the existing product lists.
 */
(function () {
    var dataEl = document.getElementById('hs-ki-merge-data');
    if (!dataEl) return;

    var term = dataEl.getAttribute('data-term');
    var exclude = dataEl.getAttribute('data-exclude');
    var url = dataEl.getAttribute('data-url');
    // Absolute cap from SearchSettings.InstantSearchNumberOfProducts — how many KI
    // tiles may be added on top of Lucene's already-displayed results. Without this
    // the user saw N (Lucene) + M (KI) > setting.
    var maxAdd = parseInt(dataEl.getAttribute('data-maxadd') || '0', 10);

    if (!term || term.length < 3) return;
    if (!isFinite(maxAdd) || maxAdd <= 0) return;

    var excludeSet = new Set((exclude || '').split(',').map(Number).filter(Boolean));

    var xhr = new XMLHttpRequest();
    xhr.open('POST', url);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function () {
        try {
            var data = JSON.parse(xhr.responseText);
            if (!data.results || data.results.length === 0) return;

            var kiOnly = data.results.filter(function (r) { return !excludeSet.has(r.productId); });
            if (kiOnly.length === 0) return;
            // Cap to the remaining InstantSearch quota.
            if (kiOnly.length > maxAdd) { kiOnly = kiOnly.slice(0, maxAdd); }

            function buildRowItem(r) {
                var li = document.createElement('li');
                var html = '<a class="instasearch-hit" href="' + r.url + '">';
                html += '<span class="instasearch-hit-wrapper" style="min-height:60px; align-items:center;">';
                html += '<span class="instasearch-hit-thumb d-block" style="width:60px; min-width:60px;">';
                if (r.imageUrl) html += '<img src="' + r.imageUrl + '" class="img-fluid" alt="" />';
                html += '</span>';
                html += '<span class="d-flex flex-column" style="overflow:hidden; flex:1; gap:2px;">';
                html += '<span class="d-block text-truncate fw-semibold">' + r.name;
                html += ' <span class="hs-ki-badge"><i class="fa fa-brain"></i> ' + (r.score || '') + '</span></span>';
                if (r.shortDescription) {
                    html += '<span class="d-block text-truncate small text-muted">' + r.shortDescription + '</span>';
                }
                if (r.price) {
                    html += '<span class="d-block mt-1"><span class="hs-price">' + r.price + '</span></span>';
                }
                html += '</span></span></a>';
                li.innerHTML = html;
                return li;
            }

            function buildTileItem(r, imgHeight) {
                var col = document.createElement('div');
                col.className = 'col';
                // Every slot is always emitted (with empty content if data missing) so all
                // tiles in the grid have identical outer dimensions — same fixed heights as
                // the Razor tiles. The `hs-tile-price` slot at the bottom holds the badge
                // and/or the price.
                var html = '<a class="d-block text-decoration-none text-body hs-tile" href="' + r.url + '">';
                html += '<div class="hs-tile-thumb" style="height:' + imgHeight + 'px;">';
                if (r.imageUrl) {
                    html += '<img src="' + r.imageUrl + '" class="img-fluid" style="max-height:' + imgHeight + 'px; object-fit:contain;" alt="" />';
                }
                html += '</div>';
                html += '<div class="text-truncate small fw-semibold">' + r.name + '</div>';
                html += '<div class="text-truncate text-muted" style="font-size:0.7rem;">' + (r.shortDescription || '') + '</div>';
                html += '<div class="hs-tile-price">';
                html += '<span class="hs-ki-badge"><i class="fa fa-brain"></i> ' + (r.score || '') + '</span>';
                if (r.price) {
                    html += '<span class="hs-price ms-1">' + r.price + '</span>';
                }
                html += '</div>';
                html += '</a>';
                col.innerHTML = html;
                return col;
            }

            // Hide "no results" message if present (Lucene had 0 hits)
            var noHits = document.querySelector('.instasearch-no-hits');
            if (noHits) noHits.style.display = 'none';

            // Find or CREATE the product list containers.
            // When Lucene had 0 results, these containers don't exist — we create them.
            var tileGrid = document.querySelector('#instasearch-tiles .row');
            if (!tileGrid) {
                // Prefer the glass-styled panel wrapper so the new tiles inherit the panel
                // background + radius. Falls back to noHits-parent (Lucene 0 hits, KI-only)
                // and finally to .instasearch-drop. Without this prefer, when Lucene only
                // returned category/manufacturer hits (no products), the new tiles ended up
                // OUTSIDE `.crs-instasearch-panel` → the glass background "ended" above them.
                var panelWrap = document.querySelector('.crs-instasearch-panel');
                var container = panelWrap
                    || (noHits ? noHits.parentElement : null)
                    || document.querySelector('.instasearch-drop')
                    || document.body;
                var tilesDiv = document.createElement('div');
                tilesDiv.className = 'instasearch-tiles';
                tilesDiv.id = 'instasearch-tiles';
                var grid = document.createElement('div');
                grid.className = 'row row-cols-4 g-2';
                tilesDiv.appendChild(grid);
                container.appendChild(tilesDiv);
                tileGrid = grid;
            }

            // Append KI-only products at the BOTTOM of the lists
            // (Lucene exact matches rank higher, KI supplements below)
            kiOnly.forEach(function (r) {
                tileGrid.appendChild(buildTileItem(r, 80));
            });

            var rowList = document.querySelector('#instasearch-rows');
            if (rowList) {
                kiOnly.forEach(function (r) {
                    rowList.appendChild(buildRowItem(r));
                });
            }

            var fullGrid = document.querySelector('#instasearch-full .row');
            if (fullGrid) {
                kiOnly.forEach(function (r) {
                    fullGrid.appendChild(buildTileItem(r, 200));
                });
            }

        } catch (e) {
            console.warn('KI search merge error:', e);
        }
    };
    xhr.send('q=' + encodeURIComponent(term) + '&exclude=' + (exclude || ''));
})();
