/**
 * Shop Search — grouped autocomplete (categories + products)
 *
 * Expects window.SS_CONFIG:
 * {
 *   autocompleteUrl: '/search/autocomplete',
 *   searchUrl: '/search',
 *   translations: { no_results, view_all, categories_label, products_label }
 * }
 */
(function () {
    'use strict';

    function init() {
        var cfg = window.SS_CONFIG || {};
        var t = cfg.translations || {};

        /* Attach to ALL .search-box elements */
        var boxes = document.querySelectorAll('.search-box');
        if (!boxes.length) return;

        boxes.forEach(function (box) {
            setupSearchBox(box, cfg, t);
        });
    }

    function setupSearchBox($wrap, cfg, t) {
        var $input = $wrap.querySelector('input');
        if (!$input) return;

        /* Create dropdown */
        var $dropdown = $wrap.querySelector('.ss-dropdown');
        if (!$dropdown) {
            $dropdown = document.createElement('div');
            $dropdown.className = 'ss-dropdown';
            $wrap.style.position = 'relative';
            $wrap.appendChild($dropdown);
        }

        $input.setAttribute('autocomplete', 'off');

        /* Bind search button */
        var $btn = $wrap.querySelector('button');
        if ($btn) {
            $btn.addEventListener('click', function () {
                var q = $input.value.trim();
                if (q.length >= 2) {
                    window.location.href = cfg.searchUrl + '?q=' + encodeURIComponent(q);
                }
            });
        }

        var debounceTimer = null;
        var activeIndex = -1;
        var allLinks = [];

        /* ========================
           INPUT
           ======================== */
        $input.addEventListener('input', function () {
            var q = this.value.trim();
            clearTimeout(debounceTimer);

            if (q.length < 2) {
                closeDropdown();
                return;
            }

            debounceTimer = setTimeout(function () {
                fetchAutocomplete(q);
            }, 250);
        });

        $input.addEventListener('keydown', function (e) {
            if (!$dropdown.classList.contains('show')) {
                if (e.key === 'Enter') { ssSubmit(); e.preventDefault(); }
                return;
            }

            if (e.key === 'ArrowDown') {
                e.preventDefault();
                activeIndex = Math.min(activeIndex + 1, allLinks.length - 1);
                updateActive();
            } else if (e.key === 'ArrowUp') {
                e.preventDefault();
                activeIndex = Math.max(activeIndex - 1, -1);
                updateActive();
            } else if (e.key === 'Enter') {
                e.preventDefault();
                if (activeIndex >= 0 && allLinks[activeIndex]) {
                    window.location.href = allLinks[activeIndex].getAttribute('href');
                } else {
                    ssSubmit();
                }
            } else if (e.key === 'Escape') {
                closeDropdown();
            }
        });

        document.addEventListener('click', function (e) {
            if (!$wrap.contains(e.target)) closeDropdown();
        });

        $input.addEventListener('focus', function () {
            if (allLinks.length > 0 && this.value.trim().length >= 2) {
                $dropdown.classList.add('show');
            }
        });

        /* ========================
           FETCH
           ======================== */
        function fetchAutocomplete(q) {
            showLoading();
            $dropdown.classList.add('show');

            fetch(cfg.autocompleteUrl + '?q=' + encodeURIComponent(q), {
                headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
            })
                .then(function (r) { return r.json(); })
                .then(function (data) {
                    activeIndex = -1;
                    renderGrouped(data, q);
                })
                .catch(function () { closeDropdown(); });
        }

        /* ========================
           RENDER — grouped
           ======================== */
        function renderGrouped(data, query) {
            var cats = data.categories || [];
            var products = data.products || [];
            var total = data.total_products || 0;
            var re = new RegExp('(' + escapeRegex(query) + ')', 'gi');

            $dropdown.innerHTML = '';
            allLinks = [];

            var hasResults = cats.length > 0 || products.length > 0;

            if (!hasResults) {
                $dropdown.innerHTML = '<div class="ss-empty">' + (t.no_results || 'Nieko nerasta') + '</div>';
                $dropdown.classList.add('show');
                return;
            }

            /* Categories section */
            if (cats.length > 0) {
                var catLabel = document.createElement('div');
                catLabel.className = 'ss-section-label';
                catLabel.textContent = t.categories_label || 'Kategorijos';
                $dropdown.appendChild(catLabel);

                cats.forEach(function (cat) {
                    var a = document.createElement('a');
                    a.className = 'ss-cat';
                    a.href = cat.url;

                    var imgHtml;
                    if (cat.image) {
                        imgHtml = '<img class="ss-cat-icon" src="' + cat.image + '" alt="">';
                    } else {
                        imgHtml = '<div class="ss-cat-icon-placeholder"><i class="fa-solid fa-folder"></i></div>';
                    }

                    var titleH = cat.title.replace(re, '<mark>$1</mark>');

                    a.innerHTML = imgHtml +
                        '<div class="ss-cat-info"><div class="ss-cat-title">' + titleH + '</div></div>' +
                        '<span class="ss-cat-count">' + cat.products_count + '</span>';

                    $dropdown.appendChild(a);
                    allLinks.push(a);
                });
            }

            /* Divider */
            if (cats.length > 0 && products.length > 0) {
                var div = document.createElement('div');
                div.className = 'ss-divider';
                $dropdown.appendChild(div);
            }

            /* Products section */
            if (products.length > 0) {
                var prodLabel = document.createElement('div');
                prodLabel.className = 'ss-section-label';
                prodLabel.textContent = t.products_label || 'Prekės';
                $dropdown.appendChild(prodLabel);

                products.forEach(function (item) {
                    var a = document.createElement('a');
                    a.className = 'ss-item';
                    a.href = item.url;

                    var imgHtml;
                    if (item.image) {
                        imgHtml = '<img class="ss-item-img" src="' + item.image + '" alt="">';
                    } else {
                        imgHtml = '<div class="ss-item-img-placeholder"><i class="fa-solid fa-image"></i></div>';
                    }

                    var titleH = item.title.replace(re, '<mark>$1</mark>');

                    a.innerHTML = imgHtml +
                        '<div class="ss-item-info">' +
                        '<div class="ss-item-title">' + titleH + '</div>' +
                        '<div class="ss-item-cat">' + (item.category || '') + '</div>' +
                        '</div>' +
                        '<span class="ss-item-price">' + item.price + '</span>';

                    $dropdown.appendChild(a);
                    allLinks.push(a);
                });
            }

            /* "View all" */
            if (total > products.length) {
                var allLink = document.createElement('a');
                allLink.className = 'ss-all';
                allLink.href = cfg.searchUrl + '?q=' + encodeURIComponent(query);
                allLink.textContent = (t.view_all || 'Visi rezultatai') + ' (' + total + ') →';
                $dropdown.appendChild(allLink);
                allLinks.push(allLink);
            }

            $dropdown.classList.add('show');
        }

        function showLoading() {
            $dropdown.innerHTML =
                '<div class="ss-loading"><div class="ss-dots"><span></span><span></span><span></span></div></div>';
            allLinks = [];
        }

        /* ========================
           KEYBOARD NAV
           ======================== */
        function updateActive() {
            allLinks.forEach(function (el, i) {
                el.classList.toggle('ss-active', i === activeIndex);
            });
            if (activeIndex >= 0 && allLinks[activeIndex]) {
                allLinks[activeIndex].scrollIntoView({ block: 'nearest' });
            }
        }

        /* ========================
           HELPERS
           ======================== */
        function closeDropdown() {
            $dropdown.classList.remove('show');
            $dropdown.innerHTML = '';
            activeIndex = -1;
            allLinks = [];
        }

        function escapeRegex(str) {
            return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        }

    } /* end setupSearchBox() */

    /* Global submit — finds the visible input */
    window.ssSubmit = function () {
        var cfg = window.SS_CONFIG || {};
        var inputs = document.querySelectorAll('.search-box input');
        for (var i = 0; i < inputs.length; i++) {
            var q = inputs[i].value.trim();
            if (q.length >= 2) {
                window.location.href = cfg.searchUrl + '?q=' + encodeURIComponent(q);
                return;
            }
        }
    };

    /* ========================
       SEARCH MODAL
       ======================== */

    function initSearchModal() {
        var cfg = window.SS_CONFIG || {};
        var t = cfg.translations || {};

        /* Create modal DOM */
        var overlay = document.createElement('div');
        overlay.className = 'sm-overlay';
        overlay.id = 'sm-overlay';
        overlay.innerHTML =
            '<div class="sm-container">' +
            '<div class="sm-close"><button type="button" class="sm-close-btn" onclick="closeSearchModal()"><i class="fa-solid fa-xmark"></i></button></div>' +
            '<div class="sm-input-wrap">' +
            '<i class="fa-solid fa-magnifying-glass sm-input-icon"></i>' +
            '<input type="search" class="sm-input" id="sm-input" placeholder="' + (t.placeholder || 'Ieškoti prekių...') + '" autocomplete="off">' +
            '<button type="button" class="sm-clear" id="sm-clear" onclick="smClearInput()"><i class="fa-solid fa-xmark"></i></button>' +
            '</div>' +
            '<div class="sm-results" id="sm-results">' +
            '<div class="sm-hint"><i class="fa-solid fa-magnifying-glass"></i>' + (t.enter_query || 'Įveskite paieškos frazę') + '</div>' +
            '</div>' +
            '</div>';
        document.body.appendChild(overlay);

        var $smInput = document.getElementById('sm-input');
        var $smResults = document.getElementById('sm-results');
        var $smClear = document.getElementById('sm-clear');
        var smTimer = null;

        /* Input handler */
        $smInput.addEventListener('input', function () {
            var q = this.value.trim();

            /* Show/hide clear button */
            $smClear.classList.toggle('show', q.length > 0);

            clearTimeout(smTimer);
            if (q.length < 2) {
                $smResults.innerHTML = '<div class="sm-hint"><i class="fa-solid fa-magnifying-glass"></i>' + (t.enter_query || 'Įveskite paieškos frazę') + '</div>';
                return;
            }

            smTimer = setTimeout(function () { smFetch(q); }, 250);
        });

        /* Keyboard */
        $smInput.addEventListener('keydown', function (e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                var q = this.value.trim();
                if (q.length >= 2) {
                    window.location.href = cfg.searchUrl + '?q=' + encodeURIComponent(q);
                }
            }
            if (e.key === 'Escape') {
                closeSearchModal();
            }
        });

        /* Fetch */
        function smFetch(q) {
            $smResults.innerHTML = '<div class="sm-loading"><div class="ss-dots"><span></span><span></span><span></span></div></div>';

            fetch(cfg.autocompleteUrl + '?q=' + encodeURIComponent(q), {
                headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
            })
                .then(function (r) { return r.json(); })
                .then(function (data) { smRender(data, q); })
                .catch(function () { $smResults.innerHTML = ''; });
        }

        /* Render */
        function smRender(data, query) {
            var cats = data.categories || [];
            var products = data.products || [];
            var total = data.total_products || 0;
            var re = new RegExp('(' + query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');
            var html = '';

            if (cats.length === 0 && products.length === 0) {
                $smResults.innerHTML = '<div class="sm-empty">' + (t.no_results || 'Nieko nerasta') + '</div>';
                return;
            }

            /* Categories */
            if (cats.length > 0) {
                html += '<div class="sm-section-label">' + (t.categories_label || 'Kategorijos') + '</div>';
                cats.forEach(function (cat) {
                    var img = cat.image
                        ? '<img class="sm-cat-icon" src="' + cat.image + '" alt="">'
                        : '<div class="sm-cat-icon-ph"><i class="fa-solid fa-folder"></i></div>';
                    var title = cat.title.replace(re, '<mark>$1</mark>');
                    html += '<a class="sm-cat" href="' + cat.url + '">' +
                        img +
                        '<div class="sm-cat-info"><div class="sm-cat-title">' + title + '</div></div>' +
                        '<span class="sm-cat-count">' + cat.products_count + '</span>' +
                        '</a>';
                });
            }

            if (cats.length > 0 && products.length > 0) {
                html += '<div class="sm-divider"></div>';
            }

            /* Products */
            if (products.length > 0) {
                html += '<div class="sm-section-label">' + (t.products_label || 'Prekės') + '</div>';
                products.forEach(function (item) {
                    var img = item.image
                        ? '<img class="sm-item-img" src="' + item.image + '" alt="">'
                        : '<div class="sm-item-img-ph"><i class="fa-solid fa-image"></i></div>';
                    var title = item.title.replace(re, '<mark>$1</mark>');
                    html += '<a class="sm-item" href="' + item.url + '">' +
                        img +
                        '<div class="sm-item-info"><div class="sm-item-title">' + title + '</div><div class="sm-item-cat">' + (item.category || '') + '</div></div>' +
                        '<span class="sm-item-price">' + item.price + '</span>' +
                        '</a>';
                });
            }

            /* View all */
            if (total > products.length) {
                html += '<a class="sm-all" href="' + cfg.searchUrl + '?q=' + encodeURIComponent(query) + '">' +
                    (t.view_all || 'Visi rezultatai') + ' (' + total + ') →</a>';
            }

            $smResults.innerHTML = html;
        }
    }

    /* Global open/close */
    window.openSearchModal = function () {
        var overlay = document.getElementById('sm-overlay');
        if (!overlay) return;
        overlay.classList.add('show');
        document.body.style.overflow = 'hidden';
        setTimeout(function () {
            var input = document.getElementById('sm-input');
            if (input) { input.value = ''; input.focus(); }
            var clear = document.getElementById('sm-clear');
            if (clear) clear.classList.remove('show');
            var results = document.getElementById('sm-results');
            var t = (window.SS_CONFIG || {}).translations || {};
            if (results) results.innerHTML = '<div class="sm-hint"><i class="fa-solid fa-magnifying-glass"></i>' + (t.enter_query || 'Įveskite paieškos frazę') + '</div>';
        }, 50);
    };

    window.closeSearchModal = function () {
        var overlay = document.getElementById('sm-overlay');
        if (!overlay) return;
        overlay.classList.remove('show');
        document.body.style.overflow = '';
    };

    window.smClearInput = function () {
        var input = document.getElementById('sm-input');
        var clear = document.getElementById('sm-clear');
        var results = document.getElementById('sm-results');
        var t = (window.SS_CONFIG || {}).translations || {};
        if (input) { input.value = ''; input.focus(); }
        if (clear) clear.classList.remove('show');
        if (results) results.innerHTML = '<div class="sm-hint"><i class="fa-solid fa-magnifying-glass"></i>' + (t.enter_query || 'Įveskite paieškos frazę') + '</div>';
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () { init(); initSearchModal(); });
    } else {
        init();
        initSearchModal();
    }

})();
