/**
 * Contentosapp Studio Admin — New Production + pipeline interactions.
 */
/* global CostudioData, flatpickr */
(function ($) {
    'use strict';

    var data = window.CostudioData || {};
    var ajax = data.ajax_url || '';
    var nonce = data.nonce || '';
    var i18n = data.i18n || {};
    var aiFieldSuggestXhr = {};
    var aiFieldSuggestRequestId = {};
    function t(key, fallback) {
        return (typeof i18n[key] === 'string' && i18n[key].length) ? i18n[key] : fallback;
    }

    if (!$('#fos-production-form, #fos-preview-links-btn, #fos-site-key-select').length) {
        return;
    }

    function esc(str) {
        return $('<div>').text(str).html();
    }

    // ── Category select in Nova Produção form ────────────────────────────────

    $(document).on('change', '#fos-site-key-select', function () {
        var key = $(this).val();
        var cats = (data.site_cats || {})[key] || [];
        var $sel = $('#fos-categoria-select');
        $sel.empty().append('<option value="">— ' + esc(t('select_category', 'Select category')) + ' —</option>');
        $.each(cats, function (_, cat) {
            $sel.append('<option value="' + esc(cat) + '">' + esc(cat) + '</option>');
        });

        // Also update the hidden nicho field.
        var siteName = (data.site_map || {})[key] || '';
        $('#fos-nicho').val(siteName);

        // Security: clear internal references and search results to prevent cross-domain linking
        if (typeof internalSearchResults !== 'undefined') {
            internalSearchResults = null;
            internalLinks = [];
            $('#fos-links-keywords').val('');
            renderInternalResults();
        }

        fosSyncSummaryRail();
    });

    // ── Simple Mode Toggle ───────────────────────────────────────────────────

    $(document).on('click', '.fos-np-mode-label[data-np-mode]', function () {
        var mode = $(this).data('npMode') === 'advanced' ? 'advanced' : 'simple';
        $('#fos-np-mode-toggle').prop('checked', mode === 'advanced').trigger('change');
    });

    $(document).on('change', '#fos-np-mode-toggle', function () {
        var isAdvanced = $(this).is(':checked');
        var mode = isAdvanced ? 'advanced' : 'simple';
        var $section = $('#fos-form-section');

        if (isAdvanced) {
            $section.removeClass('fos-np-mode-simple').addClass('fos-np-mode-advanced');
            $('#fos-angulo, #fos-perfil').prop('required', true);
        } else {
            $section.removeClass('fos-np-mode-advanced').addClass('fos-np-mode-simple');
            $('#fos-angulo, #fos-perfil').prop('required', false);
        }

        // Save preference
        $.post(ajax, {
            action: 'costudio_save_np_mode',
            nonce: nonce,
            mode: mode
        });

        fosSyncSummaryRail();
    });

    // ── Summary Rail: Real-time Sync ─────────────────────────────────────────

    function fosSyncSummaryRail() {
        var $rail = $('.fos-summary-rail');
        if (!$rail.length) return;

        var isSimpleMode = $('#fos-form-section').hasClass('fos-np-mode-simple');

        // Angle / Title
        var angle = $('#fos-angulo').val() || '';
        var $anglePreview = $('#fos-summary-angle-preview');
        
        if (isSimpleMode) {
            $anglePreview.text(t('summary_ai_optimized', '✨ Optimized by AI')).removeClass('fos-summary-card__title--placeholder');
        } else if (angle) {
            $anglePreview.text(angle).removeClass('fos-summary-card__title--placeholder');
        } else {
            $anglePreview.text(t('summary_angle_placeholder', 'Your editorial angle appears here...')).addClass('fos-summary-card__title--placeholder');
        }

        // Type
        var type = $('input[name="article_type"]:checked').val();
        var typeLabels = {
            'pillar': '📚 ' + t('type_pilar', 'Pillar'),
            'satellite': '🛰️ ' + t('type_satellite', 'Satellite'),
            'comparison': '⚖️ ' + t('type_comparative', 'Comparison'),
            'news': '📰 ' + t('type_news', 'News'),
            'update': '🔄 ' + t('type_update', 'Update'),
        };
        $('#fos-summary-type-val').html('<span class="fos-status-pill fos-status-pill--planned">' + esc(typeLabels[type] || type) + '</span>');

        // Keyword
        var kw = $('#fos-keyword').val() || '';
        var $kwVal = $('#fos-summary-kw-val');
        if (kw) {
            $kwVal.text(kw).removeClass('fos-summary-row__val--empty');
        } else {
            $kwVal.text('—').addClass('fos-summary-row__val--empty');
        }

        // Site
        var siteKey = $('#fos-site-key-select').val();
        var siteName = (data.site_map || {})[siteKey] || '';
        var $siteVal = $('#fos-summary-site-val');
        if (siteName) {
            $siteVal.text(siteName).removeClass('fos-summary-row__val--empty');
        } else {
            $siteVal.text('—').addClass('fos-summary-row__val--empty');
        }

        // Category
        var cat = $('#fos-categoria-select').val() || '';
        var $catVal = $('#fos-summary-cat-val');
        if (cat) {
            $catVal.text(cat).removeClass('fos-summary-row__val--empty');
        } else {
            $catVal.text('—').addClass('fos-summary-row__val--empty');
        }

        // Content language (snapshotted for this production on submit)
        var $languageOption = $('#fos-content-language option:selected');
        var languageCode = $('#fos-content-language').val() || '';
        var languageName = $languageOption.data('language-name') || $languageOption.text().trim();
        var $languageVal = $('#fos-summary-language-val');
        var flagFile = (data.flag_map || {})[languageCode] || '';
        var flagUrl = flagFile && data.flag_url_base ? data.flag_url_base + flagFile : '';
        if (languageCode && languageName) {
            $('#fos-summary-language-name').text(languageName);
            $languageVal.removeClass('fos-summary-row__val--empty');
            if (flagUrl) {
                $('#fos-content-language-flag, #fos-summary-language-flag').attr('src', flagUrl).show();
            }
        } else {
            $('#fos-summary-language-name').text('—');
            $('#fos-content-language-flag, #fos-summary-language-flag').hide();
            $languageVal.addClass('fos-summary-row__val--empty');
        }

        // Reader (hidden in simple mode)
        var reader = $('#fos-perfil').val() || '';
        var $readerVal = $('#fos-summary-reader-val');
        if (isSimpleMode) {
            $readerVal.text(t('summary_ai_optimized_short', 'Auto')).removeClass('fos-summary-row__val--empty');
        } else if (reader) {
            $readerVal.text(reader).removeClass('fos-summary-row__val--empty');
        } else {
            $readerVal.text('—').addClass('fos-summary-row__val--empty');
        }

        // Publish Mode
        var pubMode = $('#fos-publish-mode').val();
        var pubLabels = {
            'draft': t('as_draft', 'As Draft'),
            'scheduled': t('scheduled', 'Scheduled'),
            'published': t('auto_publish', 'Auto-publish')
        };
        $('#fos-summary-publish-val').text(pubLabels[pubMode] || pubMode);

        // Progress Calculation
        var fields = [siteKey, cat, languageCode, kw];
        if (!isSimpleMode) {
            fields.push(angle);
            fields.push(reader);
        }
        if (type === 'comparison') {
            // Check if at least 2 items have text
            var compFilled = 0;
            $('.fos-comp-input').each(function() { if ($(this).val().trim()) compFilled++; });
            fields.push(compFilled >= 2 ? 'ok' : '');
        }
        if (type === 'news') {
            var newsFilled = 0;
            $('.fos-news-input').each(function() { if ($(this).val().trim()) newsFilled++; });
            fields.push(newsFilled >= 1 ? 'ok' : '');
        }
        if (type === 'update') {
            fields.push($('#fos-update-id').val() ? 'ok' : '');
            fields.push($('#fos-update-inst').val().trim() ? 'ok' : '');
        }

        var total = fields.length;
        var filled = fields.filter(Boolean).length;
        var pct = Math.round((filled / total) * 100);
        $('#fos-summary-pct').text(pct + '%');
        $('#fos-summary-fill').css('width', pct + '%');

        var $statusMsg = $('#fos-form-status-msg');
        if (pct >= 100) {
            $statusMsg.html('<span class="fos-np-footer-status--ready">✓ ' + t('ready_to_produce', 'Ready to start production') + '</span>');
        } else {
            $statusMsg.html('<span>' + t('complete_required', 'Complete the required fields to continue') + '</span>');
        }

        fosUpdatePipelinePreview(type);
    }

    function fosUpdatePipelinePreview(type) {
        // News: only Discoverer (1) is skipped.
        // Update: Discoverer (1), Brief (2), Research (3), Designer (5) and Social (6) are skipped
        // — only the Editor agent (4) runs on the original article.
        $('.fos-pipeline-step').each(function() {
            var step = parseInt($(this).data('step'), 10);
            var isSkipped = false;
            if (type === 'news' && step === 1) {
                isSkipped = true;
            } else if (type === 'update' && step !== 4) {
                isSkipped = true;
            }
            $(this).toggleClass('fos-pipeline-step--skipped', isSkipped);
            $(this).find('.fos-pipeline-step__num').text(isSkipped ? t('skipped', 'Skipped') : t('step_n', 'Step') + ' ' + step);
        });
    }

    // Bind inputs to summary sync
    $(document).on('input', '#fos-keyword, #fos-angulo, #fos-perfil, #fos-update-inst, .fos-comp-input, .fos-news-input', fosSyncSummaryRail);
    $(document).on('change', '#fos-categoria-select, #fos-content-language, #fos-publish-mode, #fos-exec-mode', fosSyncSummaryRail);

    function fosProductionAiFieldContextKey() {
        return [
            $.trim($('#fos-keyword').val() || '').toLowerCase(),
            $('#fos-site-key-select').val() || '',
            $.trim($('#fos-categoria-select').val() || '').toLowerCase(),
            $('input[name="article_type"]:checked').val() || '',
            $.trim($('#fos-angulo').val() || '').toLowerCase(),
            $.trim($('#fos-perfil').val() || '').toLowerCase(),
            $('#fos-content-language').val() || ''
        ].join('|');
    }

    function fosAiFieldDefaultLabel($btn) {
        var fieldType = $btn.data('field-type') || '';
        if (fieldType === 'angle') {
            return t('field_suggest_angle', 'Suggest angle');
        }
        if (fieldType === 'reader_profile') {
            return t('field_suggest_reader_profile', 'Suggest profile');
        }
        return t('field_suggest_ai', 'Suggest with AI');
    }

    function fosSetAiFieldButtonLabel($btn, label) {
        if ($btn.hasClass('fos-ai-input-suggest--adornment')) return;
        var $label = $btn.find('.fos-ai-input-suggest__label');
        if ($label.length) {
            $label.text(label);
            return;
        }
        $btn.text(label);
    }

    function fosSetAiFieldLoading($btn, isLoading) {
        var label = isLoading ? t('field_generating_ai', 'Generating...') : fosAiFieldDefaultLabel($btn);
        $btn.toggleClass('is-loading', isLoading)
            .prop('disabled', isLoading || $.trim($('#fos-keyword').val() || '').length < 4)
            .attr('aria-busy', isLoading ? 'true' : 'false');
        fosSetAiFieldButtonLabel($btn, label);
    }

    function fosUpdateAiFieldButtons() {
        var hasKeyword = $.trim($('#fos-keyword').val() || '').length >= 4;
        $('.fos-ai-input-suggest').each(function () {
            var $btn = $(this);
            if (!$btn.hasClass('is-loading')) {
                $btn.prop('disabled', !hasKeyword)
                    .attr('aria-busy', 'false');
                fosSetAiFieldButtonLabel($btn, fosAiFieldDefaultLabel($btn));
            }
        });
    }

    function fosShowAiFieldStatus($btn, message, type) {
        var $field = $btn.closest('.cts-field');
        var $status = $field.children('.fos-ai-field-status');
        if (!$status.length) {
            $status = $('<div class="fos-ai-field-status" aria-live="polite"></div>');
            var $hint = $field.find('.fos-field-hint').last();
            if ($hint.length) {
                $hint.after($status);
            } else {
                $field.append($status);
            }
        }

        $status
            .removeClass('fos-ai-field-status--error fos-ai-field-status--ok')
            .addClass(type === 'error' ? 'fos-ai-field-status--error' : 'fos-ai-field-status--ok')
            .text(message)
            .show();

        window.setTimeout(function () {
            $status.fadeOut(140, function () {
                $(this).text('').removeClass('fos-ai-field-status--error fos-ai-field-status--ok');
            });
        }, 4200);
    }

    function fosAiFieldErrorMessage(res) {
        if (res && res.responseJSON && res.responseJSON.data) {
            if (typeof res.responseJSON.data === 'string') return res.responseJSON.data;
            if (res.responseJSON.data.message) return res.responseJSON.data.message;
        }
        return t('field_ai_failed_soft', 'Could not generate a suggestion right now.');
    }

    $(document).on('input change', '#fos-keyword, #fos-site-key-select, #fos-categoria-select, #fos-content-language, input[name="article_type"]', fosUpdateAiFieldButtons);

    $(document).on('change', '#fos-content-language', function () {
        Object.keys(aiFieldSuggestXhr).forEach(function (fieldType) {
            var request = aiFieldSuggestXhr[fieldType];
            if (request && request.readyState !== 4) {
                request.abort();
            }
            aiFieldSuggestXhr[fieldType] = null;
            delete aiFieldSuggestRequestId[fieldType];
        });
        $('.fos-ai-field-status').stop(true, true).hide().text('');
        $('.fos-ai-input-suggest').each(function () {
            fosSetAiFieldLoading($(this), false);
        });
    });

    $(document).on('click', '.fos-ai-input-suggest', function () {
        var $btn = $(this);
        var keyword = $.trim($('#fos-keyword').val() || '');
        if (keyword.length < 4 || $btn.hasClass('is-loading')) return;

        var fieldType = $btn.data('field-type') || '';
        var target = $btn.data('target') || '';
        var $target = $(target);
        if (!$target.length) return;

        var requestId = String(Date.now()) + ':' + String(Math.random());
        aiFieldSuggestRequestId[fieldType] = requestId;
        var contextKey = fosProductionAiFieldContextKey();

        if (aiFieldSuggestXhr[fieldType] && aiFieldSuggestXhr[fieldType].readyState !== 4) {
            aiFieldSuggestXhr[fieldType].abort();
        }

        fosSetAiFieldLoading($btn, true);

        aiFieldSuggestXhr[fieldType] = $.post(ajax, {
            action: 'costudio_suggest_production_field',
            nonce: nonce,
            field_type: fieldType,
            keyword: keyword,
            site_key: $('#fos-site-key-select').val() || '',
            category: $('#fos-categoria-select').val() || '',
            article_type: $('input[name="article_type"]:checked').val() || '',
            angle: $('#fos-angulo').val() || '',
            reader_profile: $('#fos-perfil').val() || '',
            lang_code: $('#fos-content-language').val() || ''
        })
            .done(function (res) {
                if (aiFieldSuggestRequestId[fieldType] !== requestId || contextKey !== fosProductionAiFieldContextKey()) return;

                var suggestion = (res && res.success && res.data && res.data.suggestion)
                    ? String(res.data.suggestion)
                    : '';

                if (suggestion) {
                    $target.val(suggestion).trigger('input').trigger('change').trigger('focus');
                } else {
                    fosShowAiFieldStatus($btn, t('field_ai_failed_soft', 'Could not generate a suggestion right now.'), 'error');
                }
            })
            .fail(function (res) {
                if (res && res.statusText === 'abort') return;
                if (aiFieldSuggestRequestId[fieldType] !== requestId || contextKey !== fosProductionAiFieldContextKey()) return;

                fosShowAiFieldStatus($btn, fosAiFieldErrorMessage(res), 'error');
            })
            .always(function () {
                if (aiFieldSuggestRequestId[fieldType] !== requestId) return;

                aiFieldSuggestXhr[fieldType] = null;
                fosSetAiFieldLoading($btn, false);
            });
    });

    fosUpdateAiFieldButtons();

    // ── Segmented Control Handlers ───────────────────────────────────────────

    $(document).on('click', '.fos-np-segmented__btn', function() {
        var $btn = $(this);
        var $parent = $btn.closest('.fos-np-segmented');
        var mode = $btn.data('mode');
        
        $parent.find('.fos-np-segmented__btn').removeClass('is-active');
        $btn.addClass('is-active');

        if ($parent.attr('id') === 'fos-publish-mode-segmented') {
            $('#fos-publish-mode').val(mode).trigger('change');
            
            // Re-use existing logic for date picker and hints
            var $hint = $('#fos-publish-hint');
            var $dateWrap = $('#fos-publish-date-wrap');
            
            $dateWrap.hide();
            if (mode === 'draft') {
                $hint.text(t('hint_draft', 'Article saved as draft — review and publish manually.'));
            } else if (mode === 'scheduled') {
                $hint.text(t('hint_scheduled', 'Article scheduled for a future date.'));
                $dateWrap.show();
            } else {
                $hint.text(t('hint_published', 'Auto-publishes to the site immediately.'));
            }
        } else {
            $('#fos-exec-mode').val(mode).trigger('change');
            var $execHint = $('#fos-exec-hint');
            if (mode === 'auto') {
                $execHint.text(t('hint_exec_auto', 'The pipeline runs directly from Agent 1 to 7.'));
            } else {
                $execHint.text(t('hint_exec_manual', 'Pipeline pauses after each agent so you can review and approve.'));
            }
        }
    });

    // ── Radio group: article type → update hidden extensao field ─────────────

    function fosSyncArticleTypeRequiredFields(type) {
        var selectedType = type || $('input[name="article_type"]:checked').val() || 'satellite';
        $('#fos-update-inst').prop('required', selectedType === 'update');
    }

    function fosApplyArticleTypeState() {
        var val = $('input[name="article_type"]:checked').val() || 'satellite';
        var ext = {
            'pillar': '3000-5000',
            'satellite': '2000-2600',
            'comparison': '2500-4000',
            'news': '1000-1500',
            'update': '1500-2500',
        };
        $('#fos-extensao').val(ext[val] || '2000-2600');
        
        // Contextual panels logic (already in original code, but let's ensure rail syncs)
        $('.fos-type-panel').removeClass('fos-type-panel--active');
        $('.fos-type-panel[data-panel-type="' + val + '"]').addClass('fos-type-panel--active');
        fosSyncArticleTypeRequiredFields(val);
        
        fosSyncSummaryRail();
    }

    $(document).on('change', 'input[name="article_type"]', fosApplyArticleTypeState);
    $(document).on('click', '.fos-np-type-chip', function () {
        window.setTimeout(fosApplyArticleTypeState, 0);
    });

    // Run initial sync on load
    $(document).ready(function() {
        if ($('#fos-production-form').length) {
            fosSyncSummaryRail();

            // Initialize Flatpickr for the date field if available
            if (typeof flatpickr !== 'undefined') {
                flatpickr('#fos-publish-date', {
                    enableTime: true,
                    dateFormat: "Y-m-d\\TH:i",
                    altInput: true,
                    altFormat: "d/m/Y - H:i",
                    time_24hr: true,
                    minDate: "today",
                    minuteIncrement: 5
                });
            }
        }
    });

    // ── Referências do artigo: abas ───────────────────────────────────────────

    // Chip click: toggle visual state + native checkbox (solo chips are pointer-events:none via CSS)
    // e.preventDefault() prevents the browser from also natively toggling the checkbox after our handler,
    // which would cancel the toggle and leave visual/state out of sync.
    $(document).on('click', '.fos-chip:not(.fos-chip--solo)', function (e) {
        e.preventDefault();
        var $chip = $(this);
        var $cb = $('#' + $chip.attr('for'));
        var nowChecked = !$cb.is(':checked');
        $cb.prop('checked', nowChecked);
        $chip.toggleClass('fos-chip--active', nowChecked);
    });

    function hasPremiumSitePicker() {
        var $picker = $('#fos-links-site-checkboxes');
        return $picker.length && $picker.hasClass('fos-refs-site-picker');
    }

    function updateSitePickerSummary() {
        var $picker = $('#fos-links-site-checkboxes');
        if (!hasPremiumSitePicker()) return;

        var selectedSites = [];
        var total = 0;
        var checked = 0;
        var label = '';

        $picker.find('.fos-links-site-cb').each(function () {
            var $cb = $(this);
            var $option = $cb.next('.fos-refs-site-option');
            var isChecked = $cb.is(':checked');

            total++;
            $option
                .toggleClass('fos-refs-site-option--active', isChecked)
                .attr('aria-checked', isChecked ? 'true' : 'false');

            if (isChecked) {
                checked++;
                selectedSites.push({
                    key: $option.data('site-key') || $cb.val(),
                    label: $option.data('site-label') || $.trim($option.find('.fos-refs-site-option__name').text()) || $cb.val(),
                    initial: $option.data('site-initial') || '?',
                    accent: $option.data('site-accent') || '',
                    soft: $option.data('site-soft') || '',
                    border: $option.data('site-border') || ''
                });
            }
        });

        if (checked === total && total > 0) {
            label = $picker.data('label-all') || 'All sites';
        } else if (checked === 0) {
            label = $picker.data('label-none') || 'No site selected';
        } else if (checked === 1) {
            label = selectedSites[0].label;
        } else {
            label = ($picker.data('label-many') || '%d sites selected').replace('%d', checked);
        }

        $picker.find('.fos-refs-site-picker__summary').text(label);
        renderSitePickerBadges(selectedSites);
        $('#fos-links-sites-count').text(checked + ' / ' + total);
    }

    function renderSitePickerBadges(selectedSites) {
        var $badges = $('#fos-links-sites-badges');
        if (!$badges.length) return;

        $badges.empty();

        selectedSites.slice(0, 4).forEach(function (site) {
            var $badge = $('<span/>', {
                'class': 'fos-refs-site-badge',
                'data-site-key': site.key,
                text: site.initial
            });

            if (site.accent) {
                $badge.css('--fos-site-accent', site.accent);
            }
            if (site.soft) {
                $badge.css('--fos-site-soft', site.soft);
            }
            if (site.border) {
                $badge.css('--fos-site-border', site.border);
            }

            $badge.appendTo($badges);
        });

        if (selectedSites.length > 4) {
            $('<span/>', {
                'class': 'fos-refs-site-badge fos-refs-site-badge--more',
                text: '+' + (selectedSites.length - 4)
            }).appendTo($badges);
        }

        $badges.toggleClass('fos-refs-site-picker__badges--empty', selectedSites.length === 0);
    }

    function filterSitePickerOptions() {
        if (!hasPremiumSitePicker()) return;

        var query = ($('#fos-links-sites-search').val() || '').toString().trim().toLowerCase();
        var visibleCount = 0;

        $('#fos-links-site-checkboxes .fos-refs-site-option').each(function () {
            var $option = $(this);
            var name = ($option.data('site-name') || $option.text() || '').toString().toLowerCase();
            var isVisible = !query || name.indexOf(query) !== -1;

            $option.toggle(isVisible);
            if (isVisible) visibleCount++;
        });

        $('.fos-refs-site-picker__empty').prop('hidden', visibleCount > 0);
    }

    function closeSitePicker() {
        if (!hasPremiumSitePicker()) return;

        var $picker = $('#fos-links-site-checkboxes');
        $picker.removeClass('fos-refs-site-picker--open');
        $('#fos-links-sites-toggle').attr('aria-expanded', 'false');
        $('#fos-links-sites-menu').prop('hidden', true);
    }

    $(document).on('click', '#fos-links-sites-toggle', function (e) {
        e.preventDefault();
        e.stopPropagation();

        var $picker = $('#fos-links-site-checkboxes');
        var $menu = $('#fos-links-sites-menu');
        var isOpen = $picker.hasClass('fos-refs-site-picker--open');

        $picker.toggleClass('fos-refs-site-picker--open', !isOpen);
        $(this).attr('aria-expanded', isOpen ? 'false' : 'true');
        $menu.prop('hidden', isOpen);

        if (!isOpen) {
            $('#fos-links-sites-search').trigger('focus').trigger('select');
        }
    });

    $(document).on('click', '.fos-refs-site-picker__menu', function (e) {
        e.stopPropagation();
    });

    $(document).on('click', '.fos-refs-site-option', function (e) {
        e.preventDefault();

        var $option = $(this);
        var $cb = $('#' + $option.attr('for'));
        var nowChecked = !$cb.is(':checked');

        $cb.prop('checked', nowChecked);
        $option.toggleClass('fos-refs-site-option--active', nowChecked);
        updateSitePickerSummary();
    });

    $(document).on('keydown', '.fos-refs-site-option', function (e) {
        if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            $(this).trigger('click');
        }
    });

    $(document).on('input', '#fos-links-sites-search', filterSitePickerOptions);

    $(document).on('keydown', '#fos-links-sites-search', function (e) {
        if (e.key === 'Enter') {
            e.preventDefault();
        }
    });

    $(document).on('click', '.fos-refs-site-picker__action', function (e) {
        e.preventDefault();
        if (!hasPremiumSitePicker()) return;

        var action = $(this).data('site-action');
        var checked = action === 'all';

        $('#fos-links-site-checkboxes .fos-links-site-cb').prop('checked', checked);
        updateSitePickerSummary();
    });

    $(document).on('click', closeSitePicker);
    $(document).on('keydown', function (e) {
        if (e.key === 'Escape') {
            closeSitePicker();
        }
    });

    updateSitePickerSummary();
    filterSitePickerOptions();

    $(document).on('click', '.fos-refs-tab', function () {
        var tab = $(this).data('tab');
        $('.fos-refs-tab').removeClass('fos-refs-tab--active').attr('aria-selected', 'false');
        $(this).addClass('fos-refs-tab--active').attr('aria-selected', 'true');
        $('.fos-refs-panel').removeClass('fos-refs-panel--active').attr('hidden', true);
        $('#fos-refs-panel-' + tab).addClass('fos-refs-panel--active').removeAttr('hidden');
    });

    // ── Estado em memória ─────────────────────────────────────────────────────
    // Cada item interno: { title, url, site_key, site_name, post_type }
    // Cada item externo: { url, description }
    var internalSearchResults = null; // null means no search yet
    var internalLinks = []; // selected links only
    var externalLinks = [];

    // ── Contadores circulares das abas ────────────────────────────────────────

    function updateTabCounts() {
        var selInternal = internalLinks.length;
        $('span.fos-tab-count[data-tab="internal"]').text(selInternal);
        $('span.fos-tab-count[data-tab="external"]').text(externalLinks.length);
    }

    function isInternalLinkSelected(url) {
        return internalLinks.some(function(l) { return l.url === url; });
    }

    function renderInternalResults() {
        var $list = $('#fos-links-result-list');
        var $wrap = $('#fos-links-results-wrap');
        var $empty = $('#fos-links-empty-msg');

        var $selectedList = $('#fos-links-selected-list');
        var $selectedWrap = $('#fos-links-selected-wrap');
        var $selectedCount = $('#fos-links-selected-count');

        $list.empty();
        $selectedList.empty();
        updateTabCounts();

        // Render Search Results
        if (internalSearchResults === null) {
            $wrap.hide();
            $empty.show();
        } else if (internalSearchResults.length === 0) {
            $wrap.hide();
            $empty.text(t('no_results_found', 'No results found.')).show();
        } else {
            $empty.hide();
            $wrap.show();

            $.each(internalSearchResults, function (idx, item) {
                var typeLabel = item.post_type === 'page' ? t('page_label', 'Page') : t('post_label', 'Post');
                var isSelected = isInternalLinkSelected(item.url);
                var itemClass = 'fos-links-result-item' + (isSelected ? ' fos-links-result-item--selected' : ' fos-links-result-item--unselected');
                var cbClass = 'fos-result-checkbox' + (isSelected ? ' fos-result-checkbox--checked' : '');
                var typeClass = 'fos-links-badge fos-links-badge--type' + (item.post_type === 'page' ? ' fos-links-badge--page' : '');
                var $item = $(
                    '<div class="' + itemClass + '" data-idx="' + idx + '">' +
                    '<div class="' + cbClass + '" aria-hidden="true">' +
                    '<svg class="fos-result-check-icon" viewBox="0 0 10 8" fill="none" xmlns="http://www.w3.org/2000/svg">' +
                    '<path d="M1 4l3 3 5-6" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>' +
                    '</svg>' +
                    '</div>' +
                    '<div class="fos-links-result-item__title">' + esc(item.title) + '</div>' +
                    '<div class="fos-links-result-badges">' +
                    '<span class="fos-links-badge fos-links-badge--site">' + esc(item.site_name) + '</span>' +
                    '<span class="' + typeClass + '">' + esc(typeLabel) + '</span>' +
                    '</div>' +
                    '</div>'
                );
                $list.append($item);
            });

            // Update result footer (toggle all based on current search results)
            var totalInSearch = internalSearchResults.length;
            var selectedInSearch = internalSearchResults.filter(function(i) { return isInternalLinkSelected(i.url); }).length;
            var allSelInSearch = totalInSearch > 0 && selectedInSearch === totalInSearch;

            $('#fos-links-count-label').html(
                '<strong>' + selectedInSearch + '</strong> ' + t('of', 'of') + ' ' + totalInSearch + ' ' + t('links_selected', 'selected links')
            );
            $('#fos-links-toggle-all-btn').text(
                allSelInSearch ? t('deselect_all', 'Deselect all') : t('select_all', 'Select all')
            );
        }

        // Render Selected Links
        if (internalLinks.length > 0) {
            $selectedCount.text(internalLinks.length);
            $.each(internalLinks, function(idx, item) {
                var $selItem = $(
                    '<div style="display:flex; gap:8px; padding:6px 10px; background:var(--fos-primary-faint); border:1px solid var(--fos-primary-border); border-radius:6px; align-items:center;">' +
                    '<span style="font-size:12.5px; font-weight:600; color:var(--fos-text); flex:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">' + esc(item.title) + '</span>' +
                    '<button type="button" class="fos-internal-remove-btn" data-url="' + esc(item.url) + '" style="border:none; background:transparent; color:var(--fos-text-dim); cursor:pointer; font-size:13px; line-height:1; padding:0 4px;">×</button>' +
                    '</div>'
                );
                $selectedList.append($selItem);
            });
            $selectedWrap.show();
        } else {
            $selectedWrap.hide();
        }
    }

    $(document).on('click', '.fos-links-result-item', function () {
        var idx = parseInt($(this).data('idx'), 10);
        var item = internalSearchResults[idx];
        if (!item) return;

        if (isInternalLinkSelected(item.url)) {
            internalLinks = internalLinks.filter(function(l) { return l.url !== item.url; });
        } else {
            internalLinks.push(item);
        }
        renderInternalResults();
    });

    $(document).on('click', '.fos-internal-remove-btn', function(e) {
        e.stopPropagation();
        var urlToRemove = $(this).data('url');
        internalLinks = internalLinks.filter(function(l) { return l.url !== urlToRemove; });
        renderInternalResults();
    });

    $(document).on('click', '#fos-links-toggle-all-btn', function () {
        if (!internalSearchResults || !internalSearchResults.length) return;

        var selectedInSearch = internalSearchResults.filter(function(i) { return isInternalLinkSelected(i.url); }).length;
        var allSelInSearch = selectedInSearch === internalSearchResults.length;

        if (allSelInSearch) {
            // Deselect all from current search results
            var urlsToRemove = internalSearchResults.map(function(i) { return i.url; });
            internalLinks = internalLinks.filter(function(l) { return urlsToRemove.indexOf(l.url) === -1; });
        } else {
            // Select all from current search results
            internalSearchResults.forEach(function(item) {
                if (!isInternalLinkSelected(item.url)) {
                    internalLinks.push(item);
                }
            });
        }
        renderInternalResults();
    });

    $(document).on('click', '#fos-links-clear-btn', function () {
        internalSearchResults = null;
        $('#fos-links-keywords').val('');
        $('#fos-preview-links-btn').removeClass('fos-np-btn-search-wp--loading');

        renderInternalResults();
    });

    $(document).on('click', '#fos-preview-links-btn', function () {
        var siteKeys = [];
        $('#fos-links-site-checkboxes .fos-links-site-cb:checked').each(function () {
            siteKeys.push($(this).val());
        });

        var postTypes = [];
        $('.fos-links-type-cb:checked').each(function () {
            postTypes.push($(this).val());
        });

        var keywords = $('#fos-links-keywords').val().trim();

        if (!siteKeys.length) { alert(t('select_site_first', 'Select at least one site.')); return; }
        if (!postTypes.length) { alert(t('select_type_first', 'Select at least one content type.')); return; }
        if (!keywords) { alert(t('enter_keywords', 'Enter keywords to search.')); return; }

        var $btn = $('#fos-preview-links-btn');
        $btn.addClass('fos-np-btn-search-wp--loading');

        var postData = {
            action: 'costudio_preview_links',
            nonce: nonce,
            keywords: keywords,
        };

        // Send arrays using bracket notation expected by PHP.
        $.each(siteKeys, function (i, v) { postData['site_keys[' + i + ']'] = v; });
        $.each(postTypes, function (i, v) { postData['post_types[' + i + ']'] = v; });

        $.post(ajax, postData)
            .done(function (res) {
                $btn.removeClass('fos-np-btn-search-wp--loading');

                if (res.success && res.data.links) {
                    internalSearchResults = res.data.links;
                } else {
                    internalSearchResults = [];
                }
                renderInternalResults();
            })
            .fail(function () {
                $btn.removeClass('fos-np-btn-search-wp--loading');
                internalSearchResults = null;
                renderInternalResults();
                alert(t('request_failed_connection', 'Request failed. Check your connection.'));
            });
    });

    $(document).on('keydown', '#fos-links-keywords', function (e) {
        if (e.key !== 'Enter' || e.isComposing) return;
        e.preventDefault();
        $('#fos-preview-links-btn').trigger('click');
    });

    var EXT_WARN_THRESHOLD = 10;

    function renderExternalList() {
        var $list = $('#fos-ext-list');
        var $empty = $('#fos-ext-empty-msg');
        var $warn = $('#fos-ext-many-warn');

        $list.empty();

        if (!externalLinks.length) {
            $list.hide();
            $empty.show();
            $warn.hide();
            updateTabCounts();
            return;
        }

        $empty.hide();
        $list.show();

        $.each(externalLinks, function (idx, item) {
            var shortUrl = item.url.length > 60 ? item.url.slice(0, 57) + '…' : item.url;
            var chainIcon = '<svg width="14" height="14" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">' +
                '<path d="M7.5 10.5a3.5 3.5 0 0 0 5 0l2-2a3.536 3.536 0 0 0-5-5L8 5" stroke="#0F6E56" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>' +
                '<path d="M10.5 7.5a3.5 3.5 0 0 0-5 0l-2 2a3.536 3.536 0 0 0 5 5L10 13" stroke="#0F6E56" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>' +
                '</svg>';
            var $item = $(
                '<div class="fos-ext-item">' +
                '<div class="fos-ext-item__icon" aria-hidden="true">' + chainIcon + '</div>' +
                '<div class="fos-ext-item__info">' +
                '<a class="fos-ext-item__url" href="' + esc(item.url) + '" target="_blank" rel="noopener" title="' + esc(item.url) + '">' + esc(shortUrl) + '</a>' +
                (item.description ? '<span class="fos-ext-item__desc">' + esc(item.description) + '</span>' : '') +
                '</div>' +
                '<button type="button" class="fos-ext-item__remove" data-idx="' + idx + '" aria-label="' + t('remove', 'Remove') + '">×</button>' +
                '</div>'
            );
            $list.append($item);
        });

        $warn.toggle(externalLinks.length > EXT_WARN_THRESHOLD);
        updateTabCounts();
    }

    $(document).on('click', '.fos-ext-item__remove', function () {
        var idx = parseInt($(this).data('idx'), 10);
        externalLinks.splice(idx, 1);
        renderExternalList();
    });

    $(document).on('click', '#fos-ext-add-btn', function () {
        var url = $.trim($('#fos-ext-url').val());
        var desc = $.trim($('#fos-ext-desc').val());

        if (!url) {
            alert(t('url_required', 'Enter the URL before adding.'));
            $('#fos-ext-url').focus();
            return;
        }

        // Basic URL validation.
        try {
            var parsed = new URL(url);
            if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
                throw new Error('protocol');
            }
        } catch (_) {
            alert(t('url_invalid', 'Invalid URL. Use format https://example.com/article'));
            $('#fos-ext-url').focus();
            return;
        }

        externalLinks.push({ url: url, description: desc });
        renderExternalList();

        $('#fos-ext-url').val('').focus();
        $('#fos-ext-desc').val('');
    });

    $(document).on('keydown', '#fos-ext-url, #fos-ext-desc', function (e) {
        if (e.key !== 'Enter' || e.isComposing) return;
        e.preventDefault();
        $('#fos-ext-add-btn').trigger('click');
    });
    // ────────────────────────────────────────────────────────────────────────
    // ── PRODUCTION SUBMIT FLOW ──────────────────────────────────────────────
    // ────────────────────────────────────────────────────────────────────────

    // ── Publish Mode Selector ──────────────────────────────────────────────────

    var $publishPills = $('.fos-np-publish-pill');
    var $publishInput = $('#fos-publish-mode');
    var $publishHint = $('#fos-publish-hint');
    var $publishDateWrap = $('#fos-publish-date-wrap');
    var $publishDateInput = $('#fos-publish-date');

    // Default datetime calculation (tomorrow 09:00 AM)
    if ($publishDateInput.length && !$publishDateInput.val()) {
        var tmr = new Date();
        tmr.setDate(tmr.getDate() + 1);
        tmr.setHours(9, 0, 0, 0);
        // Format to YYYY-MM-DDTHH:mm
        var pad = function (n) { return n < 10 ? '0' + n : n; };
        var dtString = tmr.getFullYear() + '-' + pad(tmr.getMonth() + 1) + '-' + pad(tmr.getDate()) + 'T' + pad(tmr.getHours()) + ':' + pad(tmr.getMinutes());
        $publishDateInput.val(dtString);
    }

    $publishPills.on('click', function () {
        var $btn = $(this);
        var mode = $btn.data('mode');

        $publishPills.removeClass('is-active');
        $btn.addClass('is-active');
        $publishInput.val(mode);

        if (mode === 'scheduled') {
            $publishHint.text(t('publish_hint_scheduled', 'Scheduled article - set publication date and time below.'));
            $publishDateWrap.fadeIn(200);
            updateDateHint();
        } else {
            $publishDateWrap.hide();
            if (mode === 'draft') {
                $publishHint.text(t('publish_hint_draft', 'Article saved as draft - review and publish manually.'));
            } else if (mode === 'published') {
                $publishHint.text(t('publish_hint_published', 'Article published immediately after the pipeline finishes.'));
            }
        }
    });

    function updateDateHint() {
        if ($publishInput.val() !== 'scheduled') return;

        var val = $publishDateInput.val();
        if (!val) {
            $publishHint.text(t('publish_hint_scheduled_req', 'Invalid date - fill in the scheduling field.'));
            return;
        }

        var selected = new Date(val).getTime();
        var now = new Date().getTime();
        var diff = selected - now;

        if (diff <= 0) {
            $publishHint.html('<span style="color:var(--fos-danger)">' + t('publish_hint_scheduled_past', 'Past date - choose a future date.') + '</span>');
        } else {
            var days = Math.floor(diff / (1000 * 60 * 60 * 24));
            var hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            var mins = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

            var timeStr = [];
            if (days > 0) timeStr.push(days + ' ' + (days === 1 ? t('day', 'day') : t('days', 'days')));
            if (hours > 0) timeStr.push(hours + 'h');
            if (mins > 0 && days === 0) timeStr.push(mins + ' min');

            var finalStr = t('publish_hint_scheduled_in', 'Will be published in') + ' ' + timeStr.join(' / ');
            $publishHint.text(finalStr);
        }
    }

    $publishDateInput.on('input change', updateDateHint);

    // Initial state setup
    if ($publishInput.length) {
        var initialMode = $publishInput.val();
        $('.fos-np-publish-pill[data-mode="' + initialMode + '"]').trigger('click');
    }

    // ── Execution Mode Selector ────────────────────────────────────────────────

    var $execPills = $('.fos-np-exec-pill');
    var $execInput = $('#fos-exec-mode');
    var $execHint = $('#fos-exec-hint');
    var $startBtn = $('#fos-start-btn');

    $execPills.on('click', function () {
        var $btn = $(this);
        var mode = $btn.data('mode');

        $execPills.removeClass('is-active');
        $btn.addClass('is-active');
        $execInput.val(mode);

        if (mode === 'manual') {
            $execHint.text(t('exec_manual_warning', 'In manual mode, the pipeline pauses after each agent and waits for your approval to continue.'))
                .addClass('fos-np-publish-hint--warning');
            $startBtn.removeClass('cts-btn--primary').addClass('cts-btn--warning').html('✋ ' + t('start_review_mode', 'Start with review'));
        } else {
            $execHint.text(t('exec_hint_auto', 'Pipeline runs straight from Agent 1 to 7.'))
                .removeClass('fos-np-publish-hint--warning');
            $startBtn.removeClass('cts-btn--warning').addClass('cts-btn--primary').html('🚀 ' + t('start_production', 'Start production'));
        }
    });

    // ── Article Type Context Panels ──────────────────────────────────────────

    var $typeRadios = $('input[name="article_type"]');
    var $panels = $('.fos-type-panel');

    function updateContextPanel() {
        var selectedType = $('input[name="article_type"]:checked').val() || 'satellite';
        $panels.removeClass('fos-type-panel--active');
        $('.fos-type-panel[data-panel-type="' + selectedType + '"]').addClass('fos-type-panel--active');
        fosApplyArticleTypeState();
    }

    updateContextPanel(); // Init on load

    // Dynamic Lists (Comparativo & Notícia)
    function attachDynamicList($btn, $list, inputClass, maxItems, placeholder) {
        $btn.on('click', function () {
            var currentCount = $list.find('.fos-type-dynamic-item').length;
            if (currentCount >= maxItems) return;

            var newItemHtml = '';
            if (inputClass === 'fos-comp-input') {
                newItemHtml = '<div class="fos-type-dynamic-item">' +
                    '<div class="fos-type-dynamic-item__num">' + (currentCount + 1) + '</div>' +
                    '<input type="text" class="cts-input fos-comp-input fos-comp-input-label" placeholder="' + t('placeholder_comp_label', 'Product or service name') + '" style="flex:1; border:none; padding:6px 4px; height:auto; box-shadow:none; outline:none; background:transparent;" autocomplete="off">' +
                    '<div style="width:1px; background:var(--fos-border); margin:4px 0;"></div>' +
                    '<input type="url" class="cts-input fos-comp-input-url" placeholder="' + t('placeholder_comp_url', 'https://... (optional)') + '" style="flex:1; border:none; padding:6px 4px; height:auto; box-shadow:none; outline:none; background:transparent; font-family:var(--fos-font-mono); font-size:12px; color:var(--fos-text-sub);" autocomplete="off">' +
                    '<button type="button" class="fos-type-remove-btn" title="' + t('remove', 'Remove') + '">&times;</button>' +
                    '</div>';
            } else {
                newItemHtml = '<div class="fos-type-dynamic-item">' +
                    '<div class="fos-type-dynamic-item__dot"></div>' +
                    '<input type="url" class="cts-input ' + inputClass + '" placeholder="' + placeholder + '" style="flex:1; border:none; padding:0; height:auto; box-shadow:none; outline:none;" autocomplete="off">' +
                    '<button type="button" class="fos-type-remove-btn" title="' + t('remove', 'Remove') + '">&times;</button>' +
                    '</div>';
            }
            $list.append(newItemHtml);

            if ($list.find('.fos-type-dynamic-item').length >= maxItems) {
                $btn.prop('disabled', true).css('opacity', '0.5');
            }
        });
    }

    $(document).on('click', '.fos-type-remove-btn', function () {
        var $item = $(this).closest('.fos-type-dynamic-item');
        var $list = $item.closest('.fos-type-dynamic-list');
        var isComp = $list.attr('id') === 'fos-comp-list';
        var maxItems = isComp ? 6 : 5;
        var btnId = isComp ? '#fos-add-comp-btn' : '#fos-add-news-btn';

        $item.remove();

        // Re-number if it's Comparativo
        if (isComp) {
            $list.find('.fos-type-dynamic-item').each(function (index) {
                $(this).find('.fos-type-dynamic-item__num').text(index + 1);
            });
        }

        // Re-enable add button
        if ($list.find('.fos-type-dynamic-item').length < maxItems) {
            $(btnId).prop('disabled', false).css('opacity', '1');
        }
        
        fosSyncSummaryRail();
    });

    attachDynamicList($('#fos-add-comp-btn'), $('#fos-comp-list'), 'fos-comp-input', 8, '');
    attachDynamicList($('#fos-add-news-btn'), $('#fos-news-list'), 'fos-news-input', 5, 'https://...');

    // Fetch Article (Pilar & Atualização)
    function setupPostSearch(btnId, displayId, resultsId, hiddenIds, isUpdate, clearBtnId) {
        $(btnId).on('click', function () {
            var query = $(displayId).val().trim();
            if (!query) return;

            var $btn = $(this);
            $btn.addClass('fos-np-btn-search-wp--loading');
            $(resultsId).hide().empty();

            $.post(ajax, {
                action: 'costudio_fetch_wp_post',
                nonce: nonce,
                site_key: $('#fos-site-key-select').val() || 'local',
                query: query
            }).done(function (res) {
                $btn.removeClass('fos-np-btn-search-wp--loading');
                if (res.success && res.data.posts && res.data.posts.length > 0) {
                    var html = '<div class="fos-links-result-list" style="margin-bottom:0;">';
                    res.data.posts.forEach(function (p) {
                        var title = p.title || '';
                        html += '<div class="fos-links-result-item fos-post-search-item" data-id="' + (parseInt(p.id, 10) || 0) + '" data-url="' + esc(p.url || '') + '" data-title="' + esc(title) + '" data-date="' + esc(p.date || '') + '" data-modified="' + esc(p.modified || '') + '" data-words="' + (parseInt(p.word_count, 10) || 0) + '">' +
                            '<div class="fos-links-result-item__title">' + esc(title) + '</div>' +
                            '</div>';
                    });
                    html += '</div>';
                    $(resultsId).html(html).slideDown(200);
                    $(clearBtnId).show();
                } else {
                    $(resultsId).html('<div class="fos-notice fos-notice--info">' + t('no_results_found', 'No results found.') + '</div>').slideDown(200);
                    $(clearBtnId).show();
                }
            }).fail(function () {
                $btn.removeClass('fos-np-btn-search-wp--loading');
                alert(t('error_searching_post', 'Error searching post.'));
            });
        });

        // Trigger search on Enter key — restored preventDefault to stop form submission
        $(displayId).on('keydown', function (e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                e.stopPropagation();
                $(btnId).click();
                return false;
            }
        });

        // Click on result item — using a more robust delegation pattern
        $(resultsId).on('click', '.fos-post-search-item', function (e) {
            e.preventDefault();
            e.stopPropagation();
            
            var $item = $(this);
            $(hiddenIds.url).val($item.data('url'));
            $(hiddenIds.title).val($item.data('title'));

            if (isUpdate) {
                $(hiddenIds.id).val($item.data('id'));

                // Fetch full content
                var $btn = $(btnId);
                $btn.addClass('fos-np-btn-search-wp--loading');

                $.post(ajax, {
                    action: 'costudio_fetch_post_content',
                    nonce: nonce,
                    site_key: $('#fos-site-key-select').val() || 'local',
                    post_id: $item.data('id')
                }).done(function (res) {
                    $btn.removeClass('fos-np-btn-search-wp--loading');
                    if (res.success) {
                        if (hiddenIds.id) $(hiddenIds.id).val(res.data.id || $item.data('id') || '');
                        if (hiddenIds.url) $(hiddenIds.url).val(res.data.url || $item.data('url') || '');
                        if (hiddenIds.title) $(hiddenIds.title).val(res.data.title || $item.data('title') || '');
                        $(hiddenIds.content).val(res.data.content);
                        $(displayId).val(''); // clear search
                        $(resultsId).slideUp(200).empty();
                        $(btnId).hide(); // Hide search button after selection in Atualização

                        // Render selection
                        var d = new Date($item.data('modified'));
                        var now = new Date();
                        var diffMonths = (now.getFullYear() - d.getFullYear()) * 12 + now.getMonth() - d.getMonth();
                        var modText = diffMonths > 0 ? t('edited_months', 'edited') + ' ' + diffMonths + ' ' + t('months', 'months') : t('edited_recently', 'edited recently');

                        var dDate = new Date($item.data('date'));
                        var dateStr = ("0" + dDate.getDate()).slice(-2) + '/' + ("0" + (dDate.getMonth() + 1)).slice(-2) + '/' + dDate.getFullYear();

                        var selHtml = '<div class="fos-type-article-result">' +
                            '<div class="fos-type-article-result__check"><svg width="10" height="8" viewBox="0 0 10 8" fill="none"><path d="M1 4L4 7L9 1" stroke="white" stroke-width="1.5" stroke-linecap="round"/></svg></div>' +
                            '<div style="min-width:0; flex:1;">' +
                            '<div style="font-size:13px; font-weight:500; color:var(--cts-text);">' + esc(res.data.title || '') + '</div>' +
                            '<div style="font-size:11px; color:var(--fos-text-dim); margin-top:2px;">' + esc(t('published_on', 'Published on')) + ' ' + esc(dateStr) + ' · ' + (parseInt(res.data.word_count, 10) || 0) + ' ' + esc(t('words', 'words')) + ' · ' + esc(modText) + '</div>' +
                            '</div></div>';
                        $('#fos-update-selected-result').html(selHtml).slideDown(200);
                        fosSyncSummaryRail();
                    } else {
                        if (hiddenIds.id) $(hiddenIds.id).val('');
                        if (hiddenIds.content) $(hiddenIds.content).val('');
                        fosSyncSummaryRail();
                        var serverMsg = (res && res.data) ? (typeof res.data === 'string' ? res.data : (res.data.message || '')) : '';
                        alert(t('error_extracting_post_content', 'Error extracting post content.') + (serverMsg ? '\n\n' + serverMsg : ''));
                    }
                }).fail(function () {
                    $btn.removeClass('fos-np-btn-search-wp--loading');
                    if (hiddenIds.id) $(hiddenIds.id).val('');
                    if (hiddenIds.content) $(hiddenIds.content).val('');
                    fosSyncSummaryRail();
                    alert(t('error_connection_extracting_post_content', 'Connection error while extracting post content.'));
                });
            } else {
                $(displayId).val($item.data('title'));
                $(resultsId).slideUp(200);
                fosSyncSummaryRail();
            }
        });

        // Clear selection
        $(clearBtnId).on('click', function () {
            $(displayId).val('');
            $(resultsId).slideUp(200).empty();
            $(this).hide();
            $(btnId).show(); // Ensure search button is visible again

            // Clear hidden fields
            if (hiddenIds.url) $(hiddenIds.url).val('');
            if (hiddenIds.title) $(hiddenIds.title).val('');

            if (isUpdate) {
                if (hiddenIds.id) $(hiddenIds.id).val('');
                if (hiddenIds.content) $(hiddenIds.content).val('');
                $('#fos-update-selected-result').slideUp(200).empty();
            }

            fosSyncSummaryRail();
        });
    }

    setupPostSearch('#fos-btn-buscar-pilar', '#fos-pilar-url-display', '#fos-pilar-search-results', { url: '#fos-pilar-url', title: '#fos-pilar-title' }, false, '#fos-btn-limpar-pilar');
    setupPostSearch('#fos-btn-buscar-update', '#fos-update-url-display', '#fos-update-search-results', { id: '#fos-update-id', url: '#fos-update-url', title: '#fos-update-title', content: '#fos-update-content' }, true, '#fos-btn-limpar-update');

    // ── Form submit ───────────────────────────────────────────────────────────

    $(document).on('submit', '#fos-production-form', function (e) {
        e.preventDefault();

        // Serialize links state into the hidden field BEFORE form capture.
        var linksJson = JSON.stringify({
            internal: internalLinks,
            external: externalLinks,
        });
        $('#fos-links-internos-json').val(linksJson);

        var selectedType = $('input[name="article_type"]:checked').val() || 'satellite';
        var formData = $(this).serializeArray();

        // Type-specific Validations and Data Gathering
        if (selectedType === 'comparison') {
            var compItems = [];
            $('#fos-comp-list .fos-comp-input').each(function () {
                var val = $(this).val().trim();
                if (val) {
                    var parts = val.split(' — ');
                    var label = parts[0].trim();
                    var url = parts.length > 1 && parts[1].indexOf('http') === 0 ? parts[1].trim() : '';
                    compItems.push({ label: label, url: url });
                }
            });
            if (compItems.length < 2) {
                alert(t('error_comparative_min_items', 'Comparative type requires at least 2 items.'));
                return;
            }
            compItems.forEach(function (item, idx) {
                formData.push({ name: 'comparison_items[' + idx + '][label]', value: item.label });
                formData.push({ name: 'comparison_items[' + idx + '][url]', value: item.url });
            });
        } else if (selectedType === 'news') {
            var newsSources = [];
            $('#fos-news-list .fos-news-input').each(function () {
                var val = $(this).val().trim();
                if (val) {
                    newsSources.push({ url: val });
                }
            });
            if (newsSources.length < 1) {
                alert(t('error_news_min_sources', 'News type requires at least 1 source URL.'));
                return;
            }
            newsSources.forEach(function (item, idx) {
                formData.push({ name: 'news_sources[' + idx + '][url]', value: item.url });
            });
        } else if (selectedType === 'update') {
            var updateId = $('#fos-update-id').val();
            if (!updateId) {
                alert(t('error_update_requires_existing', 'Update type requires selecting an existing article.'));
                return;
            }
            if (!$('#fos-update-inst').val().trim()) {
                alert(t('error_update_requires_instructions', 'Update type requires instructions describing what to change.'));
                return;
            }
        }

        if ($publishInput.length && $publishInput.val() === 'scheduled') {
            var pDate = $publishDateInput.val();
            if (!pDate || new Date(pDate).getTime() <= new Date().getTime()) {
                alert(t('error_invalid_schedule_date', 'Please choose a valid future date for scheduling.'));
                return;
            }
        }

        var $btn = $('#fos-start-btn');
        var orig = $btn.html();
        $btn.html('<span class="spinner is-active" style="float:none;margin:0 6px -3px 0"></span> ' + t('starting', 'Starting…'))
            .prop('disabled', true);

        // Serialize links state into the hidden field before form capture.
        var linksJson = JSON.stringify({
            internal: internalLinks,
            external: externalLinks,
        });
        $('#fos-links-internos-json').val(linksJson);

        formData.push({ name: 'action', value: 'costudio_start_production' });
        formData.push({ name: 'nonce', value: nonce });

        // Sprint B.4.2 — Pre-submit gate (Caso A): when the user's monthly
        // quota is exhausted but they still have extras balance, ask them
        // to confirm before submitting. The server's CAP_Quota::increment
        // would silently debit an extra otherwise — fine technically, but
        // bad UX for an action that costs real money.
        //
        // Resolves to true (proceed) in three paths:
        //   (1) Monthly quota still has room → no confirmation needed
        //   (2) No extras / addons disabled → no confirmation possible anyway
        //   (3) User confirmed the extras consumption
        // Resolves false only when the user explicitly cancels the modal.
        var ctx              = data.addon_context || {};
        var monthlyRemaining = parseInt(ctx.monthly_remaining || 0, 10);
        var addonBalance     = parseInt(ctx.addon_balance     || 0, 10);
        var addonEnabled     = !!ctx.addon_enabled;
        var needsConfirm     = (addonEnabled && monthlyRemaining <= 0 && addonBalance > 0);

        var preSubmit;
        if (needsConfirm && typeof window.costudioConfirmExtra === 'function') {
            preSubmit = window.costudioConfirmExtra(addonBalance).then(function (confirmed) {
                if (confirmed) {
                    // Tag the request so the server can record this as an
                    // explicit-consent extras debit (useful for telemetry
                    // and audit trail in Sprint C.5).
                    formData.push({ name: 'consume_extra', value: '1' });
                }
                return confirmed;
            });
        } else {
            preSubmit = Promise.resolve(true);
        }

        preSubmit.then(function (proceed) {
            if (!proceed) {
                // User cancelled — restore button, no submission.
                $btn.html(orig).prop('disabled', false);
                return;
            }
            submitProductionRequest();
        });

        function submitProductionRequest() {
            $.post(ajax, formData)
                .done(function (res) {
                    $btn.html(orig).prop('disabled', false);

                    if (!res.success) {
                        var errData = (res.data && typeof res.data === 'object') ? res.data : null;
                        var errMsg  = errData && errData.message
                            ? errData.message
                            : (res.data || t('error_starting_production', 'Error starting production.'));

                        // Sprint B.4.3 — Caso B: when server says quota is
                        // exhausted AND user can buy (PRO/Studio with addons
                        // enabled), open the buy modal directly in
                        // production_blocked context instead of showing a
                        // dead-end error. Preserves user momentum: they came
                        // here to produce, we offer the unblock path inline.
                        if (errData && errData.code === 'quota_exhausted' && errData.can_buy
                            && typeof window.costudioAddonModal === 'function') {
                            // Sprint B.4.4 — Save form state so we can restore +
                            // auto-submit after the user returns from Stripe.
                            // Saved before opening the modal (not later) so we
                            // capture the exact inputs the user just submitted,
                            // not whatever they tinker with after seeing the modal.
                            saveProductionStateForRetry();

                            window.costudioAddonModal({
                                context:  'production_blocked',
                                headline: errMsg + ' ' + t(
                                    'addon_buy_to_continue',
                                    'Buy a pack below to keep producing.'
                                )
                            });
                            return;
                        }

                        showFosError(errMsg);
                        return;
                    }

                    // Redirect immediately to the standalone live Detail page.
                    window.location.href = 'admin.php?page=costudio-detalhe&id=' + res.data.production_id;
                })
                .fail(function () {
                    $btn.html(orig).prop('disabled', false);
                    showFosError(t('request_failed_connection', 'Request failed. Check your connection.'));
                });
        }
    });

    // ── UI helpers ────────────────────────────────────────────────────────────

    function showFosError(msg) {
        // ── Generic error: show inline error notice + retry button ────────────
        // Update and show error notice.
        $('#fos-error-message').text(msg);
        $('#fos-error-notice').slideDown(250);

        // Swap submit → retry in footer.
        $('#fos-start-btn').hide();
        $('#fos-retry-btn').show();

        // Ensure retry button exists in the footer (inject if not present).
        if (!$('#fos-retry-btn').length) {
            var $retryBtn = $('<button type="button" id="fos-retry-btn" class="cts-btn cts-btn--danger cts-btn--lg"></button>')
                .text('\uD83D\uDD04 ' + (window.CostudioData && window.CostudioData.i18n && window.CostudioData.i18n.try_again ? window.CostudioData.i18n.try_again : 'Try again'));
            $('#fos-start-btn').after($retryBtn);
        }

        // Scroll into view.
        setTimeout(function () {
            var $notice = $('#fos-error-notice');
            if ($notice.length) {
                $notice[0].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }
        }, 300);

        // Hide legacy external panel if still visible.
        // (no-op — panel removed, kept for safety during transition)
    }

    // ── Retry button: reset all state back to default ────────────────────────
    $(document).on('click', '#fos-retry-btn', function () {
        $('#fos-error-notice').slideUp(200);
        $('#fos-retry-btn').hide();
        $('#fos-start-btn').show();
    });

    // ── Sprint B.4.4 — Auto-retry after Stripe purchase ─────────────────────
    //
    // When the user hits the quota wall and goes through the buy flow, we
    // save the form state to sessionStorage right before opening the buy
    // modal (see saveProductionStateForRetry below). After Stripe returns,
    // the addon-checkout JS shows a toast and reloads the page. On that
    // post-reload load, we restore the form values and auto-submit so the
    // user goes straight to the production they originally intended.
    //
    // Coordination with addon-checkout.js:
    //   - First load (return from Stripe): URL has ?addon_purchase=success
    //     → addon-checkout handles toast + resync + reload, we wait
    //   - Second load (post-reload): URL clean of addon_purchase → we act
    //
    // 10-min TTL on the saved state — beyond that the user clearly got
    // distracted, replaying their old form would be surprising.

    var STORAGE_KEY     = 'costudio_pending_production';
    var RETRY_TTL_MS    = 10 * 60 * 1000;
    var RETRY_DELAY_MS  = 1200; // brief pause so the user sees the banner
                                 // before the form auto-submits

    function saveProductionStateForRetry() {
        var $form = $('#fos-production-form');
        if (!$form.length || typeof sessionStorage === 'undefined') return;

        try {
            sessionStorage.setItem(STORAGE_KEY, JSON.stringify({
                savedAt:  Date.now(),
                formData: $form.serializeArray()
            }));
        } catch (e) {
            // sessionStorage might be full or disabled — silent fail, the
            // user will just have to re-fill the form after purchase.
        }
    }

    function attemptProductionRetryIfPending() {
        if (typeof sessionStorage === 'undefined') return;

        var raw;
        try { raw = sessionStorage.getItem(STORAGE_KEY); } catch (e) { return; }
        if (!raw) return;

        var saved;
        try { saved = JSON.parse(raw); } catch (e) {
            try { sessionStorage.removeItem(STORAGE_KEY); } catch (ee) {}
            return;
        }
        if (!saved || !saved.savedAt || !Array.isArray(saved.formData)) return;

        // Stale state → clear without acting.
        if (Date.now() - saved.savedAt > RETRY_TTL_MS) {
            try { sessionStorage.removeItem(STORAGE_KEY); } catch (e) {}
            return;
        }

        // First load after Stripe: addon-checkout.js is about to reload the
        // page (it shows toast + resync + reload). Don't act yet — we'll
        // re-run on the clean post-reload load.
        var params = new URLSearchParams(window.location.search);
        if (params.has('addon_purchase')) return;

        // Form must be on this page to restore into.
        var $form = $('#fos-production-form');
        if (!$form.length) return;

        // Consume the saved state — clear before restoring so any error
        // doesn't leave us in a retry-loop.
        try { sessionStorage.removeItem(STORAGE_KEY); } catch (e) {}

        restoreFormFields(saved.formData);
        showRetryBanner();

        window.setTimeout(function () {
            $('#fos-start-btn').trigger('click');
        }, RETRY_DELAY_MS);
    }

    function restoreFormFields(fields) {
        fields.forEach(function (field) {
            // Skip fields that should NEVER come from old state. action+nonce
            // are re-generated on submit, consume_extra is a per-submit flag.
            if (field.name === 'action' || field.name === 'nonce' || field.name === 'consume_extra') {
                return;
            }

            var $el = $('#fos-production-form [name="' + field.name + '"]');
            if (!$el.length) return;

            if ($el.is('input[type="radio"]') || $el.is('input[type="checkbox"]')) {
                // For checkable inputs, find the one matching the saved value.
                $el.filter('[value="' + field.value + '"]').prop('checked', true).trigger('change');
            } else {
                $el.val(field.value).trigger('change');
            }
        });
    }

    function showRetryBanner() {
        var msg = (window.CostudioData && window.CostudioData.i18n && window.CostudioData.i18n.production_retry_banner)
            ? window.CostudioData.i18n.production_retry_banner
            : 'Continuing your production…';
        var $banner = $('<div class="notice notice-info fos-addon-toast"><p></p></div>');
        $banner.find('p').text(msg);
        $('.wrap').first().prepend($banner);
        // Auto-fade after the submit fires (4s gives the redirect time to start).
        window.setTimeout(function () {
            $banner.fadeOut(400, function () { $(this).remove(); });
        }, 4000);
    }

    $(function () { attemptProductionRetryIfPending(); });

    // ────────────────────────────────────────────────────────────────────────

}(jQuery));

