jQuery(function ($) {

    // === Settings tabs (Divi-5 style) ===
    // Contract:
    // - One .dbdb-settings-tabs container per page.
    // - Top tabs:   a.dbdb-settings-tab-link[data-top]
    // - Sub tabs:   a.dbdb-settings-subtab-link[data-top][data-sub]
    // - Panels:     .dbdb-settings-panel[data-top][data-sub]
    //
    // Behavior:
    // - Selecting a top tab shows its subtab row, then selects the first subtab (or the saved/previously active one)
    // - Selecting a subtab shows exactly one matching panel
    // - State is stored in localStorage (non-critical; falls back to defaults if unavailable)

    function dbdbStorageKey(suffix) {
        return 'dbdb-settings-' + suffix;
    }

    function dbdbSafeGet(key) {
        try {
            return window.localStorage ? window.localStorage.getItem(key) : null;
        } catch (e) {
            return null;
        }
    }

    function dbdbSafeSet(key, value) {
        try {
            if (window.localStorage) {
                window.localStorage.setItem(key, value);
            }
        } catch (e) {
            // ignore
        }
    }

    // jQuery attribute selectors break if the value contains certain characters.
    // WordPress slugs are usually safe, but keep this robust.
    function dbdbEscapeAttrSelector(val) {
        if (typeof val === 'undefined' || val === null) {
            return '';
        }
        // Prefer native CSS.escape when available.
        if (window.CSS && typeof window.CSS.escape === 'function') {
            return window.CSS.escape(String(val));
        }
        // Minimal escaping fallback.
        return String(val).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
    }

    function dbdbActivatePanel($root, top, sub) {
        // Hide all panels
        $root.find('.dbdb-settings-panel').hide();

        // Deactivate all subtabs
        $root.find('.dbdb-settings-subtab-link').attr('aria-selected', 'false').closest('li').removeClass('db-settings-box-tab-active');

        // Activate selected subtab
    var topSel = dbdbEscapeAttrSelector(top);
    var subSel = dbdbEscapeAttrSelector(sub);
    var $subLink = $root.find('.dbdb-settings-subtab-link[data-top="' + topSel + '"][data-sub="' + subSel + '"]');
        $subLink.attr('aria-selected', 'true').closest('li').addClass('db-settings-box-tab-active');

        // Show matching panel
    $root.find('.dbdb-settings-panel[data-top="' + topSel + '"][data-sub="' + subSel + '"]').show();

        dbdbSafeSet(dbdbStorageKey('active-top'), top);
        dbdbSafeSet(dbdbStorageKey('active-sub-' + top), sub);
    }

    function dbdbActivateTop($root, top) {
        // Deactivate all top tabs
        $root.find('.dbdb-settings-tab-link').attr('aria-selected', 'false').closest('li').removeClass('db-settings-box-tab-active');

        // Activate selected top tab
        var topSel = dbdbEscapeAttrSelector(top);
        var $topLink = $root.find('.dbdb-settings-tab-link[data-top="' + topSel + '"]');
        $topLink.attr('aria-selected', 'true').closest('li').addClass('db-settings-box-tab-active');

        // Show only this top's subtab row
        $root.find('.dbdb-settings-sub-tabs').hide();
        var $subRow = $root.find('.dbdb-settings-sub-tabs[data-top="' + topSel + '"]');
        // Fallback: if selector didn't match (edge-case attribute selector), locate by data() comparison.
        if (!$subRow.length) {
            $subRow = $root.find('.dbdb-settings-sub-tabs').filter(function () {
                return $(this).data('top') == top;
            });
        }
        $subRow.show();

        // Decide sub tab to show
        var savedSub = dbdbSafeGet(dbdbStorageKey('active-sub-' + top));
        var $firstSub = $subRow.find('.dbdb-settings-subtab-link').first();
    var savedSubSel = dbdbEscapeAttrSelector(savedSub);
    var sub = savedSub && $subRow.find('.dbdb-settings-subtab-link[data-sub="' + savedSubSel + '"]').length ? savedSub : ($firstSub.data('sub') || '');

        if (sub) {
            dbdbActivatePanel($root, top, sub);
        } else {
            // No subtabs/panels for this group; just hide all panels.
            $root.find('.dbdb-settings-panel').hide();
        }

        dbdbSafeSet(dbdbStorageKey('active-top'), top);
    }

    function dbdbInitSettingsTabs() {
        $('.dbdb-settings-tabs').each(function () {
            var $root = $(this);
            var defaultTop = $root.data('default-top') || '';
            var defaultSub = $root.data('default-sub') || '';

            var savedTop = dbdbSafeGet(dbdbStorageKey('active-top'));
            var top = savedTop && $root.find('.dbdb-settings-tab-link[data-top="' + savedTop + '"]').length ? savedTop : defaultTop;
            if (!top) {
                top = $root.find('.dbdb-settings-tab-link').first().data('top') || '';
            }

            dbdbActivateTop($root, top);

            // If we have a default sub for the default top and nothing stored yet, apply it.
            // (We do it after activating top, so the sub row exists.)
            if (top === defaultTop && defaultSub && !$root.find('.dbdb-settings-subtab-link[data-top="' + top + '"][data-sub="' + defaultSub + '"]').closest('li').hasClass('db-settings-box-tab-active')) {
                if ($root.find('.dbdb-settings-subtab-link[data-top="' + top + '"][data-sub="' + defaultSub + '"]').length) {
                    dbdbActivatePanel($root, top, defaultSub);
                }
            }
        });
    }

    $(document).on('click', '.dbdb-settings-tab-link', function (e) {
        e.preventDefault();
        var $root = $(this).closest('.dbdb-settings-tabs');
        var top = $(this).data('top');
        dbdbActivateTop($root, top);
    });

    $(document).on('click', '.dbdb-settings-subtab-link', function (e) {
        e.preventDefault();
        var $root = $(this).closest('.dbdb-settings-tabs');
        var top = $(this).data('top');
        var sub = $(this).data('sub');
        dbdbActivatePanel($root, top, sub);
    });

    // Initialize tabs before legacy code runs.
    dbdbInitSettingsTabs();

    /* Define useful functions */
    $.fn.expand = function () { this.each(function () { $(this).slideDown(200); }); return this; }
    $.fn.collapse = function () { this.each(function () { $(this).slideUp(200); }); return this; }
    $.fn.section = function () { return this.next().next(); }
    $.fn.subheadings = function () { return this.nextUntil(".wtf-topheading", "h3"); }
    $.fn.isopen = function () { return this.filter(function () { return ($(this).next().val() == 1); }); }
    $.fn.opened = function () { return this.isopen().section(); }

    // === Legacy accordion (disabled when using tabs) ===
    // Keep the old code in place for backwards compatibility on pages that still output .wtf-section-head markup.
    if ($('.dbdb-settings-tabs').length === 0) {
        /* Show currently expanded sections */
        $('.wtf-topheading').opened().show().subheadings().show().opened().show();

        /* Add opened / closed classes */
        $('.wtf-section-head').each(function () {
            var section = $(this).section();
            if (section.is(":visible")) {
                $(this).addClass('dbdb-settings-section-opened');
            } else {
                $(this).addClass('dbdb-settings-section-closed');
            }
        });

        /* Handle clicks on section headings */
        $(".wtf-section-head").click(function () {
            var section = $(this).section();
            if (section.is(":visible")) { // block is open, so close it
                section.collapse(); // close block
                if ($(this).hasClass('wtf-topheading')) { // hide subsections
                    $(this).subheadings().collapse().opened().collapse();
                }
                $(this).removeClass('dbdb-settings-section-opened');
                $(this).addClass('dbdb-settings-section-closed');
            } else {
                section.expand(); // open block
                if ($(this).hasClass('wtf-topheading')) { // show subsections
                    $(this).subheadings().expand().opened().expand();
                }
                $(this).removeClass('dbdb-settings-section-closed');
                $(this).addClass('dbdb-settings-section-opened');
            }

            // record state in hidden input
            var hiddenInput = $(this).next();
            var newState = (hiddenInput.val() == '1') ? 0 : 1;
            hiddenInput.val(newState);

            // rotate "expanded" icon
            var expandedIcon = $(this).children(':first');
            expandedIcon.toggleClass('rotated');
        });
    }

    // initialize the colorpickers
    if ($.fn.wpColorPicker) {
        $('.wtf-colorpicker').wpColorPicker();
    }

});

// Image picker 
jQuery(document).ready(function ($) {

    // handle image picker thumbnails
    $(document).on('change', '.wtf-imagepicker', function () {
        $(this).next().next('.wtf-imagepicker-thumb').attr('src', $(this).val());
    });

});

// Icon picker - pass click on .dbdb-icon-picker-wrapper to the hidden media library button
jQuery(document).ready(function ($) {
    $(document).on('click', '.dbdb-icon-picker-wrapper span.wtf-imagepicker', function () {
        $(this).closest('.dbdb-icon-picker-wrapper').find('.wtf-imagepicker-btn').click();
    });
    // Prevent the click from being passed to the parent element
    $(document).on('click', '.dbdb-icon-picker-wrapper .wtf-imagepicker-btn', function (e) {
        e.stopPropagation();
    });
    // Prevent clicks on the .wtf-imagepicker input from being passed to the parent element
    $(document).on('click', '.dbdb-icon-picker-wrapper input.wtf-imagepicker', function (e) {
        e.stopPropagation();
    });
});

// Media uploader
jQuery(document).ready(function ($) {

    if (typeof wp === 'undefined' || !wp.media || !wp.media.editor) {
        return;
    }

    // Override the "Insert into Post" button text
    if (typeof _wpMediaViewsL10n != 'undefined') {
        _wpMediaViewsL10n.insertIntoPost = 'Use Image';
    }

    var _custom_media = true;
    var _orig_send_attachment = wp.media.editor.send.attachment;

    // Display media when choose image button clicked
    //$('.upload-button').click(function (e) {
    $(document).on('click', '.upload-button', function (e) {

        //var send_attachment_bkp = wp.media.editor.send.attachment;
        var button = $(this);
        var input = button.prev('input');
        _custom_media = true;

        // Return handler
        wp.media.editor.send.attachment = function (props, attachment) {

            // Return the image URL
            var size = props.size;
            var att = attachment.sizes && attachment.sizes[size] ? attachment.sizes[size] : attachment;
            if (_custom_media && att && att.url) { input.val(att.url); }
            else { _orig_send_attachment.apply(this, [props, attachment]); }

            // Update the thumbnail
            $('.wtf-imagepicker').change();
        }

        // Show the editor
        wp.media.editor.open(button);
    });

    $('.add_media').on('click', function () { _custom_media = false; });

});
