// CRS.HybridSearch: Fix browser form restoration for facet checkboxes.
// Problem: Browsers (Chrome, Edge, Firefox) restore checkbox states on page refresh (F5)
// and back/forward navigation, ignoring the server-rendered HTML.
// This causes unchecked facets to appear checked after page reload.
// Fix: Use 'pageshow' event (fires AFTER browser form restoration, unlike DOMContentLoaded)
// to sync each checkbox's JS property (.checked) with the HTML attribute (checked="checked")
// which reflects the actual server-side IsSelected state.
(function () {
    function fixFacetCheckboxes() {
        var checkboxes = document.querySelectorAll('input.facet-control-native[type="checkbox"]');
        checkboxes.forEach(function (cb) {
            // HTML attribute = server state, JS property = browser-restored state
            var serverChecked = cb.hasAttribute('checked');
            if (cb.checked !== serverChecked) {
                cb.checked = serverChecked;
            }
            // Prevent future browser form restoration
            cb.autocomplete = 'off';
        });
    }

    // pageshow fires after browser form restoration (handles both fresh loads and bfcache)
    window.addEventListener('pageshow', fixFacetCheckboxes);
    // DOMContentLoaded as additional safety net
    document.addEventListener('DOMContentLoaded', fixFacetCheckboxes);

    // Stretch instant search dropdown to right edge of container
    function fixInstasearchWidth() {
        var drop = document.querySelector('.instasearch-drop.open');
        if (!drop) return;
        var container = drop.closest('.container') || drop.closest('.menubar-container');
        if (!container) return;
        var containerRect = container.getBoundingClientRect();
        var dropRect = drop.getBoundingClientRect();
        var rightEdge = containerRect.right;
        var newWidth = rightEdge - dropRect.left;
        if (newWidth > 400) {
            drop.style.width = newWidth + 'px';
            drop.style.maxWidth = 'none';
        }
    }

    // Observe DOM for .instasearch-drop.open appearing
    var observer = new MutationObserver(function () {
        var drop = document.querySelector('.instasearch-drop.open');
        if (drop) fixInstasearchWidth();
    });
    document.addEventListener('DOMContentLoaded', function () {
        var target = document.querySelector('.instasearch') || document.body;
        observer.observe(target, { attributes: true, childList: true, subtree: true });
    });
    window.addEventListener('resize', fixInstasearchWidth);
})();
