/**
 * Release Hub Frontend JavaScript
 */
(function() {
    'use strict';

    // Initialize immediately if DOM ready, otherwise wait
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

    function init() {
        initTabs();
        // Only initialize toggle if not already done by frontend-changelog.js
        if (!window.chaChangelogInitialized) {
            window.chaChangelogInitialized = true;
            initToggleButtons();
        }
        initReleaseSearch();
        initSearchAwarePagination();
    }

    /**
     * Initialize tab switching
     */
    function initTabs() {
        const hubs = document.querySelectorAll('.cha-release-hub');

        hubs.forEach(hub => {
            const tabs = hub.querySelectorAll('.cha-hub-tab');
            const panels = hub.querySelectorAll('.cha-hub-panel');

            tabs.forEach(tab => {
                tab.addEventListener('click', () => {
                    const targetId = tab.getAttribute('data-tab');

                    // Update tabs
                    tabs.forEach(t => t.classList.remove('active'));
                    tab.classList.add('active');

                    // Update panels
                    panels.forEach(p => {
                        if (p.getAttribute('data-panel') === targetId) {
                            p.classList.add('active');
                        } else {
                            p.classList.remove('active');
                        }
                    });

                    // Update URL hash without scrolling
                    history.replaceState(null, null, '#' + targetId);
                });
            });

            // Check URL hash and activate corresponding tab on load
            const hash = window.location.hash.substring(1); // Remove #
            if (hash) {
                const targetTab = hub.querySelector(`[data-tab="${hash}"]`);
                if (targetTab) {
                    targetTab.click();
                }
            }
        });
    }

    /**
     * Initialize the release search bar:
     * - Debounced input → fires AJAX cha_filter_releases.
     * - Replaces only the .cha-changelog-container + .cha-pagination DOM (so
     *   subscribe header, badge filter pills, and the search input itself
     *   keep their state across requests).
     * - Syncs ?cha_search= in the URL via history.replaceState so deep links work
     *   and the current state survives back/forward navigation.
     * - Sends the active badge filter (read from URL) so search and badge filter
     *   compose correctly.
     */
    function initReleaseSearch() {
        const cfg = window.changeloger_local_object;
        if (!cfg || !cfg.ajax_url) {
            // No AJAX wiring available — fall back to the form's GET submit.
            return;
        }

        document.querySelectorAll('[data-cha-release-search]').forEach(form => {
            const input = form.querySelector('.cha-release-search__input');
            const clearBtn = form.querySelector('.cha-release-search__clear');
            if (!input) return;

            // Prevent the form from submitting via GET when JS handles it.
            form.addEventListener('submit', e => {
                e.preventDefault();
                runSearch(form, input.value);
            });

            let timer = null;
            input.addEventListener('input', () => {
                clearTimeout(timer);
                timer = setTimeout(() => runSearch(form, input.value), 300);
            });

            if (clearBtn) {
                clearBtn.addEventListener('click', () => {
                    input.value = '';
                    runSearch(form, '');
                    input.focus();
                });
            }
        });

        // Restore search state from URL on back/forward navigation.
        window.addEventListener('popstate', () => {
            const params = new URLSearchParams(window.location.search);
            const term = params.get('cha_search') || '';
            const form = document.querySelector('[data-cha-release-search]');
            const input = form && form.querySelector('.cha-release-search__input');
            if (input && input.value !== term) {
                input.value = term;
                runSearch(form, term, /*pushState*/ false);
            }
        });
    }

    /**
     * Pagination links currently rebuild via plain links (?cha_page=...). When
     * a search term is active we want pagination to keep that term and also
     * route through AJAX (so we reuse the same DOM-swap path as search).
     */
    function initSearchAwarePagination() {
        const cfg = window.changeloger_local_object;
        if (!cfg || !cfg.ajax_url) return;

        document.addEventListener('click', e => {
            const link = e.target.closest('.cha-pagination a');
            if (!link) return;

            const form = document.querySelector('[data-cha-release-search]');
            if (!form) return;
            const input = form.querySelector('.cha-release-search__input');
            const term = input ? input.value : '';
            if (!term) return; // No active search — let default link handling run.

            e.preventDefault();
            const url = new URL(link.href, window.location.origin);
            const page = parseInt(url.searchParams.get('cha_page') || '1', 10);
            runSearch(form, term, true, page);
        });
    }

    /**
     * Execute an AJAX search request and swap the releases container + pagination.
     *
     * @param {HTMLFormElement} form
     * @param {string} term
     * @param {boolean} [pushState=true] Whether to update browser history.
     * @param {number} [page=1] Page to load.
     */
    function runSearch(form, term, pushState = true, page = 1) {
        const cfg = window.changeloger_local_object;
        if (!cfg || !cfg.ajax_url) return;

        const params = new URLSearchParams(window.location.search);
        const badge = params.get('cha_badge') || '';

        const body = new URLSearchParams();
        body.set('action', 'cha_filter_releases');
        body.set('product_id', form.dataset.productId || '0');
        body.set('limit', form.dataset.limit || '0');
        body.set('layout', form.dataset.layout || 'default');
        body.set('width_mode', form.dataset.widthMode || 'default');
        body.set('custom_width', form.dataset.customWidth || '800');
        body.set('badge', badge);
        body.set('search', term);
        body.set('page', String(page));

        const hub = form.closest('.cha-release-hub') || document;
        const container = hub.querySelector('.cha-changelog-container');
        if (container) container.classList.add('cha-changelog-container--loading');

        fetch(cfg.ajax_url, {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
            body: body.toString(),
        })
            .then(r => r.json())
            .then(data => {
                if (!data || !data.success || !data.data) return;
                swapReleasesHTML(hub, data.data.html);
                syncUrl(term, page, badge, pushState);
            })
            .catch(() => {
                // On failure, leave the existing UI alone but remove loading state.
            })
            .finally(() => {
                const c = hub.querySelector('.cha-changelog-container');
                if (c) c.classList.remove('cha-changelog-container--loading');
            });
    }

    /**
     * Replace the existing releases container + pagination with the new HTML
     * returned by the AJAX response.
     */
    function swapReleasesHTML(hub, html) {
        // The response html includes the container + pagination siblings.
        const wrapper = document.createElement('div');
        wrapper.innerHTML = html;

        const oldContainer = hub.querySelector('.cha-changelog-container');
        const oldPagination = hub.querySelector('.cha-pagination');
        const oldNoResults = hub.querySelector('.cha-no-releases');

        const newContainer = wrapper.querySelector('.cha-changelog-container');
        const newPagination = wrapper.querySelector('.cha-pagination');
        const newNoResults = wrapper.querySelector('.cha-no-releases');

        // Remove stale nodes.
        if (oldNoResults) oldNoResults.remove();
        if (oldPagination) oldPagination.remove();

        if (oldContainer) {
            if (newContainer) {
                oldContainer.replaceWith(newContainer);
            } else {
                oldContainer.remove();
            }
        } else if (newContainer) {
            // No previous container (was a no-results state) — insert after the search form.
            const form = hub.querySelector('[data-cha-release-search]');
            (form || hub).insertAdjacentElement('afterend', newContainer);
        }

        if (newNoResults) {
            // Place the no-results message where the container would have gone.
            const anchor = hub.querySelector('.cha-changelog-container') || hub.querySelector('[data-cha-release-search]') || hub;
            anchor.insertAdjacentElement('afterend', newNoResults);
        }

        if (newPagination) {
            const anchor = hub.querySelector('.cha-changelog-container') || hub;
            anchor.insertAdjacentElement('afterend', newPagination);
        }
    }

    /**
     * Update the URL bar to reflect the current search/page/badge state.
     */
    function syncUrl(term, page, badge, push) {
        const url = new URL(window.location.href);
        if (term) url.searchParams.set('cha_search', term);
        else url.searchParams.delete('cha_search');

        if (page > 1) url.searchParams.set('cha_page', String(page));
        else url.searchParams.delete('cha_page');

        if (badge) url.searchParams.set('cha_badge', badge);

        const next = url.pathname + url.search + url.hash;
        if (push) {
            window.history.pushState({ chaSearch: term, chaPage: page }, '', next);
        } else {
            window.history.replaceState({ chaSearch: term, chaPage: page }, '', next);
        }
    }

    /**
     * Initialize toggle buttons for change items using event delegation
     */
    function initToggleButtons() {
        // Use capture phase to ensure we get the event first
        document.addEventListener('click', function(e) {
            const button = e.target.closest('.cha-change-toggle');
            if (!button) return;

            e.preventDefault();
            e.stopPropagation();

            const section = button.closest('.cha-change-section');
            if (!section) return;

            const items = section.querySelector('.cha-change-items');
            if (!items) return;

            const isExpanded = button.getAttribute('aria-expanded') === 'true';

            button.setAttribute('aria-expanded', !isExpanded);
            
            if (isExpanded) {
                items.setAttribute('hidden', '');
            } else {
                items.removeAttribute('hidden');
            }
        }, true); // Use capture phase
    }

})();
