document.addEventListener('DOMContentLoaded', function () {
    // Prevent Bootstrap Modal crash when data-bs-target points at a missing element
    // (e.g. actions menu rendered without <x-ui.modal.actions />).
    document.addEventListener('click', function (event) {
        const trigger = event.target.closest('[data-bs-toggle="modal"][data-bs-target]');
        if (!trigger) {
            return;
        }
        const selector = trigger.getAttribute('data-bs-target');
        if (!selector || !document.querySelector(selector)) {
            event.preventDefault();
            event.stopImmediatePropagation();
        }
    }, true);

    const searchToggle = document.getElementById('topnavSearchToggle');
    const searchModal = document.getElementById('searchOverlayModal');
    const closeSearchBtn = document.getElementById('closeSearchOverlay');
    const searchBackdrop = document.getElementById('searchOverlayBackdrop');

    if (searchToggle && searchModal) {
        searchToggle.addEventListener('click', function (e) {
            e.preventDefault();
            searchModal.classList.add('active');
        });
    }
    if (closeSearchBtn && searchModal) {
        closeSearchBtn.addEventListener('click', function () {
            searchModal.classList.remove('active');
        });
    }
    if (searchBackdrop && searchModal) {
        searchBackdrop.addEventListener('click', function () {
            searchModal.classList.remove('active');
        });
    }

    const mobileNav = document.getElementById('headerMobileNav');
    if (mobileNav && window.bootstrap && window.bootstrap.Collapse) {
        mobileNav.querySelectorAll('a.dropdown-item').forEach(function (a) {
            a.addEventListener('click', function () {
                const instance =
                    window.bootstrap.Collapse.getInstance(mobileNav) ||
                    new window.bootstrap.Collapse(mobileNav, { toggle: false });
                instance.hide();
            });
        });
    }

    setTimeout(function () {
        const loader = document.getElementById('loader');
        if (loader) loader.style.display = 'none';
    }, 400);

    document.querySelectorAll('.dynamic-year').forEach(function (el) {
        el.textContent = new Date().getFullYear();
    });
});
