(() => {
    const openButton = document.getElementById('openFilterButton');
    const closeButton = document.getElementById('closeFilterButton');
    const panel = document.getElementById('filterPanel');
    const overlay = document.getElementById('filterOverlay');
    const provinceField = document.getElementById('provinceField');
    const scopeInputs = document.querySelectorAll('input[name="scope"]');

    if (!openButton || !closeButton || !panel || !overlay) {
        return;
    }

    const updateProvinceField = () => {
        const selected = document.querySelector('input[name="scope"]:checked');
        const isProvince = selected?.value === 'province';

        if (provinceField) {
            provinceField.hidden = !isProvince;
        }
    };

    const openPanel = () => {
        overlay.hidden = false;
        document.body.classList.add('filter-open');
        panel.setAttribute('aria-hidden', 'false');
        openButton.setAttribute('aria-expanded', 'true');

        requestAnimationFrame(() => {
            panel.classList.add('is-open');
        });
    };

    const closePanel = () => {
        panel.classList.remove('is-open');
        panel.setAttribute('aria-hidden', 'true');
        openButton.setAttribute('aria-expanded', 'false');
        document.body.classList.remove('filter-open');

        window.setTimeout(() => {
            overlay.hidden = true;
        }, 220);
    };

    openButton.addEventListener('click', openPanel);
    closeButton.addEventListener('click', closePanel);
    overlay.addEventListener('click', closePanel);

    document.addEventListener('keydown', (event) => {
        if (event.key === 'Escape' && panel.classList.contains('is-open')) {
            closePanel();
        }
    });

    scopeInputs.forEach((input) => {
        input.addEventListener('change', updateProvinceField);
    });

    updateProvinceField();
})();
