document.addEventListener('DOMContentLoaded', function () {

    // Conditional form (delegated)
    document.addEventListener('change', function (e) {
        var radio = e.target.closest('.vimeify-auth input[type=radio][name=connection_type]');
        if (!radio) return;

        var allDetails = radio.closest('.vimeify-auth-form--row').querySelectorAll('.vimeify-auth-form--option-details');
        for (var i = 0; i < allDetails.length; i++) {
            allDetails[i].classList.add('vimeify-hidden');
        }
        var wrapper = radio.closest('.vimeify-auth-form--option');
        if (wrapper) {
            var details = wrapper.querySelector('.vimeify-auth-form--option-details');
            if (details) {
                details.classList.remove('vimeify-hidden');
            }
        }
    });

    // Connect handler (delegated)
    document.addEventListener('click', async function (e) {
        var button = e.target.closest('#vimeify-auth-form button[type=submit]');
        if (!button) return;

        e.preventDefault();

        button.disabled = true;
        button.classList.remove('vimeify-auth-ready');
        button.classList.add('disabled');

        var wrapper = button.closest('#vimeify-auth-form');
        var formData = new FormData();

        // Connection type
        var checkboxes = wrapper.querySelectorAll('input[name=connection_type]');
        var conn_type = '';
        for (var i = 0; i < checkboxes.length; i++) {
            if (checkboxes[i].checked) {
                conn_type = checkboxes[i].value;
                formData.append('connection_type', checkboxes[i].value);
            }
        }

        // Form Fields
        var fields = document.querySelectorAll('.vimeify-auth-field');
        for (var i = 0; i < fields.length; i++) {
            formData.append(fields[i].name, fields[i].value);
        }

        // Nonce
        formData.append('_wpnonce', Vimeify_Connect.nonce);

        // Call
        var url = Vimeify_Connect.ajax_url + '?action=vimeify_connect';
        const response = await fetch(url, {
            method: 'POST',
            body: formData,
        });

        if (response.ok) {
            const main = button.closest('.vimeify-auth')
            const notice = main.querySelector('.vimeify-auth-notice');
            const result = await response.json();
            notice.innerHTML = result?.data?.message;
            notice.classList.remove('vimeify-auth-notice--success')
            notice.classList.remove('vimeify-auth-notice--error')
            notice.classList.remove('vimeify-hidden');
            if (result?.success) {
                notice.classList.add('vimeify-auth-notice--success');
                setTimeout(function () {
                    window.location.reload();
                }, 500);
            } else {
                notice.classList.add('vimeify-auth-notice--error');
            }
        }

        button.disabled = false;
        button.classList.add('vimeify-auth-ready');
        button.classList.remove('disabled');
    });

    // Disconnect handler (delegated)
    document.addEventListener('click', async function (e) {
        var disconnectBtn = e.target.closest('#vimeify-auth-disconnect-action');
        if (!disconnectBtn) return;

        e.preventDefault();

        disconnectBtn.disabled = true;
        disconnectBtn.classList.remove('vimeify-auth-ready');
        disconnectBtn.classList.add('disabled');

        var formData = new FormData();

        // Nonce
        formData.append('_wpnonce', Vimeify_Connect.nonce);

        // Call
        var url = Vimeify_Connect.ajax_url + '?action=vimeify_disconnect';
        const response = await fetch(url, {
            method: 'POST',
            body: formData,
        });

        if (response.ok) {
            const main = disconnectBtn.closest('.vimeify-auth')
            const notice = main.querySelector('.vimeify-auth-notice');
            const result = await response.json();
            notice.innerHTML = result?.data?.message;
            notice.classList.remove('vimeify-auth-notice--success')
            notice.classList.remove('vimeify-auth-notice--error')
            notice.classList.remove('vimeify-hidden');
            if (result?.success) {
                notice.classList.add('vimeify-auth-notice--success');
                setTimeout(function () {
                    window.location.reload();
                }, 500);
            } else {
                notice.classList.add('vimeify-auth-notice--error');
            }
        }

        disconnectBtn.disabled = false;
        disconnectBtn.classList.add('vimeify-auth-ready');
        disconnectBtn.classList.remove('disabled');
    });

})