/**
 * Bundle UI switch config button component.
 *
 * @package EaLab\WP_Deployer
 */


(() => {
    const disableAllButtons = () => {
        const currentButtonElements = document.querySelectorAll('deploy-sync-content--bundle-ui-switch-button');
        currentButtonElements.forEach((toDisable) => {
            const toDisableButton = toDisable.querySelector('button');
            toDisableButton.dataset.inProgress = 'true';
            toDisableButton.classList.add('disabled');
        });
    };

    const enableAllButtons = () => {
        const currentButtonElements = document.querySelectorAll('deploy-sync-content--bundle-ui-switch-button');
        currentButtonElements.forEach((toEnable) => {
            const toDisableButton = toEnable.querySelector('button');
            delete toDisableButton.dataset.inProgress;
            toDisableButton.classList.remove('disabled');
        });
    }

    const handle = () => {
        // Retrieve all button elements.
        const buttonElements = document.querySelectorAll('deploy-sync-content--bundle-ui-switch-button');

        buttonElements.forEach((buttonElement) => {
            if (buttonElement.getAttribute('data-initialized') === 'true') {
                // The element is already initialized.
                return;
            }

            // Mark the element as initialized.
            buttonElement.setAttribute('data-initialized', 'true');

            const button = buttonElement.querySelector('button');
            const statusText = buttonElement.querySelector('.status-text');
            const styleTextInteractve = buttonElement.querySelector('.style-text.interactive');
            const styleTextClassic = buttonElement.querySelector('.style-text.classic');

            // Append the action on click on the button.
            button.addEventListener('click', () => {
                if (button.dataset.inProgress) {
                    // An update is already in progress.
                    // Wait for it to finish.
                    return;
                }

                // Disable all buttons.
                disableAllButtons();

                statusText.classList.add('in-progress');
                statusText.classList.remove('ok', 'not-ok');
                statusText.textContent = deploy_sync_content__button_settings?.text?.updating ?? 'Updating the configuration…';

                // Add the nonce header to the request.
                const headers = new Headers();
                headers.append('X-WP-Nonce', deploy_sync_content__button_settings?.rest?.nonce ?? '');

                const url = buttonElement.dataset.url ?? '';

                if (!url) {
                    return;
                }

                fetch(url, {method: 'GET', headers: headers})
                    .then((response) => {
                        if (!response.ok) {
                            throw new Error(deploy_sync_content__button_settings?.text?.error ?? 'An error occurred. Please check your network status or the basic Deploy & Sync Content settings, or try again later.');
                        }

                        return response.json();
                    })
                    .then(() => {
                        statusText.textContent = deploy_sync_content__button_settings?.text?.updateSuccessful ?? 'The configuration has been updated successfully.';

                        statusText.classList.add('ok');

                        if (styleTextInteractve.classList.contains('hidden')) {
                            styleTextInteractve.classList.remove('hidden');
                            styleTextClassic.classList.add('hidden');
                        } else {
                            styleTextInteractve.classList.add('hidden');
                            styleTextClassic.classList.remove('hidden');
                        }
                    })
                    .catch(() => {
                        statusText.textContent = (deploy_sync_content__button_settings?.text?.updateError ?? 'The configuration could not be updated.');

                        statusText.classList.add('not-ok');
                    })
                    .finally(() => {
                        statusText.classList.remove('in-progress');

                        // Reenable all buttons.
                        enableAllButtons();
                    })
            });
        });
    };

    handle();
})();
