/* modules/free/settings/assets/js/admin.js */
(function (window, $) {
    'use strict';

    var modules = window.noesiaSwaAdminModules || (window.noesiaSwaAdminModules = {});
    var nsVars = window.noesia_admin_vars || {};
    var ajaxUrl = nsVars.ajax_url || '';
    var nonces = {
        reset: nsVars.nonce_reset || ''
    };

    var state = {
        booted: false,
        bound: false,
        inFlight: false,
        settingsTabsReady: false
    };

    var storageKeys = {
        activeSettingsTab: 'noesia_swa_settings_active_tab'
    };

    function hasUi() {
       return $('#btn-simple-reset').length > 0 || $('.noesia-swa-settings-consent-toggle-row').length > 0 || $('[data-noesia-swa-settings-tab]').length > 0;
    }

    function syncConsentToggleRows(context) {
        var $scope = context ? $(context) : $(document);
        var $rows = $scope.is('.noesia-swa-settings-consent-toggle-row')
            ? $scope
            : $scope.find('.noesia-swa-settings-consent-toggle-row');

        $rows.each(function () {
            var $row = $(this);
            var checked = $row.find('input[type="checkbox"]').first().prop('checked');

            $row.toggleClass('noesia-swa-settings-consent-toggle-row--enabled', !!checked);
        });
    }

    function getSettingsTabStorage() {
        try {
            return window.localStorage;
        } catch (error) {
            return null;
        }
    }

    function getSavedSettingsTabId() {
        var storage = getSettingsTabStorage();

        if (!storage) {
            return '';
        }

        return String(storage.getItem(storageKeys.activeSettingsTab) || '');
    }

    function saveSettingsTabId(tabId) {
        var storage = getSettingsTabStorage();

        if (!storage) {
            return false;
        }

        storage.setItem(storageKeys.activeSettingsTab, String(tabId || ''));

        return true;
    }

    function getSettingsTabs() {
        return $('[data-noesia-swa-settings-tab]');
    }

    function getSettingsPanels() {
        return $('[data-noesia-swa-settings-panel]');
    }

    function getDefaultSettingsTabId() {
        var $tabList = $('[data-noesia-swa-settings-tablist="1"]').first();
        var defaultId = $.trim(String($tabList.attr('data-noesia-swa-settings-default-tab') || ''));

        if (defaultId) {
            return defaultId;
        }

        return $.trim(String(getSettingsTabs().first().attr('data-noesia-swa-settings-tab') || ''));
    }

    function activateSettingsTab(tabId) {
        var safeTabId = $.trim(String(tabId || ''));
        var $tabs = getSettingsTabs();
        var $panels = getSettingsPanels();
        var $activeTab;
        var controlsId;

        if (!$tabs.length || !$panels.length) {
            return false;
        }

        if (!$tabs.filter('[data-noesia-swa-settings-tab="' + safeTabId.replace(/"/g, '\"') + '"]').length) {
            safeTabId = getDefaultSettingsTabId();
        }

        if (!safeTabId) {
            return false;
        }

        $tabs.each(function () {
            var $tab = $(this);
            var isActive = String($tab.attr('data-noesia-swa-settings-tab') || '') === safeTabId;

            $tab
                .toggleClass('is-active', isActive)
                .attr('aria-selected', isActive ? 'true' : 'false')
                .attr('tabindex', isActive ? '0' : '-1');
        });

        $panels.each(function () {
            var $panel = $(this);
            var isActive = String($panel.attr('data-noesia-swa-settings-panel') || '') === safeTabId;

            $panel.prop('hidden', !isActive);
        });

        $activeTab = $tabs.filter('[data-noesia-swa-settings-tab="' + safeTabId.replace(/"/g, '\"') + '"]').first();
        controlsId = String($activeTab.attr('aria-controls') || '');

        if (controlsId) {
            $('#' + controlsId).prop('hidden', false);
        }

        saveSettingsTabId(safeTabId);

        return true;
    }

    function initSettingsTabs() {
        var $tabs = getSettingsTabs();
        var targetTabId = getSavedSettingsTabId();

        if (!$tabs.length) {
            state.settingsTabsReady = false;
            return false;
        }

        if (!targetTabId || !$tabs.filter('[data-noesia-swa-settings-tab="' + targetTabId.replace(/"/g, '\"') + '"]').length) {
            targetTabId = getDefaultSettingsTabId();
        }

        state.settingsTabsReady = true;

        return activateSettingsTab(targetTabId);
    }

    function strings() {
        var s = nsVars.strings || {};

        return {
            confirmReset: String(s.confirm_reset || 'Are you sure?'),
            confirmResetFinal: String(s.confirm_reset_final || 'This will permanently wipe plugin data. Continue?'),
            wiping: String(s.wiping || 'Wiping database...'),
            success: String(s.success_reset || 'Success'),
            errorPrefix: String(s.error || 'Error: '),
            serverError: String(s.server_error || 'Server Error')
        };
    }

    function getStatusEl() {
        return $('#simple-reset-status');
    }

    function setStatus(message, type) {
        var $status = getStatusEl();

        if (!$status.length) {
            return;
        }

        $status
            .removeClass('noesia-status-success noesia-status-error noesia-status-working')
            .text(String(message || ''));

        if (type === 'success') {
            $status.addClass('noesia-status-success');
        } else if (type === 'error') {
            $status.addClass('noesia-status-error');
        } else if (type === 'working') {
            $status.addClass('noesia-status-working');
        }
    }

    function setBusy(isBusy) {
        state.inFlight = !!isBusy;
        $('#btn-simple-reset').prop('disabled', !!isBusy);
    }

    function confirmFactoryReset() {
        var i18n = strings();

        if (!window.confirm(i18n.confirmReset)) {
            return false;
        }

        if (!window.confirm(i18n.confirmResetFinal)) {
            return false;
        }

        return true;
    }

    function runFactoryReset() {
        var i18n = strings();
        var request;

        if (!ajaxUrl || !nonces.reset) {
            setStatus(i18n.errorPrefix + 'Missing reset endpoint.', 'error');
            return $.Deferred().reject().promise();
        }

        setBusy(true);
        setStatus(i18n.wiping, 'working');

        request = $.ajax({
            url: ajaxUrl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'noesia_swa_factory_reset',
                nonce: nonces.reset
            }
        });

        request.done(function (response) {
            var message;

            if (response && response.success) {
                setStatus(i18n.success, 'success');

                window.setTimeout(function () {
                    window.location.reload();
                }, 800);

                return;
            }

            if (response && response.data && typeof response.data === 'object' && response.data.message) {
                message = String(response.data.message);
            } else if (response && typeof response.data !== 'undefined') {
                message = String(response.data);
            } else {
                message = 'Unknown error';
            }

            setStatus(i18n.errorPrefix + message, 'error');
            setBusy(false);
        });

        request.fail(function () {
            setStatus(i18n.errorPrefix + i18n.serverError, 'error');
            setBusy(false);
        });

        return request;
    }

    function noesiaSwaFactoryReset() {
        if (state.inFlight) {
            return false;
        }

        if (!confirmFactoryReset()) {
            return false;
        }

        runFactoryReset();
        return true;
    }

    function bindEvents() {
        if (state.bound) {
            return true;
        }

        state.bound = true;

        $(document)
            .off('click.noesiaSwaFactoryReset', '#btn-simple-reset')
            .on('click.noesiaSwaFactoryReset', '#btn-simple-reset', function (e) {
                e.preventDefault();
                e.stopPropagation();
                noesiaSwaFactoryReset();
            })
            .off('change.noesiaSwaSettingsConsentToggle', '.noesia-swa-settings-consent-toggle-row input[type="checkbox"]')
            .on('change.noesiaSwaSettingsConsentToggle', '.noesia-swa-settings-consent-toggle-row input[type="checkbox"]', function () {
                $(this).data('noesiaSwaUserTouched', true);
                syncConsentToggleRows($(this).closest('.noesia-swa-settings-consent-toggle-row'));
            })
            .off('click.noesiaSwaSettingsTabs', '[data-noesia-swa-settings-tab]')
            .on('click.noesiaSwaSettingsTabs', '[data-noesia-swa-settings-tab]', function (e) {
                e.preventDefault();
                activateSettingsTab($(this).attr('data-noesia-swa-settings-tab'));
            });

        return true;
    }

    function boot() {
        if (state.booted) {
            return true;
        }

        if (!hasUi()) {
            return false;
        }

        bindEvents();
        initSettingsTabs();
        syncConsentToggleRows(document);
        state.booted = true;

        return true;
    }

    function init() {
        return boot();
    }

    function onSectionOpen(target) {
        if (String(target || 'settings') !== 'settings') {
            return false;
        }

        init();
        initSettingsTabs();
        syncConsentToggleRows(document);

        return true;
    }

    function onShow() {
        return onSectionOpen('settings');
    }

    function show() {
        return onSectionOpen('settings');
    }

    modules['settings'] = $.extend({}, modules['settings'] || {}, {
        boot: boot,
        init: init,
        onSectionOpen: onSectionOpen,
        onShow: onShow,
        show: show,
        initSettingsTabs: initSettingsTabs,
        activateSettingsTab: activateSettingsTab,
        syncConsentToggleRows: syncConsentToggleRows,
        noesiaSwaFactoryReset: noesiaSwaFactoryReset,
        runFactoryReset: runFactoryReset
    });

    $(boot);
})(window, jQuery);
