const faqCollapse = {
    init() {
        document.querySelectorAll('.wp-block-yoast-faq-block').forEach(faq => {
            this.setupFaq(faq);
        });
    },

    setupFaq(faq) {
        const uniqid = Math.floor(Math.random() * (999 - 100 + 1) + 100);
        const faqId = `faq${uniqid}`;
        faq.id = faqId;

        let first = true;
        faq.querySelectorAll('.schema-faq-section').forEach(section => {
            const questionId = section.id;
            section.removeAttribute('id');
            const answerId = questionId.replace('question', 'answer');

            const question = section.querySelector('.schema-faq-question');
            const answer = section.querySelector('.schema-faq-answer');

            question.id = questionId;
            if (!first) {
                question.classList.add('collapsed');
            }
            question.setAttribute('data-bs-toggle', 'collapse');
            question.setAttribute('data-bs-target', `#${answerId}`);
            question.setAttribute('aria-expanded', first.toString());
            question.setAttribute('aria-controls', answerId);

            answer.id = answerId;
            answer.classList.add('accordion-collapse', 'collapse');
            if (first) {
                answer.classList.add('show');
            }
            answer.setAttribute('aria-labelledby', questionId);
            answer.setAttribute('data-bs-parent', `#${faqId}`);

            first = false;
        });
    }
};

document.addEventListener('DOMContentLoaded', () => faqCollapse.init());
