// Main Model/Popup **************************
jQuery(document).ready(function ($) {
    // === Cached elements ===
    var $modal = $('#gam-setup-modal');
    var $openInline = $('#gam-open-setup-inline');
    var $closeBtn = $modal.find('.gam-modal-close');
    var $form = $('#gam-setup-form');
    var $useDefault = $('#gam_use_default');
    var $inputs = $('#gam_client_id, #gam_client_secret, #gam_redirect_uri');
    var $status = $('#gam-setup-status');
    var $status2 = $('#gam-setup-status2');
    var $syncBtn = $('#gam-sync-api');
    var $syncStatus = $('#gam-sync-status');
    var $saveConfigBtn = $('#gam-save-config');
    var $revokeBtn = $('#gam-revoke-default');
    var cfg = window.gam_ads_ad_manager_and_ad_exchange || {};

    // === Modal helpers ===
    function showModal() { $modal.show(); }
    function hideModal() { $modal.hide(); }

    // === Steps Animation ===
    function CallWelcomeBox() {
        setStep(1);
        const welcomeBox = $('.welcome_box');
        welcomeBox.css('scale', '0');
        setTimeout(() => welcomeBox.hide(), 1000);
        window.localStorage.setItem('GAMAdInserterWelcomeBoxShowed', 'true');
    }
    if (window.localStorage.getItem('GAMAdInserterWelcomeBoxShowed')) {
        $('.welcome_box').hide();
    }
    $('#startsetup').on('click', CallWelcomeBox);

    // === Auto-open modal if plugin not configured ===
    const GAMADSMBAIcurrentTab = new URLSearchParams(window.location.search).get('tab');
    if (cfg.has_config !== '1' && GAMADSMBAIcurrentTab != "settings") {
        setTimeout(function () { showModal(); }, 300);
    }

    // === Modal open/close buttons ===
    $openInline.on('click', function () { showModal(); });
    $closeBtn.on('click', function () { hideModal(); });

    // === Eye toggle for password visibility ===
    $(document).on('click', '.gam-eye-btn, .gam-toggle-visibility', function (e) {
        e.preventDefault();
        var target = $(this).data('target') ? $($(this).data('target')) : $(this).siblings('input');
        if (target.length) {
            var type = target.attr('type') === 'password' ? 'text' : 'password';
            target.attr('type', type);
        }
    });

    // === Use default configs checkbox toggle ===
    $useDefault.on('change', function () {
        var checked = $(this).is(':checked');
        if (checked) {
            $inputs.val('').prop('disabled', true).attr('placeholder', 'Using default configs');
            $('#fadeBoxingIfcheck').addClass('defaultChecked');
        } else {
            $('#fadeBoxingIfcheck').removeClass('defaultChecked');
            $inputs.prop('disabled', false).attr('placeholder', '');
        }
    });

    $(".openConfigBoxButton").on('click', function () {
        $(".openConfigBoxButton.openbtn").removeClass('openbtn');
        $(".form-setup-box.onpen-config-box").removeClass('onpen-config-box');

        $(this).closest(".form-setup-box").addClass('onpen-config-box');
        $(this).addClass('openbtn');
    });

    $('#gam-use-default-config').on('change', function () {
        var disabled = $(this).is(':checked');
        $('#gam-config-section input[type="text"], #gam-config-section input[type="password"]').prop('disabled', disabled);
        if (disabled) {
            $('#gam-client-id, #gam-client-secret, #gam-redirect-uri').val('');
        }
        $(".setting_form_box").eq(1).toggleClass("defaultChecked");
    });

    // === Save (modal form submission) ===
    $form.on('submit', function (e) {
        e.preventDefault();
        if (!$useDefault.is(':checked') && (!$('#gam_client_id').val() || !$('#gam_client_secret').val() || !$('#gam_redirect_uri').val())) {
            $status.text('Fields are required to continue!');
            $status2.text('Fields are required to continue!');
            return;
        }
        $status.text('Saving…');
        $status2.text('Saving…');

        var data = {
            action: 'gamadsmbai_save_config',
            nonce: cfg.nonce,
            use_default: $useDefault.is(':checked') ? '1' : '0',
            client_id: $('#gam_client_id').val(),
            client_secret: $('#gam_client_secret').val(),
            redirect_uri: $('#gam_redirect_uri').val(),
            site_url: window.location.href
        };

        $.post(cfg.ajaxUrl, data)
            .done(function (resp) {
                if (resp && resp.success) {
                    $status.text(resp.data.message || 'Saved');
                    $status2.text(resp.data.message || 'Saved');
                    window._0xGamAdsCngs = resp.data.configs;
                    // setTimeout(function () { location.reload(); }, 800);
                    $(".gam-modal-inner-gamadsmbai").show();
                    $form.hide();
                    $('#skipfornow').on('click', function () { hideModal(); });
                    $("#gam-redirect-link").attr(
                        "href",
                        "https://accounts.google.com/o/oauth2/v2/auth"
                        + "?response_type=code"
                        + "&client_id=" + encodeURIComponent(_0xGamAdsCngs.cid)
                        + "&redirect_uri=" + encodeURIComponent(_0xGamAdsCngs.rui)
                        + "&scope=" + encodeURIComponent("https://www.googleapis.com/auth/admanager")
                        + "&access_type=offline&prompt=consent"
                    );
                    setStep(2);
                    $("#codepaste").css('opacity', '1');
                } else {
                    var m = (resp && resp.data && resp.data.message) ? resp.data.message : 'Error saving';
                    $status.text(m);
                    $status2.text(m);
                }
            })
            .fail(function (xhr) {
                var msg = 'Request failed';
                if (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                    msg = xhr.responseJSON.data.message;
                }
                $status.text(msg);
                $status2.text(msg);
            });
    });

    // === Save (inline settings page button) ===
    $saveConfigBtn.on('click', function (e) {
        e.preventDefault();
        var useDefault = $('#gam-use-default-config').is(':checked') ? '1' : '0';

        $.post(cfg.ajaxUrl, {
            action: 'gamadsmbai_save_config',
            nonce: cfg.nonce,
            use_default: useDefault,
            client_id: $('#gam-client-id').val(),
            client_secret: $('#gam-client-secret').val(),
            redirect_uri: $('#gam-redirect-uri').val(),
            site_url: window.location.href
        })
            .done(function (res) {
                alert(res.data ? res.data.message : 'Saved');
                location.reload();
            })
            .fail(function (xhr) {
                alert('Save failed: ' + (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message ? xhr.responseJSON.data.message : 'server error'));
            });
    });

    // === Sync from API (modal + settings page) ===
    $syncBtn.on('click', function (e) {
        e.preventDefault();
        $syncStatus.text('Syncing…');
        $.post(cfg.ajaxUrl, {
            action: 'gamadsmbai_sync_config',
            nonce: cfg.nonce,
            site_url: window.location.href
        })
            .done(function (resp) {
                if (resp && resp.success) {
                    $syncStatus.text(resp.data.message || 'Synced');
                    setTimeout(function () { location.reload(); }, 800);
                } else {
                    var m = (resp && resp.data && resp.data.message) ? resp.data.message : 'Sync failed';
                    $syncStatus.text(m);
                }
            })
            .fail(function (xhr) {
                var msg = 'Request failed';
                if (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                    msg = xhr.responseJSON.data.message;
                }
                $syncStatus.text(msg);
            });
    });

    // === Revoke default config ===
    $revokeBtn.on('click', function (e) {
        e.preventDefault();
        if (!confirm('Clear default config?')) return;

        $.post(cfg.ajaxUrl, {
            action: 'gamadsmbai_revoke_default',
            nonce: cfg.nonce
        })
            .done(function (res) {
                alert(res.data ? res.data.message : 'Revoked');
                location.reload();
            })
            .fail(function () {
                alert('Revoke failed');
            });
    });

    // ToolTip
    const $tooltip = $('#configinfoshare');
    const $tooltips = $('#allinfoshare');
    $('.infoclassconfigs').on({
        mouseenter: function (e) {
            const info = $(this).data('info');
            if (!info) return;

            const offset = $(this).offset();
            const height = $(this).outerHeight();
            const width = $(this).outerWidth();

            $tooltip
                .text(info)
                .css({
                    top: offset.top + height + 7 + 'px', // below element
                    left: offset.left + 'px'
                })
                .show();
            $tooltips
                .text(info)
                .css({
                    top: offset.top + height + 7 + 'px', // below element
                    left: offset.left + 'px'
                })
                .show();
        },
        mouseleave: function () {
            $tooltip.hide().text('');
            $tooltips.hide().text('');
        }
    });
});
// Main Model/Popup ************************** END


// Create Ads Plus Others Page **************************
jQuery(document).ready(function ($) {

    // AD FIELDS Script
    let customAdCodeEditorMb;
    let codeEditorInitialized = false;

    // AdUnit Filter Varliables
    let userPastedPassBackScript;

    /* -------- Validate GPT Size Structure -------- */
    function isValidSizeStructure(size) {
        if (size === "fluid") return true;
        if (Array.isArray(size)) {
            // Single size like [300,250]
            if (
                size.length === 2 &&
                Number.isInteger(size[0]) &&
                Number.isInteger(size[1])
            ) {
                return true;
            }
            // Multiple sizes
            return size.every(s => isValidSizeStructure(s));
        }
        return false;
    }

    /* -------- Parse Sizes Safely -------- */
    function parseSizes(raw) {
        // Normalize quotes
        let safe = raw.replace(/'/g, '"').trim();
        try {
            const parsed = JSON.parse(safe);
            if (isValidSizeStructure(parsed)) {
                return parsed;
            }
            return null;
        } catch (e) {
            return null;
        }
    }

    /* -------- Safe Argument Splitter -------- */
    function splitTopLevelArgs(str) {
        let args = [];
        let current = '';
        let depth = 0;
        let inString = false;
        let stringChar = '';
        for (let i = 0; i < str.length; i++) {
            const char = str[i];
            if ((char === '"' || char === "'") && str[i - 1] !== '\\') {
                if (!inString) {
                    inString = true;
                    stringChar = char;
                } else if (stringChar === char) {
                    inString = false;
                }
            }
            if (!inString) {
                if (char === '[') depth++;
                if (char === ']') depth--;
                if (char === ',' && depth === 0) {
                    args.push(current.trim());
                    current = '';
                    continue;
                }
            }
            current += char;
        }
        if (current.trim()) {
            args.push(current.trim());
        }
        return args;
    }

    function extractGPTSlot(code) {
        const defineMatch = code.match(
            /googletag\.(defineSlot|defineOutOfPageSlot)\s*\(([\s\S]*?)\)\s*\./
        );
        if (!defineMatch) return null;
        const argsString = defineMatch[2].trim();
        const args = splitTopLevelArgs(argsString);
        if (args.length < 2) return null;
        const slotPath = args[0].replace(/^['"]|['"]$/g, '');
        const sizesRaw = args[1].trim();
        let sizes = parseSizes(sizesRaw);
        return {
            slot: slotPath,
            sizes: sizes
        };
    }

    // Filter Ad Unit And Sizes Step Code
    function resetFilterSteps() {
        $('#indicator_text').html('');
    }
    function FilterStepsLoader(arrg) {
        if (arrg === "show") {
            $('#filteradunit_process_indicatorsvg').addClass('show');
        } else if (arrg === "hide") {
            $('#filteradunit_process_indicatorsvg').removeClass('show');
        }
    }
    function addFilterStep(text, status = 'loading') {
        const step = $('<span class="filter-step"></span>')
            .addClass(status)
            .text(text);
        $('#indicator_text').append(step);
        return step;
    }
    function markStepSuccess(stepElement) {
        stepElement
            .removeClass('loading')
            .addClass('success')
            .append('<span class="check">✓</span>');
    }
    function markStepError(stepElement, message) {
        stepElement
            .removeClass('loading')
            .addClass('error')
            .text(message);
    }

    function initializeCustomCodeEditor() {
        if (codeEditorInitialized) return;
        if ($('#gam_custom_code').length) {
            const editorWrapper = wp.codeEditor.initialize('gam_custom_code', {
                codemirror: {
                    mode: 'htmlmixed',
                    lineNumbers: true,
                    lineWrapping: true,
                    indentUnit: 2,
                    tabSize: 2,
                    theme: 'darcula'
                }
            });
            customAdCodeEditorMb = editorWrapper.codemirror;
        }


        // AdUnit Filter TextArea
        if ($('#manual_mode_adunit_filter_textbox').length) {
            const adUnitFilterWrapper = wp.codeEditor.initialize('manual_mode_adunit_filter_textbox', {
                codemirror: {
                    mode: 'htmlmixed',
                    lineNumbers: true,
                    lineWrapping: true,
                    indentUnit: 2,
                    tabSize: 1,
                    theme: 'darcula'
                }
            });
            userPastedPassBackScript = adUnitFilterWrapper.codemirror;
        }
        // Delay binding slightly to ensure editor ready
        setTimeout(function () {
            if (userPastedPassBackScript) {
                let filterTypingTimer = null;
                let filterAdunitError = false;
                let filterSizeError = false;
                userPastedPassBackScript.on('change', function (instance) {
                    clearTimeout(filterTypingTimer);
                    // Debounce Change
                    filterTypingTimer = setTimeout(function () {
                        resetFilterSteps();
                        // Step 1
                        FilterStepsLoader('show');
                        const stepFiltering = addFilterStep('Filtering..');
                        const codeEditorvalue = instance.getValue();
                        if (!codeEditorvalue) {
                            FilterStepsLoader('hide');
                            resetFilterSteps();
                            return;
                        }
                        const result = extractGPTSlot(codeEditorvalue);
                        if (!result) {
                            console.warn("No GPT slot Detected");
                            setTimeout(() => { markStepError(stepFiltering, '! No GPT Slot Detected'); FilterStepsLoader('hide'); }, 500);
                            return;
                        }

                        // Step 2
                        const stepSlot = addFilterStep('Valid Slot');
                        console.log("Valid GPT Slot Detected");
                        if (!result.slot) {
                            setTimeout(() => { markStepError(stepSlot, '! Invalid Ad-Unit'); }, 500);
                            filterAdunitError = true;
                        } else {
                            setTimeout(() => markStepSuccess(stepSlot), 500);
                            filterAdunitError = false;
                        }

                        // Step 3
                        const stepSizes = addFilterStep('Valid Sizes');
                        const formattedSizes = [];
                        if (!result.sizes) {
                            console.warn("Invalid size format");
                            setTimeout(() => { markStepError(stepSizes, '! Invalid Size Format'); }, 1000);
                            filterSizeError = true;
                        } else {
                            console.log("Valid GPT Size Detected");
                            let sizesArray = result.sizes;
                            // normalize
                            if (!Array.isArray(sizesArray)) {
                                sizesArray = [sizesArray];
                            }
                            // if single size like [300,250]
                            if (Array.isArray(sizesArray) && typeof sizesArray[0] === 'number') {
                                sizesArray = [sizesArray];
                            }
                            function formatGPTSize(size) {
                                if (size === 'fluid') return 'fluid';
                                if (Array.isArray(size) && size.length === 2) {
                                    const [w, h] = size;
                                    if (Number.isInteger(w) && Number.isInteger(h)) {
                                        return `${w}x${h}`;
                                    }
                                }
                                return null;
                            }
                            sizesArray.forEach(size => {
                                const formatted = formatGPTSize(size);
                                if (!formatted) return;
                                formattedSizes.push(formatted);
                                if (!($("#gam_ad_sizes").val() || '').includes(formatted)) {
                                    addTag(formatted);
                                }
                            });
                            if (formattedSizes.length === 0) {
                                setTimeout(() => { markStepError(stepSizes, 'Empty size format'); }, 1000);
                            }
                            $("#gam_ad_sizes").val(formattedSizes.join(','));
                            setTimeout(() => markStepSuccess(stepSizes), 1000);
                            filterSizeError = false;
                        }

                        // Step 4
                        const stepDone = addFilterStep('Filtered');

                        if (filterAdunitError || filterSizeError) {
                            setTimeout(() => { markStepError(stepDone, 'Error Marked'); FilterStepsLoader('hide'); }, 1500);
                            return;
                        }

                        $('input[name=gam_ad_unit]').val(result.slot);

                        setTimeout(() => markStepSuccess(stepDone), 1500);
                        setTimeout(() => {
                            $('#gam_ad_unit').trigger('input'); resetFilterSteps(); FilterStepsLoader('hide');
                        }, 2000);
                    }, 1500);
                });
            }
        }, 100);

        // Comman For Both
        setTimeout(() => {
            if (customAdCodeEditorMb) {
                customAdCodeEditorMb.refresh();
            }
            if (userPastedPassBackScript) {
                userPastedPassBackScript.refresh();
            }
            const gutter = document.querySelectorAll(".CodeMirror-gutter.CodeMirror-linenumbers");
            if (gutter.length) {
                gutter.forEach(gtd => {
                    gtd.style.minWidth = "29px";
                });
            };
        }, 200);

        codeEditorInitialized = true;
    }

    initializeCustomCodeEditor();

    // ADD-NEW-AD
    // Run after DOM is ready
    // jQuery(document).ready(function ($) {
    const adTypeItems = $(".gam-ad-type-item");
    const adTypeInput = $("#gam_selected_ad_type");
    const adUnitWrapper = $("#gam-ad-unit-wrapper");
    const customCodeWrapper = $("#gam-custom-code-wrapper");
    const AdunitFilterCodeEditor = $(".manual_mode_adunit_filter_block");
    const adPositionSelect = $("#gam_ad_position");
    const showOnceCheckbox = $("#show_once");
    const formArea = $(".gam-ad-form-area");
    const blocks = $("#blocks");

    function toggleCustomField() {
        if (adPositionSelect.val() === 'custom') {
            $("#custom_position_field").show();
        } else {
            $("#custom_position_field").hide();
            $("#custom_ad_position").val('');
        }
    }

    // Set initial visibility for custom position field
    toggleCustomField();

    adPositionSelect.on('change', toggleCustomField);

    const adPosition = $('#gam_ad_position');
    const paragraphField = $('#paragraph_position_field');
    const customField = $('#custom_position_field');

    function toggleFields() {
        const val = $('#gam_ad_position').val();
        if (['between_posts', 'before_paragraph', 'after_paragraph', 'before_image', 'after_image'].includes(val)) {
            paragraphField.show();
            customField.hide();
        } else if (val === 'custom') {
            customField.show();
            paragraphField.hide();
        } else {
            paragraphField.hide();
            customField.hide();
        }
        toggleAlignmentOptions();
    }

    adPosition.on('change', toggleFields);
    toggleFields(); // run on page load

    function toggleAlignmentOptions() {
        var adType = $('#gam_selected_ad_type').val();
        var $alignmentSelect = $("#gam_ad_alignment");

        if (adType === "anchor" || adType === "sticky") {
            $alignmentSelect.find("option").hide();
            $alignmentSelect.find("option[data-anchor-only]").each(function () { $(this).show(); });
        } else if (adType === "floater") {
            $alignmentSelect.find("option").hide();
            $alignmentSelect.find("option[value=left]").show();
            $alignmentSelect.find("option[value=right]").show();
        } else if ($('#gam_ad_position').val() === 'custom') {
            $alignmentSelect.find("option").hide();
            $alignmentSelect.find("option[data-custom-postion-only]").each(function () { $(this).show(); });
        } else if (adType === "popup") {
            $alignmentSelect.find("option").hide();
            $alignmentSelect.find("option[data-popupad-trigger-only]").each(function () { $(this).show(); });
        } else {
            // // if previously selected "top/bottom", reset to default
            // if ($(this).is(":selected")) {
            //     $alignmentSelect.val("");
            // }
            $alignmentSelect.find("option").show();
            $alignmentSelect.find("option[data-anchor-only]").each(function () { $(this).hide(); });
            $alignmentSelect.find("option[data-custom-postion-only]").each(function () { $(this).hide(); });
            $alignmentSelect.find("option[data-popupad-trigger-only]").each(function () { $(this).hide(); });
        }

    }

    // Run on load
    toggleAlignmentOptions();

    const searchInput = $("#gam-size-search");
    const dropdown = $(".gam-sizes-dropdown");

    // 🔹 Show/hide size section depending on Ad Unit value
    function toggleSizeWrapper() {
        if ($("#gam_ad_unit").val() !== "") {
            $("#gam-size-wrapper").show();
            // Close Filter Ad unit Block
            $('.open_filter_script_block').show();
            $('.manual_mode_adunit_wrapper').hide();
        } else {
            $("#gam-size-wrapper").hide();
            // Close Filter Ad unit Block
            $('.open_filter_script_block').hide();
            $('.manual_mode_adunit_wrapper').show();
        }
    }
    toggleSizeWrapper();

    $('#open_filter_code_editor').on('click', function () {
        $('.manual_mode_adunit_wrapper').show();
        $('.open_filter_script_block').hide();
    });



    let preSelected = ($("#gam_ad_sizes").val() || "").split(",").map(s => s.trim()).filter(Boolean);
    preSelected.forEach(size => addTag(size));

    $("#gam_ad_unit").on("focus click input", function () {
        if ($(this).val() && ($("#gam_selected_ad_type").val() !== 'interstitial' && $("#gam_selected_ad_type").val() !== 'anchor' && $("#gam_selected_ad_type").val() !== 'rewarded')) {
            toggleSizeWrapper();
        }
    });

    // 🔹 Toggle dropdown
    searchInput.on("focus click", function () {
        dropdown.show();
    });
    $(document).on("click", function (e) {
        if (!$(e.target).closest(".gam-sizes-select").length) {
            dropdown.hide();
        }
    });

    // 🔹 Filter dropdown options
    searchInput.on("keyup", function () {
        let val = $(this).val().toLowerCase();
        $(".gam-size-option").each(function () {
            $(this).toggle($(this).text().toLowerCase().includes(val));
        });
    });

    // 🔹 Click option to add tag
    $("#gam-normal-sizes .gam-size-option").on("click", function () {
        const size = $(this).data("value");
        if (!$("#gam_ad_sizes").val().includes(size)) {
            addTag(size);
        }
        searchInput.val(""); // reset search
        dropdown.hide();
    });

    // 🔹 Add tag function
    function addTag(size) {
        const tag = $(`
            <div class="gam-tag">${size}
                <span class="remove-tag">&times;</span>
            </div>
        `);

        tag.find(".remove-tag").on("click", function () {
            tag.remove();
            updateHidden();
        });

        $("#gam-selected-sizes").append(tag);
        updateHidden();
    }

    // 🔹 Update hidden input
    function updateHidden() {
        let sizes = [];
        $("#gam-selected-sizes").find(".gam-tag").each(function () {
            sizes.push($(this).text().replace("×", "").trim());
        });
        $("#gam_ad_sizes").val(sizes.join(","));
    }


    // Toggle responsive vs normal sizes
    $('#is_responsive').on('change', function () {
        if (this.checked) {
            // Responsive mode ON
            $('#gam-normal-sizes').hide();
            $('#gam-responsive-sizes').show();
        } else {
            // Normal mode ON
            $('#gam-responsive-sizes').hide();
            $('#gam-normal-sizes').show();
        }
    }).trigger('change');


    // Tabs
    $('.gam-device-tabs').on('click', 'li', function () {
        var device = $(this).data('device');
        $(this).addClass('active').siblings().removeClass('active');
        $('.gam-device-panel').hide();
        $('.gam-device-panel[data-device="' + device + '"]').show();
    });

    function addChip($wrapper, value, onUpdate) {
        if (!value) return;
        if ($wrapper.find('.gam-size-chip[data-value="' + value + '"]').length) return;

        var $chip = $(
            '<span class="gam-size-chip" data-value="' + value + '">' +
            value + ' <button type="button" class="remove" aria-label="Remove">×</button>' +
            '</span>'
        );
        $wrapper.append($chip);

        $chip.on('click', '.remove', function (e) {
            e.stopPropagation();
            $chip.remove();
            onUpdate();
        });
    }

    function updateHiddenResposive() {
        var data = {};
        ['desktop', 'tablet', 'mobile'].forEach(function (dev) {
            var vals = [];
            $('.gam-device-panel[data-device="' + dev + '"] .gam-selected-sizes .gam-size-chip').each(function () {
                vals.push($(this).data('value'));
            });
            if (vals.length) data[dev] = vals.join(',');
        });
        $('#gam_responsive_sizes').val(JSON.stringify(data));
    }

    function initDevicePanel(device) {
        var $panel = $('.gam-device-panel[data-device="' + device + '"]');
        var $search = $panel.find('.gam-size-search');
        var $dropdown = $panel.find('.gam-sizes-dropdown');
        var $selectWrap = $panel.find('.gam-sizes-select');
        var $chips = $panel.find('.gam-selected-sizes');

        // Show dropdown on focus/click
        $search.on('focus click', function () {
            $dropdown.show();
        });

        // Filter options
        $search.on('input', function () {
            var term = $(this).val().toLowerCase();
            $dropdown.find('.gam-size-option').each(function () {
                $(this).toggle($(this).text().toLowerCase().indexOf(term) !== -1);
            });
        });

        // Click option -> add chip
        $dropdown.on('click', '.gam-size-option', function () {
            addChip($chips, $(this).data('value'), updateHiddenResposive);
            updateHiddenResposive();
        });

        // Click outside -> hide dropdown
        $(document).on('mousedown', function (e) {
            if (!$(e.target).closest($selectWrap).length) {
                $dropdown.hide();
            }
        });
    }

    // Init all device panels
    ['desktop', 'tablet', 'mobile'].forEach(initDevicePanel);

    // Preload from hidden JSON (when editing an existing ad)
    (function preload() {
        var isResponsive = $('#is_responsive').is(':checked');

        if (isResponsive) {
            // Responsive JSON preload
            var raw = $('#gam_responsive_sizes').val();
            if (raw) {
                var parsed;
                try { parsed = JSON.parse(raw); } catch (e) { parsed = {}; }
                ['desktop', 'tablet', 'mobile'].forEach(function (dev) {
                    if (parsed && parsed[dev]) {
                        String(parsed[dev]).split(',').forEach(function (v) {
                            v = (v || '').trim();
                            if (!v) return;
                            var $chips = $('.gam-device-panel[data-device="' + dev + '"] .gam-selected-sizes');
                            addChip($chips, v, updateHiddenResposive);
                        });
                    }
                });
                updateHiddenResposive();
            }
        } else {
            // Normal sizes preload
            let preSelected = ($("#gam_ad_sizes").val() || "").split(",").map(s => s.trim()).filter(Boolean);
            preSelected.forEach(size => addTag(size));
        }
    })();

    $('#is_refreshad').on('change', function () {
        if (this.checked) {
            $('#refreshad_intervel').prop('disabled', false);
        } else {
            $('#refreshad_intervel').prop('disabled', true);
        }
    }).trigger('change');


    function syncDevices() {
        let activeDevices = [];
        $('.active_devices .device.active').each(function () {
            activeDevices.push($(this).data('type'));
        });

        // Default back to all devices if none selected
        if (activeDevices.length === 0) {
            activeDevices = ['desktop', 'tablet', 'mobile'];
            $('.active_devices .device').addClass('active');
        }

        $('#gam_active_devices').val(activeDevices.join(','));
    }

    // Sync UI with hidden input value on page load
    function syncDeviceWithHiddenInput() {
        let savedDevices = ($('#gam_active_devices').val() || "").split(',').map(s => s.trim()).filter(Boolean);
        $('.active_devices .device').each(function () {
            let type = $(this).data('type');
            if (savedDevices.includes(type)) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }
        });
    }
    syncDeviceWithHiddenInput();

    // Update hidden input whenever a device is clicked
    $('.active_devices .device').on('click', function () {
        $(this).toggleClass('active');
        syncDevices();
    });

    // Initial sync
    syncDevices();



    // Run on ad_type change
    adTypeInput.on("change", function () {
        toggleAlignmentOptions();
    });

    function getUrlParam(param, action = 'get') {
        const url = new URL(window.location.href);
        const urlParams = url.searchParams;

        if (action === 'delete') {
            urlParams.delete(param);
            window.history.replaceState({}, "", url.toString());
            return null;
        }

        return urlParams.get(param);
    }


    const adId = getUrlParam('edit_id');

    function resetAdForm() {
        // Full form reset
        $("#gam-ad-form")[0].reset();
        $('#gam_active_devices').val('desktop,tablet,mobile')
        syncDeviceWithHiddenInput();
        // Explicitly clear all custom fields and hidden inputs
        $("#gam-ad-id").val('');
        $("#gam_selected_ad_type").val('');
        $("#gam_ad_unit").val('');
        $("#is_refreshad").prop('checked', false);
        $("#refreshad_intervel").val('30');
        $("#refreshad_intervel").show();
        $("#refreshad_intervel").prop('disabled', true);
        $(".gam-refreshad-toggle").show();
        $("#gam_ad_sizes").val('');
        $(".gam-tag").remove();
        $('#gam_responsive_sizes').val('{}');
        $('.gam-size-chip').remove();
        $("#gam-size-wrapper").hide();
        updateHidden();
        updateHiddenResposive();
        $('#is_responsive').prop('checked', false);
        $('#is_responsive').trigger('change');
        $('#gam_blockid').val('0');
        $('label[for=gam_ad_position]').show();
        $("#gam_ad_position").val('');
        $("#gam_ad_position").show();
        $("#gam_ad_position option").prop('disabled', false);
        $("#paragraph_counts").val('');
        $("#gam_ad_alignment").val('');
        $("#gam_ad_alignment_box").show();
        $('#gam_ad_alignment_or_trigger').text("Ad Alignment");
        $("#custom_ad_position").val('');
        $("#gam_custom_code").val('');
        $('#custom_position_field label').text('Enter Custom Position');

        // Reset checkboxes
        $("#show_once").prop('checked', true);
        $("#gam-is-active").val('0');
        $("#gam-save-ad-button-disable").hide();
        $("#gam-save-ad-button-publish").show();
        $("#gam-save-ad-button").text('Draft');

        $('.enable_ad_class').hide();
        $('.activeinactivebutton').removeClass("active");
        $("[name='show_on_all_pages']").prop('checked', false);
        $(".visible_type_pages").show();
        $(".gam-ad-form-group.flex_position_div._eql_pad").removeClass("rev-row");

        // Reset selects
        $("[name='visible_pages[]']").prop('checked', false).prop('disabled', false);

        // Reset CodeMirror
        if (typeof customAdCodeEditorMb !== 'undefined' && customAdCodeEditorMb) {
            customAdCodeEditorMb.setValue('');
            customAdCodeEditorMb.clearHistory();
        }
        // Reset AdunitFilter Code Editor
        if (typeof userPastedPassBackScript !== 'undefined' && userPastedPassBackScript) {
            userPastedPassBackScript.setValue('');
            userPastedPassBackScript.clearHistory();
        }

        // Clear any dynamic custom fields
        $("#custom_fields_container").empty();
        toggleFields();
    }

    function preSetIfInterstitial() {
        $("#is_refreshad").prop('checked', false);
        $("#refreshad_intervel").val('');
        $("#refreshad_intervel").hide();
        $("#refreshad_intervel").prop('disabled', true);
        $(".gam-refreshad-toggle").hide();
        // Size remove
        $("#gam_ad_sizes").val('');
        $(".gam-tag").remove();
        $("#gam-size-wrapper").hide();
        updateHidden();
        $("#show_on_all_pages").prop('checked', true);
        if ($("#show_on_all_pages").prop('checked') == true) {
            $("[name='visible_pages[]']").prop('disabled', true);
            //     $(".visible_type_pages").hide();
        } else {
            $("[name='visible_pages[]']").prop('disabled', false);
            // $(".visible_type_pages").show();
        }
        $("#gam_ad_position").val('head');
        $("#gam_ad_position").hide();
        $("#gam_ad_alignment_box").hide();
        $('label[for=gam_ad_position]').hide();
    }

    function preSetIfAnchor() {
        $("#is_refreshad").prop('checked', false);
        $("#refreshad_intervel").val('');
        $("#refreshad_intervel").hide();
        $("#refreshad_intervel").prop('disabled', true);
        $(".gam-refreshad-toggle").hide();
        // Size remove
        $("#gam_ad_sizes").val('');
        $(".gam-tag").remove();
        $("#gam-size-wrapper").hide();
        updateHidden();
        $("#show_on_all_pages").prop('checked', true);
        if ($("#show_on_all_pages").prop('checked') == true) {
            $("[name='visible_pages[]']").prop('disabled', true);
            // $(".visible_type_pages").hide();
        } else {
            $("[name='visible_pages[]']").prop('disabled', false);
            // $(".visible_type_pages").show();
        }
        $("#gam_ad_position").val('head');
        $("#gam_ad_position").hide();
        $('label[for=gam_ad_position]').hide();
        $("#gam_ad_alignment_box").show();
        $(".gam-ad-form-group.flex_position_div._eql_pad").addClass("rev-row");
    }

    function preSetIfRewarded() {
        $("#is_refreshad").prop('checked', false);
        $("#refreshad_intervel").val('');
        $("#refreshad_intervel").hide();
        $("#refreshad_intervel").prop('disabled', true);
        $(".gam-refreshad-toggle").hide();
        // Size remove
        $("#gam_ad_sizes").val('');
        $(".gam-tag").remove();
        $("#gam-size-wrapper").hide();
        updateHidden();
        $("#show_on_all_pages").prop('checked', true);
        if ($("#show_on_all_pages").prop('checked') == true) {
            $("[name='visible_pages[]']").prop('disabled', true);
            // $(".visible_type_pages").hide();
        } else {
            $("[name='visible_pages[]']").prop('disabled', false);
            // $(".visible_type_pages").show();
        }
        $("#gam_ad_position").val('head');
        $("#gam_ad_position").hide();
        $('label[for=gam_ad_position]').hide();
        $('#custom_position_field').show();
        $('#custom_position_field label').text('Class Or ID of the element (prefered a tag)');
        $("#gam_ad_alignment_box").hide();
        $(".gam-ad-form-group.flex_position_div._eql_pad").addClass("rev-row");
    }

    function preSetIfPopup() {
        $("#is_refreshad").prop('checked', false);
        $("#refreshad_intervel").val('30');
        $("#refreshad_intervel").hide();
        $("#refreshad_intervel").prop('disabled', true);
        $(".gam-refreshad-toggle").hide();
        $("#gam_ad_position").val('head');
        $("#gam_ad_position").hide();
        $('label[for=gam_ad_position]').hide();
        $("#gam_ad_alignment_box").show();
        $('#gam_ad_alignment_or_trigger').text("Display Trigger");
        if ($("[name='gam_ad_alignment']").val() === '') {
            $("[name='gam_ad_alignment']").val('default');
        };
        $(".gam-ad-form-group.flex_position_div._eql_pad").addClass("rev-row");
    }

    function preSetIfFloater() {
        $(".gam-refreshad-toggle").show();
        $("#refreshad_intervel").val('30');
        $("#refreshad_intervel").show();
        $("#refreshad_intervel").prop('disabled', true);
        $("#gam_ad_position").val('footer');
        $("#gam_ad_position").hide();
        $('label[for=gam_ad_position]').hide();
        $("#gam_ad_alignment_box").show();
        $(".gam-ad-form-group.flex_position_div._eql_pad").addClass("rev-row");
    }

    function preSetIfPushDown() {
        $(".gam-refreshad-toggle").show();
        $("#refreshad_intervel").val('30');
        $("#refreshad_intervel").show();
        $("#refreshad_intervel").prop('disabled', true);
        $('label[for=gam_ad_position]').hide();
        $("#gam_ad_position").hide();
        $("#gam_ad_position").val('head');
        $("#gam_ad_alignment_box").hide();
    }

    function preSetIfSticky() {
        $('label[for=gam_ad_position]').hide();
        $("#gam_ad_position").hide();
        $("#gam_ad_position").val('footer');
        $("#gam_ad_alignment_box").show();
        $(".gam-ad-form-group.flex_position_div._eql_pad").addClass("rev-row");
    }

    let BlockResponsData = [];
    let CustomCodeDrafts = {}; // { blockid: "unsaved code here" }

    function saveCurrentDraft(blockid) {
        if (!blockid) return;
        const type = adTypeInput.val(); // adTypeInput
        if (!CustomCodeDrafts[type]) CustomCodeDrafts[type] = {};

        if (customAdCodeEditorMb) {
            CustomCodeDrafts[type][blockid] = customAdCodeEditorMb.getValue();
        } else {
            CustomCodeDrafts[type][blockid] = $("#gam_custom_code").val();
        }
    }

    function loadBlockCode(blockid, matchedAd) {
        let code = "";
        const type = adTypeInput.val(); // or your adTypeInput

        if (CustomCodeDrafts[type] && CustomCodeDrafts[type][blockid] !== undefined) {
            code = CustomCodeDrafts[type][blockid]; // unsaved draft
        } else {
            code = matchedAd?.custom_code || "";
        }

        if (customAdCodeEditorMb) {
            customAdCodeEditorMb.setValue(code);
            customAdCodeEditorMb.clearHistory();
        } else {
            $("#gam_custom_code").val(code);
        }
    }

    // Click handler for ad type items
    adTypeItems.on('click', function () {

        resetAdForm();
        CustomCodeDrafts = {};

        adTypeItems.removeClass("active");
        $(this).addClass("active");

        const selectedType = $(this).data("type");
        adTypeInput.val(selectedType);
        $('.previewOfAdModel').show();

        // Show/hide fields based on ad type
        if (selectedType === "custom_ad") {
            adUnitWrapper.hide();
            customCodeWrapper.show();
            blocks.show();
            $('.blockid').removeClass("selected");
            $('.blockid[data-type="1"]').addClass("selected");
            $('#gam_blockid').val(1);
            $('.previewOfAdModel').hide();
            AdunitFilterCodeEditor.hide();
        } else if (selectedType === "banner") {
            adUnitWrapper.show();
            customCodeWrapper.hide();
            AdunitFilterCodeEditor.show();
            if ($("#gam_ad_unit").val() !== "") {
                // Close Filter Ad unit Block
                $('.open_filter_script_block').show();
                $('.manual_mode_adunit_wrapper').hide();
            } else {
                // Open Filter Ad unit Block
                $('.open_filter_script_block').hide();
                $('.manual_mode_adunit_wrapper').show();
            }
            blocks.show();
            $('.blockid').removeClass("selected");
            $('.blockid[data-type="1"]').addClass("selected");
            $('#gam_blockid').val(1);
        } else {
            adUnitWrapper.show();
            customCodeWrapper.hide();
            AdunitFilterCodeEditor.show();
            if ($("#gam_ad_unit").val() !== "") {
                // Close Filter Ad unit Block
                $('.open_filter_script_block').show();
                $('.manual_mode_adunit_wrapper').hide();
            } else {
                // Open Filter Ad unit Block
                $('.open_filter_script_block').hide();
                $('.manual_mode_adunit_wrapper').show();
            }
            blocks.hide();
            toggleFields();
            toggleAlignmentOptions();
        }

        // If type is interstitial → auto set position & show_once checkbox
        if (selectedType === "interstitial") {
            preSetIfInterstitial();
            toggleCustomField();
        }
        if (selectedType === "anchor") {
            preSetIfAnchor();
            toggleCustomField();
        }

        if (selectedType === "rewarded") {
            preSetIfRewarded();
            toggleCustomField();
        }

        if (selectedType === "popup") {
            preSetIfPopup();
            toggleCustomField();
        }

        if (selectedType === "floater") {
            preSetIfFloater();
            toggleCustomField();
        }

        if (selectedType === "push_down") {
            preSetIfPushDown();
            toggleCustomField();
        }

        if (selectedType === "sticky") {
            preSetIfSticky();
            toggleCustomField();
        }

        // Show form area
        formArea.show();

        // Upgrade
        if (selectedType === "upgrade_now" || selectedType === "manual_upgrade") {
            $('.premium_content').remove();
            const proDi = $('<div></div>');
            proDi.addClass('premium_content');
            const proDiCo = `<div class="gamadsmbai_pro_wrapper${selectedType === "manual_upgrade" ? " pro_plus" : ''}">
                    <div class="pro_t">
                    <svg height="25px" width="25px" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 512 512" xml:space="preserve" fill="#000000">
                    <g id="SVGRepo_bgCarrier" stroke-width="0"></g>
                    <g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round" stroke="#CCCCCC" stroke-width="1.024"></g>
                    <g id="SVGRepo_iconCarrier"> 
                    <polygon style="fill:${selectedType === "manual_upgrade" ? '#8c27f4' : '#F8C660'};" points="461.354,263.687 347.439,356.077 257.578,220.794 167.748,356.035 53.864,264.199 43.363,201.714 158.302,294.71 257.557,145.29 356.833,294.71 471.771,201.714 "></polygon> 
                    <g> <polygon style="fill:${selectedType === "manual_upgrade" ? '#8c27f4' : '#F8C660'};" points="461.354,263.636 429.975,450.298 85.159,450.298 53.864,264.148 167.748,356.049 257.578,220.801 347.439,356.107 "></polygon> 
                    <circle style="fill:${selectedType === "manual_upgrade" ? '#8c27f4' : '#F8C660'};" cx="257.567" cy="103.497" r="41.796"></circle> 
                    <circle style="fill:${selectedType === "manual_upgrade" ? '#8c27f4' : '#F8C660'};" cx="467.592" cy="184.999" r="33.959"></circle> 
                    <circle style="fill:${selectedType === "manual_upgrade" ? '#8c27f4' : '#F8C660'};" cx="44.408" cy="184.999" r="33.959"></circle> </g> 
                    <polygon style="fill:${selectedType === "manual_upgrade" ? '#8c27f4' : '#F8C660'};" points="258.132,413.632 220.503,360.33 258.132,307.028 295.76,360.33 "></polygon> 
                    <g> <path style="fill:#F8C660;" d="M512,185c0-24.487-19.921-44.408-44.408-44.408S423.184,160.513,423.184,185 c0,12.43,5.14,23.676,13.398,31.745l-77.398,62.622l-84.14-126.641c20.239-7.206,34.769-26.548,34.769-49.228 c0-28.808-23.437-52.245-52.245-52.245c-28.808,0-52.245,23.437-52.245,52.245c0,22.675,14.524,42.013,34.754,49.223 L155.95,279.366l-79.147-64.037c7.443-7.944,12.013-18.61,12.013-30.329c0-24.487-19.921-44.408-44.408-44.408S0,160.513,0,185 c0,22.076,16.194,40.434,37.326,43.837l37.53,223.14c0.846,5.031,5.203,8.77,10.304,8.77h344.816c5.102,0,9.458-3.738,10.304-8.77 l37.638-223.767C497.439,223.542,512,205.932,512,185z M226.22,103.498c0-17.285,14.062-31.347,31.347-31.347 s31.347,14.062,31.347,31.347s-14.062,31.347-31.347,31.347S226.22,120.783,226.22,103.498z M159.885,305.039 c2.908-0.446,5.493-2.096,7.12-4.547l90.553-136.319l90.572,136.319c1.628,2.45,4.213,4.1,7.12,4.546 c2.907,0.443,5.868-0.355,8.155-2.206l92.643-74.956c0.233,0.063,0.465,0.127,0.699,0.186l-5.022,29.879l-101.944,82.772 l-83.499-125.708c-1.937-2.915-5.204-4.668-8.704-4.668c-3.5,0-6.768,1.752-8.704,4.668l-83.485,125.683L63.491,258.437 l-5.251-31.246l93.489,75.641C154.016,304.684,156.974,305.482,159.885,305.039z M20.898,185c0-12.964,10.546-23.51,23.51-23.51 s23.51,10.546,23.51,23.51s-10.546,23.51-23.51,23.51S20.898,197.964,20.898,185z M421.137,439.849H93.998l-25.26-150.267 l92.447,74.597c2.287,1.847,5.247,2.63,8.152,2.184c2.905-0.447,5.488-2.104,7.115-4.553l81.126-122.135l81.157,122.181 c1.63,2.453,4.218,4.103,7.129,4.547c2.916,0.445,5.875-0.362,8.161-2.218l92.437-74.999L421.137,439.849z M467.592,208.51 c-12.964,0-23.51-10.546-23.51-23.51s10.546-23.51,23.51-23.51c12.964,0,23.51,10.546,23.51,23.51S480.556,208.51,467.592,208.51z"></path> <path style="fill:#F8C660;" d="M266.145,301.002c-1.958-2.773-5.141-4.423-8.536-4.423c-3.395,0-6.578,1.65-8.536,4.423 l-37.629,53.302c-2.551,3.613-2.551,8.44,0,12.052l37.629,53.302c1.958,2.773,5.141,4.423,8.536,4.423 c3.395,0,6.578-1.65,8.536-4.423l37.629-53.302c2.551-3.613,2.551-8.44,0-12.052L266.145,301.002z M257.609,395.515l-24.838-35.185 l24.838-35.185l24.838,35.185L257.609,395.515z"></path> 
                    </g> </g>
                    </svg>
                    <span id="proDiCo">${selectedType === "manual_upgrade" ? 'This feature need to manual implementation, please contact us' : 'Upgrade to unlock this feature'}</span>
                    </div>
                    <div class="pro_sb">
                    <button id="${selectedType === "manual_upgrade" ? 'manual_upgrade_button">CONTACT US' : 'upgrade_button">UPGRADE NOW'}</button>
                    </div></div>`;
            proDi.append(proDiCo);
            $('.gam-ad-form-area').append(proDi);
            $('#upgrade_button').on('click', function () {
                window.open('https://gamadinserter.com/#pricing', '_blank');
            })
            $('#manual_upgrade_button').on('click', function () {
                window.open('https://magicbid.ai/contact-us/', '_blank');
            })
            return;
        }
        $('.premium_content').remove();

        if (adId) {
            adTypeItems.hide();
            $(this).show();

            jQuery('#gam-ajax-loader').show();
            // Call Ajax
            $.ajax({
                url: gam_ads_ad_manager_and_ad_exchange.ajaxUrl,
                type: "POST",
                dataType: "json",
                data: {
                    action: "gam_ads_ad_manager_and_ad_exchange_get_ad_by_id",
                    nonce: gam_ads_ad_manager_and_ad_exchange.nonce,
                    id: adId
                },
                success: function (res) {
                    if (res.success && res.data) {
                        const ad = res.data;
                        if (ad.id) {
                            // Fill form inputs
                            $("[name='ad_id']").val(ad.id || '');
                            $('.blockid').removeClass("selected");
                            $('.blockid[data-type="' + ad.blockid + '"]').addClass("selected");
                            $('#gam_blockid').val(ad.blockid);
                            $('#gam_active_devices').val(ad.gam_active_devices);
                            syncDeviceWithHiddenInput();
                            $("[name='gam_ad_unit']").val(ad.gam_ad_unit || '');
                            if (ad.gam_ad_unit) {
                                $("#gam-size-wrapper").show()
                                // Close Filter Ad unit Block
                                $('.open_filter_script_block').show();
                                $('.manual_mode_adunit_wrapper').hide();
                            };
                            $("#gam_ad_sizes").val(ad.gam_ad_sizes || '');
                            if (ad.gam_ad_sizes) {
                                let sizes = ad.gam_ad_sizes.split(",").filter(Boolean);
                                sizes.forEach(size => addTag(size));
                            }
                            if (parseInt(ad.is_responsive) === 1) {
                                $('#is_responsive').prop('checked', true);
                                $('#is_responsive').trigger('change');
                            }
                            $('#gam_responsive_sizes').val(JSON.stringify(ad.gam_responsive_sizes));
                            if (ad.gam_responsive_sizes) {
                                var parsed;
                                try { parsed = JSON.parse(ad.gam_responsive_sizes); } catch (e) { parsed = {}; }
                                ['desktop', 'tablet', 'mobile'].forEach(function (dev) {
                                    if (parsed && parsed[dev]) {
                                        String(parsed[dev]).split(',').forEach(function (v) {
                                            v = (v || '').trim();
                                            if (!v) return;
                                            var $chips = $('.gam-device-panel[data-device="' + dev + '"] .gam-selected-sizes');
                                            addChip($chips, v, updateHiddenResposive);
                                        });
                                    }
                                });
                                updateHiddenResposive();
                            }
                            $("[name='gam_ad_position']").val(ad.ad_position || '');
                            $("[name='paragraph_counts']").val(ad.paragraph_counts || '');
                            $("[name='gam_ad_alignment']").val(ad.ad_alignment || '');
                            showOnceCheckbox.prop('checked', ad.show_once == 1);
                            $("#gam-is-active").val(ad.is_active);
                            if (ad.is_active == 1) {
                                $("#gam-save-ad-button-disable").show();
                                $("#gam-save-ad-button-publish").hide();
                                $("#gam-save-ad-button").text('Save');
                                $('.activeinactivebutton').addClass("active")
                                $('.enable_ad_class').hide();
                                if (ad.ad_type === "custom_ad") {
                                    $('.enable_ad_class').show();
                                }
                            } else {
                                $('.activeinactivebutton').removeClass("active");
                                $('.enable_ad_class').show();
                                $("#gam-save-ad-button-disable").hide();
                                $("#gam-save-ad-button-publish").show();
                                $("#gam-save-ad-button").text('Draft');
                            }
                            $("[name='show_on_all_pages']").prop('checked', ad.show_entire_site == 1);
                            if (ad.show_entire_site == 1) {
                                $("[name='visible_pages[]']").prop('disabled', true);
                            } else {
                                $("[name='visible_pages[]']").prop('disabled', false);
                            }
                            // Visible pages checkboxes (multiple select)
                            if (ad.visible_pages && Array.isArray(ad.visible_pages)) {
                                $("[name='visible_pages[]']").each(function () {
                                    $(this).prop('checked', ad.visible_pages.includes($(this).val()));
                                });
                            } else {
                                $("[name='visible_pages[]']").prop('checked', false);
                            }
                            // Update CodeMirror if exists
                            if (customAdCodeEditorMb && ad.custom_code !== undefined) {
                                customAdCodeEditorMb.setValue(ad.custom_code);
                                customAdCodeEditorMb.clearHistory();
                            } else if (!customAdCodeEditorMb) {
                                $("#gam_custom_code").val(ad.custom_code || '');
                            }
                            toggleCustomField();
                            toggleFields();
                            toggleAlignmentOptions();
                            if (ad.ad_type === "interstitial") {
                                preSetIfInterstitial();
                            } else if (ad.ad_type === "anchor") {
                                preSetIfAnchor();
                            } else if (ad.ad_type === "rewarded") {
                                preSetIfRewarded();
                            } else if (ad.ad_type === "popup") {
                                preSetIfPopup();
                            } else if (ad.ad_type === "floater") {
                                preSetIfFloater();
                            } else if (ad.ad_type === "push_down") {
                                preSetIfPushDown();
                            }
                            if (parseInt(ad.is_refreshad) === 1) {
                                $("#is_refreshad").prop('checked', true);
                                $("#refreshad_intervel").val(ad.refreshad_intervel);
                                $("#refreshad_intervel").show();
                                $("#refreshad_intervel").prop('disabled', false);
                            }
                            $("[name='custom_ad_position']").val(ad.custom_ad_position || '');

                        }
                    } else {
                        console.warn("No ad data found for ID:", adId);
                        wp.data.dispatch('core/notices').createNotice(
                            'warning',
                            'No ad data found!',
                            { isDismissible: true }
                        );
                    }
                    jQuery('#gam-ajax-loader').hide();
                },
                error: function (xhr, status, error) {
                    console.error("Error fetching ad data:", error);
                    wp.data.dispatch('core/notices').createNotice(
                        'error',
                        'Error fetching ad data: ' + error,
                        { isDismissible: true }
                    );
                    jQuery('#gam-ajax-loader').hide();
                }
            });
        } else {
            jQuery('#gam-ajax-loader').show();
            // AJAX: get existing show_once ad data and fill form if exists
            const blockid = $('#gam_blockid').val();
            const AllBlockIds = $('.blockid');
            AllBlockIds.removeClass("activeads warnactiveads");

            $.ajax({
                url: gam_ads_ad_manager_and_ad_exchange.ajaxUrl,
                type: "POST",
                dataType: "json",
                data: {
                    action: "gam_ads_ad_manager_and_ad_exchange_get_show_once_ad",
                    nonce: gam_ads_ad_manager_and_ad_exchange.nonce,
                    ad_type: selectedType,
                    // blockid: blockid
                },
                success: function (res) {
                    if (res.success && res.data && res.data.length > 0) {
                        BlockResponsData = res.data;
                        AllBlockIds.each(function () {
                            const elBlockId = $(this).data('type'); // assuming you set data-blockid on element
                            const found = res.data.find(d => String(d?.blockid) == String(elBlockId));
                            if (found) {
                                if (parseInt(found.is_active, 10) === 1) {
                                    $(this).addClass("activeads").removeClass("warnactiveads");
                                } else {
                                    $(this).addClass("warnactiveads").removeClass("activeads");
                                }
                            }
                        });
                        const matchedAd = res.data.find(d => d?.blockid == blockid);
                        if (matchedAd) {
                            // Fill form inputs
                            $("[name='ad_id']").val(matchedAd.id || '');
                            $('#gam_active_devices').val(matchedAd.gam_active_devices);
                            syncDeviceWithHiddenInput();
                            $("[name='gam_ad_unit']").val(matchedAd.gam_ad_unit || '');
                            if (matchedAd.gam_ad_unit) {
                                $("#gam-size-wrapper").show();
                                // Close Filter Ad unit Block
                                $('.open_filter_script_block').show();
                                $('.manual_mode_adunit_wrapper').hide();
                            };
                            $("#gam_ad_sizes").val(matchedAd.gam_ad_sizes || '');
                            if (matchedAd.gam_ad_sizes) {
                                let sizes = matchedAd.gam_ad_sizes.split(",").filter(Boolean);
                                sizes.forEach(size => addTag(size));
                            }
                            if (parseInt(matchedAd.is_responsive) === 1) {
                                $('#is_responsive').prop('checked', true);
                                $('#is_responsive').trigger('change');
                            }
                            $('#gam_responsive_sizes').val(JSON.stringify(matchedAd.gam_responsive_sizes));
                            if (matchedAd.gam_responsive_sizes) {
                                var parsed;
                                try { parsed = JSON.parse(matchedAd.gam_responsive_sizes); } catch (e) { parsed = {}; }
                                ['desktop', 'tablet', 'mobile'].forEach(function (dev) {
                                    if (parsed && parsed[dev]) {
                                        String(parsed[dev]).split(',').forEach(function (v) {
                                            v = (v || '').trim();
                                            if (!v) return;
                                            var $chips = $('.gam-device-panel[data-device="' + dev + '"] .gam-selected-sizes');
                                            addChip($chips, v, updateHiddenResposive);
                                        });
                                    }
                                });
                                updateHiddenResposive();
                            }
                            $("[name='gam_ad_position']").val(matchedAd.ad_position || '');
                            $("[name='paragraph_counts']").val(matchedAd.paragraph_counts || '');
                            $("[name='gam_ad_alignment']").val(matchedAd.ad_alignment || '');
                            showOnceCheckbox.prop('checked', matchedAd.show_once == 1);
                            $("#gam-is-active").val(matchedAd.is_active);
                            if (matchedAd.is_active == 1) {
                                $("#gam-save-ad-button-disable").show();
                                $("#gam-save-ad-button-publish").hide();
                                $("#gam-save-ad-button").text('Save');
                                $('.activeinactivebutton').addClass("active");
                                $('.enable_ad_class').hide();
                                if (matchedAd.ad_type === "custom_ad") {
                                    $('.enable_ad_class').show();
                                }
                            } else {
                                $('.activeinactivebutton').removeClass("active");
                                $('.enable_ad_class').show();
                                $("#gam-save-ad-button-disable").hide();
                                $("#gam-save-ad-button-publish").show();
                                $("#gam-save-ad-button").text('Draft');
                            }
                            $("[name='show_on_all_pages']").prop('checked', matchedAd.show_entire_site == 1);
                            if (matchedAd.show_entire_site == 1) {
                                $("[name='visible_pages[]']").prop('disabled', true);
                            } else {
                                $("[name='visible_pages[]']").prop('disabled', false);
                            }
                            // Visible pages checkboxes (multiple select)
                            if (matchedAd.visible_pages && Array.isArray(matchedAd.visible_pages)) {
                                $("[name='visible_pages[]']").each(function () {
                                    $(this).prop('checked', matchedAd.visible_pages.includes($(this).val()));
                                });
                            } else {
                                $("[name='visible_pages[]']").prop('checked', false);
                            }

                            // Update CodeMirror if exists
                            if (customAdCodeEditorMb && matchedAd.custom_code !== undefined) {
                                customAdCodeEditorMb.setValue(matchedAd.custom_code);
                                customAdCodeEditorMb.clearHistory();
                            } else if (!customAdCodeEditorMb) {
                                $("#gam_custom_code").val(matchedAd.custom_code || '');
                            }
                            toggleCustomField();
                            toggleFields();
                            toggleAlignmentOptions();
                            if (matchedAd.ad_type === "interstitial") {
                                preSetIfInterstitial();
                            } else if (matchedAd.ad_type === "anchor") {
                                preSetIfAnchor();
                            } else if (matchedAd.ad_type === "rewarded") {
                                preSetIfRewarded();
                            } else if (matchedAd.ad_type === "popup") {
                                preSetIfPopup();
                            } else if (matchedAd.ad_type === "floater") {
                                preSetIfFloater();
                            } else if (matchedAd.ad_type === "push_down") {
                                preSetIfPushDown();
                            }
                            if (parseInt(matchedAd.is_refreshad) === 1) {
                                $("#is_refreshad").prop('checked', true);
                                $("#refreshad_intervel").val(matchedAd.refreshad_intervel);
                                $("#refreshad_intervel").show();
                                $("#refreshad_intervel").prop('disabled', false);
                            }
                            $("[name='custom_ad_position']").val(matchedAd.custom_ad_position || '');
                        }
                    } else {
                        // Reset form if no data found
                        if ($("#gam_selected_ad_type").val() === "interstitial") {
                            preSetIfInterstitial();
                        } else if ($("#gam_selected_ad_type").val() === "anchor") {
                            preSetIfAnchor();
                        } else if ($("#gam_selected_ad_type").val() === "rewarded") {
                            preSetIfRewarded();
                        } else if ($("#gam_selected_ad_type").val() === "popup") {
                            preSetIfPopup();
                        } else if ($("#gam_selected_ad_type").val() === "floater") {
                            preSetIfFloater();
                        } else if ($("#gam_selected_ad_type").val() === "push_down") {
                            preSetIfPushDown();
                        } else {
                            BlockResponsData = [];
                            if ($("#gam-ad-form")[0].reset()) {
                                adTypeInput.val(selectedType);
                                adPositionSelect.val('');
                                showOnceCheckbox.prop('checked', false);
                                $("#gam_ad_sizes").val('');
                                $(".gam-tag").remove();
                                updateHidden();
                                $('#gam_responsive_sizes').val('{}');
                                $('.gam-size-chip').remove();
                                updateHiddenResposive();
                                $('#is_responsive').prop('checked', false);
                                $('#is_responsive').trigger('change');
                                $("#gam_ad_position").val('');
                                $("#custom_ad_position").val('');
                                $("[name='show_on_all_pages']").prop('checked', false);
                                $("[name='visible_pages[]']").prop('disabled', false);
                                if (customAdCodeEditorMb) {
                                    customAdCodeEditorMb.setValue('');
                                    customAdCodeEditorMb.clearHistory();
                                } else {
                                    $("#gam_custom_code").val('');
                                }
                                toggleCustomField();
                                toggleFields();
                                toggleAlignmentOptions();
                            }
                        };
                    }
                    jQuery('#gam-ajax-loader').hide();
                },
                error: function (xhr, status, error) {
                    console.error("Failed to fetch ad data");
                    wp.data.dispatch('core/notices').createNotice(
                        'error',
                        'Failed to fetch ad data: ' + error,
                        { isDismissible: true }
                    );
                    jQuery('#gam-ajax-loader').hide();
                }
            });
        }
    });

    // On page load, if any ad type item is active, trigger click to load data and show form
    if (adTypeItems.filter('.active').length) {
        adTypeItems.filter('.active').trigger('click');
    } else {
        formArea.hide();
    }

    // Save button handler
    $("#gam-save-ad-button").on('click', function (e) {
        e.preventDefault();
        jQuery('#gam-ajax-loader').show();
        if (customAdCodeEditorMb) {
            customAdCodeEditorMb.save();
        }
        let formData = $("#gam-ad-form").serializeArray();
        formData.push({
            name: "action",
            value: "gam_ads_ad_manager_and_ad_exchange_save_ad"
        });
        formData.push({
            name: "nonce",
            value: gam_ads_ad_manager_and_ad_exchange.nonce
        });
        $.ajax({
            url: gam_ads_ad_manager_and_ad_exchange.ajaxUrl,
            type: "POST",
            dataType: "json",
            data: formData,
            success: function (res) {
                if (res.success) {
                    // Optionally refresh or re-trigger ad type selection to reload updated data
                    const currentType = adTypeInput.val();
                    adTypeItems.filter(`[data-type="${currentType}"]`).trigger('click');
                    // window.location.reload();
                    wp.data.dispatch('core/notices').createNotice(
                        'success',
                        'Ad Saved successfully',
                        { isDismissible: true }
                    );
                    jQuery('#gam-ajax-loader').show();
                } else {
                    wp.data.dispatch('core/notices').createNotice(
                        'warning',
                        res.data || "Error saving ad.",
                        { isDismissible: true }
                    );
                    jQuery('#gam-ajax-loader').hide();
                }
            },
            error: function () {
                wp.data.dispatch('core/notices').createNotice(
                    'error',
                    res.data || "AJAX SERVER ERROR.",
                    { isDismissible: true }
                );
                jQuery('#gam-ajax-loader').hide();
            }
        });
    });

    // Show/hide visible pages select based on "show on entire site" checkbox
    const allPagesCheckbox = $('[name="show_on_all_pages"]');
    const pagesCheckboxes = $('[name="visible_pages[]"]');

    if (allPagesCheckbox.length && pagesCheckboxes.length) {
        function togglePagesCheckboxes() {
            if (allPagesCheckbox.prop('checked')) {
                pagesCheckboxes.prop('disabled', true);
            } else {
                pagesCheckboxes.prop('disabled', false);
            }
        }
        allPagesCheckbox.on('change', togglePagesCheckboxes);
        togglePagesCheckboxes();
    }

    $('.activeinactivebutton').on('click', function () {
        const $enableAd = $('#gam-is-active');
        let enableAd = $enableAd.val();

        if (enableAd === "1") {
            $(this).removeClass("active");
            $enableAd.val("0");
        } else {
            $(this).addClass("active");
            $enableAd.val("1");
        }
    });

    $('.blockid').on('click', function () {
        saveCurrentDraft($('#gam_blockid').val());
        $('.blockid').removeClass("selected");
        $(this).addClass("selected");
        $('#gam_blockid').val($(this).data("type"));
        $("#gam_ad_unit").val('');
        $('#gam_active_devices').val('desktop,tablet,mobile');
        syncDeviceWithHiddenInput();
        $("#is_refreshad").prop('checked', false);
        $("#refreshad_intervel").val('30');
        $("#refreshad_intervel").show();
        $("#refreshad_intervel").prop('disabled', true);
        $(".gam-refreshad-toggle").show();
        $("#gam_ad_sizes").val('');
        $(".gam-tag").remove();
        $("#gam-size-wrapper").hide();
        updateHidden();
        $('#gam_responsive_sizes').val('{}');
        $('.gam-size-chip').remove();
        updateHiddenResposive();
        $('#is_responsive').prop('checked', false);
        $('#is_responsive').trigger('change');
        $('#gam-ad-id').val('');
        $('#gam-is-active').val("0");
        $("#gam-save-ad-button-disable").hide();
        $("#gam-save-ad-button-publish").show();
        $("#gam-save-ad-button").text('Draft');
        $('.activeinactivebutton').removeClass("active");
        $('.enable_ad_class').hide();
        $('[name="visible_pages[]"]').prop('disabled', false);
        $('#gam_ad_position').val('');
        toggleCustomField();
        toggleFields();
        toggleAlignmentOptions();
        if (adTypeInput.val() === 'custom_ad' && CustomCodeDrafts[adTypeInput.val()]?.[$(this).data("type")]) {
            if (customAdCodeEditorMb) {
                customAdCodeEditorMb.setValue(CustomCodeDrafts[adTypeInput.val()]?.[$(this).data("type")]);
            } else {
                $("#gam_custom_code").val(CustomCodeDrafts[adTypeInput.val()]?.[$(this).data("type")]);
            }
        } else {
            if (customAdCodeEditorMb) {
                customAdCodeEditorMb.setValue('');
                customAdCodeEditorMb.clearHistory();
            } else {
                $("#gam_custom_code").val('');
            }
        }

        if (typeof userPastedPassBackScript !== 'undefined' && userPastedPassBackScript) {
            userPastedPassBackScript.setValue('');
            userPastedPassBackScript.clearHistory();
        }

        // Open Filter Ad unit Block
        $('.open_filter_script_block').hide();
        $('.manual_mode_adunit_wrapper').show();

        // AJAX: get existing show_once
        jQuery('#gam-ajax-loader').show();
        const blockid = $('#gam_blockid').val();

        if (BlockResponsData && BlockResponsData.length > 0) {
            const matchedAd = BlockResponsData?.find(d => d?.blockid == blockid);
            if (matchedAd) {
                $("#gam-ad-id").val(matchedAd.id || '');
                $('#gam_active_devices').val(matchedAd.gam_active_devices);
                syncDeviceWithHiddenInput();
                $("[name='gam_ad_unit']").val(matchedAd.gam_ad_unit || '');
                if (matchedAd.gam_ad_unit) {
                    $("#gam-size-wrapper").show();
                    // Close Filter Ad unit Block
                    $('.open_filter_script_block').show();
                    $('.manual_mode_adunit_wrapper').hide();
                }
                if (parseInt(matchedAd.is_refreshad) === 1) {
                    $("#is_refreshad").prop('checked', true);
                    $("#refreshad_intervel").val(matchedAd.refreshad_intervel);
                    $("#refreshad_intervel").show();
                    $("#refreshad_intervel").prop('disabled', false);
                }
                $("[name='gam_ad_sizes']").val(matchedAd.gam_ad_sizes || '');
                if (matchedAd.gam_ad_sizes) {
                    let sizes = matchedAd.gam_ad_sizes.split(",").filter(Boolean);
                    sizes.forEach(size => addTag(size));
                }
                if (parseInt(matchedAd.is_responsive) === 1) {
                    $('#is_responsive').prop('checked', true);
                    $('#is_responsive').trigger('change');
                }
                $('#gam_responsive_sizes').val(JSON.stringify(matchedAd.gam_responsive_sizes));
                if (matchedAd.gam_responsive_sizes) {
                    var parsed;
                    try { parsed = JSON.parse(matchedAd.gam_responsive_sizes); } catch (e) { parsed = {}; }
                    ['desktop', 'tablet', 'mobile'].forEach(function (dev) {
                        if (parsed && parsed[dev]) {
                            String(parsed[dev]).split(',').forEach(function (v) {
                                v = (v || '').trim();
                                if (!v) return;
                                var $chips = $('.gam-device-panel[data-device="' + dev + '"] .gam-selected-sizes');
                                addChip($chips, v, updateHiddenResposive);
                            });
                        }
                    });
                    updateHiddenResposive();
                }
                $("[name='gam_ad_position']").val(matchedAd.ad_position || '');
                $("[name='paragraph_counts']").val(matchedAd.paragraph_counts || '');
                $("[name='gam_ad_alignment']").val(matchedAd.ad_alignment || '');
                $("#show_once").prop('checked', matchedAd.show_once == 1);
                $("#gam-is-active").val(matchedAd.is_active);
                if (matchedAd.is_active == 1) {
                    $("#gam-save-ad-button-disable").show();
                    $("#gam-save-ad-button-publish").hide();
                    $("#gam-save-ad-button").text('Save');
                    $('.activeinactivebutton').addClass("active");
                    $('.enable_ad_class').hide();
                    if (matchedAd.ad_type === "custom_ad") {
                        $('.enable_ad_class').show();
                    }
                } else {
                    $('.activeinactivebutton').removeClass("active");
                    $('.enable_ad_class').show();
                    $("#gam-save-ad-button-disable").hide();
                    $("#gam-save-ad-button-publish").show();
                    $("#gam-save-ad-button").text('Draft');
                }
                $("[name='show_on_all_pages']").prop('checked', matchedAd.show_entire_site == 1);
                if ($('[name="show_on_all_pages"]').prop('checked')) {
                    $('[name="visible_pages[]"]').prop('disabled', true);
                } else {
                    $('[name="visible_pages[]"]').prop('disabled', false);
                }
                // Visible pages checkboxes (multiple select)
                if (matchedAd.visible_pages && Array.isArray(matchedAd.visible_pages)) {
                    $("[name='visible_pages[]']").each(function () {
                        $(this).prop('checked', matchedAd.visible_pages.includes($(this).val()));
                    });
                } else {
                    $("[name='visible_pages[]']").prop('checked', false);
                }
                if (adTypeInput.val() === 'custom_ad' && CustomCodeDrafts[adTypeInput.val()]?.[blockid]) {
                    if (customAdCodeEditorMb) {
                        customAdCodeEditorMb.setValue(CustomCodeDrafts[adTypeInput.val()]?.[blockid]);
                    } else {
                        $("#gam_custom_code").val(CustomCodeDrafts[adTypeInput.val()]?.[blockid]);
                    }
                } else {
                    loadBlockCode(matchedAd.blockid, matchedAd);
                }
                toggleCustomField();
                toggleFields();
                toggleAlignmentOptions();
                $("[name='custom_ad_position']").val(matchedAd.custom_ad_position || '');
            } else {
                // Reset form if no data found
                if ($("#gam-ad-form")[0].reset()) {
                    adTypeInput.val(adTypeInput);
                    $("#gam_ad_unit").val('');
                    adPositionSelect.val('');
                    $("#is_refreshad").prop('checked', false);
                    $("#refreshad_intervel").val('30');
                    $("#refreshad_intervel").show();
                    $("#refreshad_intervel").prop('disabled', true);
                    $(".gam-refreshad-toggle").show();
                    $("#show_once").prop('checked', false);
                    $("#gam_ad_sizes").val('');
                    $(".gam-tag").remove();
                    $("#gam-size-wrapper").hide();
                    updateHidden();
                    $('#gam_responsive_sizes').val('{}');
                    $('.gam-size-chip').remove();
                    updateHiddenResposive();
                    $('#is_responsive').prop('checked', false);
                    $('#is_responsive').trigger('change');
                    $("#custom_ad_position").val('');
                    $("#gam_ad_position").val('');
                    $("#paragraph_counts").val('');
                    $("#gam_ad_alignment").val('');
                    $("[name='show_on_all_pages']").prop('checked', false);
                    if ($('[name="show_on_all_pages"]').prop('checked')) {
                        $('[name="visible_pages[]"]').prop('disabled', true);
                    } else {
                        $('[name="visible_pages[]"]').prop('disabled', false);
                    }
                    $('#gam-is-active').val("0");
                    $("#gam-save-ad-button-disable").hide();
                    $("#gam-save-ad-button-publish").show();
                    $("#gam-save-ad-button").text('Draft');
                    $('.activeinactivebutton').removeClass("active");
                    $('.enable_ad_class').hide();
                    if (adTypeInput.val() === 'custom_ad' && CustomCodeDrafts[adTypeInput.val()]?.[blockid]) {
                        if (customAdCodeEditorMb) {
                            customAdCodeEditorMb.setValue(CustomCodeDrafts[adTypeInput.val()]?.[blockid]);
                        } else {
                            $("#gam_custom_code").val(CustomCodeDrafts[adTypeInput.val()]?.[blockid]);
                        }
                    } else {
                        if (customAdCodeEditorMb) {
                            customAdCodeEditorMb.setValue('');
                            customAdCodeEditorMb.clearHistory();
                        } else {
                            $("#gam_custom_code").val('');
                        }
                    }
                    // Open Filter Ad unit Block
                    $('.open_filter_script_block').hide();
                    $('.manual_mode_adunit_wrapper').show();

                    toggleCustomField();
                    toggleFields();
                    toggleAlignmentOptions();
                };
            }
        }
        jQuery('#gam-ajax-loader').hide();
    });

    // Trigger Publisher
    $("#gam-save-ad-button-publish").on('click', function (e) {
        e.preventDefault();
        $("#gam-is-active").val("1");
        $("#gam-save-ad-button").trigger('click');
    })

    // Trigger Disable
    $("#gam-save-ad-button-disable").on('click', function (e) {
        e.preventDefault();
        $("#gam-is-active").val("0");
        $("#gam-save-ad-button").trigger('click');
    })
    // });
    // JQUERY END

    // ToolTips
    // $(document).ready(function () {
    const tooltip = $(".floating_tooltip_box");
    let showTimer = null;

    $(document).on("mouseenter", ".floating_tooltip_on", function () {
        const title = $(this).data("title");
        clearTimeout(showTimer);
        showTimer = setTimeout(() => {
            tooltip.text(title).fadeIn(150);
        }, 200);
    });

    $(document).on("mousemove", ".floating_tooltip_on", function (e) {
        const offset = 15;
        const tooltipWidth = tooltip.outerWidth();
        const tooltipHeight = tooltip.outerHeight();
        const winWidth = $(window).width();
        const winHeight = $(window).height();
        let left = e.clientX + offset;
        let top = e.clientY + offset;
        // Adjust if going beyond right edge
        if (left + tooltipWidth > winWidth) {
            left = e.clientX - tooltipWidth - offset;
        }
        // Adjust if going beyond bottom edge
        if (top + tooltipHeight > winHeight) {
            top = e.clientY - tooltipHeight - offset;
        }

        tooltip.css({
            top: top + "px",
            left: left + "px"
        });
    });

    $(document).on("mouseleave", ".floating_tooltip_on", function () {
        clearTimeout(showTimer);
        tooltip.fadeOut(150);
    });
    // });
});



// Dashboard Page **************************
jQuery(document).ready(function ($) {
    $('.gam-tab-button').on('click', function () {
        $('.gam-tab-button').removeClass('active');
        $(this).addClass('active');

        var tab = $(this).data('tab');
        var adcounts = $(this).data('adcounts');
        var content = '';

        if (tab === 'total-ads') {
            content = '<h3>Total Ads</h3>' +
                '<p>' + adcounts + '</p>';
        } else if (tab === 'active-ads') {
            content = '<h3>Active Ads</h3>' +
                '<p>' + adcounts + '</p>';
        } else if (tab === 'inactive-ads') {
            content = '<h3>Inactive Ads</h3>' +
                '<p>' + adcounts + '</p>';
        }

        $('#gam-dashboard-content').html(content);
    });
});


// Settings Page **************************
jQuery(function ($) {
    jQuery(document).ready(function ($) {
        $(".settings_tabs button").on("click", function () {
            $(".settings_tabs button").removeClass("active");
            $(this).addClass("active");
            $(".tab_content").hide();
            if ($(this).hasClass("gamadsmbai_setting_tab")) {
                $("#gamadsmbai_content").show();
            } else if ($(this).hasClass("banner_labeling_setting_tab")) {
                $("#banner_labeling_content").show();
            } else if ($(this).hasClass("gamadsmbai_configs_setting_tab")) {
                $("#gam_configs_content").show();
            }
        });
    });

    jQuery(document).on('click', '#gam-redirect-link', function (e) {
        e.preventDefault();
        $('.paste_auth_code_box').show();
        const width = 600;
        const height = 700;
        const left = (window.screen.width / 2) - (width / 2);
        const top = (window.screen.height / 2) - (height / 2);


        const href = $(this).attr('href');
        const popup = window.open(
            '',
            'gamOauthPopup',
            `width=${width},height=${height},top=${top},left=${left},resizable=yes,scrollbars=yes,status=yes`
        );

        // move the popup immediately (to avoid blocker)
        popup.location.href = href;


        if (!popup || popup.closed || typeof popup.closed === 'undefined') {
            alert("Popup blocked! Please allow popups for this site.");
        }
    });

    // Setting Page
    $('#gam-save-code').on('click', function () {
        var code = $('#gam-auth-code').val().trim();
        if (!code) {
            alert('Please enter the authorization code.');
            return;
        }
        var loaderCircle = $(".msgbox svg");
        loaderCircle.show();
        $('#gam-message').css('color', 'inherit').text('Requesting access token...');

        $.post(gam_ads_ad_manager_and_ad_exchange.ajaxUrl, {
            action: 'gam_ads_ad_manager_and_ad_exchange_save_auth_code',
            nonce: gam_ads_ad_manager_and_ad_exchange.nonce,
            auth_code: code // the handler also accepts `code`, but this is preferred
        }, function (res) {
            if (res && res.success) {
                var msg = (res && res.data && res.data.message) ? res.data.message : 'Done';
                $('#gam-message').css('color', 'inherit').text(msg);
                location.href = "/wp-admin/admin.php?page=gam-ads-ad-manager-and-ad-exchange&tab=settings";
            } else {
                var msg = (res && res.data && res.data.message) ? res.data.message : 'Unknown error';
                $('#gam-message').css('color', 'red').text('❌ ' + msg);
                loaderCircle.hide();
            }
        }).fail(function (xhr) {
            $('#gam-message').css('color', 'red').text('❌ Network/Server error');
            loaderCircle.hide();
        });
    });

    $('#gamadsai_manual_mode').on('click', function () {
        var loaderCircle = $(".msgbox svg");
        loaderCircle.show();
        $('#gam-message').css('color', 'inherit').text('Activating Manual Mode...');
        $.post(gam_ads_ad_manager_and_ad_exchange.ajaxUrl, {
            action: 'gamadsmbai_manual_mode_active',
            nonce: gam_ads_ad_manager_and_ad_exchange.nonce
        }, function (res) {
            if (res && res.success) {
                var msg = (res && res.data && res.data.message) ? res.data.message : 'Done';
                $('#gam-message').css('color', 'inherit').text(msg);
                if (!$('#gamadsai_manual_mode').data("settingpage")) {
                    $('#codepaste').hide();
                }
                const $NetworkSelect = $('#NetworkSelect');
                $NetworkSelect.show();
                $NetworkSelect.css('opacity', '1');
                let html = "<p>✅ Setup Complete. You'll be redirect home screen, if not click </p><button id='setupfinishnow' class=button>Finish Now</button>";
                $NetworkSelect.html(html);
                $('#setupfinishnow').on('click', () => { setStep(4); window.location.href = "/wp-admin/admin.php?page=gam-ads-ad-manager-and-ad-exchange"; });
                setStep(3);
                setTimeout(() => { setStep(4); location.href = "/wp-admin/admin.php?page=gam-ads-ad-manager-and-ad-exchange"; }, 3000);
            } else {
                var msg = (res && res.data && res.data.message) ? res.data.message : 'Unknown error';
                $('#gam-message').css('color', 'red').text('❌ ' + msg);
            }
            loaderCircle.hide();
        }).fail(function (xhr) {
            $('#gam-message').css('color', 'red').text('❌ Network/Server error');
            loaderCircle.hide();
        });
    })

    // Popup Model
    $('#gam-save-code-popup-model').on('click', function () {
        var code = $('#gam-auth-code-popup-model').val().trim();
        if (!code) {
            alert('Please enter the authorization code.');
            return;
        }
        var loaderCircle = $(".msgbox svg");
        loaderCircle.show();
        $('#gam-message').css('color', 'inherit').text('Requesting access token...');

        $.post(gam_ads_ad_manager_and_ad_exchange.ajaxUrl, {
            action: 'gam_ads_ad_manager_and_ad_exchange_save_auth_code',
            nonce: gam_ads_ad_manager_and_ad_exchange.nonce,
            auth_code: code // the handler also accepts `code`, but this is preferred
        }, function (res) {
            if (res && res.success) {
                var msg = (res && res.data && res.data.message) ? res.data.message : 'Done';
                $('#gam-message').css('color', 'inherit').text(msg);
                $('#codepaste').hide();
                $('#NetworkSelect').show();
                const $select = $('#network_code_select_popup_model');
                let html = '<option disabled selected value="">No Network Code Found !</option>';
                if (res?.data?.networks && (res?.data?.networks?.length > 0)) {
                    var netcd = res?.data?.networks;
                    html = '';
                    var CurrentNetworkCode = $select.attr('data-currentSelectedCode') || '';
                    netcd?.forEach((opt, ind) => {
                        var name = opt?.displayName;
                        var netcode = opt?.networkCode;
                        html += `<option ${CurrentNetworkCode && (parseInt(CurrentNetworkCode) === parseInt(netcode)) ? 'selected' : ''} value="${netcode}">${ind + 1} : ${name}, (${netcode})</option>`;
                    })
                }
                $select.html(html);
                setStep(3);
                $('#NetworkSelect').css('opacity', '1');
            } else {
                var msg = (res && res.data && res.data.message) ? res.data.message : 'Unknown error';
                $('#gam-message').css('color', 'red').text('❌ ' + msg);
            }
            loaderCircle.hide();
        }).fail(function (xhr) {
            $('#gam-message').css('color', 'red').text('❌ Network/Server error');
            loaderCircle.hide();
        });
    });

    $('#gam-disconnect').on('click', function () {
        if (!confirm('Are you sure you want to revoke access?')) return;
        $.post(gam_ads_ad_manager_and_ad_exchange.ajaxUrl, {
            action: 'gam_ads_ad_manager_and_ad_exchange_disconnect',
            nonce: gam_ads_ad_manager_and_ad_exchange.nonce,
        }, function (res) {
            if (res.success) location.reload();
            else alert('Failed to revoke access: ' + (res.data || ''));
        });
    });

    $('#refetchNetworks').on('click', function () {
        if (!confirm('Refresh Networks Code May Effect Current Ad Codes?')) return;
        var loaderCircle = $(".msgbox svg");
        loaderCircle.show();
        $('#gam-message').css('color', 'inherit').text('Refreshing Networks..');
        $.post(gam_ads_ad_manager_and_ad_exchange.ajaxUrl, {
            action: 'gam_ads_ad_manager_and_ad_exchange_refetch_networks',
            nonce: gam_ads_ad_manager_and_ad_exchange.nonce,
        }, function (res) {
            if (res.success) {
                var msg = (res && res.data && res.data.message) ? res.data.message : 'Done';
                $('#gam-message').css('color', 'inherit').text(msg);
                loaderCircle.hide();
                setTimeout(() => {
                    location.reload();
                }, 200);
            } else {
                var msg = (res && res.data && res.data.message) ? res.data.message : 'Unknown error';
                $('#gam-message').css('color', 'red').text('❌ ' + msg);
                alert('Failed: ' + (res.data || ''));
                loaderCircle.hide();
            };
        }).fail(function (xhr) {
            $('#gam-message').css('color', 'red').text('❌ Network/Server error');
            loaderCircle.hide();
        });
    });

    $('#gam-select-network-form').on('submit', function (e) {
        e.preventDefault();

        var formData = $(this).serialize();

        var loaderCircle = $(".msgbox svg");
        $.ajax({
            url: gam_ads_ad_manager_and_ad_exchange.ajaxUrl,
            type: 'POST',
            data: formData,
            beforeSend: function () {
                loaderCircle.show();
                $('#gam-message').css('color', 'inherit').text('Saving network...');
            },
            success: function (response) {
                var msg = (response && response.data && response.data.message) ? response.data.message : 'Done';
                $('#gam-message').css('color', 'inherit').text(msg);
                loaderCircle.hide();
                setTimeout(() => {
                    location.reload();
                }, 200);
            },
            error: function (xhr) {
                console.error('Network/Server error :', xhr.responseText);
                $('#gam-message').css('color', 'red').text('❌ Network/Server error');
                loaderCircle.hide();
            }
        });
    });

    // Popup Model
    $('#gam-select-network-form-popup-model').on('submit', function (e) {
        e.preventDefault();
        var formData = $(this).serialize();
        var loaderCircle = $(".msgbox svg");
        $.ajax({
            url: gam_ads_ad_manager_and_ad_exchange.ajaxUrl,
            type: 'POST',
            data: formData,
            beforeSend: function () {
                loaderCircle.show();
                $('#gam-message').css('color', 'inherit').text('Saving network...');
            },
            success: function (response) {
                var msg = (response && response.data && response.data.message) ? response.data.message : 'Done';
                $('#gam-message').css('color', 'inherit').html(msg + '<p>Setup Completed.</p>');
                loaderCircle.hide();
                setStep(4);
                setTimeout(() => {
                    location.reload();
                }, 2000);
            },
            error: function (xhr) {
                console.error('Network/Server error :', xhr.responseText);
                $('#gam-message').css('color', 'red').text('❌ Network/Server error');
                loaderCircle.hide();
            }
        });
    });

    $('#editnetworktoselect').on('click', function (e) {
        $('#gam-select-network-block').show();
        $(this).hide();
    });
});


// Manage Ads **************************
jQuery(document).ready(function ($) {
    function loadAds(page = 1, search = '') {
        $('#gam-ajax-loader').show();
        $('#gam-ads-list-container').html('<p>Loading...</p>');
        const rfrsadtr = $('#gam-ads-list-container').data('rfrsad');
        $.ajax({
            url: gam_ads_ad_manager_and_ad_exchange.ajaxUrl,
            method: 'POST',
            data: {
                action: 'gam_ads_ad_manager_and_ad_exchange_get_ads_list',
                nonce: gam_ads_ad_manager_and_ad_exchange.nonce,
                page: page,
                search: search,
            },
            success: function (res) {
                if (res.success) {
                    var ads = res.data.ads;
                    var totalPages = res.data.total_pages;
                    var currentPage = res.data.current_page;
                    var html = '<table class="gam-ads-table" style="width:100%; border-collapse: collapse;">';
                    html += '<thead><tr><th>ID</th><th>Ad Type</th><th>Ad Unit ID</th><th>Responsive</th>' + (rfrsadtr ? '<th>Refresh Ad</th>' : '') + '<th>Sizes</th><th>Visible On</th><th>Position</th><th>Alignment</th><th>Created At</th><th>Last Modified</th><th style="min-width: 110px">Actions</th></tr></thead><tbody>';
                    if (ads.length === 0) {
                        html += '<tr><td colspan="11" style="text-align:center;">No ads found</td></tr>';
                    } else {
                        // function escapeHtml(str) {
                        //     if (!str) return '';
                        //     return str.replace(/&/g, "&amp;")
                        //         .replace(/</g, "&lt;")
                        //         .replace(/>/g, "&gt;")
                        //         .replace(/"/g, "&quot;")
                        //         .replace(/'/g, "&#039;");
                        // }
                        function capitalizeFirst(str) {
                            if (!str) return '';
                            str = String(str);
                            return str
                                .split(',') // handle multiple pages
                                .map(item => item.trim())
                                .map(item =>
                                    item
                                        .split('_') // handle underscores
                                        .map(word => word.charAt(0).toUpperCase() + word.slice(1))
                                        .join(' ')
                                )
                                .join(', ');
                        }
                        // Handle responsive JSON object with new line display
                        function formatResponsiveSizes(jsonStr) {
                            if (!jsonStr) return '';
                            let obj;
                            try {
                                obj = JSON.parse(jsonStr);
                            } catch (e) {
                                return capitalizeFirst(jsonStr); // fallback if not JSON
                            }

                            return Object.entries(obj)
                                .map(([device, sizes]) => {
                                    return capitalizeFirst(device) + ': ' + sizes;
                                })
                                .join('<br>'); // new line for HTML table cell
                        }
                        ads.forEach(function (ad, index) {
                            html += '<tr>';
                            html += '<td>' + (parseInt(index) + 1) + '</td>';
                            html += '<td>' + capitalizeFirst(ad.ad_type) + '</td>';
                            html += '<td>' + (ad.gam_ad_unit || 'Default') + '</td>';
                            html += '<td>' + (parseInt(ad.is_responsive) === 1 ? 'Yes' : 'No') + '</td>';
                            if (rfrsadtr) {
                                html += '<td>' + ((parseInt(ad.is_refreshad) === 1) ? ('Yes, ' + (parseInt(ad.refreshad_intervel) === 60 ? '1 min' : (parseInt(ad.refreshad_intervel) + 's'))) : 'No') + '</td>';
                            }
                            html += '<td>' + (parseInt(ad.is_responsive) === 1 ? formatResponsiveSizes(ad.gam_responsive_sizes) : (ad.gam_ad_sizes ? capitalizeFirst(ad.gam_ad_sizes) : 'No Size')) + '</td>';
                            html += '<td>' + (parseInt(ad.show_entire_site) === 1 ? 'Entire Site' : capitalizeFirst(ad.visible_pages)) + '</td>';
                            html += '<td>' + (ad.ad_position ? (capitalizeFirst(ad.ad_position) + ' ' + ad.paragraph_counts + ' ' + capitalizeFirst(ad.custom_ad_position)) : 'Default') + '</td>';
                            html += '<td>' + (ad.ad_alignment ? capitalizeFirst(ad.ad_alignment) : 'Default') + '</td>';
                            html += '<td>' + ad.created_at + '</td>';
                            html += '<td>' + ad.updated_at + '</td>';
                            html += '<td><div class="manage_action_buttons"><button title="' + (ad.is_active == 1 ? 'This ad is ACTIVE right now' : 'This ad is INACTIVE right now') + '" class="gam-toggle-onoff-btn' + (ad.is_active == 1 ? " active" : "") + '" data-id="' + ad.id + '" data-status="' + ad.is_active + '"> <span class="gam-toggle-slider"></span> <span class="gam-label gam-on">ON</span> <span class="gam-label gam-off">OFF</span> </button>';
                            html += '<button title="Edit Ad" class="gam-edit-ad" data-id="' + ad.id + '" ><svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"><path fill-rule="evenodd" clip-rule="evenodd" d="m3.99 16.854-1.314 3.504a.75.75 0 0 0 .966.965l3.503-1.314a3 3 0 0 0 1.068-.687L18.36 9.175s-.354-1.061-1.414-2.122c-1.06-1.06-2.122-1.414-2.122-1.414L4.677 15.786a3 3 0 0 0-.687 1.068zm12.249-12.63 1.383-1.383c.248-.248.579-.406.925-.348.487.08 1.232.322 1.934 1.025.703.703.945 1.447 1.025 1.934.058.346-.1.677-.348.925L19.774 7.76s-.353-1.06-1.414-2.12c-1.06-1.062-2.121-1.415-2.121-1.415z" fill="#f5fbff"></path></g></svg></button> ';
                            html += '<button title="Delete Ad" class="gam-delete-ad" data-id="' + ad.id + '" ><svg viewBox="0 0 1024 1024" class="icon" version="1.1" xmlns="http://www.w3.org/2000/svg" fill="#000000"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"><path d="M667.8 362.1H304V830c0 28.2 23 51 51.3 51h312.4c28.4 0 51.4-22.8 51.4-51V362.2h-51.3z" fill="#fff0f0"></path><path d="M750.3 295.2c0-8.9-7.6-16.1-17-16.1H289.9c-9.4 0-17 7.2-17 16.1v50.9c0 8.9 7.6 16.1 17 16.1h443.4c9.4 0 17-7.2 17-16.1v-50.9z" fill="#fff0f0"></path><path d="M733.3 258.3H626.6V196c0-11.5-9.3-20.8-20.8-20.8H419.1c-11.5 0-20.8 9.3-20.8 20.8v62.3H289.9c-20.8 0-37.7 16.5-37.7 36.8V346c0 18.1 13.5 33.1 31.1 36.2V830c0 39.6 32.3 71.8 72.1 71.8h312.4c39.8 0 72.1-32.2 72.1-71.8V382.2c17.7-3.1 31.1-18.1 31.1-36.2v-50.9c0.1-20.2-16.9-36.8-37.7-36.8z m-293.5-41.5h145.3v41.5H439.8v-41.5z m-146.2 83.1H729.5v41.5H293.6v-41.5z m404.8 530.2c0 16.7-13.7 30.3-30.6 30.3H355.4c-16.9 0-30.6-13.6-30.6-30.3V382.9h373.6v447.2z" fill="#f5fcff"></path><path d="M511.6 798.9c11.5 0 20.8-9.3 20.8-20.8V466.8c0-11.5-9.3-20.8-20.8-20.8s-20.8 9.3-20.8 20.8v311.4c0 11.4 9.3 20.7 20.8 20.7zM407.8 798.9c11.5 0 20.8-9.3 20.8-20.8V466.8c0-11.5-9.3-20.8-20.8-20.8s-20.8 9.3-20.8 20.8v311.4c0.1 11.4 9.4 20.7 20.8 20.7zM615.4 799.6c11.5 0 20.8-9.3 20.8-20.8V467.4c0-11.5-9.3-20.8-20.8-20.8s-20.8 9.3-20.8 20.8v311.4c0 11.5 9.3 20.8 20.8 20.8z" fill="#f5fcff"></path></g></svg></button></td>';
                            html += '</div></tr>';
                            html += '</tr>';
                        });
                    }
                    html += '</tbody></table>';

                    // Pagination
                    if (totalPages > 1) {
                        html += '<div class="gam-pagination">';
                        for (var i = 1; i <= totalPages; i++) {
                            html += '<button class="gam-page-btn" data-page="' + i + '"' + (i === currentPage ? ' disabled' : '') + '>' + i + '</button>';
                        }
                        html += '</div>';
                    }

                    $('#gam-ads-list-container').html(html);
                } else {
                    $('#gam-ads-list-container').html('<p>Error loading ads</p>');
                }
                $('#gam-ajax-loader').hide();
            },
            error: function () {
                $('#gam-ajax-loader').hide();
                $('#gam-ads-list-container').html('<p>AJAX error occurred</p>');
            }
        });
    }

    loadAds();

    let DeBouncingsearchTimer = null;

    $('#gam-search-ads').on('input keyup', function (e) {
        const query = $(this).val();
        clearTimeout(DeBouncingsearchTimer);
        if (e.key === 'Enter') {
            loadAds(1, query);
            return;
        }
        DeBouncingsearchTimer = setTimeout(() => {
            loadAds(1, query);
        }, 1500);
    });


    $(document).on('click', '.gam-page-btn', function () {
        loadAds($(this).data('page'), $('#gam-search-ads').val());
    });

    $(document).on('click', '.gam-delete-ad', function () {
        if (!confirm('Are you sure you want to delete this ad?')) return;
        var adId = $(this).data('id');
        $('#gam-ajax-loader').show();
        $.ajax({
            url: gam_ads_ad_manager_and_ad_exchange.ajaxUrl,
            method: 'POST',
            data: {
                action: 'gam_ads_ad_manager_and_ad_exchange_delete_ad',
                nonce: gam_ads_ad_manager_and_ad_exchange.nonce,
                ad_id: adId,
            },
            success: function (res) {
                if (res.success) {
                    alert('Ad deleted successfully.');
                    loadAds();
                } else {
                    alert(res.data || 'Error deleting ad.');
                }
                $('#gam-ajax-loader').hide();
            },
            error: function () {
                $('#gam-ajax-loader').hide();
                alert('AJAX error occurred.');
            }
        });
    });

    $(document).on('click', '.gam-edit-ad', function () {
        var adId = $(this).data('id');
        window.location.href = "/wp-admin/admin.php?page=gam-ads-ad-manager-and-ad-exchange&tab=add-new-ad&edit_id=" + adId;
    });

    $(document).on('click', '.gam-toggle-onoff-btn', function () {
        $(this).toggleClass('active');
        $('#gam-ajax-loader').show();
        let btn = $(this);
        let adId = btn.data('id');
        let currentStatus = btn.data('status');
        let newStatus = currentStatus == 1 ? 0 : 1;
        $.post(gam_ads_ad_manager_and_ad_exchange.ajaxUrl, {
            action: 'gam_ads_ad_manager_and_ad_exchange_toggle_ad_status',
            nonce: gam_ads_ad_manager_and_ad_exchange.nonce,
            ad_id: adId,
            status: newStatus
        }, function (response) {
            if (response.success) {
                btn.text(newStatus == 1 ? 'On' : 'Off');
                btn.data('status', newStatus);
                loadAds();
            } else {
                alert(response.data || 'Failed to update status');
            }
            $('#gam-ajax-loader').hide();
        });
    });
});

// Premium Ads **************************
jQuery(document).ready(function ($) {
    // Verify License
    $('.lic-key-frm').on('submit', function (e) {
        e.preventDefault();
        var $form = $(this);
        var licenseKey = $form.find('input[name="license_key"]').val().trim();
        var $msgBox = $form.find('#valdtnmsgbx');
        var loaderCircle = $(".msgbox svg");
        var $btn = $form.find('button');
        $('.new-lic-key-buy a').removeAttr('href').css('cursor', 'default').css("background", '#ebac6d').on('click', function (e) {
            e.preventDefault();
        });
        if (!licenseKey) {
            $msgBox.html("<small style='color:#cc0000'>Please enter your licence key.</small>");
            return;
        }
        loaderCircle.show();
        $.ajax({
            url: gam_ads_ad_manager_and_ad_exchange.ajaxUrl,
            type: "POST",
            dataType: "json",
            data: {
                action: "gamadsmbai_check_licence_and_save",
                nonce: gam_ads_ad_manager_and_ad_exchange.nonce,
                license_key: licenseKey
            },
            beforeSend: function () {
                $btn.prop("disabled", true).text("Validating...");
                $msgBox.html("<small>Validating license...</small>");
            },
            success: function (res) {
                if (res && res.success) {
                    $msgBox.html("<small style='color:#28a745'>" + res.data.message + "</small>");
                    loaderCircle.hide();
                    // Delay so user sees message
                    setTimeout(function () {
                        location.reload();
                    }, 1200);
                } else {
                    var err = res && res.data && res.data.message ? res.data.message : "Invalid license";
                    $msgBox.html("<small style='color:#cc0000'>Error: " + err + "</small>");
                    loaderCircle.hide();
                    $btn.prop("disabled", false).text("Save");
                }
            },
            error: function () {
                $msgBox.html("<small style='color:#cc0000'>! Server error, Please try again.</small>");
                loaderCircle.hide();
                $btn.prop("disabled", false).text("Save");
            }
        });
    });

    $(document).on('click', '#gam-refresh-license', function () {
        var $btn = $(this);
        var $msgBox = $('#lic-remove-msg');
        var loaderCircle = $(".msgbox svg");
        $.ajax({
            url: gam_ads_ad_manager_and_ad_exchange.ajaxUrl,
            type: "POST",
            dataType: "json",
            data: {
                action: "gamadsmbai_refresh_licence_and_save",
                nonce: gam_ads_ad_manager_and_ad_exchange.nonce
            },
            beforeSend: function () {
                $btn.prop("disabled", true);
                $msgBox.html("<small>Refreshing license...</small>");
                loaderCircle.show();
            },
            success: function (res) {
                if (res && res.success) {
                    $msgBox.html("<small style='color:#28a745'>" + res.data.message + "</small>");
                    loaderCircle.hide();
                    setTimeout(function () {
                        location.reload();
                    }, 1200);
                } else {
                    var err = res && res.data && res.data.message ? res.data.message : "Failed.";
                    $msgBox.html("<small style='color:#cc0000'>Error: " + err + "</small>");
                    loaderCircle.hide();
                    $btn.prop("disabled", false)
                        .text("Deactivate License");
                }
            },
            error: function () {
                $msgBox.html("<small style='color:#cc0000'>! Server error.</small>");
                loaderCircle.hide();
                $btn.prop("disabled", false)
                    .text("Deactivate License");
            }
        });
    });

    // Remove & Revoke License
    $(document).on('click', '#gam-remove-license', function () {
        if (!confirm("Are you sure you want to deactivate this license on this site?")) {
            return;
        }
        var $btn = $(this);
        var $msgBox = $('#lic-remove-msg');
        var loaderCircle = $(".msgbox svg");

        $.ajax({
            url: gam_ads_ad_manager_and_ad_exchange.ajaxUrl,
            type: "POST",
            dataType: "json",
            data: {
                action: "gamadsmbai_remove_license",
                nonce: gam_ads_ad_manager_and_ad_exchange.nonce
            },
            beforeSend: function () {
                $btn.prop("disabled", true).text("Removing...");
                $msgBox.html("<small>Deactivating license...</small>");
                loaderCircle.show();
            },
            success: function (res) {
                if (res && res.success) {
                    $msgBox.html("<small style='color:#28a745'>" + res.data.message + "</small>");
                    loaderCircle.hide();
                    setTimeout(function () {
                        location.reload();
                    }, 1200);
                } else {
                    var err = res && res.data && res.data.message ? res.data.message : "Failed.";
                    $msgBox.html("<small style='color:#cc0000'>Error: " + err + "</small>");
                    loaderCircle.hide();
                    $btn.prop("disabled", false)
                        .text("Deactivate License");
                }
            },
            error: function () {
                $msgBox.html("<small style='color:#cc0000'>! Server error.</small>");
                loaderCircle.hide();
                $btn.prop("disabled", false)
                    .text("Deactivate License");
            }
        });
    });
    // Label Handling
    $("#banner_label_mng_frm").on('submit', function (e) {
        e.preventDefault();
        var $msgBox = $('#gam-message-label');
        var loaderCircle = $(".msgbox svg");
        $.ajax({
            url: gam_ads_ad_manager_and_ad_exchange.ajaxUrl,
            type: "POST",
            dataType: "json",
            data: {
                action: "gamadsmbai_save_adsbanners_label_showhide",
                nonce: gam_ads_ad_manager_and_ad_exchange.nonce,
                show_banner_ad_label: $('#show_banner_ad_label').is(':checked') ? 'on' : '',
                show_credit_label: $('#show_credit_label').is(':checked') ? 'on' : ''
            },
            beforeSend: function () {
                $msgBox.html("<small>Saving...</small>");
                loaderCircle.show();
            },
            success: function (res) {
                if (res && res.success) {
                    $msgBox.html("<small style='color:#28a745'>" + res.data.message + "</small>");
                    loaderCircle.hide();
                    setTimeout(function () {
                        $msgBox.html("");
                    }, 1200);
                } else {
                    var err = res && res.data && res.data.message ? res.data.message : "Failed.";
                    $msgBox.html("<small style='color:#cc0000'>Error: " + err + "</small>");
                    loaderCircle.hide();
                }
            },
            error: function () {
                $msgBox.html("<small style='color:#cc0000'>! Server error.</small>");
                loaderCircle.hide();
            }
        });
    });

    // Preview Demo Model **********************
    // Open Demo Button
    $('#openpreviewmodebutton').on('click', function (e) {
        e.preventDefault();
        const $preview = $('#previewmodeon');
        const $activeType = $('.gam-ad-type-item.active');
        $preview.toggleClass('active');
        if ($activeType.length) {
            $('#current_previewing_title').text(`${$activeType.data('type').toUpperCase()} DEMO AD`);
        } else {
            $('#current_previewing_title').text('PREVIEW DEMO AD');
        }
    });

    $('#closepreviewmodebutton').on('click', function (e) {
        e.preventDefault();
        $('#previewmodeon').removeClass('active');
        $('#current_previewing_title').text('PREVIEW DEMO AD');
    });

});

