/**
 * Single Product Reviews Scripts.
 *
 * Handles the toggle for the review form.
 */

(function () {
    'use strict';

    document.addEventListener('DOMContentLoaded', () => {
        initReviewToggle();
    });

    /**
     * WooCommerce Review Toggle.
     */
    function initReviewToggle() {
        document.addEventListener('click', (e) => {
            const toggleBtn = e.target.closest('.js-toggle-review-form');
            if (!toggleBtn) return;

            e.preventDefault();
            const formWrapper = document.getElementById('review_form_wrapper');
            if (!formWrapper) return;

            // Use computed style to determine current state
            const isHidden = window.getComputedStyle(formWrapper).display === 'none';
            const allToggleBtns = document.querySelectorAll('.js-toggle-review-form');

            if (isHidden) {
                formWrapper.style.display = 'block';
                allToggleBtns.forEach(btn => {
                    btn.classList.add('is-active');
                    const activeText = btn.getAttribute('data-text-active');
                    if (activeText) btn.textContent = activeText;
                });

                // Scroll to form with offset
                setTimeout(() => {
                    const yOffset = -150;
                    const rect = formWrapper.getBoundingClientRect();
                    const y = rect.top + window.pageYOffset + yOffset;
                    window.scrollTo({ top: y, behavior: 'smooth' });
                }, 100);
            } else {
                formWrapper.style.display = 'none';
                allToggleBtns.forEach(btn => {
                    btn.classList.remove('is-active');
                    const normalText = btn.getAttribute('data-text-normal');
                    if (normalText) btn.textContent = normalText;
                });
            }
        });
    }
})();
