/**
 * Global Loading State Handler for Forms and Click Events
 */
(function () {
    'use strict';

    /**
     * Set a button or clickable element into loading state.
     * @param {HTMLElement} btn 
     */
    function showButtonLoading(btn) {
        if (!btn) return;
        btn.classList.add('is-loading');
        btn.setAttribute('data-loading', 'true');
        btn.style.pointerEvents = 'none';
        
        // Short timeout before disabling element so form submit payload retains submit button value if needed
        setTimeout(function () {
            btn.disabled = true;
        }, 10);
    }

    /**
     * Remove loading state from a button or clickable element.
     * @param {HTMLElement} btn 
     */
    function hideButtonLoading(btn) {
        if (!btn) return;
        btn.classList.remove('is-loading');
        btn.removeAttribute('data-loading');
        btn.disabled = false;
        btn.style.pointerEvents = '';
    }

    // Expose helpers globally
    window.showButtonLoading = showButtonLoading;
    window.hideButtonLoading = hideButtonLoading;

    document.addEventListener('DOMContentLoaded', function () {
        // Track the last clicked submit button inside forms
        let lastClickedSubmitter = null;

        document.addEventListener('click', function (e) {
            const btn = e.target.closest('button, input[type="submit"], a.btn');
            if (!btn) return;

            if (btn.tagName === 'BUTTON' || btn.type === 'submit') {
                lastClickedSubmitter = btn;
            }

            // Handle elements explicitly marked with data-loading-click or .js-loading-click
            if (btn.hasAttribute('data-loading-click') || btn.classList.contains('js-loading-click')) {
                showButtonLoading(btn);
            }
        }, true);

        // Global form submission loading handler
        document.addEventListener('submit', function (e) {
            const form = e.target;
            if (!form || e.defaultPrevented) return;

            // Find the submit button
            let submitBtn = e.submitter || lastClickedSubmitter;
            if (!submitBtn || !form.contains(submitBtn)) {
                submitBtn = form.querySelector('button[type="submit"], input[type="submit"], button:not([type="button"])');
            }

            if (submitBtn) {
                showButtonLoading(submitBtn);
            }
        });
    });
})();
