/**
 * FormTheme Accordion Handler
 * Manages collapsible accordion sections with only one section expanded at a time
 */

(function($) {
    'use strict';

    /**
     * FormTheme Accordion Handler
     */
    class FormThemeAccordion {
        constructor() {
            this.wrapper = document.querySelector('.griffinforms-accordion-wrapper');
            if (!this.wrapper) return;

            this.buttons = this.wrapper.querySelectorAll('.griffinforms-accordion-button');
            this.collapses = this.wrapper.querySelectorAll('.griffinforms-accordion-collapse');

            this.init();
        }

        /**
         * Initialize accordion
         */
        init() {
            this.buttons.forEach((button) => {
                button.addEventListener('click', (e) => this.toggleSection(e));
            });
        }

        /**
         * Toggle section - close others, open this one
         */
        toggleSection(event) {
            const button = event.currentTarget;
            const item = button.closest('.griffinforms-accordion-item');
            const collapse = item.querySelector('.griffinforms-accordion-collapse');

            // Check if this section is currently expanded
            const isExpanded = button.getAttribute('data-expanded') === 'true';

            if (isExpanded) {
                // Close this section
                this.closeSection(button, collapse);
            } else {
                // Close all other sections and open this one
                this.closeAllSections();
                this.openSection(button, collapse);
            }
        }

        /**
         * Open a section
         */
        openSection(button, collapse) {
            button.setAttribute('data-expanded', 'true');
            collapse.classList.add('show');

            // Scroll into view if needed
            setTimeout(() => {
                button.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }, 100);
        }

        /**
         * Close a section
         */
        closeSection(button, collapse) {
            button.setAttribute('data-expanded', 'false');
            collapse.classList.remove('show');
        }

        /**
         * Close all sections
         */
        closeAllSections() {
            this.buttons.forEach((button) => {
                const item = button.closest('.griffinforms-accordion-item');
                const collapse = item.querySelector('.griffinforms-accordion-collapse');
                this.closeSection(button, collapse);
            });
        }
    }

    /**
     * Initialize accordion when DOM is ready
     */
    document.addEventListener('DOMContentLoaded', function() {
        new FormThemeAccordion();
    });

})(jQuery);
