/**
 * Contentosapp Studio Admin JavaScript
 *
 * This file now keeps only shared Settings/Agents interactions.
 * Other contexts were extracted into page-specific JS files under admin/js/.
 *
 * @package Contentosapp_Studio
 * @since   3.0.0
 */
/* global CostudioData, marked */
(function ($) {
    'use strict';

    var data = window.CostudioData || {};
    var ajax = data.ajax_url || '';
    var nonce = data.nonce || '';
    var i18n = data.i18n || {};

    // ── Helpers ───────────────────────────────────────────────────────────────

    $(document).ready(function () {
        fosInitWizard();
        fosInitDashboardWelcome();
    });

    /**
     * Dashboard welcome banner dismiss.
     */
    function fosInitDashboardWelcome() {
        var $banner = $('#fos-welcome-banner');
        if (!$banner.length) return;

        $banner.on('click', '#fos-dismiss-welcome', function (e) {
            e.preventDefault();
            $banner.fadeOut(300);
        });
    }

    // ── Setup Wizard ──────────────────────────────────────────────────────────

    function fosInitWizard() {
        var $wrap = $('.fos-wizard-wrap');
        if (!$wrap.length) return;

        var wizardNonce = $('#fos-wizard-nonce').val() || nonce;

        // Initialize button state based on current input value (handles pre-filled masked key).
        var $testBtn = $('#fos-wiz-test-btn');
        var $apiInput = $('#fos-wiz-apikey');
        $testBtn.prop('disabled', $apiInput.val().trim().length < 8);

        function focusWizardSiteAction() {
            window.setTimeout(function () {
                var $target = $('#fos-wiz-local-connect-btn:visible').first();
                if (!$target.length) {
                    $target = $('#fos-wiz-site-add-btn:visible').first();
                }
                if (!$target.length) {
                    return;
                }

                if (!$target.is('button, a, input, select, textarea')) {
                    $target.attr('tabindex', '-1');
                }

                $('html, body').animate({
                    scrollTop: Math.max(0, $target.offset().top - 120)
                }, 180);
                $target.trigger('focus');
            }, 80);
        }

        function goToSiteStepAndFocus() {
            goToStep(2);
            focusWizardSiteAction();
        }

        function goToStep(n) {
            $('.fos-wizard-panel').removeClass('is-active');
            $('#panel-' + n).addClass('is-active');

            // Update tabs
            for (var i = 1; i <= 3; i++) {
                var $tab = $('#step-tab-' + i);
                var $num = $('#step-num-' + i);
                $tab.removeClass('fos-wizard-step--active fos-wizard-step--done fos-wizard-step--pending');

                if (i < n) {
                    $tab.addClass('fos-wizard-step--done');
                    $num.text('✓');
                } else if (i === n) {
                    $tab.addClass('fos-wizard-step--active');
                    $num.text(i);
                } else {
                    $tab.addClass('fos-wizard-step--pending');
                    $num.text(i);
                }
            }

            // If reaching step 3, update the summary checklist based on current selections.
            if (n === 3) {
                // ── Site summary ─────────────────────────────────────────────
                var $connectedSites = $('#fos-wiz-sites-container .fos-wizard-site-connected');
                if ($connectedSites.length > 0) {
                    var siteNames = [];
                    $connectedSites.each(function () {
                        var name = $(this).find('.fos-wizard-site-name').clone().children('span').remove().end().text().trim();
                        if (name) { siteNames.push(name); }
                    });
                    var siteLabel = siteNames.length === 1
                        ? siteNames[0]
                        : siteNames.length + ' ' + (i18n.sites_connected || 'sites connected');
                    $('#fos-wiz-summary-site-dot')
                        .removeClass('fos-wizard-check__dot--warn')
                        .addClass('fos-wizard-check__dot--ok')
                        .text('✓');
                    $('#fos-wiz-summary-site').html(
                        '<strong>' + (i18n.wordpress_site || 'WordPress site') + '</strong> — ' +
                        siteLabel + ' ' + (i18n.connected_check || '✓ Connected!')
                    );
                } else {
                    $('#fos-wiz-summary-site-dot')
                        .removeClass('fos-wizard-check__dot--ok')
                        .addClass('fos-wizard-check__dot--warn')
                        .text('!');
                    $('#fos-wiz-summary-site').html(
                        '<strong>' + (i18n.wordpress_site || 'WordPress site') + '</strong> — ' +
                        (i18n.no_site_connected || 'No site connected — articles will be saved as drafts only.') + ' ' +
                        '<a href="#panel-2" id="fos-wiz-add-site-from-summary" class="fos-wizard-inline-action">' +
                        (i18n.add_site_settings || 'Adicionar um site nas Configurações →') +
                        '</a>'
                    );
                }

                var providerObj = $('.fos-wizard-provider.is-selected');
                var providerName = providerObj.find('.fos-wizard-provider__name').text();
                var rawProvider = providerObj.data('provider');

                $('#fos-wiz-summary-ai').html('<strong>' + (i18n.ai_provider || 'AI Provider') + '</strong> — ' + providerName + ' ' + (i18n.configured_and_tested || 'configured to generate.'));

                if (rawProvider === 'contentos') {
                    // Magic state! Everything is solved by ContentOS natively.
                    $('#fos-wiz-summary-img-dot').removeClass('fos-wizard-check__dot--skip').addClass('fos-wizard-check__dot--ok').text('✓');
                    $('#fos-wiz-summary-img').html('<strong>' + (i18n.image_provider || 'Image provider') + '</strong> — ContentOS Auto ' + (i18n.configured || 'configured successfully.'));

                    $('#fos-wiz-summary-search-dot').removeClass('fos-wizard-check__dot--skip').addClass('fos-wizard-check__dot--ok').text('✓');
                    $('#fos-wiz-summary-search').html('<strong>' + (i18n.web_search || 'Web Search') + '</strong> — ContentOS Auto Native Search ' + (i18n.configured || 'configured successfully.'));
                } else {
                    // Check BYOK state
                    var imgProvider = $('#fos-wiz-img-provider').val();
                    var imgKey = $('#fos-wiz-img-apikey').val().trim();
                    var searchProvider = $('#fos-wiz-search-provider').val();
                    var searchKey = $('#fos-wiz-search-apikey').val().trim();

                    if (imgProvider && imgKey) {
                        $('#fos-wiz-summary-img-dot').removeClass('fos-wizard-check__dot--skip').addClass('fos-wizard-check__dot--ok').text('✓');
                        $('#fos-wiz-summary-img').html('<strong>' + (i18n.image_provider || 'Image provider') + '</strong> — ' + imgProvider + ' ' + (i18n.configured || 'configured.'));
                    }
                    if (searchProvider && searchKey) {
                        $('#fos-wiz-summary-search-dot').removeClass('fos-wizard-check__dot--skip').addClass('fos-wizard-check__dot--ok').text('✓');
                        $('#fos-wiz-summary-search').html('<strong>' + (i18n.web_search || 'Web Search') + '</strong> — ' + searchProvider + ' ' + (i18n.configured || 'configured.'));
                    }
                }
            }
        }

        // Step 1: Provider Selection
        $wrap.on('click', '.fos-wizard-provider', function () {
            if ($(this).hasClass('is-disabled')) {
                var msg = i18n.provider_unavailable || 'Provider unavailable.';
                var $notice = $('<div class="fos-wizard-pro-notice" style="margin-top:10px;padding:10px 14px;background:var(--fos-primary-faint);border:1px solid var(--fos-primary-border);border-radius:var(--fos-radius-sm);font-size:13px;color:var(--fos-text)"></div>').html(msg);
                var $existing = $wrap.find('.fos-wizard-pro-notice');
                if ($existing.length) { $existing.replaceWith($notice); } else { $wrap.find('.fos-wizard-providers').after($notice); }
                setTimeout(function () { $notice.fadeOut(300, function () { $notice.remove(); }); }, 4000);
                return;
            }

            $('.fos-wizard-provider').removeClass('is-selected');
            $(this).addClass('is-selected');

            var provider = $(this).data('provider');
            $(this).find('input[type="radio"]').prop('checked', true);

            // Toggle banner
            $('#freetier-banner').toggle(provider === 'gemini');

            // Toggle UI sections depending on mode
            if (provider === 'contentos') {
                $('#fos-wiz-apikey-wrap').hide();
                $('#fos-wiz-byok-advanced').hide();
                $testBtn.prop('disabled', true);
                $('#fos-wiz-btn-1').prop('disabled', false); // Can continue immediately

                // Save the selection automatically to bypass connection test
                $.post(ajax, {
                    action: 'costudio_save_settings',
                    nonce: wizardNonce,
                    ai_provider: 'contentos',
                    ai_image_provider: 'contentos',
                    search_api_provider: 'contentos',
                    search_grounding: 1
                });
            } else {
                $('#fos-wiz-apikey-wrap').show();
                $('#fos-wiz-byok-advanced').show();

                // Reset test UI for BYOK
                $apiInput.val('');
                $('#fos-wiz-img-apikey, #fos-wiz-search-apikey').val('');
                $('#fos-wiz-img-provider, #fos-wiz-search-provider').val('');
                $('#fos-wiz-result-ok, #fos-wiz-result-err').hide();
                $testBtn.prop('disabled', true);
                $('#fos-wiz-btn-1').prop('disabled', true);

                // Placeholder
                var placeholders = {
                    'gemini': i18n.placeholder_gemini || 'Paste your Gemini API key here...',
                    'openai': i18n.placeholder_openai || 'sk-...',
                    'claude': i18n.placeholder_claude || 'sk-ant-...'
                };
                $('#fos-wiz-apikey').attr('placeholder', placeholders[provider] || '');
            }
        });

        // API Key input behavior
        $wrap.on('input', '#fos-wiz-apikey', function () {
            var val = $(this).val().trim();
            $testBtn.prop('disabled', val.length < 8);
            $('#fos-wiz-result-ok, #fos-wiz-result-err').hide();
        });

        // Test Connection
        $wrap.on('click', '#fos-wiz-test-btn', function () {
            var $btn = $(this);
            var provider = $('.fos-wizard-provider.is-selected').data('provider');
            var apiKey = $('#fos-wiz-apikey').val().trim();

            $btn.prop('disabled', true);
            $('#fos-wiz-result-loading').css('display', 'flex');
            $('#fos-wiz-result-ok, #fos-wiz-result-err').hide();

            $.post(ajax, {
                action: 'costudio_test_ai_connection',
                nonce: wizardNonce,
                provider: provider,
                api_key: apiKey
            }).done(function (res) {
                $('#fos-wiz-result-loading').hide();
                if (res.success) {
                    $('#fos-wiz-result-ok').css('display', 'flex');
                    $('#fos-wiz-btn-1').prop('disabled', false);
                    $('#fos-wiz-btn-1-hint').hide();

                    var imgProvider = $('#fos-wiz-img-provider').val();
                    var imgKey = $('#fos-wiz-img-apikey').val().trim();
                    var searchProvider = $('#fos-wiz-search-provider').val();
                    var searchKey = $('#fos-wiz-search-apikey').val().trim();

                    // Save the keys and providers formally
                    $.post(ajax, {
                        action: 'costudio_save_settings',
                        nonce: wizardNonce,
                        ai_mode: 'byok',
                        ai_provider: provider,
                        ai_api_key: apiKey,
                        ai_image_provider: imgProvider,
                        ai_image_api_key: imgKey,
                        costudio_image_mode: imgProvider ? 'generate' : '',
                        search_api_provider: searchProvider,
                        search_api_key: searchKey,
                        search_grounding: 0
                    });

                } else {
                    $('#fos-wiz-result-err').text('✕ ' + (res.data || i18n.error || 'Error')).css('display', 'flex');
                    $btn.prop('disabled', false);
                }
            }).fail(function () {
                $('#fos-wiz-result-loading').hide();
                $('#fos-wiz-result-err').text('✕ ' + (i18n.error || 'Error')).css('display', 'flex');
                $btn.prop('disabled', false);
            });
        });

        // Navigation
        $wrap.on('click', '#fos-wiz-btn-1', function () {
            var provider = $('.fos-wizard-provider.is-selected').data('provider');
            if (provider === 'contentos') {
                // Se foi ContentOS Auto, salva e depois pula, pois ele não clicou em testar chave.
                var $btn = $(this);
                $btn.prop('disabled', true).text('…');
                $.post(ajax, {
                    action: 'costudio_save_settings',
                    nonce: wizardNonce,
                    ai_mode: 'contentos',
                    ai_provider: 'contentos',
                    ai_image_provider: 'contentos',
                    costudio_image_mode: 'generate',
                    costudio_image_quantity: 1,
                    search_api_provider: 'contentos',
                    search_grounding: 1
                }).always(function () {
                    $btn.prop('disabled', false).text(i18n.continue_btn || 'Continue →');
                    goToStep(2);
                });
            } else {
                goToStep(2);
            }
        });
        $wrap.on('click', '#fos-wiz-back-2', function () { goToStep(1); });
        $wrap.on('click', '#fos-wiz-btn-2', function () { goToStep(3); });
        $wrap.on('click', '#fos-wiz-skip-2', function (e) { e.preventDefault(); goToStep(3); });
        $wrap.on('click', '#fos-wiz-back-3-provider', function () { goToStep(1); });
        $wrap.on('click', '#fos-wiz-back-3-site', function () { goToSiteStepAndFocus(); });
        $wrap.on('click', '#fos-wiz-add-site-from-summary', function (e) {
            e.preventDefault();
            goToSiteStepAndFocus();
        });

        // Set sessionStorage flag on any wizard exit so the dashboard shows the welcome banner.
        $wrap.on('click', '.fos-wizard-cta, .fos-wizard-skip, .fos-wizard-brand__skip, .fos-wizard-exit', function () {
            sessionStorage.setItem('costudio_from_wizard', '1');
        });

        // Step 2: Category helpers
        function fosWizRenderCatTags(categories) {
            var $wrap = $('#fos-wiz-cat-tags-wrap');
            $wrap.empty();
            if (!categories || !categories.length) {
                $wrap.html('<span class="fos-cat-area__empty">' + (i18n.categories_empty || 'No categories found.') + '</span>');
                return;
            }
            categories.forEach(function (cat) {
                $('<button type="button"></button>')
                    .addClass('fos-cat-tag')
                    .text(cat)
                    .on('click', function () { $(this).toggleClass('fos-cat-tag--selected'); })
                    .appendTo($wrap);
            });
        }

        function fosWizGetSelectedCats() {
            var names = [];
            $('#fos-wiz-cat-tags-wrap .fos-cat-tag--selected').each(function () {
                names.push($(this).text().trim());
            });
            return names.join(', ');
        }

        function fosWizResetCats() {
            $('#fos-wiz-cat-tags-wrap').html('<span class="fos-cat-area__empty">' + (i18n.categories_prompt || 'Enter the URL above and click "Load from site".') + '</span>');
            $('#fos-wiz-load-cats-btn').prop('disabled', false).text('🔄 ' + (i18n.load_from_site || 'Load from site'));
        }

        $wrap.on('click', '#fos-wiz-load-cats-btn', function () {
            var $btn = $(this);
            var $catWrap = $('#fos-wiz-cat-tags-wrap');
            var url = $('#fos-wiz-site-url').val().trim();

            if (!url) {
                alert(i18n.site_url_required || 'Please enter the site URL first.');
                return;
            }

            $btn.prop('disabled', true).text(i18n.loading || 'Loading…');
            $catWrap.html('<span class="fos-cat-area__loading"><span class="fos-conn-spinner"></span> ' + (i18n.categories_loading || 'Loading categories…') + '</span>');

            $.post(ajax, {
                action: 'costudio_fetch_site_categories',
                nonce: wizardNonce,
                url: url,
                user: $('#fos-wiz-site-user').val().trim(),
                password: $('#fos-wiz-site-pass').val().trim(),
            })
                .done(function (res) {
                    if (res && res.success && res.data && Array.isArray(res.data.categories)) {
                        fosWizRenderCatTags(res.data.categories);
                    } else {
                        var msg = (res && res.data && res.data.message) || (i18n.categories_fetch_error || 'Could not load categories.');
                        $catWrap.html('<span class="fos-cat-area__empty">' + $('<span>').text(msg).html() + '</span>');
                    }
                })
                .fail(function () {
                    $catWrap.html('<span class="fos-cat-area__empty">' + (i18n.categories_fetch_error || 'Could not load categories.') + '</span>');
                })
                .always(function () {
                    $btn.prop('disabled', false).text('🔄 ' + (i18n.load_from_site || 'Load from site'));
                });
        });

        // Local site: auto-connect
        $wrap.on('click', '#fos-wiz-local-connect-btn', function () {
            var $btn = $(this);
            var $card = $('#fos-wiz-local-connect-card');
            $btn.prop('disabled', true).text(i18n.loading || 'Connecting…');

            $.post(ajax, {
                action: 'costudio_connect_local_site',
                nonce: wizardNonce
            }).done(function (res) {
                if (res.success) {
                    var siteName = res.data.site_name || 'This site';
                    var siteUrl  = res.data.site_url  || '';
                    var siteKey  = res.data.site_key  || '__local__';

                    // Replace card with connected state
                    var $connected = $(
                        '<div class="fos-wizard-site-connected fos-wizard-site-local" data-site-key="' + siteKey + '">' +
                        '<div class="fos-wizard-site-dot"></div>' +
                        '<div>' +
                        '<div class="fos-wizard-site-name">' + $('<div>').text(siteName).html() +
                        ' <span class="fos-wizard-local-badge">' + (i18n.this_site || 'This site') + '</span></div>' +
                        '<div class="fos-wizard-site-url">' + $('<div>').text(siteUrl).html() +
                        ' · ' + (i18n.auto_connected || 'Auto-connected · no credentials needed') + '</div>' +
                        '</div>' +
                        '<div class="fos-wizard-site-actions">' +
                        '<span class="fos-wizard-site-remove" data-key="' + siteKey + '">✕ ' + (i18n.remove || 'Remove') + '</span>' +
                        '</div>' +
                        '</div>'
                    );
                    $card.replaceWith($connected);

                    // Enable continue button
                    $('#fos-wiz-btn-2').prop('disabled', false);
                } else {
                    $btn.prop('disabled', false).text(i18n.error || 'Error');
                }
            }).fail(function () {
                $btn.prop('disabled', false).text(i18n.error || 'Error — try again');
            });
        });

        // Step 2: Site Add — keep the add-site control in sync with the local allowance.
        function fosWizUpdateSiteLimit() {
            var max = parseInt($('#fos-wiz-max-sites').val(), 10) || 1;
            var count = $('#fos-wiz-sites-container .fos-wizard-site-connected').length;
            if (count >= max) {
                $('#fos-wiz-site-add-btn').hide();
                $('#fos-wiz-site-limit-notice').show();
            } else {
                $('#fos-wiz-site-add-btn').show();
                $('#fos-wiz-site-limit-notice').hide();
            }
        }

        $wrap.on('click', '#fos-wiz-site-add-btn', function () {
            // Re-check limit before opening form (defensive guard).
            var max = parseInt($('#fos-wiz-max-sites').val(), 10) || 1;
            var count = $('#fos-wiz-sites-container .fos-wizard-site-connected').length;
            if (count >= max) {
                fosWizUpdateSiteLimit();
                return;
            }
            $(this).fadeOut(150, function () {
                $('#fos-wiz-site-form').slideDown(250);
            });
        });

        $wrap.on('click', '#fos-wiz-cancel-site', function () {
            $('#fos-wiz-editing-key').val('');
            $('#fos-wiz-site-pass').attr('placeholder', $('#fos-wiz-site-pass').data('placeholder-new'));
            $('#fos-wiz-site-name, #fos-wiz-site-url, #fos-wiz-site-user, #fos-wiz-site-pass').val('');
            $('#fos-wiz-site-form').slideUp(200, function () {
                fosWizResetCats();
                fosWizUpdateSiteLimit();
            });
        });

        $wrap.on('click', '.fos-wizard-site-edit', function () {
            var $card = $(this).closest('.fos-wizard-site-connected');
            var siteKey = $card.data('site-key');
            var siteName = $card.data('site-name') || '';
            var siteUrl = $card.data('site-url') || '';
            var siteUser = $card.data('site-user') || '';
            var siteColor = $card.data('site-color') || '#3b82f6';

            // Pre-fill form
            $('#fos-wiz-site-name').val(siteName);
            $('#fos-wiz-site-url').val(siteUrl);
            $('#fos-wiz-site-user').val(siteUser);
            $('#fos-wiz-site-color').val(siteColor);
            $('#fos-wiz-site-pass').val('').attr('placeholder', $('#fos-wiz-site-pass').data('placeholder-edit'));
            $('#fos-wiz-editing-key').val(siteKey);
            fosWizResetCats();

            // Show form below this card
            $('#fos-wiz-site-add-btn').hide();
            $('#fos-wiz-site-form').insertAfter($card).slideDown(250);
        });

        $wrap.on('click', '.fos-wizard-site-remove', function () {
            var $card = $(this).closest('.fos-wizard-site-connected');
            var siteKey = $card.data('site-key');
            var $btn = $(this);

            $btn.text('…').css('pointer-events', 'none');

            $.post(ajax, {
                action: 'costudio_delete_site',
                nonce: wizardNonce,
                site_key: siteKey
            }).done(function (res) {
                if (res.success) {
                    $card.slideUp(200, function () {
                        if (siteKey === '__local__') {
                            // Restore the Plug & Play offer card
                            var homeUrl = data.home_url || '';
                            var $plugCard = $(
                                '<div class="fos-wizard-local-connect" id="fos-wiz-local-connect-card">' +
                                '<div class="fos-wizard-local-connect__icon">⚡</div>' +
                                '<div class="fos-wizard-local-connect__body">' +
                                '<div class="fos-wizard-local-connect__title">' +
                                (i18n.connect_this_site || 'Connect this site') +
                                ' <span class="fos-wizard-local-badge">' + (i18n.plug_and_play || 'Plug & Play') + '</span>' +
                                '</div>' +
                                '<div class="fos-wizard-local-connect__url">' + $('<div>').text(homeUrl).html() + '</div>' +
                                '<div class="fos-wizard-local-connect__sub">' + (i18n.no_credentials || 'No credentials needed — publishes directly to this WordPress installation.') + '</div>' +
                                '</div>' +
                                '<button type="button" class="fos-wizard-btn fos-wizard-btn--primary" id="fos-wiz-local-connect-btn">' +
                                (i18n.auto_connect_arrow || 'Auto-connect →') +
                                '</button>' +
                                '</div>'
                            );
                            $(this).replaceWith($plugCard);
                        } else {
                            $(this).remove();
                        }
                        fosWizUpdateSiteLimit();
                    });
                } else {
                    $btn.text('✕ ' + (i18n.remove || 'Remove')).css('pointer-events', '');
                    alert(res.data || i18n.error || 'Error');
                }
            }).fail(function () {
                $btn.text('✕ ' + (i18n.remove || 'Remove')).css('pointer-events', '');
            });
        });

        $wrap.on('click', '#fos-wiz-save-site', function () {
            var $btn = $(this);
            var name = $('#fos-wiz-site-name').val().trim();
            var url = $('#fos-wiz-site-url').val().trim();
            var user = $('#fos-wiz-site-user').val().trim();
            var pass = $('#fos-wiz-site-pass').val().trim();
            var color = $('#fos-wiz-site-color').val().trim() || '#3b82f6';
            var editingKey = $('#fos-wiz-editing-key').val().trim();
            var isEditing = editingKey !== '';

            if (!name || !url || !user || (!pass && !isEditing)) {
                alert(i18n.fields_required || 'Please fill all fields.');
                return;
            }

            var orig = $btn.text();
            $btn.prop('disabled', true).text('…');

            $.post(ajax, {
                action: 'costudio_save_site',
                nonce: wizardNonce,
                url: url,
                user: user,
                password: pass,
                name: name,
                color: color,
                old_key: editingKey,
                categories: fosWizGetSelectedCats()
            }).done(function (res) {
                if (res.success) {
                    var site = res.data.site;
                    var siteKey = site.key || '';
                    var cardHtml = '<div class="fos-wizard-site-connected"' +
                        ' data-site-key="' + siteKey + '"' +
                        ' data-site-name="' + $('<span>').text(site.name || '').html() + '"' +
                        ' data-site-url="' + $('<span>').text(site.url || '').html() + '"' +
                        ' data-site-color="' + $('<span>').text(site.color || '#3b82f6').html() + '"' +
                        ' data-site-user="' + $('<span>').text(site.user || '').html() + '">' +
                        '<div class="fos-wizard-site-dot"></div>' +
                        '<div>' +
                        '<div class="fos-wizard-site-name">' + $('<span>').text(site.name || site.url).html() + '</div>' +
                        '<div class="fos-wizard-site-url">' + $('<span>').text(site.url).html() + ' · ' + (i18n.connected || 'Connected') + '</div>' +
                        '</div>' +
                        '<div class="fos-wizard-site-actions">' +
                        '<span class="fos-wizard-site-edit">✎ ' + (i18n.edit || 'Edit') + '</span>' +
                        '<span class="fos-wizard-site-remove">✕ ' + (i18n.remove || 'Remove') + '</span>' +
                        '</div>' +
                        '</div>';

                    if (isEditing) {
                        $('#fos-wiz-sites-container .fos-wizard-site-connected[data-site-key="' + editingKey + '"]').replaceWith(cardHtml);
                    } else {
                        $('#fos-wiz-sites-container').append(cardHtml);
                    }

                    // Reset form state
                    $('#fos-wiz-editing-key').val('');
                    $('#fos-wiz-site-pass').attr('placeholder', $('#fos-wiz-site-pass').data('placeholder-new'));
                    $('#fos-wiz-site-name, #fos-wiz-site-url, #fos-wiz-site-user, #fos-wiz-site-pass').val('');
                    fosWizResetCats();

                    // Close form and enforce limit
                    $('#fos-wiz-site-form').slideUp(200, function () {
                        fosWizUpdateSiteLimit();
                        $('#fos-wiz-btn-2').prop('disabled', false);
                    });
                } else {
                    alert(res.data || i18n.error || 'Error');
                }
            }).always(function () {
                $btn.prop('disabled', false).text(orig);
            });
        });
    }
    // ── Tab switching (Studio page) ───────────────────────────────────────────

    function fosActivateStudioTab(tab, updateUrl) {
        if (typeof updateUrl === 'undefined') {
            updateUrl = true;
        }

        var $btn = $('.fos-studio-tab-btn[data-tab="' + tab + '"]');
        if (!$btn.length) { return; }

        // Update buttons
        $('.fos-studio-tab-btn').removeClass('is-active').attr('aria-selected', 'false');
        $btn.addClass('is-active').attr('aria-selected', 'true');

        // Update panels
        $('.fos-studio-panel').removeClass('is-active');
        $('#fos-studio-panel-' + tab).addClass('is-active');

        // Update Simple/Advanced toggle visibility
        if (tab === 'producao') {
            $('#fos-np-mode-toggle-wrap').show();
        } else {
            $('#fos-np-mode-toggle-wrap').hide();
        }

        // If Hub is activated, fetch latest data to prevent stale view
        if (tab === 'hub' && typeof window.fosLoadCentralTable === 'function') {
            window.fosLoadCentralTable(1);
        }

        // Update URL to preserve state
        if (updateUrl && window.history && window.history.pushState) {
            var newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
            var searchParams = new URLSearchParams(window.location.search);
            searchParams.set('tab', tab);
            newUrl += '?' + searchParams.toString();
            window.history.pushState({ path: newUrl }, '', newUrl);
        }
    }

    $(document).on('click', '.fos-studio-tab-btn', function (e) {
        e.preventDefault();
        fosActivateStudioTab($(this).data('tab'), true);
    });

    // Handle browser back/forward buttons for Studio tabs
    window.addEventListener('popstate', function (event) {
        var searchParams = new URLSearchParams(window.location.search);
        var tab = searchParams.get('tab') || 'hub';
        if ($('.fos-studio-tab-btn[data-tab="' + tab + '"]').length) {
            fosActivateStudioTab(tab, false);
        }
    });

    // Initialize Studio tab from URL if loaded as SPA
    $(document).ready(function() {
        if ($('.fos-studio-tab-btn').length) {
            var searchParams = new URLSearchParams(window.location.search);
            var tab = searchParams.get('tab') || 'hub';
            // Only force activation if URL explicitly sets it or if it's the default and not active
            if (!$('.fos-studio-panel.is-active').length) {
                 fosActivateStudioTab(tab, false);
            }
        }
    });

    // ── Tab switching (Settings page) ─────────────────────────────────────────

    function fosActivateTab(tab) {
        var $btn = $('.fos-tab-btn[data-tab="' + tab + '"]');
        if (!$btn.length) { return; }

        $('.fos-tab-btn').removeClass('is-active');
        $btn.addClass('is-active');

        $('.fos-tab-panel').removeClass('is-active');
        $('#fos-tab-' + tab).addClass('is-active');

        var $saveBar = $('#fos-settings-save-bar');
        if ($saveBar.length) {
            $saveBar.toggle(tab !== 'sites');
        }
    }

    // Restore tab after page reload.
    var _savedTab = sessionStorage.getItem('costudio_active_tab');
    if (_savedTab) {
        sessionStorage.removeItem('costudio_active_tab');
        fosActivateTab(_savedTab);
    }

    $(document).on('click', '.fos-tab-btn', function (e) {
        e.preventDefault();
        fosActivateTab($(this).data('tab'));
    });


    function initTelemetryConsentNotice() {
        var notice = document.getElementById('fos-telemetry-consent-notice');
        if (!notice) {
            return;
        }

        var acceptBtn = document.getElementById('fos-telemetry-notice-accept');
        var declineBtn = document.getElementById('fos-telemetry-notice-decline');
        var detailsLink = document.getElementById('fos-telemetry-notice-details');
        var modal = document.getElementById('fos-telemetry-notice-modal');
        var modalClose = document.getElementById('fos-telemetry-notice-modal-close');
        var modalX = document.getElementById('fos-telemetry-notice-modal-x');

        function closeModal() {
            if (modal) {
                modal.style.display = 'none';
            }
        }

        function saveConsent(consent) {
            if (acceptBtn) {
                acceptBtn.disabled = true;
            }
            if (declineBtn) {
                declineBtn.disabled = true;
            }

            $.post(ajax, {
                action: 'costudio_save_telemetry_consent',
                nonce: nonce,
                consent: consent
            }).done(function () {
                if (notice.parentNode) {
                    notice.parentNode.removeChild(notice);
                }
                closeModal();
            }).fail(function () {
                if (acceptBtn) {
                    acceptBtn.disabled = false;
                }
                if (declineBtn) {
                    declineBtn.disabled = false;
                }
            });
        }

        if (acceptBtn) {
            acceptBtn.addEventListener('click', function () { saveConsent(1); });
        }
        if (declineBtn) {
            declineBtn.addEventListener('click', function () { saveConsent(0); });
        }
        if (detailsLink && modal) {
            detailsLink.addEventListener('click', function (e) {
                e.preventDefault();
                modal.style.display = 'flex';
            });
        }
        if (modalClose) {
            modalClose.addEventListener('click', closeModal);
        }
        if (modalX) {
            modalX.addEventListener('click', closeModal);
        }
        if (modal) {
            modal.addEventListener('click', function (e) {
                if (e.target === modal) {
                    closeModal();
                }
            });
        }
    }

    function initWizardPrivacyConsent() {
        var card = document.getElementById('fos-wiz-privacy-card');
        if (!card) {
            return;
        }

        var confirmed = document.getElementById('fos-wiz-privacy-confirmed');
        var acceptBtn = document.getElementById('fos-wiz-privacy-accept');
        var declineBtn = document.getElementById('fos-wiz-privacy-decline');
        var detailsLink = document.getElementById('fos-wiz-privacy-details');
        var modal = document.getElementById('fos-wiz-privacy-modal');
        var modalClose = document.getElementById('fos-wiz-privacy-modal-close');
        var modalX = document.getElementById('fos-wiz-privacy-modal-x');
        var ctaPrimary = document.getElementById('fos-wiz-cta-primary');
        var ctaSecondary = document.getElementById('fos-wiz-cta-secondary');

        function unlockCtas() {
            [ctaPrimary, ctaSecondary].forEach(function (el) {
                if (!el) {
                    return;
                }
                el.style.pointerEvents = '';
                el.style.opacity = '';
                el.style.cursor = '';
            });
        }

        function saveConsent(consentValue) {
            if (acceptBtn) {
                acceptBtn.disabled = true;
            }
            if (declineBtn) {
                declineBtn.disabled = true;
            }

            $.post(ajax, {
                action: 'costudio_save_telemetry_consent',
                nonce: nonce,
                consent: consentValue
            }).done(function () {
                card.style.display = 'none';
                if (confirmed) {
                    confirmed.style.display = '';
                }
                unlockCtas();
            }).fail(function () {
                if (acceptBtn) {
                    acceptBtn.disabled = false;
                }
                if (declineBtn) {
                    declineBtn.disabled = false;
                }
                window.alert(i18n.telemetry_save_error || 'Could not save your preference. Please try again.');
            });
        }

        if (acceptBtn) {
            acceptBtn.addEventListener('click', function () { saveConsent(1); });
        }
        if (declineBtn) {
            declineBtn.addEventListener('click', function () { saveConsent(0); });
        }
        if (detailsLink && modal) {
            detailsLink.addEventListener('click', function (e) {
                e.preventDefault();
                modal.style.display = 'flex';
            });
        }

        function closePrivacyModal() {
            if (modal) {
                modal.style.display = 'none';
            }
        }

        if (modalClose) {
            modalClose.addEventListener('click', closePrivacyModal);
        }
        if (modalX) {
            modalX.addEventListener('click', closePrivacyModal);
        }
        if (modal) {
            modal.addEventListener('click', function (e) {
                if (e.target === modal) {
                    closePrivacyModal();
                }
            });
        }

        [ctaPrimary, ctaSecondary].forEach(function (el) {
            if (!el) {
                return;
            }
            el.addEventListener('click', function (e) {
                if (el.style.pointerEvents === 'none') {
                    e.preventDefault();
                }
            });
        });
    }

    function initByokWarningModal() {
        var modal = document.getElementById('fos-byok-warning-modal');
        if (!modal || modal.getAttribute('data-show') !== '1') {
            return;
        }

        var modalNonce = modal.getAttribute('data-nonce') || nonce;
        var btnConfirm = document.getElementById('fos-byok-warning-confirm');
        var btnCancel = document.getElementById('fos-byok-warning-cancel');
        var btnX = document.getElementById('fos-byok-warning-x');
        var $form = $('#fos-production-form');
        var pendingSubmit = false;

        function closeModal() {
            modal.style.display = 'none';
        }

        $form.on('submit.byokGate', function (e) {
            if (pendingSubmit) {
                return;
            }
            e.preventDefault();
            e.stopImmediatePropagation();
            modal.style.display = 'flex';
        });

        if (btnCancel) {
            btnCancel.addEventListener('click', closeModal);
        }
        if (btnX) {
            btnX.addEventListener('click', closeModal);
        }
        modal.addEventListener('click', function (e) {
            if (e.target === modal) {
                closeModal();
            }
        });

        if (btnConfirm) {
            btnConfirm.addEventListener('click', function () {
                btnConfirm.disabled = true;
                $.post(ajax, {
                    action: 'costudio_dismiss_byok_warning',
                    nonce: modalNonce
                }).always(function () {
                    closeModal();
                    $form.off('submit.byokGate');
                    pendingSubmit = true;
                    $form.trigger('submit');
                });
            });
        }
    }

    function initAdvancedSettingsControls() {
        var checkbox = document.getElementById('fos-uninstall-delete-data');
        var modal = document.getElementById('fos-uninstall-confirm-modal');
        var input = document.getElementById('fos-uninstall-confirm-input');
        var confirmBtn = document.getElementById('fos-uninstall-confirm-btn');
        var cancelBtn = document.getElementById('fos-uninstall-cancel-btn');

        if (checkbox && modal && input && confirmBtn && cancelBtn) {
            checkbox.addEventListener('change', function () {
                if (this.checked) {
                    this.checked = false;
                    modal.style.display = 'flex';
                    input.value = '';
                    confirmBtn.disabled = true;
                    confirmBtn.style.opacity = '0.5';
                    confirmBtn.style.pointerEvents = 'none';
                    input.focus();
                } else {
                    $.post(ajax, {
                        action: 'costudio_toggle_uninstall_data',
                        nonce: nonce,
                        enabled: 0
                    });
                }
            });

            input.addEventListener('input', function () {
                var ok = this.value.trim() === 'DELETE';
                confirmBtn.disabled = !ok;
                confirmBtn.style.opacity = ok ? '1' : '0.5';
                confirmBtn.style.pointerEvents = ok ? 'auto' : 'none';
            });

            cancelBtn.addEventListener('click', function () {
                modal.style.display = 'none';
                input.value = '';
            });

            confirmBtn.addEventListener('click', function () {
                checkbox.checked = true;
                modal.style.display = 'none';
                $.post(ajax, {
                    action: 'costudio_toggle_uninstall_data',
                    nonce: nonce,
                    enabled: 1
                });
            });

            modal.addEventListener('click', function (e) {
                if (e.target === modal) {
                    modal.style.display = 'none';
                    input.value = '';
                }
            });
        }

        function persist(option, enabled) {
            $.post(ajax, {
                action: 'costudio_toggle_advanced_option',
                nonce: nonce,
                option: option,
                enabled: enabled ? 1 : 0
            });
        }

        var autoRetry = document.getElementById('fos-auto-retry-agents');
        if (autoRetry) {
            autoRetry.addEventListener('change', function () {
                persist('costudio_auto_retry_agents', this.checked);
            });
        }

        var webSearch = document.getElementById('fos-enable-web-search');
        if (webSearch) {
            webSearch.addEventListener('change', function () {
                persist('costudio_enable_web_search', this.checked);
            });
        }

        var optimizeTables = document.getElementById('fos-housekeeping-optimize-tables');
        if (optimizeTables) {
            optimizeTables.addEventListener('change', function () {
                persist('costudio_housekeeping_optimize_tables', this.checked);
            });
        }

        var telemetry = document.getElementById('fos-telemetry-enabled');
        if (telemetry) {
            telemetry.addEventListener('change', function () {
                $.post(ajax, {
                    action: 'costudio_save_telemetry_consent',
                    nonce: nonce,
                    consent: this.checked ? 1 : 0
                });
            });
        }

        var detailsLink = document.getElementById('fos-telemetry-details-link');
        var detailsModal = document.getElementById('fos-telemetry-details-modal');
        var detailsClose = document.getElementById('fos-telemetry-details-close');
        var detailsX = document.getElementById('fos-telemetry-details-x');

        if (detailsLink && detailsModal) {
            detailsLink.addEventListener('click', function (e) {
                e.preventDefault();
                detailsModal.style.display = 'flex';
            });
        }

        function closeDetailsModal() {
            if (detailsModal) {
                detailsModal.style.display = 'none';
            }
        }

        if (detailsClose) {
            detailsClose.addEventListener('click', closeDetailsModal);
        }
        if (detailsX) {
            detailsX.addEventListener('click', closeDetailsModal);
        }
        if (detailsModal) {
            detailsModal.addEventListener('click', function (e) {
                if (e.target === detailsModal) {
                    closeDetailsModal();
                }
            });
        }
    }

    function initApiDiagnosis() {
        var btn = document.getElementById('fos-diagnose-api-btn');
        var box = document.getElementById('fos-diagnose-api-result');
        if (!btn || !box) {
            return;
        }

        var labels = {
            btn: i18n.diagnose_api_btn || 'Diagnose API connectivity',
            testing: i18n.testing || 'Testing...',
            loading: i18n.diagnose_api_loading || 'Running connectivity tests (PHP, DNS, TCP, HTTPS, REST API)... may take up to 60s.',
            title: i18n.diagnose_api_title || 'Connectivity report',
            badgeOk: i18n.diagnose_api_ok || 'All checks passed',
            badgeWarn: i18n.diagnose_api_warn || 'Some checks need attention',
            errGeneric: i18n.diagnose_api_unexpected || 'Unexpected response from the server.',
            netError: i18n.network_error || 'Network error',
            hideReport: i18n.hide_report || 'Hide',
            showReport: i18n.show_report || 'Show report'
        };

        function esc(value) {
            var d = document.createElement('div');
            d.textContent = value == null ? '' : String(value);
            return d.innerHTML;
        }

        function showBox() {
            box.style.display = 'block';
        }

        function renderLoading() {
            showBox();
            box.classList.remove('fos-diagnose-api-result--collapsed');
            box.className = 'fos-diagnose-api-result fos-diagnose-api-result--panel fos-diagnose-api-result--state-loading';
            box.innerHTML =
                '<div class="fos-diagnose-api-result__inner">' +
                '<div class="fos-diagnose-api-result__head">' +
                '<div class="fos-diagnose-api-result__head-main">' +
                '<span class="fos-diagnose-api-result__title">' + esc(labels.title) + '</span>' +
                '</div>' +
                '<button type="button" class="button-link fos-diagnose-api-result__toggle" aria-expanded="true">' + esc(labels.hideReport) + '</button>' +
                '</div>' +
                '<div class="fos-diagnose-api-result__scroll">' +
                '<p class="fos-diagnose-api-result__lead">' + esc(labels.loading) + '</p>' +
                '<div class="fos-diagnose-api-result__progress" role="progressbar" aria-busy="true"></div>' +
                '</div></div>';
        }

        function renderRows(rows) {
            var allOk = true;
            var idx;
            for (idx = 0; idx < rows.length; idx++) {
                if (!rows[idx].ok) {
                    allOk = false;
                    break;
                }
            }

            var state = allOk ? 'success' : 'warning';
            var badge = allOk ? labels.badgeOk : labels.badgeWarn;
            var html = '<div class="fos-diagnose-api-result__inner">';

            box.classList.remove('fos-diagnose-api-result--collapsed');
            html += '<div class="fos-diagnose-api-result__head">';
            html += '<div class="fos-diagnose-api-result__head-main">';
            html += '<span class="fos-diagnose-api-result__title">' + esc(labels.title) + '</span>';
            html += '<span class="fos-diagnose-api-result__badge fos-diagnose-api-result__badge--' + (allOk ? 'ok' : 'warn') + '">' + esc(badge) + '</span>';
            html += '</div>';
            html += '<button type="button" class="button-link fos-diagnose-api-result__toggle" aria-expanded="true">' + esc(labels.hideReport) + '</button>';
            html += '</div>';
            html += '<div class="fos-diagnose-api-result__scroll">';
            html += '<ul class="fos-diagnose-api-result__list">';
            for (idx = 0; idx < rows.length; idx++) {
                var row = rows[idx];
                var ok = !!row.ok;
                html += '<li class="fos-diagnose-api-result__row fos-diagnose-api-result__row--' + (ok ? 'ok' : 'fail') + '">';
                html += '<span class="fos-diagnose-api-result__mark" aria-hidden="true"></span>';
                html += '<div class="fos-diagnose-api-result__body">';
                html += '<div class="fos-diagnose-api-result__label">' + esc(row.test) + '</div>';
                html += '<div class="fos-diagnose-api-result__detail">' + esc(row.detail) + '</div>';
                html += '</div></li>';
            }
            html += '</ul></div></div>';

            box.className = 'fos-diagnose-api-result fos-diagnose-api-result--panel fos-diagnose-api-result--state-' + state;
            box.innerHTML = html;
        }

        function renderError(message) {
            showBox();
            box.classList.remove('fos-diagnose-api-result--collapsed');
            box.className = 'fos-diagnose-api-result fos-diagnose-api-result--panel fos-diagnose-api-result--state-error';
            box.innerHTML =
                '<div class="fos-diagnose-api-result__inner">' +
                '<div class="fos-diagnose-api-result__head">' +
                '<div class="fos-diagnose-api-result__head-main">' +
                '<span class="fos-diagnose-api-result__title">' + esc(labels.title) + '</span>' +
                '</div>' +
                '<button type="button" class="button-link fos-diagnose-api-result__toggle" aria-expanded="true">' + esc(labels.hideReport) + '</button>' +
                '</div>' +
                '<div class="fos-diagnose-api-result__scroll">' +
                '<p class="fos-diagnose-api-result__error">' + esc(message) + '</p>' +
                '</div></div>';
        }

        box.addEventListener('click', function (e) {
            var toggle = e.target.closest('.fos-diagnose-api-result__toggle');
            if (!toggle) {
                return;
            }
            e.preventDefault();
            var collapsed = box.classList.toggle('fos-diagnose-api-result--collapsed');
            toggle.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
            toggle.textContent = collapsed ? labels.showReport : labels.hideReport;
        });

        btn.addEventListener('click', function () {
            btn.disabled = true;
            btn.textContent = labels.testing;
            renderLoading();

            var fd = new FormData();
            fd.append('action', 'costudio_diagnose_api');
            fd.append('nonce', nonce);

            window.fetch(ajax, { method: 'POST', body: fd })
                .then(function (response) { return response.json(); })
                .then(function (json) {
                    btn.disabled = false;
                    btn.textContent = labels.btn;
                    if (!json.success || !json.data) {
                        renderError(labels.errGeneric + ' ' + JSON.stringify(json));
                        return;
                    }
                    renderRows(json.data);
                })
                .catch(function (err) {
                    btn.disabled = false;
                    btn.textContent = labels.btn;
                    renderError(labels.netError + ': ' + ((err && err.message) ? err.message : String(err)));
                });
        });
    }

    window.fosUpdateAiStatusBadge = function (mode) {
        var $badge = $('#fos-ai-status');
        if (!$badge.length) {
            return;
        }
        var $text = $badge.find('.fos-int-status__text');
        var hasKey = !!($('#fos-ai-api-key').val() || '').trim();

        function t(k, fallback) {
            return (typeof i18n[k] === 'string' && i18n[k].length) ? i18n[k] : fallback;
        }

        if (mode === 'byok') {
            if (hasKey) {
                $badge.removeClass('fos-int-status--warn').addClass('fos-int-status--ok');
                $text.text(t('api_key_saved', 'API key saved'));
            } else {
                $badge.removeClass('fos-int-status--ok').addClass('fos-int-status--warn');
                $text.text(t('api_key_pending', 'API key pending'));
            }
        } else {
            $badge.removeClass('fos-int-status--warn').addClass('fos-int-status--ok');
            $text.text(t('using_plan_quota', 'Using ContentOS Auto quota'));
        }
    };

    window.fosUpdateImgStatusBadge = function () {
        var $badge = $('#fos-image-status');
        if (!$badge.length) {
            return;
        }
        var $text = $badge.find('.fos-int-status__text');
        var imgMode = $('#fos-img-mode-value').val() || 'generate';
        var providerEl = document.getElementById('fos-image-provider');
        var provider = providerEl ? providerEl.value : '';
        var hasKey = !!($('#fos-image-api-key').val() || '').trim();

        function t(k, fallback) {
            return (typeof i18n[k] === 'string' && i18n[k].length) ? i18n[k] : fallback;
        }

        if (imgMode === 'none') {
            $badge.removeClass('fos-int-status--ok').addClass('fos-int-status--warn');
            $text.text(t('no_images_mode', 'No images'));
        } else if (imgMode === 'placeholder') {
            $badge.removeClass('fos-int-status--warn').addClass('fos-int-status--ok');
            $text.text(t('placeholder_mode', 'Suggesting placements'));
        } else if (provider === 'contentos') {
            $badge.removeClass('fos-int-status--warn').addClass('fos-int-status--ok');
            $text.text(t('using_plan_quota', 'Using ContentOS Auto quota'));
        } else if (provider && hasKey) {
            $badge.removeClass('fos-int-status--warn').addClass('fos-int-status--ok');
            $text.text(t('api_key_saved', 'API key saved'));
        } else if (provider && !hasKey) {
            $badge.removeClass('fos-int-status--ok').addClass('fos-int-status--warn');
            $text.text(t('api_key_pending', 'API key pending'));
        } else {
            $badge.removeClass('fos-int-status--ok').addClass('fos-int-status--warn');
            $text.text(t('select_provider_status', 'Provider not selected'));
        }
    };

    window.fosApplyGlobalExecutionMode = function (mode) {
        var providerSelect = document.getElementById('fos-image-provider');
        var imageModeEl = document.getElementById('fos-img-mode-value');
        var imageMode = imageModeEl ? imageModeEl.value : 'generate';
        var imgByokFields = document.getElementById('fos-img-byok-fields');
        var imgContentosInfo = document.getElementById('fos-img-contentos-info');
        var searchGrounding = document.getElementById('fos-search-grounding');
        var searchNativeRow = searchGrounding ? searchGrounding.closest('.fos-int-toggle-row') : null;
        var searchExternal = document.getElementById('fos-search-external-fields');

        function syncImageQuantityStepperMax() {
            var stepper = document.querySelector('.fos-img-qty-stepper');
            var valueInput = document.getElementById('fos-img-qty-value');
            var valueDisplay = document.getElementById('fos-img-qty-display');
            if (!stepper || !valueInput) {
                return;
            }

            var min = parseInt(stepper.getAttribute('data-min') || '1', 10);
            var maxAttr = mode === 'contentos'
                ? (stepper.getAttribute('data-contentos-max') || stepper.getAttribute('data-max'))
                : (stepper.getAttribute('data-byok-max') || stepper.getAttribute('data-max'));
            var max = parseInt(maxAttr || '3', 10);
            if (!Number.isFinite(min) || min < 1) { min = 1; }
            if (!Number.isFinite(max) || max < min) { max = min; }

            stepper.setAttribute('data-max', String(max));
            if (window.jQuery) {
                window.jQuery(stepper).data('max', max);
            }

            var current = parseInt(valueInput.value || String(min), 10);
            if (!Number.isFinite(current)) { current = min; }
            current = Math.max(min, Math.min(max, current));
            valueInput.value = String(current);
            if (valueDisplay) {
                valueDisplay.textContent = String(current);
            }
        }

        // Update service-gated state on the "Generate with AI" card.
        // PHP renders the initial state; JS must sync it when the mode switches.
        var formEl = document.getElementById('fos-settings-ai-form');
        var managedImagesUnavailable = !!(formEl && formEl.getAttribute('data-managed-images-unavailable') === '1');
        var genCard = document.querySelector('.fos-img-mode-card[data-mode="generate"]');
        if (mode === 'contentos' && managedImagesUnavailable && imageMode === 'generate') {
            imageMode = 'placeholder';
            if (imageModeEl) {
                imageModeEl.value = imageMode;
            }
            document.querySelectorAll('.fos-img-mode-card').forEach(function (card) {
                card.classList.remove('fos-img-mode-card--active');
            });
            var placeholderCard = document.querySelector('.fos-img-mode-card[data-mode="placeholder"]');
            if (placeholderCard) {
                placeholderCard.classList.add('fos-img-mode-card--active');
            }
            document.querySelectorAll('.fos-img-section').forEach(function (section) {
                section.classList.remove('fos-img-section--active');
            });
            var placeholderSection = document.getElementById('fos-img-section-placeholder');
            if (placeholderSection) {
                placeholderSection.classList.add('fos-img-section--active');
            }
        }
        if (genCard) {
            if (mode === 'byok') {
                genCard.classList.remove('fos-img-mode-card--service-gated');
                var existingBadge = genCard.querySelector('.fos-img-mode-plan-badge');
                if (existingBadge) { existingBadge.parentNode.removeChild(existingBadge); }
            } else if (managedImagesUnavailable) {
                genCard.classList.add('fos-img-mode-card--service-gated');
                if (!genCard.querySelector('.fos-img-mode-plan-badge')) {
                    var planBadge = document.createElement('span');
                    planBadge.className = 'fos-img-mode-plan-badge';
                    planBadge.textContent = (typeof i18n.contentos_auto_pro_studio === 'string' && i18n.contentos_auto_pro_studio.length)
                        ? i18n.contentos_auto_pro_studio
                        : 'Unavailable on this plan';
                    var iconRow = genCard.querySelector('.fos-img-mode-icon-row');
                    if (iconRow) { iconRow.appendChild(planBadge); } else { genCard.insertBefore(planBadge, genCard.firstChild); }
                }
            }
        }

        if (mode === 'contentos') {
            if (providerSelect && providerSelect.value && providerSelect.value !== 'contentos') {
                providerSelect.setAttribute('data-byok-last', providerSelect.value);
            }
            if (imageMode === 'generate' && providerSelect && providerSelect.value !== 'contentos') {
                providerSelect.value = 'contentos';
                if ($.fn.trigger) {
                    $(providerSelect).trigger('change');
                }
            }
            if (imgByokFields) {
                imgByokFields.style.display = 'none';
            }
            if (imgContentosInfo) {
                imgContentosInfo.style.display = imageMode === 'generate' ? 'block' : 'none';
            }
            if (searchNativeRow) {
                searchNativeRow.style.display = '';
                // Web search (native grounding) is available on every plan,
                // including Starter — never gate this row.
                searchNativeRow.classList.remove('fos-int-toggle-row--service-gated');
            }
            if (searchGrounding && !searchGrounding.checked) {
                searchGrounding.checked = true;
            }
            if (searchExternal) {
                searchExternal.style.display = 'none';
            }
        } else {
            if (imageMode === 'generate' && providerSelect && providerSelect.value === 'contentos') {
                var lastByok = providerSelect.getAttribute('data-byok-last') || '';
                providerSelect.value = lastByok;
                if (lastByok && $.fn.trigger) {
                    $(providerSelect).trigger('change');
                }
            }
            if (imgContentosInfo) {
                imgContentosInfo.style.display = 'none';
            }
            if (imgByokFields) {
                imgByokFields.style.display = imageMode === 'generate' ? '' : 'none';
            }
            if (searchGrounding) {
                searchGrounding.checked = false;
            }
            if (searchNativeRow) {
                searchNativeRow.style.display = 'none';
            }
            if (searchExternal) {
                searchExternal.style.display = '';
            }
        }

        window.fosUpdateImgStatusBadge();
        if (window.fosSyncSearchGroundingUI) {
            window.fosSyncSearchGroundingUI();
        }
        if (mode === 'byok' && $.fn.trigger) {
            $('#fos-search-grounding').trigger('change');
        }
        syncImageQuantityStepperMax();
    };

    window.fosSetAiMode = function (mode) {
        var input = document.getElementById('fos-ai-mode-input');
        if (input) {
            input.value = mode;
        }

        document.querySelectorAll('.fos-production-mode-grid .fos-aimode-card').forEach(function (card) {
            card.classList.remove('fos-img-mode-card--active');
        });

        var active = document.getElementById('fos-aimode-' + mode);
        if (active) {
            active.classList.add('fos-img-mode-card--active');
        }

        var byokFields = document.getElementById('fos-aimode-byok-fields');
        var contentosInfo = document.getElementById('fos-aimode-contentos-info');

        if (mode === 'byok') {
            if (byokFields) {
                byokFields.style.display = '';
            }
            if (contentosInfo) {
                contentosInfo.style.display = 'none';
            }
        } else {
            if (byokFields) {
                byokFields.style.display = 'none';
            }
            if (contentosInfo) {
                contentosInfo.style.display = '';
            }
        }

        window.fosApplyGlobalExecutionMode(mode);
        window.fosUpdateAiStatusBadge(mode);
    };

    $(document).on('click', '.fos-execution-option[data-ai-mode]', function () {
        window.fosSetAiMode($(this).data('aiMode') || 'contentos');
    });

    $(function () {
        initTelemetryConsentNotice();
        initWizardPrivacyConsent();
        initByokWarningModal();
        initAdvancedSettingsControls();
        initApiDiagnosis();

        var aiModeInput = document.getElementById('fos-ai-mode-input');
        if (aiModeInput) {
            window.fosApplyGlobalExecutionMode(aiModeInput.value || 'contentos');
        }
    });

    // ── Upgrade/License interactions were extracted to costudio-admin-license.js ──

    // Settings integrations/search/language handlers were extracted to:
    // - admin/js/costudio-admin-settings-integrations.js

    // Site settings/modal handlers were extracted to:
    // - admin/js/costudio-admin-sites.js

    // Hub (central table/plan/csv/filter) handlers were extracted to:
    // - admin/js/costudio-admin-hub.js

    // Production (nova produção + pipeline) handlers were extracted to:
    // - admin/js/costudio-admin-production.js

    // Detail handlers were extracted to:
    // - admin/js/costudio-admin-detail.js

    // Dashboard quick-add and Settings > Language preview were extracted to:
    // - admin/js/costudio-admin-dashboard.js
    // - admin/js/costudio-admin-settings-language.js


}(jQuery));
