(function ($) {
    'use strict';

    function getContentMode() {
        var $mode = $('#maca_content_mode');
        return $mode.length ? $mode.val() : ($('.maca-settings-sections').data('content-mode') || 'files');
    }

    function tabVisibleForMode($link, mode) {
        var modes = ($link.data('content-modes') || '').toString().split(',');
        return modes.indexOf(mode) !== -1;
    }

    function updateTabNavVisibility() {
        var mode = getContentMode();
        var $active = $('.maca-settings-tabs .nav-tab-active');
        var activeHidden = $active.length && !$active.is(':visible');

        $('.maca-settings-tabs .nav-tab').each(function () {
            var $link = $(this);
            var show = tabVisibleForMode($link, mode);
            $link.toggle(show);
            if (!show) {
                $link.removeClass('nav-tab-active');
            }
        });

        if (activeHidden) {
            var $first = $('.maca-settings-tabs .nav-tab:visible').first();
            if ($first.length) {
                window.location.href = $first.attr('href');
            }
        }
    }

    function showSettingsTab(tab) {
        var mode = getContentMode();
        $('.maca-settings-sections').attr('data-active-tab', tab);
        $('.maca-settings-tab-panel').each(function () {
            var $panel = $(this);
            var isActive = $panel.data('settings-tab') === tab;
            var modeOk = true;
            if ($panel.hasClass('maca-setting-dishes-only') && mode !== 'dishes') {
                modeOk = false;
            }
            if ($panel.hasClass('maca-setting-files-only') && mode !== 'files') {
                modeOk = false;
            }
            $panel.toggle(isActive && modeOk);
        });
        $('#maca_settings_tab').val(tab);
    }

    window.macaMenulistRefreshSettingsPanels = function () {
        var tab = $('.maca-settings-sections').data('active-tab');
        updateTabNavVisibility();
        showSettingsTab(tab);
    };

    $(function () {
        var $sections = $('.maca-settings-sections');
        if (!$sections.length) {
            return;
        }

        var initialTab = $sections.data('active-tab');
        showSettingsTab(initialTab);
        updateTabNavVisibility();

        $('#maca_content_mode').on('change', function () {
            window.macaMenulistRefreshSettingsPanels();
        });

        function updateOfferingModeRows() {
            var mode = $('#maca_offering_mode').val();
            var showTakeaway = mode === 'takeaway_only';
            $('.maca-settings-takeaway-row').toggle(showTakeaway);
        }

        $('#maca_offering_mode').on('change', updateOfferingModeRows);
        updateOfferingModeRows();

        $('.maca-settings-tabs .nav-tab').on('click', function () {
            var tab = $(this).data('settings-tab');
            if (tab) {
                $('#maca_settings_tab').val(tab);
            }
        });
    });
})(jQuery);
