(function () {
    'use strict';

    function getConfig() {
        return window.tiamrSettings || {};
    }

    function setStatus(wrapper, text, state) {
        var status = wrapper ? wrapper.querySelector('.amr-autosave-status') : null;

        if (!status) {
            return;
        }

        status.textContent = text || '';
        status.setAttribute('data-state', state || '');
    }

    function setToggleSavedState(wrapper, input) {
        if (!wrapper || !input) {
            return;
        }

        wrapper.classList.remove('amr-is-saving', 'amr-save-error');
        wrapper.classList.toggle('amr-is-saved-on', input.checked);
        wrapper.classList.toggle('amr-is-saved-off', !input.checked);
    }


    function saveFreemiusBetaMode(input) {
        var config = getConfig();
        var beta = config.beta || {};

        if (!input.hasAttribute('data-amr-beta-toggle') || !beta.native) {
            return Promise.resolve();
        }

        if (input.checked && beta.confirm && !window.confirm(beta.confirm)) {
            return Promise.reject(new Error('cancelled'));
        }

        var form = new FormData();
        form.append('action', beta.action || '');
        form.append('security', beta.security || '');
        form.append('is_beta', input.checked ? 'true' : 'false');
        form.append('module_id', beta.moduleId || '');

        return fetch(beta.ajaxUrl || config.ajaxUrl || ajaxurl, {
            method: 'POST',
            credentials: 'same-origin',
            body: form
        }).then(function (response) {
            return response.json();
        }).then(function (data) {
            if (!data || !data.success) {
                throw new Error('Beta save failed');
            }

            return data;
        });
    }

    function postSetting(input, previousValue) {
        var config = getConfig();
        var wrapper = input.closest('.amr-modern-toggle');
        var delay = parseInt(config.delay || 500, 10);

        input.disabled = true;
        wrapper.classList.add('amr-is-saving');
        wrapper.classList.remove('amr-save-error');
        setStatus(wrapper, (config.strings && config.strings.saving) || 'Saving...', 'saving');

        var form = new FormData();
        form.append('action', config.action || 'tiamr_save_setting');
        form.append('nonce', config.nonce || '');
        form.append('option', input.getAttribute('data-option') || '');
        form.append('value', input.checked ? '1' : '0');

        var request = saveFreemiusBetaMode(input).then(function () {
            return fetch(config.ajaxUrl || ajaxurl, {
                method: 'POST',
                credentials: 'same-origin',
                body: form
            }).then(function (response) {
                return response.json();
            });
        });

        var timer = new Promise(function (resolve) {
            window.setTimeout(resolve, isNaN(delay) ? 500 : delay);
        });

        Promise.all([request, timer]).then(function (results) {
            var data = results[0];

            if (!data || !data.success) {
                throw new Error('Save failed');
            }

            input.disabled = false;
            setToggleSavedState(wrapper, input);
            setStatus(wrapper, (config.strings && config.strings.saved) || 'Saved', 'saved');
        }).catch(function () {
            input.checked = previousValue;
            input.disabled = false;
            wrapper.classList.remove('amr-is-saving', 'amr-is-saved-on', 'amr-is-saved-off');
            wrapper.classList.add('amr-save-error');
            setStatus(wrapper, (config.strings && config.strings.failed) || 'Could not save. Please try again.', 'error');
        });
    }

    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('[data-amr-autosave-toggle]').forEach(function (input) {
            var wrapper = input.closest('.amr-modern-toggle');
            setToggleSavedState(wrapper, input);

            input.addEventListener('change', function () {
                var previousValue = !input.checked;
                postSetting(input, previousValue);
            });
        });
    });
})();
