/**
 * StoryPosts Admin - Settings Page
 * Handles tab switching and CMB2 conditional field visibility.
 *
 * Data is passed via wp_localize_script() as window.storypostsSettings.
 */
(function ($) {
    'use strict';

    if (typeof storypostsSettings === 'undefined') {
        return;
    }

    $(document).ready(function () {

        var fieldTabs = storypostsSettings.fieldTabs;

        // ── 1. Assign data-tab attributes to each CMB2 row ──────────────────
        $('.cmb-row').each(function () {
            var $row   = $(this);
            var $input = $row.find('input, select, textarea');
            var inputId = $input.attr('id');

            if (inputId) {
                for (var prefix in fieldTabs) {
                    if (inputId.startsWith(prefix)) {
                        $row.attr('data-tab', fieldTabs[prefix]);
                        break;
                    }
                }
            }
        });

        // ── 2. Assign data-tab to section title rows (no inputs) ─────────────
        $('.cmb-row').each(function () {
            var $row = $(this);
            if ($row.attr('data-tab')) return;

            var text = $row.text().toLowerCase();
            if (text.indexOf('global upload') !== -1 || text.indexOf('style settings') !== -1) {
                $row.attr('data-tab', 'general');
            } else if (text.indexOf('admin stories') !== -1) {
                $row.attr('data-tab', 'collection-stories');
            } else if (text.indexOf('user stories') !== -1) {
                $row.attr('data-tab', 'user-stories');
            } else if (text.indexOf('blog stories') !== -1) {
                $row.attr('data-tab', 'blog-stories');
            } else if (text.indexOf('product stories') !== -1) {
                $row.attr('data-tab', 'product-stories');
            }
        });

        // ── 3. Tab switching ─────────────────────────────────────────────────
        function switchTab(target) {
            var tabName = target.replace('#tab-', '');

            $('.nav-tab').removeClass('nav-tab-active');
            $('.nav-tab[href="' + target + '"]').addClass('nav-tab-active');

            $('.cmb-row').each(function () {
                var $row   = $(this);
                var rowTab = $row.attr('data-tab');

                if (rowTab === tabName) {
                    var conditionMet = $row.data('condition-met');
                    if (conditionMet === false) {
                        $row.hide();
                    } else {
                        $row.show();
                    }
                    $row.find('input, select, textarea').trigger('change.conditionals');
                } else if (rowTab) {
                    $row.hide();
                }
            });
        }

        // ── 4. CMB2-aware conditional field logic ───────────────────────────
        function initConditionals() {
            $('[data-conditional-id]').each(function () {
                var $field    = $(this);
                var targetId  = $field.data('conditional-id');
                var targetVal = $field.data('conditional-value');
                var $row      = $field.closest('.cmb-row');
                var $target   = $('#' + targetId);

                // Broad selector fallbacks for CMB2 multicheck / radio groups
                if (!$target.length) {
                    $target = $('input[name^="' + targetId + '"]');
                }
                if (!$target.length) {
                    $target = $('input[name="' + targetId + '"]');
                }

                function check() {
                    var currentVal;
                    if ($target.is(':checkbox')) {
                        currentVal = $target.is(':checked') ? 'on' : 'off';
                    } else if ($target.is(':radio')) {
                        currentVal = $target.filter(':checked').val();
                    } else {
                        currentVal = $target.val();
                    }

                    var activeTab = $('.nav-tab-active').attr('href').replace('#tab-', '');
                    var rowTab    = $row.attr('data-tab');

                    if (currentVal == targetVal) { // intentional == for loose matching
                        $row.data('condition-met', true);
                        if (!rowTab || rowTab === activeTab) {
                            $row.show();
                        }
                    } else {
                        $row.data('condition-met', false);
                        $row.hide();
                    }
                }

                $target.on('change.conditionals', check);
                check(); // initial evaluation
            });
        }

        // ── 5. Boot ──────────────────────────────────────────────────────────
        initConditionals();        // must run BEFORE switchTab so condition-met is seeded
        switchTab('#tab-general'); // open first tab

        $('.nav-tab').on('click', function (e) {
            e.preventDefault();
            switchTab($(this).attr('href'));
        });
    });

})(jQuery);
