// CRS.HybridSearch - HybridMenu Frontend JS
// Lazy-loads rotator products when the corresponding dropdown is opened. Rotates them
// on the configured interval. Falls back gracefully if the rotator container is missing.

(function (global) {
    'use strict';

    var endpoint = null;
    var initialized = false;

    function load(rotEl) {
        if (rotEl.dataset.loaded === '1' || rotEl.dataset.loading === '1') return;
        rotEl.dataset.loading = '1';
        var fd = new FormData();
        fd.append('entityId', rotEl.dataset.entityId || '0');
        fd.append('entityType', rotEl.dataset.entityType || 'Category');
        fd.append('categoryId', rotEl.dataset.categoryId || '0');

        // CSRF — use any anti-forgery token on the current page if present.
        var tk = document.querySelector('input[name="__RequestVerificationToken"]');
        if (tk) fd.append('__RequestVerificationToken', tk.value);

        fetch(endpoint, { method: 'POST', body: fd, credentials: 'same-origin' })
            .then(function (r) { return r.ok ? r.json() : null; })
            .then(function (data) {
                rotEl.dataset.loaded = '1';
                rotEl.dataset.loading = '0';
                if (!data || !data.ids || data.ids.length === 0) return;
                var grid = rotEl.querySelector('.crs-hm-rotator-products');
                if (!grid) return;
                // Minimal placeholder render — names + permalink. A theme can override this.
                grid.innerHTML = data.names.map(function (n, i) {
                    return '<a class="crs-hm-rot-item" href="/product/' + data.ids[i] + '">' + escapeHtml(n) + '</a>';
                }).join('');
                schedule(rotEl);
            })
            .catch(function () { rotEl.dataset.loading = '0'; });
    }

    function schedule(rotEl) {
        var interval = parseInt(rotEl.dataset.interval || '4000', 10);
        if (interval <= 0) return;
        var cycle = rotEl.dataset.cycle === 'true';
        var grid = rotEl.querySelector('.crs-hm-rotator-products');
        if (!grid) return;
        var children = Array.prototype.slice.call(grid.children);
        if (children.length <= 1) return;
        var idx = 0;
        children.forEach(function (c, i) { c.style.display = i === 0 ? '' : 'none'; });
        setInterval(function () {
            children[idx].style.display = 'none';
            idx = (idx + 1) % children.length;
            if (!cycle && idx === 0) return;
            children[idx].style.display = '';
        }, interval);
    }

    function escapeHtml(s) {
        if (s == null) return '';
        return String(s)
            .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
    }

    function attach() {
        var rotators = document.querySelectorAll('.crs-hm-teaser-rotator');
        rotators.forEach(function (rotEl) {
            // Defer loading until the dropdown is shown (data-id on parent dropdown-menu-X).
            var dropdown = rotEl.closest('.crs-hybridmenu-dropdown');
            if (!dropdown) { load(rotEl); return; }
            // Bootstrap-compatible: 'shown.bs.dropdown' event from megaMenu plugin.
            $(dropdown).one('mouseenter focusin', function () { load(rotEl); });
        });
    }

    var CrsHybridMenu = {
        init: function (rotatorEndpoint) {
            if (initialized) return;
            initialized = true;
            endpoint = rotatorEndpoint;
            attach();
        }
    };

    global.CrsHybridMenu = CrsHybridMenu;
})(window);
