document.addEventListener('alpine:init', () => {
    Alpine.data('addressAutocomplete', (searchUrl) => ({
        query: '',
        results: [],
        open: false,
        loading: false,
        selecting: false,
        debounceTimer: null,
        searchUrl: searchUrl,

        handleInput(value) {
            if (this.selecting) return;
            this.query = value;
            clearTimeout(this.debounceTimer);
            if (this.query.length < 3) {
                this.results = [];
                this.open = false;
                return;
            }
            this.debounceTimer = setTimeout(() => this.search(), 400);
        },

        async search() {
            this.loading = true;
            try {
                const res = await fetch(this.searchUrl + '?q=' + encodeURIComponent(this.query));
                this.results = await res.json();
                this.open = this.results.length > 0;
            } catch (e) {
                this.results = [];
                this.open = false;
            } finally {
                this.loading = false;
            }
        },

        select(result) {
            this.selecting = true;
            this.fillField(this.$refs.streetWrapper, result.street);
            this.fillField(this.$refs.cityWrapper, result.city);
            this.fillField(this.$refs.postalWrapper, result.postal);
            this.query = result.street;
            this.open = false;
            this.results = [];
            clearTimeout(this.debounceTimer);
            this.selecting = false;
        },

        fillField(wrapperEl, value) {
            const input = wrapperEl.querySelector('input');
            if (!input) return;
            input.value = value;
            input.dispatchEvent(new Event('input', { bubbles: true }));
            input.dispatchEvent(new Event('change', { bubbles: true }));
        },
    }));
});

document.addEventListener('livewire:navigated', () => {
    // Reinitialize Alpine components after SPA navigation
    if (window.Alpine) {
        window.Alpine.initTree(document.body);
    }
});

document.addEventListener('livewire:init', () => {
    Livewire.hook('request', ({ fail }) => {
        if (fail && fail.status === 419) {
            alert('Your session has expired — this usually happens when the page has been open for a long time. Please refresh and try again.');
        }
    });
});
