/**
 * _             _       _
 * | |____      _| | __ _| |__
 * | '_ \ \ /\ / / |/ _` | '_ \
 * | |_) \ V  V /| | (_| | |_) |
 * |_.__/ \_/\_/ |_|\__,_|_.__/.
 *
 * @author    Bwlab di Luigi Massa <info@bwlab.it>
 * @copyright since 2014 Bwlab
 * @license   proprietary
 */
/* bwwithdrawal — vanilla ES6+, no jQuery */
(function () {
    'use strict';

    function init() {
        document.querySelectorAll('.bwwithdrawal-toggle').forEach(initButton);
    }

    function initButton(toggleBtn) {
        const wrapper = toggleBtn.closest('.bwwithdrawal-wrapper');
        if (!wrapper) return;

        const formPanel = wrapper.querySelector('.bwwithdrawal-form');
        const form = wrapper.querySelector('.bwwithdrawal-form__inner');
        if (!formPanel || !form) return;

        toggleBtn.addEventListener('click', () => {
            const expanded = toggleBtn.getAttribute('aria-expanded') === 'true';
            toggleBtn.setAttribute('aria-expanded', String(!expanded));
            formPanel.hidden = expanded;
        });

        const checkbox = form.querySelector('input[type="checkbox"][name="declaration"]');
        const submitBtn = form.querySelector('.bwwithdrawal-submit');
        if (checkbox && submitBtn) {
            checkbox.addEventListener('change', () => {
                submitBtn.disabled = !checkbox.checked;
            });
        }

        form.addEventListener('submit', (e) => {
            e.preventDefault();
            submitForm(form, wrapper, toggleBtn);
        });
    }

    function submitForm(form, wrapper, toggleBtn) {
        const submitBtn = form.querySelector('.bwwithdrawal-submit');
        const feedback = form.querySelector('.bwwithdrawal-feedback');
        const orderId = wrapper.dataset.orderId;
        const token = wrapper.dataset.token;

        submitBtn.disabled = true;
        if (feedback) feedback.textContent = '';

        const body = new URLSearchParams({
            id_order: orderId,
            token: token,
            customer_name: form.querySelector('[name="customer_name"]').value,
            customer_email: form.querySelector('[name="customer_email"]').value,
        });

        fetch(`${bwwithdrawal.ajaxUrl}?ajax=1`, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: body.toString(),
        })
            .then((r) => r.json())
            .then((data) => {
                if (data.success) {
                    form.closest('.bwwithdrawal-form').hidden = true;
                    toggleBtn.hidden = true;
                    const msg = document.createElement('p');
                    msg.className = 'bwwithdrawal-submitted alert alert-success';
                    msg.textContent = data.message;
                    wrapper.appendChild(msg);
                } else {
                    if (feedback) feedback.textContent = data.message;
                    submitBtn.disabled = false;
                }
            })
            .catch(() => {
                if (feedback) feedback.textContent = bwwithdrawal.errorMessage;
                submitBtn.disabled = false;
            });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
