/**
 * WPFAQBlock – Frontend Accordion JS
 * @package WPFAQBlock
 * @since   2.0.0
 */
( function () {
    'use strict';

    document.addEventListener( 'DOMContentLoaded', function () {
        document.querySelectorAll( '.wpfaqblock-question' ).forEach( function ( btn ) {
            btn.addEventListener( 'click', function () {
                var item   = btn.closest( '.wpfaqblock-item' );
                var answer = document.getElementById( btn.getAttribute( 'aria-controls' ) );
                var isOpen = item.classList.contains( 'is-open' );

                // Close all others in same accordion group.
                var group = item.closest( '.wpfaqblock-accordion' );
                if ( group ) {
                    group.querySelectorAll( '.wpfaqblock-item.is-open' ).forEach( function ( open ) {
                        if ( open !== item ) {
                            open.classList.remove( 'is-open' );
                            var openBtn = open.querySelector( '.wpfaqblock-question' );
                            var openAns = open.querySelector( '.wpfaqblock-answer' );
                            if ( openBtn ) openBtn.setAttribute( 'aria-expanded', 'false' );
                            if ( openAns ) openAns.setAttribute( 'hidden', '' );
                        }
                    } );
                }

                // Toggle current.
                item.classList.toggle( 'is-open', !isOpen );
                btn.setAttribute( 'aria-expanded', String( !isOpen ) );
                if ( isOpen ) {
                    answer.setAttribute( 'hidden', '' );
                } else {
                    answer.removeAttribute( 'hidden' );
                }
            } );
        } );
    } );

} )();
