'use strict';
import { Controller } from '@hotwired/stimulus';
/**
 * Filter panel controller.
 *
 * The filter UI is anchor-based: each chip is an <a href> that points to the
 * URL with that filter toggled. This controller adds light progressive
 * enhancements:
 *
 *   - debounced submit for the free-text search (so users see results while
 *     typing),
 *   - "+ age" custom-age input that pushes a new ?alter=<n> URL,
 *   - intercepting chip clicks to use Turbo for partial navigation when
 *     Turbo is available.
 *
 * Filtering itself always happens via GET URL changes — never POST — so HTTP
 * caches can do their job.
 */
export default class default_1 extends Controller {
    constructor() {
        super(...arguments);
        this.debounceTimer = null;
        this.onLinkClick = (e) => {
            // Plain anchors handle navigation themselves; we do nothing.
            // Turbo, if loaded, will intercept and do a partial visit.
        };
    }
    connect() {
        // If a chip link is clicked while a custom date / price input has
        // pending input, we still want that input to apply.
        this.element.addEventListener('click', this.onLinkClick);
    }
    disconnect() {
        this.element.removeEventListener('click', this.onLinkClick);
        if (this.debounceTimer !== null) {
            window.clearTimeout(this.debounceTimer);
        }
    }
    submit(event) {
        if (event && event.type === 'keydown' && event.key !== 'Enter')
            return;
        if (event && event.type === 'keydown')
            event.preventDefault();
        if (this.debounceTimer !== null) {
            window.clearTimeout(this.debounceTimer);
            this.debounceTimer = null;
        }
        if (typeof this.formTarget.requestSubmit === 'function') {
            this.formTarget.requestSubmit();
        }
        else {
            this.formTarget.submit();
        }
    }
    beforeSubmit(_event) {
        // Strip empty params so the URL stays clean.
        window.requestAnimationFrame(() => {
            this.cleanupHiddenEmpties();
        });
    }
    cleanupHiddenEmpties() {
        const form = this.formTarget;
        form.querySelectorAll('input[type="hidden"]').forEach((el) => {
            const inp = el;
            if (inp.value === '' || inp.value === null)
                inp.remove();
        });
    }
    debounceSubmit() {
        if (this.debounceTimer !== null)
            window.clearTimeout(this.debounceTimer);
        this.debounceTimer = window.setTimeout(() => {
            this.submit();
        }, 450);
    }
    updateAgeAdd() {
        if (!this.hasAgeInputTarget || !this.hasAgeAddBtnTarget)
            return;
        const v = Number(this.ageInputTarget.value);
        const valid = v >= 1 && v <= 27;
        this.ageAddBtnTarget.disabled = !valid;
    }
    addAge(event) {
        var _a;
        event === null || event === void 0 ? void 0 : event.preventDefault();
        if (!this.hasAgeInputTarget)
            return;
        const v = Number(this.ageInputTarget.value);
        if (!(v >= 1 && v <= 27))
            return;
        const url = new URL(window.location.href);
        const params = url.searchParams;
        // Read whatever the URL currently has — accept both the canonical
        // comma form (`?alter=3,7`) and any stale `?alter[]=3&alter[]=7`
        // bookmark a user might still have.
        const arrayForm = params.getAll('alter[]');
        const commaForm = ((_a = params.get('alter')) !== null && _a !== void 0 ? _a : '').split(',').filter((s) => s !== '');
        const existing = arrayForm.length ? arrayForm : commaForm;
        if (existing.includes(String(v))) {
            this.ageInputTarget.value = '';
            this.updateAgeAdd();
            return;
        }
        // Write back in the canonical comma form. This is what
        // `OfferListController::instantiateForm` (line 117) parses — the
        // backend rejects PHP array syntax (`alter[]=`) with `is_string`
        // and silently drops the filter. The Twig `filter_active_pills`
        // template also reads only the comma form, so without this the
        // active-filter pill would not render either.
        params.delete('alter');
        params.delete('alter[]');
        const all = [...existing, String(v)].sort();
        params.set('alter', all.join(','));
        params.delete('page');
        navigateInFrame(url.toString());
    }
}
default_1.targets = ['form', 'search', 'ageInput', 'ageAddBtn', 'count', 'reset'];
/**
 * Navigate to `url` inside the offer-list Turbo frame so the page doesn't
 * scroll-jump to the top. The frame has `data-turbo-action="advance"`, so
 * Turbo also pushes browser history — URLs remain shareable / cacheable.
 *
 * Duplicated in wishlists.ts because Symfony AssetMapper doesn't resolve
 * relative imports between controllers; not worth a shared module.
 */
function navigateInFrame(url) {
    const a = document.createElement('a');
    a.href = url;
    a.setAttribute('data-turbo-frame', 'cms-offer-list');
    a.setAttribute('data-turbo-action', 'advance');
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();
    a.remove();
}
