(function($) {
    'use strict';

    const cfg = window.aysaAgent8V3Lab || {};
    const state = {
        canonical: null,
        messages: [],
        qaEvents: [],
        qaRunId: '',
        stressRunning: false,
        stressStopRequested: false,
        lastDebug: {},
        qaResults: [],
        activeTest: null,
        workerTasks: [],
        workerTimers: {},
        ragContexts: [],
        guidance: null,
        guidanceIdentity: '',
        guidanceCollapsed: false,
        offpageLinkExchangePreflight: null,
        externalAction: null,
        billing: null,
        walletSnapshot: null,
        legacyCommit: null,
        languageFallbacks: [],
        businessProfileTimer: null,
        businessProfileRefreshing: false,
        seoProfileTimer: null,
        seoProfileRefreshing: false,
        competitionKeywordTimer: null,
        competitionKeywordRefreshing: false,
        keywordResearchTimer: null,
        keywordResearchRefreshing: false,
        keywordResearchAutoStarted: false,
        technicalSeoTimer: null,
        technicalSeoRefreshing: false,
        onPageSeoTimer: null,
        onPageSeoRefreshing: false,
        onPageAnalysisApproval: null,
        technicalFixExecutionTimer: null,
        technicalFixExecutionRefreshing: false,
        technicalFixExecutionModule: '',
        imageAltTestMode: {
            items: [],
            history: [],
            historyLoaded: false,
            historyLoading: false,
            result: null,
            testMode: null,
            billingIdentity: null,
            billingIdentityHealth: null,
            walletSnapshot: null,
            productGates: null,
            topup: null,
            running: false,
            message: ''
        },
        onPageContentRewriteHistory: {
            rows: [],
            loaded: false,
            loading: false,
            message: ''
        },
        onPageHistorySourceRunId: '',
        offpageBacklinkAuditTimer: null,
        offpageBacklinkAuditRefreshing: false,
        offpageBacklinkStrategyTimer: null,
        offpageBacklinkStrategyRefreshing: false,
        offpageBacklinkStrategyAutoRefreshed: false,
        monitoringRefreshTimer: null,
        monitoringRefreshTicks: 0,
        monitoringRefreshInFlight: false,
        monitoringRefreshPreflight: null,
        completedRunMessages: {},
        pendingChat: null,
        typewriterTimers: {},
        betaIssueBreadcrumbs: [],
        lastBetaIssueContext: {},
        modal: {
            key: '',
            page: 1,
            perPage: 25,
            filters: {},
            lastTrigger: null,
            workspace: false,
            viewCache: {},
            monitoringFilterState: {},
            monitoringTransitioning: false,
            monitoringResetScrollAfterLoad: false,
            onpageMetadataSelectedItems: {},
            onpageMetadataConfirmedSelectionHash: '',
            onpageMetadataConfirmedItems: []
        }
    };

    function setStatus(status) {
        if (
            status === 'completed'
            && state.canonical
            && isActivationLikePhase(state.canonical.phase)
            && !activationVerified(state.canonical)
        ) {
            status = 'awaiting_activation';
        }
        $('[data-agent8v3-status]').text(text(status)).attr('data-agent8v3-status', status);
    }

    function escapeHtml(value) {
        return String(value || '').replace(/[&<>"']/g, function(ch) {
            return {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            }[ch];
        });
    }

    function redactBetaIssueString(value) {
        return String(value || '')
            .replace(/aysa_pk_[a-z0-9]{20,}/ig, '[redacted_activation_key]')
            .replace(/\b(?:ya29\.[A-Za-z0-9_.-]+|1\/\/[A-Za-z0-9_.-]+)\b/g, '[redacted_google_token]')
            .replace(/\b[A-Za-z0-9._%+-]{2,}@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, '[masked_email]')
            .replace(/\b(?:cs_(?:test|live)|sk_(?:test|live))_[A-Za-z0-9_-]{20,}\b/g, '[redacted_stripe_key]');
    }

    function redactBetaIssueValue(value, depth) {
        depth = depth || 0;
        if (depth > 4) {
            return '[truncated]';
        }
        if (Array.isArray(value)) {
            return value.slice(0, 50).map(function(item) {
                return redactBetaIssueValue(item, depth + 1);
            });
        }
        if (value && typeof value === 'object') {
            const out = {};
            Object.keys(value).slice(0, 80).forEach(function(key) {
                if (/(cookie|password|secret|token|authorization|raw_prompt|full_page_content|html_body|page_content)/i.test(key)) {
                    out[key] = '[redacted]';
                    return;
                }
                out[key] = redactBetaIssueValue(value[key], depth + 1);
            });
            return out;
        }
        if (typeof value === 'string') {
            return redactBetaIssueString(value).slice(0, 600);
        }
        if (typeof value === 'number' || typeof value === 'boolean' || value === null) {
            return value;
        }
        return String(value || '').slice(0, 200);
    }

    function recordBetaIssueBreadcrumb(type, data) {
        const breadcrumb = redactBetaIssueValue({
            at: new Date().toISOString(),
            type: type,
            data: data || {},
            phase: state.canonical && state.canonical.phase ? state.canonical.phase : '',
            status: $('[data-agent8v3-status]').attr('data-agent8v3-status') || 'idle',
            modal_key: state.modal && state.modal.key ? state.modal.key : ''
        });
        state.betaIssueBreadcrumbs.push(breadcrumb);
        if (state.betaIssueBreadcrumbs.length > 50) {
            state.betaIssueBreadcrumbs = state.betaIssueBreadcrumbs.slice(-50);
        }
    }

    function betaIssueAjaxSummary(action, data) {
        data = data || {};
        return {
            action: String(action || ''),
            agent_action: String(data.agent_action || ''),
            modal_key: String(data.modal_key || ''),
            has_payload: !!data.payload,
            page: String(data.page || ''),
            filters: redactBetaIssueValue(data.filters || {})
        };
    }

    function customerText(value) {
        const isRo = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const replacements = {
            'DataForSEO': 'AYSA',
            'Screaming Frog': isRo ? 'crawler tehnic' : 'technical crawler',
            'API worker': isRo ? 'analiza automată' : 'automatic analysis',
            'Worker status': isRo ? 'Status analiză' : 'Analysis status',
            'Worker': isRo ? 'Analiză automată' : 'Automatic analysis',
            'worker': isRo ? 'analiză automată' : 'automatic analysis',
            'snapshoturile': isRo ? 'datele' : 'saved data',
            'snapshoturi': isRo ? 'date' : 'saved data',
            'snapshots': 'saved data',
            'snapshot': isRo ? 'date salvate' : 'saved data',
            'dry-run': isRo ? 'verificare fără modificări' : 'no-change check',
            'Dry-run': isRo ? 'Verificare fără modificări' : 'No-change check',
            'route evidence': isRo ? 'dovadă că poate fi aplicat și verificat' : 'proof it can be applied and verified',
            'Route evidence': isRo ? 'Dovadă că poate fi aplicat și verificat' : 'Proof it can be applied and verified',
            'ledger': isRo ? 'înregistrare de credit' : 'credit record',
            'Ledger': isRo ? 'Înregistrare de credit' : 'Credit record',
            'blocked': isRo ? 'blocat pentru siguranță' : 'blocked for safety',
            'Blocked': isRo ? 'Blocat pentru siguranță' : 'Blocked for safety',
            'stage': isRo ? 'etapă' : 'step',
            'Stage': isRo ? 'Etapă' : 'Step',
            'bridge': isRo ? 'verificare de conectare' : 'connection check',
            'Bridge': isRo ? 'Verificare de conectare' : 'Connection check',
            'model R3': isRo ? 'verificare de siguranță' : 'safety check',
            'Model R3': isRo ? 'Verificare de siguranță' : 'Safety check',
            'compact': isRo ? 'rezumat' : 'summary',
            'Compact': isRo ? 'Rezumat' : 'Summary',
            'projection': 'result',
            'Projection': 'Result',
            'payload': isRo ? 'rezultat' : 'result',
            'Run ID': isRo ? 'Referință analiză' : 'Analysis reference',
            'Billable API': isRo ? 'Consumă credite' : 'Uses credits',
            'billable': isRo ? 'consumă credite' : 'uses credits',
            'Local sync': isRo ? 'Salvare locală' : 'Local save',
            'legacy sync': isRo ? 'salvare locală' : 'local save',
            'sync legacy': isRo ? 'salvare locală' : 'local save'
        };
        let textValue = String(value || '');
        Object.keys(replacements).forEach(function(key) {
            textValue = textValue.split(key).join(replacements[key]);
        });
        const providerLabel = isRo ? 'metrici SEO actualizate' : 'updated SEO metrics';
        textValue = textValue.replace(/dataforseo_labs\.[A-Za-z0-9_.-]+/gi, providerLabel);
        textValue = textValue.replace(/dataforseo[_-][A-Za-z0-9_.-]+/gi, providerLabel);
        textValue = textValue.replace(/\bdataforseo\b/gi, 'AYSA');
        textValue = textValue.replace(/\bscreamingfrog\b/gi, isRo ? 'crawler tehnic' : 'technical crawler');
        textValue = textValue.replace(/screaming[ _-]frog/gi, isRo ? 'crawler tehnic' : 'technical crawler');
        return textValue;
    }

    function clientFacingMessageBody(value) {
        const isRo = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const raw = String(value || '').trim();
        const exact = {
            'registered action completed.': isRo ? 'Acțiunea a fost finalizată.' : 'Action completed.',
            planning: isRo ? 'Planificare' : 'Planning',
            executing: isRo ? 'Execuție' : 'Executing',
            collecting: isRo ? 'Colectez datele necesare.' : 'Collecting the required data.',
            shadow_started: isRo ? 'Pasul a început în mod controlat.' : 'The step started in controlled mode.'
        };
        const normalized = raw.toLowerCase();
        let output = Object.prototype.hasOwnProperty.call(exact, normalized) ? exact[normalized] : raw;
        output = output
            .replace(/modul shadow/gi, isRo ? 'mod controlat' : 'controlled mode')
            .replace(/state-ul Agent8 V3/gi, isRo ? 'progresul Agent8' : 'Agent8 progress')
            .replace(/Agent8 V3 state/gi, isRo ? 'progresul Agent8' : 'Agent8 progress');
        return output;
    }

    function linkifySafeText(value, sanitizeCopy) {
        const safeValue = sanitizeCopy ? customerText(value) : value;
        return escapeHtml(safeValue).replace(/https:\/\/(?:checkout\.stripe\.com|app\.aysa\.ai)\/[A-Za-z0-9._~:/?#\[\]@!$&amp;'()*+,;=%-]*/g, function(url) {
            return '<a href="' + url + '" target="_blank" rel="noopener noreferrer">' + url + '</a>';
        });
    }

    function sanitizeModalHtml(value) {
        const container = document.createElement('div');
        container.innerHTML = String(value || '');
        const allowed = ['H2', 'H3', 'P', 'UL', 'OL', 'LI', 'STRONG', 'EM', 'A'];
        Array.prototype.slice.call(container.querySelectorAll('*')).forEach(function(node) {
            if (allowed.indexOf(node.tagName) === -1) {
                node.replaceWith(document.createTextNode(node.textContent || ''));
                return;
            }
            Array.prototype.slice.call(node.attributes || []).forEach(function(attr) {
                if (node.tagName === 'A' && attr.name === 'href' && /^https?:\/\//i.test(attr.value || '')) {
                    return;
                }
                node.removeAttribute(attr.name);
            });
        });
        return container.innerHTML;
    }

    const I18N = {
        en: {
            title: 'AYSA Agent8', subtitle: 'Deterministic execution system', active: 'Active', workspaceActive: 'Workspace active', workspaceAwaitingActivation: 'Awaiting activation', awaiting_activation: 'awaiting activation', conversation: 'Conversation',
            execution: 'Agent8 Execution', waiting: 'waiting for updates', placeholder: 'Describe the task for AYSA Agent 8...', composerLabel: 'Message for AYSA Agent 8',
            authenticated: 'Authenticated', unauthenticated: 'Unauthenticated', automatedSeo: 'Automated SEO', qaDiagnostics: 'QA Diagnostics', controls: 'Controls',
            reportProblem: 'Report a problem', progressTitle: 'Agent8 progress', progressHint: 'See where you are and what comes next.',
            sendMessage: 'Send message', addContext: 'Add context', agentLanguage: 'Agent8 language',
            issueIntro: 'We send a support description and safe technical details to the AYSA team. We do not include keys, tokens, cookies, passwords, or complete page content.', issueClose: 'Close report', issueWhat: 'What is not working?', issuePlaceholder: 'Briefly describe what you tried, what you saw, and what you expected to happen.',
            issueModule: 'Module', issueActivationSetup: 'Activation / Setup', issueBilling: 'Billing / Credits', issuePluginUi: 'Plugin interface', issueType: 'What type of problem is this?', issueCannotContinue: 'I cannot continue', issueConfusingWrong: 'It looks wrong / confusing', issueCreditConsumed: 'Credits were consumed', issueEmailMissing: 'The email did not arrive', issueOther: 'Other',
            issueSupportEmail: 'Support email, optional', issueScreenshot: 'Screenshot', issueScreenshotNo: 'Do not attach a screenshot now', issueScreenshotYes: 'I can send the screenshot separately', issueSafeContext: 'Safe context included', issueContextActions: 'The latest UI actions, up to 50, without secrets.', issueContextState: 'Agent8 phase, current module, visible status, and current admin URL.', issueContextWallet: 'Wallet and credit status as a summary only, without changes.', issueCancel: 'Cancel', issueSubmit: 'Send report',
            fullReset: 'Reset Agent8 progress', fullResetTitle: 'Reset only the current Agent8 progress without the full deletion inventory.', fullResetConfirm: 'Reset only the current Agent8 progress to pre-activation? This clears the Agent8 transcript, setup data, research run state, and locally saved runtime results. It does not run the full inventory-based test cleanup.', fullResetDone: 'Agent8 progress was reset.',
            factoryReset: 'Full test reset…', factoryResetTitle: 'Preview every allowlisted deletion before returning the test project to pre-activation.', factoryResetConfirmTitle: 'Confirm full test reset', factoryResetConfirmBody: 'Enter the exact phrase below. Only the allowlisted project Agent8/setup test state is cleared; the wallet, billing records, WordPress content, orders, and live SEO writes remain preserved.', factoryResetInput: 'Type the exact confirmation phrase', factoryResetExecute: 'Execute full test reset', factoryResetCancel: 'Cancel',
            integrationStressConfirm: 'Run the real integration stress test? This can start automated analyses and consume credits.',
            runAll: 'Run All Tests', runState: 'Run State Tests', runSetup: 'Run Setup Tests', runResearch: 'Run Research Test', runSetupStress: 'Setup Stress Test', runIntegrationStress: 'Integration Stress Test', runAction: 'Run Action Tests', runLlm: 'Run LLM Tests',
            runWorker: 'Run Worker Test', runRag: 'Run RAG Test', runLanguage: 'Run Language Tests', runDeployParity: 'Verify Deploy Parity', runLegacySync: 'Verify Legacy Sync', runInvalid: 'Run Invalid Action Tests', runReset: 'Run Reset Test', runStress: 'Run 15 Min Stress Test',
            stopStress: 'Stop Stress Test', clearQa: 'Clear QA Log', exportQa: 'Export QA Log JSON', systemStatus: 'System Status',
            currentPhase: 'Current Phase', stateVersion: 'Saved State Version', language: 'Language', apiStatus: 'API Status',
            qaStorage: 'QA Storage', requestId: 'Request ID', activeTest: 'Active Test', name: 'Name', steps: 'Steps',
            result: 'Result', recentActions: 'Recent Actions', noQaActions: 'No QA actions yet', performance: 'Performance',
            avgResponse: 'Avg Response', throughput: 'Throughput', errorRate: 'Error Rate', canonicalState: 'Saved State',
            credits: 'Credits', availableCredits: 'Available', estimatedCredits: 'Estimated', stepUsed: 'Step Used', billingReference: 'Reference', lastBillableAction: 'Last credit-consuming action', billingStatus: 'Status', plan: 'Plan', legacySync: 'Local save',
            idle: 'Idle', approvalRequired: 'Approval Required', awaiting_approval: 'Awaiting approval', approve: 'Approve', reject: 'Reject',
            expand: 'Expand', collapse: 'Collapse', missingUncertain: 'Missing / uncertain', observations: 'Notes',
            writesState: 'writes_state: true', requiresApproval: 'requires_approval: true', billableFalse: 'billable: false', writes_state: 'writes_state: true', requires_approval: 'requires_approval: true', billable: 'billable', here: 'here', aici: 'here',
            start_setup_profile: 'start Setup SEO Profile', request_activation_key: 'request activation key', validate_activation_key: 'validate activation key', repair_legacy_activation_sync: 'repair legacy activation sync',
            retry_activation_key: 'retry activation key', continue_after_activation: 'continue after activation', reset_activation_shadow: 'reset activation shadow',
            start_architecture_test: 'start architecture test', save_business_type: 'save business type', save_primary_goal: 'save primary goal',
            reset_lab: 'reset lab', send_lab_email: 'send lab email', run_worker_ping: 'run worker ping', run_rag_context_test: 'run RAG context test',
            start_google_integrations: 'start Google integrations', skip_google_integrations: 'skip Google integrations', start_business_profile: 'start business profile',
            prepare_google_connection: 'connect Google', refresh_google_connection_status: 'refresh Google status', save_google_property_selection: 'save Google properties',
            continue_to_business_profile: 'continue to business profile',
            run_business_profile_autofill: 'analyze website', refresh_business_profile_autofill_status: 'check business profile analysis',
            save_business_profile_field: 'save business profile field', mark_business_profile_field_unavailable: 'mark field unavailable', confirm_business_profile: 'confirm business profile',
            start_objectives: 'start objectives', start_seo_profile: 'start SEO profile', save_seo_profile: 'save SEO profile', confirm_seo_profile: 'confirm SEO profile', edit_seo_profile: 'edit SEO profile', commit_seo_profile_to_legacy: 'sync SEO profile to legacy', repair_seo_profile_confirmation_gap: 'repair SEO profile', start_competition_keyword: 'start competition and keywords',
            run_competition_keyword_analysis: 'start analysis', refresh_competition_keyword_analysis_status: 'check progress', confirm_competition_keyword: 'confirm results', repair_competition_keyword_quality: 'recheck quality gate',
            revise_competition_keyword_selection: 'update selection',
            save_objectives: 'save objectives', confirm_objectives: 'confirm objectives', edit_objectives: 'edit objectives', commit_objectives_to_legacy: 'sync objectives to legacy', commit_competition_keyword_to_legacy: 'sync competition to legacy',
            start_tone_of_voice: 'start tone of voice', select_tone_of_voice_friendly: 'warm and friendly', select_tone_of_voice_professional: 'professional and clear',
            select_tone_of_voice_expert: 'expert and educational', select_tone_of_voice_premium: 'premium and elegant', start_research_handoff: 'prepare research handoff', commit_setup_completed_to_legacy: 'finalize legacy sync',
            start_keyword_research_run: 'start Keyword Research', refresh_keyword_research_status: 'check research progress', retry_keyword_research_run: 'Approve Keyword Research retry', start_technical_seo_run: 'Start Technical SEO audit', refresh_technical_seo_status: 'check Technical SEO', complete_technical_seo_review: 'Complete Technical SEO review', skip_technical_seo: 'skip Technical SEO', planning: 'Planning', executing: 'Executing', completed: 'completed', completed_with_warnings: 'ready, needs review',
            running: 'running', thinking: 'thinking', failed: 'failed',
            approve_content_plan: 'Approve plan',
            modalLoading: 'Loading', modalLoadingData: 'Loading review data...', modalSlowLoading: 'This tab is taking longer than expected. No action started and the site was not changed. If the detailed list is unavailable, AYSA will show a safe summary instead of applying anything.', modalUnavailable: 'Review unavailable', modalFailed: 'Modal request failed.', modalRequestFailed: 'Request failed',
            modalErrorEmptyFixPlan: 'There are no automatic fixes available for this module.', modalErrorUnknownAction: 'This action is not available in the current API version.', modalErrorInvalidJson: 'The API returned an invalid response; check the diagnostic.', modalErrorStaleState: 'State changed in the background. Refreshing and retrying.', modalNoExecutableFixes: 'No automatic fixes available.',
            modalSearch: 'Search...', modalSearchDetails: 'Search details...', modalSearchLabel: 'Search review data', modalStatusLabel: 'Review status', modalPrevious: 'Previous', modalNext: 'Next', chatProviderFallback: 'I could not generate the reply right now. You can try again or continue from the recommended step.', modalWhatDone: 'What we know / done', modalNextStepLabel: 'Next step', modalAll: 'All', modalAccepted: 'Accepted', modalRejected: 'Rejected', modalPage: 'Page', modalRows: 'rows', total: 'total', accepted: 'accepted', rejected: 'rejected', filtered: 'filtered', included: 'in this batch', remaining: 'remaining', approved: 'approved', ready: 'ready',
            modalKeywordMappingTitle: 'Keyword Mapping', modalKeywordMappingSubtitle: 'Keyword groups mapped to target pages after Keyword Research. Review targets and confidence before any next step.',
            modalCluster: 'Cluster', modalTargetUrl: 'Target URL', modalPrimaryKeyword: 'Primary keyword', modalKeywordFamily: 'Keyword family', modalSignals: 'Signals', modalIntent: 'Intent', modalStatus: 'Status', modalConfidence: 'Confidence', modalTrust: 'Trust', modalRecommendation: 'Recommendation', modalReasons: 'Reasons', modalTrusted: 'Trusted', modalRecommendedReject: 'Recommended reject', modalReviewNeeded: 'Review', modalReview: 'Review', modalAction: 'Action',
            modalSchemaMoreItems: 'markups',
            internalLinks: 'links', inboundLinks: 'in', outboundLinks: 'out', existingLinks: 'Existing links', proposedLinks: 'Proposed opportunities', noLinks: 'No links', maxOutboundPerPage: 'max outbound/page',
            internalLinkingPlanHint: 'Start here: each row is a target page/entity. Expand Links to review proposed source pages, anchors, and reject individual links.',
            internalLinkingStatsHint: 'Link statistics shows each page, configured keywords, existing inbound/outbound links, and a shortcut back to its link plan.',
            internalLinkingAnchorHint: 'Anchor text statistics summarizes anchor frequency from existing and accepted proposed links.',
            internalLinkingKeywordsMore: 'more',
            modalIntentLegend: 'Intent', modalStatusLegend: 'Status', modalConfidenceLegend: 'Confidence', modalReviewLegend: 'Review', modalAutomation: 'Automation', modalA8Automated: 'A8 Automated', modalPartialAutomation: 'Partial automation', modalManualReview: 'Manual review', modalA8AutomatedTitle: 'AYSA can submit this fix for execution after you save the plan.', modalPartialAutomationTitle: 'AYSA can assist this fix, but review is needed before execution.', modalManualReviewTitle: 'This item is review-only for now.', modalAutomationLegend: 'A8 Automated = can be submitted by AYSA after you save the plan', modalMapped: 'mapped', modalLocal: 'local', modalCommercial: 'commercial', modalInformational: 'informational', modalNavigational: 'navigational',
            reject_keyword_mapping: 'Reject', restore_keyword_mapping: 'Restore', reject_technical_fix: 'Reject', restore_technical_fix: 'Restore', execute_technical_fix_plan: 'Submit plan', refresh_technical_fix_execution_status: 'Refresh execution', generate_pagespeed_report: 'Generate report', prepare_image_alt_text: 'Generate image alt text',
            executable: 'executable', manual_needed: 'manual review needed', execution_status: 'Execution', not_executable_yet: 'cannot be applied automatically', submitted: 'submitted, pending execution', synced: 'synced, pending verification', queued: 'queued', skipped: 'skipped', applied: 'reported by site, pending verification',
            statusCompletedWithWarnings: 'Ready, needs review', statusReady: 'Ready', manualNeededHuman: 'Manual review needed', notExecutableHuman: 'Cannot be applied automatically', needsImprovementHuman: 'Needs improvement', excellentHuman: 'Excellent',
            technicalReviewWarningConfirm: 'Continue without applying Image Alt now?\n\nYou can come back and prepare image proposals separately. AYSA will not modify images in this step.',
        },
        ro: {
            title: 'AYSA Agent8', subtitle: 'Sistem de execuție determinist', active: 'Activ', workspaceActive: 'Spațiu de lucru activ', workspaceAwaitingActivation: 'Așteaptă activarea', awaiting_activation: 'așteaptă activarea', conversation: 'Conversație',
            execution: 'Execuție Agent8', waiting: 'așteaptă actualizări', placeholder: 'Descrie sarcina pentru AYSA Agent 8...', composerLabel: 'Mesaj pentru AYSA Agent 8',
            authenticated: 'Autentificat', unauthenticated: 'Neautentificat', automatedSeo: 'SEO automatizat', qaDiagnostics: 'Diagnostic QA', controls: 'Controale',
            reportProblem: 'Raportează o problemă', progressTitle: 'Progres Agent8', progressHint: 'Îți arătăm unde ești și ce urmează.',
            sendMessage: 'Trimite mesajul', addContext: 'Adaugă context', agentLanguage: 'Limba Agent8',
            issueIntro: 'Trimitem o descriere pentru suport și detalii tehnice sigure către echipa AYSA. Nu includem chei, tokenuri, cookies, parole sau conținut complet de pagină.', issueClose: 'Închide raportarea', issueWhat: 'Ce nu funcționează?', issuePlaceholder: 'Descrie pe scurt ce ai încercat, ce ai văzut și ce te așteptai să se întâmple.',
            issueModule: 'Modul', issueActivationSetup: 'Activare / Configurare', issueBilling: 'Facturare / Credite', issuePluginUi: 'Interfață plugin', issueType: 'Ce fel de problemă pare?', issueCannotContinue: 'Nu pot continua', issueConfusingWrong: 'Pare greșit / confuz', issueCreditConsumed: 'S-a consumat credit', issueEmailMissing: 'Emailul nu a venit', issueOther: 'Altceva',
            issueSupportEmail: 'Email suport, opțional', issueScreenshot: 'Captură de ecran', issueScreenshotNo: 'Nu atașa o captură acum', issueScreenshotYes: 'Pot trimite captura separat', issueSafeContext: 'Ce context sigur atașăm', issueContextActions: 'Ultimele acțiuni UI, maximum 50, fără secrete.', issueContextState: 'Faza Agent8, modulul curent, statusul vizibil și URL-ul admin curent.', issueContextWallet: 'Wallet și status credite doar ca rezumat, fără modificări.', issueCancel: 'Renunță', issueSubmit: 'Trimite raportul',
            fullReset: 'Reset progres Agent8', fullResetTitle: 'Resetează doar progresul curent Agent8, fără inventarul complet de ștergere.', fullResetConfirm: 'Resetezi doar progresul curent Agent8 la preactivare? Se curăță transcriptul Agent8, datele de setup, starea rulărilor research și rezultatele runtime salvate local. Nu se execută curățarea completă inventariată a proiectului de test.', fullResetDone: 'Progresul Agent8 a fost resetat.',
            factoryReset: 'Reset complet test…', factoryResetTitle: 'Previzualizează fiecare ștergere allowlisted înainte de revenirea proiectului de test la preactivare.', factoryResetConfirmTitle: 'Confirmă resetul complet al testului', factoryResetConfirmBody: 'Introdu fraza exactă de mai jos. Se curăță doar starea de test Agent8/setup a proiectului allowlisted; wallet-ul, înregistrările de billing, conținutul și comenzile WordPress, precum și scrierile SEO live rămân păstrate.', factoryResetInput: 'Scrie fraza exactă de confirmare', factoryResetExecute: 'Execută resetul complet al testului', factoryResetCancel: 'Anulează',
            integrationStressConfirm: 'Rulezi stress testul de integrare reală? Poate porni analize automate și poate consuma credite.',
            runAll: 'Rulează toate testele', runState: 'Teste state', runSetup: 'Teste Setup', runResearch: 'Test Research', runSetupStress: 'Stress Setup Profile', runIntegrationStress: 'Stress integrare reală', runAction: 'Teste acțiuni', runLlm: 'Teste LLM',
            runWorker: 'Test worker', runRag: 'Test RAG', runLanguage: 'Teste limbă', runDeployParity: 'Verifică deploy parity', runLegacySync: 'Verifică sync legacy', runInvalid: 'Teste acțiuni invalide', runReset: 'Test reset', runStress: 'Stress test 15 min',
            stopStress: 'Oprește stress test', clearQa: 'Curăță log QA', exportQa: 'Exportă log QA JSON', systemStatus: 'Status sistem',
            currentPhase: 'Fază curentă', stateVersion: 'Versiune stare salvată', language: 'Limbă', apiStatus: 'Status API',
            qaStorage: 'Stocare QA', requestId: 'Request ID', activeTest: 'Test activ', name: 'Nume', steps: 'Pași',
            result: 'Rezultat', recentActions: 'Acțiuni recente', noQaActions: 'Nu există acțiuni QA', performance: 'Performanță',
            credits: 'Credite', availableCredits: 'Disponibile', estimatedCredits: 'Estimat', stepUsed: 'Consum pas', billingReference: 'Referință', lastBillableAction: 'Ultima acțiune cu credite', billingStatus: 'Status', plan: 'Plan', legacySync: 'Salvare locală',
            avgResponse: 'Răspuns mediu', throughput: 'Throughput', errorRate: 'Rată erori', canonicalState: 'Stare salvată',
            idle: 'Inactiv', approvalRequired: 'Necesită aprobare', awaiting_approval: 'Așteaptă aprobarea', approve: 'Aprobă', reject: 'Respinge',
            expand: 'Extinde', collapse: 'Restrânge', missingUncertain: 'Lipsește / incert', observations: 'Observații',
            writesState: 'scrie state: true', requiresApproval: 'necesită aprobare: true', billableFalse: 'consumă credite: false', writes_state: 'writes_state: true', requires_approval: 'requires_approval: true', billable: 'consumă credite', here: 'aici', aici: 'aici',
            start_setup_profile: 'pornește Setup SEO Profile', request_activation_key: 'cere cheia de activare', validate_activation_key: 'validează cheia de activare', repair_legacy_activation_sync: 'repară sync activare legacy',
            retry_activation_key: 'reîncearcă cheia', continue_after_activation: 'continuă după activare', reset_activation_shadow: 'resetează activation shadow',
            start_architecture_test: 'pornește test arhitectură', save_business_type: 'salvează tip business', save_primary_goal: 'salvează obiectiv principal',
            reset_lab: 'resetează lab', send_lab_email: 'trimite email lab', run_worker_ping: 'rulează worker ping', run_rag_context_test: 'testează context RAG',
            start_google_integrations: 'pornește integrări Google', skip_google_integrations: 'omite integrările Google', start_business_profile: 'pornește business profile',
            prepare_google_connection: 'conectează Google', refresh_google_connection_status: 'actualizează status Google', save_google_property_selection: 'salvează proprietăți Google',
            continue_to_business_profile: 'continuă către business profile',
            run_business_profile_autofill: 'analizează website-ul', refresh_business_profile_autofill_status: 'verifică analiza Business Profile',
            save_business_profile_field: 'salvează câmp Business Profile', mark_business_profile_field_unavailable: 'marchează câmp indisponibil', confirm_business_profile: 'confirmă Business Profile',
            start_objectives: 'pornește obiective', start_seo_profile: 'pornește SEO profile', save_seo_profile: 'salvează SEO Profile', confirm_seo_profile: 'confirmă SEO Profile', edit_seo_profile: 'editează SEO Profile', commit_seo_profile_to_legacy: 'sincronizează SEO Profile legacy', repair_seo_profile_confirmation_gap: 'repară SEO Profile', start_competition_keyword: 'pornește competiție și keywords',
            run_competition_keyword_analysis: 'pornește analiza', refresh_competition_keyword_analysis_status: 'verifică progresul', confirm_competition_keyword: 'confirmă rezultatele', repair_competition_keyword_quality: 'reverifică quality gate',
            revise_competition_keyword_selection: 'actualizează selecția',
            save_objectives: 'salvează obiective', confirm_objectives: 'confirmă obiective', edit_objectives: 'editează obiective', commit_objectives_to_legacy: 'sincronizează obiective legacy', commit_competition_keyword_to_legacy: 'sincronizează competiție legacy',
            start_tone_of_voice: 'pornește tone of voice', select_tone_of_voice_friendly: 'cald și prietenos', select_tone_of_voice_professional: 'profesional și clar',
            select_tone_of_voice_expert: 'expert și educativ', select_tone_of_voice_premium: 'premium și elegant', start_research_handoff: 'pregătește handoff research', commit_setup_completed_to_legacy: 'finalizează sync legacy',
            start_keyword_research_run: 'pornește Keyword Research', refresh_keyword_research_status: 'verifică progresul research', retry_keyword_research_run: 'Aprobă reluarea Keyword Research', start_technical_seo_run: 'Pornește auditul Technical SEO', refresh_technical_seo_status: 'verifică Technical SEO', complete_technical_seo_review: 'Finalizează Technical SEO', skip_technical_seo: 'sari peste Technical SEO', planning: 'Planificare', executing: 'Execuție', completed: 'finalizat', completed_with_warnings: 'necesită verificare',
            running: 'rulează', thinking: 'gândește', failed: 'eșuat',
            approve_content_plan: 'Aprobă planul',
            modalLoading: 'Se încarcă', modalLoadingData: 'Se încarcă datele de review...', modalSlowLoading: 'Datele acestui tab se încarcă greu. Nu am pornit nicio acțiune și nu am modificat site-ul. Dacă lista detaliată nu este disponibilă, AYSA afișează un rezumat sigur în loc să aplice ceva.', modalUnavailable: 'Review indisponibil', modalFailed: 'Cererea modalului a eșuat.', modalRequestFailed: 'Cerere eșuată',
            modalErrorEmptyFixPlan: 'Nu există fixuri automate disponibile pentru acest modul.', modalErrorUnknownAction: 'Acțiunea nu este disponibilă în versiunea API curentă.', modalErrorInvalidJson: 'API-ul a returnat un răspuns invalid; vezi diagnosticul.', modalErrorStaleState: 'State-ul s-a schimbat în fundal. Reîncarc și reîncerc.', modalNoExecutableFixes: 'Nu există fixuri automate disponibile.',
            modalSearch: 'Caută...', modalSearchDetails: 'Caută în detalii...', modalSearchLabel: 'Caută în datele review-ului', modalStatusLabel: 'Status review', modalPrevious: 'Înapoi', modalNext: 'Înainte', chatProviderFallback: 'Nu am putut genera răspunsul acum. Poți reîncerca sau continua din pasul recomandat.', modalWhatDone: 'Ce știm / ce am făcut', modalNextStepLabel: 'Următorul pas', modalAll: 'Toate', modalAccepted: 'Acceptate', modalRejected: 'Respinse', modalPage: 'Pagina', modalRows: 'rânduri', total: 'total', accepted: 'acceptate', rejected: 'respinse', filtered: 'filtrate', included: 'în batch', remaining: 'rămase', approved: 'aprobat', ready: 'pregătit',
            modalKeywordMappingTitle: 'Keyword Mapping', modalKeywordMappingSubtitle: 'Grupuri de keywords mapate la pagini țintă după Keyword Research. Verifică targetul și încrederea înainte de pasul următor.',
            modalCluster: 'Cluster', modalTargetUrl: 'URL țintă', modalPrimaryKeyword: 'Keyword principal', modalKeywordFamily: 'Familie keywords', modalSignals: 'Semnale', modalIntent: 'Intent', modalStatus: 'Status', modalConfidence: 'Încredere', modalTrust: 'Încredere', modalRecommendation: 'Recomandare', modalReasons: 'Motive', modalTrusted: 'De încredere', modalRecommendedReject: 'Recomandat respins', modalReviewNeeded: 'De verificat', modalReview: 'De verificat', modalAction: 'Acțiune',
            modalSchemaMoreItems: 'markup-uri',
            internalLinks: 'linkuri', inboundLinks: 'in', outboundLinks: 'out', existingLinks: 'Linkuri existente', proposedLinks: 'Oportunități propuse', noLinks: 'Nu există linkuri', maxOutboundPerPage: 'max outbound/pagină',
            internalLinkingPlanHint: 'Începe de aici: fiecare rând este o pagină/entitate țintă. Extinde Linkuri ca să verifici paginile sursă, ancorele și să respingi linkuri individuale.',
            internalLinkingStatsHint: 'Statistici legătură arată fiecare pagină, cuvintele cheie configurate, linkurile inbound/outbound existente și scurtătura către planul ei.',
            internalLinkingAnchorHint: 'Anchor text statistics sumarizează frecvența ancorelor din linkurile existente și propunerile acceptate.',
            internalLinkingKeywordsMore: 'în plus',
            modalIntentLegend: 'Intent', modalStatusLegend: 'Status', modalConfidenceLegend: 'Încredere', modalReviewLegend: 'Review', modalAutomation: 'Automatizare', modalA8Automated: 'A8 Automatizat', modalPartialAutomation: 'Automatizare parțială', modalManualReview: 'Review manual', modalA8AutomatedTitle: 'AYSA poate trimite acest fix spre execuție după ce salvezi planul.', modalPartialAutomationTitle: 'AYSA poate asista acest fix, dar este nevoie de review înainte de execuție.', modalManualReviewTitle: 'Acest element este doar pentru review momentan.', modalAutomationLegend: 'A8 Automatizat = poate fi trimis de AYSA după ce salvezi planul', modalMapped: 'mapat', modalLocal: 'local', modalCommercial: 'comercial', modalInformational: 'informațional', modalNavigational: 'navigațional',
            reject_keyword_mapping: 'Respinge', restore_keyword_mapping: 'Restaurează', reject_technical_fix: 'Respinge', restore_technical_fix: 'Restaurează', execute_technical_fix_plan: 'Trimite planul', refresh_technical_fix_execution_status: 'Actualizează execuția', generate_pagespeed_report: 'Generează raport', prepare_image_alt_text: 'Generează alt text imagini',
            executable: 'executabile', manual_needed: 'necesită verificare manuală', execution_status: 'Execuție', not_executable_yet: 'nu poate fi aplicat automat', submitted: 'trimis, în așteptarea execuției', synced: 'sincronizat, în așteptarea verificării', queued: 'în coadă', skipped: 'sărite', applied: 'raportat de site, în așteptarea verificării',
            statusCompletedWithWarnings: 'Gata, cu observații', statusReady: 'Gata', manualNeededHuman: 'Necesită verificare manuală', notExecutableHuman: 'Nu poate fi aplicat automat', needsImprovementHuman: 'Necesită îmbunătățire', excellentHuman: 'Excelent',
            technicalReviewWarningConfirm: 'Continuăm fără să aplicăm Image Alt acum?\n\nPoți reveni și relansa pregătirea imaginilor separat. AYSA nu va modifica imaginile în acest pas.',
        },
        fr: {
            title: 'AYSA Agent8', subtitle: 'Système d’exécution déterministe', active: 'Actif', conversation: 'Conversation',
            execution: 'Exécution Agent8', waiting: 'en attente de l’état', placeholder: 'Décrivez la tâche pour AYSA Agent 8...',
            authenticated: 'Authentifié', automatedSeo: 'SEO automatisé', qaDiagnostics: 'Diagnostics QA', controls: 'Contrôles',
            runAll: 'Lancer tous les tests', runState: 'Tests d’état', runAction: 'Tests d’actions', runLlm: 'Tests LLM',
            runInvalid: 'Tests actions invalides', runReset: 'Test reset', runStress: 'Stress test 15 min',
            stopStress: 'Arrêter le stress test', clearQa: 'Effacer le log QA', exportQa: 'Exporter log QA JSON', systemStatus: 'État système',
            currentPhase: 'Phase actuelle', stateVersion: 'Version état', language: 'Langue', apiStatus: 'État API',
            qaStorage: 'Stockage QA', requestId: 'Request ID', activeTest: 'Test actif', name: 'Nom', steps: 'Étapes',
            result: 'Résultat', recentActions: 'Actions récentes', noQaActions: 'Aucune action QA', performance: 'Performance',
            avgResponse: 'Réponse moyenne', throughput: 'Débit', errorRate: 'Taux d’erreur', canonicalState: 'État canonique',
            idle: 'Inactif', approvalRequired: 'Approbation requise', approve: 'Approuver', reject: 'Rejeter',
            start_architecture_test: 'démarrer le test architecture', save_business_type: 'enregistrer le type d’entreprise', save_primary_goal: 'enregistrer l’objectif principal',
            reset_lab: 'réinitialiser le lab', send_lab_email: 'envoyer email lab', planning: 'Planification', executing: 'Exécution', completed: 'terminé',
            running: 'en cours', thinking: 'réflexion', failed: 'échec'
        },
        de: {
            title: 'AYSA Agent8', subtitle: 'Deterministisches Ausführungssystem', active: 'Aktiv', conversation: 'Konversation',
            execution: 'Agent8 Ausführung', waiting: 'wartet auf Status', placeholder: 'Beschreibe die Aufgabe für AYSA Agent 8...',
            authenticated: 'Authentifiziert', automatedSeo: 'Automatisiertes SEO', qaDiagnostics: 'QA-Diagnose', controls: 'Steuerung',
            runAll: 'Alle Tests starten', runState: 'Status-Tests', runAction: 'Aktions-Tests', runLlm: 'LLM-Tests',
            runInvalid: 'Ungültige Aktionen testen', runReset: 'Reset testen', runStress: '15-Min-Stresstest',
            stopStress: 'Stresstest stoppen', clearQa: 'QA-Log löschen', exportQa: 'QA-Log JSON exportieren', systemStatus: 'Systemstatus',
            currentPhase: 'Aktuelle Phase', stateVersion: 'Statusversion', language: 'Sprache', apiStatus: 'API-Status',
            qaStorage: 'QA-Speicher', requestId: 'Request ID', activeTest: 'Aktiver Test', name: 'Name', steps: 'Schritte',
            result: 'Ergebnis', recentActions: 'Letzte Aktionen', noQaActions: 'Keine QA-Aktionen', performance: 'Leistung',
            avgResponse: 'Ø Antwort', throughput: 'Durchsatz', errorRate: 'Fehlerrate', canonicalState: 'Kanonischer Status',
            idle: 'Leerlauf', approvalRequired: 'Genehmigung erforderlich', approve: 'Genehmigen', reject: 'Ablehnen',
            runAll: 'Alle Tests starten', runState: 'Status-Tests', runAction: 'Aktions-Tests', runLlm: 'LLM-Tests',
            runInvalid: 'Ungültige Aktionen testen', runReset: 'Reset testen', runStress: '15-Min-Stresstest',
            stopStress: 'Stresstest stoppen', clearQa: 'QA-Log löschen', exportQa: 'QA-Log JSON exportieren',
            start_architecture_test: 'Architekturtest starten', save_business_type: 'Geschäftstyp speichern', save_primary_goal: 'Hauptziel speichern',
            reset_lab: 'Lab zurücksetzen', send_lab_email: 'Lab-E-Mail senden', planning: 'Planung', executing: 'Ausführung', completed: 'abgeschlossen',
            running: 'läuft', thinking: 'denkt', failed: 'fehlgeschlagen'
        },
        es: {
            title: 'AYSA Agent8', subtitle: 'Sistema de ejecución determinista', active: 'Activo', conversation: 'Conversación',
            execution: 'Ejecución Agent8', waiting: 'esperando estado', placeholder: 'Describe la tarea para AYSA Agent 8...',
            authenticated: 'Autenticado', automatedSeo: 'SEO automatizado', qaDiagnostics: 'Diagnóstico QA', controls: 'Controles',
            systemStatus: 'Estado del sistema', currentPhase: 'Fase actual', stateVersion: 'Versión de estado', language: 'Idioma',
            apiStatus: 'Estado API', activeTest: 'Prueba activa', recentActions: 'Acciones recientes', performance: 'Rendimiento',
            canonicalState: 'Estado canónico', idle: 'Inactivo', approvalRequired: 'Requiere aprobación', approve: 'Aprobar', reject: 'Rechazar'
        },
        it: {
            title: 'AYSA Agent8', subtitle: 'Sistema di esecuzione deterministico', active: 'Attivo', conversation: 'Conversazione',
            execution: 'Esecuzione Agent8', waiting: 'in attesa dello stato', placeholder: 'Descrivi il task per AYSA Agent 8...',
            authenticated: 'Autenticato', automatedSeo: 'SEO automatizzato', qaDiagnostics: 'Diagnostica QA', controls: 'Controlli',
            systemStatus: 'Stato sistema', currentPhase: 'Fase corrente', stateVersion: 'Versione stato', language: 'Lingua',
            apiStatus: 'Stato API', activeTest: 'Test attivo', recentActions: 'Azioni recenti', performance: 'Prestazioni',
            canonicalState: 'Stato canonico', idle: 'Inattivo', approvalRequired: 'Approvazione richiesta', approve: 'Approva', reject: 'Rifiuta'
        },
        pt: {
            title: 'AYSA Agent8', subtitle: 'Sistema de execução determinístico', active: 'Ativo', conversation: 'Conversa',
            execution: 'Execução Agent8', waiting: 'aguardando estado', placeholder: 'Descreva a tarefa para AYSA Agent 8...',
            authenticated: 'Autenticado', automatedSeo: 'SEO automatizado', qaDiagnostics: 'Diagnóstico QA', controls: 'Controles',
            systemStatus: 'Status do sistema', currentPhase: 'Fase atual', stateVersion: 'Versão do estado', language: 'Idioma',
            apiStatus: 'Status API', activeTest: 'Teste ativo', recentActions: 'Ações recentes', performance: 'Desempenho',
            canonicalState: 'Estado canônico', idle: 'Inativo', approvalRequired: 'Aprovação necessária', approve: 'Aprovar', reject: 'Rejeitar'
        },
        nl: {
            title: 'AYSA Agent8', subtitle: 'Deterministisch uitvoeringssysteem', active: 'Actief', conversation: 'Gesprek',
            execution: 'Agent8 uitvoering', waiting: 'wacht op status', placeholder: 'Beschrijf de taak voor AYSA Agent 8...',
            authenticated: 'Geauthenticeerd', automatedSeo: 'Geautomatiseerde SEO', qaDiagnostics: 'QA-diagnose', controls: 'Bediening',
            systemStatus: 'Systeemstatus', currentPhase: 'Huidige fase', stateVersion: 'Statusversie', language: 'Taal',
            apiStatus: 'API-status', activeTest: 'Actieve test', recentActions: 'Recente acties', performance: 'Prestaties',
            canonicalState: 'Canonieke status', idle: 'Inactief', approvalRequired: 'Goedkeuring vereist', approve: 'Goedkeuren', reject: 'Afwijzen'
        },
        pl: {
            title: 'AYSA Agent8', subtitle: 'Deterministyczny system wykonania', active: 'Aktywny', conversation: 'Rozmowa',
            execution: 'Wykonanie Agent8', waiting: 'oczekiwanie na stan', placeholder: 'Opisz zadanie dla AYSA Agent 8...',
            authenticated: 'Uwierzytelniono', automatedSeo: 'Automatyczne SEO', qaDiagnostics: 'Diagnostyka QA', controls: 'Kontrole',
            systemStatus: 'Status systemu', currentPhase: 'Aktualna faza', stateVersion: 'Wersja stanu', language: 'Język',
            apiStatus: 'Status API', activeTest: 'Aktywny test', recentActions: 'Ostatnie akcje', performance: 'Wydajność',
            canonicalState: 'Stan kanoniczny', idle: 'Bezczynny', approvalRequired: 'Wymaga zatwierdzenia', approve: 'Zatwierdź', reject: 'Odrzuć'
        },
        ar: {
            title: 'مختبر AYSA Agent 8 V3', subtitle: 'نظام تنفيذ حتمي', active: 'نشط', conversation: 'المحادثة',
            execution: 'تنفيذ Agent8', waiting: 'بانتظار الحالة', placeholder: 'اكتب المهمة لـ AYSA Agent 8...',
            authenticated: 'تم التوثيق', automatedSeo: 'SEO آلي', qaDiagnostics: 'تشخيص QA', controls: 'التحكم',
            runAll: 'تشغيل كل الاختبارات', runState: 'اختبارات الحالة', runAction: 'اختبارات الإجراءات', runLlm: 'اختبارات LLM',
            runInvalid: 'اختبارات إجراء غير صالح', runReset: 'اختبار إعادة الضبط', runStress: 'اختبار ضغط 15 دقيقة',
            stopStress: 'إيقاف اختبار الضغط', clearQa: 'مسح سجل QA', exportQa: 'تصدير سجل QA JSON', systemStatus: 'حالة النظام',
            currentPhase: 'المرحلة الحالية', stateVersion: 'إصدار الحالة', language: 'اللغة', apiStatus: 'حالة API',
            qaStorage: 'تخزين QA', requestId: 'Request ID', activeTest: 'اختبار نشط', name: 'الاسم', steps: 'الخطوات',
            result: 'النتيجة', recentActions: 'الإجراءات الأخيرة', noQaActions: 'لا توجد إجراءات QA', performance: 'الأداء',
            avgResponse: 'متوسط الاستجابة', throughput: 'الإنتاجية', errorRate: 'معدل الخطأ', canonicalState: 'الحالة المعتمدة',
            idle: 'خامل', approvalRequired: 'يتطلب موافقة', approve: 'موافقة', reject: 'رفض',
            start_architecture_test: 'بدء اختبار البنية', save_business_type: 'حفظ نوع النشاط', save_primary_goal: 'حفظ الهدف الرئيسي',
            reset_lab: 'إعادة ضبط المختبر', send_lab_email: 'إرسال بريد المختبر'
        }
    };

    const LANGUAGE_PACK = {
        ro: 'ro', 'en-GB': 'en', 'en-US': 'en', 'en-CA': 'en', fr: 'fr', 'fr-CA': 'fr', 'ar-AE': 'ar',
        de: 'de', es: 'es', it: 'it', pt: 'pt', nl: 'nl', pl: 'pl', sq: 'sq', hy: 'hy', az: 'az', eu: 'eu',
        be: 'be', bs: 'bs', bg: 'bg', ca: 'ca', hr: 'hr', cs: 'cs', da: 'da', et: 'et', fi: 'fi', gl: 'gl',
        ka: 'ka', el: 'el', hu: 'hu', is: 'is', ga: 'ga', lv: 'lv', lt: 'lt', lb: 'lb', mk: 'mk', mt: 'mt',
        no: 'no', ru: 'ru', sr: 'sr', sk: 'sk', sl: 'sl', sv: 'sv', tr: 'tr', uk: 'uk', cy: 'cy', yi: 'yi'
    };

    const ACTIVE_I18N_COMPLETIONS = {
        fr: {
            fullReset: 'Réinitialisation complète', fullResetConfirm: 'Réinitialiser Agent8 Lab en préactivation et effacer l’historique du chat, les données de configuration et les résultats locaux enregistrés?', fullResetDone: 'Agent8 Lab a été réinitialisé.', integrationStressConfirm: 'Lancer le test réel d’intégration? Cela peut démarrer des analyses automatisées et consommer des crédits.',
            runSetup: 'Test Setup', runResearch: 'Test Research', runSetupStress: 'Stress test Setup', runIntegrationStress: 'Stress test intégration', runWorker: 'Test worker', runRag: 'Test RAG', runLanguage: 'Tests langue', runDeployParity: 'Vérifier la parité du déploiement', runLegacySync: 'Vérifier la synchronisation locale',
            unauthenticated: 'Non authentifié', credits: 'Crédits', availableCredits: 'Disponibles', estimatedCredits: 'Estimés', stepUsed: 'Consommation étape', billingReference: 'Référence', lastBillableAction: 'Dernière action avec crédits', billingStatus: 'Statut', plan: 'Plan', legacySync: 'Sauvegarde locale',
            expand: 'Développer', collapse: 'Réduire', writesState: 'écrit l’état: true', requiresApproval: 'requiert approbation: true', billableFalse: 'facturable: false', writes_state: 'writes_state: true', requires_approval: 'requires_approval: true', billable: 'facturable', here: 'ici', aici: 'ici',
            approve_content_plan: 'Approuver le plan', modalLoading: 'Chargement', modalLoadingData: 'Chargement des données de revue...', modalUnavailable: 'Revue indisponible', modalFailed: 'La requête du modal a échoué.', modalRequestFailed: 'Requête échouée', modalErrorEmptyFixPlan: 'Aucun correctif automatique n’est disponible pour ce module.', modalErrorUnknownAction: 'Cette action n’est pas disponible dans la version actuelle de l’API.', modalErrorInvalidJson: 'L’API a renvoyé une réponse invalide; vérifiez le diagnostic.', modalErrorStaleState: 'L’état a changé en arrière-plan. Actualisation et nouvelle tentative.', modalNoExecutableFixes: 'Aucun correctif automatique disponible.',
            modalSearch: 'Rechercher...', modalSearchDetails: 'Rechercher dans les détails...', chatProviderFallback: 'Je n’ai pas pu générer la réponse maintenant. Vous pouvez réessayer ou continuer depuis l’étape recommandée.', modalWhatDone: 'Ce que nous savons / avons fait', modalNextStepLabel: 'Prochaine étape', modalAll: 'Tous', modalAccepted: 'Acceptés', modalRejected: 'Rejetés', modalPage: 'Page', modalRows: 'lignes', total: 'total', accepted: 'acceptés', rejected: 'rejetés', filtered: 'filtrés', included: 'dans ce lot', remaining: 'restants', approved: 'approuvé', ready: 'prêt',
            modalKeywordMappingTitle: 'Mapping des mots-clés', modalKeywordMappingSubtitle: 'Clusters associés et pages cibles depuis la projection de recherche.', modalCluster: 'Cluster', modalTargetUrl: 'URL cible', modalPrimaryKeyword: 'Mot-clé principal', modalKeywordFamily: 'Famille de mots-clés', modalSignals: 'Signaux', modalIntent: 'Intention', modalStatus: 'Statut', modalConfidence: 'Confiance', modalTrust: 'Confiance', modalRecommendation: 'Recommandation', modalReasons: 'Raisons', modalTrusted: 'Fiable', modalRecommendedReject: 'Rejet recommandé', modalReviewNeeded: 'Revue', modalReview: 'Revue', modalAction: 'Action',
            modalSchemaMoreItems: 'balises', internalLinks: 'liens', inboundLinks: 'entrants', outboundLinks: 'sortants', existingLinks: 'Liens existants', proposedLinks: 'Opportunités proposées', noLinks: 'Aucun lien', maxOutboundPerPage: 'max sortants/page', internalLinkingPlanHint: 'Commencez ici: chaque ligne est une page ou entité cible. Ouvrez Liens pour revoir les pages sources, ancres et rejeter des liens individuels.', internalLinkingStatsHint: 'Les statistiques de liens montrent chaque page, les mots-clés configurés, les liens entrants/sortants et un raccourci vers son plan.', internalLinkingAnchorHint: 'Les statistiques d’ancres résument la fréquence des ancres dans les liens existants et proposés.', internalLinkingKeywordsMore: 'de plus',
            modalIntentLegend: 'Intention', modalStatusLegend: 'Statut', modalConfidenceLegend: 'Confiance', modalReviewLegend: 'Revue', modalAutomation: 'Automatisation', modalA8Automated: 'A8 automatisé', modalPartialAutomation: 'Automatisation partielle', modalManualReview: 'Revue manuelle', modalA8AutomatedTitle: 'AYSA peut soumettre ce correctif après l’enregistrement du plan.', modalPartialAutomationTitle: 'AYSA peut assister ce correctif, mais une revue est requise avant l’exécution.', modalManualReviewTitle: 'Cet élément est en revue uniquement pour l’instant.', modalAutomationLegend: 'A8 automatisé = peut être soumis par AYSA après l’enregistrement du plan', modalMapped: 'mappé', modalLocal: 'local', modalCommercial: 'commercial', modalInformational: 'informationnel', modalNavigational: 'navigationnel',
            reject_keyword_mapping: 'Rejeter', restore_keyword_mapping: 'Restaurer', reject_technical_fix: 'Rejeter', restore_technical_fix: 'Restaurer', execute_technical_fix_plan: 'Submit plan', refresh_technical_fix_execution_status: 'Actualiser l’exécution', generate_pagespeed_report: 'Générer le rapport', prepare_image_alt_text: 'Générer les textes alt des images',
            executable: 'exécutable', manual_needed: 'manuel requis', execution_status: 'Exécution', not_executable_yet: 'pas encore exécutable', submitted: 'soumis', synced: 'synchronisé, vérification en attente', queued: 'en file', skipped: 'ignoré', applied: 'signalé par le site, vérification en attente'
        },
        de: {
            fullReset: 'Vollständig zurücksetzen', fullResetConfirm: 'Agent8 Lab auf Voraktivierung zurücksetzen und Chatverlauf, Setup-Daten und lokal gespeicherte Ergebnisse löschen?', fullResetDone: 'Agent8 Lab wurde zurückgesetzt.', integrationStressConfirm: 'Den echten Integrationstest starten? Das kann automatisierte Analysen starten und Credits verbrauchen.',
            runSetup: 'Setup-Test', runResearch: 'Research-Test', runSetupStress: 'Setup-Stresstest', runIntegrationStress: 'Integrations-Stresstest', runWorker: 'Worker-Test', runRag: 'RAG-Test', runLanguage: 'Sprachtests', runDeployParity: 'Deploy-Parität prüfen', runLegacySync: 'Lokale Synchronisierung prüfen',
            unauthenticated: 'Nicht authentifiziert', credits: 'Credits', availableCredits: 'Verfügbar', estimatedCredits: 'Geschätzt', stepUsed: 'Schrittverbrauch', billingReference: 'Referenz', lastBillableAction: 'Letzte creditpflichtige Aktion', billingStatus: 'Status', plan: 'Plan', legacySync: 'Lokale Speicherung',
            expand: 'Erweitern', collapse: 'Reduzieren', writesState: 'schreibt Status: true', requiresApproval: 'erfordert Freigabe: true', billableFalse: 'abrechenbar: false', writes_state: 'writes_state: true', requires_approval: 'requires_approval: true', billable: 'abrechenbar', here: 'hier', aici: 'hier',
            approve_content_plan: 'Plan freigeben', modalLoading: 'Lädt', modalLoadingData: 'Review-Daten werden geladen...', modalUnavailable: 'Review nicht verfügbar', modalFailed: 'Modal-Anfrage fehlgeschlagen.', modalRequestFailed: 'Anfrage fehlgeschlagen', modalErrorEmptyFixPlan: 'Für dieses Modul sind keine automatischen Korrekturen verfügbar.', modalErrorUnknownAction: 'Diese Aktion ist in der aktuellen API-Version nicht verfügbar.', modalErrorInvalidJson: 'Die API hat eine ungültige Antwort geliefert; Diagnostik prüfen.', modalErrorStaleState: 'Der Status hat sich im Hintergrund geändert. Aktualisiere und versuche erneut.', modalNoExecutableFixes: 'Keine automatischen Korrekturen verfügbar.',
            modalSearch: 'Suchen...', modalSearchDetails: 'Details durchsuchen...', chatProviderFallback: 'Ich konnte die Antwort gerade nicht generieren. Du kannst es erneut versuchen oder mit dem empfohlenen Schritt fortfahren.', modalWhatDone: 'Was wir wissen / getan haben', modalNextStepLabel: 'Nächster Schritt', modalAll: 'Alle', modalAccepted: 'Akzeptiert', modalRejected: 'Abgelehnt', modalPage: 'Seite', modalRows: 'Zeilen', total: 'gesamt', accepted: 'akzeptiert', rejected: 'abgelehnt', filtered: 'gefiltert', included: 'in diesem Batch', remaining: 'verbleibend', approved: 'freigegeben', ready: 'bereit',
            modalKeywordMappingTitle: 'Keyword-Mapping', modalKeywordMappingSubtitle: 'Gemappte Cluster und Zielseiten aus der Research-Projektion.', modalCluster: 'Cluster', modalTargetUrl: 'Ziel-URL', modalPrimaryKeyword: 'Hauptkeyword', modalKeywordFamily: 'Keyword-Familie', modalSignals: 'Signale', modalIntent: 'Intention', modalStatus: 'Status', modalConfidence: 'Konfidenz', modalTrust: 'Vertrauen', modalRecommendation: 'Empfehlung', modalReasons: 'Gründe', modalTrusted: 'Vertrauenswürdig', modalRecommendedReject: 'Ablehnung empfohlen', modalReviewNeeded: 'Review', modalReview: 'Review', modalAction: 'Aktion',
            modalSchemaMoreItems: 'Markups', internalLinks: 'Links', inboundLinks: 'eingehend', outboundLinks: 'ausgehend', existingLinks: 'Bestehende Links', proposedLinks: 'Vorgeschlagene Chancen', noLinks: 'Keine Links', maxOutboundPerPage: 'max. ausgehend/Seite', internalLinkingPlanHint: 'Hier starten: Jede Zeile ist eine Zielseite oder Entität. Öffne Links, um Quellseiten, Anker und einzelne Links zu prüfen.', internalLinkingStatsHint: 'Linkstatistiken zeigen jede Seite, konfigurierte Keywords, bestehende interne Links und eine Abkürzung zum Plan.', internalLinkingAnchorHint: 'Ankerstatistiken fassen die Häufigkeit von Ankern in bestehenden und akzeptierten Links zusammen.', internalLinkingKeywordsMore: 'mehr',
            modalIntentLegend: 'Intention', modalStatusLegend: 'Status', modalConfidenceLegend: 'Konfidenz', modalReviewLegend: 'Review', modalAutomation: 'Automatisierung', modalA8Automated: 'A8 automatisiert', modalPartialAutomation: 'Teilautomatisierung', modalManualReview: 'Manueller Review', modalA8AutomatedTitle: 'AYSA kann diese Korrektur nach Speichern und Ausführen ausführen.', modalPartialAutomationTitle: 'AYSA kann helfen, aber vor der Ausführung ist ein Review nötig.', modalManualReviewTitle: 'Dieses Element ist derzeit nur Review.', modalAutomationLegend: 'A8 automatisiert = AYSA kann nach Speichern und Ausführen arbeiten', modalMapped: 'gemappt', modalLocal: 'lokal', modalCommercial: 'kommerziell', modalInformational: 'informativ', modalNavigational: 'navigational',
            reject_keyword_mapping: 'Ablehnen', restore_keyword_mapping: 'Wiederherstellen', reject_technical_fix: 'Ablehnen', restore_technical_fix: 'Wiederherstellen', execute_technical_fix_plan: 'Submit plan', refresh_technical_fix_execution_status: 'Ausführung aktualisieren', generate_pagespeed_report: 'Bericht generieren', prepare_image_alt_text: 'Alt-Texte für Bilder generieren',
            executable: 'ausführbar', manual_needed: 'manuell nötig', execution_status: 'Ausführung', not_executable_yet: 'noch nicht ausführbar', submitted: 'gesendet', synced: 'synchronisiert, Prüfung ausstehend', queued: 'in Warteschlange', skipped: 'übersprungen', applied: 'von der Website gemeldet, Prüfung ausstehend'
        }
    };

    const ACTIVE_I18N_ALIASES = {
        es: {
            title: 'AYSA Agent8', subtitle: 'Sistema de ejecución determinista', active: 'Activo', conversation: 'Conversación', execution: 'Ejecución Agent8', waiting: 'esperando actualizaciones', placeholder: 'Describe la tarea para AYSA Agent 8...',
            authenticated: 'Autenticado', unauthenticated: 'No autenticado', automatedSeo: 'SEO automatizado', qaDiagnostics: 'Diagnóstico QA', controls: 'Controles', fullReset: 'Restablecimiento completo', runAll: 'Ejecutar todas las pruebas', runState: 'Pruebas de estado', runSetup: 'Prueba Setup', runResearch: 'Prueba Research', runAction: 'Pruebas de acciones', runLlm: 'Pruebas LLM', runLanguage: 'Pruebas de idioma', clearQa: 'Limpiar registro QA', exportQa: 'Exportar registro QA JSON', systemStatus: 'Estado del sistema', credits: 'Créditos', availableCredits: 'Disponibles', estimatedCredits: 'Estimados', activeTest: 'Prueba activa', recentActions: 'Acciones recientes', performance: 'Rendimiento', planning: 'Planificación', executing: 'Ejecución', completed: 'completado', running: 'en curso', thinking: 'pensando', failed: 'fallido', approve: 'Aprobar', reject: 'Rechazar', modalLoading: 'Cargando', modalSearch: 'Buscar...', modalSearchDetails: 'Buscar en detalles...', modalAll: 'Todos', modalAccepted: 'Aceptados', modalRejected: 'Rechazados', modalAction: 'Acción', execute_technical_fix_plan: 'Submit plan', reject_technical_fix: 'Rechazar', restore_technical_fix: 'Restaurar'
        },
        it: {
            title: 'AYSA Agent8', subtitle: 'Sistema di esecuzione deterministico', active: 'Attivo', conversation: 'Conversazione', execution: 'Esecuzione Agent8', waiting: 'in attesa di aggiornamenti', placeholder: 'Descrivi il task per AYSA Agent 8...',
            authenticated: 'Autenticato', unauthenticated: 'Non autenticato', automatedSeo: 'SEO automatizzato', qaDiagnostics: 'Diagnostica QA', controls: 'Controlli', fullReset: 'Reset completo', runAll: 'Esegui tutti i test', runState: 'Test stato', runSetup: 'Test Setup', runResearch: 'Test Research', runAction: 'Test azioni', runLlm: 'Test LLM', runLanguage: 'Test lingua', clearQa: 'Pulisci log QA', exportQa: 'Esporta log QA JSON', systemStatus: 'Stato sistema', credits: 'Crediti', availableCredits: 'Disponibili', estimatedCredits: 'Stimati', activeTest: 'Test attivo', recentActions: 'Azioni recenti', performance: 'Prestazioni', planning: 'Pianificazione', executing: 'Esecuzione', completed: 'completato', running: 'in corso', thinking: 'pensando', failed: 'fallito', approve: 'Approva', reject: 'Rifiuta', modalLoading: 'Caricamento', modalSearch: 'Cerca...', modalSearchDetails: 'Cerca nei dettagli...', modalAll: 'Tutti', modalAccepted: 'Accettati', modalRejected: 'Rifiutati', modalAction: 'Azione', execute_technical_fix_plan: 'Submit plan', reject_technical_fix: 'Rifiuta', restore_technical_fix: 'Ripristina'
        },
        pt: {
            title: 'AYSA Agent8', subtitle: 'Sistema de execução determinístico', active: 'Ativo', conversation: 'Conversa', execution: 'Execução Agent8', waiting: 'aguardando atualizações', placeholder: 'Descreva a tarefa para AYSA Agent 8...',
            authenticated: 'Autenticado', unauthenticated: 'Não autenticado', automatedSeo: 'SEO automatizado', qaDiagnostics: 'Diagnóstico QA', controls: 'Controles', fullReset: 'Reset completo', runAll: 'Executar todos os testes', runState: 'Testes de estado', runSetup: 'Teste Setup', runResearch: 'Teste Research', runAction: 'Testes de ações', runLlm: 'Testes LLM', runLanguage: 'Testes de idioma', clearQa: 'Limpar log QA', exportQa: 'Exportar log QA JSON', systemStatus: 'Status do sistema', credits: 'Créditos', availableCredits: 'Disponíveis', estimatedCredits: 'Estimados', activeTest: 'Teste ativo', recentActions: 'Ações recentes', performance: 'Desempenho', planning: 'Planejamento', executing: 'Execução', completed: 'concluído', running: 'em execução', thinking: 'pensando', failed: 'falhou', approve: 'Aprovar', reject: 'Rejeitar', modalLoading: 'Carregando', modalSearch: 'Pesquisar...', modalSearchDetails: 'Pesquisar nos detalhes...', modalAll: 'Todos', modalAccepted: 'Aceitos', modalRejected: 'Rejeitados', modalAction: 'Ação', execute_technical_fix_plan: 'Submit plan', reject_technical_fix: 'Rejeitar', restore_technical_fix: 'Restaurar'
        },
        nl: {
            title: 'AYSA Agent8', subtitle: 'Deterministisch uitvoeringssysteem', active: 'Actief', conversation: 'Gesprek', execution: 'Agent8 uitvoering', waiting: 'wacht op updates', placeholder: 'Beschrijf de taak voor AYSA Agent 8...',
            authenticated: 'Geauthenticeerd', unauthenticated: 'Niet geauthenticeerd', automatedSeo: 'Geautomatiseerde SEO', qaDiagnostics: 'QA-diagnose', controls: 'Bediening', fullReset: 'Volledige reset', runAll: 'Alle tests uitvoeren', runState: 'Statustests', runSetup: 'Setup-test', runResearch: 'Research-test', runAction: 'Actietests', runLlm: 'LLM-tests', runLanguage: 'Taaltests', clearQa: 'QA-log wissen', exportQa: 'QA-log JSON exporteren', systemStatus: 'Systeemstatus', credits: 'Credits', availableCredits: 'Beschikbaar', estimatedCredits: 'Geschat', activeTest: 'Actieve test', recentActions: 'Recente acties', performance: 'Prestaties', planning: 'Planning', executing: 'Uitvoering', completed: 'voltooid', running: 'actief', thinking: 'denkt', failed: 'mislukt', approve: 'Goedkeuren', reject: 'Afwijzen', modalLoading: 'Laden', modalSearch: 'Zoeken...', modalSearchDetails: 'Zoeken in details...', modalAll: 'Alle', modalAccepted: 'Geaccepteerd', modalRejected: 'Afgewezen', modalAction: 'Actie', execute_technical_fix_plan: 'Submit plan', reject_technical_fix: 'Afwijzen', restore_technical_fix: 'Herstellen'
        },
        pl: {
            title: 'AYSA Agent8', subtitle: 'Deterministyczny system wykonania', active: 'Aktywny', conversation: 'Rozmowa', execution: 'Wykonanie Agent8', waiting: 'oczekuje na aktualizacje', placeholder: 'Opisz zadanie dla AYSA Agent 8...',
            authenticated: 'Uwierzytelniono', unauthenticated: 'Nie uwierzytelniono', automatedSeo: 'Automatyczne SEO', qaDiagnostics: 'Diagnostyka QA', controls: 'Kontrole', fullReset: 'Pełny reset', runAll: 'Uruchom wszystkie testy', runState: 'Testy stanu', runSetup: 'Test Setup', runResearch: 'Test Research', runAction: 'Testy akcji', runLlm: 'Testy LLM', runLanguage: 'Testy języka', clearQa: 'Wyczyść log QA', exportQa: 'Eksportuj log QA JSON', systemStatus: 'Status systemu', credits: 'Kredyty', availableCredits: 'Dostępne', estimatedCredits: 'Szacowane', activeTest: 'Aktywny test', recentActions: 'Ostatnie akcje', performance: 'Wydajność', planning: 'Planowanie', executing: 'Wykonanie', completed: 'ukończone', running: 'w toku', thinking: 'myśli', failed: 'nieudane', approve: 'Zatwierdź', reject: 'Odrzuć', modalLoading: 'Ładowanie', modalSearch: 'Szukaj...', modalSearchDetails: 'Szukaj w szczegółach...', modalAll: 'Wszystkie', modalAccepted: 'Zaakceptowane', modalRejected: 'Odrzucone', modalAction: 'Akcja', execute_technical_fix_plan: 'Submit plan', reject_technical_fix: 'Odrzuć', restore_technical_fix: 'Przywróć'
        },
        ar: {
            fullReset: 'إعادة ضبط كاملة', fullResetConfirm: 'هل تريد إعادة Agent8 Lab إلى ما قبل التفعيل ومسح سجل المحادثة وبيانات الإعداد والنتائج المحلية؟', fullResetDone: 'تمت إعادة ضبط Agent8 Lab.', integrationStressConfirm: 'تشغيل اختبار التكامل الحقيقي؟ قد يبدأ تحليلات آلية ويستهلك أرصدة.', runSetup: 'اختبار الإعداد', runResearch: 'اختبار البحث', runWorker: 'اختبار العامل', runRag: 'اختبار RAG', runLanguage: 'اختبارات اللغة', credits: 'الأرصدة', availableCredits: 'متاح', estimatedCredits: 'مقدر', modalLoading: 'جار التحميل', modalSearch: 'بحث...', modalSearchDetails: 'بحث في التفاصيل...', modalAll: 'الكل', modalAccepted: 'مقبول', modalRejected: 'مرفوض', modalAction: 'إجراء', execute_technical_fix_plan: 'Submit plan', reject_technical_fix: 'رفض', restore_technical_fix: 'استعادة'
        }
    };

    const ACTIVE_I18N_WORDS = {
        fr: { start: 'démarrer', run: 'lancer', refresh: 'actualiser', retry: 'réessayer', complete: 'finaliser', skip: 'ignorer', confirm: 'confirmer', save: 'enregistrer', edit: 'modifier', commit: 'synchroniser', continue: 'continuer', prepare: 'préparer', connect: 'connecter', check: 'vérifier', repair: 'réparer', execute: 'exécuter', reject: 'rejeter', restore: 'restaurer', generate: 'générer', modal: 'fenêtre', error: 'erreur', keyword: 'mot-clé', mapping: 'mapping', technical: 'technique', fix: 'correctif', execution: 'exécution', status: 'statut', image: 'image', alt: 'alt', text: 'texte', page: 'page', rows: 'lignes', research: 'recherche', business: 'entreprise', profile: 'profil', objectives: 'objectifs', competition: 'concurrence', quality: 'qualité', gate: 'contrôle', tone: 'ton', voice: 'voix', content: 'contenu', plan: 'plan', schema: 'schema', links: 'liens', internal: 'interne', automation: 'automatisation', manual: 'manuel', review: 'revue' },
        de: { start: 'starten', run: 'ausführen', refresh: 'aktualisieren', retry: 'erneut versuchen', complete: 'abschließen', skip: 'überspringen', confirm: 'bestätigen', save: 'speichern', edit: 'bearbeiten', commit: 'synchronisieren', continue: 'fortfahren', prepare: 'vorbereiten', connect: 'verbinden', check: 'prüfen', repair: 'reparieren', execute: 'ausführen', reject: 'ablehnen', restore: 'wiederherstellen', generate: 'generieren', modal: 'Dialog', error: 'Fehler', keyword: 'Keyword', mapping: 'Mapping', technical: 'technisch', fix: 'Korrektur', execution: 'Ausführung', status: 'Status', image: 'Bild', alt: 'Alt', text: 'Text', page: 'Seite', rows: 'Zeilen', research: 'Recherche', business: 'Business', profile: 'Profil', objectives: 'Ziele', competition: 'Wettbewerb', quality: 'Qualität', gate: 'Kontrolle', tone: 'Ton', voice: 'Stimme', content: 'Inhalt', plan: 'Plan', schema: 'Schema', links: 'Links', internal: 'intern', automation: 'Automatisierung', manual: 'manuell', review: 'Review' },
        es: { start: 'iniciar', run: 'ejecutar', refresh: 'actualizar', retry: 'reintentar', complete: 'finalizar', skip: 'omitir', confirm: 'confirmar', save: 'guardar', edit: 'editar', commit: 'sincronizar', continue: 'continuar', prepare: 'preparar', connect: 'conectar', check: 'verificar', repair: 'reparar', execute: 'ejecutar', reject: 'rechazar', restore: 'restaurar', generate: 'generar', modal: 'modal', error: 'error', keyword: 'palabra clave', mapping: 'mapeo', technical: 'técnico', fix: 'corrección', execution: 'ejecución', status: 'estado', image: 'imagen', alt: 'alt', text: 'texto', page: 'página', rows: 'filas', research: 'investigación', business: 'negocio', profile: 'perfil', objectives: 'objetivos', competition: 'competencia', quality: 'calidad', gate: 'control', tone: 'tono', voice: 'voz', content: 'contenido', plan: 'plan', schema: 'schema', links: 'enlaces', internal: 'interno', automation: 'automatización', manual: 'manual', review: 'revisión' },
        it: { start: 'avvia', run: 'esegui', refresh: 'aggiorna', retry: 'riprova', complete: 'finalizza', skip: 'salta', confirm: 'conferma', save: 'salva', edit: 'modifica', commit: 'sincronizza', continue: 'continua', prepare: 'prepara', connect: 'connetti', check: 'verifica', repair: 'ripara', execute: 'esegui', reject: 'rifiuta', restore: 'ripristina', generate: 'genera', modal: 'finestra', error: 'errore', keyword: 'parola chiave', mapping: 'mappatura', technical: 'tecnico', fix: 'correzione', execution: 'esecuzione', status: 'stato', image: 'immagine', alt: 'alt', text: 'testo', page: 'pagina', rows: 'righe', research: 'ricerca', business: 'business', profile: 'profilo', objectives: 'obiettivi', competition: 'competizione', quality: 'qualità', gate: 'controllo', tone: 'tono', voice: 'voce', content: 'contenuto', plan: 'piano', schema: 'schema', links: 'link', internal: 'interno', automation: 'automazione', manual: 'manuale', review: 'revisione' },
        pt: { start: 'iniciar', run: 'executar', refresh: 'atualizar', retry: 'tentar novamente', complete: 'finalizar', skip: 'ignorar', confirm: 'confirmar', save: 'salvar', edit: 'editar', commit: 'sincronizar', continue: 'continuar', prepare: 'preparar', connect: 'conectar', check: 'verificar', repair: 'reparar', execute: 'executar', reject: 'rejeitar', restore: 'restaurar', generate: 'gerar', modal: 'modal', error: 'erro', keyword: 'palavra-chave', mapping: 'mapeamento', technical: 'técnico', fix: 'correção', execution: 'execução', status: 'status', image: 'imagem', alt: 'alt', text: 'texto', page: 'página', rows: 'linhas', research: 'pesquisa', business: 'negócio', profile: 'perfil', objectives: 'objetivos', competition: 'concorrência', quality: 'qualidade', gate: 'controle', tone: 'tom', voice: 'voz', content: 'conteúdo', plan: 'plano', schema: 'schema', links: 'links', internal: 'interno', automation: 'automação', manual: 'manual', review: 'revisão' },
        nl: { start: 'starten', run: 'uitvoeren', refresh: 'verversen', retry: 'opnieuw proberen', complete: 'afronden', skip: 'overslaan', confirm: 'bevestigen', save: 'opslaan', edit: 'bewerken', commit: 'synchroniseren', continue: 'doorgaan', prepare: 'voorbereiden', connect: 'verbinden', check: 'controleren', repair: 'herstellen', execute: 'uitvoeren', reject: 'afwijzen', restore: 'herstellen', generate: 'genereren', modal: 'venster', error: 'fout', keyword: 'zoekwoord', mapping: 'mapping', technical: 'technisch', fix: 'correctie', execution: 'uitvoering', status: 'status', image: 'afbeelding', alt: 'alt', text: 'tekst', page: 'pagina', rows: 'rijen', research: 'onderzoek', business: 'bedrijf', profile: 'profiel', objectives: 'doelen', competition: 'concurrentie', quality: 'kwaliteit', gate: 'controle', tone: 'toon', voice: 'stem', content: 'inhoud', plan: 'plan', schema: 'schema', links: 'links', internal: 'intern', automation: 'automatisering', manual: 'handmatig', review: 'review' },
        pl: { start: 'uruchom', run: 'wykonaj', refresh: 'odśwież', retry: 'ponów', complete: 'zakończ', skip: 'pomiń', confirm: 'potwierdź', save: 'zapisz', edit: 'edytuj', commit: 'zsynchronizuj', continue: 'kontynuuj', prepare: 'przygotuj', connect: 'połącz', check: 'sprawdź', repair: 'napraw', execute: 'wykonaj', reject: 'odrzuć', restore: 'przywróć', generate: 'wygeneruj', modal: 'okno', error: 'błąd', keyword: 'słowo kluczowe', mapping: 'mapowanie', technical: 'techniczny', fix: 'poprawka', execution: 'wykonanie', status: 'status', image: 'obraz', alt: 'alt', text: 'tekst', page: 'strona', rows: 'wiersze', research: 'research', business: 'biznes', profile: 'profil', objectives: 'cele', competition: 'konkurencja', quality: 'jakość', gate: 'kontrola', tone: 'ton', voice: 'głos', content: 'treść', plan: 'plan', schema: 'schema', links: 'linki', internal: 'wewnętrzne', automation: 'automatyzacja', manual: 'manualne', review: 'review' },
        ar: { start: 'بدء', run: 'تشغيل', refresh: 'تحديث', retry: 'إعادة المحاولة', complete: 'إنهاء', skip: 'تخطي', confirm: 'تأكيد', save: 'حفظ', edit: 'تعديل', commit: 'مزامنة', continue: 'متابعة', prepare: 'تحضير', connect: 'اتصال', check: 'فحص', repair: 'إصلاح', execute: 'تنفيذ', reject: 'رفض', restore: 'استعادة', generate: 'إنشاء', modal: 'نافذة', error: 'خطأ', keyword: 'كلمة مفتاحية', mapping: 'ربط', technical: 'تقني', fix: 'تصحيح', execution: 'تنفيذ', status: 'حالة', image: 'صورة', alt: 'بديل', text: 'نص', page: 'صفحة', rows: 'صفوف', research: 'بحث', business: 'نشاط', profile: 'ملف', objectives: 'أهداف', competition: 'منافسة', quality: 'جودة', gate: 'فحص', tone: 'نبرة', voice: 'صوت', content: 'محتوى', plan: 'خطة', schema: 'schema', links: 'روابط', internal: 'داخلي', automation: 'أتمتة', manual: 'يدوي', review: 'مراجعة' }
    };

    function generatedLanguageValue(language, key, fallback) {
        const dictionary = ACTIVE_I18N_WORDS[language] || {};
        const tokens = String(key || '')
            .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
            .split(/[_\s-]+/)
            .map(function(token) { return token.toLowerCase(); })
            .filter(Boolean);
        if (tokens.length > 0) {
            const translated = tokens.map(function(token) {
                return dictionary[token] || token;
            }).join(' ');
            return translated.charAt(0).toUpperCase() + translated.slice(1);
        }
        return String(fallback || key || '');
    }

    function completeActiveLanguagePack(language) {
        const base = I18N.en || {};
        const existing = I18N[language] || {};
        const completion = ACTIVE_I18N_COMPLETIONS[language] || ACTIVE_I18N_ALIASES[language] || {};
        const completed = {};
        Object.keys(base).forEach(function(key) {
            completed[key] = completion[key] || existing[key] || generatedLanguageValue(language, key, base[key]);
        });
        I18N[language] = completed;
    }

    ['fr', 'de', 'es', 'it', 'pt', 'nl', 'pl', 'ar'].forEach(completeActiveLanguagePack);

    const FULL_I18N = {
        sq: {title:'AYSA Agent8',subtitle:'Sistem ekzekutimi determinist',active:'Aktiv',conversation:'Bisedë',execution:'Ekzekutim Agent8',waiting:'në pritje të gjendjes',placeholder:'Përshkruani detyrën për AYSA Agent 8...',authenticated:'I autentikuar',automatedSeo:'SEO e automatizuar',qaDiagnostics:'Diagnostikë QA',controls:'Kontrolle',runAll:'Ekzekuto të gjitha testet',runState:'Teste gjendjeje',runAction:'Teste veprimesh',runLlm:'Teste LLM',runInvalid:'Teste veprimesh të pavlefshme',runReset:'Test reset',runStress:'Stress test 15 min',stopStress:'Ndalo stress test',clearQa:'Pastro log QA',exportQa:'Eksporto log QA JSON',systemStatus:'Statusi i sistemit',currentPhase:'Faza aktuale',stateVersion:'Versioni i gjendjes',language:'Gjuha',apiStatus:'Status API',qaStorage:'Ruajtje QA',requestId:'Request ID',activeTest:'Test aktiv',name:'Emri',steps:'Hapa',result:'Rezultat',recentActions:'Veprime të fundit',noQaActions:'Nuk ka veprime QA',performance:'Performanca',avgResponse:'Përgjigje mesatare',throughput:'Throughput',errorRate:'Shkalla e gabimeve',canonicalState:'Gjendje kanonike',idle:'Joaktiv',approvalRequired:'Kërkohet miratim',approve:'Mirato',reject:'Refuzo',writesState:'shkruan gjendje: true',requiresApproval:'kërkon miratim: true',billableFalse:'i faturueshëm: false',start_architecture_test:'nis testin e arkitekturës',save_business_type:'ruaj tipin e biznesit',save_primary_goal:'ruaj objektivin kryesor',reset_lab:'reseto lab',send_lab_email:'dërgo email lab',planning:'Planifikim',executing:'Ekzekutim',completed:'përfunduar',running:'duke ekzekutuar',thinking:'duke menduar',failed:'dështoi'},
        hy: {title:'AYSA Agent8',subtitle:'Դետերմինիստական կատարման համակարգ',active:'Ակտիվ',conversation:'Զրույց',execution:'Agent8 կատարում',waiting:'սպասում է վիճակին',placeholder:'Նկարագրեք առաջադրանքը AYSA Agent 8-ի համար...',authenticated:'Նույնականացված',automatedSeo:'Ավտոմատացված SEO',qaDiagnostics:'QA ախտորոշում',controls:'Կառավարում',runAll:'Գործարկել բոլոր թեստերը',runState:'Վիճակի թեստեր',runAction:'Գործողությունների թեստեր',runLlm:'LLM թեստեր',runInvalid:'Անվավեր գործողությունների թեստեր',runReset:'Reset թեստ',runStress:'15 րոպե stress test',stopStress:'Կանգնեցնել stress test-ը',clearQa:'Մաքրել QA log-ը',exportQa:'Արտահանել QA log JSON',systemStatus:'Համակարգի վիճակ',currentPhase:'Ընթացիկ փուլ',stateVersion:'Վիճակի տարբերակ',language:'Լեզու',apiStatus:'API վիճակ',qaStorage:'QA պահեստ',requestId:'Request ID',activeTest:'Ակտիվ թեստ',name:'Անուն',steps:'Քայլեր',result:'Արդյունք',recentActions:'Վերջին գործողություններ',noQaActions:'QA գործողություններ չկան',performance:'Արդյունավետություն',avgResponse:'Միջին պատասխան',throughput:'Թողունակություն',errorRate:'Սխալի տոկոս',canonicalState:'Կանոնիկ վիճակ',idle:'Պասիվ',approvalRequired:'Պահանջվում է հաստատում',approve:'Հաստատել',reject:'Մերժել',writesState:'գրում է վիճակ: true',requiresApproval:'պահանջում է հաստատում: true',billableFalse:'վճարովի: false',start_architecture_test:'սկսել ճարտարապետության թեստը',save_business_type:'պահել բիզնեսի տեսակը',save_primary_goal:'պահել հիմնական նպատակը',reset_lab:'վերակայել lab-ը',send_lab_email:'ուղարկել lab email',planning:'Պլանավորում',executing:'Կատարում',completed:'ավարտված',running:'աշխատում է',thinking:'մտածում է',failed:'ձախողվեց'},
        az: {title:'AYSA Agent8',subtitle:'Deterministik icra sistemi',active:'Aktiv',conversation:'Söhbət',execution:'Agent8 icrası',waiting:'state gözlənilir',placeholder:'AYSA Agent 8 üçün tapşırığı təsvir edin...',authenticated:'Autentifikasiya olunub',automatedSeo:'Avtomatlaşdırılmış SEO',qaDiagnostics:'QA Diaqnostika',controls:'İdarəetmə',runAll:'Bütün testləri işə sal',runState:'State testləri',runAction:'Əməl testləri',runLlm:'LLM testləri',runInvalid:'Yanlış əməl testləri',runReset:'Reset testi',runStress:'15 dəq stress testi',stopStress:'Stress testini dayandır',clearQa:'QA logunu təmizlə',exportQa:'QA log JSON ixrac et',systemStatus:'Sistem statusu',currentPhase:'Cari mərhələ',stateVersion:'State versiyası',language:'Dil',apiStatus:'API statusu',qaStorage:'QA saxlanması',requestId:'Request ID',activeTest:'Aktiv test',name:'Ad',steps:'Addımlar',result:'Nəticə',recentActions:'Son əməliyyatlar',noQaActions:'QA əməliyyatı yoxdur',performance:'Performans',avgResponse:'Orta cavab',throughput:'Buraxılış',errorRate:'Xəta faizi',canonicalState:'Kanonik state',idle:'Boşda',approvalRequired:'Təsdiq tələb olunur',approve:'Təsdiqlə',reject:'Rədd et',writesState:'state yazır: true',requiresApproval:'təsdiq tələb edir: true',billableFalse:'ödənişli: false',start_architecture_test:'arxitektura testini başlat',save_business_type:'biznes tipini saxla',save_primary_goal:'əsas məqsədi saxla',reset_lab:'labı sıfırla',send_lab_email:'lab emaili göndər',planning:'Planlaşdırma',executing:'İcra',completed:'tamamlandı',running:'işləyir',thinking:'düşünür',failed:'uğursuz'},
        eu: {title:'AYSA Agent8',subtitle:'Exekuzio sistema determinista',active:'Aktibo',conversation:'Elkarrizketa',execution:'Agent8 exekuzioa',waiting:'egoeraren zain',placeholder:'Deskribatu AYSA Agent 8rentzako zeregina...',authenticated:'Autentifikatuta',automatedSeo:'SEO automatizatua',qaDiagnostics:'QA diagnostikoa',controls:'Kontrolak',runAll:'Exekutatu proba guztiak',runState:'Egoera probak',runAction:'Ekintza probak',runLlm:'LLM probak',runInvalid:'Ekintza baliogabeen probak',runReset:'Reset proba',runStress:'15 min stress test',stopStress:'Gelditu stress test',clearQa:'Garbitu QA loga',exportQa:'Esportatu QA log JSON',systemStatus:'Sistemaren egoera',currentPhase:'Uneko fasea',stateVersion:'Egoera bertsioa',language:'Hizkuntza',apiStatus:'API egoera',qaStorage:'QA biltegiratzea',requestId:'Request ID',activeTest:'Proba aktiboa',name:'Izena',steps:'Urratsak',result:'Emaitza',recentActions:'Azken ekintzak',noQaActions:'Ez dago QA ekintzarik',performance:'Errendimendua',avgResponse:'Batez besteko erantzuna',throughput:'Throughput',errorRate:'Errore tasa',canonicalState:'Egoera kanonikoa',idle:'Inaktibo',approvalRequired:'Onarpena behar da',approve:'Onartu',reject:'Baztertu',writesState:'egoera idazten du: true',requiresApproval:'onarpena behar du: true',billableFalse:'fakturagarria: false',start_architecture_test:'hasi arkitektura proba',save_business_type:'gorde negozio mota',save_primary_goal:'gorde helburu nagusia',reset_lab:'berrezarri lab',send_lab_email:'bidali lab emaila',planning:'Plangintza',executing:'Exekuzioa',completed:'amaituta',running:'martxan',thinking:'pentsatzen',failed:'huts egin du'},
        be: {title:'AYSA Agent8',subtitle:'Дэтэрмінаваная сістэма выканання',active:'Актыўны',conversation:'Размова',execution:'Выкананне Agent8',waiting:'чаканне стану',placeholder:'Апiшыце задачу для AYSA Agent 8...',authenticated:'Аўтэнтыфікавана',automatedSeo:'Аўтаматызаванае SEO',qaDiagnostics:'QA дыягностыка',controls:'Кіраванне',runAll:'Запусціць усе тэсты',runState:'Тэсты стану',runAction:'Тэсты дзеянняў',runLlm:'LLM тэсты',runInvalid:'Тэсты няправільных дзеянняў',runReset:'Reset тэст',runStress:'15-хвілінны stress test',stopStress:'Спыніць stress test',clearQa:'Ачысціць QA log',exportQa:'Экспартаваць QA log JSON',systemStatus:'Стан сістэмы',currentPhase:'Бягучая фаза',stateVersion:'Версія стану',language:'Мова',apiStatus:'API статус',qaStorage:'QA сховішча',requestId:'Request ID',activeTest:'Актыўны тэст',name:'Назва',steps:'Крокі',result:'Вынік',recentActions:'Апошнія дзеянні',noQaActions:'QA дзеянняў няма',performance:'Прадукцыйнасць',avgResponse:'Сярэдні адказ',throughput:'Прапускная здольнасць',errorRate:'Працэнт памылак',canonicalState:'Кананічны стан',idle:'Неактыўны',approvalRequired:'Патрабуецца зацвярджэнне',approve:'Зацвердзіць',reject:'Адхіліць',writesState:'піша стан: true',requiresApproval:'патрабуе зацвярджэння: true',billableFalse:'аплатна: false',start_architecture_test:'запусціць тэст архітэктуры',save_business_type:'захаваць тып бізнесу',save_primary_goal:'захаваць галоўную мэту',reset_lab:'скінуць lab',send_lab_email:'адправіць lab email',planning:'Планаванне',executing:'Выкананне',completed:'завершана',running:'выконваецца',thinking:'думае',failed:'памылка'},
        bs: {title:'AYSA Agent8',subtitle:'Deterministički sistem izvršavanja',active:'Aktivan',conversation:'Razgovor',execution:'Agent8 izvršavanje',waiting:'čeka stanje',placeholder:'Opišite zadatak za AYSA Agent 8...',authenticated:'Autentificiran',automatedSeo:'Automatizirani SEO',qaDiagnostics:'QA dijagnostika',controls:'Kontrole',runAll:'Pokreni sve testove',runState:'Testovi stanja',runAction:'Testovi akcija',runLlm:'LLM testovi',runInvalid:'Testovi nevažećih akcija',runReset:'Reset test',runStress:'15 min stress test',stopStress:'Zaustavi stress test',clearQa:'Očisti QA log',exportQa:'Izvezi QA log JSON',systemStatus:'Status sistema',currentPhase:'Trenutna faza',stateVersion:'Verzija stanja',language:'Jezik',apiStatus:'API status',qaStorage:'QA pohrana',requestId:'Request ID',activeTest:'Aktivni test',name:'Naziv',steps:'Koraci',result:'Rezultat',recentActions:'Nedavne akcije',noQaActions:'Nema QA akcija',performance:'Performanse',avgResponse:'Prosječan odgovor',throughput:'Propusnost',errorRate:'Stopa grešaka',canonicalState:'Kanonsko stanje',idle:'Neaktivan',approvalRequired:'Potrebno odobrenje',approve:'Odobri',reject:'Odbij',writesState:'piše stanje: true',requiresApproval:'zahtijeva odobrenje: true',billableFalse:'naplativo: false',start_architecture_test:'pokreni test arhitekture',save_business_type:'sačuvaj tip biznisa',save_primary_goal:'sačuvaj glavni cilj',reset_lab:'resetuj lab',send_lab_email:'pošalji lab email',planning:'Planiranje',executing:'Izvršavanje',completed:'završeno',running:'radi',thinking:'razmišlja',failed:'neuspješno'},
        bg: {title:'AYSA Agent8',subtitle:'Детерминистична система за изпълнение',active:'Активен',conversation:'Разговор',execution:'Изпълнение Agent8',waiting:'изчаква състояние',placeholder:'Опишете задачата за AYSA Agent 8...',authenticated:'Удостоверен',automatedSeo:'Автоматизирано SEO',qaDiagnostics:'QA диагностика',controls:'Контроли',runAll:'Стартирай всички тестове',runState:'Тестове на състояние',runAction:'Тестове на действия',runLlm:'LLM тестове',runInvalid:'Тестове на невалидни действия',runReset:'Reset тест',runStress:'15 мин stress test',stopStress:'Спри stress test',clearQa:'Изчисти QA log',exportQa:'Експорт QA log JSON',systemStatus:'Статус на системата',currentPhase:'Текуща фаза',stateVersion:'Версия на състояние',language:'Език',apiStatus:'API статус',qaStorage:'QA съхранение',requestId:'Request ID',activeTest:'Активен тест',name:'Име',steps:'Стъпки',result:'Резултат',recentActions:'Последни действия',noQaActions:'Няма QA действия',performance:'Производителност',avgResponse:'Среден отговор',throughput:'Пропускателност',errorRate:'Процент грешки',canonicalState:'Канонично състояние',idle:'Неактивен',approvalRequired:'Изисква одобрение',approve:'Одобри',reject:'Отхвърли',writesState:'записва състояние: true',requiresApproval:'изисква одобрение: true',billableFalse:'платимо: false',start_architecture_test:'стартирай архитектурен тест',save_business_type:'запази тип бизнес',save_primary_goal:'запази основна цел',reset_lab:'нулирай lab',send_lab_email:'изпрати lab email',planning:'Планиране',executing:'Изпълнение',completed:'завършено',running:'работи',thinking:'мисли',failed:'неуспешно'},
        ca: {title:'AYSA Agent8',subtitle:'Sistema d’execució determinista',active:'Actiu',conversation:'Conversa',execution:'Execució Agent8',waiting:'esperant estat',placeholder:'Descriu la tasca per a AYSA Agent 8...',authenticated:'Autenticat',automatedSeo:'SEO automatitzat',qaDiagnostics:'Diagnòstic QA',controls:'Controls',runAll:'Executa totes les proves',runState:'Proves d’estat',runAction:'Proves d’accions',runLlm:'Proves LLM',runInvalid:'Proves d’accions invàlides',runReset:'Prova reset',runStress:'Stress test 15 min',stopStress:'Atura stress test',clearQa:'Neteja log QA',exportQa:'Exporta log QA JSON',systemStatus:'Estat del sistema',currentPhase:'Fase actual',stateVersion:'Versió d’estat',language:'Idioma',apiStatus:'Estat API',qaStorage:'Emmagatzematge QA',requestId:'Request ID',activeTest:'Prova activa',name:'Nom',steps:'Passos',result:'Resultat',recentActions:'Accions recents',noQaActions:'No hi ha accions QA',performance:'Rendiment',avgResponse:'Resposta mitjana',throughput:'Throughput',errorRate:'Taxa d’error',canonicalState:'Estat canònic',idle:'Inactiu',approvalRequired:'Requereix aprovació',approve:'Aprova',reject:'Rebutja',writesState:'escriu estat: true',requiresApproval:'requereix aprovació: true',billableFalse:'facturable: false',start_architecture_test:'inicia prova d’arquitectura',save_business_type:'desa tipus de negoci',save_primary_goal:'desa objectiu principal',reset_lab:'reinicia lab',send_lab_email:'envia email lab',planning:'Planificació',executing:'Execució',completed:'completat',running:'executant',thinking:'pensant',failed:'fallit'},
        hr: {title:'AYSA Agent8',subtitle:'Deterministički sustav izvršavanja',active:'Aktivan',conversation:'Razgovor',execution:'Izvršavanje Agent8',waiting:'čeka stanje',placeholder:'Opišite zadatak za AYSA Agent 8...',authenticated:'Autenticirano',automatedSeo:'Automatizirani SEO',qaDiagnostics:'QA dijagnostika',controls:'Kontrole',runAll:'Pokreni sve testove',runState:'Testovi stanja',runAction:'Testovi akcija',runLlm:'LLM testovi',runInvalid:'Testovi nevažećih akcija',runReset:'Reset test',runStress:'15 min stress test',stopStress:'Zaustavi stress test',clearQa:'Očisti QA log',exportQa:'Izvezi QA log JSON',systemStatus:'Status sustava',currentPhase:'Trenutna faza',stateVersion:'Verzija stanja',language:'Jezik',apiStatus:'API status',qaStorage:'QA pohrana',requestId:'Request ID',activeTest:'Aktivni test',name:'Naziv',steps:'Koraci',result:'Rezultat',recentActions:'Nedavne akcije',noQaActions:'Nema QA akcija',performance:'Performanse',avgResponse:'Prosječan odgovor',throughput:'Propusnost',errorRate:'Stopa grešaka',canonicalState:'Kanonsko stanje',idle:'Neaktivan',approvalRequired:'Potrebno odobrenje',approve:'Odobri',reject:'Odbij',writesState:'piše stanje: true',requiresApproval:'zahtijeva odobrenje: true',billableFalse:'naplativo: false',start_architecture_test:'pokreni test arhitekture',save_business_type:'spremi tip poslovanja',save_primary_goal:'spremi glavni cilj',reset_lab:'resetiraj lab',send_lab_email:'pošalji lab email',planning:'Planiranje',executing:'Izvršavanje',completed:'dovršeno',running:'radi',thinking:'razmišlja',failed:'neuspjelo'},
        cs: {title:'AYSA Agent8',subtitle:'Deterministický systém spouštění',active:'Aktivní',conversation:'Konverzace',execution:'Spuštění Agent8',waiting:'čeká na stav',placeholder:'Popište úkol pro AYSA Agent 8...',authenticated:'Ověřeno',automatedSeo:'Automatizované SEO',qaDiagnostics:'QA diagnostika',controls:'Ovládání',runAll:'Spustit všechny testy',runState:'Testy stavu',runAction:'Testy akcí',runLlm:'LLM testy',runInvalid:'Testy neplatných akcí',runReset:'Reset test',runStress:'15min stress test',stopStress:'Zastavit stress test',clearQa:'Vymazat QA log',exportQa:'Exportovat QA log JSON',systemStatus:'Stav systému',currentPhase:'Aktuální fáze',stateVersion:'Verze stavu',language:'Jazyk',apiStatus:'API stav',qaStorage:'QA úložiště',requestId:'Request ID',activeTest:'Aktivní test',name:'Název',steps:'Kroky',result:'Výsledek',recentActions:'Nedávné akce',noQaActions:'Žádné QA akce',performance:'Výkon',avgResponse:'Průměrná odpověď',throughput:'Propustnost',errorRate:'Chybovost',canonicalState:'Kanonický stav',idle:'Nečinný',approvalRequired:'Vyžaduje schválení',approve:'Schválit',reject:'Odmítnout',writesState:'zapisuje stav: true',requiresApproval:'vyžaduje schválení: true',billableFalse:'účtovatelné: false',start_architecture_test:'spustit test architektury',save_business_type:'uložit typ podnikání',save_primary_goal:'uložit hlavní cíl',reset_lab:'resetovat lab',send_lab_email:'odeslat lab email',planning:'Plánování',executing:'Spouštění',completed:'dokončeno',running:'běží',thinking:'přemýšlí',failed:'selhalo'},
        da: {title:'AYSA Agent8',subtitle:'Deterministisk eksekveringssystem',active:'Aktiv',conversation:'Samtale',execution:'Agent8 eksekvering',waiting:'venter på tilstand',placeholder:'Beskriv opgaven for AYSA Agent 8...',authenticated:'Godkendt',automatedSeo:'Automatiseret SEO',qaDiagnostics:'QA-diagnostik',controls:'Kontroller',runAll:'Kør alle tests',runState:'Tilstandstests',runAction:'Handlingstests',runLlm:'LLM-tests',runInvalid:'Ugyldige handlingstests',runReset:'Reset-test',runStress:'15 min stresstest',stopStress:'Stop stresstest',clearQa:'Ryd QA-log',exportQa:'Eksporter QA-log JSON',systemStatus:'Systemstatus',currentPhase:'Aktuel fase',stateVersion:'Tilstandsversion',language:'Sprog',apiStatus:'API-status',qaStorage:'QA-lager',requestId:'Request ID',activeTest:'Aktiv test',name:'Navn',steps:'Trin',result:'Resultat',recentActions:'Seneste handlinger',noQaActions:'Ingen QA-handlinger',performance:'Ydeevne',avgResponse:'Gns. svar',throughput:'Gennemløb',errorRate:'Fejlrate',canonicalState:'Kanonisk tilstand',idle:'Inaktiv',approvalRequired:'Godkendelse kræves',approve:'Godkend',reject:'Afvis',writesState:'skriver tilstand: true',requiresApproval:'kræver godkendelse: true',billableFalse:'fakturerbar: false',start_architecture_test:'start arkitekturtest',save_business_type:'gem virksomhedstype',save_primary_goal:'gem primært mål',reset_lab:'nulstil lab',send_lab_email:'send lab email',planning:'Planlægning',executing:'Eksekvering',completed:'fuldført',running:'kører',thinking:'tænker',failed:'fejlet'}
    };

    $.extend(I18N, FULL_I18N);

    $.extend(I18N, {
        es: $.extend({}, I18N.es, {runAll:'Ejecutar todas las pruebas',runState:'Pruebas de estado',runAction:'Pruebas de acciones',runLlm:'Pruebas LLM',runInvalid:'Pruebas de acciones inválidas',runReset:'Prueba de reset',runStress:'Stress test 15 min',stopStress:'Detener stress test',clearQa:'Limpiar log QA',exportQa:'Exportar log QA JSON',qaStorage:'Almacenamiento QA',requestId:'Request ID',name:'Nombre',steps:'Pasos',result:'Resultado',noQaActions:'No hay acciones QA',avgResponse:'Respuesta media',throughput:'Rendimiento',errorRate:'Tasa de error',writesState:'escribe estado: true',requiresApproval:'requiere aprobación: true',billableFalse:'facturable: false',start_architecture_test:'iniciar prueba de arquitectura',save_business_type:'guardar tipo de negocio',save_primary_goal:'guardar objetivo principal',reset_lab:'reiniciar lab',send_lab_email:'enviar email lab',planning:'Planificación',executing:'Ejecución',completed:'completado',running:'ejecutando',thinking:'pensando',failed:'fallido'}),
        it: $.extend({}, I18N.it, {runAll:'Esegui tutti i test',runState:'Test di stato',runAction:'Test azioni',runLlm:'Test LLM',runInvalid:'Test azioni non valide',runReset:'Test reset',runStress:'Stress test 15 min',stopStress:'Ferma stress test',clearQa:'Pulisci log QA',exportQa:'Esporta log QA JSON',qaStorage:'Archiviazione QA',requestId:'Request ID',name:'Nome',steps:'Passi',result:'Risultato',noQaActions:'Nessuna azione QA',avgResponse:'Risposta media',throughput:'Throughput',errorRate:'Tasso errori',writesState:'scrive stato: true',requiresApproval:'richiede approvazione: true',billableFalse:'fatturabile: false',start_architecture_test:'avvia test architettura',save_business_type:'salva tipo business',save_primary_goal:'salva obiettivo principale',reset_lab:'resetta lab',send_lab_email:'invia email lab',planning:'Pianificazione',executing:'Esecuzione',completed:'completato',running:'in esecuzione',thinking:'elaborazione',failed:'fallito'}),
        pt: $.extend({}, I18N.pt, {runAll:'Executar todos os testes',runState:'Testes de estado',runAction:'Testes de ações',runLlm:'Testes LLM',runInvalid:'Testes de ações inválidas',runReset:'Teste reset',runStress:'Stress test 15 min',stopStress:'Parar stress test',clearQa:'Limpar log QA',exportQa:'Exportar log QA JSON',qaStorage:'Armazenamento QA',requestId:'Request ID',name:'Nome',steps:'Passos',result:'Resultado',noQaActions:'Sem ações QA',avgResponse:'Resposta média',throughput:'Throughput',errorRate:'Taxa de erro',writesState:'escreve estado: true',requiresApproval:'requer aprovação: true',billableFalse:'cobrável: false',start_architecture_test:'iniciar teste de arquitetura',save_business_type:'guardar tipo de negócio',save_primary_goal:'guardar objetivo principal',reset_lab:'reiniciar lab',send_lab_email:'enviar email lab',planning:'Planejamento',executing:'Execução',completed:'concluído',running:'em execução',thinking:'pensando',failed:'falhou'}),
        nl: $.extend({}, I18N.nl, {runAll:'Alle tests uitvoeren',runState:'Statustests',runAction:'Actietests',runLlm:'LLM-tests',runInvalid:'Ongeldige acties testen',runReset:'Resettest',runStress:'15 min stresstest',stopStress:'Stresstest stoppen',clearQa:'QA-log wissen',exportQa:'QA-log JSON exporteren',qaStorage:'QA-opslag',requestId:'Request ID',name:'Naam',steps:'Stappen',result:'Resultaat',noQaActions:'Geen QA-acties',avgResponse:'Gem. antwoord',throughput:'Doorvoer',errorRate:'Foutpercentage',writesState:'schrijft status: true',requiresApproval:'vereist goedkeuring: true',billableFalse:'factureerbaar: false',start_architecture_test:'architectuurtest starten',save_business_type:'bedrijfstype opslaan',save_primary_goal:'hoofddoel opslaan',reset_lab:'lab resetten',send_lab_email:'lab e-mail verzenden',planning:'Planning',executing:'Uitvoering',completed:'voltooid',running:'actief',thinking:'denkt',failed:'mislukt'}),
        pl: $.extend({}, I18N.pl, {runAll:'Uruchom wszystkie testy',runState:'Testy stanu',runAction:'Testy akcji',runLlm:'Testy LLM',runInvalid:'Testy błędnych akcji',runReset:'Test reset',runStress:'Stress test 15 min',stopStress:'Zatrzymaj stress test',clearQa:'Wyczyść log QA',exportQa:'Eksportuj log QA JSON',qaStorage:'Magazyn QA',requestId:'Request ID',name:'Nazwa',steps:'Kroki',result:'Wynik',noQaActions:'Brak akcji QA',avgResponse:'Średnia odpowiedź',throughput:'Przepustowość',errorRate:'Wskaźnik błędów',writesState:'zapisuje stan: true',requiresApproval:'wymaga zatwierdzenia: true',billableFalse:'płatne: false',start_architecture_test:'uruchom test architektury',save_business_type:'zapisz typ biznesu',save_primary_goal:'zapisz główny cel',reset_lab:'zresetuj lab',send_lab_email:'wyślij email lab',planning:'Planowanie',executing:'Wykonanie',completed:'ukończono',running:'działa',thinking:'myśli',failed:'niepowodzenie'}),
        et: {title:'AYSA Agent8',subtitle:'Deterministlik täitmissüsteem',active:'Aktiivne',conversation:'Vestlus',execution:'Agent8 täitmine',waiting:'ootab olekut',placeholder:'Kirjelda ülesannet AYSA Agent 8 jaoks...',authenticated:'Autenditud',automatedSeo:'Automatiseeritud SEO',qaDiagnostics:'QA diagnostika',controls:'Juhtnupud',runAll:'Käivita kõik testid',runState:'Oleku testid',runAction:'Toimingute testid',runLlm:'LLM testid',runInvalid:'Vigaste toimingute testid',runReset:'Reset test',runStress:'15 min stress test',stopStress:'Peata stress test',clearQa:'Tühjenda QA logi',exportQa:'Ekspordi QA log JSON',systemStatus:'Süsteemi olek',currentPhase:'Praegune faas',stateVersion:'Oleku versioon',language:'Keel',apiStatus:'API olek',qaStorage:'QA salvestus',requestId:'Request ID',activeTest:'Aktiivne test',name:'Nimi',steps:'Sammud',result:'Tulemus',recentActions:'Hiljutised toimingud',noQaActions:'QA toiminguid pole',performance:'Jõudlus',avgResponse:'Keskmine vastus',throughput:'Läbilase',errorRate:'Veamäär',canonicalState:'Kanooniline olek',idle:'Jõude',approvalRequired:'Vajab kinnitust',approve:'Kinnita',reject:'Lükka tagasi',writesState:'kirjutab olekut: true',requiresApproval:'vajab kinnitust: true',billableFalse:'arveldatav: false',start_architecture_test:'käivita arhitektuuri test',save_business_type:'salvesta äritüüp',save_primary_goal:'salvesta peamine eesmärk',reset_lab:'lähtesta lab',send_lab_email:'saada lab email',planning:'Planeerimine',executing:'Täitmine',completed:'lõpetatud',running:'töötab',thinking:'mõtleb',failed:'ebaõnnestus'},
        fi: {title:'AYSA Agent8',subtitle:'Deterministinen suoritusjärjestelmä',active:'Aktiivinen',conversation:'Keskustelu',execution:'Agent8 suoritus',waiting:'odottaa tilaa',placeholder:'Kuvaile tehtävä AYSA Agent 8:lle...',authenticated:'Tunnistettu',automatedSeo:'Automatisoitu SEO',qaDiagnostics:'QA-diagnostiikka',controls:'Ohjaimet',runAll:'Suorita kaikki testit',runState:'Tilatestit',runAction:'Toimintotestit',runLlm:'LLM-testit',runInvalid:'Virheellisten toimintojen testit',runReset:'Reset-testi',runStress:'15 min stressitesti',stopStress:'Pysäytä stressitesti',clearQa:'Tyhjennä QA-loki',exportQa:'Vie QA-loki JSON',systemStatus:'Järjestelmän tila',currentPhase:'Nykyinen vaihe',stateVersion:'Tilan versio',language:'Kieli',apiStatus:'API-tila',qaStorage:'QA-tallennus',requestId:'Request ID',activeTest:'Aktiivinen testi',name:'Nimi',steps:'Vaiheet',result:'Tulos',recentActions:'Viimeisimmät toiminnot',noQaActions:'Ei QA-toimintoja',performance:'Suorituskyky',avgResponse:'Keskimääräinen vastaus',throughput:'Läpimeno',errorRate:'Virheprosentti',canonicalState:'Kanoninen tila',idle:'Jouten',approvalRequired:'Hyväksyntä vaaditaan',approve:'Hyväksy',reject:'Hylkää',writesState:'kirjoittaa tilaa: true',requiresApproval:'vaatii hyväksynnän: true',billableFalse:'laskutettava: false',start_architecture_test:'käynnistä arkkitehtuuritesti',save_business_type:'tallenna liiketoimintatyyppi',save_primary_goal:'tallenna päätavoite',reset_lab:'nollaa lab',send_lab_email:'lähetä lab-sähköposti',planning:'Suunnittelu',executing:'Suoritus',completed:'valmis',running:'käynnissä',thinking:'ajattelee',failed:'epäonnistui'},
        gl: {title:'AYSA Agent8',subtitle:'Sistema de execución determinista',active:'Activo',conversation:'Conversa',execution:'Execución Agent8',waiting:'agardando estado',placeholder:'Describe a tarefa para AYSA Agent 8...',authenticated:'Autenticado',automatedSeo:'SEO automatizado',qaDiagnostics:'Diagnóstico QA',controls:'Controis',runAll:'Executar todas as probas',runState:'Probas de estado',runAction:'Probas de accións',runLlm:'Probas LLM',runInvalid:'Probas de accións inválidas',runReset:'Proba reset',runStress:'Stress test 15 min',stopStress:'Deter stress test',clearQa:'Limpar log QA',exportQa:'Exportar log QA JSON',systemStatus:'Estado do sistema',currentPhase:'Fase actual',stateVersion:'Versión de estado',language:'Idioma',apiStatus:'Estado API',qaStorage:'Almacenamento QA',requestId:'Request ID',activeTest:'Proba activa',name:'Nome',steps:'Pasos',result:'Resultado',recentActions:'Accións recentes',noQaActions:'Non hai accións QA',performance:'Rendemento',avgResponse:'Resposta media',throughput:'Throughput',errorRate:'Taxa de erro',canonicalState:'Estado canónico',idle:'Inactivo',approvalRequired:'Require aprobación',approve:'Aprobar',reject:'Rexeitar',writesState:'escribe estado: true',requiresApproval:'require aprobación: true',billableFalse:'facturable: false',start_architecture_test:'iniciar proba de arquitectura',save_business_type:'gardar tipo de negocio',save_primary_goal:'gardar obxectivo principal',reset_lab:'reiniciar lab',send_lab_email:'enviar email lab',planning:'Planificación',executing:'Execución',completed:'completado',running:'executando',thinking:'pensando',failed:'fallou'},
        ka: {title:'AYSA Agent8',subtitle:'დეტერმინისტული შესრულების სისტემა',active:'აქტიური',conversation:'საუბარი',execution:'Agent8 შესრულება',waiting:'ელოდება მდგომარეობას',placeholder:'აღწერეთ დავალება AYSA Agent 8-სთვის...',authenticated:'ავტორიზებულია',automatedSeo:'ავტომატიზებული SEO',qaDiagnostics:'QA დიაგნოსტიკა',controls:'მართვა',runAll:'ყველა ტესტის გაშვება',runState:'მდგომარეობის ტესტები',runAction:'ქმედებების ტესტები',runLlm:'LLM ტესტები',runInvalid:'არასწორი ქმედებების ტესტები',runReset:'Reset ტესტი',runStress:'15 წთ stress test',stopStress:'Stress test-ის შეჩერება',clearQa:'QA ლოგის გასუფთავება',exportQa:'QA log JSON ექსპორტი',systemStatus:'სისტემის სტატუსი',currentPhase:'მიმდინარე ფაზა',stateVersion:'მდგომარეობის ვერსია',language:'ენა',apiStatus:'API სტატუსი',qaStorage:'QA შენახვა',requestId:'Request ID',activeTest:'აქტიური ტესტი',name:'სახელი',steps:'ნაბიჯები',result:'შედეგი',recentActions:'ბოლო ქმედებები',noQaActions:'QA ქმედებები არ არის',performance:'წარმადობა',avgResponse:'საშუალო პასუხი',throughput:'გამტარობა',errorRate:'შეცდომის მაჩვენებელი',canonicalState:'კანონიკური მდგომარეობა',idle:'უმოქმედო',approvalRequired:'საჭიროა დამტკიცება',approve:'დამტკიცება',reject:'უარყოფა',writesState:'წერს მდგომარეობას: true',requiresApproval:'ითხოვს დამტკიცებას: true',billableFalse:'ფასიანი: false',start_architecture_test:'არქიტექტურის ტესტის დაწყება',save_business_type:'ბიზნეს ტიპის შენახვა',save_primary_goal:'მთავარი მიზნის შენახვა',reset_lab:'lab-ის reset',send_lab_email:'lab email-ის გაგზავნა',planning:'დაგეგმვა',executing:'შესრულება',completed:'დასრულდა',running:'მუშაობს',thinking:'ფიქრობს',failed:'ვერ შესრულდა'}
    });

    $.extend(I18N, {
        el: {title:'AYSA Agent8',subtitle:'Ντετερμινιστικό σύστημα εκτέλεσης',active:'Ενεργό',conversation:'Συνομιλία',execution:'Εκτέλεση Agent8',waiting:'αναμονή κατάστασης',placeholder:'Περιγράψτε την εργασία για το AYSA Agent 8...',authenticated:'Πιστοποιημένο',automatedSeo:'Αυτοματοποιημένο SEO',qaDiagnostics:'QA διαγνωστικά',controls:'Έλεγχοι',runAll:'Εκτέλεση όλων των τεστ',runState:'Τεστ κατάστασης',runAction:'Τεστ ενεργειών',runLlm:'Τεστ LLM',runInvalid:'Τεστ άκυρων ενεργειών',runReset:'Τεστ reset',runStress:'Stress test 15 λεπτά',stopStress:'Διακοπή stress test',clearQa:'Καθαρισμός QA log',exportQa:'Εξαγωγή QA log JSON',systemStatus:'Κατάσταση συστήματος',currentPhase:'Τρέχουσα φάση',stateVersion:'Έκδοση κατάστασης',language:'Γλώσσα',apiStatus:'Κατάσταση API',qaStorage:'Αποθήκευση QA',requestId:'Request ID',activeTest:'Ενεργό τεστ',name:'Όνομα',steps:'Βήματα',result:'Αποτέλεσμα',recentActions:'Πρόσφατες ενέργειες',noQaActions:'Δεν υπάρχουν QA ενέργειες',performance:'Απόδοση',avgResponse:'Μέση απόκριση',throughput:'Ρυθμός',errorRate:'Ποσοστό σφαλμάτων',canonicalState:'Κανονική κατάσταση',idle:'Ανενεργό',approvalRequired:'Απαιτείται έγκριση',approve:'Έγκριση',reject:'Απόρριψη',writesState:'γράφει κατάσταση: true',requiresApproval:'απαιτεί έγκριση: true',billableFalse:'χρεώσιμο: false',start_architecture_test:'έναρξη τεστ αρχιτεκτονικής',save_business_type:'αποθήκευση τύπου επιχείρησης',save_primary_goal:'αποθήκευση κύριου στόχου',reset_lab:'reset lab',send_lab_email:'αποστολή lab email',planning:'Σχεδιασμός',executing:'Εκτέλεση',completed:'ολοκληρώθηκε',running:'τρέχει',thinking:'σκέφτεται',failed:'απέτυχε'},
        hu: {title:'AYSA Agent8',subtitle:'Determinisztikus végrehajtási rendszer',active:'Aktív',conversation:'Beszélgetés',execution:'Agent8 végrehajtás',waiting:'állapotra vár',placeholder:'Írd le a feladatot az AYSA Agent 8 számára...',authenticated:'Hitelesítve',automatedSeo:'Automatizált SEO',qaDiagnostics:'QA diagnosztika',controls:'Vezérlés',runAll:'Összes teszt futtatása',runState:'Állapotteszt',runAction:'Akcióteszt',runLlm:'LLM teszt',runInvalid:'Érvénytelen akciók tesztje',runReset:'Reset teszt',runStress:'15 perces stresszteszt',stopStress:'Stresszteszt leállítása',clearQa:'QA napló törlése',exportQa:'QA napló JSON export',systemStatus:'Rendszerállapot',currentPhase:'Aktuális fázis',stateVersion:'Állapotverzió',language:'Nyelv',apiStatus:'API állapot',qaStorage:'QA tárhely',requestId:'Request ID',activeTest:'Aktív teszt',name:'Név',steps:'Lépések',result:'Eredmény',recentActions:'Legutóbbi akciók',noQaActions:'Nincs QA akció',performance:'Teljesítmény',avgResponse:'Átlag válasz',throughput:'Áteresztés',errorRate:'Hibaarány',canonicalState:'Kanonikus állapot',idle:'Inaktív',approvalRequired:'Jóváhagyás szükséges',approve:'Jóváhagyás',reject:'Elutasítás',writesState:'állapotot ír: true',requiresApproval:'jóváhagyást igényel: true',billableFalse:'számlázható: false',start_architecture_test:'architektúra teszt indítása',save_business_type:'üzlettípus mentése',save_primary_goal:'fő cél mentése',reset_lab:'lab visszaállítása',send_lab_email:'lab email küldése',planning:'Tervezés',executing:'Végrehajtás',completed:'befejezve',running:'fut',thinking:'gondolkodik',failed:'sikertelen'},
        is: {title:'AYSA Agent8',subtitle:'Ákveðið keyrslukerfi',active:'Virkt',conversation:'Samtal',execution:'Agent8 keyrsla',waiting:'bíður eftir stöðu',placeholder:'Lýstu verkefninu fyrir AYSA Agent 8...',authenticated:'Auðkennt',automatedSeo:'Sjálfvirkt SEO',qaDiagnostics:'QA greining',controls:'Stýringar',runAll:'Keyra öll próf',runState:'Stöðupróf',runAction:'Aðgerðapróf',runLlm:'LLM próf',runInvalid:'Ógild aðgerðapróf',runReset:'Reset próf',runStress:'15 mín stress test',stopStress:'Stöðva stress test',clearQa:'Hreinsa QA log',exportQa:'Flytja út QA log JSON',systemStatus:'Kerfisstaða',currentPhase:'Núverandi fasi',stateVersion:'Stöðuútgáfa',language:'Tungumál',apiStatus:'API staða',qaStorage:'QA geymsla',requestId:'Request ID',activeTest:'Virkt próf',name:'Nafn',steps:'Skref',result:'Niðurstaða',recentActions:'Nýlegar aðgerðir',noQaActions:'Engar QA aðgerðir',performance:'Afköst',avgResponse:'Meðalsvar',throughput:'Afköst',errorRate:'Villuhlutfall',canonicalState:'Kanonísk staða',idle:'Óvirkt',approvalRequired:'Samþykki krafist',approve:'Samþykkja',reject:'Hafna',writesState:'skrifar stöðu: true',requiresApproval:'krefst samþykkis: true',billableFalse:'gjaldskylt: false',start_architecture_test:'ræsa arkitektúrpróf',save_business_type:'vista tegund fyrirtækis',save_primary_goal:'vista aðalmarkmið',reset_lab:'endurstilla lab',send_lab_email:'senda lab email',planning:'Áætlun',executing:'Keyrsla',completed:'lokið',running:'keyrir',thinking:'hugsar',failed:'mistókst'},
        ga: {title:'AYSA Agent8',subtitle:'Córas forghníomhaithe cinntitheach',active:'Gníomhach',conversation:'Comhrá',execution:'Forghníomhú Agent8',waiting:'ag fanacht le staid',placeholder:'Déan cur síos ar an tasc do AYSA Agent 8...',authenticated:'Fíordheimhnithe',automatedSeo:'SEO uathoibrithe',qaDiagnostics:'Diagnóis QA',controls:'Rialuithe',runAll:'Rith gach tástáil',runState:'Tástálacha staid',runAction:'Tástálacha gnímh',runLlm:'Tástálacha LLM',runInvalid:'Tástálacha gnímh neamhbhailí',runReset:'Tástáil reset',runStress:'Stress test 15 nóim',stopStress:'Stop stress test',clearQa:'Glan log QA',exportQa:'Easpórtáil log QA JSON',systemStatus:'Stádas córais',currentPhase:'Céim reatha',stateVersion:'Leagan staid',language:'Teanga',apiStatus:'Stádas API',qaStorage:'Stóráil QA',requestId:'Request ID',activeTest:'Tástáil ghníomhach',name:'Ainm',steps:'Céimeanna',result:'Toradh',recentActions:'Gníomhartha le déanaí',noQaActions:'Níl gníomhartha QA ann',performance:'Feidhmíocht',avgResponse:'Meánfhreagra',throughput:'Tréchur',errorRate:'Ráta earráide',canonicalState:'Staid chanónach',idle:'Díomhaoin',approvalRequired:'Ceadú riachtanach',approve:'Ceadaigh',reject:'Diúltaigh',writesState:'scríobhann staid: true',requiresApproval:'éilíonn ceadú: true',billableFalse:'inmhuirir: false',start_architecture_test:'tosaigh tástáil ailtireachta',save_business_type:'sábháil cineál gnó',save_primary_goal:'sábháil príomhsprioc',reset_lab:'athshocraigh lab',send_lab_email:'seol email lab',planning:'Pleanáil',executing:'Forghníomhú',completed:'críochnaithe',running:'ag rith',thinking:'ag smaoineamh',failed:'theip'},
        lv: {title:'AYSA Agent8',subtitle:'Deterministiska izpildes sistēma',active:'Aktīvs',conversation:'Saruna',execution:'Agent8 izpilde',waiting:'gaida stāvokli',placeholder:'Aprakstiet uzdevumu AYSA Agent 8...',authenticated:'Autentificēts',automatedSeo:'Automatizēts SEO',qaDiagnostics:'QA diagnostika',controls:'Vadība',runAll:'Palaist visus testus',runState:'Stāvokļa testi',runAction:'Darbību testi',runLlm:'LLM testi',runInvalid:'Nederīgu darbību testi',runReset:'Reset tests',runStress:'15 min stress test',stopStress:'Apturēt stress test',clearQa:'Notīrīt QA log',exportQa:'Eksportēt QA log JSON',systemStatus:'Sistēmas statuss',currentPhase:'Pašreizējā fāze',stateVersion:'Stāvokļa versija',language:'Valoda',apiStatus:'API statuss',qaStorage:'QA krātuve',requestId:'Request ID',activeTest:'Aktīvs tests',name:'Nosaukums',steps:'Soļi',result:'Rezultāts',recentActions:'Pēdējās darbības',noQaActions:'Nav QA darbību',performance:'Veiktspēja',avgResponse:'Vidējā atbilde',throughput:'Caurlaidspēja',errorRate:'Kļūdu īpatsvars',canonicalState:'Kanoniskais stāvoklis',idle:'Neaktīvs',approvalRequired:'Nepieciešams apstiprinājums',approve:'Apstiprināt',reject:'Noraidīt',writesState:'raksta stāvokli: true',requiresApproval:'prasa apstiprinājumu: true',billableFalse:'maksas: false',start_architecture_test:'sākt arhitektūras testu',save_business_type:'saglabāt biznesa tipu',save_primary_goal:'saglabāt galveno mērķi',reset_lab:'atiestatīt lab',send_lab_email:'nosūtīt lab email',planning:'Plānošana',executing:'Izpilde',completed:'pabeigts',running:'darbojas',thinking:'domā',failed:'neizdevās'},
        lt: {title:'AYSA Agent8',subtitle:'Deterministinė vykdymo sistema',active:'Aktyvus',conversation:'Pokalbis',execution:'Agent8 vykdymas',waiting:'laukia būsenos',placeholder:'Aprašykite užduotį AYSA Agent 8...',authenticated:'Autentifikuota',automatedSeo:'Automatizuotas SEO',qaDiagnostics:'QA diagnostika',controls:'Valdikliai',runAll:'Vykdyti visus testus',runState:'Būsenos testai',runAction:'Veiksmų testai',runLlm:'LLM testai',runInvalid:'Neteisingų veiksmų testai',runReset:'Reset testas',runStress:'15 min stress test',stopStress:'Stabdyti stress test',clearQa:'Išvalyti QA log',exportQa:'Eksportuoti QA log JSON',systemStatus:'Sistemos būsena',currentPhase:'Dabartinė fazė',stateVersion:'Būsenos versija',language:'Kalba',apiStatus:'API būsena',qaStorage:'QA saugykla',requestId:'Request ID',activeTest:'Aktyvus testas',name:'Pavadinimas',steps:'Žingsniai',result:'Rezultatas',recentActions:'Naujausi veiksmai',noQaActions:'QA veiksmų nėra',performance:'Našumas',avgResponse:'Vidutinis atsakas',throughput:'Pralaidumas',errorRate:'Klaidų dažnis',canonicalState:'Kanoninė būsena',idle:'Neaktyvus',approvalRequired:'Reikia patvirtinimo',approve:'Patvirtinti',reject:'Atmesti',writesState:'rašo būseną: true',requiresApproval:'reikalauja patvirtinimo: true',billableFalse:'apmokestinama: false',start_architecture_test:'paleisti architektūros testą',save_business_type:'išsaugoti verslo tipą',save_primary_goal:'išsaugoti pagrindinį tikslą',reset_lab:'atstatyti lab',send_lab_email:'siųsti lab email',planning:'Planavimas',executing:'Vykdymas',completed:'baigta',running:'vykdoma',thinking:'galvoja',failed:'nepavyko'}
    });

    $.extend(I18N, {
        lb: {title:'AYSA Agent8',subtitle:'Deterministescht Ausféierungssystem',active:'Aktiv',conversation:'Gespréich',execution:'Agent8 Ausféierung',waiting:'waart op Status',placeholder:'Beschreift d’Aufgab fir AYSA Agent 8...',authenticated:'Authentifizéiert',automatedSeo:'Automatiséiert SEO',qaDiagnostics:'QA Diagnostik',controls:'Kontrollen',runAll:'All Tester starten',runState:'Status Tester',runAction:'Aktioun Tester',runLlm:'LLM Tester',runInvalid:'Ongëlteg Aktiounen testen',runReset:'Reset Test',runStress:'15 Min Stress Test',stopStress:'Stress Test stoppen',clearQa:'QA Log läschen',exportQa:'QA Log JSON exportéieren',systemStatus:'Systemstatus',currentPhase:'Aktuell Phas',stateVersion:'Status Versioun',language:'Sprooch',apiStatus:'API Status',qaStorage:'QA Späicher',requestId:'Request ID',activeTest:'Aktiven Test',name:'Numm',steps:'Schrëtt',result:'Resultat',recentActions:'Rezent Aktiounen',noQaActions:'Keng QA Aktiounen',performance:'Leeschtung',avgResponse:'Duerchschnëtt Äntwert',throughput:'Duerchsatz',errorRate:'Feelerquote',canonicalState:'Kanonesche Status',idle:'Inaktiv',approvalRequired:'Geneemegung erfuerderlech',approve:'Geneemegen',reject:'Ofleenen',writesState:'schreift Status: true',requiresApproval:'erfuerdert Geneemegung: true',billableFalse:'verrechenbar: false',start_architecture_test:'Architekturtest starten',save_business_type:'Business Typ späicheren',save_primary_goal:'Haaptzil späicheren',reset_lab:'Lab zerécksetzen',send_lab_email:'Lab Email schécken',planning:'Planung',executing:'Ausféierung',completed:'ofgeschloss',running:'leeft',thinking:'denkt',failed:'gescheitert'},
        mk: {title:'AYSA Agent8',subtitle:'Детерминистички систем за извршување',active:'Активен',conversation:'Разговор',execution:'Извршување Agent8',waiting:'чека состојба',placeholder:'Опишете ја задачата за AYSA Agent 8...',authenticated:'Автентициран',automatedSeo:'Автоматизиран SEO',qaDiagnostics:'QA дијагностика',controls:'Контроли',runAll:'Стартувај ги сите тестови',runState:'Тестови на состојба',runAction:'Тестови на акции',runLlm:'LLM тестови',runInvalid:'Тестови на невалидни акции',runReset:'Reset тест',runStress:'15 мин stress test',stopStress:'Стопирај stress test',clearQa:'Исчисти QA log',exportQa:'Експорт QA log JSON',systemStatus:'Статус на систем',currentPhase:'Тековна фаза',stateVersion:'Верзија на состојба',language:'Јазик',apiStatus:'API статус',qaStorage:'QA складирање',requestId:'Request ID',activeTest:'Активен тест',name:'Име',steps:'Чекори',result:'Резултат',recentActions:'Последни акции',noQaActions:'Нема QA акции',performance:'Перформанси',avgResponse:'Просечен одговор',throughput:'Пропусност',errorRate:'Стапка на грешки',canonicalState:'Канонска состојба',idle:'Неактивен',approvalRequired:'Потребно одобрување',approve:'Одобри',reject:'Одбиј',writesState:'пишува состојба: true',requiresApproval:'бара одобрување: true',billableFalse:'наплатливо: false',start_architecture_test:'започни тест на архитектура',save_business_type:'зачувај тип на бизнис',save_primary_goal:'зачувај главна цел',reset_lab:'ресетирај lab',send_lab_email:'испрати lab email',planning:'Планирање',executing:'Извршување',completed:'завршено',running:'работи',thinking:'размислува',failed:'неуспешно'},
        mt: {title:'AYSA Agent8',subtitle:'Sistema ta’ eżekuzzjoni deterministika',active:'Attiv',conversation:'Konverżazzjoni',execution:'Eżekuzzjoni Agent8',waiting:'jistenna l-istat',placeholder:'Iddeskrivi l-kompitu għal AYSA Agent 8...',authenticated:'Awtentikat',automatedSeo:'SEO awtomatizzat',qaDiagnostics:'Dijanjostika QA',controls:'Kontrolli',runAll:'Mexxi t-testijiet kollha',runState:'Testijiet tal-istat',runAction:'Testijiet tal-azzjonijiet',runLlm:'Testijiet LLM',runInvalid:'Testijiet ta’ azzjonijiet invalidi',runReset:'Test reset',runStress:'Stress test 15-il minuta',stopStress:'Waqqaf stress test',clearQa:'Naddaf QA log',exportQa:'Esporta QA log JSON',systemStatus:'Status tas-sistema',currentPhase:'Fażi kurrenti',stateVersion:'Verżjoni tal-istat',language:'Lingwa',apiStatus:'Status API',qaStorage:'Ħażna QA',requestId:'Request ID',activeTest:'Test attiv',name:'Isem',steps:'Passi',result:'Riżultat',recentActions:'Azzjonijiet riċenti',noQaActions:'Ebda azzjoni QA',performance:'Prestazzjoni',avgResponse:'Rispons medju',throughput:'Throughput',errorRate:'Rata ta’ żbalji',canonicalState:'Stat kanoniku',idle:'Wieqaf',approvalRequired:'Approvazzjoni meħtieġa',approve:'Approva',reject:'Irrifjuta',writesState:'jikteb stat: true',requiresApproval:'jeħtieġ approvazzjoni: true',billableFalse:'fatturabbli: false',start_architecture_test:'ibda test tal-arkitettura',save_business_type:'issejvja tip ta’ negozju',save_primary_goal:'issejvja għan ewlieni',reset_lab:'reset lab',send_lab_email:'ibgħat lab email',planning:'Ippjanar',executing:'Eżekuzzjoni',completed:'lest',running:'għaddej',thinking:'jaħseb',failed:'falla'},
        no: {title:'AYSA Agent8',subtitle:'Deterministisk utførelsessystem',active:'Aktiv',conversation:'Samtale',execution:'Agent8 utførelse',waiting:'venter på tilstand',placeholder:'Beskriv oppgaven for AYSA Agent 8...',authenticated:'Autentisert',automatedSeo:'Automatisert SEO',qaDiagnostics:'QA-diagnostikk',controls:'Kontroller',runAll:'Kjør alle tester',runState:'Tilstandstester',runAction:'Handlingstester',runLlm:'LLM-tester',runInvalid:'Ugyldige handlingstester',runReset:'Reset-test',runStress:'15 min stresstest',stopStress:'Stopp stresstest',clearQa:'Tøm QA-logg',exportQa:'Eksporter QA-logg JSON',systemStatus:'Systemstatus',currentPhase:'Gjeldende fase',stateVersion:'Tilstandsversjon',language:'Språk',apiStatus:'API-status',qaStorage:'QA-lagring',requestId:'Request ID',activeTest:'Aktiv test',name:'Navn',steps:'Steg',result:'Resultat',recentActions:'Nylige handlinger',noQaActions:'Ingen QA-handlinger',performance:'Ytelse',avgResponse:'Gjennomsnittlig svar',throughput:'Gjennomstrømning',errorRate:'Feilrate',canonicalState:'Kanonisk tilstand',idle:'Inaktiv',approvalRequired:'Godkjenning kreves',approve:'Godkjenn',reject:'Avvis',writesState:'skriver tilstand: true',requiresApproval:'krever godkjenning: true',billableFalse:'fakturerbar: false',start_architecture_test:'start arkitekturtest',save_business_type:'lagre virksomhetstype',save_primary_goal:'lagre hovedmål',reset_lab:'tilbakestill lab',send_lab_email:'send lab e-post',planning:'Planlegging',executing:'Utførelse',completed:'fullført',running:'kjører',thinking:'tenker',failed:'mislyktes'},
        ru: {title:'AYSA Agent8',subtitle:'Детерминированная система выполнения',active:'Активен',conversation:'Диалог',execution:'Выполнение Agent8',waiting:'ожидание состояния',placeholder:'Опишите задачу для AYSA Agent 8...',authenticated:'Аутентифицирован',automatedSeo:'Автоматизированное SEO',qaDiagnostics:'QA диагностика',controls:'Управление',runAll:'Запустить все тесты',runState:'Тесты состояния',runAction:'Тесты действий',runLlm:'LLM тесты',runInvalid:'Тесты неверных действий',runReset:'Reset тест',runStress:'15 мин stress test',stopStress:'Остановить stress test',clearQa:'Очистить QA log',exportQa:'Экспорт QA log JSON',systemStatus:'Статус системы',currentPhase:'Текущая фаза',stateVersion:'Версия состояния',language:'Язык',apiStatus:'API статус',qaStorage:'QA хранилище',requestId:'Request ID',activeTest:'Активный тест',name:'Название',steps:'Шаги',result:'Результат',recentActions:'Последние действия',noQaActions:'Нет QA действий',performance:'Производительность',avgResponse:'Средний ответ',throughput:'Пропускная способность',errorRate:'Процент ошибок',canonicalState:'Каноническое состояние',idle:'Неактивен',approvalRequired:'Требуется подтверждение',approve:'Подтвердить',reject:'Отклонить',writesState:'записывает состояние: true',requiresApproval:'требует подтверждения: true',billableFalse:'платно: false',start_architecture_test:'запустить тест архитектуры',save_business_type:'сохранить тип бизнеса',save_primary_goal:'сохранить главную цель',reset_lab:'сбросить lab',send_lab_email:'отправить lab email',planning:'Планирование',executing:'Выполнение',completed:'завершено',running:'выполняется',thinking:'думает',failed:'ошибка'},
        sr: {title:'AYSA Agent8',subtitle:'Детерминистички систем извршавања',active:'Активан',conversation:'Разговор',execution:'Извршавање Agent8',waiting:'чека стање',placeholder:'Опишите задатак за AYSA Agent 8...',authenticated:'Аутентификован',automatedSeo:'Аутоматизовани SEO',qaDiagnostics:'QA дијагностика',controls:'Контроле',runAll:'Покрени све тестове',runState:'Тестови стања',runAction:'Тестови акција',runLlm:'LLM тестови',runInvalid:'Тестови неважећих акција',runReset:'Reset тест',runStress:'15 мин stress test',stopStress:'Заустави stress test',clearQa:'Очисти QA log',exportQa:'Извези QA log JSON',systemStatus:'Статус система',currentPhase:'Тренутна фаза',stateVersion:'Верзија стања',language:'Језик',apiStatus:'API статус',qaStorage:'QA складиште',requestId:'Request ID',activeTest:'Активан тест',name:'Име',steps:'Кораци',result:'Резултат',recentActions:'Недавне акције',noQaActions:'Нема QA акција',performance:'Перформансе',avgResponse:'Просечан одговор',throughput:'Пропусност',errorRate:'Стопа грешака',canonicalState:'Канонско стање',idle:'Неактиван',approvalRequired:'Потребно одобрење',approve:'Одобри',reject:'Одбиј',writesState:'пише стање: true',requiresApproval:'захтева одобрење: true',billableFalse:'наплативо: false',start_architecture_test:'покрени тест архитектуре',save_business_type:'сачувај тип бизниса',save_primary_goal:'сачувај главни циљ',reset_lab:'ресетуј lab',send_lab_email:'пошаљи lab email',planning:'Планирање',executing:'Извршавање',completed:'завршено',running:'ради',thinking:'размишља',failed:'неуспешно'}
    });

    $.extend(I18N, {
        sk: {title:'AYSA Agent8',subtitle:'Deterministický systém vykonávania',active:'Aktívny',conversation:'Konverzácia',execution:'Vykonávanie Agent8',waiting:'čaká na stav',placeholder:'Popíšte úlohu pre AYSA Agent 8...',authenticated:'Overené',automatedSeo:'Automatizované SEO',qaDiagnostics:'QA diagnostika',controls:'Ovládanie',runAll:'Spustiť všetky testy',runState:'Testy stavu',runAction:'Testy akcií',runLlm:'LLM testy',runInvalid:'Testy neplatných akcií',runReset:'Reset test',runStress:'15 min stress test',stopStress:'Zastaviť stress test',clearQa:'Vyčistiť QA log',exportQa:'Exportovať QA log JSON',systemStatus:'Stav systému',currentPhase:'Aktuálna fáza',stateVersion:'Verzia stavu',language:'Jazyk',apiStatus:'API stav',qaStorage:'QA úložisko',requestId:'Request ID',activeTest:'Aktívny test',name:'Názov',steps:'Kroky',result:'Výsledok',recentActions:'Nedávne akcie',noQaActions:'Žiadne QA akcie',performance:'Výkon',avgResponse:'Priemerná odpoveď',throughput:'Priepustnosť',errorRate:'Miera chýb',canonicalState:'Kanonický stav',idle:'Neaktívny',approvalRequired:'Vyžaduje schválenie',approve:'Schváliť',reject:'Odmietnuť',writesState:'zapisuje stav: true',requiresApproval:'vyžaduje schválenie: true',billableFalse:'účtovateľné: false',start_architecture_test:'spustiť test architektúry',save_business_type:'uložiť typ podnikania',save_primary_goal:'uložiť hlavný cieľ',reset_lab:'resetovať lab',send_lab_email:'odoslať lab email',planning:'Plánovanie',executing:'Vykonávanie',completed:'dokončené',running:'beží',thinking:'premýšľa',failed:'zlyhalo'},
        sl: {title:'AYSA Agent8',subtitle:'Deterministični sistem izvajanja',active:'Aktiven',conversation:'Pogovor',execution:'Izvajanje Agent8',waiting:'čaka na stanje',placeholder:'Opišite nalogo za AYSA Agent 8...',authenticated:'Avtenticirano',automatedSeo:'Avtomatiziran SEO',qaDiagnostics:'QA diagnostika',controls:'Kontrole',runAll:'Zaženi vse teste',runState:'Testi stanja',runAction:'Testi akcij',runLlm:'LLM testi',runInvalid:'Testi neveljavnih akcij',runReset:'Reset test',runStress:'15 min stress test',stopStress:'Ustavi stress test',clearQa:'Počisti QA log',exportQa:'Izvozi QA log JSON',systemStatus:'Status sistema',currentPhase:'Trenutna faza',stateVersion:'Različica stanja',language:'Jezik',apiStatus:'API status',qaStorage:'QA shramba',requestId:'Request ID',activeTest:'Aktivni test',name:'Ime',steps:'Koraki',result:'Rezultat',recentActions:'Nedavne akcije',noQaActions:'Ni QA akcij',performance:'Zmogljivost',avgResponse:'Povprečen odgovor',throughput:'Prepustnost',errorRate:'Stopnja napak',canonicalState:'Kanonično stanje',idle:'Neaktiven',approvalRequired:'Potrebna odobritev',approve:'Odobri',reject:'Zavrni',writesState:'piše stanje: true',requiresApproval:'zahteva odobritev: true',billableFalse:'zaračunljivo: false',start_architecture_test:'zaženi test arhitekture',save_business_type:'shrani tip poslovanja',save_primary_goal:'shrani glavni cilj',reset_lab:'ponastavi lab',send_lab_email:'pošlji lab email',planning:'Načrtovanje',executing:'Izvajanje',completed:'dokončano',running:'teče',thinking:'razmišlja',failed:'neuspešno'},
        sv: {title:'AYSA Agent8',subtitle:'Deterministiskt körningssystem',active:'Aktiv',conversation:'Konversation',execution:'Agent8 körning',waiting:'väntar på tillstånd',placeholder:'Beskriv uppgiften för AYSA Agent 8...',authenticated:'Autentiserad',automatedSeo:'Automatiserad SEO',qaDiagnostics:'QA-diagnostik',controls:'Kontroller',runAll:'Kör alla tester',runState:'Tillståndstester',runAction:'Åtgärdstester',runLlm:'LLM-tester',runInvalid:'Ogiltiga åtgärdstester',runReset:'Reset-test',runStress:'15 min stresstest',stopStress:'Stoppa stresstest',clearQa:'Rensa QA-logg',exportQa:'Exportera QA-logg JSON',systemStatus:'Systemstatus',currentPhase:'Aktuell fas',stateVersion:'Tillståndsversion',language:'Språk',apiStatus:'API-status',qaStorage:'QA-lagring',requestId:'Request ID',activeTest:'Aktivt test',name:'Namn',steps:'Steg',result:'Resultat',recentActions:'Senaste åtgärder',noQaActions:'Inga QA-åtgärder',performance:'Prestanda',avgResponse:'Genomsnittligt svar',throughput:'Genomströmning',errorRate:'Felfrekvens',canonicalState:'Kanoniskt tillstånd',idle:'Inaktiv',approvalRequired:'Godkännande krävs',approve:'Godkänn',reject:'Avvisa',writesState:'skriver tillstånd: true',requiresApproval:'kräver godkännande: true',billableFalse:'debiterbar: false',start_architecture_test:'starta arkitekturtest',save_business_type:'spara företagstyp',save_primary_goal:'spara huvudmål',reset_lab:'återställ lab',send_lab_email:'skicka lab email',planning:'Planering',executing:'Körning',completed:'klart',running:'kör',thinking:'tänker',failed:'misslyckades'},
        tr: {title:'AYSA Agent8',subtitle:'Deterministik yürütme sistemi',active:'Aktif',conversation:'Konuşma',execution:'Agent8 yürütme',waiting:'durum bekleniyor',placeholder:'AYSA Agent 8 için görevi açıklayın...',authenticated:'Kimliği doğrulandı',automatedSeo:'Otomatik SEO',qaDiagnostics:'QA tanılama',controls:'Kontroller',runAll:'Tüm testleri çalıştır',runState:'Durum testleri',runAction:'Aksiyon testleri',runLlm:'LLM testleri',runInvalid:'Geçersiz aksiyon testleri',runReset:'Reset testi',runStress:'15 dk stress test',stopStress:'Stress testi durdur',clearQa:'QA log temizle',exportQa:'QA log JSON dışa aktar',systemStatus:'Sistem durumu',currentPhase:'Geçerli faz',stateVersion:'Durum sürümü',language:'Dil',apiStatus:'API durumu',qaStorage:'QA depolama',requestId:'Request ID',activeTest:'Aktif test',name:'Ad',steps:'Adımlar',result:'Sonuç',recentActions:'Son aksiyonlar',noQaActions:'QA aksiyonu yok',performance:'Performans',avgResponse:'Ortalama yanıt',throughput:'Throughput',errorRate:'Hata oranı',canonicalState:'Kanonik durum',idle:'Boşta',approvalRequired:'Onay gerekli',approve:'Onayla',reject:'Reddet',writesState:'durum yazar: true',requiresApproval:'onay gerektirir: true',billableFalse:'ücretli: false',start_architecture_test:'mimari testini başlat',save_business_type:'iş tipini kaydet',save_primary_goal:'ana hedefi kaydet',reset_lab:'labı sıfırla',send_lab_email:'lab email gönder',planning:'Planlama',executing:'Yürütme',completed:'tamamlandı',running:'çalışıyor',thinking:'düşünüyor',failed:'başarısız'},
        uk: {title:'AYSA Agent8',subtitle:'Детермінована система виконання',active:'Активний',conversation:'Розмова',execution:'Виконання Agent8',waiting:'очікує стан',placeholder:'Опишіть завдання для AYSA Agent 8...',authenticated:'Автентифіковано',automatedSeo:'Автоматизоване SEO',qaDiagnostics:'QA діагностика',controls:'Керування',runAll:'Запустити всі тести',runState:'Тести стану',runAction:'Тести дій',runLlm:'LLM тести',runInvalid:'Тести невалідних дій',runReset:'Reset тест',runStress:'15 хв stress test',stopStress:'Зупинити stress test',clearQa:'Очистити QA log',exportQa:'Експортувати QA log JSON',systemStatus:'Статус системи',currentPhase:'Поточна фаза',stateVersion:'Версія стану',language:'Мова',apiStatus:'API статус',qaStorage:'QA сховище',requestId:'Request ID',activeTest:'Активний тест',name:'Назва',steps:'Кроки',result:'Результат',recentActions:'Останні дії',noQaActions:'Немає QA дій',performance:'Продуктивність',avgResponse:'Середня відповідь',throughput:'Пропускна здатність',errorRate:'Відсоток помилок',canonicalState:'Канонічний стан',idle:'Неактивний',approvalRequired:'Потрібне схвалення',approve:'Схвалити',reject:'Відхилити',writesState:'записує стан: true',requiresApproval:'потребує схвалення: true',billableFalse:'платно: false',start_architecture_test:'запустити тест архітектури',save_business_type:'зберегти тип бізнесу',save_primary_goal:'зберегти головну ціль',reset_lab:'скинути lab',send_lab_email:'надіслати lab email',planning:'Планування',executing:'Виконання',completed:'завершено',running:'виконується',thinking:'думає',failed:'помилка'},
        cy: {title:'AYSA Agent8',subtitle:'System weithredu benderfynol',active:'Gweithredol',conversation:'Sgwrs',execution:'Gweithredu Agent8',waiting:'yn aros am gyflwr',placeholder:'Disgrifiwch y dasg ar gyfer AYSA Agent 8...',authenticated:'Wedi’i ddilysu',automatedSeo:'SEO awtomataidd',qaDiagnostics:'Diagnosteg QA',controls:'Rheolyddion',runAll:'Rhedeg pob prawf',runState:'Profion cyflwr',runAction:'Profion gweithred',runLlm:'Profion LLM',runInvalid:'Profion gweithred annilys',runReset:'Prawf reset',runStress:'Stress test 15 mun',stopStress:'Stopio stress test',clearQa:'Clirio log QA',exportQa:'Allforio log QA JSON',systemStatus:'Statws system',currentPhase:'Cam cyfredol',stateVersion:'Fersiwn cyflwr',language:'Iaith',apiStatus:'Statws API',qaStorage:'Storio QA',requestId:'Request ID',activeTest:'Prawf gweithredol',name:'Enw',steps:'Camau',result:'Canlyniad',recentActions:'Gweithredoedd diweddar',noQaActions:'Dim gweithredoedd QA',performance:'Perfformiad',avgResponse:'Ymateb cyfartalog',throughput:'Throughput',errorRate:'Cyfradd gwall',canonicalState:'Cyflwr canonaidd',idle:'Anweithredol',approvalRequired:'Angen cymeradwyaeth',approve:'Cymeradwyo',reject:'Gwrthod',writesState:'yn ysgrifennu cyflwr: true',requiresApproval:'angen cymeradwyaeth: true',billableFalse:'biladwy: false',start_architecture_test:'cychwyn prawf pensaernïaeth',save_business_type:'cadw math busnes',save_primary_goal:'cadw prif nod',reset_lab:'ailosod lab',send_lab_email:'anfon lab email',planning:'Cynllunio',executing:'Gweithredu',completed:'cwblhawyd',running:'yn rhedeg',thinking:'yn meddwl',failed:'methodd'},
        yi: {title:'AYSA Agent8',subtitle:'דיטערמיניסטישע אויספיר סיסטעם',active:'אַקטיוו',conversation:'שמועס',execution:'Agent8 אויספיר',waiting:'וואַרט אויף מצב',placeholder:'באַשרײַבט די אויפגאַבע פֿאַר AYSA Agent 8...',authenticated:'אויטענטיפיצירט',automatedSeo:'אויטאָמאַטישער SEO',qaDiagnostics:'QA דיאַגנאָסטיק',controls:'קאָנטראָלן',runAll:'לויפן אַלע טעסטן',runState:'מצב טעסטן',runAction:'אַקציע טעסטן',runLlm:'LLM טעסטן',runInvalid:'אומגילטיקע אַקציע טעסטן',runReset:'Reset טעסט',runStress:'15 מינוט stress test',stopStress:'אָפּשטעלן stress test',clearQa:'רייניקן QA log',exportQa:'עקספּאָרטירן QA log JSON',systemStatus:'סיסטעם מצב',currentPhase:'איצטיקע פאַזע',stateVersion:'מצב ווערסיע',language:'שפּראַך',apiStatus:'API מצב',qaStorage:'QA סטאָרידזש',requestId:'Request ID',activeTest:'אַקטיווער טעסט',name:'נאָמען',steps:'שריט',result:'רעזולטאַט',recentActions:'לעצטע אַקציעס',noQaActions:'קיין QA אַקציעס',performance:'פּערפאָרמאַנס',avgResponse:'דורכשניט ענטפער',throughput:'Throughput',errorRate:'טעות קורס',canonicalState:'קאַנאָנישער מצב',idle:'נישט אַקטיוו',approvalRequired:'באשטעטיקונג פארלאנגט',approve:'באשטעטיקן',reject:'אָפּוואַרפן',writesState:'שרייבט מצב: true',requiresApproval:'דאַרף באשטעטיקונג: true',billableFalse:'בילאַבאַל: false',start_architecture_test:'אָנהייבן אַרכיטעקטור טעסט',save_business_type:'אויפהיטן ביזנעס טיפּ',save_primary_goal:'אויפהיטן הויפּט ציל',reset_lab:'reset lab',send_lab_email:'שיקן lab email',planning:'פּלאַנירונג',executing:'אויספיר',completed:'געענדיקט',running:'לויפט',thinking:'טראַכט',failed:'דורכגעפאַלן'}
    });

    function normalizeLanguageCode(language) {
        const raw = String(language || '').trim();
        const normalized = raw.toLowerCase().replace(/_/g, '-');
        const aliases = {
            romanian: 'ro',
            romana: 'ro',
            română: 'ro',
            ro: 'ro',
            english: 'en',
            'english (europe/uk)': 'en-GB',
            'english (united states)': 'en-US',
            'english (canada)': 'en-CA'
        };
        return aliases[normalized] || raw || 'ro';
    }

    function uiLanguage() {
        const selectedLanguage = $('#aysa-agent8v3-language').val();
        if (selectedLanguage) {
            return normalizeLanguageCode(selectedLanguage);
        }
        const canonical = state.canonical || {};
        return normalizeLanguageCode((canonical.data && canonical.data.language) || (canonical.decisions && canonical.decisions.language) || 'ro');
    }

    function text(key) {
        const language = uiLanguage();
        const packKey = LANGUAGE_PACK[language] || language;
        const pack = I18N[packKey] || I18N.en;
        if (pack[key]) {
            return pack[key];
        }
        if (I18N.en[key]) {
            const fallback = String(language || 'unknown') + ':ui:' + key;
            if (!state.languageFallbacks.includes(fallback)) {
                state.languageFallbacks.push(fallback);
            }
            return I18N.en[key];
        }
        const missing = String(language || 'unknown') + ':missing:' + key;
        if (!state.languageFallbacks.includes(missing)) {
            state.languageFallbacks.push(missing);
        }
        return key;
    }

    function localizeOnPageAeoPreflightModal(modal) {
        const uiLang = String(uiLanguage() || '');
        const htmlLang = String((document.documentElement && document.documentElement.lang) || '');
        const appLang = String($('.aysa-agent8v3-app').attr('lang') || '');
        const modalLang = String((modal && modal.language) || '');
        const isRomanian = uiLang.indexOf('ro') === 0 ||
            htmlLang.indexOf('ro') === 0 ||
            appLang.indexOf('ro') === 0 ||
            modalLang.indexOf('ro') === 0;
        if (!modal || typeof modal !== 'object' || !isRomanian) {
            return modal;
        }
        if (String(modal.modal_key || '') !== 'onpage_seo' || String(modal.active_tab || '') !== 'aeo_content_qa') {
            return modal;
        }

        const rows = Array.isArray(modal.rows) ? modal.rows : [];
        const mappedCount = rows.filter(function(row) {
            return String((row && (row.mapping_state || row.keyword_mapping_state)) || '') === 'mapped' ||
                String((row && row.mapping_review_section_key) || '') === 'confirmed';
        }).length;
        modal.language = 'ro';
        if (typeof modal.subtitle === 'string' && modal.subtitle.indexOf('I read the On Page SEO workspace') !== -1) {
            modal.subtitle = 'Am citit workspace-ul On Page SEO. Am găsit ' + rows.length + ' pagini/entități în acest review, dintre care ' + mappedCount + ' sunt mapate pe keyword-uri. Nu generez conținut și nu modific site-ul în acest pas.';
        }

        (Array.isArray(modal.actions) ? modal.actions : []).forEach(function(action) {
            if (!action || String(action.action || '') !== 'prepare_onpage_aeo_preview_preflight') {
                return;
            }
            const payload = action.payload && typeof action.payload === 'object' ? action.payload : {};
            const selectedCount = Number(payload.selected_count || payload.selected_rows_count || (Array.isArray(payload.selection) ? payload.selection.length : 0) || 0);
            action.label = 'Pregătește propuneri FAQ (' + selectedCount + ') - Necesită estimare și limită maximă de cost';
            action.disabled_reason = 'Pentru propuneri FAQ trebuie confirmate rândurile selectate, estimarea și limita maximă de cost. Nu generez conținut și nu modific site-ul în acest pas.';
            action.badges = ['Doar previzualizare', 'Fără modificări live', 'Necesită limită de cost'];
            payload.selection_scope_label = 'Doar rândurile vizibile confirmate și mapate';
            payload.estimated_cost_label = 'Estimare exactă necesară înainte de generare';
            payload.output_type_label = payload.output_type_label || 'FAQ / answer block / summary';
        });

        return modal;
    }

    function actionLabel(action) {
        return text(action) || String(action || '').replace(/_/g, ' ');
    }

    function updateModalChromeText() {
        $('label[for="aysa-agent8v3-modal-search"]').text(text('modalSearchLabel'));
        $('label[for="aysa-agent8v3-modal-status"]').text(text('modalStatusLabel'));
        $('#aysa-agent8v3-modal-prev').text(text('modalPrevious'));
        $('#aysa-agent8v3-modal-next').text(text('modalNext'));
        $('#aysa-agent8v3-modal-close').attr('aria-label', String(uiLanguage() || 'ro').indexOf('ro') === 0 ? 'Închide review-ul' : 'Close review');
    }

    function updateIssueModalText() {
        const replaceLeadingText = function(selector, key) {
            const label = $(selector).first();
            const textNode = label.contents().filter(function() { return this.nodeType === 3; }).first();
            if (textNode.length) {
                textNode[0].nodeValue = text(key) + '\n';
            }
        };
        $('#aysa-agent8v3-issue-title').text(text('reportProblem'));
        $('.aysa-agent8v3-issue-intro').text(text('issueIntro'));
        $('.aysa-agent8v3-issue-header [data-agent8v3-issue-close]').attr('aria-label', text('issueClose'));
        $('label[for="aysa-agent8v3-issue-summary"]').text(text('issueWhat'));
        $('#aysa-agent8v3-issue-summary').attr('placeholder', text('issuePlaceholder'));
        replaceLeadingText('.aysa-agent8v3-issue-module-label', 'issueModule');
        replaceLeadingText('.aysa-agent8v3-issue-type-label', 'issueType');
        replaceLeadingText('.aysa-agent8v3-issue-email-label', 'issueSupportEmail');
        replaceLeadingText('.aysa-agent8v3-issue-screenshot-label', 'issueScreenshot');
        $('#aysa-agent8v3-issue-module option[value="activation_setup"]').text(text('issueActivationSetup'));
        $('#aysa-agent8v3-issue-module option[value="billing"]').text(text('issueBilling'));
        $('#aysa-agent8v3-issue-module option[value="plugin_ui"]').text(text('issuePluginUi'));
        $('#aysa-agent8v3-issue-type option[value="cannot_continue"]').text(text('issueCannotContinue'));
        $('#aysa-agent8v3-issue-type option[value="confusing_wrong"]').text(text('issueConfusingWrong'));
        $('#aysa-agent8v3-issue-type option[value="credit_consumed"]').text(text('issueCreditConsumed'));
        $('#aysa-agent8v3-issue-type option[value="email_missing"]').text(text('issueEmailMissing'));
        $('#aysa-agent8v3-issue-type option[value="other"]').text(text('issueOther'));
        $('#aysa-agent8v3-issue-screenshot-consent option[value="no"]').text(text('issueScreenshotNo'));
        $('#aysa-agent8v3-issue-screenshot-consent option[value="yes"]').text(text('issueScreenshotYes'));
        $('.aysa-agent8v3-issue-body details summary').text(text('issueSafeContext'));
        $('.aysa-agent8v3-issue-body details li').eq(0).text(text('issueContextActions'));
        $('.aysa-agent8v3-issue-body details li').eq(1).text(text('issueContextState'));
        $('.aysa-agent8v3-issue-body details li').eq(2).text(text('issueContextWallet'));
        $('.aysa-agent8v3-issue-footer [data-agent8v3-issue-close]').text(text('issueCancel'));
        $('#aysa-agent8v3-issue-submit').text(text('issueSubmit'));
    }

    function shortId(value) {
        const raw = String(value || '');
        if (raw === '-' || raw.length <= 18) {
            return raw || '-';
        }
        return raw.slice(0, 10) + '...' + raw.slice(-6);
    }

    function applyInterfaceLanguage(language) {
        language = normalizeLanguageCode(language);
        const packKey = LANGUAGE_PACK[language] || language;
        const isRtl = packKey === 'ar';
        // State hydration can return a newer canonical language than the
        // WordPress-cached shell config. Keep the selector in sync before any
        // text() lookup because uiLanguage() intentionally reads that control
        // first. Do not emit change here; the canonical state is already the
        // source of this update.
        const selectLanguage = language === 'en' ? 'en-GB' : language;
        const languageSelector = $('#aysa-agent8v3-language');
        if (languageSelector.find('option[value="' + selectLanguage + '"]').length) {
            languageSelector.val(selectLanguage);
        }
        $('.aysa-agent8v3-app').attr('lang', language || 'ro').attr('dir', isRtl ? 'rtl' : 'ltr');
        $('.aysa-agent8v3-brand h1').text('AYSA Agent8');
        $('.aysa-agent8v3-subtitle').text(String(language || '').indexOf('ro') === 0 ? 'Workspace SEO' : 'SEO workspace');
        $('.aysa-agent8v3-topbar .aysa-agent8v3-active-pill').contents().filter(function() { return this.nodeType === 3; }).remove();
        $('.aysa-agent8v3-topbar .aysa-agent8v3-active-pill').append(text('active'));
        $('.aysa-agent8v3-chat-eyebrow').text(text('conversation'));
        $('.aysa-agent8v3-chat-head strong').first().text(text('execution'));
        $('#aysa-agent8v3-input').attr('placeholder', text('placeholder')).attr('aria-label', text('composerLabel'));
        updateAuthPill(state.canonical);
        $('.aysa-agent8v3-composer-toolbar .aysa-agent8v3-mode-pill').text(text('automatedSeo'));
        $('#aysa-agent8v3-report-problem').text(text('reportProblem'));
        $('.aysa-agent8v3-progress-panel-head h2').text(text('progressTitle'));
        $('.aysa-agent8v3-progress-panel-head p').text(text('progressHint'));
        $('#aysa-agent8v3-send').attr('aria-label', text('sendMessage'));
        $('.aysa-agent8v3-plus').attr('aria-label', text('addContext'));
        $('label[for="aysa-agent8v3-language"]').text(text('agentLanguage'));
        $('#aysa-agent8v3-language').attr('aria-label', text('agentLanguage'));
        $('#aysa-agent8v3-full-reset').text(text('fullReset')).attr('title', text('fullResetTitle')).attr('aria-label', text('fullResetTitle'));
        $('#aysa-agent8v3-factory-reset').text(text('factoryReset')).attr('title', text('factoryResetTitle')).attr('aria-label', text('factoryResetTitle'));
        updateModalChromeText();
        updateIssueModalText();
        $('.aysa-agent8v3-diagnostics-header h2').text(text('qaDiagnostics'));
        $('#aysa-agent8v3-qa-toggle').text(String(language || '').indexOf('ro') === 0 ? 'Detalii tehnice' : 'Technical details');
        $('.aysa-agent8v3-qa-run[data-suite="all"]').text(text('runAll'));
        $('.aysa-agent8v3-qa-run[data-suite="state"]').text(text('runState'));
        $('.aysa-agent8v3-qa-run[data-suite="setup"]').text(text('runSetup'));
        $('.aysa-agent8v3-qa-run[data-suite="research"]').text(text('runResearch'));
        $('.aysa-agent8v3-qa-run[data-suite="setup_stress"]').text(text('runSetupStress'));
        $('.aysa-agent8v3-qa-run[data-suite="setup_integration_stress"]').text(text('runIntegrationStress'));
        $('.aysa-agent8v3-qa-run[data-suite="action"]').text(text('runAction'));
        $('.aysa-agent8v3-qa-run[data-suite="llm"]').text(text('runLlm'));
        $('.aysa-agent8v3-qa-run[data-suite="worker"]').text(text('runWorker'));
        $('.aysa-agent8v3-qa-run[data-suite="rag"]').text(text('runRag'));
        $('.aysa-agent8v3-qa-run[data-suite="language"]').text(text('runLanguage'));
        $('.aysa-agent8v3-qa-run[data-suite="deploy_parity"]').text(text('runDeployParity'));
        $('.aysa-agent8v3-qa-run[data-suite="legacy_sync"]').text(text('runLegacySync'));
        $('.aysa-agent8v3-qa-run[data-suite="invalid_action"]').text(text('runInvalid'));
        $('.aysa-agent8v3-qa-run[data-suite="reset"]').text(text('runReset'));
        $('.aysa-agent8v3-qa-run[data-suite="stress_15m"]').text(text('runStress'));
        $('#aysa-agent8v3-qa-stop').text(text('stopStress'));
        $('#aysa-agent8v3-qa-clear').text(text('clearQa'));
        $('#aysa-agent8v3-qa-export').text(text('exportQa'));
        $('.aysa-agent8v3-metric-card h3').eq(0).text(text('systemStatus'));
        $('.aysa-agent8v3-metric-card h3').eq(1).text(text('credits'));
        $('.aysa-agent8v3-metric-card h3').eq(2).text(text('activeTest'));
        $('.aysa-agent8v3-metric-card h3').eq(3).text(text('recentActions'));
        $('.aysa-agent8v3-metric-card h3').eq(4).text(text('performance'));
        $('.aysa-agent8v3-state-card summary').text(text('canonicalState'));
        $('#aysa-agent8v3-qa-storage').closest('.aysa-agent8v3-metric-row').find('span').text(text('qaStorage'));
        $('#aysa-agent8v3-request-id').closest('.aysa-agent8v3-metric-row').find('span').text(text('requestId'));
    }

    function addMessage(role, body, extra) {
        if (String(role || '').indexOf('qa') === 0 || role === 'execution') {
            appendQaLiveLine(role, body);
            return;
        }

        const id = extra && extra.id ? String(extra.id) : 'msg_' + Date.now() + '_' + Math.random().toString(16).slice(2);
        state.messages.push($.extend({
            id: id,
            role: role,
            body: body,
            phase: state.canonical && state.canonical.phase ? state.canonical.phase : '',
            status: $('[data-agent8v3-status]').attr('data-agent8v3-status') || 'idle',
            created_at: new Date().toISOString()
        }, extra || {}));
        renderMessages();
        return id;
    }

    function isActivationLikePhase(phase) {
        const value = String(phase || '').toLowerCase();
        return ['welcome', 'pre_activation', 'activation_key_requested', 'activation_failed'].indexOf(value) !== -1;
    }

    function looksLikeActivationKey(message) {
        const raw = String(message || '').trim();
        if (!raw) {
            return false;
        }
        return /\b(?:aysa_(?:pk|sk|ak|key)_[A-Za-z0-9_-]{12,}|sk-[A-Za-z0-9_-]{20,}|[A-Za-z0-9_-]{32,}\.[A-Za-z0-9_-]{16,})\b/.test(raw);
    }

    function shouldMaskComposerMessage(message) {
        const raw = String(message || '').trim();
        if (!raw) {
            return false;
        }

        if (looksLikeActivationKey(raw)) {
            return true;
        }

        const phase = String(state.canonical && state.canonical.phase ? state.canonical.phase : '').toLowerCase();
        const isActivationPhase = isActivationLikePhase(phase);

        const guidance = state.guidance && typeof state.guidance === 'object' ? state.guidance : {};
        const action = String(guidance.allowed_action || guidance.action || '').toLowerCase();
        if (isActivationPhase && (action.indexOf('activation_key') !== -1 || action.indexOf('secret_key') !== -1) && looksLikeActivationKey(raw)) {
            return true;
        }

        return false;
    }

    function appendQaLiveLine(role, body) {
        const label = role === 'execution' ? 'Execution' : 'QA';
        const line = '<div class="aysa-agent8v3-qa-live-line"><strong>' + escapeHtml(label) + '</strong><span>' + escapeHtml(body) + '</span></div>';
        $('#aysa-agent8v3-qa-body').prop('hidden', false);
        $('#aysa-agent8v3-qa-results').prepend(line);
    }

    function isSeoModuleGuidanceMessage(message) {
        if (!message || typeof message !== 'object') {
            return false;
        }
        const role = String(message.role || '').toLowerCase();
        if (role === 'user' || role === 'qa user' || role === 'qa stress user') {
            return false;
        }
        const payload = [
            message.body || '',
            message.phase || '',
            message.status || '',
            message.guidance ? JSON.stringify(message.guidance) : ''
        ].join(' ');
        return /technical_(?:overview|site_audit|pagespeed|schema|redirects|sitemap_robots|image_alt|internal_linking)|Technical SEO|Keyword Research|On Page|Off Page|Monitoring|Content Plan|Apply\s+All|Run\s+All|Fix\s+All/i.test(payload);
    }

    function isStaleTechnicalNoAutoApplyMessage(message) {
        if (!message || typeof message !== 'object') {
            return false;
        }
        const role = String(message.role || '').toLowerCase();
        if (role === 'user' || role === 'qa user' || role === 'qa stress user') {
            return false;
        }
        const payload = [
            message.body || '',
            message.phase || '',
            message.guidance ? JSON.stringify(message.guidance) : ''
        ].join(' ');
        return /Technical SEO|technical_seo|alt text pentru imagini|Image Alt/i.test(payload)
            && /Nu aplic nicio modificare automat|no changes are applied automatically|without automatically applying changes|execuție\s+dry-run|dry-run|pus în coadă pentru execuție|a început/i.test(payload);
    }

    function technicalSeoReviewChatMessageHtml(guidance, messages) {
        const currentPhase = state.canonical && state.canonical.phase ? String(state.canonical.phase) : '';
        if (currentPhase !== 'technical_seo_review' || !guidance || typeof guidance !== 'object') {
            return '';
        }
        const body = String(guidance.body || '').trim();
        if (!body) {
            return '';
        }
        const alreadyVisible = (messages || []).some(function(message) {
            return String(message && message.body ? message.body : '').trim() === body;
        });
        if (alreadyVisible) {
            return '';
        }
        return '<div class="aysa-agent8v3-message assistant aysa-agent8v3-technical-review-summary">' +
            '<div class="aysa-agent8v3-message-head">' +
                '<span class="aysa-agent8v3-message-logo">A8</span>' +
                '<span class="aysa-agent8v3-message-role">AYSA Agent 8</span>' +
                '<span class="aysa-agent8v3-status-badge">' + escapeHtml(text(guidance.status || 'guidance')) + '</span>' +
            '</div>' +
            '<div class="aysa-agent8v3-message-card">' +
                '<div class="aysa-agent8v3-message-body">' + linkifySafeText(body, true) + '</div>' +
            '</div>' +
        '</div>';
    }

    function isSetupConversationPhase(phase) {
        return [
            'google_integrations',
            'business_profile',
            'objectives',
            'seo_profile',
            'competition_keyword',
            'tone_of_voice',
            'research_handoff_ready',
            'research_handoff_running',
            'research_handoff_complete'
        ].indexOf(String(phase || '')) !== -1;
    }

    function isMonitoringConversationPhase(phase) {
        return ['monitoring_ready', 'monitoring_review', 'monitoring_active'].indexOf(String(phase || '')) !== -1;
    }

    function isMonitoringGuidanceMessage(message) {
        if (!message || typeof message !== 'object') {
            return false;
        }
        const role = String(message.role || '').toLowerCase();
        if (role === 'user' || role === 'qa user' || role === 'qa stress user') {
            return false;
        }
        const payload = [
            message.body || '',
            message.phase || '',
            message.status || '',
            message.guidance ? JSON.stringify(message.guidance) : ''
        ].join(' ');
        return /(monitoring|monitorizare|pozi[tț]ii\s+(google|serp)|search\s*console|ai\s*visibility|vizibilitate\s+ai|refresh)/i.test(payload);
    }

    function guidanceIsTextOnlyMessage(phase, guidance) {
        const displayMode = guidance && typeof guidance === 'object' ? String(guidance.display_mode || '') : '';
        return displayMode === 'chat_message' || isActivationLikePhase(phase);
    }

    function guidanceRendersInConversation(phase, guidance) {
        if (!guidance || typeof guidance !== 'object') {
            return false;
        }
        if (state.offpageLinkExchangePreflight && String(phase || '') === 'offpage_seo_review') {
            return true;
        }
        if (guidanceIsTextOnlyMessage(phase, guidance)) {
            return true;
        }
        if (String(phase || '') === 'technical_seo_ready') {
            return true;
        }
        if (isMonitoringConversationPhase(phase)) {
            return true;
        }
        if (String(phase || '').indexOf('technical_seo') !== -1) {
            return false;
        }
        return isSetupConversationPhase(phase);
    }

    function monitoringEntryCardHtml(phase) {
        if (!isMonitoringConversationPhase(phase)) {
            return '';
        }
        const isRo = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const title = isRo ? 'Monitorizare' : 'Monitoring';
        const body = isRo
            ? 'Monitorizarea urmărește automat paginile și cuvintele cheie aprobate, conform frecvenței din Profil SEO. Verificările automate vor rula doar în limitele politicii și bugetului aprobat.'
            : 'Monitoring follows approved pages and keywords using the frequency from the SEO Profile. Automated checks run only within the approved policy and budget.';
        const label = isRo ? 'Vezi monitorizarea' : 'View monitoring';
        return '<div class="aysa-agent8v3-message assistant aysa-agent8v3-monitoring-entry-message">' +
            '<div class="aysa-agent8v3-message-head">' +
                '<span class="aysa-agent8v3-message-logo">A8</span>' +
                '<span class="aysa-agent8v3-message-role">AYSA Agent 8</span>' +
            '</div>' +
            '<div class="aysa-agent8v3-message-card aysa-agent8v3-guidance-card is-monitoring-entry">' +
                '<div class="aysa-agent8v3-guidance-title"><strong>' + escapeHtml(title) + '</strong></div>' +
                '<div class="aysa-agent8v3-guidance-content">' +
                    '<p>' + escapeHtml(body) + '</p>' +
                    '<div class="aysa-agent8v3-guidance-options">' +
                        '<button type="button" class="button button-primary aysa-agent8v3-guidance-option aysa-agent8v3-modal-open is-primary" data-modal-key="monitoring">' + escapeHtml(label) + '</button>' +
                    '</div>' +
                '</div>' +
            '</div>' +
        '</div>';
    }

    function normalizeOffpageLinkExchangePreflight(value) {
        if (!value || typeof value !== 'object') {
            return null;
        }
        const nested = value.offpage_link_exchange_preflight && typeof value.offpage_link_exchange_preflight === 'object'
            ? value.offpage_link_exchange_preflight
            : value;
        const summary = value.summary && typeof value.summary === 'object'
            ? value.summary
            : (nested.summary && typeof nested.summary === 'object' ? nested.summary : {});
        const requestSummaries = Array.isArray(nested.request_summaries)
            ? nested.request_summaries
            : (Array.isArray(summary.request_summaries) ? summary.request_summaries : []);
        if (!Object.keys(summary).length && !requestSummaries.length) {
            return null;
        }
        return {
            summary: summary,
            request_summaries: requestSummaries.slice(0, 50),
            status: String(nested.status || value.status || '')
        };
    }

    function isLinkExchangeSummaryRequest(message) {
        const normalized = String(message || '').toLowerCase();
        return /(link\s*exchange|schimb de linkuri|schimb linkuri)/i.test(normalized);
    }

    function offpageLinkExchangeRequestSummaryHtml(value) {
        const view = normalizeOffpageLinkExchangePreflight(value);
        if (!view) {
            return '';
        }
        const summary = view.summary || {};
        const requests = Array.isArray(view.request_summaries) ? view.request_summaries : [];
        const isRo = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const partner = String(summary.partner_domain || (requests[0] && requests[0].partner_domain) || (isRo ? 'Partener' : 'Partner'));
        const existing = parseInt(summary.existing_partner_requests || summary.requests || requests.length, 10) || requests.length;
        const verified = parseInt(summary.verified_partner_requests || summary.verified_requests, 10) || requests.filter(function(row) {
            return String(row.record_classification || '') === 'verified_active';
        }).length;
        const archived = requests.filter(function(row) {
            return String(row.record_classification || '').indexOf('expired_archived') === 0
                || String(row.local_status || '').toLowerCase() === 'expired';
        }).length;
        const requestHtml = requests.map(function(row) {
            const classification = String(row.record_classification || '');
            const isVerified = classification === 'verified_active' || String(row.verification_status || '').indexOf('verificat pe ambele') !== -1;
            const isArchived = classification.indexOf('expired_archived') === 0 || String(row.local_status || '').toLowerCase() === 'expired';
            const statusLabel = isVerified
                ? (isRo ? 'Verificată și activă' : 'Verified and active')
                : (isArchived ? (isRo ? 'Expirată / arhivată' : 'Expired / archived') : (row.verification_status || (isRo ? 'De verificat' : 'Needs review')));
            const requester = [row.requester_source_url || '', row.requester_target_url || '', row.requester_anchor || ''].filter(Boolean).join(' → ');
            const counterparty = [row.counterparty_source_url || '', row.counterparty_target_url || '', row.counterparty_anchor || ''].filter(Boolean).join(' → ');
            const selectedSource = row.source_url || '';
            const selectedTarget = row.target_url || '';
            const selectedAnchor = row.anchor || '';
            const duplicate = row.duplicate_of_exchange_ref
                ? (isRo ? 'Duplicat al: ' : 'Duplicate of: ') + row.duplicate_of_exchange_ref
                : (isArchived ? (isRo ? 'Nu este numărată ca schimb live.' : 'Not counted as a live exchange.') : '');
            return '<div class="aysa-agent8v3-link-exchange-request-row">' +
                '<div class="aysa-agent8v3-link-exchange-request-head"><strong>' + escapeHtml((isRo ? 'Cererea #' : 'Request #') + (row.request_id || '?')) + '</strong><span>' + escapeHtml(row.exchange_ref || '-') + '</span><em>' + escapeHtml(statusLabel) + '</em></div>' +
                (requester ? '<div><small>' + escapeHtml(isRo ? 'Site solicitant: ' : 'Requester site: ') + '</small>' + linkifySafeText(requester, true) + '</div>' : '') +
                (counterparty ? '<div><small>' + escapeHtml(isRo ? 'Partener: ' : 'Counterparty: ') + '</small>' + linkifySafeText(counterparty, true) + '</div>' : '') +
                (!requester && !counterparty ? '<div>' + linkifySafeText([selectedSource, selectedTarget, selectedAnchor].filter(Boolean).join(' → '), true) + '</div>' : '') +
                (row.readback_status ? '<div class="aysa-agent8v3-link-exchange-readback"><small>' + escapeHtml(isRo ? 'Readback: ' : 'Readback: ') + '</small>' + escapeHtml(row.readback_status) + '</div>' : '') +
                (duplicate ? '<div class="aysa-agent8v3-link-exchange-duplicate">' + escapeHtml(duplicate) + '</div>' : '') +
            '</div>';
        }).join('');
        return '<div class="aysa-agent8v3-message assistant aysa-agent8v3-link-exchange-summary-message">' +
            '<div class="aysa-agent8v3-message-head"><span class="aysa-agent8v3-message-logo">A8</span><span class="aysa-agent8v3-message-role">AYSA Agent 8</span><span class="aysa-agent8v3-status-badge">' + escapeHtml(isRo ? 'Link Exchange' : 'Link Exchange') + '</span></div>' +
            '<div class="aysa-agent8v3-message-card aysa-agent8v3-guidance-card is-review">' +
                '<div class="aysa-agent8v3-guidance-title"><strong>' + escapeHtml((isRo ? 'Schimb de linkuri cu ' : 'Link Exchange with ') + partner) + '</strong><span>' + escapeHtml(isRo ? 'Preflight read-only' : 'Read-only preflight') + '</span></div>' +
                '<p>' + escapeHtml(isRo ? 'Am găsit cererile existente. Nu am creat o cerere nouă și nu am consumat credite.' : 'I found the existing requests. I did not create a new request or consume credits.') + '</p>' +
                '<div class="aysa-agent8v3-guidance-checklist"><span class="is-complete">' + escapeHtml((isRo ? 'Cereri existente: ' : 'Existing requests: ') + existing) + '</span><span class="is-complete">' + escapeHtml((isRo ? 'Schimburi verificate: ' : 'Verified exchanges: ') + verified) + '</span><span class="is-complete">' + escapeHtml((isRo ? 'Arhivate/duplicate: ' : 'Archived/duplicates: ') + archived) + '</span><span class="is-complete">0 credite</span></div>' +
                (requestHtml ? '<details class="aysa-agent8v3-guidance-details" open><summary>' + escapeHtml(isRo ? 'Vezi cererile' : 'View requests') + '</summary><div class="aysa-agent8v3-guidance-review-grid">' + requestHtml + '</div></details>' : '') +
                '<div class="aysa-agent8v3-guidance-review-note"><span>' + escapeHtml(isRo ? 'Crearea unei cereri noi' : 'New request creation') + '</span><strong>' + escapeHtml(isRo ? 'Dezactivată în versiunea beta' : 'Disabled in beta') + '</strong></div>' +
                '<p class="aysa-agent8v3-guidance-review-instruction">' + escapeHtml(isRo ? 'Nu am apelat providerul și nu am modificat WordPress.' : 'No provider was called and WordPress was not modified.') + '</p>' +
            '</div>' +
        '</div>';
    }

    function renderMessages(options) {
        const preserveScroll = !!(options && options.preserveScroll);
        const currentEl = document.getElementById('aysa-agent8v3-messages');
        const previousScrollTop = currentEl ? currentEl.scrollTop : 0;
        const previousScrollHeight = currentEl ? currentEl.scrollHeight : 0;
        const currentPhaseForMessages = state.canonical && state.canonical.phase ? String(state.canonical.phase) : '';
        const visibleMessages = isActivationLikePhase(currentPhaseForMessages)
            ? state.messages.filter(function(message) {
                return !isSeoModuleGuidanceMessage(message);
            })
            : (isMonitoringConversationPhase(currentPhaseForMessages)
                ? state.messages.filter(function(message) {
                    return !isMonitoringGuidanceMessage(message);
                })
                : (currentPhaseForMessages.indexOf('technical_seo') !== -1
                    ? state.messages.filter(function(message) {
                        return !isStaleTechnicalNoAutoApplyMessage(message);
                    })
                    : state.messages));
        let lastAssistantIndex = -1;
        let lastGuidanceIndex = -1;
        visibleMessages.forEach(function(message, index) {
            if (String(message.role || '') === 'assistant') {
                lastAssistantIndex = index;
                if (message.guidance && typeof message.guidance === 'object') {
                    lastGuidanceIndex = index;
                }
            }
        });

        const messageHtml = visibleMessages.map(function(message, index) {
            const role = String(message.role || 'system');
            const phase = message.phase || (state.canonical && state.canonical.phase) || '';
            const status = message.status || 'completed';
            if (role === 'user' || role === 'qa user' || role === 'qa stress user') {
                return '<div class="aysa-agent8v3-message user">' +
                    '<div class="aysa-agent8v3-message-body">' + linkifySafeText(message.body, false) + '</div>' +
                '</div>';
            }
            if (role === 'execution') {
                return '<div class="aysa-agent8v3-message qa">' +
                    '<div class="aysa-agent8v3-message-head">' +
                        '<span class="aysa-agent8v3-message-logo">A8</span>' +
                        '<span class="aysa-agent8v3-message-role">AYSA Agent 8</span>' +
                        '<span class="aysa-agent8v3-status-badge">Executing</span>' +
                    '</div>' +
                    '<div class="aysa-agent8v3-message-card">' +
                        '<div class="aysa-agent8v3-action-title"><strong>Stress Test Execution</strong><span class="aysa-agent8v3-active-pill"><span></span>Running</span></div>' +
                        '<pre class="aysa-agent8v3-terminal">' + escapeHtml(message.body) + '</pre>' +
                    '</div>' +
                '</div>';
            }
            if (role === 'worker') {
                return workerTaskHtml(message.worker || {});
            }
            const assistantHtml = '<div class="aysa-agent8v3-message ' + escapeHtml(role === 'assistant' ? 'assistant' : role.indexOf('qa') === 0 ? 'qa' : 'system') + '">' +
                '<div class="aysa-agent8v3-message-head">' +
                    '<span class="aysa-agent8v3-message-logo">A8</span>' +
                    '<span class="aysa-agent8v3-message-role">' + escapeHtml(role.indexOf('qa') === 0 ? 'QA Runner' : role === 'assistant' ? 'AYSA Agent 8' : 'system') + '</span>' +
                    (role === 'assistant' && index === lastAssistantIndex ? '<span class="aysa-agent8v3-status-badge">' + escapeHtml(statusLabel(status, phase)) + '</span>' : '') +
                '</div>' +
                '<div class="aysa-agent8v3-message-card">' +
                    '<div class="aysa-agent8v3-message-body">' + (message.isThinking ? thinkingMessageHtml(message) : linkifySafeText(clientFacingMessageBody(message.body), true)) + '</div>' +
                '</div>' +
            '</div>';
            const guidanceHtml = '';
            return assistantHtml + guidanceHtml;
        }).join('');
        const ragHtml = state.ragContexts.map(ragContextHtml).join('');
        const currentPhase = state.canonical && state.canonical.phase ? String(state.canonical.phase) : '';
        const exchangeSummaryHtml = offpageLinkExchangeRequestSummaryHtml(state.offpageLinkExchangePreflight);
        const guidanceAsChat = guidanceIsTextOnlyMessage(currentPhase, state.guidance);
        const guidanceInConversation = guidanceRendersInConversation(currentPhase, state.guidance);
        const guidanceInActionsOnly = (currentPhase.indexOf('technical_seo') !== -1 && currentPhase !== 'technical_seo_ready')
            || currentPhase.indexOf('onpage_seo') === 0;
        const technicalReviewSummaryHtml = technicalSeoReviewChatMessageHtml(state.guidance, visibleMessages);
        const monitoringEntryHtml = monitoringEntryCardHtml(currentPhase);
        const guidanceHtml = exchangeSummaryHtml || guidanceAsChat || monitoringEntryHtml || guidanceInActionsOnly ? '' : phaseGuidanceCardHtml(state.guidance, state.externalAction, state.guidanceCollapsed);
        const guidanceDialogueHtml = exchangeSummaryHtml || guidanceAsChat || guidanceInConversation || guidanceInActionsOnly ? '' : guidanceDialogueMessageHtml(state.guidance);
        const html = messageHtml + technicalReviewSummaryHtml + ragHtml + exchangeSummaryHtml + monitoringEntryHtml + guidanceHtml + guidanceDialogueHtml;
        $('#aysa-agent8v3-messages').html(html);
        const el = document.getElementById('aysa-agent8v3-messages');
        if (el) {
            if (preserveScroll) {
                el.scrollTop = previousScrollTop + Math.max(0, el.scrollHeight - previousScrollHeight);
            } else {
                el.scrollTop = el.scrollHeight;
            }
        }
    }

    function thinkingMessageHtml(message) {
        return '<span class="aysa-agent8v3-thinking-text">' + escapeHtml(message.body || 'AYSA gândește') + '</span>' +
            '<span class="aysa-agent8v3-thinking-dots" aria-hidden="true"><span></span><span></span><span></span></span>';
    }

    function addThinkingMessage() {
        removeThinkingMessage();
        const isRo = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const id = addMessage('assistant', isRo ? 'AYSA gândește' : 'AYSA is thinking', {
            id: 'agent8_thinking_' + Date.now(),
            isThinking: true,
            status: 'thinking'
        });
        return id || '';
    }

    function removeThinkingMessage() {
        state.messages = state.messages.filter(function(message) {
            return !message.isThinking;
        });
        renderMessages({ preserveScroll: true });
    }

    function appendAssistantMessage(body, options) {
        const fullBody = String(body || '').trim();
        if (!fullBody) {
            return '';
        }
        if (options && options.instant) {
            return addMessage('assistant', fullBody);
        }
        const id = addMessage('assistant', '');
        typeAssistantMessage(id, fullBody);
        return id;
    }

    function ensureTransientAssistantMessage(body, id) {
        const fullBody = String(body || '').trim();
        if (!fullBody) {
            return '';
        }
        const messageId = id || 'agent8_transient_assistant';
        const exists = state.messages.some(function(message) {
            return String(message.id || '') === messageId;
        });
        if (exists) {
            return messageId;
        }
        state.messages.push({
            id: messageId,
            role: 'assistant',
            body: fullBody,
            phase: state.canonical && state.canonical.phase ? state.canonical.phase : '',
            status: $('[data-agent8v3-status]').attr('data-agent8v3-status') || 'idle',
            created_at: new Date().toISOString(),
            transient: true
        });
        renderMessages();
        return messageId;
    }

    function typeAssistantMessage(id, fullBody) {
        if (!id || !fullBody) {
            return;
        }
        if (state.typewriterTimers[id]) {
            window.clearInterval(state.typewriterTimers[id]);
        }
        let index = 0;
        const step = Math.max(2, Math.min(8, Math.ceil(fullBody.length / 120)));
        state.typewriterTimers[id] = window.setInterval(function() {
            index = Math.min(fullBody.length, index + step);
            const message = state.messages.filter(function(item) {
                return item.id === id;
            })[0];
            if (!message) {
                window.clearInterval(state.typewriterTimers[id]);
                delete state.typewriterTimers[id];
                return;
            }
            message.body = fullBody.slice(0, index);
            renderMessages({ preserveScroll: true });
            if (index >= fullBody.length) {
                window.clearInterval(state.typewriterTimers[id]);
                delete state.typewriterTimers[id];
            }
        }, 18);
    }

    function guidanceIdentity(guidance) {
        if (!guidance || typeof guidance !== 'object') {
            return '';
        }
        if (guidance.guidance_id) {
            return String(guidance.guidance_id);
        }
        return [
            guidance.phase || '',
            guidance.variant || '',
            guidance.status || '',
            guidance.title || ''
        ].map(function(part) {
            return String(part || '');
        }).join(':');
    }

    function guidanceShouldStartCollapsed(guidance) {
        if (!guidance || typeof guidance !== 'object' || !guidance.collapsible) {
            return false;
        }
        if (String(guidance.phase || '') === 'technical_seo_ready') {
            return false;
        }
        const status = String(guidance.status || '').toLowerCase();
        if (guidanceHasActiveQuestion(guidance) && (status === 'collecting' || status === 'needs_input' || status === 'missing')) {
            return false;
        }
        return true;
    }

    function guidanceHasActiveQuestion(guidance) {
        if (!guidance || typeof guidance !== 'object') {
            return false;
        }
        const review = guidance.review && typeof guidance.review === 'object' ? guidance.review : null;
        const dialogue = review && review.dialogue && typeof review.dialogue === 'object' ? review.dialogue : null;
        return !!(
            (review && String(review.next_question || '').trim() !== '') ||
            (dialogue && String(dialogue.question || '').trim() !== '')
        );
    }

    function legacyGuidanceIdentity(guidance) {
        if (!guidance || typeof guidance !== 'object') {
            return '';
        }
        return [
            guidance.variant || '',
            guidance.status || '',
            guidance.title || ''
        ].map(function(part) {
            return String(part || '');
        }).join(':');
    }

    function guidanceMatches(a, b) {
        const aIdentity = guidanceIdentity(a);
        const bIdentity = guidanceIdentity(b);
        if (aIdentity && bIdentity && aIdentity === bIdentity) {
            return true;
        }
        const aLegacy = legacyGuidanceIdentity(a);
        const bLegacy = legacyGuidanceIdentity(b);
        return !!(aLegacy && bLegacy && aLegacy === bLegacy);
    }

    function shouldRenderTranscriptGuidance(guidance, index, lastGuidanceIndex) {
        if (index === lastGuidanceIndex && guidanceMatches(guidance, state.guidance)) {
            return false;
        }
        return true;
    }

    function isWorkerAction(action) {
        return String(action || '') === 'run_worker_ping';
    }

    function beginWorkerTask(action) {
        const id = 'worker_' + Date.now() + '_' + Math.random().toString(16).slice(2);
        const task = {
            id: id,
            action: action,
            label: actionLabel(action),
            progress: 8,
            status: 'running',
            run_id: '',
            task_id: '',
            task_status: 'queued',
            run_status: 'queued',
            artifact_path: '',
            started_at: Date.now(),
            duration_ms: 0,
            error: ''
        };
        state.workerTasks.push(task);
        ensureWorkerMessage(task);
        state.workerTimers[id] = window.setInterval(function() {
            const task = findWorkerTask(id);
            if (!task || task.status !== 'running') {
                clearWorkerTimer(id);
                return;
            }
            task.progress = Math.min(92, task.progress + Math.max(1, Math.round((92 - task.progress) * 0.18)));
            task.duration_ms = Date.now() - task.started_at;
            ensureWorkerMessage(task);
            renderMessages();
        }, 450);
        renderMessages();
        return id;
    }

    function completeWorkerTask(id, response) {
        const task = findWorkerTask(id);
        if (!task) {
            return;
        }
        const debug = response && response.debug ? response.debug : {};
        const worker = debug.worker || {};
        const output = worker.output || {};
        task.run_id = worker.run_id || '';
        task.task_id = worker.task_id || '';
        task.task_status = worker.task_status || '';
        task.run_status = worker.run_status || '';
        task.artifact_path = output.artifact_path || '';
        task.status = worker.task_status === 'completed' ? 'completed' : 'failed';
        task.progress = 100;
        task.duration_ms = Date.now() - task.started_at;
        task.error = worker.error || '';
        clearWorkerTimer(id);
        ensureWorkerMessage(task);
        renderMessages();
    }

    function failWorkerTask(id, error) {
        const task = findWorkerTask(id);
        if (!task) {
            return;
        }
        task.status = 'failed';
        task.progress = 100;
        task.duration_ms = Date.now() - task.started_at;
        task.error = error || 'worker_request_failed';
        clearWorkerTimer(id);
        ensureWorkerMessage(task);
        renderMessages();
    }

    function ensureWorkerMessage(task) {
        const exists = state.messages.some(function(message) {
            return message.role === 'worker' && message.worker && message.worker.id === task.id;
        });
        if (exists) {
            return;
        }
        state.messages.push({
            role: 'worker',
            worker: task,
            phase: state.canonical && state.canonical.phase ? state.canonical.phase : '',
            status: task.status || 'running',
            created_at: new Date().toISOString()
        });
    }

    function findWorkerTask(id) {
        return state.workerTasks.filter(function(task) {
            return task.id === id;
        })[0] || null;
    }

    function clearWorkerTimer(id) {
        if (state.workerTimers[id]) {
            window.clearInterval(state.workerTimers[id]);
            delete state.workerTimers[id];
        }
    }

    function workerTaskHtml(task) {
        const status = task.status || 'running';
        const progress = Math.max(0, Math.min(100, parseInt(task.progress, 10) || 0));
        const rows = [
            ['Run', task.run_id || '-'],
            ['Task', task.task_id || '-'],
            ['Task status', task.task_status || status],
            ['Duration', Math.max(0, Math.round((task.duration_ms || 0) / 1000)) + 's']
        ];
        if (task.artifact_path) {
            rows.push(['Artifact', task.artifact_path]);
        }
        if (task.error) {
            rows.push(['Error', task.error]);
        }
        return '<div class="aysa-agent8v3-message assistant aysa-agent8v3-worker-message">' +
            '<div class="aysa-agent8v3-message-head">' +
                '<span class="aysa-agent8v3-message-logo">A8</span>' +
                '<span class="aysa-agent8v3-message-role">Worker</span>' +
                '<span class="aysa-agent8v3-status-badge">' + escapeHtml(text(status)) + '</span>' +
            '</div>' +
            '<div class="aysa-agent8v3-message-card aysa-agent8v3-worker-card">' +
                '<div class="aysa-agent8v3-worker-title"><strong>' + escapeHtml(task.label || 'Worker task') + '</strong><span>' + escapeHtml(progress + '%') + '</span></div>' +
                '<div class="aysa-agent8v3-worker-progress" aria-label="Worker task progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="' + escapeHtml(progress) + '">' +
                    '<span class="is-' + escapeHtml(status) + '" style="width:' + escapeHtml(progress) + '%"></span>' +
                '</div>' +
                '<div class="aysa-agent8v3-worker-meta">' + rows.map(function(row) {
                    return '<div><span>' + escapeHtml(row[0]) + '</span><strong>' + escapeHtml(row[1]) + '</strong></div>';
                }).join('') + '</div>' +
            '</div>' +
        '</div>';
    }

    function isSameGuidanceOption(option, primaryCta) {
        if (!option || !primaryCta) {
            return false;
        }
        const optionAction = String(option.action || '');
        const primaryAction = String(primaryCta.action || '');
        const optionModal = String(option.modal_key || option.modal || '');
        const primaryModal = String(primaryCta.modal_key || primaryCta.modal || '');
        if (optionAction && optionAction === primaryAction) {
            return JSON.stringify(option.payload || {}) === JSON.stringify(primaryCta.payload || {});
        }
        return Boolean(optionModal && optionModal === primaryModal);
    }

    function guidancePrimaryCtaHtml(primaryCta, externalAction) {
        if (!primaryCta || typeof primaryCta !== 'object') {
            return '';
        }
        const action = String(primaryCta.action || '');
        const modalKey = String(primaryCta.modal_key || primaryCta.modal || '');
        const externalUrl = externalAction && externalAction.url ? String(externalAction.url) : '';
        let display = normalizeActionDisplay(primaryCta.label || actionLabel(action || modalKey), primaryCta.badges || []);
        const onPageContinuation = action === 'start_onpage_seo_run' ? onPageContinuationContext() : null;
        if (onPageContinuation) {
            display = Object.assign({}, display, {
                label: onPageContinuation.label
            });
        }
        if (externalUrl && action === 'prepare_google_connection') {
            return '<span class="aysa-agent8v3-action-with-badges is-header-cta">' +
                '<a class="button button-primary aysa-agent8v3-guidance-option is-primary" target="_blank" rel="noopener noreferrer" href="' + escapeHtml(externalUrl) + '">' + escapeHtml((externalAction && externalAction.label) || display.label) + '</a>' +
                actionBadgesHtml(display.badges) +
            '</span>';
        }
        if (modalKey) {
            return '<span class="aysa-agent8v3-action-with-badges is-header-cta">' +
                '<button type="button" class="button button-primary aysa-agent8v3-guidance-option aysa-agent8v3-modal-open is-primary" data-modal-key="' + escapeHtml(modalKey) + '">' + escapeHtml(display.label || modalKey.replace(/_/g, ' ')) + '</button>' +
                actionBadgesHtml(display.badges) +
            '</span>';
        }
        if (!action || isStatusOnlyAction(action)) {
            return '';
        }
        const payload = actionPayloadForGuidanceButton(action, primaryCta.payload, display.label);
        const nextStepClass = isNextStepTransitionAction(action) ? ' is-next-step-cta' : '';
        return '<span class="aysa-agent8v3-action-with-badges is-header-cta' + nextStepClass + '">' +
            '<button type="button" class="button button-primary aysa-agent8v3-guidance-option aysa-agent8v3-action is-primary' + nextStepClass + '" data-action="' + escapeHtml(action) + '" data-payload="' + escapeHtml(JSON.stringify(payload)) + '">' + escapeHtml(display.label) + '</button>' +
            actionBadgesHtml(display.badges) +
        '</span>';
    }

    function isNextStepTransitionAction(action) {
        return [
            'continue_to_business_profile',
            'confirm_business_profile',
            'confirm_objectives',
            'confirm_seo_profile',
            'confirm_competition_keyword',
            'start_seo_profile',
            'start_competition_keyword',
            'start_tone_of_voice',
            'start_research_handoff',
            'start_keyword_research_run',
            'start_technical_seo_run',
            'start_onpage_seo_run',
            'start_offpage_seo_review',
            'activate_monitoring',
            'open_continuous_optimization'
        ].indexOf(String(action || '')) !== -1;
    }

    function isStatusOnlyAction(action) {
        return /^refresh_/.test(String(action || '')) || /_status$/.test(String(action || ''));
    }

    function isGuidanceTerminal(guidance) {
        const progress = guidance && guidance.progress && typeof guidance.progress === 'object' ? guidance.progress : {};
        const status = String(progress.status || guidance && guidance.status || '').toLowerCase();
        return ['completed', 'complete', 'finalizat', 'completed_with_warnings'].indexOf(status) !== -1;
    }

    function isAnalysisStartAction(action) {
        return /^(run|retry)_/.test(String(action || ''));
    }

    function nextStepHeaderCtaHtml(nextStepCta, externalAction) {
        if (!nextStepCta || typeof nextStepCta !== 'object' || isStatusOnlyAction(nextStepCta.action || '')) {
            return '';
        }
        return guidancePrimaryCtaHtml(nextStepCta, externalAction);
    }

    function phaseGuidanceCardHtml(guidance, externalAction, collapsed) {
        if (!guidance || typeof guidance !== 'object') {
            return '';
        }
        collapsed = !!(collapsed && guidance.collapsible);
        const isTerminal = isGuidanceTerminal(guidance);
        const options = Array.isArray(guidance.options) ? guidance.options : [];
        const primaryCta = guidance.primary_cta && typeof guidance.primary_cta === 'object' ? guidance.primary_cta : null;
        const externalUrl = externalAction && externalAction.url ? String(externalAction.url) : '';
        const buttons = options.filter(function(option) {
            return !isSameGuidanceOption(option, primaryCta);
        }).map(function(option) {
            const action = String(option.action || '');
            const modalKey = String(option.modal_key || option.modal || '');
            if (modalKey) {
                const kind = String(option.kind || 'secondary');
                return '<button type="button" class="button aysa-agent8v3-guidance-option aysa-agent8v3-modal-open is-' + escapeHtml(kind) + '" data-modal-key="' + escapeHtml(modalKey) + '">' +
                    escapeHtml(option.label || modalKey.replace(/_/g, ' ')) +
                '</button>';
            }
            if (!action || (externalUrl && action === 'prepare_google_connection')) {
                return '';
            }
            const kind = String(option.kind || 'secondary');
            const display = normalizeActionDisplay(option.label || actionLabel(action), option.badges || []);
            const payload = actionPayloadForGuidanceButton(action, option.payload, display.label);
            return '<span class="aysa-agent8v3-action-with-badges">' +
                '<button type="button" class="button aysa-agent8v3-guidance-option aysa-agent8v3-action is-' + escapeHtml(kind) + '" data-action="' + escapeHtml(action) + '" data-payload="' + escapeHtml(JSON.stringify(payload)) + '">' +
                    escapeHtml(display.label) +
                '</button>' +
                actionBadgesHtml(display.badges) +
            '</span>';
        }).join('') + (externalUrl && !(primaryCta && String(primaryCta.action || '') === 'prepare_google_connection') ? '<a class="button button-primary aysa-agent8v3-guidance-option is-primary" target="_blank" rel="noopener noreferrer" href="' + escapeHtml(externalUrl) + '">' + escapeHtml((externalAction && externalAction.label) || 'Open Google authorization') + '</a>' : '');
        const primaryAction = primaryCta ? String(primaryCta.action || '') : '';
        const primaryHtml = isTerminal && isAnalysisStartAction(primaryAction) ? '' : (isNextStepTransitionAction(primaryAction) ? '' : guidancePrimaryCtaHtml(primaryCta, externalAction));
        const nextStepHtml = isSameGuidanceOption(guidance.next_step_cta, primaryCta)
            ? ''
            : nextStepHeaderCtaHtml(guidance.next_step_cta, externalAction);

        const hasProgress = guidance.progress && typeof guidance.progress === 'object';
        const hasReview = guidance.review && typeof guidance.review === 'object';
        const hasBody = String(guidance.body || '').trim() !== '';
        if (!buttons && !primaryHtml && !nextStepHtml && !hasProgress && !hasReview && !hasBody) {
            return '';
        }
        const optionsHtml = buttons ? '<div class="aysa-agent8v3-guidance-options">' + buttons + '</div>' : '';
        const bodyHtml = isTerminal && hasReview ? '' : '<p>' + escapeHtml(guidance.body || '') + '</p>';
        const progressHtml = isTerminal && hasReview ? '' : guidanceProgressHtml(guidance.progress);
        return '<div class="aysa-agent8v3-message assistant aysa-agent8v3-guidance-message' + (collapsed ? ' is-collapsed' : '') + (isTerminal ? ' is-terminal' : '') + '">' +
            '<div class="aysa-agent8v3-message-head">' +
                '<span class="aysa-agent8v3-message-logo">A8</span>' +
                '<span class="aysa-agent8v3-message-role">AYSA Agent 8</span>' +
                '<span class="aysa-agent8v3-status-badge">' + escapeHtml(text(guidance.status || 'guidance')) + '</span>' +
            '</div>' +
            '<div class="aysa-agent8v3-message-card aysa-agent8v3-guidance-card is-' + escapeHtml(guidance.variant || 'setup') + '">' +
                '<div class="aysa-agent8v3-guidance-title">' +
                    '<strong>' + escapeHtml(guidance.title || '') + '</strong>' +
                    '<span>' + escapeHtml(text(guidance.status || '')) + '</span>' +
                    primaryHtml +
                    nextStepHtml +
                    (guidance.collapsible ? '<button type="button" class="button-link aysa-agent8v3-guidance-toggle">' + escapeHtml(collapsed ? text('expand') : text('collapse')) + '</button>' : '') +
                '</div>' +
                '<div class="aysa-agent8v3-guidance-content">' +
                    bodyHtml +
                    progressHtml +
                    guidanceReviewHtml(guidance.review, isTerminal) +
                    optionsHtml +
                '</div>' +
            '</div>' +
        '</div>';
    }

    function nextStepGuidanceHtml(nextStepCta, externalAction) {
        if (!nextStepCta || typeof nextStepCta !== 'object' || isStatusOnlyAction(nextStepCta.action || '')) {
            return '';
        }
        const ctaHtml = guidancePrimaryCtaHtml(nextStepCta, externalAction);
        if (!ctaHtml) {
            return '';
        }
        const isRo = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        return '<div class="aysa-agent8v3-message assistant aysa-agent8v3-next-step-message">' +
            '<div class="aysa-agent8v3-action-card aysa-agent8v3-next-step-card">' +
                '<div class="aysa-agent8v3-action-title"><strong>' + escapeHtml(isRo ? 'Următorul pas' : 'Next step') + '</strong></div>' +
                '<div class="aysa-agent8v3-action-buttons">' + ctaHtml + '</div>' +
            '</div>' +
        '</div>';
    }

    function setupObservabilityHtml(canonical, projection) {
        projection = projection || {};
        const phase = String(projection.phase || (canonical && canonical.phase) || '');
        const setupPhases = ['google_integrations', 'business_profile', 'objectives', 'seo_profile', 'competition_keyword', 'tone_of_voice', 'research_handoff_ready', 'research_handoff_running', 'research_handoff_complete'];
        if (setupPhases.indexOf(phase) === -1) {
            return '';
        }
        const diagnostics = state.setupDiagnostics && typeof state.setupDiagnostics === 'object' ? state.setupDiagnostics : {};
        const legacy = diagnostics.legacy_commit || state.legacyCommit || {};
        const legacySync = diagnostics.legacy_sync || {};
        const dataSource = diagnostics.data_source || {};
        const isRo = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const steps = [
            ['google_integrations', 'Google'],
            ['business_profile', 'Business Profile'],
            ['objectives', 'Objectives'],
            ['seo_profile', 'SEO Profile'],
            ['competition_keyword', 'Competition & Keywords'],
            ['tone_of_voice', 'Tone of Voice'],
            ['research_handoff_ready', 'Research Handoff']
        ];
        const activeIndex = setupStepIndex(phase);
        const stepHtml = steps.map(function(step, index) {
            const stateClass = index < activeIndex ? 'is-done' : (index === activeIndex ? 'is-active' : 'is-pending');
            return '<span class="aysa-agent8v3-setup-step ' + stateClass + '">' + escapeHtml(step[1]) + '</span>';
        }).join('');
        const warning = String(legacySync.warning || '');
        const rows = [
            [isRo ? 'Etapă' : 'Step', phase ? phase.replace(/_/g, ' ') : '-'],
            [isRo ? 'Date principale' : 'Main data', dataSource.canonical ? (isRo ? 'pregătite' : 'ready') : (isRo ? 'în lucru' : 'in progress')],
            [isRo ? 'Salvare locală' : 'Local save', String(legacy.status || 'not available') === 'not available' ? (isRo ? 'în așteptare' : 'pending') : (isRo ? 'actualizată' : 'updated')],
            [isRo ? 'Verificare' : 'Check', legacySync.ok === false ? (isRo ? 'necesită atenție' : 'needs attention') : 'ok']
        ];
        return '<div class="aysa-agent8v3-setup-observability">' +
            '<div class="aysa-agent8v3-setup-steps">' + stepHtml + '</div>' +
            (warning ? '<div class="aysa-agent8v3-setup-warning">' + escapeHtml(warning) + '</div>' : '') +
            '<div class="aysa-agent8v3-setup-diagnostics">' + rows.map(function(row) {
                return '<span><small>' + escapeHtml(row[0]) + '</small><strong>' + escapeHtml(row[1]) + '</strong></span>';
            }).join('') + '</div>' +
        '</div>';
    }

    function renderSetupProgressPanel(canonical, projection) {
        const target = $('#aysa-agent8v3-setup-progress-panel');
        if (!target.length) {
            return;
        }
        projection = projection || {};
        const phase = String(projection.phase || (canonical && canonical.phase) || '');
        const diagnostics = state.setupDiagnostics && typeof state.setupDiagnostics === 'object' ? state.setupDiagnostics : {};
        const legacySync = diagnostics.legacy_sync || {};
        const isRo = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const canonicalMonitoring = canonical && canonical.data && canonical.data.monitoring && typeof canonical.data.monitoring === 'object'
            ? canonical.data.monitoring
            : {};
        const canonicalMonitoringPolicy = canonicalMonitoring.policy && typeof canonicalMonitoring.policy === 'object'
            ? canonicalMonitoring.policy
            : {};
        const canonicalMonitoringActive = !!canonicalMonitoringPolicy.enabled
            && ['active', 'confirmed'].indexOf(String(canonicalMonitoringPolicy.status || canonicalMonitoring.policy_status || '')) !== -1
            && !!canonicalMonitoringPolicy.auto_execute_within_policy;
        const monitoringModalOpen = state.modal
            && state.modal.key === 'monitoring'
            && state.modal.current
            && String(state.modal.current.modal_key || '') === 'monitoring';
        const monitoringWorkspaceActive = monitoringModalOpen || canonicalMonitoringActive;
        const monitoringStatusModel = monitoringModalOpen
            && state.modal.current.monitoring_status_model
            && typeof state.modal.current.monitoring_status_model === 'object'
            ? state.modal.current.monitoring_status_model
            : (canonicalMonitoringActive ? {
                policy_active: true,
                message: isRo ? 'Monitorizare automată activă' : 'Automatic monitoring active',
                next_check_at: String((canonicalMonitoringPolicy.next_due_at_by_source && (canonicalMonitoringPolicy.next_due_at_by_source.serp || canonicalMonitoringPolicy.next_due_at_by_source.gsc)) || '')
            } : {});
        $('.aysa-agent8v3-progress-panel-head h2').text(isRo ? 'Progres Agent8' : 'Agent8 progress');
        $('.aysa-agent8v3-progress-panel-head p').text(isRo ? 'Îți arătăm unde ești și ce urmează.' : 'See where you are and what comes next.');
        const progressGroups = setupProgressGroups(isRo);
        const steps = progressGroups.reduce(function(all, group) {
            return all.concat(group.steps || []);
        }, []);
        if (isActivationLikePhase(phase)) {
            const activationTitle = isRo ? 'Înainte de activare' : 'Before activation';
            const activationState = phase === 'activation_failed'
                ? (isRo ? 'Cheia trebuie verificată din nou' : 'The key needs to be checked again')
                : (isRo ? 'Așteaptă cheia' : 'Waiting for key');
            target.html(
                '<div class="aysa-agent8v3-progress-summary is-preactivation">' +
                    '<span>' + escapeHtml(activationTitle) + '</span>' +
                    '<strong>' + escapeHtml(activationState) + '</strong>' +
                    '<p>' + escapeHtml(isRo ? 'Fără audituri / fără credite / fără modificări.' : 'No audits / no credits / no changes.') + '</p>' +
                '</div>' +
                '<div class="aysa-agent8v3-progress-groups">' +
                    '<section class="aysa-agent8v3-progress-group is-active">' +
                        '<div class="aysa-agent8v3-progress-group-head">' +
                            '<strong>' + escapeHtml(activationTitle) + '</strong>' +
                            '<small>' + escapeHtml(isRo ? 'În lucru' : 'In progress') + '</small>' +
                        '</div>' +
                        '<ol class="aysa-agent8v3-progress-steps">' +
                            '<li class="is-active" aria-current="step">' +
                                '<span class="aysa-agent8v3-progress-dot"><i></i></span>' +
                                '<span><strong>' + escapeHtml(isRo ? 'Activare AYSA' : 'AYSA activation') + '</strong><small>' + escapeHtml(activationState) + '</small></span>' +
                            '</li>' +
                            '<li class="is-pending">' +
                                '<span class="aysa-agent8v3-progress-dot"></span>' +
                                '<span><strong>' + escapeHtml(isRo ? 'Setup inițial' : 'Initial setup') + '</strong><small>' + escapeHtml(isRo ? 'Urmează după activare' : 'Next after activation') + '</small></span>' +
                            '</li>' +
                        '</ol>' +
                    '</section>' +
                '</div>'
            );
            return;
        }
        const progressState = setupProgressState(canonical || {}, phase, steps.length);
        const activeIndex = progressState.index;
        const isFlowComplete = progressState.complete;
        const boundedIndex = Math.max(0, Math.min(activeIndex, steps.length - 1));
        const currentStep = isFlowComplete ? null : steps[boundedIndex];
        const nextStep = isFlowComplete ? null : steps[Math.min(boundedIndex + 1, steps.length - 1)];
        const primaryCta = state.guidance && state.guidance.primary_cta && typeof state.guidance.primary_cta === 'object' ? state.guidance.primary_cta : null;
        const ctaHtml = !guidanceRendersInConversation(phase, state.guidance) && primaryCta && !isStatusOnlyAction(primaryCta.action || '') ? guidancePrimaryCtaHtml(primaryCta, state.externalAction) : '';
        const warning = !!(progressState.warning || (legacySync && legacySync.ok === false));
        const activeStepText = phase === 'research_handoff_complete' || /_review$/.test(phase || '')
            ? (isRo ? 'Necesită verificare' : 'Needs review')
            : (/_ready$/.test(phase || '') ? (isRo ? 'Pregătit' : 'Ready') : (isRo ? 'În lucru' : 'In progress'));
        const guidanceProgress = state.guidance && state.guidance.progress && typeof state.guidance.progress === 'object' ? state.guidance.progress : null;
        const progressBarHtml = guidanceProgress ? rightPanelProgressHtml(guidanceProgress, isRo) : '';
        let stepOffset = 0;
        const stepHtml = progressGroups.map(function(group) {
            const groupStart = stepOffset;
            const groupEnd = groupStart + (group.steps || []).length - 1;
            const groupWarning = progressGroupHasWarning(group, canonical || {});
            let groupClass = groupWarning ? 'is-active' : (isFlowComplete || activeIndex > groupEnd ? 'is-done' : (boundedIndex >= groupStart && boundedIndex <= groupEnd ? 'is-active' : 'is-pending'));
	            const technicalReviewGroup = group && group.key === 'technical_seo' && groupWarning;
	            let groupStateText = groupClass === 'is-done'
	                ? (isRo ? 'Finalizat' : 'Done')
	                : (technicalReviewGroup
	                    ? (isRo ? 'Audit finalizat, review necesar' : 'Audit complete, review needed')
	                    : (groupWarning ? (isRo ? 'Finalizat cu verificări' : 'Done with checks') : (groupClass === 'is-active' ? activeStepText : (isRo ? 'Urmează' : 'Next'))));
            if (monitoringWorkspaceActive && group && group.key === 'monitoring') {
                groupClass = 'is-active';
                groupStateText = String(monitoringStatusModel.message || (isRo ? 'Monitorizare activă' : 'Monitoring active'));
            }
            const items = (group.steps || []).map(function(step, localIndex) {
                const index = groupStart + localIndex;
                const stepState = progressStepState(step, index, activeIndex, boundedIndex, isFlowComplete, canonical || {}, isRo);
                const stateClass = stepState.stateClass;
                const currentAttr = stateClass === 'is-active' ? ' aria-current="step"' : '';
                const stateText = stepState.stateText || (stateClass === 'is-done'
                    ? (isRo ? 'Finalizat' : 'Done')
                    : (stateClass === 'is-active' ? activeStepText : (isRo ? 'Urmează' : 'Next')));
                const stepLabelHtml = progressStepButtonHtml(group, step) || '<strong>' + escapeHtml(step.label) + '</strong>';
                return '<li class="' + stateClass + '"' + currentAttr + '>' +
                    '<span class="aysa-agent8v3-progress-dot">' + (stateClass === 'is-active' && stepState.showLoader ? '<i></i>' : '') + '</span>' +
                    '<span>' + stepLabelHtml + '<small>' + escapeHtml(stateText) + '</small></span>' +
                '</li>';
            }).join('');
            stepOffset += (group.steps || []).length;
            return '<section class="aysa-agent8v3-progress-group ' + groupClass + '">' +
                '<div class="aysa-agent8v3-progress-group-head">' +
                    '<strong>' + escapeHtml(group.label) + '</strong>' +
                    '<small>' + escapeHtml(groupStateText) + '</small>' +
                '</div>' +
                '<ol class="aysa-agent8v3-progress-steps">' + items + '</ol>' +
            '</section>';
        }).join('');
        const statusText = monitoringWorkspaceActive
            ? String(monitoringStatusModel.message || (isRo ? 'Monitorizare' : 'Monitoring'))
            : (warning
            ? (isRo ? 'Necesită atenție' : 'Needs attention')
            : (progressState.status || (isFlowComplete ? (isRo ? 'Flow finalizat' : 'Flow complete') : (isRo ? 'În lucru' : 'In progress'))));
        const guidanceActiveTask = guidanceProgress && guidanceProgress.active_task ? String(guidanceProgress.active_task) : '';
        const nowText = monitoringWorkspaceActive
            ? (isRo ? 'Monitorizare & Evoluție' : 'Monitoring & Evolution')
            : (guidanceActiveTask && phase.indexOf('technical_seo') !== -1
            ? guidanceActiveTask
            : (isFlowComplete
                ? (isRo ? 'Flow-ul principal este finalizat.' : 'The main flow is complete.')
                : ((isRo ? 'Acum: ' : 'Now: ') + currentStep.label)));
        const nextText = monitoringWorkspaceActive
            ? String(monitoringStatusModel.next_check_at
                ? ((isRo ? 'Următoarea verificare: ' : 'Next check: ') + monitoringDisplayDate(monitoringStatusModel.next_check_at))
                : (monitoringStatusModel.next_check_reason || (isRo ? 'Verifică starea fiecărei surse.' : 'Review each source status.')))
            : (isFlowComplete
            ? (isRo ? 'Poți continua cu optimizările recurente.' : 'You can continue with recurring optimization.')
            : ((isRo ? 'Urmează: ' : 'Next: ') + (nextStep && nextStep.key !== currentStep.key ? nextStep.label : (isRo ? 'verificarea pasului curent' : 'review this step'))));
        const moduleDrawerHtml = globalModuleDrawerHtml(canonical || {}, isRo);
        const technicalReviewLinksHtml = technicalProgressReviewLinksHtml(canonical || {}, isRo);
        const monitoringReviewLinksHtml = monitoringProgressReviewLinksHtml(canonical || {}, isRo);
        target.html(
            '<div class="aysa-agent8v3-progress-summary ' + (warning ? 'has-warning' : '') + '">' +
                '<span>' + escapeHtml(statusText) + '</span>' +
                '<strong>' + escapeHtml(nowText) + '</strong>' +
                '<p>' + escapeHtml(warning ? (progressState.message || (isRo ? 'Unele date trebuie verificate înainte de continuare.' : 'Some details need review before continuing.')) : nextText) + '</p>' +
                progressBarHtml +
            '</div>' +
            '<div class="aysa-agent8v3-progress-groups">' + stepHtml + '</div>' +
            moduleDrawerHtml +
            technicalReviewLinksHtml +
            monitoringReviewLinksHtml +
            (ctaHtml ? '<div class="aysa-agent8v3-progress-next"><small>' + escapeHtml(isRo ? 'Următorul pas' : 'Next step') + '</small>' + ctaHtml + '</div>' : '')
        );
        restoreOnPageAnalysisApproval();
    }

    function globalModuleDrawerHtml(canonical, isRo) {
        const phase = String(canonical && canonical.phase ? canonical.phase : '');
        if (phase.indexOf('pre_activation') !== -1 || phase.indexOf('activation') !== -1) {
            return '';
        }
        const items = globalModuleDrawerItems(canonical || {}, isRo).filter(function(item) {
            return ['monitoring', 'technical_site_audit', 'onpage_seo', 'content_plan', 'offpage_seo', 'research_keywords', 'keyword_mapping'].indexOf(String(item.modalKey || '')) !== -1 &&
                (!isMonitoringConversationPhase(phase) || String(item.modalKey || '') !== 'monitoring');
        });
        if (!items.length) {
            return '';
        }
        return '<details class="aysa-agent8v3-module-drawer" aria-label="' + escapeHtml(isRo ? 'Module AYSA' : 'AYSA modules') + '">' +
            '<summary><strong>' + escapeHtml(isRo ? 'Module AYSA' : 'AYSA modules') + '</strong>' +
                '<small>' + escapeHtml(isRo ? 'Deschide un singur spațiu de review' : 'Open one review workspace') + '</small></summary>' +
            '<div class="aysa-agent8v3-module-drawer-list">' + items.map(function(item) {
                const unavailable = !item.modalKey;
                const filterAttrs = item.filters && typeof item.filters === 'object'
                    ? Object.keys(item.filters).map(function(filterKey) {
                        return ' data-modal-filter-' + escapeHtml(filterKey) + '="' + escapeHtml(item.filters[filterKey]) + '"';
                    }).join('')
                    : '';
                const attrs = unavailable
                    ? ' disabled aria-disabled="true"'
                    : ' data-modal-key="' + escapeHtml(item.modalKey) + '"' + (item.tab ? ' data-modal-tab="' + escapeHtml(item.tab) + '"' : '') + filterAttrs;
                const classes = 'button aysa-agent8v3-module-drawer-item' + (unavailable ? ' is-disabled' : ' aysa-agent8v3-workspace-open');
                return '<button type="button" class="' + classes + '"' + attrs + '>' +
                    '<span class="aysa-agent8v3-module-drawer-main">' +
                        '<strong>' + escapeHtml(item.label) + '</strong>' +
                        '<small>' + escapeHtml(item.description) + '</small>' +
                    '</span>' +
                    '<span class="aysa-agent8v3-module-drawer-meta">' +
                        '<em>' + escapeHtml(item.status) + '</em>' +
                        '<small>' + escapeHtml(item.safety) + '</small>' +
                    '</span>' +
                '</button>';
            }).join('') + '</div>' +
        '</details>';
    }

    function globalModuleDrawerItems(canonical, isRo) {
        const data = canonical && canonical.data && typeof canonical.data === 'object' ? canonical.data : {};
        const decisions = canonical && canonical.decisions && typeof canonical.decisions === 'object' ? canonical.decisions : {};
        const phase = String(canonical && canonical.phase ? canonical.phase : '');
	        const statusFor = function(key, fallback) {
	            const source = data[key] && typeof data[key] === 'object' ? data[key] : {};
	            const review = source.review && typeof source.review === 'object' ? source.review : {};
	            if (key === 'technical_seo' && String(review.status || '') === 'completed') {
	                return isRo ? 'Review finalizat' : 'Review complete';
	            }
	            const status = String(source.status || source.run_status || source.phase || '');
	            if (status !== '') {
	                if (status === 'completed_with_warnings') {
	                    if (key === 'technical_seo') {
	                        return isRo ? 'Audit finalizat, review necesar' : 'Audit complete, review needed';
	                    }
	                    return isRo ? 'Finalizat cu verificări' : 'Completed with checks';
	                }
                return clientFacingLabel(status.replace(/_/g, ' '));
            }
            return fallback;
        };
        const ready = isRo ? 'Disponibil' : 'Available';
        const noDebit = isRo ? 'Fără debit la deschidere' : 'No debit on open';
        const approval = isRo ? 'Necesită aprobare pentru execuție' : 'Execution requires approval';
        const readonly = isRo ? 'Fără cost / doar verificare' : 'Read-only';
        const unavailable = isRo ? 'Indisponibil momentan' : 'Currently unavailable';
        const items = [
            {
                label: isRo ? 'Monitoring & Evoluție' : 'Monitoring & Evolution',
                description: isRo ? 'Poziții SERP, Search Console și AI sunt surse separate. Refresh-ul cere aprobare.' : 'SERP positions, Search Console, and AI are separate sources. Refresh requires approval.',
                status: statusFor('monitoring', ready),
                safety: noDebit,
                modalKey: 'monitoring',
                tab: 'overview'
            },
            {
                label: 'Technical SEO',
                description: isRo ? 'Review tehnic, probleme, PageSpeed, Schema, sitemap, redirecturi și imagini.' : 'Technical review, issues, PageSpeed, Schema, sitemap, redirects and images.',
                status: statusFor('technical_seo', ready),
                safety: approval,
                modalKey: 'technical_site_audit',
                tab: 'safe_bundle'
            },
            {
                label: 'On Page SEO',
                description: isRo ? 'Review pentru mapping, metadata, conținut, AEO, linkuri și alt text.' : 'Review mapping, metadata, content, AEO, links and alt text.',
                status: statusFor('onpage_seo', ready),
                safety: approval,
                modalKey: 'onpage_seo',
                tab: 'overview'
            },
            {
                label: isRo ? 'Targeturi & pagini lipsă' : 'Targets & missing pages',
                description: isRo ? 'Maparea cuvintelor-cheie către pagini și paginile noi care merită planificate.' : 'Keyword-to-page mapping and new pages worth planning.',
                status: ready,
                safety: noDebit,
                modalKey: 'missing_pages'
            },
            {
                label: 'Content Plan',
                description: isRo ? 'Idei aprobate pentru conținut; generarea și publicarea sunt pași separați.' : 'Approved content ideas; generation and publishing are separate steps.',
                status: statusFor('content_plan', ready),
                safety: approval,
                modalKey: 'content_plan',
                tab: 'overview'
            },
            {
                label: 'Off Page SEO',
                description: isRo ? 'Plan autoritate, publisheri, Link Exchange, SEO Text Ads și GBP separat când există conexiune.' : 'Authority plan, publishers, Link Exchange, SEO Text Ads, and separate GBP when connected.',
                status: statusFor('offpage_seo', ready),
                safety: approval,
                modalKey: 'offpage_seo',
                tab: 'overview'
            },
            {
                label: isRo ? 'Backlink Audit' : 'Backlink Audit',
                description: isRo ? 'Raportul actual de linkuri este primul pas pentru Planul de autoritate. Auditul nou cere cost și aprobare separate.' : 'The current link report is the first step for the Authority Plan. A fresh audit needs separate cost and approval.',
                status: ready,
                safety: noDebit,
                modalKey: 'offpage_seo',
                tab: 'backlink_audit'
            },
            {
                label: isRo ? 'Plan de autoritate' : 'Authority plan',
                description: isRo ? 'Recomandări de linkuri și costuri estimate, fără comandă la deschidere.' : 'Link recommendations and estimated costs, without ordering on open.',
                status: ready,
                safety: noDebit,
                modalKey: 'offpage_seo',
                tab: 'link_building_plan'
            },
            {
                label: isRo ? 'Monitorizare linkuri' : 'Link Monitoring',
                description: isRo ? 'Readback pentru linkurile publicate și sursele monitorizate.' : 'Readback for published links and monitored sources.',
                status: ready,
                safety: readonly,
                modalKey: 'offpage_seo',
                tab: 'link_monitoring'
            },
            {
                label: isRo ? 'Linkuri lunare incluse' : 'Included Monthly Links',
                description: isRo ? 'Quota lunară, sloturi și status scheduler, fără consum extra la deschidere.' : 'Monthly quota, slots and scheduler status, without extra consumption on open.',
                status: ready,
                safety: noDebit,
                modalKey: 'offpage_seo',
                tab: 'included_links'
            },
            {
                label: isRo ? 'Articole publisher' : 'Publisher Articles',
                description: isRo ? 'Comenzi și plasări publisher, cu aprobare separată pentru publicare/billing.' : 'Publisher orders and placements, with separate publish/billing approval.',
                status: ready,
                safety: approval,
                modalKey: 'offpage_seo',
                tab: 'publisher_articles'
            },
            {
                label: isRo ? 'Reclame text SEO - verificare' : 'SEO text ads - readiness',
                description: isRo ? 'Preview și status pentru reclame text SEO lunare.' : 'Preview and status for monthly SEO text ads.',
                status: ready,
                safety: approval,
                modalKey: 'offpage_seo',
                tab: 'seo_text_ads',
                filters: {
                    seo_text_ads_preflight: '1'
                }
            },
            {
                label: isRo ? 'Schimb de linkuri' : 'Link Exchange',
                description: isRo ? 'Cereri, obligații și tracking pentru schimburi de linkuri AYSA.' : 'Requests, obligations and tracking for AYSA link exchanges.',
                status: ready,
                safety: approval,
                modalKey: 'offpage_seo',
                tab: 'link_exchange'
            },
            {
                label: isRo ? 'Status comenzi / verificări' : 'Order / verification status',
                description: isRo ? 'Starea comenzilor, verificărilor și plasărilor deja aprobate.' : 'Status of approved orders, checks and placements.',
                status: ready,
                safety: readonly,
                modalKey: 'offpage_seo',
                tab: 'execution_report'
            },
            {
                label: isRo ? 'Cercetare cuvinte-cheie' : 'Keyword Research / Research',
                description: isRo ? 'Cercetarea cuvintelor-cheie și strategia, fără rulare nouă la deschidere.' : 'Keyword research and strategy, without a new run on open.',
                status: statusFor('keyword_research', ready),
                safety: isRo ? 'Necesită cost maxim pentru rulare' : 'Run requires max cost',
                modalKey: 'research_keywords',
                tab: 'overview'
            },
            {
                label: isRo ? 'Mapare cuvinte-cheie către pagini' : 'Keyword-to-page mapping',
                description: isRo ? 'Toate keywordurile principale, cu targetul valid, remaparea necesară sau ruta către Content Plan.' : 'All primary keywords, with a valid target, required remapping, or the Content Plan route.',
                status: ready,
                safety: readonly,
                modalKey: 'keyword_mapping',
                tab: 'overview'
            },
            {
                label: isRo ? 'Business / SEO Profile' : 'Business / SEO Profile',
                description: isRo ? 'Setup, profil business, obiective, profil SEO și ton.' : 'Setup, business profile, objectives, SEO profile and tone.',
                status: decisions.setup_completed || phase.indexOf('setup') === -1 ? ready : (isRo ? 'În setup' : 'In setup'),
                safety: readonly,
                modalKey: '',
                tab: ''
            },
            {
                label: 'Goal-first SEO',
                description: isRo ? 'Obiective SEO ghidate, disponibile după setup și On Page.' : 'Guided SEO objectives, available after setup and On Page.',
                status: data.goal_first_seo ? (isRo ? 'Fără modal dedicat' : 'No dedicated modal') : unavailable,
                safety: data.goal_first_seo ? (isRo ? 'Deschis prin conversație ghidată' : 'Opened through guided conversation') : (isRo ? 'Setup necesar' : 'Setup required'),
                modalKey: '',
                tab: ''
            }
        ];
        return items;
    }

    function technicalProgressReviewLinksHtml(canonical, isRo) {
        return '';
    }

    function monitoringProgressReviewLinksHtml(canonical, isRo) {
        return '';
    }

    function monitoringProgressStepButtonHtml(group, step) {
        return '';
    }

    function progressStepButtonHtml(group, step) {
        const monitoringButton = monitoringProgressStepButtonHtml(group, step);
        if (monitoringButton) {
            return monitoringButton;
        }
        const groupKey = String((group && group.key) || '');
        const stepKey = String((step && step.key) || '');
        const isMappingStep = (groupKey === 'research' && stepKey === 'keyword_mapping')
            || (groupKey === 'onpage_seo' && stepKey === 'onpage_keyword_mapping');
        if (isMappingStep) {
            return '<button type="button" class="button-link aysa-agent8v3-workspace-open" data-modal-key="keyword_mapping">' +
                escapeHtml(step.label || '') +
            '</button>';
        }
        return '';
    }

    function rightPanelProgressHtml(progress, isRo) {
        const percent = Math.max(0, Math.min(100, parseInt(progress.percent, 10) || 0));
        const status = String(progress.status || 'running');
        const coverageScope = String(progress.coverage_scope || '');
        const percentLabel = coverageScope === 'batch' || coverageScope === 'batch_or_unknown'
            ? percent + '% ' + (isRo ? 'lot' : 'batch')
            : percent + '%';
        const label = progress.active_task
            ? String(progress.active_task)
            : (status === 'completed' ? (isRo ? 'Gata pentru review' : 'Ready for review') : (isRo ? 'Analiza este în lucru' : 'Analysis in progress'));
        return '<div class="aysa-agent8v3-progress-meter">' +
            '<div><span>' + escapeHtml(label) + '</span><strong>' + escapeHtml(percentLabel) + '</strong></div>' +
            '<div class="aysa-agent8v3-worker-progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="' + escapeHtml(percent) + '">' +
                '<span class="is-' + escapeHtml(status) + '" style="width:' + escapeHtml(percent) + '%"></span>' +
            '</div>' +
        '</div>';
    }

    function progressStepState(step, index, activeIndex, boundedIndex, isFlowComplete, canonical, isRo) {
        let stateClass = index < activeIndex || isFlowComplete ? 'is-done' : (index === boundedIndex ? 'is-active' : 'is-pending');
        let stateText = '';
        const technicalMap = {
            technical_overview: 'site_audit',
            technical_pagespeed: 'pagespeed',
            technical_schema: 'schema',
            technical_redirects: 'redirects',
            technical_sitemap_robots: 'sitemap_robots',
            technical_internal_linking: 'internal_linking',
            technical_image_alt: 'image_alt'
        };
        const moduleKey = technicalMap[step && step.key];
        const technical = canonical && canonical.data && canonical.data.technical_seo ? canonical.data.technical_seo : {};
        const technicalReview = technical && technical.review && typeof technical.review === 'object' ? technical.review : {};
        const technicalReviewCompleted = String(technicalReview.status || '') === 'completed';
        const summaryModules = technical && technical.summary && technical.summary.modules ? technical.summary.modules : {};
        const projectionModules = technical && technical.projection && technical.projection.modules ? technical.projection.modules : {};
        const projectionModule = moduleKey && projectionModules[moduleKey] && typeof projectionModules[moduleKey] === 'object' ? projectionModules[moduleKey] : {};
        const directProjectionModule = moduleKey && technical && technical.projection && technical.projection[moduleKey] && typeof technical.projection[moduleKey] === 'object'
            ? technical.projection[moduleKey]
            : {};
        const summaryModule = moduleKey && summaryModules[moduleKey] && typeof summaryModules[moduleKey] === 'object' ? summaryModules[moduleKey] : {};
        const imageOptimizationExecution = technical && technical.fix_execution && technical.fix_execution.image_optimization && typeof technical.fix_execution.image_optimization === 'object'
            ? technical.fix_execution.image_optimization
            : {};
        const imageAltExecution = technical && technical.fix_execution && technical.fix_execution.image_alt && typeof technical.fix_execution.image_alt === 'object'
            ? technical.fix_execution.image_alt
            : {};
        const verifiedWebpCount = parseInt(imageOptimizationExecution.verified_count || 0, 10) || 0;
        const webpExecutionVerified = String(imageOptimizationExecution.status || '') === 'verified'
            && verifiedWebpCount > 0
            && (parseInt(imageOptimizationExecution.failed_count || 0, 10) || 0) === 0;
        const technicalNoSafeInternalLinks = moduleKey === 'internal_linking' && (function() {
            const summary = summaryModule && summaryModule.summary && typeof summaryModule.summary === 'object' ? summaryModule.summary : {};
            const projectionSummary = projectionModule && projectionModule.summary && typeof projectionModule.summary === 'object' ? projectionModule.summary : {};
            const directSummary = directProjectionModule && directProjectionModule.summary && typeof directProjectionModule.summary === 'object' ? directProjectionModule.summary : {};
            const modalRows = state.modal && state.modal.key === 'technical_internal_linking' && state.modal.current && Array.isArray(state.modal.current.rows)
                ? state.modal.current.rows.length
                : 0;
            const inventory = parseInt(summaryModule.inventory_count || summary.inventory_count || summary.inventory_total || projectionSummary.inventory_count || projectionSummary.inventory_total || directProjectionModule.inventory_count || directSummary.inventory_count || directSummary.inventory_total || 0, 10) || 0;
            const opportunities = Math.max(
                parseInt(summaryModule.opportunity_count || summaryModule.preview_links_to_add || summary.opportunity_count || summary.preview_links_to_add || projectionSummary.opportunity_count || projectionSummary.preview_links_to_add || directProjectionModule.opportunity_count || directSummary.opportunity_count || directSummary.preview_links_to_add || 0, 10) || 0,
                Array.isArray(projectionModule.rows) ? projectionModule.rows.length : 0,
                Array.isArray(directProjectionModule.rows) ? directProjectionModule.rows.length : 0,
                projectionModule.preview_package && Array.isArray(projectionModule.preview_package.items) ? projectionModule.preview_package.items.length : 0,
                directProjectionModule.preview_package && Array.isArray(directProjectionModule.preview_package.items) ? directProjectionModule.preview_package.items.length : 0,
                modalRows
            );
            const explicitEmpty = summaryModule.no_safe_opportunities === true
                || projectionModule.no_safe_opportunities === true
                || directProjectionModule.no_safe_opportunities === true
                || ['no_safe_opportunities', 'empty'].indexOf(String(summaryModule.status || projectionModule.status || directProjectionModule.status || '')) !== -1;
            return explicitEmpty && inventory <= 0 && opportunities <= 0;
        })();
        const technicalPageSpeedUnavailable = moduleKey === 'pagespeed' && (function() {
            const statusText = String(summaryModule.status_label || summaryModule.warning || projectionModule.status_label || projectionModule.warning || '').toLowerCase();
            return statusText.indexOf('indisponibil') !== -1 || statusText.indexOf('unavailable') !== -1 || summaryModule.data_available === false || projectionModule.data_available === false;
        })();
        const offpageMap = {
            offpage_gbp: 'google_business_profile',
            offpage_gbp_social: 'gbp_social_calendar',
            offpage_backlink_audit: 'backlink_audit',
            offpage_link_building: 'link_building_plan',
            offpage_link_exchange: 'link_exchange',
            offpage_included_links: 'included_links',
            offpage_link_monitoring: 'link_monitoring',
            offpage_publishers: 'publisher_articles',
            offpage_seo_text_ads: 'order_readiness',
            offpage_execution_report: 'execution_report'
        };
        const offpageModuleKey = offpageMap[step && step.key];
        const offpage = canonical && canonical.data && canonical.data.offpage_seo ? canonical.data.offpage_seo : {};
        const offpageReviewCompleted = String(offpage && offpage.status || '') === 'completed'
            || !!(canonical && canonical.decisions && canonical.decisions.offpage_seo_review_completed);
        const offpageModules = offpage && offpage.modules ? offpage.modules : {};
        const offpageStateSummary = offpage && offpage.offpage_state && offpage.offpage_state.summary ? offpage.offpage_state.summary : {};
        const offpageStateModules = offpageStateSummary && offpageStateSummary.modules ? offpageStateSummary.modules : {};
        const offpageIncluded = offpageStateSummary && offpageStateSummary.included_links ? {included_links: offpageStateSummary.included_links} : {};
        const offpageLinkMonitoring = offpageStateSummary && offpageStateSummary.link_monitoring ? {link_monitoring: offpageStateSummary.link_monitoring} : {};
        const offpageModule = offpageModuleKey && (offpageModules[offpageModuleKey] || offpageStateModules[offpageModuleKey] || offpageIncluded[offpageModuleKey] || offpageLinkMonitoring[offpageModuleKey])
            ? Object.assign({}, offpageModules[offpageModuleKey] || {}, offpageStateModules[offpageModuleKey] || {}, offpageIncluded[offpageModuleKey] || {}, offpageLinkMonitoring[offpageModuleKey] || {})
            : null;
        const monitoringMap = {
            monitoring_rank: 'rank_tracking',
            monitoring_gsc: 'gsc_performance',
            monitoring_ai: 'ai_visibility',
            monitoring_opportunities: 'opportunities',
            monitoring_history: 'history',
            continuous_optimization: 'continuous_optimization'
        };
        const monitoringModuleKey = monitoringMap[step && step.key];
        const monitoring = canonical && canonical.data && canonical.data.monitoring ? canonical.data.monitoring : {};
        const monitoringPolicy = monitoring && monitoring.policy && typeof monitoring.policy === 'object' ? monitoring.policy : {};
        const monitoringPolicyActive = !!monitoringPolicy.enabled
            && ['active', 'confirmed'].indexOf(String(monitoringPolicy.status || monitoring.policy_status || '')) !== -1
            && !!monitoringPolicy.auto_execute_within_policy;
        const monitoringStateModules = monitoring && monitoring.modules ? monitoring.modules : {};
        const modalMonitoringModules = state.modal && state.modal.key === 'monitoring' && state.modal.current && state.modal.current.monitoring_modules ? state.modal.current.monitoring_modules : {};
        const monitoringModule = monitoringModuleKey && (monitoringStateModules[monitoringModuleKey] || modalMonitoringModules[monitoringModuleKey])
            ? Object.assign({}, monitoringStateModules[monitoringModuleKey] || {}, modalMonitoringModules[monitoringModuleKey] || {})
            : null;
        const module = moduleKey && (Object.keys(projectionModule).length || Object.keys(summaryModule).length) ? Object.assign({}, projectionModule, summaryModule) : (offpageModule || monitoringModule);
        if (module) {
            const moduleStatus = String(module.status || '');
	            if (moduleStatus === 'ready' || moduleStatus === 'completed' || moduleStatus === 'ordered') {
	                if (technicalNoSafeInternalLinks) {
	                    stateClass = 'is-active';
	                    stateText = isRo ? 'Fără oportunități sigure' : 'No safe opportunities';
                } else if (technicalPageSpeedUnavailable) {
                    stateClass = 'is-active';
                    stateText = isRo ? 'Date indisponibile' : 'Data unavailable';
                } else if (offpageModuleKey === 'included_links') {
                    stateClass = 'is-done';
                    const used = parseInt(module.quota_used || module.ordered_count || 0, 10) || 0;
                    const total = parseInt(module.quota_total || 0, 10) || 0;
                    stateText = total > 0 ? (isRo ? (used + '/' + total + ' linkuri incluse') : (used + '/' + total + ' included links')) : (isRo ? 'Gata' : 'Ready');
                } else if (offpageModuleKey === 'link_monitoring') {
                    stateClass = 'is-active';
                    const active = parseInt(module.active_count || 0, 10) || 0;
                    const partial = parseInt(module.partial_count || 0, 10) || 0;
                    stateText = active > 0
                        ? (isRo ? (active + ' active · ' + partial + ' parțiale') : (active + ' active · ' + partial + ' partial'))
                        : (isRo ? 'Fără cost / doar verificare' : 'Read-only');
	                } else {
	                    stateClass = 'is-done';
	                    stateText = moduleKey ? (isRo ? 'Verificat în audit' : 'Checked in audit') : (isRo ? 'Gata' : 'Ready');
	                }
            } else if (moduleStatus === 'completed_with_warnings') {
                stateClass = 'is-active';
                if (moduleKey === 'image_alt') {
                    const pending = parseInt(module.pending || 0, 10) || 0;
                    const optimized = parseInt(module.optimized || 0, 10) || 0;
                    stateText = pending > 0
                        ? (isRo ? (pending + ' imagini rămase · ' + optimized + ' optimizate') : (pending + ' images left · ' + optimized + ' optimized'))
                        : (isRo ? 'Necesită verificare' : 'Needs review');
                } else {
                    stateText = isRo ? 'Necesită verificare' : 'Needs review';
                }
            } else if (moduleStatus === 'running') {
                stateClass = 'is-active';
                const checked = parseInt(module.checked || module.processed || 0, 10) || 0;
                const total = parseInt(module.count || module.total || 0, 10) || 0;
                stateText = total > 0 ? (isRo ? (checked + '/' + total + ' verificate') : (checked + '/' + total + ' checked')) : (isRo ? 'Se verifică' : 'Checking');
            } else if (moduleStatus === 'selected' || moduleStatus === 'pending') {
                stateClass = 'is-active';
                stateText = offpageModuleKey === 'included_links' ? (isRo ? 'În așteptare' : 'Pending') : (isRo ? 'În lucru' : 'In progress');
            } else if (moduleStatus === 'inactive') {
                stateClass = 'is-pending';
                stateText = isRo ? 'Inactiv' : 'Inactive';
            } else if (moduleStatus === 'skipped' || moduleStatus === 'unavailable') {
                stateClass = 'is-active';
                stateText = isRo ? 'Necesită verificare' : 'Needs review';
            } else if (moduleStatus === 'blocked') {
                stateClass = 'is-active';
                stateText = moduleKey === 'schema' ? (isRo ? 'Încă verificăm Schema' : 'Still checking Schema') : (isRo ? 'Necesită atenție' : 'Needs attention');
            } else if (moduleStatus === 'failed') {
                stateClass = 'is-active';
                stateText = isRo ? 'Necesită atenție' : 'Needs attention';
            } else if (moduleStatus === 'queued' || moduleStatus === 'pending') {
                stateClass = 'is-pending';
                stateText = isRo ? 'În așteptare' : 'Waiting';
            }
            if (moduleKey === 'image_alt' && webpExecutionVerified) {
                const verifiedAltCount = parseInt(imageAltExecution.verified_count || 0, 10) || 0;
                const altApplyVerified = String(imageAltExecution.status || '') === 'verified'
                    && verifiedAltCount > 0
                    && (parseInt(imageAltExecution.failed_count || 0, 10) || 0) === 0;
                const altCompleted = altApplyVerified;
                stateClass = altCompleted ? 'is-done' : 'is-active';
                stateText = altCompleted
                    ? (isRo ? ('WebP: ' + verifiedWebpCount + ' · ALT finalizat') : ('WebP: ' + verifiedWebpCount + ' · ALT complete'))
                    : (isRo ? ('WebP: ' + verifiedWebpCount + ' finalizate · ALT de verificat') : ('WebP: ' + verifiedWebpCount + ' complete · review ALT'));
            }
	        if (offpageModuleKey && offpageReviewCompleted) {
	            stateClass = 'is-done';
	            stateText = isRo ? 'Revizuit' : 'Reviewed';
	        }
	        if (moduleKey && technicalReviewCompleted) {
	            stateClass = 'is-done';
	            if (!(moduleKey === 'image_alt' && webpExecutionVerified)) {
	                stateText = ['completed_with_warnings', 'blocked', 'skipped', 'unavailable', 'failed_retryable', 'failed_final'].indexOf(String(module && module.status || '')) !== -1
	                    ? (isRo ? 'Revizuit · fără aplicare automată' : 'Reviewed · no automatic apply')
	                    : (isRo ? 'Revizuit' : 'Reviewed');
	            }
	        }
	        }
	        if (offpageReviewCompleted && ['offpage_gbp', 'offpage_gbp_social'].indexOf(String(step && step.key || '')) !== -1) {
	            stateClass = 'is-done';
	            stateText = isRo ? 'Dezactivat pentru lansare' : 'Disabled for launch';
	        }
	        if (monitoringPolicyActive && monitoringModuleKey) {
	            stateClass = 'is-done';
	            if (monitoringModuleKey === 'ai_visibility') {
	                stateText = isRo ? 'Opțional · aprobare separată' : 'Optional · separate approval';
	            } else {
	                const processedMonitoring = parseInt(monitoringModule && monitoringModule.processed || 0, 10) || 0;
	                stateText = processedMonitoring > 0
	                    ? (isRo ? ('Actualizat: ' + processedMonitoring) : ('Updated: ' + processedMonitoring))
	                    : (isRo ? 'Monitorizare automată activă' : 'Automatic monitoring active');
	            }
	        }
        return {
            stateClass: stateClass,
            stateText: stateText,
            showLoader: stateClass === 'is-active' && /_running$/.test(String(canonical.phase || ''))
        };
    }

    function progressGroupHasWarning(group, canonical) {
        if (!group || (group.key !== 'technical_seo' && group.key !== 'offpage_seo' && group.key !== 'monitoring')) {
            return false;
        }
        const root = canonical && canonical.data && canonical.data[group.key] ? canonical.data[group.key] : {};
        if (group.key === 'technical_seo' && root.review && String(root.review.status || '') === 'completed') {
            return false;
        }
        if (group.key === 'offpage_seo' && (String(root.status || '') === 'completed'
            || !!(canonical && canonical.decisions && canonical.decisions.offpage_seo_review_completed))) {
            return false;
        }
        const summaryModules = root && root.summary && root.summary.modules ? root.summary.modules : {};
        const projectionModules = root && root.projection && root.projection.modules ? root.projection.modules : {};
        const stateModules = root && root.modules ? root.modules : {};
        const modules = Object.assign({}, projectionModules || {}, summaryModules || {});
        Object.assign(modules, stateModules || {});
        return Object.keys(modules || {}).some(function(key) {
            return modules[key] && ['completed_with_warnings', 'skipped', 'unavailable', 'failed_retryable', 'failed_final'].indexOf(String(modules[key].status || '')) !== -1;
        });
    }

    function setupProgressGroups(isRo) {
        return [
            {
                key: 'setup',
                label: isRo ? 'Setup inițial' : 'Initial setup',
                steps: [
                    {key: 'google_integrations', label: isRo ? 'Google' : 'Google'},
                    {key: 'business_profile', label: isRo ? 'Profil afacere' : 'Business profile'},
                    {key: 'objectives', label: isRo ? 'Obiective' : 'Objectives'},
                    {key: 'seo_profile', label: isRo ? 'Profil SEO' : 'SEO profile'},
                    {key: 'competition_keyword', label: isRo ? 'Cuvinte cheie' : 'Keywords'},
                    {key: 'tone_of_voice', label: isRo ? 'Ton' : 'Tone'}
                ]
            },
            {
                key: 'research',
                label: isRo ? 'Cercetare și strategie' : 'Research & strategy',
                steps: [
                    {key: 'keyword_research', label: isRo ? 'Cercetare cuvinte-cheie' : 'Keyword Research'},
                    {key: 'research_keywords', label: isRo ? 'Cuvinte-cheie' : 'Keywords'},
                    {key: 'keyword_mapping', label: isRo ? 'Mapare cuvinte-cheie către pagini' : 'Keyword-to-page mapping'},
                    {key: 'missing_pages', label: isRo ? 'Targeturi & pagini lipsă' : 'Targets & missing pages'},
                    {key: 'content_plan', label: isRo ? 'Content Plan' : 'Content Plan'}
                ]
            },
            {
                key: 'technical_seo',
                label: isRo ? 'Technical SEO' : 'Technical SEO',
                steps: [
                    {key: 'technical_overview', label: isRo ? 'Overview / Site Audit' : 'Overview / Site Audit'},
                    {key: 'technical_pagespeed', label: isRo ? 'PageSpeed' : 'PageSpeed'},
                    {key: 'technical_schema', label: isRo ? 'Schema' : 'Schema'},
                    {key: 'technical_redirects', label: isRo ? 'Redirecturi / 404' : 'Redirects / 404'},
                    {key: 'technical_sitemap_robots', label: isRo ? 'Sitemap & Robots' : 'Sitemap & Robots'},
                    {key: 'technical_internal_linking', label: isRo ? 'Internal Linking' : 'Internal Linking'},
                    {key: 'technical_image_alt', label: isRo ? 'Imagini: WebP + texte ALT' : 'Images: WebP + ALT text'}
                ]
            },
            {
                key: 'onpage_seo',
                label: isRo ? 'On Page SEO' : 'On Page SEO',
                steps: [
                    {key: 'onpage_keyword_mapping', label: isRo ? 'Mapare cuvinte-cheie' : 'Keyword Mapping'},
                    {key: 'onpage_meta', label: isRo ? 'Titluri și descrieri' : 'Titles and descriptions'},
                    {key: 'onpage_content', label: isRo ? 'Conținut' : 'Content'},
                    {key: 'onpage_aeo', label: isRo ? 'Întrebări și răspunsuri' : 'Questions and answers'},
                    {key: 'onpage_links', label: isRo ? 'Linkuri interne' : 'Internal links'},
                    {key: 'onpage_alt_text', label: isRo ? 'Texte alternative imagini' : 'Image alternative text'},
                    {key: 'onpage_execution_report', label: isRo ? 'Raport execuție' : 'Execution report'}
                ]
            },
            {
                key: 'offpage_seo',
                label: isRo ? 'Off Page SEO' : 'Off Page SEO',
                steps: [
                    {key: 'offpage_backlink_audit', label: isRo ? 'Backlink Audit' : 'Backlink Audit'},
                    {key: 'offpage_link_building', label: isRo ? 'Plan de autoritate' : 'Authority plan'},
                    {key: 'offpage_link_exchange', label: isRo ? 'Schimb de linkuri' : 'Link exchange'},
                    {key: 'offpage_included_links', label: isRo ? 'Linkuri incluse lunar' : 'Included monthly links'},
                    {key: 'offpage_publishers', label: isRo ? 'Articole publisher' : 'Publisher articles'},
                    {key: 'offpage_seo_text_ads', label: isRo ? 'Reclame text SEO' : 'SEO text ads'},
                    {key: 'offpage_link_monitoring', label: isRo ? 'Monitorizare linkuri' : 'Link monitoring'},
                    {key: 'offpage_execution_report', label: isRo ? 'Raport execuție' : 'Execution report'},
                    {key: 'offpage_gbp', label: isRo ? 'Local: Google Business Profile' : 'Local: Google Business Profile'},
                    {key: 'offpage_gbp_social', label: isRo ? 'Social: Calendar social' : 'Social: Social calendar'}
                ]
            },
            {
                key: 'monitoring',
                label: isRo ? 'Monitorizare & Evoluție' : 'Monitoring & Evolution',
                steps: [
                    {key: 'monitoring_rank', label: isRo ? 'Poziții Google / SERP' : 'Google / SERP positions'},
                    {key: 'monitoring_gsc', label: isRo ? 'Search Console' : 'Search Console'},
                    {key: 'monitoring_ai', label: isRo ? 'Vizibilitate în AI' : 'AI visibility'}
                ]
            }
        ];
    }

    function setupProgressSteps(isRo) {
        return setupProgressGroups(isRo).reduce(function(all, group) {
            return all.concat(group.steps || []);
        }, []);
    }

    function setupProgressState(canonical, phase, totalSteps) {
        const isRo = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const decisions = canonical && canonical.decisions && typeof canonical.decisions === 'object' ? canonical.decisions : {};
        const data = canonical && canonical.data && typeof canonical.data === 'object' ? canonical.data : {};
        const research = data.research_handoff && typeof data.research_handoff === 'object' ? data.research_handoff : {};
        const mappingResolution = research.keyword_mapping_resolution && typeof research.keyword_mapping_resolution === 'object'
            ? research.keyword_mapping_resolution
            : {};
        const mappingSummary = mappingResolution.summary && typeof mappingResolution.summary === 'object'
            ? mappingResolution.summary
            : {};
        const setupConfirmed = !!(
            decisions.business_profile_confirmed &&
            decisions.objectives_confirmed &&
            decisions.seo_profile_confirmed &&
            decisions.competition_keyword_confirmed &&
            decisions.tone_of_voice_selected
        );
        if (/^(technical_|onpage_|offpage_|monitoring_|continuous_optimization)/.test(phase || '')) {
            return {
                index: setupConfirmed ? agent8ProgressIndexForPhase(phase) : 0,
                complete: setupConfirmed && phase === 'continuous_optimization_active',
                warning: !setupConfirmed,
                status: setupConfirmed ? agent8ProgressStatusForPhase(phase, isRo) : (isRo ? 'Necesită verificare' : 'Needs attention'),
                message: setupConfirmed ? '' : (isRo ? 'Setup-ul trebuie verificat înainte de continuare.' : 'Setup must be reviewed before continuing.')
            };
        }
        const order = {
            welcome: 0,
            activation_verified: 0,
            google_integrations: 0,
            business_profile: 1,
            objectives: 2,
            seo_profile: 3,
            competition_keyword: 4,
            tone_of_voice: 5,
            research_handoff_ready: 6,
            research_handoff_running: 6,
            research_handoff_complete: 10
        };
        if (phase === 'research_handoff_complete') {
            const researchStatus = String(research.status || (research.completion && research.completion.status) || '').toLowerCase();
            if (String(mappingSummary.finalization_status || '') === 'needs_verification') {
                const unresolved = Number(mappingSummary.needs_attention || 0);
                return {
                    index: 10,
                    complete: false,
                    warning: true,
                    status: isRo ? 'Necesită verificare' : 'Needs review',
                    message: isRo
                        ? 'Mappingul necesită verificare pentru ' + unresolved + ' keyworduri fără target public valid.'
                        : 'Mapping needs review for ' + unresolved + ' keywords without a valid public target.'
                };
            }
            if (researchStatus === 'failed' || researchStatus === 'blocked') {
                return {
                    index: 6,
                    complete: false,
                    warning: true,
                    status: isRo ? 'Necesită atenție' : 'Needs attention',
                    message: isRo
                        ? 'Keyword Research nu a finalizat curat. Datele parțiale sunt doar pentru diagnostic; nu trecem la Content Plan până nu există rezultat valid.'
                        : 'Keyword Research did not finish cleanly. Partial data is diagnostic only; Content Plan is not unlocked until there is a valid result.'
                };
            }
            if (researchStatus === 'completed_with_warnings') {
                return {
                    index: 10,
                    complete: false,
                    warning: false,
                    status: isRo ? 'În lucru' : 'In progress',
                    message: isRo
                        ? 'Keyword Research este disponibil cu observații. Verifică datele înainte de Content Plan.'
                        : 'Keyword Research is available with warnings. Review the data before Content Plan.'
                };
            }
        }
        if (Object.prototype.hasOwnProperty.call(order, phase)) {
            return {
                index: order[phase],
                complete: false,
                warning: false,
                status: phase === 'activation_verified'
                    ? (isRo ? 'Activarea este verificată' : 'Activation verified')
                    : (phase === 'research_handoff_complete' ? (isRo ? 'Necesită verificare' : 'Needs review') : (isRo ? 'În lucru' : 'In progress')),
                message: ''
            };
        }
        return {
            index: 0,
            complete: false,
            warning: true,
            status: isRo ? 'Necesită verificare' : 'Needs attention',
            message: isRo ? 'Nu putem determina sigur etapa curentă. Verifică pasul afișat în conversație.' : 'We cannot safely detect the current step. Check the step shown in the conversation.'
        };
    }

	    function agent8ProgressIndexForPhase(phase) {
	        const map = {
	            technical_seo_ready: 10,
	            technical_seo_running: 11,
	            technical_seo_review: 11,
	            technical_seo_complete: 18,
            onpage_handoff_ready: 18,
            onpage_seo_ready: 18,
            onpage_seo_running: 18,
            onpage_seo_review: 18,
            onpage_seo_complete: 25,
            offpage_seo_ready: 25,
            offpage_seo_review: 25,
            offpage_seo_complete: 35,
            monitoring_ready: 35,
            monitoring_review: 35,
            monitoring_active: 35,
            continuous_optimization_active: 36
        };
        return Object.prototype.hasOwnProperty.call(map, phase) ? map[phase] : 0;
    }

	    function agent8ProgressStatusForPhase(phase, isRo) {
	        if (phase === 'continuous_optimization_active') {
	            return isRo ? 'Optimizare continuă activă' : 'Continuous optimization active';
	        }
	        if (phase === 'monitoring_active') {
	            return isRo ? 'Monitorizare activă' : 'Monitoring active';
	        }
	        if (phase === 'technical_seo_ready' || phase === 'onpage_seo_ready') {
	            return isRo ? 'Pregătit' : 'Ready';
	        }
	        if (/_(review|ready)$/.test(phase || '')) {
	            return isRo ? 'Necesită verificare' : 'Needs review';
	        }
        if (/_running$/.test(phase || '')) {
            return isRo ? 'În lucru' : 'In progress';
        }
        return isRo ? 'În lucru' : 'In progress';
    }

    function setupStepIndex(phase) {
        if (phase === 'research_handoff_running' || phase === 'research_handoff_complete') {
            return 6;
        }
        const order = ['google_integrations', 'business_profile', 'objectives', 'seo_profile', 'competition_keyword', 'tone_of_voice', 'research_handoff_ready'];
        const index = order.indexOf(phase);
        return index === -1 ? 0 : index;
    }

    function guidanceReviewHtml(review, suppressSecondary) {
        if (!review || typeof review !== 'object') {
            return '';
        }
        suppressSecondary = !!suppressSecondary;
        const rows = Array.isArray(review.rows) ? review.rows : [];
        const checklist = Array.isArray(review.checklist) ? review.checklist : [];
        const details = Array.isArray(review.details) ? review.details : [];
        const missing = Array.isArray(review.missing) ? review.missing : [];
        const warnings = Array.isArray(review.warnings) ? review.warnings : [];
        const selectionGroups = Array.isArray(review.selection_groups) ? review.selection_groups : [];
        const rowHtml = rows.map(function(row) {
            const meta = [row.source || '', row.reason || ''].filter(Boolean).join(' · ');
            return '<div class="aysa-agent8v3-guidance-review-row">' +
                '<span>' + escapeHtml(row.label || '') + '</span>' +
                '<strong>' + escapeHtml(row.value || '-') + '</strong>' +
                (meta ? '<small>' + escapeHtml(meta) + '</small>' : '') +
            '</div>';
        }).join('');
        const selectionHtml = selectionGroups.length ? '<div class="aysa-agent8v3-guidance-selection-groups">' + selectionGroups.map(function(group) {
            const items = Array.isArray(group.items) ? group.items : [];
            if (!items.length) {
                return '';
            }
            return '<div class="aysa-agent8v3-guidance-selection-group">' +
                '<strong>' + escapeHtml(group.title || '') + '</strong>' +
                '<div class="aysa-agent8v3-guidance-selection-list">' + items.map(function(item) {
                    const action = item.action && typeof item.action === 'object' ? item.action : null;
                    const actionName = action ? String(action.action || '') : '';
                    const payload = action && action.payload && typeof action.payload === 'object' ? action.payload : {};
                    const actionButton = actionName
                        ? '<button type="button" class="button-link aysa-agent8v3-action" data-action="' + escapeHtml(actionName) + '" data-payload="' + escapeHtml(JSON.stringify(payload)) + '">' + escapeHtml(action.label || '') + '</button>'
                        : '';
                    return '<span class="aysa-agent8v3-guidance-selection-item is-' + escapeHtml(item.status || 'accepted') + '">' +
                        '<span>' + escapeHtml(item.label || '') + '</span>' +
                        '<em>' + escapeHtml(item.status_label || '') + '</em>' +
                        actionButton +
                    '</span>';
                }).join('') + '</div>' +
            '</div>';
        }).join('') + '</div>' : '';
        const detailsHtml = !suppressSecondary && details.length ? '<details class="aysa-agent8v3-guidance-details"><summary>' + escapeHtml(text('expand')) + '</summary>' +
            '<div class="aysa-agent8v3-guidance-review-grid">' + details.map(function(row) {
                return '<div class="aysa-agent8v3-guidance-review-row">' +
                    '<span>' + escapeHtml(row.label || '') + '</span>' +
                    '<strong>' + escapeHtml(row.value || '-') + '</strong>' +
                '</div>';
            }).join('') + '</div></details>' : '';
        const checklistHtml = checklist.length ? '<div class="aysa-agent8v3-guidance-checklist">' + checklist.map(function(item) {
            return '<span class="is-' + escapeHtml(item.status || 'missing') + '">' + escapeHtml(item.label || item.field || '') + '</span>';
        }).join('') + '</div>' : '';
        const nextHtml = review.next_question ? '<div class="aysa-agent8v3-guidance-next-question">' + escapeHtml(review.next_question) + '</div>' : '';
        const missingHtml = missing.length ? '<div class="aysa-agent8v3-guidance-review-note is-missing"><span>' + escapeHtml(text('missingUncertain')) + '</span><strong>' + escapeHtml(missing.slice(0, 8).map(clientFacingLabel).join(', ')) + '</strong></div>' : '';
        const warningsHtml = warnings.length ? '<div class="aysa-agent8v3-guidance-review-note"><span>' + escapeHtml(text('observations')) + '</span><strong>' + escapeHtml(warnings.map(clientFacingLabel).join(' ')) + '</strong></div>' : '';
        return '<div class="aysa-agent8v3-guidance-review">' +
            '<div class="aysa-agent8v3-guidance-review-title">' + escapeHtml(review.title || 'Result') + '</div>' +
            checklistHtml +
            nextHtml +
            '<div class="aysa-agent8v3-guidance-review-grid">' + rowHtml + '</div>' +
            selectionHtml +
            detailsHtml +
            missingHtml +
            warningsHtml +
            (suppressSecondary ? '' : '<p class="aysa-agent8v3-guidance-review-instruction">' + escapeHtml(review.instruction || '') + '</p>') +
        '</div>';
    }

    function guidanceDialogueMessageHtml(guidance) {
        const review = guidance && guidance.review && typeof guidance.review === 'object' ? guidance.review : null;
        const dialogue = review && review.dialogue && typeof review.dialogue === 'object' ? review.dialogue : null;
        const hasInlineQuestion = !!(review && String(review.next_question || '').trim() !== '');
        if (!dialogue && !hasInlineQuestion) {
            return '';
        }
        const details = dialogue && Array.isArray(dialogue.details) ? dialogue.details : [];
        const missing = dialogue && Array.isArray(dialogue.missing) ? dialogue.missing : [];
        const body = (dialogue ? [
            dialogue.summary || '',
            details.join(' '),
            missing.length ? 'Mai am nevoie punctual de: ' + missing.slice(0, 6).join(', ') + '.' : '',
            dialogue.question || ''
        ] : [
            guidance.body || '',
            review.next_question || ''
        ]).filter(function(part) {
            return String(part || '').trim() !== '';
        });
        if (!body.length) {
            return '';
        }
        return '<div class="aysa-agent8v3-message assistant aysa-agent8v3-guidance-dialogue-message">' +
            '<div class="aysa-agent8v3-message-head">' +
                '<span class="aysa-agent8v3-message-logo">A8</span>' +
                '<span class="aysa-agent8v3-message-role">AYSA Agent 8</span>' +
            '</div>' +
            '<div class="aysa-agent8v3-message-card">' +
                '<div class="aysa-agent8v3-message-body">' + body.map(function(part) {
                    return '<p>' + linkifySafeText(part, true) + '</p>';
                }).join('') + '</div>' +
            '</div>' +
        '</div>';
    }

    function guidanceProgressHtml(progress) {
        if (!progress || typeof progress !== 'object') {
            return '';
        }
        const percent = Math.max(0, Math.min(100, parseInt(progress.percent, 10) || 0));
        const status = String(progress.status || 'running');
        const meta = [];
        if (progress.total_tasks) {
            meta.push((parseInt(progress.completed_tasks, 10) || 0) + '/' + (parseInt(progress.total_tasks, 10) || 0));
        }
        if (progress.eta_label) {
            meta.push(progress.eta_label);
        }
        return '<div class="aysa-agent8v3-guidance-progress">' +
            '<div class="aysa-agent8v3-worker-title">' +
                '<strong>' + escapeHtml(progress.label || text('running')) + '</strong>' +
                '<span>' + escapeHtml(percent + '%') + '</span>' +
            '</div>' +
            '<div class="aysa-agent8v3-worker-progress" aria-label="Business profile progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="' + escapeHtml(percent) + '">' +
                '<span class="is-' + escapeHtml(status) + '" style="width:' + escapeHtml(percent) + '%"></span>' +
            '</div>' +
            '<div class="aysa-agent8v3-guidance-progress-meta">' +
                '<span>' + escapeHtml(progress.active_task || status) + '</span>' +
                '<strong>' + escapeHtml(meta.join(' · ')) + '</strong>' +
            '</div>' +
        '</div>';
    }

    function addRagContextCard(rag) {
        if (!rag || typeof rag !== 'object') {
            return;
        }
        state.ragContexts = [{
            id: 'rag_' + Date.now() + '_' + Math.random().toString(16).slice(2),
            authority: rag.authority || 'context_only',
            sources: Array.isArray(rag.sources) ? rag.sources : [],
            items_count: parseInt(rag.items_count, 10) || (Array.isArray(rag.items) ? rag.items.length : 0),
            availability: rag.availability && typeof rag.availability === 'object' ? rag.availability : {},
            items: Array.isArray(rag.items) ? rag.items.slice(0, 4) : [],
            citations: Array.isArray(rag.citations) ? rag.citations.slice(0, 6) : [],
            writes_state: !!rag.writes_state
        }];
        renderMessages();
    }

    function ragContextHtml(rag) {
        const sources = rag.sources.length ? rag.sources.join(', ') : '-';
        const items = rag.items.map(function(item) {
            const title = item.title || item.type || item.source || 'context';
            const content = truncateText(item.content || '', 220);
            return '<li><strong>' + escapeHtml(title) + '</strong>' + (content ? '<span>' + escapeHtml(content) + '</span>' : '') + '</li>';
        }).join('');
        const citations = rag.citations.map(function(citation) {
            return '<span>' + escapeHtml((citation.source || '-') + ':' + (citation.ref || '-')) + '</span>';
        }).join('');
        const availability = ragAvailabilityHtml(rag.availability || {});
        return '<div class="aysa-agent8v3-message assistant aysa-agent8v3-rag-message">' +
            '<div class="aysa-agent8v3-message-head">' +
                '<span class="aysa-agent8v3-message-logo">A8</span>' +
                '<span class="aysa-agent8v3-message-role">RAG Context</span>' +
                '<span class="aysa-agent8v3-status-badge">' + escapeHtml(rag.authority) + '</span>' +
            '</div>' +
            '<div class="aysa-agent8v3-message-card aysa-agent8v3-rag-card">' +
                '<button type="button" class="aysa-agent8v3-rag-close" data-rag-id="' + escapeHtml(rag.id) + '" aria-label="Close RAG context">×</button>' +
                '<div class="aysa-agent8v3-rag-summary">' +
                    '<div><span>Sources</span><strong>' + escapeHtml(sources) + '</strong></div>' +
                    '<div><span>Items</span><strong>' + escapeHtml(rag.items_count) + '</strong></div>' +
                    '<div><span>Writes state</span><strong>' + escapeHtml(rag.writes_state ? 'yes' : 'no') + '</strong></div>' +
                '</div>' +
                availability +
                (items ? '<ul class="aysa-agent8v3-rag-items">' + items + '</ul>' : '<p class="aysa-agent8v3-rag-empty">No RAG items returned.</p>') +
                (citations ? '<div class="aysa-agent8v3-rag-citations">' + citations + '</div>' : '') +
            '</div>' +
        '</div>';
    }

    function ragAvailabilityHtml(availability) {
        const rows = ['aysa', 'client'].map(function(source) {
            const item = availability[source] || {};
            const status = item.status || 'unknown';
            const reason = item.reason || '';
            const count = item.items_count !== undefined ? item.items_count : '-';
            return '<div class="is-' + escapeHtml(status) + '">' +
                '<strong>' + escapeHtml(source.toUpperCase() + ' RAG') + '</strong>' +
                '<span>' + escapeHtml(status + ' | items ' + count) + '</span>' +
                (reason ? '<em>' + escapeHtml(reason) + '</em>' : '') +
            '</div>';
        }).join('');
        return '<div class="aysa-agent8v3-rag-availability">' + rows + '</div>';
    }

    function truncateText(value, limit) {
        const textValue = String(value || '').replace(/\s+/g, ' ').trim();
        return textValue.length > limit ? textValue.slice(0, limit - 1) + '…' : textValue;
    }

    function addExecutionLog(line) {
        const timestamp = new Date().toTimeString().slice(0, 8);
        appendQaLiveLine('execution', '[' + timestamp + '] ' + line);
    }

    function statusLabel(status, phase) {
        if (isActivationLikePhase(phase)) {
            return text('workspaceAwaitingActivation');
        }
        if (status === 'running' || status === 'thinking') {
            return phase === 'welcome' ? 'Planning' : 'Executing';
        }
        if (status === 'failed') {
            return 'Failed';
        }
        if (phase === 'architecture_verified') {
            return 'Completed';
        }
        return 'Planning';
    }

    function activationVerified(canonical) {
        return !!(canonical && canonical.decisions && canonical.decisions.activation_verified);
    }

    function updateAuthPill(canonical) {
        const canonicalLoaded = !!(canonical && typeof canonical === 'object');
        if (!canonicalLoaded) {
            $('.aysa-agent8v3-auth-pill')
                .removeClass('is-authenticated is-unauthenticated')
                .addClass('is-loading')
                .text(text('modalLoading'));
            const loadingWorkspacePill = $('.aysa-agent8v3-topbar .aysa-agent8v3-active-pill');
            loadingWorkspacePill
                .addClass('is-awaiting-activation')
                .contents()
                .filter(function() { return this.nodeType === 3; })
                .remove();
            loadingWorkspacePill.append(text('modalLoading'));
            return;
        }
        const authenticated = activationVerified(canonical);
        $('.aysa-agent8v3-auth-pill')
            .removeClass('is-loading')
            .toggleClass('is-authenticated', authenticated)
            .toggleClass('is-unauthenticated', !authenticated)
            .text(authenticated ? text('authenticated') : text('unauthenticated'));
        const workspacePill = $('.aysa-agent8v3-topbar .aysa-agent8v3-active-pill');
        workspacePill
            .toggleClass('is-awaiting-activation', !authenticated)
            .contents()
            .filter(function() { return this.nodeType === 3; })
            .remove();
        workspacePill.append(authenticated ? text('workspaceActive') : text('workspaceAwaitingActivation'));
    }

    function canonicalBusinessProfileUnavailableField(value) {
        const key = String(value || '').trim().toLowerCase().replace(/[^a-z0-9_]+/g, '_');
        const aliases = {
            email: 'support_email',
            e_mail: 'support_email',
            mail: 'support_email',
            public_email: 'support_email',
            contact_email: 'support_email',
            email_address: 'support_email',
            supportemail: 'support_email',
            supportemailaddress: 'support_email',
            support_email: 'support_email',
            business_profile_support_email: 'support_email',
            businessprofilesupportemail: 'support_email',
            business_profile_email: 'support_email',
            phone: 'support_phone',
            telefon: 'support_phone',
            tel: 'support_phone',
            support_phone: 'support_phone',
            address: 'address',
            adresa: 'address',
            adres_: 'address',
            locatie: 'address',
            location: 'address'
        };
        return aliases[key] || key;
    }

    function inferBusinessProfileUnavailableFieldFromLabel(label) {
        const text = String(label || '').toLowerCase();
        if (/(e[-\s]?mail|email|mail)/.test(text)) {
            return 'support_email';
        }
        if (/(telefon|phone|tel\b)/.test(text)) {
            return 'support_phone';
        }
        if (/(adres|address|locaț|locat|location)/.test(text)) {
            return 'address';
        }
        return '';
    }

    function onPageContinuationContext() {
        const canonical = state.canonical && typeof state.canonical === 'object' ? state.canonical : {};
        const data = canonical.data && typeof canonical.data === 'object' ? canonical.data : {};
        const onPage = data.onpage_seo && typeof data.onpage_seo === 'object' ? data.onpage_seo : {};
        const summary = onPage.summary && typeof onPage.summary === 'object' ? onPage.summary : {};
        const phase = String(canonical.phase || '');
        const status = String(onPage.status || '');
        const token = String(summary.next_continuation_token || '').trim();
        const unprocessedTotal = Math.max(0, parseInt(summary.unprocessed_total || 0, 10) || 0);
        const running = Math.max(0, parseInt(summary.running || 0, 10) || 0);
        const queued = Math.max(0, parseInt(summary.queued || 0, 10) || 0);
        if (
            phase !== 'onpage_seo_review'
            || ['completed', 'completed_with_warnings'].indexOf(status) === -1
            || token === ''
            || unprocessedTotal <= 0
            || running > 0
            || queued > 0
        ) {
            return null;
        }
        const currentBatchNumber = Math.max(1, parseInt(summary.current_batch_number || 1, 10) || 1);
        const nextBatchNumber = currentBatchNumber + 1;
        const ro = state.language === 'Romanian' || String(uiLanguage() || '').indexOf('ro') === 0;
        return {
            continuation_mode: true,
            continuation_token: token,
            current_batch_number: currentBatchNumber,
            next_batch_number: nextBatchNumber,
            unprocessed_total: unprocessedTotal,
            label: ro ? ('Continuă cu lotul ' + String(nextBatchNumber)) : ('Continue with batch ' + String(nextBatchNumber))
        };
    }

    function actionPayloadForGuidanceButton(action, rawPayload, label) {
        const payload = rawPayload && typeof rawPayload === 'object' ? Object.assign({}, rawPayload) : {};
        if (String(action || '') === 'mark_business_profile_field_unavailable') {
            payload.field = canonicalBusinessProfileUnavailableField(
                payload.field || payload.field_key || payload.name || inferBusinessProfileUnavailableFieldFromLabel(label)
            );
        }
        if (String(action || '') === 'start_onpage_seo_run') {
            const continuation = onPageContinuationContext();
            if (continuation) {
                payload.continuation_mode = true;
                payload.continuation_token = continuation.continuation_token;
                payload.current_batch_number = continuation.current_batch_number;
                payload.unprocessed_total = continuation.unprocessed_total;
            }
        }
        return payload;
    }

    function businessProfileFallbackGuidance(canonical) {
        if (!canonical || typeof canonical !== 'object' || String(canonical.phase || '') !== 'business_profile') {
            return null;
        }
        const decisions = canonical.decisions && typeof canonical.decisions === 'object' ? canonical.decisions : {};
        const data = canonical.data && typeof canonical.data === 'object' ? canonical.data : {};
        const business = data.business_profile && typeof data.business_profile === 'object' ? data.business_profile : {};
        const completion = business.completion && typeof business.completion === 'object' ? business.completion : {};
        const proposal = business.proposal && typeof business.proposal === 'object' ? business.proposal : {};
        const allowed = Array.isArray(canonical.allowed_actions) ? canonical.allowed_actions : [];
        if (decisions.business_profile_confirmed || business.confirmed || allowed.indexOf('mark_business_profile_field_unavailable') === -1) {
            return null;
        }
        const missing = Array.isArray(completion.missing_required_fields) ? completion.missing_required_fields.map(function(item) {
            return String(item || '');
        }).filter(Boolean) : [];
        if (missing.indexOf('support_email') === -1 && missing.indexOf('address') === -1) {
            return null;
        }
        const isRo = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const rows = [
            ['company_name', isRo ? 'Nume companie' : 'Company name'],
            ['website', 'Website'],
            ['website_type', isRo ? 'Tip website' : 'Website type'],
            ['business_type', isRo ? 'Tip business' : 'Business type'],
            ['industry', isRo ? 'Industrie' : 'Industry'],
            ['core_services', isRo ? 'Servicii principale' : 'Main services'],
            ['service_area', isRo ? 'Arie servicii' : 'Service area'],
            ['support_phone', isRo ? 'Telefon' : 'Phone']
        ].map(function(pair) {
            return { label: pair[1], value: String(proposal[pair[0]] || '').trim() };
        }).filter(function(row) {
            return row.value !== '';
        });
        const options = [{
            action: 'refresh_business_profile_autofill_status',
            label: isRo ? 'Verifică analiza' : 'Check analysis',
            kind: 'secondary',
            badges: []
        }];
        if (missing.indexOf('support_email') !== -1) {
            options.push({
                action: 'mark_business_profile_field_unavailable',
                label: isRo ? 'Emailul nu este public' : 'Email is not public',
                kind: 'primary',
                payload: { field: 'support_email' },
                badges: [isRo ? 'Nu publicăm automat' : 'No automatic publishing']
            });
        }
        if (missing.indexOf('address') !== -1) {
            options.push({
                action: 'mark_business_profile_field_unavailable',
                label: isRo ? 'Adresa nu este publică' : 'Address is not public',
                kind: 'primary',
                payload: { field: 'address' },
                badges: [isRo ? 'Nu publicăm automat' : 'No automatic publishing']
            });
        }
        return {
            title: 'Business Profile',
            body: isRo
                ? 'Am o propunere Business Profile, dar mai trebuie completate câteva date înainte de confirmare. Dacă telefonul, emailul sau adresa nu sunt publice, marchează-le ca nepublice. Nu publicăm nimic automat.'
                : 'I have a Business Profile proposal, but a few details still need confirmation. If phone, email, or address are not public, mark them as unavailable. Nothing is published automatically.',
            status: 'review',
            variant: 'business_profile',
            collapsible: true,
            collapsed: false,
            progress: business.progress && typeof business.progress === 'object' ? business.progress : {
                status: 'completed',
                percent: 100,
                label: isRo ? 'Propunerea Business Profile este gata' : 'Business Profile proposal is ready'
            },
            review: {
                title: isRo ? 'Rezultat propus' : 'Proposed result',
                rows: rows,
                completion_status: String(completion.status || 'incomplete'),
                missing: missing,
                next_question: isRo
                    ? 'Completează câmpurile lipsă sau marchează-le ca nepublice.'
                    : 'Fill in the missing fields or mark them as not public.',
                instruction: isRo
                    ? 'Răspunde direct în chat sau folosește butoanele de mai jos pentru câmpurile care nu sunt publice.'
                    : 'Reply in chat or use the buttons below for fields that are not public.'
            },
            options: options,
            primary_cta: options.find(function(option) {
                return option.action === 'mark_business_profile_field_unavailable';
            }) || null,
            phase: 'business_profile',
            guidance_id: 'business_profile:fallback:review'
        };
    }

    function isUsableGuidance(guidance) {
        return !!(guidance && typeof guidance === 'object' && (
            String(guidance.title || '').trim() !== ''
            || String(guidance.body || '').trim() !== ''
            || (Array.isArray(guidance.options) && guidance.options.length > 0)
            || (guidance.primary_cta && typeof guidance.primary_cta === 'object')
        ));
    }

    function businessProfileFallbackActionCardHtml(guidance) {
        if (!isUsableGuidance(guidance)) {
            return '';
        }
        const options = Array.isArray(guidance.options) ? guidance.options : [];
        const buttons = options.map(function(option) {
            if (!option || typeof option !== 'object') {
                return '';
            }
            const action = String(option.action || '');
            const label = String(option.label || actionLabel(action));
            if (!action || !label) {
                return '';
            }
            const payload = actionPayloadForGuidanceButton(action, option.payload, label);
            const kind = String(option.kind || 'secondary');
            return '<button type="button" class="button aysa-agent8v3-guidance-option aysa-agent8v3-action is-' + escapeHtml(kind) + '" data-action="' + escapeHtml(action) + '" data-payload="' + escapeHtml(JSON.stringify(payload)) + '">' + escapeHtml(label) + '</button>';
        }).filter(Boolean).join('');
        if (!buttons) {
            return '';
        }
        return '<div class="aysa-agent8v3-action-card aysa-agent8v3-business-profile-fallback-card">' +
            '<div class="aysa-agent8v3-action-title"><strong>' + escapeHtml(String(guidance.title || 'Business Profile')) + '</strong><span>' + escapeHtml(String(guidance.status || 'review')) + '</span></div>' +
            '<p>' + escapeHtml(String(guidance.body || '')) + '</p>' +
            '<div class="aysa-agent8v3-action-buttons">' + buttons + '</div>' +
        '</div>';
    }

    function applyPayloadContext(payload, options) {
        const data = payload && payload.data ? payload.data : payload;
        const canonical = data && data.state ? data.state : null;
        const projection = data && data.projection ? data.projection : {};
        const debug = data && data.debug ? data.debug : {};
        const showRag = !!(options && options.showRag);
        state.canonical = canonical;
        state.lastDebug = debug;
        const rawGuidance = projection && projection.guidance && typeof projection.guidance === 'object' ? projection.guidance : null;
        const nextGuidance = isUsableGuidance(rawGuidance) ? rawGuidance : businessProfileFallbackGuidance(canonical);
        const nextGuidanceIdentity = guidanceIdentity(nextGuidance);
        const sameGuidance = nextGuidanceIdentity && nextGuidanceIdentity === state.guidanceIdentity;
        state.guidance = nextGuidance;
        state.guidanceIdentity = nextGuidanceIdentity;
        if (guidanceHasActiveQuestion(state.guidance)) {
            state.guidanceCollapsed = false;
        } else {
            state.guidanceCollapsed = sameGuidance ? state.guidanceCollapsed : guidanceShouldStartCollapsed(state.guidance);
        }
        state.externalAction = projection && projection.external_action ? projection.external_action : null;
        state.setupDiagnostics = projection && projection.setup_diagnostics ? projection.setup_diagnostics : null;
        state.offpageExecution = (projection && projection.offpage_execution) || (data && data.offpage_execution) || null;
        const actionResult = data && data.action_result && typeof data.action_result === 'object' ? data.action_result : {};
        const monitoringPreflight = actionResult.monitoring_refresh_preflight && typeof actionResult.monitoring_refresh_preflight === 'object'
            ? actionResult.monitoring_refresh_preflight
            : (data && data.monitoring_refresh_preflight && typeof data.monitoring_refresh_preflight === 'object'
                ? data.monitoring_refresh_preflight
                : null);
        if (monitoringPreflight) {
            // Keep the existing read-only preflight result while the modal reloads its normal saved snapshot.
            state.monitoringRefreshPreflight = monitoringPreflight;
        }
        const offpagePreflight = normalizeOffpageLinkExchangePreflight(projection && projection.offpage_link_exchange_preflight);
        if (offpagePreflight) {
            state.offpageLinkExchangePreflight = offpagePreflight;
        } else if (String((canonical && canonical.phase) || '') !== 'offpage_seo_review') {
            state.offpageLinkExchangePreflight = null;
        }
        state.billing = mergeBillingSnapshot(state.billing, data && data.billing ? data.billing : null);
        state.walletSnapshot = data && data.wallet_snapshot ? data.wallet_snapshot : (state.billing && state.billing.wallet_snapshot ? state.billing.wallet_snapshot : null);
        state.legacyCommit = data && data.legacy_commit ? data.legacy_commit : (projection && projection.legacy_commit ? projection.legacy_commit : null);
        state.languageFallbacks = [].concat(
            Array.isArray(projection.language_fallbacks) ? projection.language_fallbacks : [],
            data && Array.isArray(data.language_fallbacks) ? data.language_fallbacks : []
        );
        if (!showRag) {
            state.ragContexts = [];
        }
        applyInterfaceLanguage(projection.language || (canonical && canonical.data && canonical.data.language) || 'ro');
        updateAuthPill(canonical);
        updateFactoryResetVisibility();

        $('#aysa-agent8v3-state').text(JSON.stringify(canonical || {}, null, 2));
        $('#aysa-agent8v3-debug').text(JSON.stringify(debug || {}, null, 2));
        $('#aysa-agent8v3-projection').html([
            projection.phase ? '<div class="aysa-agent8v3-projection-row"><span>' + escapeHtml(text('currentPhase')) + '</span><strong>' + escapeHtml(projection.phase) + '</strong></div>' : '',
            projection.state_version ? '<div class="aysa-agent8v3-projection-row"><span>' + escapeHtml(text('stateVersion')) + '</span><strong>' + escapeHtml(projection.state_version) + '</strong></div>' : '',
            projection.language ? '<div class="aysa-agent8v3-projection-row"><span>' + escapeHtml(text('language')) + '</span><strong>' + escapeHtml(languageLabel(projection.language)) + '</strong></div>' : '',
            projection.status ? '<div class="aysa-agent8v3-projection-row"><span>' + escapeHtml(text('apiStatus')) + '</span><strong>' + escapeHtml(projection.status) + '</strong></div>' : ''
        ].join(''));
        $('#aysa-agent8v3-request-id').text(debug.request_id || '-');
        $('#aysa-agent8v3-qa-storage').text(cfg.qa_enabled ? 'Enabled' : 'Disabled');
        $('#aysa-agent8v3-chat-phase').text(projection.phase || (canonical && canonical.phase) || text('waiting'));
        $('#aysa-agent8v3-language').val(projection.language || (canonical && canonical.data && canonical.data.language) || 'ro');

        renderActions(canonical || {}, projection || {});
        renderSetupProgressPanel(canonical || {}, projection || {});
        renderCredits();
        renderDiagnostics();
        syncBusinessProfileAutoRefresh();
        syncSeoProfileAutoRefresh();
        syncCompetitionKeywordAutoRefresh();
        maybeAutoFinalizeSetupSync();
        syncKeywordResearchAutoRefresh();
        maybeAutoStartTechnicalSeo();
        syncTechnicalSeoAutoRefresh();
        syncOnPageSeoAutoRefresh();

        return {
            data: data,
            canonical: canonical,
            projection: projection,
            debug: debug,
            showRag: showRag
        };
    }

    function renderPayload(payload, options) {
        if (state.modal && state.modal.viewCache) {
            state.modal.viewCache = {};
        }
        const context = applyPayloadContext(payload, options || {});
        const projection = context.projection || {};
        const debug = context.debug || {};
        const silent = !!(options && options.silent);
        const allowTranscriptHydrate = !!(options && options.allowTranscriptHydrate);
        const phase = context.canonical && context.canonical.phase ? String(context.canonical.phase) : String(projection.phase || '');

        if (!silent && allowTranscriptHydrate && Array.isArray(projection.transcript) && projection.transcript.length) {
            hydrateTranscript(projection.transcript);
        } else if (!silent && allowTranscriptHydrate && Array.isArray(projection.transcript) && !projection.transcript.length && projection.assistant_message && isActivationLikePhase(phase)) {
            state.messages = [];
            ensureTransientAssistantMessage(projection.assistant_message, 'agent8_preactivation_welcome');
        } else if (!silent && options && options.forceAssistantAppend && projection.assistant_message) {
            appendAssistantMessage(projection.assistant_message);
        } else if (!silent && projection.assistant_message && !allowTranscriptHydrate) {
            appendAssistantMessage(projection.assistant_message);
        } else if (silent) {
            updateLiveGuidanceBlocks();
        }
        if (!silent && allowTranscriptHydrate) {
            updateLiveGuidanceBlocks();
        }
        if (debug.rag && context.showRag) {
            addRagContextCard(debug.rag);
        }
        recordBetaIssueBreadcrumb('state_rendered', {
            phase: phase,
            projection_status: String(projection.status || ''),
            request_id: String(debug.request_id || ''),
            actions_count: Array.isArray(projection.actions) ? projection.actions.length : 0
        });
    }

    function renderProgressPayload(payload, options) {
        options = $.extend({ preserveScroll: true }, options || {});
        const previousGuidance = state.guidance;
        const previousPhase = state.canonical && state.canonical.phase ? String(state.canonical.phase) : '';
        const context = applyPayloadContext(payload, options);
        const currentPhase = context.canonical && context.canonical.phase ? String(context.canonical.phase) : '';
        if (previousPhase && currentPhase && previousPhase !== currentPhase) {
            maybeAppendFinalProgressMessage(previousGuidance, state.guidance);
            updateLiveGuidanceBlocks();
            return;
        }
        preserveMessagesScroll(function() {
            updateLiveGuidanceBlocks();
        }, true);
        maybeAppendFinalProgressMessage(previousGuidance, state.guidance);
    }

    function preserveMessagesScroll(callback, preserveScroll) {
        const el = document.getElementById('aysa-agent8v3-messages');
        const previousScrollTop = el ? el.scrollTop : 0;
        const previousScrollHeight = el ? el.scrollHeight : 0;
        callback();
        if (!el || !preserveScroll) {
            return;
        }
        el.scrollTop = previousScrollTop + Math.max(0, el.scrollHeight - previousScrollHeight);
    }

    function updateLiveGuidanceBlocks() {
        const container = $('#aysa-agent8v3-messages');
        const currentPhase = state.canonical && state.canonical.phase ? String(state.canonical.phase) : '';
        const exchangeSummaryHtml = offpageLinkExchangeRequestSummaryHtml(state.offpageLinkExchangePreflight);
        const guidanceAsChat = guidanceIsTextOnlyMessage(currentPhase, state.guidance);
        const guidanceInConversation = guidanceRendersInConversation(currentPhase, state.guidance);
        const guidanceInActionsOnly = (currentPhase.indexOf('technical_seo') !== -1 && currentPhase !== 'technical_seo_ready')
            || currentPhase.indexOf('onpage_seo') === 0;
        const guidanceHtml = exchangeSummaryHtml || guidanceAsChat || isMonitoringConversationPhase(currentPhase) || guidanceInActionsOnly ? '' : phaseGuidanceCardHtml(state.guidance, state.externalAction, state.guidanceCollapsed);
        const dialogueHtml = exchangeSummaryHtml || guidanceAsChat || guidanceInConversation || guidanceInActionsOnly ? '' : guidanceDialogueMessageHtml(state.guidance);
        replaceLiveBlock(container, '.aysa-agent8v3-link-exchange-summary-message', exchangeSummaryHtml, '.aysa-agent8v3-guidance-message');
        replaceLiveBlock(container, '.aysa-agent8v3-guidance-message', guidanceHtml, '.aysa-agent8v3-guidance-dialogue-message');
        replaceLiveBlock(container, '.aysa-agent8v3-guidance-dialogue-message', dialogueHtml, '');
        renderActions(state.canonical || {}, {});
    }

    function updateGuidanceCollapsedDom() {
        const collapsed = !!(state.guidance && state.guidance.collapsible && state.guidanceCollapsed);
        $('.aysa-agent8v3-guidance-message').toggleClass('is-collapsed', collapsed);
        $('.aysa-agent8v3-guidance-toggle').text(collapsed ? text('expand') : text('collapse'));
        const guidanceExpanded = !!(
            state.guidance &&
            state.guidance.collapsible &&
            !state.guidanceCollapsed &&
            !guidanceHasActiveQuestion(state.guidance) &&
            $('#aysa-agent8v3-actions .aysa-agent8v3-guidance-message').length
        );
        $('.aysa-agent8v3-app, .aysa-agent8v3-chat-panel').toggleClass('is-guidance-expanded', guidanceExpanded);
    }

    function replaceLiveBlock(container, selector, html, beforeSelector) {
        const allExisting = container.children(selector);
        const existing = allExisting.last();
        if (!html) {
            allExisting.remove();
            return;
        }
        if (allExisting.length > 1) {
            allExisting.not(existing).remove();
        }
        if (existing.length) {
            existing.replaceWith(html);
            return;
        }
        const before = beforeSelector ? container.children(beforeSelector).last() : $();
        if (before.length) {
            before.before(html);
            return;
        }
        container.append(html);
    }

    function progressStatus(guidance) {
        const progress = guidance && guidance.progress && typeof guidance.progress === 'object' ? guidance.progress : {};
        return String(progress.status || guidance && guidance.status || '').toLowerCase();
    }

    function progressRunKey(guidance) {
        const progress = guidance && guidance.progress && typeof guidance.progress === 'object' ? guidance.progress : {};
        const canonical = state.canonical || {};
        const data = canonical.data || {};
        const phase = String(canonical.phase || guidance && guidance.phase || '');
        const source = phase.indexOf('business_profile') !== -1 ? data.business_profile
            : phase.indexOf('seo_profile') !== -1 ? data.seo_profile
            : phase.indexOf('competition_keyword') !== -1 ? data.competition_keyword
            : phase.indexOf('research_handoff') !== -1 ? data.research_handoff
            : phase.indexOf('technical_seo') !== -1 ? data.technical_seo
            : phase.indexOf('onpage_seo') !== -1 ? data.onpage_seo
            : null;
        const runRef = source && typeof source === 'object'
            ? (source.run_id || source.autofill_run_id || source.job_id || source.worker_ref || (source.run_ids ? JSON.stringify(source.run_ids) : ''))
            : '';
        return String(runRef || [
            phase,
            guidance && guidance.variant || '',
            progress.total_tasks || '',
            progress.label || ''
        ].join(':'));
    }

    function maybeAppendFinalProgressMessage(previousGuidance, nextGuidance) {
        const previousStatus = progressStatus(previousGuidance);
        const nextStatus = progressStatus(nextGuidance);
        const terminal = ['completed', 'failed', 'cancelled', 'canceled'].indexOf(nextStatus) !== -1;
        if (!terminal || ['queued', 'running', 'blocked'].indexOf(previousStatus) === -1) {
            return;
        }
        const key = progressRunKey(nextGuidance) + ':' + nextStatus;
        if (state.completedRunMessages[key]) {
            return;
        }
        state.completedRunMessages[key] = true;
        const progress = nextGuidance && nextGuidance.progress && typeof nextGuidance.progress === 'object' ? nextGuidance.progress : {};
        const isRo = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const title = nextGuidance && nextGuidance.title ? String(nextGuidance.title) : (isRo ? 'Analiza' : 'Analysis');
        const phase = state.canonical && state.canonical.phase ? String(state.canonical.phase) : '';
        const isResearchComplete = phase === 'research_handoff_complete';
        const isTechnicalComplete = phase === 'technical_seo_review';
        const body = nextStatus === 'completed'
            ? (isResearchComplete
                ? (isRo
                    ? 'Research-ul este gata. Următorul pas este să verifici rezultatele înainte să pornim Technical SEO. Uită-te întâi la cuvintele cheie propuse și respinge ce nu este relevant. Apoi verifică mappingul: asta înseamnă pagina pe care o asociem fiecărui keyword, ca să știm ce optimizăm. După aceea verifică paginile lipsă, adică paginile noi pe care ar merita să le creăm. La final verifică Content Plan și aprobă-l dacă arată bine.'
                    : 'Research is ready. Next, review the results before we start Technical SEO. Check the proposed keywords first and reject anything that is not relevant. Then review mapping: this means the page associated with each keyword, so we know what to optimize. After that, review missing pages, the new pages worth creating. Finally, review the Content Plan and approve it if it looks good.')
                : (isTechnicalComplete
                    ? (isRo
                        ? 'Am terminat verificarea Technical SEO. Am găsit câteva optimizări care pot fi pregătite în siguranță, câteva care au nevoie de verificarea ta și câteva pe care nu le aplic automat. Nu am modificat site-ul. Deschide review-ul ca să excluzi ce nu vrei și să aprobi doar ce este sigur.'
                        : 'Technical SEO is complete. I found a few optimizations that can be safely prepared, a few that need your review, and a few I will not apply automatically. I did not change the site. Open the review to exclude what you do not want and approve only what is safe.')
                : (isRo ? title + ' este gata.' : title + ' is ready.'))
                )
            : (isRo ? title + ' s-a oprit cu eroare.' : title + ' stopped with an error.');
        state.messages.push({
            role: 'assistant',
            body: !isResearchComplete && progress.label ? body + ' ' + String(progress.label) : body,
            phase: phase,
            status: nextStatus,
            created_at: new Date().toISOString()
        });
        renderMessages({ preserveScroll: true });
    }

    function hydrateTranscript(transcript) {
        let persistedLinkExchangeSummary = null;
        state.messages = transcript.map(function(item) {
            const body = String(item.message || '').trim();
            if (/^(State-ul canonic Agent8 a fost încărcat\.|Agent8 canonical state loaded\.)$/i.test(body)) {
                return null;
            }
            if (
                state.canonical &&
                String(state.canonical.phase || '') === 'technical_seo_review' &&
                /^(Review-ul Technical SEO (a fost|este) finalizat\. Putem continua către următorul pas on-page\.|Technical SEO review is complete\. We can continue to the next on-page step\.)$/i.test(body)
            ) {
                return null;
            }
            const role = String(item.role || '') === 'user' ? 'user' : 'assistant';
            if (item && item.link_exchange_summary && typeof item.link_exchange_summary === 'object') {
                persistedLinkExchangeSummary = item.link_exchange_summary;
            } else if (item && item.payload && item.payload.link_exchange_summary && typeof item.payload.link_exchange_summary === 'object') {
                persistedLinkExchangeSummary = item.payload.link_exchange_summary;
            }
            return {
                role: role,
                body: body,
                guidance: null,
                linkExchangeSummary: item.link_exchange_summary || null,
                phase: state.canonical && state.canonical.phase ? state.canonical.phase : '',
                status: 'completed',
                created_at: item.created_at || new Date().toISOString()
            };
        }).filter(function(item) {
            return item && item.body !== '';
        });
        if (persistedLinkExchangeSummary) {
            state.offpageLinkExchangePreflight = normalizeOffpageLinkExchangePreflight(persistedLinkExchangeSummary);
        }
        renderMessages();
    }

    function renderActions(canonical, projection) {
        const pending = canonical.pending_approval;
        let html = offpageExecutionHtml(state.offpageExecution);
        const currentPhase = canonical && canonical.phase ? String(canonical.phase) : '';
        if (!isUsableGuidance(state.guidance)) {
            const fallbackGuidance = businessProfileFallbackGuidance(canonical);
            if (fallbackGuidance) {
                state.guidance = fallbackGuidance;
                state.guidanceIdentity = guidanceIdentity(fallbackGuidance);
            }
        }
        const guidanceInConversation = guidanceRendersInConversation(currentPhase, state.guidance);
        let guidanceHtml = '';
        try {
            guidanceHtml = guidanceInConversation ? '' : phaseGuidanceCardHtml(state.guidance, state.externalAction, state.guidanceCollapsed);
        } catch (e) {
            guidanceHtml = '';
        }
        html += guidanceHtml;
        if (currentPhase === 'business_profile' && !guidanceInConversation && html.indexOf('mark_business_profile_field_unavailable') === -1) {
            html += businessProfileFallbackActionCardHtml(state.guidance || businessProfileFallbackGuidance(canonical));
        }
        if (pending && pending.action) {
            html += '<div class="aysa-agent8v3-action-card">' +
                '<div class="aysa-agent8v3-action-title"><strong>' + escapeHtml(actionLabel(pending.action)) + '</strong><span class="aysa-agent8v3-approval-required">' + escapeHtml(text('approvalRequired')) + '</span></div>' +
                '<div class="aysa-agent8v3-action-meta">' +
                    '<span>' + escapeHtml(text('writesState')) + '</span><span>' + escapeHtml(text('requiresApproval')) + '</span><span>' + escapeHtml(text('billableFalse')) + '</span>' +
                '</div>' +
                '<div class="aysa-agent8v3-action-buttons">' +
                    '<button type="button" class="button button-primary aysa-agent8v3-approval" data-approval="approve">' + escapeHtml(text('approve')) + '</button>' +
                    '<button type="button" class="button aysa-agent8v3-approval" data-approval="reject">' + escapeHtml(text('reject')) + '</button>' +
                '</div>' +
            '</div>';
        } else {
            html += '';
        }
        $('#aysa-agent8v3-actions').html(html);
        const guidanceExpanded = !!(state.guidance && state.guidance.collapsible && !state.guidanceCollapsed && !guidanceHasActiveQuestion(state.guidance) && html.indexOf('aysa-agent8v3-guidance-message') !== -1);
        $('.aysa-agent8v3-app, .aysa-agent8v3-chat-panel').toggleClass('is-guidance-expanded', guidanceExpanded);
        $('.aysa-agent8v3-composer-panel').toggleClass('is-disabled', !!(pending && pending.action));
        $('#aysa-agent8v3-input, #aysa-agent8v3-send, #aysa-agent8v3-language').prop('disabled', !!(pending && pending.action));
        restoreOnPageAnalysisApproval();
    }

    function nextStepActionHtml(primaryCta, externalAction) {
        if (!primaryCta || typeof primaryCta !== 'object' || isStatusOnlyAction(primaryCta.action || '')) {
            return '';
        }
        if (!isNextStepTransitionAction(primaryCta.action || '')) {
            return '';
        }
        const ctaHtml = guidancePrimaryCtaHtml(primaryCta, externalAction);
        if (!ctaHtml) {
            return '';
        }
        const isRo = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        return '<div class="aysa-agent8v3-action-card aysa-agent8v3-next-step-card">' +
            '<div class="aysa-agent8v3-action-title"><strong>' + escapeHtml(isRo ? 'Următorul pas' : 'Next step') + '</strong></div>' +
            '<div class="aysa-agent8v3-action-buttons">' + ctaHtml + '</div>' +
        '</div>';
    }

    function offpageExecutionHtml(execution) {
        if (!execution || typeof execution !== 'object') {
            return '';
        }
        const risk = String(execution.risk_label || '');
        const badges = [
            execution.safety_status_label || '',
            execution.billing_policy || '',
            execution.billing_authority || '',
            execution.external_system || '',
            execution.confirmation_required ? 'Requires approval' : '',
            risk.indexOf('sends email') !== -1 ? 'Email only' : '',
            risk.indexOf('read-only') !== -1 ? 'Read-only' : '',
            risk.indexOf('costs credits') !== -1 ? 'Billable API' : '',
            risk.indexOf('changes external system') !== -1 ? 'Changes external system' : ''
        ].filter(Boolean).slice(0, 5);
        const status = execution.status_label || execution.status || 'completed';
        const action = execution.action_label || execution.action_title || 'Off Page action';
        const bundle = execution.refreshed_bundle || execution.action_category || '';
        return '<div class="aysa-agent8v3-action-card aysa-agent8v3-offpage-last-action">' +
            '<div class="aysa-agent8v3-action-title"><strong>Last Off Page action</strong><span class="aysa-agent8v3-status-badge">' + escapeHtml(status) + '</span></div>' +
            '<div class="aysa-agent8v3-action-meta"><span>' + escapeHtml(action) + '</span>' + (bundle ? '<span>' + escapeHtml(bundle) + '</span>' : '') + '</div>' +
            actionBadgesHtml(badges) +
        '</div>';
    }

    function languageLabel(language) {
        const labels = {
            ro: 'Romanian',
            en: 'English',
            'en-GB': 'English (Europe/UK)',
            'en-US': 'English (United States)',
            'en-CA': 'English (Canada)',
            fr: 'French',
            'fr-CA': 'French (Canada)',
            'ar-AE': 'Arabic (Dubai/UAE)',
            sq: 'Albanian',
            hy: 'Armenian',
            az: 'Azerbaijani',
            eu: 'Basque',
            be: 'Belarusian',
            bs: 'Bosnian',
            bg: 'Bulgarian',
            ca: 'Catalan',
            hr: 'Croatian',
            cs: 'Czech',
            da: 'Danish',
            nl: 'Dutch',
            et: 'Estonian',
            fi: 'Finnish',
            gl: 'Galician',
            ka: 'Georgian',
            de: 'German',
            el: 'Greek',
            hu: 'Hungarian',
            is: 'Icelandic',
            ga: 'Irish',
            it: 'Italian',
            lv: 'Latvian',
            lt: 'Lithuanian',
            lb: 'Luxembourgish',
            mk: 'Macedonian',
            mt: 'Maltese',
            no: 'Norwegian',
            pl: 'Polish',
            pt: 'Portuguese',
            ru: 'Russian',
            sr: 'Serbian',
            sk: 'Slovak',
            sl: 'Slovenian',
            es: 'Spanish',
            sv: 'Swedish',
            tr: 'Turkish',
            uk: 'Ukrainian',
            cy: 'Welsh',
            yi: 'Yiddish'
        };
        return labels[String(language || 'ro')] || 'Romanian';
    }

    function request(action, data, options) {
        options = options || {};
        const workerTaskId = data && isWorkerAction(data.agent_action) ? beginWorkerTask(data.agent_action) : '';
        const isChatRequest = action === 'aysa_agent8v3_message';
        const agentAction = String(data && data.agent_action || '');
        const isSilentReadOnlyStatusRetry = action === 'aysa_agent8v3_action'
            && isSilentReadOnlyStatusRetryAction(agentAction);
        const isSafeLocalActionRetry = action === 'aysa_agent8v3_action'
            && data
            && (
                agentAction === 'revise_competition_keyword_selection'
                || agentAction === 'refresh_google_connection_status'
                || agentAction === 'confirm_keyword_mapping_target'
                || agentAction === 'reopen_keyword_mapping_target'
                || isSilentReadOnlyStatusRetry
            );
        const retryCount = parseInt(options.retryCount || 0, 10) || 0;
        let thinkingId = options.thinkingId || '';
        if (isChatRequest && !thinkingId) {
            thinkingId = addThinkingMessage();
            state.pendingChat = {
                message: data && data.message ? String(data.message) : '',
                thinkingId: thinkingId,
                retryCount: retryCount
            };
        }
        setStatus('running');
        return $.ajax({
            url: cfg.ajax_url,
            method: 'POST',
            dataType: 'json',
            data: $.extend({
                action: action,
                nonce: cfg.nonce
            }, data || {})
        }).done(function(response) {
            if (!response || !response.success) {
                if (isChatRequest && isStaleStateResponse(response) && retryCount < 1) {
                    rawAjax('aysa_agent8v3_state', {}).done(function(stateResponse) {
                        if (stateResponse && stateResponse.success) {
                            renderPayload(stateResponse, { silent: true, preserveScroll: true });
                            request('aysa_agent8v3_message', $.extend({}, data || {}, {
                                state_version: currentVersion()
                            }), {
                                retryCount: retryCount + 1,
                                thinkingId: thinkingId
                            });
                            return;
                        }
                        removeThinkingMessage();
                        addMessage('system', text('modalErrorStaleState'));
                        setStatus('failed');
                    }).fail(function() {
                        removeThinkingMessage();
                        addMessage('system', text('modalErrorStaleState'));
                        setStatus('failed');
                    });
                    return;
                }
                if (isSafeLocalActionRetry && isStaleStateResponse(response) && retryCount < 1) {
                    rawAjax('aysa_agent8v3_state', {}).done(function(stateResponse) {
                        if (stateResponse && stateResponse.success) {
                            renderPayload(stateResponse, { silent: true, preserveScroll: true });
                            request('aysa_agent8v3_action', $.extend({}, data || {}, {
                                state_version: currentVersion()
                            }), {
                                retryCount: retryCount + 1
                            });
                            return;
                        }
                        if (!isSilentReadOnlyStatusRetry) {
                            addMessage('system', text('modalErrorStaleState'));
                        }
                        setStatus('failed');
                    }).fail(function() {
                        if (!isSilentReadOnlyStatusRetry) {
                            addMessage('system', text('modalErrorStaleState'));
                        }
                        setStatus('failed');
                    });
                    return;
                }
                if (isSilentReadOnlyStatusRetry && isStaleStateResponse(response)) {
                    rawAjax('aysa_agent8v3_state', {}).done(function(stateResponse) {
                        if (stateResponse && stateResponse.success) {
                            renderPayload(stateResponse, { silent: true, preserveScroll: true });
                            setStatus('completed');
                            return;
                        }
                        setStatus('failed');
                    }).fail(function() {
                        setStatus('failed');
                    });
                    return;
                }
                if (isChatRequest) {
                    removeThinkingMessage();
                    state.pendingChat = null;
                }
                const message = apiErrorMessage(response, 'Agent8 request failed.');
                addMessage('system', recoverableErrorMessage(message));
                if (/timed out|cURL error 28/i.test(message)) {
                    rawAjax('aysa_agent8v3_state', {}).done(function(stateResponse) {
                        if (stateResponse && stateResponse.success) {
                            renderPayload(stateResponse, { silent: true });
                        }
                    });
                }
                if (workerTaskId) {
                    failWorkerTask(workerTaskId, message);
                }
                setStatus('failed');
                return;
            }
            if (isChatRequest) {
                removeThinkingMessage();
                state.pendingChat = null;
            }
            renderPayload(response, {
                silent: !!options.silent,
                allowTranscriptHydrate: action === 'aysa_agent8v3_state' && !isChatRequest,
                showRag: !!(data && data.agent_action === 'run_rag_context_test'),
                forceAssistantAppend: isChatRequest
            });
            if (workerTaskId) {
                completeWorkerTask(workerTaskId, response.data || {});
            }
            setStatus('completed');
        }).fail(function(xhr) {
            if (isChatRequest) {
                removeThinkingMessage();
                state.pendingChat = null;
            }
            addMessage('system', apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Request failed: HTTP ' + xhr.status));
            if (workerTaskId) {
                failWorkerTask(workerTaskId, 'HTTP ' + xhr.status);
            }
            setStatus('failed');
        });
    }

    function recoverableErrorMessage(message) {
        if (/timed out|cURL error 28/i.test(String(message || ''))) {
            return 'Requestul a durat prea mult și a expirat. Reîncarc state-ul canonic; dacă datele nu s-au salvat, retrimite ultimul răspuns.';
        }
        return message;
    }

    function apiErrorCode(response) {
        const data = response && response.data ? response.data : {};
        const payload = data && data.payload ? data.payload : {};
        return data.error || data.code || payload.error || payload.code || data.message || '';
    }

    function apiErrorMessage(response, fallback) {
        const code = String(apiErrorCode(response) || '');
        const data = response && response.data ? response.data : {};
        const diagnostic = data && data.diagnostic ? data.diagnostic : {};
        const rawMessage = String(data.message || fallback || '');
        if (/openai_http_|invalid_llm_contract|provider_http_error|conversation_provider_error|HTTP 5\d\d/i.test(code + ' ' + rawMessage)) {
            return text('chatProviderFallback');
        }
        if (code === 'stale_state_version') {
            return text('modalErrorStaleState');
        }
        if (code === 'empty_fix_plan') {
            return text('modalErrorEmptyFixPlan');
        }
        if (code === 'unknown_action') {
            return text('modalErrorUnknownAction');
        }
        if (code === 'invalid_ga4_selection') {
            return 'Conexiunea Google este verificată, dar proprietatea Analytics selectată nu mai este disponibilă. Verifică statusul conexiunii și continuă.';
        }
        if (code === 'invalid_gsc_selection') {
            return 'Conexiunea Google este verificată, dar proprietatea Search Console selectată nu mai este disponibilă. Verifică statusul conexiunii și continuă.';
        }
        if (code === 'agent8v3_invalid_json' || /invalid JSON/i.test(String(data.message || ''))) {
            let message = text('modalErrorInvalidJson');
            if (diagnostic && diagnostic.http_code) {
                message += ' HTTP ' + diagnostic.http_code + '.';
            }
            if (diagnostic && diagnostic.body_preview) {
                message += ' ' + diagnostic.body_preview;
            }
            return message;
        }
        return data.message || fallback || 'Agent8 request failed.';
    }

    function automaticTopupCreditGate(response) {
        const data = response && response.data && typeof response.data === 'object' ? response.data : {};
        const payload = data.payload && typeof data.payload === 'object' ? data.payload : data;
        return payload.credit_gate && typeof payload.credit_gate === 'object'
            ? payload.credit_gate
            : (payload.billing && typeof payload.billing === 'object' ? payload.billing : {});
    }

    function requestAutomaticTopupForCreditGate(action, estimate, available) {
        const ro = state.language === 'Romanian' || String(uiLanguage() || '').indexOf('ro') === 0;
        return rawAjax('aysa_agent8v3_action', {
            agent_action: String(action || ''),
            state_version: currentVersion(),
            payload: JSON.stringify({
                credit_gate_only: true,
                analysis_only: true,
                no_wordpress_write: true,
                apply_allowed: false
            })
        }).done(function(response) {
            const gate = automaticTopupCreditGate(response);
            const order = gate.topup_order && typeof gate.topup_order === 'object' ? gate.topup_order : {};
            const checkoutUrl = String(order.checkout_url || order.payment_link || '');
            if (checkoutUrl) {
                addMessage('system', ro
                    ? ('Creditele nu sunt suficiente pentru această acțiune. Disponibil: ' + String(available) + ', necesar: ' + String(estimate) + '. Cererea de top-up a fost creată o singură dată. Deschide checkout-ul securizat: ' + checkoutUrl)
                    : ('There are not enough credits for this action. Available: ' + String(available) + ', required: ' + String(estimate) + '. The top-up request was created once. Open secure checkout: ' + checkoutUrl));
                return;
            }
            const unavailable = String(gate.topup_unavailable_reason || '');
            addMessage('system', unavailable === 'billing_company_missing'
                ? (ro ? 'Completează datele de facturare în AYSA pentru a genera checkout-ul de top-up.' : 'Complete the AYSA billing details to generate the top-up checkout.')
                : apiErrorMessage(response, ro ? 'Cererea automată de top-up nu a putut fi creată.' : 'The automatic top-up request could not be created.'));
        }).fail(function(xhr) {
            addMessage('system', apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, ro ? 'Cererea automată de top-up a eșuat.' : 'The automatic top-up request failed.'));
        });
    }

    function isStaleStateResponse(response) {
        return String(apiErrorCode(response) || '') === 'stale_state_version';
    }

    function isSilentReadOnlyStatusRetryAction(action) {
        return [
            'refresh_keyword_research_status'
        ].indexOf(String(action || '')) !== -1;
    }

    function rawAjax(action, data, options) {
        recordBetaIssueBreadcrumb('ajax_start', betaIssueAjaxSummary(action, data));
        const startedAt = Date.now();
        const xhr = $.ajax($.extend({
            url: cfg.ajax_url,
            method: 'POST',
            dataType: 'json',
            data: $.extend({
                action: action,
                nonce: cfg.nonce
            }, data || {})
        }, options || {}));
        xhr.done(function(response) {
            recordBetaIssueBreadcrumb('ajax_done', {
                action: String(action || ''),
                ok: !!(response && response.success),
                api_ok: !!(response && response.data && response.data.ok),
                issue_id: String(response && response.data && response.data.issue && response.data.issue.issue_id || ''),
                duration_ms: Date.now() - startedAt
            });
        }).fail(function(xhrObj) {
            recordBetaIssueBreadcrumb('ajax_fail', {
                action: String(action || ''),
                status: xhrObj && xhrObj.status ? xhrObj.status : 0,
                duration_ms: Date.now() - startedAt
            });
        });
        return xhr;
    }

    function shouldOpenOffpagePublisherArticlesQa() {
        const release = cfg.release && typeof cfg.release === 'object' ? cfg.release : {};
        if (!release.public_beta_safety_mode || String(release.release_channel || '') !== 'controlled-beta') {
            return false;
        }
        try {
            const params = new URLSearchParams(window.location.search || '');
            return params.get('aysa_offpage_qa') === 'publisher_articles';
        } catch (e) {
            return false;
        }
    }

    function openOffpagePublisherArticlesQaProjection() {
        state.modal.key = 'offpage_seo';
        state.modal.page = 1;
        state.modal.filters = {
            advanced: '1',
            tab: 'publisher_articles',
            status: 'all',
            qa_projection_only: '1'
        };
        state.modal.lastTrigger = null;
        state.offpageBacklinkStrategyAutoRefreshed = false;
        $('#aysa-agent8v3-modal-search').val('');
        $('#aysa-agent8v3-modal-status').val('all');
        $('#aysa-agent8v3-modal').prop('hidden', false).attr('aria-hidden', 'false');
        $('.aysa-agent8v3-modal-dialog').trigger('focus');
        loadModal();
    }

    function technicalFixExecutionStatusFromPayload(payload, module) {
        const canonical = payload && payload.data && (payload.data.state || payload.data.canonical_state || payload.data.canonical) ? (payload.data.state || payload.data.canonical_state || payload.data.canonical) : state.canonical || {};
        const technical = canonical && canonical.data && canonical.data.technical_seo ? canonical.data.technical_seo : {};
        const executions = technical.fix_execution || {};
        return executions[module] || {};
    }

    function technicalFixExecutionIsTerminal(execution) {
        const status = String((execution && execution.status) || '').toLowerCase();
        const workerStatus = String((execution && execution.worker_status) || '').toLowerCase();
        return ['completed_no_writes', 'failed', 'skipped', 'manual_review_needed', 'synced', 'already_synced'].indexOf(status) !== -1
            || ['completed', 'failed', 'cancelled', 'canceled', 'skipped'].indexOf(workerStatus) !== -1;
    }

    function stopTechnicalFixExecutionPolling() {
        if (state.technicalFixExecutionTimer) {
            window.clearInterval(state.technicalFixExecutionTimer);
            state.technicalFixExecutionTimer = null;
        }
        state.technicalFixExecutionRefreshing = false;
        state.technicalFixExecutionModule = '';
    }

    function startTechnicalFixExecutionPolling(module) {
        module = String(module || '');
        if (!module) {
            return;
        }
        stopTechnicalFixExecutionPolling();
        state.technicalFixExecutionModule = module;
        state.technicalFixExecutionTimer = window.setInterval(function() {
            if (state.technicalFixExecutionRefreshing) {
                return;
            }
            state.technicalFixExecutionRefreshing = true;
            rawAjax('aysa_agent8v3_action', {
                agent_action: 'refresh_technical_fix_execution_status',
                state_version: currentVersion(),
                payload: JSON.stringify({ module: module })
            }).done(function(response) {
                if (response && response.success) {
                    renderProgressPayload(response, { preserveScroll: true });
                    if (state.modal.key && String(state.modal.key).indexOf('technical_') === 0) {
                        loadModal();
                    }
                    if (technicalFixExecutionIsTerminal(technicalFixExecutionStatusFromPayload(response, module))) {
                        stopTechnicalFixExecutionPolling();
                    }
                }
            }).always(function() {
                state.technicalFixExecutionRefreshing = false;
            });
        }, 5000);
    }

    function offpageBacklinkAuditIsTerminal(payload) {
        const data = payload && payload.data ? payload.data : payload;
        const actionResult = data && data.action_result ? data.action_result : {};
        const workerStatus = actionResult && actionResult.worker_status ? actionResult.worker_status : {};
        const summary = workerStatus && workerStatus.summary ? workerStatus.summary : (actionResult.summary || {});
        const status = String((summary && summary.status) || '').toLowerCase();
        return ['completed', 'failed', 'cancelled', 'canceled'].indexOf(status) !== -1;
    }

    function stopOffpageBacklinkAuditPolling() {
        if (state.offpageBacklinkAuditTimer) {
            window.clearInterval(state.offpageBacklinkAuditTimer);
            state.offpageBacklinkAuditTimer = null;
        }
        state.offpageBacklinkAuditRefreshing = false;
    }

    function startOffpageBacklinkAuditPolling() {
        stopOffpageBacklinkAuditPolling();
        state.offpageBacklinkAuditTimer = window.setInterval(function() {
            if (state.offpageBacklinkAuditRefreshing) {
                return;
            }
            state.offpageBacklinkAuditRefreshing = true;
            rawAjax('aysa_agent8v3_action', {
                agent_action: 'refresh_offpage_backlink_audit_status',
                state_version: currentVersion(),
                payload: JSON.stringify({})
            }).done(function(response) {
                if (response && response.success) {
                    renderProgressPayload(response, { preserveScroll: true });
                    if (state.modal.key === 'offpage_seo') {
                        loadModal();
                    }
                    if (offpageBacklinkAuditIsTerminal(response)) {
                        stopOffpageBacklinkAuditPolling();
                    }
                }
            }).always(function() {
                state.offpageBacklinkAuditRefreshing = false;
            });
        }, 5000);
    }

    function offpageBacklinkStrategyIsTerminal(payload) {
        const data = payload && payload.data ? payload.data : payload;
        const actionResult = data && data.action_result ? data.action_result : {};
        const workerStatus = actionResult && actionResult.worker_status ? actionResult.worker_status : {};
        const summary = workerStatus && workerStatus.summary ? workerStatus.summary : (actionResult.summary || {});
        const status = String((summary && summary.status) || '').toLowerCase();
        return ['completed', 'failed', 'cancelled', 'canceled'].indexOf(status) !== -1;
    }

    function stopOffpageBacklinkStrategyPolling() {
        if (state.offpageBacklinkStrategyTimer) {
            window.clearInterval(state.offpageBacklinkStrategyTimer);
            state.offpageBacklinkStrategyTimer = null;
        }
        state.offpageBacklinkStrategyRefreshing = false;
    }

    function refreshOffpageBacklinkStrategyOnce(options) {
        options = options || {};
        if (state.offpageBacklinkStrategyRefreshing) {
            return;
        }
        state.offpageBacklinkStrategyRefreshing = true;
        rawAjax('aysa_agent8v3_action', {
            agent_action: 'refresh_offpage_backlink_strategy_status',
            state_version: currentVersion(),
            payload: JSON.stringify({})
        }).done(function(response) {
            if (response && response.success) {
                renderProgressPayload(response, { preserveScroll: true });
                if (state.modal.key === 'offpage_seo') {
                    loadModal();
                }
                if (offpageBacklinkStrategyIsTerminal(response)) {
                    stopOffpageBacklinkStrategyPolling();
                }
            }
        }).always(function() {
            state.offpageBacklinkStrategyRefreshing = false;
            if (typeof options.done === 'function') {
                options.done();
            }
        });
    }

    function startOffpageBacklinkStrategyPolling() {
        stopOffpageBacklinkStrategyPolling();
        state.offpageBacklinkStrategyTimer = window.setInterval(function() {
            refreshOffpageBacklinkStrategyOnce();
        }, 5000);
    }

    function stopMonitoringRefreshPolling() {
        if (state.monitoringRefreshTimer) {
            window.clearTimeout(state.monitoringRefreshTimer);
            state.monitoringRefreshTimer = null;
        }
        state.monitoringRefreshTicks = 0;
        state.monitoringRefreshInFlight = false;
    }

    function monitoringModalHasRunningRefresh(modal) {
        if (!modal || String(modal.modal_key || '') !== 'monitoring') {
            return false;
        }
        const summary = Array.isArray(modal.summary) ? modal.summary : [];
        return summary.some(function(item) {
            const key = String((item && item.key) || '');
            const value = String((item && item.value) || '').toLowerCase();
            return (key === 'rank_run' || key === 'ai_run') && (value.indexOf('running') !== -1 || value.indexOf('queued') !== -1);
        });
    }

    function startMonitoringRefreshPolling() {
        stopMonitoringRefreshPolling();
        const pollOnce = function(forceInitialReadback) {
            if (state.modal.key !== 'monitoring' || state.monitoringRefreshInFlight) {
                if (state.modal.key !== 'monitoring') {
                    stopMonitoringRefreshPolling();
                }
                return;
            }
            if (!forceInitialReadback && !monitoringModalHasRunningRefresh(state.modal.current || {})) {
                stopMonitoringRefreshPolling();
                return;
            }
            state.monitoringRefreshTicks += 1;
            if (state.monitoringRefreshTicks > 60) {
                stopMonitoringRefreshPolling();
                return;
            }
            state.monitoringRefreshInFlight = true;
            loadModal(false, function(nextModal) {
                state.monitoringRefreshInFlight = false;
                if (state.modal.key !== 'monitoring' || !monitoringModalHasRunningRefresh(nextModal || {})) {
                    stopMonitoringRefreshPolling();
                    return;
                }
                state.monitoringRefreshTimer = window.setTimeout(function() {
                    pollOnce(false);
                }, 6000);
            });
        };
        // The first readback is deliberate: policy confirmation has just queued the
        // existing run. Every later poll requires a still-running status.
        pollOnce(true);
    }

    function openModal(modalKey, trigger, initialFilters) {
        if (String(modalKey || '') !== 'monitoring') {
            state.monitoringRefreshPreflight = null;
        }
        state.modal.key = String(modalKey || '');
        state.modal.workspace = isWorkspaceModule(state.modal.key);
        state.modal.viewCache = {};
        state.modal.monitoringFilterState = {};
        state.modal.monitoringTransitioning = false;
        state.modal.monitoringResetScrollAfterLoad = false;
        state.modal.page = 1;
        state.modal.filters = state.modal.key === 'technical_internal_linking' ? { tab: 'link_plan' } : {};
        state.modal.onpageMetadataSelectedItems = {};
        state.modal.onpageMetadataConfirmedSelectionHash = '';
        state.modal.onpageMetadataConfirmedItems = [];
        const requestedTab = trigger && typeof trigger.getAttribute === 'function' ? String(trigger.getAttribute('data-modal-tab') || '') : '';
        if (requestedTab !== '') {
            state.modal.filters.tab = requestedTab;
            if (state.modal.key === 'monitoring' && requestedTab !== 'overview') {
                state.modal.filters.advanced = '1';
            }
        }
        if (trigger && trigger.dataset) {
            Object.keys(trigger.dataset).forEach(function(key) {
                if (key.indexOf('modalFilter') !== 0) {
                    return;
                }
                const suffix = key.slice('modalFilter'.length);
                if (!suffix) {
                    return;
                }
                const filterKey = suffix.replace(/^[A-Z]/, function(match) {
                    return match.toLowerCase();
                }).replace(/[A-Z]/g, function(match) {
                    return '_' + match.toLowerCase();
                });
                state.modal.filters[filterKey] = String(trigger.dataset[key] || '');
            });
        }
        if (initialFilters && typeof initialFilters === 'object') {
            Object.keys(initialFilters).forEach(function(key) {
                state.modal.filters[key] = initialFilters[key];
            });
        }
        state.modal.filters = ensureOnPageProjectionSyncFilter(state.modal.filters);
        state.modal.lastTrigger = trigger || null;
        state.offpageBacklinkStrategyAutoRefreshed = false;
        $('#aysa-agent8v3-modal-search').val('');
        $('#aysa-agent8v3-modal-status').val('all');
        if (state.modal.workspace) {
            enterModuleWorkspace();
            writeModuleWorkspaceRoute();
        } else {
            $('#aysa-agent8v3-modal').prop('hidden', false).attr('aria-hidden', 'false');
        }
        $('.aysa-agent8v3-modal-dialog').trigger('focus');
        loadModal();
    }

    function closeModal() {
        const wasWorkspace = !!state.modal.workspace;
        if (wasWorkspace) {
            leaveModuleWorkspace();
            clearModuleWorkspaceRoute();
        }
        $('#aysa-agent8v3-modal').prop('hidden', true).attr('aria-hidden', 'true');
        state.monitoringRefreshPreflight = null;
        state.modal.key = '';
        state.modal.workspace = false;
        state.modal.monitoringTransitioning = false;
        state.modal.monitoringResetScrollAfterLoad = false;
        $('.aysa-agent8v3-modal-dialog').removeClass('is-monitoring-workspace');
        if (state.modal.lastTrigger && typeof state.modal.lastTrigger.focus === 'function') {
            state.modal.lastTrigger.focus();
        }
    }

    function isWorkspaceModule(modalKey) {
        return [
            'offpage_seo', 'monitoring', 'technical_site_audit', 'technical_pagespeed',
            'technical_schema', 'technical_redirects', 'technical_sitemap_robots',
            'technical_image_alt', 'technical_internal_linking', 'onpage_seo',
            'content_plan', 'research_keywords', 'keyword_mapping', 'missing_pages'
        ].indexOf(String(modalKey || '')) !== -1;
    }

    function enterModuleWorkspace() {
        const $workspace = $('#aysa-agent8v3-module-workspace');
        const $dialog = $('.aysa-agent8v3-modal-dialog');
        if (!$workspace.length || !$dialog.length) {
            return;
        }
        $workspace.append($dialog).prop('hidden', false);
        $('.aysa-agent8v3-chat-panel').prop('hidden', true);
        $('#aysa-agent8v3-modal').prop('hidden', true).attr('aria-hidden', 'true');
        $dialog.attr('aria-modal', 'false');
        $('#aysa-agent8v3-modal-close').text(String(uiLanguage() || '').indexOf('ro') === 0 ? 'Înapoi la conversație' : 'Back to conversation')
            .attr('aria-label', String(uiLanguage() || '').indexOf('ro') === 0 ? 'Înapoi la conversație' : 'Back to conversation');
    }

    function leaveModuleWorkspace() {
        const $modal = $('#aysa-agent8v3-modal');
        const $dialog = $('.aysa-agent8v3-modal-dialog');
        if ($modal.length && $dialog.length) {
            $modal.append($dialog);
        }
        $('#aysa-agent8v3-module-workspace').prop('hidden', true);
        $('.aysa-agent8v3-chat-panel').prop('hidden', false);
        $dialog.attr('aria-modal', 'true');
        $('#aysa-agent8v3-modal-close').text('×');
    }

    function writeModuleWorkspaceRoute() {
        if (!state.modal.workspace || typeof window === 'undefined' || !window.history || !window.history.replaceState) {
            return;
        }
        const url = new URL(window.location.href);
        url.searchParams.set('aysa_agent8_module', state.modal.key);
        const tab = String((state.modal.filters && state.modal.filters.tab) || 'overview');
        if (tab) {
            url.searchParams.set('aysa_agent8_section', tab);
        }
        const sourceRunId = Math.max(0, parseInt((state.modal.filters && state.modal.filters.source_run_id) || '0', 10) || 0);
        if (state.modal.key === 'onpage_seo' && sourceRunId > 0 && tab !== 'execution_report') {
            url.searchParams.set('source_run_id', String(sourceRunId));
        } else if (tab !== 'execution_report') {
            url.searchParams.delete('source_run_id');
        }
        window.history.replaceState({}, '', url.toString());
    }

    function clearModuleWorkspaceRoute() {
        if (typeof window === 'undefined' || !window.history || !window.history.replaceState) {
            return;
        }
        const url = new URL(window.location.href);
        url.searchParams.delete('aysa_agent8_module');
        url.searchParams.delete('aysa_agent8_section');
        url.searchParams.delete('source_run_id');
        window.history.replaceState({}, '', url.toString());
    }

    function openModuleWorkspaceFromQuery() {
        if (typeof window === 'undefined') {
            return;
        }
        const params = new URLSearchParams(window.location.search || '');
        const moduleKey = String(params.get('aysa_agent8_module') || '');
        if (!isWorkspaceModule(moduleKey)) {
            return;
        }
        const section = String(params.get('aysa_agent8_section') || 'overview');
        const filters = { tab: section };
        const sourceRunId = Math.max(0, parseInt(params.get('source_run_id') || '0', 10) || 0);
        if (moduleKey === 'onpage_seo' && sourceRunId > 0) {
            filters.source_run_id = String(sourceRunId);
        }
        if (moduleKey === 'onpage_seo' && section !== 'overview') {
            filters.advanced = '1';
        }
        openModal(moduleKey, null, filters);
    }

    function getOnPageQaModalFixture(requestKey) {
        if (requestKey !== 'onpage_seo' || !cfg.qa_enabled || typeof window === 'undefined') {
            return '';
        }
        try {
            const params = new URLSearchParams(window.location.search || '');
            const mode = String(params.get('aysa_agent8v3_qa_modal_fixture') || '').toLowerCase();
            return ['slow', 'timeout', 'incomplete_identity'].indexOf(mode) !== -1 ? mode : '';
        } catch (error) {
            return '';
        }
    }

    function getOnPageQaHistoryRequest() {
        // Historical execution reports are read-only evidence and may be
        // opened for an explicitly allowlisted QA/admin target even when the
        // broader QA runner is disabled. The synthetic incomplete-evidence
        // fixture remains gated by cfg.qa_enabled in getOnPageQaModalFixture.
        const readOnlyHistoryAllowed = !!cfg.qa_enabled || isFactoryResetAllowedForContext(currentAgent8Context());
        if (!readOnlyHistoryAllowed || typeof window === 'undefined') {
            return null;
        }
        try {
            const params = new URLSearchParams(window.location.search || '');
            const openHistory = String(params.get('aysa_agent8v3_open_onpage_history') || '') === '1';
            const snapshotIdentity = String(params.get('aysa_agent8v3_onpage_snapshot_identity') || '').trim();
            const sourceRunId = String(params.get('aysa_agent8v3_onpage_source_run_id') || '').trim();
            if (!openHistory && !snapshotIdentity && !sourceRunId) {
                return null;
            }
            return {
                snapshot_identity: snapshotIdentity,
                source_run_id: sourceRunId
            };
        } catch (error) {
            return null;
        }
    }

    function openOnPageQaHistoryFromQuery() {
        const request = getOnPageQaHistoryRequest();
        if (!request) {
            return;
        }
        const filters = {
            advanced: '1',
            tab: 'execution_report',
            status: 'all',
            _sync_projection: '0',
            _sync_projection_mode: 'apply_readback'
        };
        if (request.snapshot_identity) {
            filters.snapshot_identity = request.snapshot_identity;
        }
        // A source run can have more than one terminal report. Load the
        // existing read-only history list first; the stable snapshot identity
        // is selected from that list below instead of guessing server-side.
        state.onPageHistorySourceRunId = request.source_run_id || '';
        // QA-only deep link to the existing read-only historical selector.
        // It does not add an action, replay a run, or refresh the projection.
        openModal('onpage_seo', null, filters);
    }

    function loadModal(retriedAfterStale, afterLoad) {
        if (!state.modal.key) {
            return;
        }
        state.modal.requestSeq = (state.modal.requestSeq || 0) + 1;
        const requestSeq = state.modal.requestSeq;
        const requestKey = String(state.modal.key || '');
        const requestPage = state.modal.page;
        const requestFilters = JSON.stringify(state.modal.filters || {});
        const modalCacheKey = [requestKey, requestPage, state.modal.perPage, requestFilters].join('|');
        const isOnPageExecutionReport = String(state.modal.key || '') === 'onpage_seo'
            && String((state.modal.filters || {}).tab || '') === 'execution_report';
        const modalTimeout = isOnPageExecutionReport
            ? 25000
            : (String(state.modal.key || '') === 'onpage_seo'
            ? 25000
            : (String(state.modal.key || '') === 'offpage_seo'
            ? 30000
            : (String(state.modal.key || '') === 'technical_sitemap_robots'
            ? 20000
            : (String(state.modal.key || '').indexOf('technical_') === 0 ? 30000 : (['keyword_mapping', 'research_keywords', 'content_plan'].indexOf(String(state.modal.key || '')) !== -1 ? 30000 : 10000)))));
        const isCurrentModalRequest = function() {
            return state.modal.key === requestKey &&
                state.modal.page === requestPage &&
                JSON.stringify(state.modal.filters || {}) === requestFilters &&
                state.modal.requestSeq === requestSeq;
        };
        if (requestKey === 'monitoring') {
            beginMonitoringTransition();
        }
        if (requestKey === 'monitoring' && state.modal.viewCache && state.modal.viewCache[modalCacheKey]) {
            renderModal(state.modal.viewCache[modalCacheKey]);
            finishMonitoringTransition();
            if (typeof afterLoad === 'function') {
                afterLoad(state.modal.viewCache[modalCacheKey]);
            }
            return;
        }
        if (requestKey === 'monitoring' && $('.aysa-agent8v3-monitoring-results').length) {
            setMonitoringSourceLoading();
        } else {
            setModalLoading();
        }
        const qaModalFixture = getOnPageQaModalFixture(requestKey);
        if (qaModalFixture) {
            // QA-only deterministic loading fixture. It never calls AJAX and
            // cannot trigger a provider, write, billing, or execution path.
            window.setTimeout(function() {
                if (!isCurrentModalRequest()) {
                    return;
                }
                if (qaModalFixture === 'slow') {
                    renderModalSlowLoadingNotice();
                    return;
                }
                if (qaModalFixture === 'incomplete_identity') {
                    renderOnPageIncompleteEvidenceFixture();
                    return;
                }
                renderModalError('modal_timeout');
            }, qaModalFixture === 'slow' ? 120 : 250);
            return;
        }
        const slowFallbackMs = requestKey === 'onpage_seo'
            ? 8000
            : (String(requestKey || '').indexOf('technical_') === 0 ? 9000 : (['research_keywords', 'content_plan', 'monitoring', 'offpage_seo'].indexOf(requestKey) !== -1 ? 8000 : 0));
        if (slowFallbackMs > 0) {
            window.setTimeout(function() {
                if (!isCurrentModalRequest()) {
                    return;
                }
                const bodyStillLoading = $('#aysa-agent8v3-modal-body .aysa-agent8v3-modal-loading-card').length > 0;
                if (!bodyStillLoading) {
                    return;
                }
                renderModalSlowLoadingNotice();
            }, slowFallbackMs);
        }
        rawAjax('aysa_agent8v3_modal', {
            modal_key: requestKey,
            state_version: 0,
            conversation_language: uiLanguage(),
            page: requestPage,
            per_page: state.modal.perPage,
            filters: requestFilters
        }, { timeout: modalTimeout }).done(function(response) {
            if (!isCurrentModalRequest()) {
                if (typeof afterLoad === 'function') {
                    afterLoad(null);
                }
                return;
            }
            if (response && response.data && response.data.wallet_snapshot && typeof response.data.wallet_snapshot === 'object') {
                state.walletSnapshot = response.data.wallet_snapshot;
                renderCredits();
            }
            if (!response || !response.success || !response.data || !response.data.modal) {
                if (isStaleStateResponse(response) && !retriedAfterStale) {
                    rawAjax('aysa_agent8v3_state', {}).done(function(stateResponse) {
                        if (!isCurrentModalRequest()) {
                            return;
                        }
                        if (stateResponse && stateResponse.success) {
                            renderPayload(stateResponse, {
                                silent: true
                            });
                            loadModal(true, afterLoad);
                        } else {
                            if (typeof afterLoad === 'function') {
                                afterLoad(null);
                            }
                            finishMonitoringTransition();
                            renderModalError('stale_state_version');
                        }
                    }).fail(function() {
                        if (!isCurrentModalRequest()) {
                            if (typeof afterLoad === 'function') {
                                afterLoad(null);
                            }
                            return;
                        }
                        if (typeof afterLoad === 'function') {
                            afterLoad(null);
                        }
                        finishMonitoringTransition();
                        renderModalError('stale_state_version');
                    });
                    return;
                }
                if (typeof afterLoad === 'function') {
                    afterLoad(null);
                }
                finishMonitoringTransition();
                renderModalError(apiErrorMessage(response, 'Modal request failed.'));
                return;
            }
            if (String(response.data.modal.modal_key || '') !== requestKey) {
                if (typeof afterLoad === 'function') {
                    afterLoad(null);
                }
                finishMonitoringTransition();
                return;
            }
            localizeOnPageAeoPreflightModal(response.data.modal);
            if (requestKey === 'monitoring') {
                state.modal.viewCache = state.modal.viewCache || {};
                state.modal.viewCache[modalCacheKey] = response.data.modal;
            }
            renderModal(response.data.modal);
            finishMonitoringTransition();
            if (typeof afterLoad === 'function') {
                afterLoad(response.data.modal);
            }
            if (requestKey === 'onpage_seo' && String((state.modal.filters || {}).tab || '') !== 'execution_report') {
                state.modal.filters._sync_projection = '0';
                state.modal.filters._sync_projection_mode = 'review';
            }
        }).fail(function(xhr, statusText) {
            if (typeof afterLoad === 'function') {
                afterLoad(null);
            }
            if (!isCurrentModalRequest()) {
                return;
            }
            finishMonitoringTransition();
            renderModalError(statusText === 'timeout'
                ? 'modal_timeout'
                : apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Request failed: HTTP ' + xhr.status));
        });
    }

    function modalTitle(modal) {
        if (modal.title) {
            return clientFacingLabel(modal.title);
        }
        if (String(modal.modal_key || '') === 'keyword_mapping') {
            return text('modalKeywordMappingTitle');
        }
        return text('modalReview');
    }

    function modalSubtitle(modal) {
        if (modal.subtitle) {
            return clientFacingLabel(modal.subtitle);
        }
        if (String(modal.modal_key || '') === 'keyword_mapping') {
            return text('modalKeywordMappingSubtitle');
        }
        return '';
    }

    function clientFacingLabel(value) {
        const raw = String(value || '');
        if (!raw) {
            return raw;
        }
        const ro = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const normalized = raw.trim().toLowerCase().replace(/\s+/g, ' ');
        const exact = {
            not_public: ro ? 'Nu este public' : 'Not public',
            objectives: ro ? 'Obiective SEO' : 'SEO objectives',
            rejected: ro ? 'Nesalvat' : 'Not saved',
            free: ro ? 'Fără cost' : 'Free',
            pending: ro ? 'În așteptare' : 'Pending',
            not_available: ro ? 'Indisponibil momentan' : 'Currently unavailable',
            'not available': ro ? 'Indisponibil momentan' : 'Currently unavailable',
            alegere: ro ? 'Selecție' : 'Selection',
            selection: ro ? 'Selecție' : 'Selection',
            'safe fixes': ro ? 'Pot fi aplicate în siguranță' : 'Safe to apply',
            safe_fixes: ro ? 'Pot fi aplicate în siguranță' : 'Safe to apply',
            'requires review': ro ? 'Necesită verificarea ta' : 'Needs your review',
            requires_review: ro ? 'Necesită verificarea ta' : 'Needs your review',
            blocked: ro ? 'Blocat pentru siguranță' : 'Blocked for safety',
            'blocked for safety': ro ? 'Blocat pentru siguranță' : 'Blocked for safety',
            unavailable: ro ? 'Momentan indisponibil' : 'Currently unavailable',
            'report only': ro ? 'Doar raport' : 'Report only',
            report_only: ro ? 'Doar raport' : 'Report only',
            'read-only': ro ? 'Fără cost / doar verificare' : 'Read-only',
            review: ro ? 'De verificat' : 'Needs review',
            trusted: ro ? 'De încredere' : 'Trusted',
            no_gsc_support: ro ? 'Fără date Search Console' : 'No Search Console data',
            'no gsc support': ro ? 'Fără date Search Console' : 'No Search Console data',
            'keywords research': 'Keyword Research',
            'keyword research': 'Keyword Research',
            'duplicate metadata': ro ? 'Titluri sau descrieri duplicate' : 'Duplicate titles or descriptions',
            'canonical / indexability': ro ? 'Canonical și indexare' : 'Canonical and indexability',
            'technical seo overview': ro ? 'Rezumat Technical SEO' : 'Technical SEO summary',
            'broken external links': ro ? 'Linkuri externe cu probleme' : 'Broken external links',
            overview: ro ? 'Rezumat' : 'Overview',
            improved: ro ? 'Îmbunătățite' : 'Improved',
            declined: ro ? 'Scăzute' : 'Declined',
            'workspace keyword research': ro ? 'Date din Keyword Research' : 'Keyword Research data',
            keyword_research_workspace: ro ? 'Date din Keyword Research' : 'Keyword Research data',
            'readiness comenzi': ro ? 'Verificare înainte de comandă' : 'Order preflight',
            'readiness comenzi adverlink': ro ? 'Verificare înainte de comandă' : 'Order preflight',
            'order readiness': ro ? 'Verificare înainte de comandă' : 'Order preflight',
            mvp: ro ? 'Disponibilitate controlată' : 'Controlled availability',
            noop: ro ? 'Sincronizare fără schimbări' : 'No change needed',
            draft_id: ro ? 'Draft' : 'Draft',
            blocked_publisher_binding_missing: ro ? 'Publicarea este blocată până la conectarea publisherului' : 'Publishing is blocked until the publisher is connected',
            'qa simulation': ro ? 'Simulare de test, fără comandă reală' : 'Test simulation, no real order',
            'qa simulation only': ro ? 'Doar simulare de test' : 'Test simulation only',
            'dry-run': ro ? 'Simulare fără execuție' : 'No-write simulation',
            endpoint: ro ? 'Integrare' : 'Integration',
            billed: ro ? 'Cost înregistrat' : 'Cost recorded',
            'gpt-5.5': ro ? 'Model AI' : 'AI model',
            gsc_not_connected: ro ? 'Search Console nu este conectat' : 'Search Console is not connected',
            ai_snapshot_missing: ro ? 'Nu există încă date salvate despre vizibilitatea AI' : 'No saved AI visibility data yet',
            policy_missing: ro ? 'Politica trebuie pregătită' : 'Policy needs setup',
            needs_confirmation: ro ? 'Necesită confirmare' : 'Needs confirmation',
            confirmed: ro ? 'Confirmată' : 'Confirmed',
            requires_reconfirmation: ro ? 'Necesită reconfirmare' : 'Needs reconfirmation',
            blocked_scope_changed: ro ? 'Necesită confirmare după schimbarea scope-ului' : 'Needs confirmation after scope change',
            blocked_cost_changed: ro ? 'Necesită confirmare după schimbarea costului' : 'Needs confirmation after cost change',
            baseline_only: ro ? 'Avem doar o verificare inițială' : 'Only an initial check is available',
            requires_two_comparable_checks: ro ? 'Sunt necesare cel puțin două verificări comparabile' : 'At least two comparable checks are required',
            preflight_blocker: ro ? 'Lipsește o condiție înainte de acțiune' : 'A requirement is missing before the action',
            missing_gsc_connection: ro ? 'Lipsește conexiunea Search Console' : 'Search Console connection is missing',
            missing_ai_prompt_pack: ro ? 'Lipsește setul de întrebări pentru AI Visibility' : 'AI Visibility question set is missing',
            type: ro ? 'Tip' : 'Type',
            handoff: ro ? 'Următorul flux' : 'Next flow',
            caveat: ro ? 'Limită' : 'Limit',
            'draft only': ro ? 'Doar draft' : 'Draft only',
            draft_only: ro ? 'Doar draft' : 'Draft only',
            'simulare lifecycle adverlink': ro ? 'Simulare comandă și status' : 'Order status simulation',
            'adverlink lifecycle simulation': ro ? 'Simulare comandă și status' : 'Order status simulation',
            'schimb de linkuri aysa': ro ? 'Schimb de linkuri' : 'Link exchange',
            'simulare publicare rețea proprie': ro ? 'Simulare publicare' : 'Publish simulation',
            'marketplace articole': ro ? 'Articole marketplace' : 'Article marketplace',
            'plasare rețea proprie': ro ? 'Plasare în rețeaua proprie' : 'Owned network placement',
            'draft rețea proprie': ro ? 'Draft pentru rețeaua proprie' : 'Owned network draft',
            'binding publisher': ro ? 'Conectare publisher' : 'Publisher connection',
            'preflight publicare rețea proprie': ro ? 'Verificare înainte de publicare' : 'Owned publish preflight',
            'draft only / fara publicare': ro ? 'Doar draft / fără publicare' : 'Draft only / no publishing',
            'fara publicare': ro ? 'Fără publicare' : 'No publishing',
            'fara comanda': ro ? 'Fără comandă' : 'No order',
            'fara debit': ro ? 'Fără debit' : 'No debit',
            'fara actiuni externe': ro ? 'Fără acțiuni externe' : 'No external actions',
            'fara gbp write': ro ? 'Fără modificări Google Business Profile' : 'No Google Business Profile writes',
            'fără cost / doar verificare': ro ? 'Fără cost / doar verificare' : 'Free / review only',
            'preflight fără debit': ro ? 'Preflight fără debit' : 'Preflight, no debit',
            'poate consuma credite': ro ? 'Poate consuma credite' : 'May use credits',
            'generează propuneri': ro ? 'Generează propuneri' : 'Generates proposals',
            'necesită confirmare înainte de aplicare': ro ? 'Necesită confirmare înainte de aplicare' : 'Requires confirmation before apply',
            'aplică modificări pe site': ro ? 'Aplică modificări pe site' : 'Applies site changes',
            'comandă externă / provider': ro ? 'Comandă externă / provider' : 'External order / provider',
            publicare: ro ? 'Publicare' : 'Publishing',
            completed_with_pending_provider: ro ? 'Finalizat; așteaptă estimare provider' : 'Completed; waiting for provider estimate',
            not_started: ro ? 'Nepornit încă' : 'Not started yet',
            all: ro ? 'Toate' : 'All',
            'missing portal': ro ? 'Portal lipsă' : 'Missing portal',
            missing_portal: ro ? 'Portal lipsă' : 'Missing portal',
            'missing cost': ro ? 'Cost lipsă' : 'Missing cost',
            missing_cost: ro ? 'Cost lipsă' : 'Missing cost',
            'requires final confirmation': ro ? 'Necesită confirmare finală' : 'Requires final confirmation',
            requires_final_confirmation: ro ? 'Necesită confirmare finală' : 'Requires final confirmation',
            'completed with warnings': ro ? 'Finalizat, necesită verificare' : 'Completed, needs review',
            completed_with_warnings: ro ? 'Finalizat, necesită verificare' : 'Completed, needs review',
            target_homepage_fallback_requires_approval: ro ? 'Homepage-ul necesită confirmare explicită' : 'Homepage requires explicit confirmation',
            excluded_until_corrected_or_approved: ro ? 'Exclus până la corectare sau aprobare' : 'Excluded until corrected or approved',
            'google text ads': 'Google Text Ads'
        };
        if (exact[normalized]) {
            return exact[normalized];
        }
        let output = raw;
        [
            ['not_available', ro ? 'Indisponibil momentan' : 'Currently unavailable'],
            ['completed_with_pending_provider', ro ? 'Finalizat; așteaptă estimare provider' : 'Completed; waiting for provider estimate'],
            ['not_started', ro ? 'Nepornit încă' : 'Not started yet'],
            ['Draft only', ro ? 'Doar drafturi' : 'Drafts only'],
            ['Missing portal', ro ? 'Portal lipsă' : 'Missing portal'],
            ['Missing cost', ro ? 'Cost lipsă' : 'Missing cost'],
            ['Requires final confirmation', ro ? 'Necesită confirmare finală' : 'Requires final confirmation'],
            ['target_homepage_fallback_requires_approval', ro ? 'Homepage-ul necesită confirmare explicită' : 'Homepage requires explicit confirmation'],
            ['excluded_until_corrected_or_approved', ro ? 'Exclus până la corectare sau aprobare' : 'Excluded until corrected or approved'],
            ['keyword_research_workspace', ro ? 'Date din Keyword Research' : 'Keyword Research data'],
            ['Workspace Keyword Research', ro ? 'Date din Keyword Research' : 'Keyword Research data'],
            ['Keywords Research', 'Keyword Research'],
            ['no_gsc_support', ro ? 'Fără date Search Console' : 'No Search Console data'],
            ['no gsc support', ro ? 'Fără date Search Console' : 'No Search Console data'],
            ['Duplicate Metadata', ro ? 'Titluri sau descrieri duplicate' : 'Duplicate titles or descriptions'],
            ['Canonical / Indexability', ro ? 'Canonical și indexare' : 'Canonical and indexability'],
            ['Technical SEO Overview', ro ? 'Rezumat Technical SEO' : 'Technical SEO summary'],
            ['Broken external links', ro ? 'Linkuri externe cu probleme' : 'Broken external links'],
            ['Readiness comenzi', ro ? 'Verificare înainte de comandă' : 'Order preflight'],
            ['Schimb de linkuri AYSA', ro ? 'Schimb de linkuri' : 'Link exchange'],
            ['Simulare publicare rețea proprie', ro ? 'Simulare publicare' : 'Publish simulation'],
            ['Marketplace articole', ro ? 'Articole marketplace' : 'Article marketplace'],
            ['DRAFT ONLY', ro ? 'Doar draft' : 'Draft only'],
            ['FARA PUBLICARE', ro ? 'Fără publicare' : 'No publishing'],
            ['FARA COMANDA', ro ? 'Fără comandă' : 'No order'],
            ['FARA DEBIT', ro ? 'Fără debit' : 'No debit'],
            ['FARA ACTIUNI EXTERNE', ro ? 'Fără acțiuni externe' : 'No external actions'],
            ['FARA GBP WRITE', ro ? 'Fără modificări Google Business Profile' : 'No Google Business Profile writes'],
            ['QA SIMULATION ONLY', ro ? 'Doar simulare de test' : 'Test simulation only'],
            ['QA SIMULATION', ro ? 'Simulare de test, fără comandă reală' : 'Test simulation, no real order'],
            ['blocked_publisher_binding_missing', ro ? 'Publicarea este blocată până la conectarea publisherului' : 'Publishing is blocked until the publisher is connected'],
            ['draft_id', ro ? 'Draft' : 'Draft'],
            ['dry-run', ro ? 'Simulare fără execuție' : 'No-write simulation'],
            ['date de acțiunes', 'date de acțiune'],
            ['regulă de aprobareul', 'regula de aprobare'],
            ['Autoactivare Pornită', ro ? 'Autoactivare indisponibilă în această versiune beta' : 'Auto-activation unavailable in this beta version'],
            ['Autoactivare inactivă în MVP', ro ? 'Autoactivare indisponibilă în această versiune beta' : 'Auto-activation unavailable in this beta version'],
            [' în MVP', ro ? ' în versiunea beta' : ' in the beta version'],
            [' in MVP', ro ? ' în versiunea beta' : ' in the beta version'],
            ['MVP', ro ? 'versiune beta' : 'beta version']
        ].forEach(function(pair) {
            output = output.split(pair[0]).join(pair[1]);
        });
        return output;
    }

    function mergeBillingSnapshot(previous, next) {
        const prior = previous && typeof previous === 'object' ? previous : null;
        const incoming = next && typeof next === 'object' ? next : null;
        if (!incoming) {
            return prior;
        }
        const incomingActual = Math.max(0, Number(incoming.actual_credits_cents || 0));
        const incomingBillable = !!incoming.billable || !!String(incoming.last_billable_action || '').trim();
        if (incomingActual > 0 || incomingBillable || !prior) {
            return incoming;
        }
        const priorActual = Math.max(0, Number(prior.actual_credits_cents || 0));
        return priorActual > 0 ? prior : incoming;
    }

    function modalLabel(label, key) {
        const labels = {
            cluster: 'modalCluster',
            target_url: 'modalTargetUrl',
            primary_keyword: 'modalPrimaryKeyword',
            keyword_family: 'modalKeywordFamily',
            signals: 'modalSignals',
            intent: 'modalIntent',
            status: 'modalStatus',
            confidence: 'modalConfidence',
            trust_score: 'modalTrust',
            recommendation: 'modalRecommendation',
            quality_reasons: 'modalReasons',
            execution_status: 'execution_status',
            automation_status: 'modalAutomation',
            review_status: 'modalReview',
            review_action: 'modalAction',
            accepted: 'modalAccepted',
            rejected: 'modalRejected',
            executable: 'executable',
            queued: 'queued',
            skipped: 'skipped',
            applied: 'applied',
            failed: 'failed',
            not_executable_yet: 'not_executable_yet',
            not_executable: 'notExecutableHuman',
            submitted: 'submitted',
            synced: 'synced',
            ready: 'statusReady',
            completed_with_warnings: 'statusCompletedWithWarnings',
            manual_needed: 'manualNeededHuman',
            needs_improvement: 'needsImprovementHuman',
            excellent: 'excellentHuman',
            trusted: 'modalTrusted',
            recommended_reject: 'modalRecommendedReject',
            review: 'modalReviewNeeded'
        };
        return labels[key] ? text(labels[key]) : clientFacingLabel(label || key || '');
    }

    function modalDisplayValue(value, key) {
        const raw = String(value || '');
        if (
            String(key || '') === 'execution_contract'
            || raw === 'existing_execute_technical_fix_plan_per_module'
            || raw.indexOf('contractele Technical SEO existente') !== -1
            || raw.indexOf('existing Technical SEO contracts') !== -1
        ) {
            return String(uiLanguage() || '').indexOf('ro') === 0
                ? 'Prin contractele Technical SEO existente'
                : 'Through the existing Technical SEO contracts';
        }
        if (String(key || '') === 'status' || String(key || '') === 'execution_status') {
            return modalLabel(raw, raw);
        }
        if (state.modal && String(state.modal.key || '').indexOf('technical_') === 0) {
            return technicalClientDisplayText(raw);
        }
        return clientFacingLabel(raw);
    }

    function technicalClientDisplayText(value) {
        let output = String(value || '');
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const urlTokens = [];
        output = output.replace(/https?:\/\/[^\s<>"']+/gi, function(url) {
            const token = 'AYSAURLTOKEN' + urlTokens.length + 'X';
            urlTokens.push([token, url]);
            return token;
        });
        const replacements = [
            [/\bOverall score\b/gi, ro ? 'Scor general' : 'Overall score'],
            [/\bDesktop score\b/gi, ro ? 'Scor desktop' : 'Desktop score'],
            [/\bMobile score\b/gi, ro ? 'Scor mobile' : 'Mobile score'],
            [/\bMobile friendly\b/gi, ro ? 'Compatibil mobil' : 'Mobile friendly'],
            [/\bgood\b/gi, ro ? 'bun' : 'good'],
            [/\bneeds improvement\b/gi, ro ? 'necesită îmbunătățiri' : 'needs improvement'],
            [/\bpoor\b/gi, ro ? 'slab' : 'poor'],
            [/\bbaseline with optimization room\b/gi, ro ? 'nivel bun, cu spațiu de optimizare' : 'baseline with optimization room'],
            [/\bPrioritize highest impact fixes\b/gi, ro ? 'Prioritizează remedierile cu impactul cel mai mare' : 'Prioritize highest impact fixes'],
            [/\bReview manual\b/gi, ro ? 'Verificare manuală' : 'Manual review'],
            [/\bSAFE FIXES\b/g, ro ? 'Pot fi aplicate în siguranță' : 'Safe to apply'],
            [/\bREQUIRES REVIEW\b/g, ro ? 'Necesită verificarea ta' : 'Needs your review'],
            [/\bREPORT ONLY\b/g, ro ? 'Doar raport' : 'Report only'],
            [/\bDuplicate Metadata\b/gi, ro ? 'Titluri sau descrieri duplicate' : 'Duplicate titles or descriptions'],
            [/\bCanonical \/ Indexability\b/gi, ro ? 'Canonical și indexare' : 'Canonical and indexability'],
            [/\bTechnical SEO Overview\b/gi, ro ? 'Rezumat Technical SEO' : 'Technical SEO summary'],
            [/\bBroken external links\b/gi, ro ? 'Linkuri externe cu probleme' : 'Broken external links'],
            [/\bReview manually or route to editorial work\b/gi, ro ? 'Trimite la verificare editorială manuală' : 'Review manually or route to editorial work'],
            [/\bExternal broken links are report\/review items unless a future editorial safety rule exists\b/gi, ro ? 'Linkurile externe rupte sunt raportate pentru verificare editorială, fără aplicare automată.' : 'External broken links are report/review items unless a future editorial safety rule exists.'],
            [/\bManual review needed\b/gi, ro ? 'Necesită verificare manuală' : 'Manual review needed'],
            [/\bSearch review data\b/gi, ro ? 'Caută în datele review-ului' : 'Search review data'],
            [/\bKeyword status\b/gi, ro ? 'Status keyword' : 'Keyword status'],
            [/\bPrevious\b/gi, ro ? 'Înapoi' : 'Previous'],
            [/\bNext\b/gi, ro ? 'Înainte' : 'Next'],
            [/\bmodel R3\b/gi, ro ? 'verificare de siguranță pentru redirecturi' : 'redirect safety check'],
            [/\bprovider_adapter_required\b/gi, ro ? 'necesită configurare sigură' : 'safe setup required'],
            [/\bprovider_urls\b/gi, ro ? 'URL-uri existente' : 'existing URLs'],
            [/\b[a-z0-9_]*provider[a-z0-9_]*\b/gi, ro ? 'configurare sigură necesară' : 'safe setup required'],
            [/\bprovider\b/gi, ro ? 'sursă' : 'source'],
            [/\b[a-z0-9_]*billing[a-z0-9_]*\b/gi, ro ? 'debitare controlată' : 'controlled charging'],
            [/\bbilling\b/gi, ro ? 'debitare' : 'charging'],
            [/\bledger\b/gi, ro ? 'înregistrare de credit' : 'credit record'],
            [/\b[a-z0-9_]*gate[a-z0-9_]*\b/gi, ro ? 'verificare de siguranță' : 'safety check'],
            [/\bgate\b/gi, ro ? 'siguranță' : 'safety'],
            [/\broute evidence\b/gi, ro ? 'dovadă că poate fi aplicat și verificat' : 'proof it can be applied and verified'],
            [/\b[a-z0-9_]*contract[a-z0-9_]*\b/gi, ro ? 'pregătire necesară' : 'preparation required'],
            [/\bcontract\b/gi, ro ? 'pregătire' : 'preparation'],
            [/\breadiness\b/gi, ro ? 'stare' : 'status'],
            [/\bdry[- ]run\b/gi, ro ? 'verificare fără modificări' : 'no-change check'],
            [/\breadback\b/gi, ro ? 'verificare după aplicare' : 'post-apply check'],
            [/\btakeover\b/gi, ro ? 'preluare controlată' : 'controlled takeover'],
            [/\bparity\b/gi, ro ? 'comparație' : 'comparison'],
            [/\bcompact snapshot\b/gi, ro ? 'rezumat' : 'summary'],
            [/\bcompact\b/gi, ro ? 'rezumat' : 'summary'],
            [/\bsnapshot\b/gi, ro ? 'date salvate' : 'saved data'],
            [/\bstage\b/gi, ro ? 'etapă' : 'step'],
            [/\bbridge\b/gi, ro ? 'verificare de conectare' : 'connection check'],
            [/\baprobares\b/gi, ro ? 'aprobări' : 'approvals'],
            [/\brestore\b/gi, ro ? 'revenire' : 'restore'],
            [/\bworker\b/gi, ro ? 'proces de fundal' : 'background process'],
            [/\bpayload\b/gi, ro ? 'date trimise' : 'submitted data'],
            [/\btask\b/gi, ro ? 'acțiune' : 'action'],
            [/\bexecutor\b/gi, ro ? 'mecanism de aplicare' : 'apply mechanism'],
            [/\bprojection\b/gi, ro ? 'afișare' : 'view'],
            [/\bstate\b/gi, ro ? 'stare salvată' : 'saved state'],
            [/\brun_id\b/gi, ro ? 'referință' : 'reference'],
            [/\bparity_pass\b/gi, ro ? 'verificat' : 'verified'],
            [/\binsufficient_data\b/gi, ro ? 'date insuficiente' : 'not enough data'],
            [/\bblocked\b/gi, ro ? 'Blocat pentru siguranță' : 'Blocked for safety'],
            [/\b[a-z]+(?:_[a-z0-9]+){1,}\b/g, ro ? 'verificare necesară' : 'needs review']
        ];
        replacements.forEach(function(pair) {
            output = output.replace(pair[0], pair[1]);
        });
        urlTokens.forEach(function(pair) {
            output = output.replace(pair[0], pair[1]);
        });
        return output;
    }

    function isTechnicalFixExecutionAction(action) {
        return String(action && action.action ? action.action : '') === 'execute_technical_fix_plan';
    }

    function technicalFixExecutionStatusLabel(status) {
        const key = String(status || '').toLowerCase();
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const labels = {
            submitted: ro ? 'trimis, în așteptarea execuției' : 'submitted, pending execution',
            queued: ro ? 'în coadă' : 'queued',
            running: ro ? 'în execuție' : 'running',
            completed_no_writes: ro ? 'finalizat fără modificări pe site' : 'completed without site changes',
            blocked: ro ? 'blocat de rollout' : 'blocked by rollout',
            partial_failed: ro ? 'parțial raportat de site' : 'partially reported by site',
            auth_mismatch: ro ? 'auth nepotrivit' : 'auth mismatch',
            no_executable_fixes: ro ? 'fără fixuri executabile' : 'no executable fixes',
            synced: ro ? 'sincronizat, în așteptarea verificării' : 'synced, pending verification',
            already_synced: ro ? 'raportat deja de site, în așteptarea verificării' : 'already reported by site, pending verification',
            applied: ro ? 'raportat aplicat, în așteptarea verificării' : 'reported applied, pending verification',
            verified: ro ? 'raportat verificat, în așteptarea confirmării' : 'reported verified, pending confirmation',
            failed: ro ? 'eșuat' : 'failed',
            skipped: ro ? 'omis, fără acțiune sigură necesară' : 'skipped, no safe action needed',
            manual_review_needed: ro ? 'necesită verificare' : 'needs review',
            schema_preview_required: ro ? 'pregătește preview Schema' : 'prepare Schema preview',
            not_started: ro ? 'plan netrimis' : 'plan not submitted'
        };
        return labels[key] || (status || '');
    }

    function renderTechnicalFixExecutionProgress(progress) {
        if (!progress || typeof progress !== 'object') {
            return '';
        }
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const status = progress.status_label || technicalFixExecutionStatusLabel(progress.status || 'not_started');
        const worker = progress.worker_status_label || (progress.worker_status ? technicalFixExecutionStatusLabel(progress.worker_status) : '');
        const ids = [];
        if (progress.run_id) {
            ids.push('run ' + String(progress.run_id));
        }
        if (progress.task_id) {
            ids.push('task ' + String(progress.task_id));
        }
        if (progress.job_id && String(progress.job_id) !== String(progress.run_id || '')) {
            ids.push('job ' + String(progress.job_id));
        }
        const details = [
            progress.message || '',
            progress.preflight_status_label ? ((ro ? 'preflight: ' : 'preflight: ') + progress.preflight_status_label) : '',
            progress.preflight_message || '',
            progress.bridge_auth_status_label ? ((ro ? 'bridge auth: ' : 'bridge auth: ') + progress.bridge_auth_status_label) : '',
            progress.bridge_context_status_label ? ((ro ? 'bridge context: ' : 'bridge context: ') + progress.bridge_context_status_label) : '',
            progress.confirmation_level === 'strong' ? (ro ? 'confirmare puternică necesară' : 'strong confirmation required') : '',
            worker && worker !== status ? worker : '',
            ids.join(' / '),
            progress.last_checked_at ? ((ro ? 'verificat: ' : 'checked: ') + progress.last_checked_at) : (progress.submitted_at ? ((ro ? 'trimis: ' : 'submitted: ') + progress.submitted_at) : ''),
            progress.writes_enabled === false ? (ro ? 'fără modificări pe site' : 'no site changes') : ''
        ].filter(function(part) { return String(part || '').trim() !== ''; });
        return '<div class="aysa-agent8v3-modal-action-progress">' +
            '<span class="aysa-agent8v3-modal-action-status">' + escapeHtml(status) + '</span>' +
            (details.length ? '<span>' + escapeHtml(details.join(' · ')) + '</span>' : '') +
            '</div>';
    }

    function technicalFixExecutionSummaryLabel(key) {
        const normalized = String(key || '');
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        if (normalized === 'reported_applied_pending_verification') {
            return ro ? 'raportat de site, în așteptarea verificării' : 'reported by site, pending verification';
        }
        return modalLabel(normalized, normalized);
    }

    function technicalFixExecutionSummaryKeys() {
        return ['total', 'accepted', 'rejected', 'filtered', 'included', 'remaining', 'executable', 'manual_needed', 'queued', 'reported_applied_pending_verification', 'skipped', 'failed'];
    }

    function selectedTechnicalImageAltApplyItems() {
        const items = [];
        $('.aysa-agent8v3-image-alt-apply-row:checked').each(function() {
            try {
                const raw = String($(this).attr('data-payload') || '{}');
                const item = JSON.parse(raw);
                if (item && typeof item === 'object') {
                    item.accepted_by_user = true;
                    item.review_status = 'accepted';
                    item.operation = item.operation || 'site_audit_image_alt_apply';
                    item.attachment_id = parseInt(item.attachment_id || item.media_id || 0, 10) || 0;
                    item.media_id = item.attachment_id;
                    item.old_alt = String(item.old_alt || item.current_alt || item.old_value || '');
                    item.old_alt_captured = Object.prototype.hasOwnProperty.call(item, 'old_alt') ||
                        Object.prototype.hasOwnProperty.call(item, 'current_alt') ||
                        Object.prototype.hasOwnProperty.call(item, 'old_value');
                    item.proposed_alt = String(item.proposed_alt || item.proposed_value || '');
                    items.push(item);
                }
            } catch (error) {
                // Ignore malformed row payloads; the API validates selected_items again.
            }
        });
        return items;
    }

    function confirmTechnicalImageAltApply(payload) {
        payload = payload && typeof payload === 'object' ? payload : {};
        if (payload.confirmation_kind !== 'technical_image_alt_apply') {
            return true;
        }
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const selected = selectedTechnicalImageAltApplyItems();
        if (!selected.length) {
            window.alert(ro ? 'Selectează cel puțin un rând Image Alt.' : 'Select at least one Image Alt row.');
            return false;
        }
        const count = selected.length;
        const examples = selected.slice(0, 5).map(function(item) {
            return {
                old_alt: String(item.old_alt || item.current_alt || item.old_value || ''),
                new_alt: String(item.proposed_alt || item.proposed_value || '')
            };
        });
        const wallet = state.walletSnapshot && typeof state.walletSnapshot === 'object' ? state.walletSnapshot : {};
        const projectId = parseInt(wallet.project_id || payload.project_id || 0, 10) || 0;
        const balance = parseInt(wallet.balance_cents || wallet.available_credits_cents || 0, 10) || 0;
        const spendable = parseInt(wallet.spendable_cents || wallet.available_credits_cents || balance || 0, 10) || 0;
        const unitCost = parseInt(payload.billing_unit_cents || 5, 10) || 5;
        const maxCost = parseInt(payload.max_cost_cents || (count * unitCost), 10) || 0;
        const lines = [
            ro
                ? 'AYSA va actualiza textul alt pentru imaginile selectate.'
                : 'AYSA will update image alt text for the selected images.',
            ro
                ? ('Imagini selectate: ' + String(count))
                : ('Selected images: ' + String(count)),
            ro
                ? ('Identitate billing AYSA: proiect ' + (projectId ? String(projectId) : 'necunoscut') + '. Emailul administratorului WordPress nu este folosit pentru debitare.')
                : ('AYSA billing identity: project ' + (projectId ? String(projectId) : 'unknown') + '. The WordPress admin email is not used for billing.'),
            ro
                ? ('Credite disponibile: ' + String(spendable) + ' / sold: ' + String(balance))
                : ('Spendable credits: ' + String(spendable) + ' / balance: ' + String(balance)),
            ro
                ? ('Cost maxim: ' + String(maxCost) + ' (' + String(unitCost) + ' / imagine schimbată și verificată)')
                : ('Max cost: ' + String(maxCost) + ' (' + String(unitCost) + ' / changed and verified image)'),
        ];
        if (examples.length) {
            lines.push('');
            lines.push(ro ? 'Exemple:' : 'Examples:');
            examples.forEach(function(example) {
                const oldAlt = String(example.old_alt || '').trim() || '-';
                const newAlt = String(example.new_alt || '').trim() || '-';
                lines.push('- ' + oldAlt + ' -> ' + newAlt);
            });
        }
        lines.push('');
        lines.push(ro
            ? 'Se debitează doar imaginile schimbate și verificate prin readback. Skipped/no-change/failed nu se debitează.'
            : 'You are charged only for changed images verified by readback. Skipped/no-change/failed items are not charged.');
        lines.push(ro
            ? 'Se modifică doar textul alt al imaginilor. Nu se modifică redirects, schema, sitemap, robots, linkuri interne sau conținut.'
            : 'Only image alt text will be updated. No redirects, schema, sitemap, robots, internal links or content will be changed.');
        lines.push('');
        lines.push(ro
            ? 'Continuă doar dacă ai verificat aceste propuneri.'
            : 'Continue only if you reviewed these proposals.');
        return window.confirm(lines.join('\n'));
    }

    function confirmTechnicalImageAltApplyAndMark(payload) {
        payload = payload && typeof payload === 'object' ? payload : {};
        if (payload.confirmation_kind !== 'technical_image_alt_apply') {
            return true;
        }
        if (!confirmTechnicalImageAltApply(payload)) {
            return false;
        }
        const selected = selectedTechnicalImageAltApplyItems();
        const capabilityContractRevision = 'technical_image_alt_controlled_beta_v2';
        const batchSeed = selected.map(function(item) {
            return [
                String(item.fix_id || item.row_id || item.item_id || ''),
                String(item.attachment_id || item.media_id || ''),
                String(item.proposed_alt || item.proposed_value || '')
            ].join('|');
        }).sort().concat([capabilityContractRevision]).join('|');
        const batchId = 'image_alt_batch_' + simpleStableHash(batchSeed);
        payload.selected_items = selected;
        payload.accepted_fixes = selected;
        payload.accepted_count = selected.length;
        payload.accepted_fix_count = selected.length;
        payload.confirmation_count = selected.length;
        payload.action_contract = 'technical_seo_image_alt_apply_accepted';
        payload.batch_id = batchId;
        payload.batch_idempotency_key = 'agent8v3:technical_seo_image_alt_apply_accepted:' + batchId;
        payload.idempotency_key = payload.batch_idempotency_key;
        const wallet = state.walletSnapshot && typeof state.walletSnapshot === 'object' ? state.walletSnapshot : {};
        const projectId = parseInt(wallet.project_id || payload.project_id || cfg.project_id || cfg.wp_project_id || 0, 10) || 0;
        const confirmationIdentity = simpleStableHash([
            String(projectId || cfg.project_id || cfg.wp_project_id || '0'),
            String(cfg.website_id || '0'),
            String(cfg.site_host || window.location.hostname || '').toLowerCase(),
            'technical_image_alt_apply',
            batchId
        ].join('|'));
        payload.bundle_confirmation_kind = 'technical_seo_apply_accepted_bundle';
        payload.bundle_confirmation_identity = confirmationIdentity;
        payload.bundle_execution_id = 'technical_bundle_execution_' + simpleStableHash([
            'image_alt',
            payload.idempotency_key,
            confirmationIdentity
        ].join('|'));
        payload.bundle_module_index = 1;
        payload.bundle_module_count = 1;
        payload.capability_contract_revision = capabilityContractRevision;
        payload.capability_activation_requested = true;
        payload.temporary_product_gates = true;
        payload.max_cost_cents = selected.length * (Math.max(1, parseInt(payload.billing_unit_cents || 5, 10) || 5));
        payload.user_confirmed = true;
        payload.confirmed_by_user = true;
        return true;
    }

    function confirmTechnicalImageAltProposalGenerationAndMark(payload) {
        payload = payload && typeof payload === 'object' ? payload : {};
        if (payload.confirmation_kind !== 'technical_image_alt_proposal_generation') {
            return true;
        }
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const estimate = parseInt(payload.estimated_cost_cents || payload.estimated_min_cost_cents || 0, 10) || 0;
        const maxCost = parseInt(payload.max_total_cost_cents || payload.max_cost_cents || payload.max_total_cost || 0, 10) || 0;
        if (estimate <= 0) {
            window.alert(ro ? 'Nu pot porni generarea Image Alt fără cost estimat.' : 'Image Alt generation cannot start without an estimated cost.');
            return false;
        }
        if (maxCost <= 0) {
            window.alert(ro ? 'Nu pot porni generarea Image Alt fără plafon maxim aprobat.' : 'Image Alt generation cannot start without an approved maximum cap.');
            return false;
        }
        if (maxCost < estimate) {
            window.alert(ro ? 'Plafonul maxim este sub costul estimat.' : 'The maximum cap is below the estimated cost.');
            return false;
        }
        const wallet = state.walletSnapshot && typeof state.walletSnapshot === 'object' ? state.walletSnapshot : {};
        const balance = parseInt(wallet.balance_cents || wallet.available_credits_cents || 0, 10) || 0;
        const spendable = parseInt(wallet.spendable_cents || wallet.available_credits_cents || balance || 0, 10) || 0;
        if (spendable > 0 && spendable < maxCost) {
            window.alert(ro
                ? ('Credite insuficiente pentru generarea Image Alt. Disponibil: ' + String(spendable) + ', necesar maxim: ' + String(maxCost) + '.')
                : ('Insufficient credits for Image Alt generation. Available: ' + String(spendable) + ', maximum required: ' + String(maxCost) + '.'));
            return false;
        }
        const billingActionKey = String(payload.billing_action_key || 'site_audit_image_alt_generate');
        const providerAdapter = String(payload.provider_adapter || 'legacy_technical_site_audit_worker');
        const lines = [
            ro
                ? 'AYSA va genera doar propuneri Image Alt pentru review.'
                : 'AYSA will generate Image Alt proposals for review only.',
            ro
                ? ('Cost estimat: ' + String(estimate) + ' credite. Cost maxim aprobat: ' + String(maxCost) + ' credite.')
                : ('Estimated cost: ' + String(estimate) + ' credits. Approved max cost: ' + String(maxCost) + ' credits.'),
            ro
                ? ('Credite disponibile: ' + String(spendable) + ' / sold: ' + String(balance))
                : ('Spendable credits: ' + String(spendable) + ' / balance: ' + String(balance)),
            ro
                ? ('Acțiune billing: ' + billingActionKey)
                : ('Billing action: ' + billingActionKey),
            ro
                ? ('Adaptor: ' + providerAdapter)
                : ('Adapter: ' + providerAdapter),
            '',
            ro
                ? 'Nu se aplică alt text, nu se scrie în WordPress, nu se optimizează WebP și nu se publică nimic.'
                : 'No alt text is applied, WordPress is not modified, WebP is not optimized, and nothing is published.',
            ro
                ? 'Continuă doar dacă aprobi acest plafon de cost.'
                : 'Continue only if you approve this cost cap.'
        ];
        if (!window.confirm(lines.join('\n'))) {
            return false;
        }
        payload.confirmed_by_user = true;
        payload.user_confirmed = true;
        payload.image_alt_proposal_generation_confirmed = true;
        payload.max_total_cost_cents = maxCost;
        payload.max_cost_cents = maxCost;
        payload.estimated_cost_cents = estimate;
        payload.billing_action_key = billingActionKey;
        payload.provider_adapter = providerAdapter;
        payload.proposal_generation_only = true;
        payload.preview_only = true;
        payload.no_apply = true;
        payload.no_wordpress_write = true;
        payload.writes_enabled = false;
        payload.apply_allowed = false;
        payload.no_webp = true;
        payload.no_image_optimization = true;
        payload.no_publish = true;
        return true;
    }

    function prepareTechnicalImageAltFinalGates(payload, button, onReady) {
        payload = payload && typeof payload === 'object' ? payload : {};
        if (payload.confirmation_kind !== 'technical_image_alt_apply') {
            onReady(payload);
            return;
        }
        button.prop('disabled', true);
        rawAjax('aysa_agent8v3_image_alt_product_gates_set', {
            project_gate_enabled: '1',
            site_gate_enabled: '1'
        }).done(function(response) {
            if (!response || !response.success) {
                renderModalError(apiErrorMessage(response, 'Image Alt gate update failed.'));
                button.prop('disabled', false);
                return;
            }
            payload.product_gates = response.data && response.data.product_gates ? response.data.product_gates : {
                project_gate_enabled: true,
                api_project_gate_enabled: true,
                site_gate_enabled: true,
                plugin_site_gate_enabled: true,
                global_kill_switch_active: false
            };
            payload.billing_status = 'image_alt_real_billing';
            payload.billing_action_key = 'agent8v3_image_alt_apply';
            payload.writes_enabled = true;
            onReady(payload);
        }).fail(function(xhr) {
            renderModalError(apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Image Alt gate update failed.'));
            button.prop('disabled', false);
        });
    }

    function confirmPageSpeedPdfReportAndMark(payload) {
        payload = payload && typeof payload === 'object' ? payload : {};
        if (payload.confirmation_kind !== 'pagespeed_pdf_report_generation') {
            return true;
        }
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const cost = parseInt(payload.billing_cost_cents || 36, 10) || 36;
        const lines = ro ? [
            'AYSA va genera un raport PDF PageSpeed pentru agenție.',
            'Cost: ' + String(cost) + ' credite, păstrând politica existentă pentru raportul PageSpeed.',
            'Nu pornesc un refresh PageSpeed nou.',
            'Nu chem providerul din această acțiune.',
            'Nu modific SEO, conținut, schema, redirects, imagini sau linkuri.',
            '',
            'Continuăm cu generarea raportului PDF?'
        ] : [
            'AYSA will generate a PageSpeed PDF report for the agency.',
            'Cost: ' + String(cost) + ' credits, preserving the existing PageSpeed report policy.',
            'No new PageSpeed refresh will start.',
            'No provider call is made by this action.',
            'No SEO, content, schema, redirects, images or links are changed.',
            '',
            'Continue generating the PDF report?'
        ];
        if (!window.confirm(lines.join('\n'))) {
            return false;
        }
        payload.user_confirmed = true;
        payload.confirmed_by_user = true;
        payload.pagespeed_report_confirmed = true;
        payload.no_refresh = true;
        payload.no_provider_call = true;
        payload.no_seo_write = true;
        return true;
    }

    function confirmOffPageAdverlinkOrderAndMark(payload) {
        payload = payload && typeof payload === 'object' ? payload : {};
        if (payload.confirmation_kind !== 'offpage_adverlink_order_apply') {
            return true;
        }
        const ro = state.language === 'Romanian';
        const targetUrl = String(payload.target_url || '').trim() || '-';
        const anchor = String(payload.anchor_or_topic || '').trim() || '-';
        const portal = String(payload.selected_portal_domain || payload.selected_portal_id || '').trim() || '-';
        const orderType = String(payload.order_type || '').trim() || '-';
        const maxCost = parseInt(payload.max_cost_cents || 0, 10) || 0;
        const currency = String(payload.currency || 'EUR').trim() || 'EUR';
        const lines = [];
        lines.push(ro ? 'COMANDA EXTERNA: Confirmi o singură comandă Adverlink?' : 'EXTERNAL ORDER: Confirm one Adverlink order?');
        lines.push('');
        lines.push((ro ? 'Target URL: ' : 'Target URL: ') + targetUrl);
        lines.push((ro ? 'Anchor/topic: ' : 'Anchor/topic: ') + anchor);
        lines.push((ro ? 'Portal: ' : 'Portal: ') + portal);
        lines.push((ro ? 'Tip comandă: ' : 'Order type: ') + orderType);
        lines.push((ro ? 'COST MAXIM: ' : 'MAX COST: ') + String(maxCost) + ' credits (' + currency + ')');
        lines.push('');
        lines.push(ro
            ? 'SE DEBITEAZA DOAR DUPA ORDER REF: debitarea se face doar după ce Adverlink returnează referința comenzii și readback-ul confirmă statusul.'
            : 'BILLED ONLY AFTER ORDER REF: billing happens only after Adverlink returns the order reference and readback confirms status.');
        lines.push(ro
            ? 'NU PUBLICA PE SITE: nu se modifică WordPress, GBP, link exchange sau conținutul site-ului în acest pas.'
            : 'DOES NOT PUBLISH ON SITE: this step does not mutate WordPress, GBP, link exchange or site content.');
        lines.push('');
        lines.push(ro
            ? 'AYSA va trimite comanda către Adverlink doar pentru acest rând. Nu există acțiune de grup.'
            : 'AYSA will send the Adverlink order only for this row. There is no bulk action.');
        if (!window.confirm(lines.join('\n'))) {
            return false;
        }
        payload.user_confirmed = true;
        payload.confirmed_by_user = true;
        payload.approval_preview_only = false;
        return true;
    }

    function confirmOffPagePublisherArticleOrderQueueAndMark(payload) {
        payload = payload && typeof payload === 'object' ? payload : {};
        if (payload.confirmation_kind !== 'publisher_article_order_queue') {
            return true;
        }
        const ro = state.language === 'Romanian' || String(uiLanguage() || '').indexOf('ro') === 0;
        const recommendationId = String(payload.recommendation_id || '').trim() || '-';
        const maxCost = parseInt(payload.max_total_cost || payload.max_total_cost_cents || payload.max_cost_cents || 0, 10) || 0;
        if (maxCost <= 0) {
            window.alert(ro
                ? 'Nu pot trimite articolul către publisher fără cost maxim exact.'
                : 'Cannot queue the article for publisher without an exact max cost.');
            return false;
        }
        const message = ro
            ? 'Trimit acest draft ca ordin pending către publisher?\n\nRecomandare: ' + recommendationId + '\nCost maxim placement: ' + String(maxCost) + ' credite.\n\nNu public direct pe publisher. Nu debitez placement acum. Debitarea placementului se face doar după publicare manuală în pluginul publisherului și readback public reușit.'
            : 'Queue this draft as a pending publisher order?\n\nRecommendation: ' + recommendationId + '\nPlacement max cost: ' + String(maxCost) + ' credits.\n\nNo direct publisher publish. No placement debit now. Placement is billed only after manual publisher publish and successful public readback.';
        if (!window.confirm(message)) {
            return false;
        }
        payload.publisher_article_order_confirmed = true;
        payload.confirmed_by_user = true;
        payload.no_direct_publish = true;
        payload.no_placement_billing_before_public_readback = true;
        payload.defer_placement_billing_until_public_readback = true;
        payload.max_total_cost = maxCost;
        payload.max_cost_cents = maxCost;
        return true;
    }

    function confirmMonitoringBillableRefreshAndMark(payload) {
        payload = payload && typeof payload === 'object' ? payload : {};
        if (payload.confirmation_kind !== 'monitoring_billable_refresh') {
            return true;
        }
        const ro = state.language === 'Romanian';
        const title = String(payload.confirmation_title || (ro ? 'Confirmi refresh-ul Monitoring?' : 'Confirm Monitoring refresh?')).trim();
        const body = String(payload.confirmation_body || (ro
            ? 'Costul providerului poate varia. Debitarea se face doar după ce snapshotul este generat.'
            : 'Provider cost may vary. Debit happens only after the snapshot is generated.')).trim();
        const provider = String(payload.provider_source || '').trim();
        const maxCost = String(payload.estimated_max_cost_label || '').trim();
        const debitTiming = String(payload.debit_timing || '').trim();
        const lines = [title, '', body];
        if (provider) {
            lines.push((ro ? 'Provider afectat: ' : 'Provider affected: ') + provider);
        }
        if (maxCost) {
            lines.push((ro ? 'Cost maxim/estimare: ' : 'Maximum/estimated cost: ') + maxCost);
        }
        if (debitTiming) {
            lines.push((ro ? 'Moment debitare: ' : 'Debit timing: ') + debitTiming);
        }
        lines.push('');
        lines.push(ro
            ? 'Nu se aplică modificări SEO pe site în acest refresh.'
            : 'No SEO changes are applied to the site during this refresh.');
        if (!window.confirm(lines.join('\n'))) {
            return false;
        }
        payload.user_confirmed = true;
        payload.confirmed_by_user = true;
        payload.monitoring_refresh_confirmed = true;
        payload.explicit_confirmation = true;
        payload.confirmed = true;
        return true;
    }

    function selectedTechnicalMetadataApplyItems() {
        const items = [];
        $('.aysa-agent8v3-metadata-apply-row:checked').each(function() {
            try {
                const raw = String($(this).attr('data-payload') || '{}');
                const item = JSON.parse(raw);
                if (item && typeof item === 'object') {
                    item.accepted_by_user = true;
                    items.push(item);
                }
            } catch (error) {
                // Ignore malformed row payloads; the API validates selected_items again.
            }
        });
        return items;
    }

    function selectedOnPageMetadataApplyItems() {
        state.modal.onpageMetadataSelectedItems = state.modal.onpageMetadataSelectedItems || {};
        $('.aysa-agent8v3-onpage-metadata-apply-row:checked').each(function() {
            try {
                const raw = String($(this).attr('data-payload') || '{}');
                const item = JSON.parse(raw);
                if (!item || typeof item !== 'object' || !item.selectable) {
                    return;
                }
                const normalized = {
                    item_id: String(item.item_id || item.entity_key || ''),
                    entity_key: String(item.entity_key || item.item_id || ''),
                    provider_output_id: String(item.provider_output_id || ''),
                    proposal_hash: String(item.proposal_hash || ''),
                    operation: 'apply_meta'
                };
                const selectionKey = normalized.provider_output_id || normalized.entity_key;
                if (selectionKey) {
                    state.modal.onpageMetadataSelectedItems[selectionKey] = normalized;
                }
            } catch (error) {
                // Ignore malformed rows; the plugin validates the scoped selection again.
            }
        });
        const currentRunId = Math.max(0, parseInt((state.modal.filters && state.modal.filters.source_run_id) || '0', 10) || 0);
        return Object.keys(state.modal.onpageMetadataSelectedItems).map(function(key) {
            return state.modal.onpageMetadataSelectedItems[key];
        }).filter(function(item) {
            if (!(item && item.entity_key && item.provider_output_id && item.proposal_hash)) {
                return false;
            }
            const match = String(item.provider_output_id).match(/^(\d+):/);
            return currentRunId <= 0 || (match && parseInt(match[1], 10) === currentRunId);
        }).filter(function(item) {
            return item.entity_key && item.provider_output_id && item.proposal_hash;
        });
    }

    function onPageMetadataSelectionHash(items) {
        return (Array.isArray(items) ? items : []).map(function(item) {
            return String(item && item.provider_output_id || '');
        }).filter(Boolean).sort().join('|');
    }

    function restoreOnPageMetadataInlineConfirmation() {
        const items = selectedOnPageMetadataApplyItems();
        const selectionHash = onPageMetadataSelectionHash(items);
        const confirmedItems = Array.isArray(state.modal.onpageMetadataConfirmedItems)
            ? state.modal.onpageMetadataConfirmedItems
            : [];
        const confirmedHash = String(state.modal.onpageMetadataConfirmedSelectionHash || '');
        if (!selectionHash || selectionHash !== confirmedHash || onPageMetadataSelectionHash(confirmedItems) !== confirmedHash) {
            return;
        }
        const button = $('#aysa-agent8v3-modal-actions .aysa-agent8v3-modal-action[data-action="execute_onpage_plan"]');
        if (!button.length) {
            return;
        }
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const maxCost = items.length * 2 * 5;
        const message = ro
            ? 'Trimitem doar Metadata aprobată pentru ' + items.length + ' elemente. Cost maxim: ' + maxCost + ' credite (5 / câmp schimbat și verificat). Failed/skipped/no-change nu se debitează. Continuăm?'
            : 'Submit approved metadata only for ' + items.length + ' items. Max cost: ' + maxCost + ' credits (5 / changed and verified field). Failed/skipped/no-change rows are not billed. Continue?';
        button.attr('data-onpage-metadata-confirmed', '1').text(ro ? 'Confirmă aplicarea optimizărilor' : 'Confirm optimization apply');
        button.closest('.aysa-agent8v3-modal-actionbar').find('.aysa-agent8v3-onpage-metadata-inline-confirm').remove();
        button.closest('.aysa-agent8v3-modal-actionbar').prepend('<div class="aysa-agent8v3-onpage-metadata-inline-confirm"><strong>' + escapeHtml(ro ? 'Confirmare finală Metadata' : 'Final metadata confirmation') + '</strong><p>' + escapeHtml(message) + '</p></div>');
    }

    function confirmTechnicalMetadataApplyAndMark(payload) {
        payload = payload && typeof payload === 'object' ? payload : {};
        if (payload.confirmation_kind !== 'technical_metadata_apply') {
            return true;
        }
        const selected = selectedTechnicalMetadataApplyItems();
        const ro = state.language === 'Romanian' || String(uiLanguage() || '').indexOf('ro') === 0;
        if (!selected.length) {
            window.alert(ro ? 'Selectează cel puțin un rând Metadata Preview.' : 'Select at least one Metadata Preview row.');
            return false;
        }
        const unitCost = Math.max(1, parseInt(payload.billing_unit_cents || 5, 10) || 5);
        const maxCost = selected.length * unitCost;
        const examples = selected.slice(0, 5).map(function(item) {
            const field = String(item.field || '');
            const url = String(item.url || '');
            const proposed = String(item.proposed_value || '').trim();
            return '- ' + field + ': ' + (url || '-') + ' -> ' + (proposed || '-');
        });
        const lines = [];
        lines.push(ro ? 'Aplicăm metadata selectată?' : 'Apply selected metadata?');
        lines.push('');
        lines.push((ro ? 'Rânduri selectate: ' : 'Selected rows: ') + selected.length);
        lines.push((ro ? 'Cost maxim: ' : 'Maximum cost: ') + maxCost + (ro ? ' credite' : ' credits'));
        if (examples.length) {
            lines.push('');
            lines.push(ro ? 'Exemple:' : 'Examples:');
            examples.forEach(function(line) {
                lines.push(line);
            });
        }
        lines.push('');
        lines.push(ro
            ? 'Se debitează doar câmpurile schimbate și verificate prin readback. Failed/skipped/no-change nu se debitează.'
            : 'Only changed fields verified by readback are charged. Failed/skipped/no-change rows are not charged.');
        lines.push(ro
            ? 'Se modifică doar titlul SEO și meta descrierea. Nu se modifică redirects, schema, sitemap, robots, linkuri interne, conținut sau canonical.'
            : 'Only SEO title and meta description can be updated. No redirects, schema, sitemap, robots, internal links, content or canonical fields will be changed.');
        if (!window.confirm(lines.join('\n'))) {
            return false;
        }
        payload.selected_items = selected;
        payload.accepted_count = selected.length;
        payload.accepted_fix_count = selected.length;
        payload.max_cost_cents = maxCost;
        payload.user_confirmed = true;
        payload.confirmed_by_user = true;
        return true;
    }

    function prepareTechnicalMetadataFinalGates(payload, button, onReady) {
        payload = payload && typeof payload === 'object' ? payload : {};
        if (payload.confirmation_kind !== 'technical_metadata_apply') {
            onReady(payload);
            return;
        }
        button.prop('disabled', true);
        rawAjax('aysa_agent8v3_metadata_product_gates_set', {
            project_gate_enabled: '1',
            site_gate_enabled: '1'
        }).done(function(response) {
            if (!response || !response.success) {
                renderModalError(apiErrorMessage(response, 'Metadata gate update failed.'));
                button.prop('disabled', false);
                return;
            }
            payload.product_gates = response.data && response.data.product_gates ? response.data.product_gates : {
                project_gate_enabled: true,
                api_project_gate_enabled: true,
                site_gate_enabled: true,
                plugin_site_gate_enabled: true,
                global_kill_switch_active: false
            };
            payload.billing_status = 'metadata_apply_real_billing';
            payload.billing_action_key = 'agent8v3_metadata_apply';
            payload.writes_enabled = true;
            onReady(payload);
        }).fail(function(xhr) {
            renderModalError(apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Metadata gate update failed.'));
            button.prop('disabled', false);
        });
    }

    function selectedTechnicalCanonicalApplyItems() {
        const items = [];
        $('.aysa-agent8v3-canonical-apply-row:checked').each(function() {
            try {
                const raw = String($(this).attr('data-payload') || '{}');
                const item = JSON.parse(raw);
                if (item && typeof item === 'object') {
                    item.accepted_by_user = true;
                    items.push(item);
                }
            } catch (error) {
                // Ignore malformed row payloads; the API validates selected_items again.
            }
        });
        return items;
    }

	    function confirmTechnicalCanonicalApplyAndMark(payload) {
        payload = payload && typeof payload === 'object' ? payload : {};
        if (payload.confirmation_kind !== 'technical_canonical_apply') {
            return true;
        }
        const selected = selectedTechnicalCanonicalApplyItems();
        const ro = state.language === 'Romanian';
        if (!selected.length) {
            window.alert(ro ? 'Selectează cel puțin un rând Canonical Preview.' : 'Select at least one Canonical Preview row.');
            return false;
        }
        const unitCost = Math.max(1, parseInt(payload.billing_unit_cents || 5, 10) || 5);
        const maxCost = selected.length * unitCost;
        const examples = selected.slice(0, 5).map(function(item) {
            const url = String(item.url || '');
            const proposed = String(item.proposed_canonical || item.proposed_value || '').trim();
            return '- ' + (url || '-') + ' -> ' + (proposed || '-');
        });
        const lines = [];
        lines.push(ro ? 'Aplicăm self-canonical pentru rândurile selectate?' : 'Apply self-canonical for selected rows?');
        lines.push('');
        lines.push((ro ? 'Rânduri selectate: ' : 'Selected rows: ') + selected.length);
        lines.push((ro ? 'Cost maxim: ' : 'Maximum cost: ') + maxCost + (ro ? ' credite' : ' credits'));
        if (examples.length) {
            lines.push('');
            lines.push(ro ? 'Exemple:' : 'Examples:');
            examples.forEach(function(line) {
                lines.push(line);
            });
        }
        lines.push('');
        lines.push(ro
            ? 'Se debitează doar canonical-urile schimbate și verificate prin readback. Failed/skipped/no-change nu se debitează.'
            : 'Only changed canonical fields verified by readback are charged. Failed/skipped/no-change rows are not charged.');
        lines.push(ro
            ? 'Se modifică doar câmpul canonical provider-aware pentru pagini fără canonical, unde canonical propus este URL-ul propriu. Nu se modifică redirects, robots, sitemap, schema, linkuri interne, conținut, titluri sau metadata.'
            : 'Only the provider-aware canonical field is updated for pages without canonical, where the proposed canonical is the page URL itself. No redirects, robots, sitemap, schema, internal links, content, titles or metadata will be changed.');
        if (!window.confirm(lines.join('\n'))) {
            return false;
        }
        payload.selected_items = selected;
        payload.accepted_count = selected.length;
        payload.accepted_fix_count = selected.length;
        payload.max_cost_cents = maxCost;
        payload.user_confirmed = true;
        payload.confirmed_by_user = true;
	        return true;
	    }

	    function selectedTechnicalSchemaApplyItems() {
	        const items = [];
	        $('.aysa-agent8v3-schema-apply-row:checked').each(function() {
	            try {
	                const raw = String($(this).attr('data-payload') || '{}');
	                const item = JSON.parse(raw);
	                if (item && typeof item === 'object') {
	                    item.accepted_by_user = true;
	                    items.push(item);
	                }
	            } catch (error) {
	                // Ignore malformed row payloads; the API validates selected_items again.
	            }
	        });
	        return items;
	    }

	    function confirmTechnicalSchemaApplyAndMark(payload) {
	        payload = payload && typeof payload === 'object' ? payload : {};
	        if (payload.confirmation_kind !== 'technical_schema_apply') {
	            return true;
	        }
	        const selected = selectedTechnicalSchemaApplyItems();
	        const ro = state.language === 'Romanian';
	        if (!selected.length) {
	            window.alert(ro ? 'Selectează cel puțin un rând Schema Preview.' : 'Select at least one Schema Preview row.');
	            return false;
	        }
	        const unitCost = Math.max(1, parseInt(payload.billing_unit_cents || 5, 10) || 5);
	        const maxCost = selected.length * unitCost;
	        const examples = selected.slice(0, 5).map(function(item) {
	            const type = String(item.schema_type || 'schema');
	            const url = String(item.url || '');
	            return '- ' + type + ': ' + (url || '-');
	        });
	        const lines = [];
	        lines.push(ro ? 'Aplicăm Schema selectată?' : 'Apply selected Schema?');
	        lines.push('');
	        lines.push((ro ? 'Rânduri selectate: ' : 'Selected rows: ') + selected.length);
	        lines.push((ro ? 'Cost maxim: ' : 'Maximum cost: ') + maxCost + (ro ? ' credite' : ' credits'));
	        if (examples.length) {
	            lines.push('');
	            lines.push(ro ? 'Exemple:' : 'Examples:');
	            examples.forEach(function(line) {
	                lines.push(line);
	            });
	        }
	        lines.push('');
	        lines.push(ro
	            ? 'Se debitează doar blocurile Schema schimbate și verificate prin readback. Failed/skipped/no-change nu se debitează.'
	            : 'Only changed Schema blocks verified by readback are charged. Failed/skipped/no-change rows are not charged.');
	        lines.push(ro
	            ? 'Se scrie doar un bloc JSON-LD controlat de AYSA pentru rândurile selectate. Nu se modifică redirects, sitemap, robots, canonical, metadata, linkuri interne, imagini sau conținut.'
	            : 'Only an AYSA-controlled JSON-LD block is written for selected rows. No redirects, sitemap, robots, canonical, metadata, internal links, images or content will be changed.');
	        if (!window.confirm(lines.join('\n'))) {
	            return false;
	        }
	        payload.selected_items = selected;
	        payload.accepted_fixes = selected;
	        payload.accepted_count = selected.length;
	        payload.accepted_fix_count = selected.length;
	        payload.selected_attachment_ids = selected.map(function(item) {
	            return parseInt(item.attachment_id || item.media_id || 0, 10) || 0;
	        }).filter(function(id) {
	            return id > 0;
	        });
	        payload.max_cost_cents = maxCost;
	        payload.user_confirmed = true;
	        payload.confirmed_by_user = true;
	        return true;
	    }

	    function confirmTechnicalSchemaConsolidationApplyAndMark(payload) {
	        payload = payload && typeof payload === 'object' ? payload : {};
	        if (payload.confirmation_kind !== 'technical_schema_consolidation_apply') {
	            return true;
	        }
	        const ro = state.language === 'Romanian';
	        const selected = Array.isArray(payload.selected_items) ? payload.selected_items.filter(function(item) {
	            return item && typeof item === 'object';
	        }) : [];
	        if (selected.length !== 1) {
	            window.alert(ro ? 'Consolidarea Schema se aplică pe o singură pagină.' : 'Schema consolidation applies to one page only.');
	            return false;
	        }
	        const item = selected[0];
	        if (!item.approval_token || !item.public_readback_hash || !item.proposed_jsonld_hash || !item.backup_required) {
	            window.alert(ro ? 'Preview-ul de consolidare nu are toate dovezile pentru aplicare.' : 'The consolidation preview is missing required evidence.');
	            return false;
	        }
	        const maxCost = Math.max(1, parseInt(payload.max_cost_cents || 5, 10) || 5);
	        const url = String(item.url || '');
	        const type = String(item.schema_type || 'schema');
	        const lines = [];
	        lines.push(ro ? 'Aplică consolidarea Schema pentru această pagină?' : 'Apply Schema consolidation for this page?');
	        lines.push('');
	        lines.push((ro ? 'URL: ' : 'URL: ') + (url || '-'));
	        lines.push((ro ? 'Tip Schema: ' : 'Schema type: ') + type);
	        lines.push((ro ? 'Cost maxim: ' : 'Maximum cost: ') + maxCost + (ro ? ' credite' : ' credits'));
	        lines.push('');
	        lines.push(ro
	            ? 'AYSA va crea backup înainte de scriere și va adăuga/actualiza un singur bloc JSON-LD controlat de AYSA.'
	            : 'AYSA will create a backup before writing and will add/update one AYSA-controlled JSON-LD block.');
	        lines.push(ro
	            ? 'Nu șterg automat Schema generată de alte pluginuri sau temă. Dacă duplicatele externe rămân, rezultatul va spune asta.'
	            : 'Schema generated by other plugins or the theme is not deleted automatically. If external duplicates remain, the result will say so.');
	        if (!window.confirm(lines.join('\n'))) {
	            return false;
	        }
	        item.accepted_by_user = true;
	        item.schema_consolidation_apply = true;
	        item.confirmation_kind = 'technical_schema_consolidation_apply';
	        item.operation = 'technical_seo_schema_consolidation_apply';
	        payload.selected_items = [item];
	        payload.accepted_count = 1;
	        payload.accepted_fix_count = 1;
	        payload.max_cost_cents = maxCost;
	        payload.user_confirmed = true;
	        payload.confirmed_by_user = true;
	        return true;
	    }

	    function imageOptimizationRowKey(item) {
	        item = item && typeof item === 'object' ? item : {};
	        const explicit = String(item.row_hash || item.payload_hash || item.item_id || item.row_id || '').trim();
	        if (explicit) {
	            return explicit;
	        }
	        return [
	            String(item.attachment_id || item.media_id || ''),
	            String(item.original_url || item.image_url || ''),
	            String(item.source_page_url || '')
	        ].join('|');
	    }

	    function imageOptimizationRejectStorageKey() {
	        return [
	            'aysa_agent8v3_image_optimization_rejections',
	            String(cfg.project_id || cfg.wp_project_id || '0'),
	            String(window.location.host || '')
	        ].join(':');
	    }

	    function imageOptimizationRejectedMap() {
	        try {
	            const raw = window.localStorage ? window.localStorage.getItem(imageOptimizationRejectStorageKey()) : '';
	            const parsed = raw ? JSON.parse(raw) : {};
	            return parsed && typeof parsed === 'object' ? parsed : {};
	        } catch (error) {
	            return {};
	        }
	    }

	    function saveImageOptimizationRejectedMap(map) {
	        try {
	            if (window.localStorage) {
	                window.localStorage.setItem(imageOptimizationRejectStorageKey(), JSON.stringify(map && typeof map === 'object' ? map : {}));
	            }
	        } catch (error) {
	            // Local storage is a UI review convenience. The apply contract still receives only selected rows.
	        }
	    }

	    function isImageOptimizationRejected(item) {
	        const key = imageOptimizationRowKey(item);
	        const map = imageOptimizationRejectedMap();
	        return !!(key && map[key]);
	    }

	    function markImageOptimizationRejected(item, rejected, reason) {
	        const key = imageOptimizationRowKey(item);
	        if (!key) {
	            return;
	        }
	        const map = imageOptimizationRejectedMap();
	        if (rejected) {
	            map[key] = {
	                row_key: key,
	                reason: reason || 'other',
	                module: 'image_optimization',
	                attachment_id: item.attachment_id || item.media_id || 0,
	                image_url: item.original_url || item.image_url || '',
	                source_page_url: item.source_page_url || '',
	                current_format: item.mime_type || '',
	                proposed_action: item.proposed_action || item.operation || 'create_webp_derivative',
	                rejected_at: new Date().toISOString()
	            };
	        } else {
	            delete map[key];
	        }
	        saveImageOptimizationRejectedMap(map);
	    }

	    function selectedTechnicalImageOptimizationApplyItems() {
	        const items = [];
	        $('.aysa-agent8v3-image-optimization-apply-row:checked').each(function() {
	            try {
	                const raw = String($(this).attr('data-payload') || '{}');
	                const item = JSON.parse(raw);
	                if (item && typeof item === 'object' && !isImageOptimizationRejected(item)) {
	                    item.accepted_by_user = true;
	                    item.backup_required = true;
	                    item.rollback_required = true;
	                    item.readback_required = true;
	                    items.push(item);
	                }
	            } catch (error) {
	                // Ignore malformed row payloads; the API validates selected_items again.
	            }
	        });
	        return items;
	    }

	    function imageOptimizationBatchCountsFromSafeBundle(moduleKey) {
	        const counts = {
	            accepted: 0,
	            rejected: 0,
	            blocked: 0
	        };
	        $('.aysa-agent8v3-safe-bundle-row').filter(function() {
	            return String($(this).attr('data-module') || '') === String(moduleKey || '');
	        }).each(function() {
	            let payload = {};
	            try {
	                payload = JSON.parse(String($(this).attr('data-payload') || '{}'));
	            } catch (error) {
	                payload = {};
	            }
	            const item = payload && payload.item && typeof payload.item === 'object' ? payload.item : {};
	            if (String(moduleKey || '') === 'image_optimization' && isImageOptimizationRejected(item)) {
	                counts.rejected += 1;
	                return;
	            }
	            if ($(this).prop('checked')) {
	                counts.accepted += 1;
	            } else if (payload && payload.exclusion_allowed) {
	                counts.rejected += 1;
	            } else {
	                counts.blocked += 1;
	            }
	        });
	        return counts;
	    }

	    function confirmTechnicalImageOptimizationApplyAndMark(payload) {
	        payload = payload && typeof payload === 'object' ? payload : {};
	        if (payload.confirmation_kind !== 'technical_image_optimization_apply') {
	            return true;
	        }
	        const selected = selectedTechnicalImageOptimizationApplyItems();
	        const ro = state.language === 'Romanian';
	        if (!selected.length) {
	            window.alert(ro ? 'Selectează cel puțin o imagine WebP Preview.' : 'Select at least one WebP Preview image.');
	            return false;
	        }
	        const unitCost = Math.max(1, parseInt(payload.billing_unit_cents || 5, 10) || 5);
	        const maxCost = selected.length * unitCost;
	        const examples = selected.slice(0, 5).map(function(item) {
	            const image = String(item.original_url || item.image_url || '');
	            const page = String(item.source_page_url || '');
	            return '- ' + (image || '-') + (page ? ' @ ' + page : '');
	        });
	        const lines = [];
	        lines.push(ro ? 'Creăm WebP pentru imaginile selectate?' : 'Create WebP for selected images?');
	        lines.push('');
	        lines.push((ro ? 'Imagini selectate: ' : 'Selected images: ') + selected.length);
	        lines.push((ro ? 'Cost maxim: ' : 'Maximum cost: ') + maxCost + (ro ? ' credite' : ' credits'));
	        if (examples.length) {
	            lines.push('');
	            lines.push(ro ? 'Exemple:' : 'Examples:');
	            examples.forEach(function(line) {
	                lines.push(line);
	            });
	        }
	        lines.push('');
	        lines.push(ro
	            ? 'Se debitează doar imaginile optimizate și verificate prin readback. Failed/skipped/no-change nu se debitează.'
	            : 'Only optimized images verified by readback are charged. Failed/skipped/no-change rows are not charged.');
	        lines.push(ro
	            ? 'Se creează doar derivative WebP urmărite de AYSA. Nu se schimbă originalul, MIME type, _wp_attached_file, metadata WordPress, conținutul paginii, URL-uri, redirects, schema sau Image Alt.'
	            : 'Only AYSA-tracked WebP derivatives are created. Originals, MIME type, _wp_attached_file, WordPress metadata, page content, URLs, redirects, schema and Image Alt are not changed.');
	        if (!window.confirm(lines.join('\n'))) {
	            return false;
	        }
	        payload.selected_items = selected;
	        payload.accepted_fixes = selected;
	        payload.accepted_count = selected.length;
	        payload.accepted_fix_count = selected.length;
	        payload.selected_attachment_ids = selected.map(function(item) {
	            return parseInt(item.attachment_id || item.media_id || 0, 10) || 0;
	        }).filter(function(id) {
	            return id > 0;
	        });
	        payload.max_cost_cents = maxCost;
	        payload.user_confirmed = true;
	        payload.confirmed_by_user = true;
	        return true;
	    }

	    function selectedInternalLinkingApplyItems() {
	        const items = [];
	        $('.aysa-agent8v3-internal-linking-apply-row:checked').each(function() {
	            try {
	                const raw = String($(this).attr('data-payload') || '{}');
	                const item = JSON.parse(raw);
	                if (item && typeof item === 'object' && !isInternalLinkingRejected(item)) {
	                    item.accepted_by_user = true;
	                    item.backup_required = true;
	                    item.rollback_required = true;
	                    item.readback_required = true;
	                    items.push(item);
	                }
	            } catch (error) {
	                // The API validates selected_items again; malformed row payloads are ignored here.
	            }
	        });
	        return items;
	    }

	    function internalLinkingRowKey(item) {
	        item = item && typeof item === 'object' ? item : {};
	        const explicit = String(item.row_hash || item.payload_hash || item.item_id || item.row_id || '').trim();
	        if (explicit) {
	            return explicit;
	        }
	        return [
	            String(item.source_post_id || ''),
	            String(item.target_post_id || ''),
	            String(item.anchor_text || item.proposed_anchor_text || '')
	        ].join('|');
	    }

	    function internalLinkingRejectStorageKey() {
	        return [
	            'aysa_agent8v3_internal_linking_rejections',
	            String(cfg.project_id || cfg.wp_project_id || '0'),
	            String(window.location.host || '')
	        ].join(':');
	    }

	    function internalLinkingRejectedMap() {
	        try {
	            const raw = window.localStorage ? window.localStorage.getItem(internalLinkingRejectStorageKey()) : '';
	            const parsed = raw ? JSON.parse(raw) : {};
	            return parsed && typeof parsed === 'object' ? parsed : {};
	        } catch (error) {
	            return {};
	        }
	    }

	    function saveInternalLinkingRejectedMap(map) {
	        try {
	            if (window.localStorage) {
	                window.localStorage.setItem(internalLinkingRejectStorageKey(), JSON.stringify(map && typeof map === 'object' ? map : {}));
	            }
	        } catch (error) {
	            // Local storage is only a UI convenience. The server-side action remains authoritative when available.
	        }
	    }

	    function isInternalLinkingRejected(item) {
	        const key = internalLinkingRowKey(item);
	        const map = internalLinkingRejectedMap();
	        return !!(key && map[key]);
	    }

	    function markInternalLinkingRejected(item, rejected, reason) {
	        const key = internalLinkingRowKey(item);
	        if (!key) {
	            return;
	        }
	        const map = internalLinkingRejectedMap();
	        if (rejected) {
	            map[key] = {
	                row_key: key,
	                reason: reason || 'other',
	                source_post_id: item.source_post_id || 0,
	                target_post_id: item.target_post_id || 0,
	                anchor: item.anchor_text || item.proposed_anchor_text || '',
	                rejected_at: new Date().toISOString()
	            };
	        } else {
	            delete map[key];
	        }
	        saveInternalLinkingRejectedMap(map);
	    }

	    function simpleStableHash(input) {
	        let hash = 5381;
	        const text = String(input || '');
	        for (let i = 0; i < text.length; i++) {
	            hash = ((hash << 5) + hash) + text.charCodeAt(i);
	            hash = hash & hash;
	        }
	        return Math.abs(hash).toString(36);
	    }

	    function confirmInternalLinkingApplyAndMark(payload) {
	        payload = payload && typeof payload === 'object' ? payload : {};
	        if (payload.confirmation_kind !== 'internal_linking_apply') {
	            return true;
	        }
	        const selected = selectedInternalLinkingApplyItems();
	        const ro = state.language === 'Romanian';
	        if (!selected.length) {
	            window.alert(ro ? 'Selectează cel puțin un rând Internal Linking Preview.' : 'Select at least one Internal Linking Preview row.');
	            return false;
	        }
	        const unitCost = Math.max(1, parseInt(payload.billing_unit_cents || 5, 10) || 5);
	        const maxCost = selected.length * unitCost;
	        const examples = selected.slice(0, 5).map(function(item) {
	            const source = String(item.source_url || '');
	            const target = String(item.target_url || '');
	            const anchor = String(item.anchor_text || item.proposed_anchor_text || '').trim();
	            return '- ' + (source || '-') + ' -> ' + (target || '-') + (anchor ? ' / "' + anchor + '"' : '');
	        });
	        const rejectedCount = Object.keys(internalLinkingRejectedMap()).length;
	        const lines = [];
	        lines.push(ro ? 'Aplicăm recomandările acceptate?' : 'Apply accepted recommendations?');
	        lines.push('');
	        lines.push((ro ? 'Recomandări acceptate: ' : 'Accepted recommendations: ') + selected.length);
	        lines.push((ro ? 'Recomandări respinse în acest review: ' : 'Rejected in this review: ') + rejectedCount);
	        lines.push((ro ? 'Cost maxim: ' : 'Maximum cost: ') + maxCost + (ro ? ' credite' : ' credits'));
	        if (examples.length) {
	            lines.push('');
	            lines.push(ro ? 'Exemple:' : 'Examples:');
	            examples.forEach(function(line) {
	                lines.push(line);
	            });
	        }
	        lines.push('');
	        lines.push(ro
	            ? 'AYSA va aplica automat doar recomandările acceptate. Recomandările respinse sau blocate nu vor fi aplicate.'
	            : 'AYSA will apply only accepted recommendations. Rejected or blocked recommendations will not be applied.');
	        lines.push(ro
	            ? 'Se debitează doar linkurile inserate și verificate prin readback. Failed/skipped/no-change/respinse nu se debitează.'
	            : 'Only inserted links verified by readback are charged. Failed/skipped/no-change/rejected rows are not charged.');
	        lines.push(ro
	            ? 'Se modifică doar conținutul paginii sursă pentru inserarea linkului intern aprobat. Nu se modifică metadata, canonical, schema, redirects, sitemap, robots, imagini, meniuri sau pagini critice.'
	            : 'Only the source page content is changed to insert the approved internal link. Metadata, canonical, schema, redirects, sitemap, robots, images, menus and critical pages are not changed.');
	        lines.push(ro
	            ? 'Continuă doar dacă sursa, ținta, ancora și contextul sunt corecte.'
	            : 'Continue only if source, target, anchor and context are correct.');
	        if (!window.confirm(lines.join('\n'))) {
	            return false;
	        }
	        const batchSeed = selected.map(function(item) {
	            return internalLinkingRowKey(item);
	        }).sort().join('|');
	        const batchId = 'il_batch_' + simpleStableHash(batchSeed);
	        payload.selected_items = selected;
	        payload.accepted_fixes = selected;
	        payload.accepted_count = selected.length;
	        payload.accepted_fix_count = selected.length;
	        payload.rejected_count = rejectedCount;
	        payload.blocked_count = Math.max(0, parseInt(payload.blocked_count || 0, 10) || 0);
	        payload.action_contract = 'technical_seo_internal_linking_apply_accepted';
	        payload.batch_id = batchId;
	        payload.batch_idempotency_key = 'agent8v3:technical_seo_internal_linking_apply_accepted:' + batchId;
	        payload.idempotency_key = payload.batch_idempotency_key;
	        payload.final_confirmation_text = ro ? 'Aplică recomandările acceptate' : 'Apply accepted recommendations';
	        payload.max_cost_cents = maxCost;
	        payload.user_confirmed = true;
	        payload.confirmed_by_user = true;
	        return true;
	    }

	    function confirmTechnicalSitemapAuthorityApplyAndMark(payload, button) {
	        payload = payload && typeof payload === 'object' ? payload : {};
	        if (payload.confirmation_kind !== 'technical_sitemap_authority_apply') {
	            return true;
	        }
	        const ro = state.language === 'Romanian';
	        const selected = Array.isArray(payload.selected_items) && payload.selected_items.length
	            ? payload.selected_items
	            : (Array.isArray(payload.accepted_fixes) ? payload.accepted_fixes : []);
	        const examples = selected.slice(0, 3).map(function(item) {
	            const provider = String(item.provider_detected || '').trim();
	            const currentValue = String(item.current_value || '').trim();
	            const proposedValue = String(item.proposed_value || '').trim();
	            return '- ' + (provider || (ro ? 'provider curent' : 'current provider')) + ': ' + (currentValue || '-') + ' -> ' + (proposedValue || 'AYSA');
	        });
	        const lines = [];
	        lines.push(ro ? 'Activăm AYSA ca autoritate sitemap?' : 'Activate AYSA as sitemap authority?');
	        lines.push('');
	        lines.push(ro
	            ? 'Această acțiune poate scrie sitemap-ul AYSA și poate actualiza robots.txt să pointeze către sitemap-ul AYSA.'
	            : 'This action may write the AYSA sitemap and update robots.txt to point to the AYSA sitemap.');
	        lines.push(ro
	            ? 'Continuă doar dacă backup-ul, paritatea și readback-ul sunt verificate.'
	            : 'Continue only if backup, parity and readback are verified.');
	        if (examples.length) {
	            lines.push('');
	            lines.push(ro ? 'Rezumat:' : 'Summary:');
	            examples.forEach(function(line) {
	                lines.push(line);
	            });
	        }
	        lines.push('');
	        lines.push(ro
	            ? 'Nu se debitează credite în acest pas până când billing-ul verificat este activat.'
	            : 'No credits are charged in this step until verified billing is enabled.');
	        if (button && button.length) {
	            if (button.attr('data-sitemap-authority-confirmed') !== '1') {
	                button.attr('data-sitemap-authority-confirmed', '1');
	                button.text(ro ? 'Confirmă activarea AYSA sitemap' : 'Confirm AYSA sitemap activation');
	                button.closest('.aysa-agent8v3-modal-actionbar').find('.aysa-agent8v3-sitemap-authority-inline-confirm').remove();
	                button.closest('.aysa-agent8v3-modal-actionbar').prepend(
	                    '<div class="aysa-agent8v3-sitemap-authority-inline-confirm">' +
	                    lines.map(function(line) {
	                        return line ? '<p>' + escapeHtml(line) + '</p>' : '<br>';
	                    }).join('') +
	                    '</div>'
	                );
	                return false;
	            }
	        } else if (!window.confirm(lines.join('\n'))) {
	            return false;
	        }
	        payload.selected_items = selected;
	        payload.accepted_fixes = selected;
	        payload.accepted_count = selected.length || 1;
	        payload.accepted_fix_count = selected.length || 1;
	        payload.user_confirmed = true;
	        payload.confirmed_by_user = true;
	        if (!enableTechnicalSitemapAuthorityProjectGates(payload)) {
	            return false;
	        }
	        return true;
	    }

	    function enableTechnicalSitemapAuthorityProjectGates(payload) {
	        const ajaxUrl = String(cfg.ajax_url || '');
	        const nonce = String(cfg.nonce || '');
	        const rawProjectId = String(payload.project_id || cfg.project_id || '');
	        const projectIdMatch = rawProjectId.match(/\d+/);
	        const projectId = projectIdMatch ? projectIdMatch[0] : '';
	        const confirmation = 'I understand sitemap authority writes are enabled for this project';
	        const ro = state.language === 'Romanian';
	        if (!ajaxUrl || !nonce || !projectId) {
	            window.alert(ro
	                ? 'Nu pot activa gate-ul Sitemap Authority: contextul admin este incomplet.'
	                : 'Cannot enable Sitemap Authority gate: admin context is incomplete.');
	            return false;
	        }
	        let ok = true;
	        ['apply', 'restore'].forEach(function(gate) {
	            if (!ok) {
	                return;
	            }
	            $.ajax({
	                url: ajaxUrl,
	                method: 'POST',
	                async: false,
	                dataType: 'json',
	                data: {
	                    action: 'aysa_technical_sitemap_authority_gate',
	                    nonce: nonce,
	                    project_id: projectId,
	                    gate: gate,
	                    enabled: '1',
	                    confirmation: confirmation
	                },
	                success: function(response) {
	                    ok = !!(response && response.success);
	                },
	                error: function() {
	                    ok = false;
	                }
	            });
	        });
	        if (!ok) {
	            window.alert(ro
	                ? 'Nu am putut activa gate-ul Sitemap Authority pentru acest proiect. Acțiunea nu a fost trimisă.'
	                : 'Could not enable the Sitemap Authority gate for this project. The action was not submitted.');
	        }
	        if (ok) {
	            payload.project_id = projectId;
	        }
	        return ok;
	    }

        function technicalReviewCompletionPayloadFromCanonical(payload) {
            payload = payload && typeof payload === 'object' ? payload : {};
            if (payload.confirmation_kind === 'technical_review_complete_with_warnings') {
                return payload;
            }
            const canonical = state.canonical && typeof state.canonical === 'object' ? state.canonical : {};
            const technical = canonical.data && canonical.data.technical_seo && typeof canonical.data.technical_seo === 'object'
                ? canonical.data.technical_seo
                : {};
            const review = technical.review && typeof technical.review === 'object' ? technical.review : {};
            if (String(review.status || '') === 'completed') {
                return payload;
            }
            const summary = technical.summary && typeof technical.summary === 'object' ? technical.summary : {};
            const modules = summary.modules && typeof summary.modules === 'object' ? summary.modules : {};
            const warningModules = [];
            [technical.module_failures, technical.module_warnings, technical.warnings, summary.module_failures, summary.module_warnings].forEach(function(items) {
                if (!Array.isArray(items)) {
                    return;
                }
                items.forEach(function(item) {
                    const key = String(item || '').trim();
                    if (key && warningModules.indexOf(key) === -1) {
                        warningModules.push(key);
                    }
                });
            });
            Object.keys(modules).forEach(function(moduleKey) {
                const module = modules[moduleKey] && typeof modules[moduleKey] === 'object' ? modules[moduleKey] : {};
                if (['failed', 'blocked', 'completed_with_warnings'].indexOf(String(module.status || '')) !== -1
                    && warningModules.indexOf(moduleKey) === -1
                ) {
                    warningModules.push(moduleKey);
                }
            });
            const hasWarnings = ['failed', 'blocked', 'completed_with_warnings'].indexOf(String(technical.status || '')) !== -1
                || warningModules.length > 0;
            if (!hasWarnings) {
                return payload;
            }
            payload.confirmation_kind = 'technical_review_complete_with_warnings';
            payload.technical_seo_skip_reason = payload.technical_seo_skip_reason || 'image_alt_pending_retry_or_accepted_for_later';
            payload.warning_modules = warningModules;
            return payload;
        }

	    function confirmTechnicalReviewCompleteWithWarningsAndMark(payload) {
        payload = payload && typeof payload === 'object' ? payload : {};
        payload = technicalReviewCompletionPayloadFromCanonical(payload);
        if (payload.confirmation_kind !== 'technical_review_complete_with_warnings') {
            return true;
        }
        // The visible warning review and explicit completion click are the
        // confirmation surface. A native confirm here can strand the AJAX
        // request while long technical state responses are still settling.
        payload.technical_seo_skip_reason = payload.technical_seo_skip_reason || 'image_alt_pending_retry_or_accepted_for_later';
        payload.review_confirmed_by_user = true;
        payload.confirmed_by_user = true;
        return true;
    }

    function modalLoadingContext() {
        const key = String(state.modal.key || '');
        const filters = state.modal.filters || {};
        const activeTab = String(filters.tab || '');
        const current = state.modal.current && String(state.modal.current.modal_key || '') === key ? state.modal.current : null;
        const ro = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const titleByKey = {
            research_keywords: ro ? 'Cercetare cuvinte-cheie' : 'Keyword Research',
            keyword_mapping: ro ? 'Mapare cuvinte-cheie către pagini' : 'Keyword-to-page mapping',
            missing_pages: ro ? 'Targeturi & pagini lipsă' : 'Targets & missing pages',
            content_plan: ro ? 'Plan de conținut' : 'Content Plan',
            onpage_seo: ro ? 'On Page SEO' : 'On Page SEO',
            technical_site_audit: ro ? 'Site Audit' : 'Site Audit',
            technical_overview: ro ? 'Concluzie Technical SEO' : 'Technical SEO conclusion',
            technical_pagespeed: 'PageSpeed',
            technical_schema: 'Schema',
            technical_redirects: ro ? 'Redirecturi' : 'Redirects',
            technical_sitemap_robots: 'Sitemap/Robots',
            technical_image_alt: ro ? 'Optimizare imagini' : 'Image optimization',
            technical_internal_linking: 'Internal Linking',
            monitoring: ro ? 'Monitoring' : 'Monitoring',
            offpage_seo: ro ? 'Off Page SEO' : 'Off Page SEO'
        };
        const tabLabel = current && Array.isArray(current.tabs)
            ? (current.tabs.find(function(tab) { return String(tab && tab.key || '') === activeTab; }) || {}).label
            : '';
        return {
            key: key,
            current: current,
            title: current ? modalTitle(current) : (titleByKey[key] || text('modalLoading')),
            subtitle: current ? modalSubtitle(current) : '',
            tabLabel: tabLabel || '',
            ro: ro
        };
    }

    function renderModalLoadingBody(context, slow) {
        context = context || modalLoadingContext();
        const target = context.tabLabel || context.title || text('modalLoading');
        const launchFallback = modalLaunchFallbackCopy(context);
        const headline = context.ro
            ? 'Încarc datele pentru ' + target + '.'
            : 'Loading data for ' + target + '.';
        const safety = context.ro
            ? 'Nu pornesc aplicări, publicări, comenzi, refresh-uri sau consum de credite din simpla deschidere.'
            : 'Opening this view does not start applies, publishing, orders, refreshes, or credit consumption.';
        const help = slow
            ? (context.ro
                ? 'Datele pot dura câteva secunde dacă lista este mare. Poți închide și redeschide review-ul; nu se pierde nicio selecție salvată.'
                : 'Large lists can take a few seconds. You can close and reopen the review; saved selections are not lost.')
            : (context.ro
                ? 'Păstrez taburile și afișez datele imediat ce sunt gata.'
                : 'Tabs stay visible and the data appears as soon as it is ready.');
        return '<div class="aysa-agent8v3-modal-loading-card' + (slow ? ' is-slow' : '') + '">' +
            '<strong>' + escapeHtml(headline) + '</strong>' +
            '<p>' + escapeHtml(safety) + '</p>' +
            '<p>' + escapeHtml(help) + '</p>' +
            launchFallback +
            '</div>';
    }

    function modalLaunchFallbackKey(context) {
        context = context || modalLoadingContext();
        const modal = context.current && typeof context.current === 'object' ? context.current : {};
        const modalKey = String(modal.modal_key || (state.modal && state.modal.key) || '');
        const activeTab = String((state.modal && state.modal.filters && state.modal.filters.tab) || modal.active_tab || (modal.filters && modal.filters.tab) || '');
        const label = String(context.tabLabel || context.title || '').toLowerCase();
        if (modalKey === 'onpage_seo' && (
            activeTab === 'metadata_preview' ||
            activeTab === 'meta_snippets' ||
            activeTab === 'metadata' ||
            label.indexOf('titluri') !== -1 ||
            label.indexOf('descrieri') !== -1 ||
            label.indexOf('metadata') !== -1 ||
            label.indexOf('meta seo') !== -1
        )) {
            return 'onpage_metadata';
        }
        if (modalKey === 'offpage_seo' && (
            activeTab === 'link_building_plan' ||
            label.indexOf('plan de autoritate') !== -1 ||
            label.indexOf('authority plan') !== -1
        )) {
            return 'offpage_authority_plan';
        }
        return '';
    }

    function modalLaunchFallbackCopy(context) {
        context = context || modalLoadingContext();
        const ro = !!context.ro;
        const key = modalLaunchFallbackKey(context);
        if (key === 'onpage_metadata') {
            const lines = ro
                ? [
                    'Titluri și descrieri se încarcă în siguranță.',
                    'Dacă lista nu apare, nu pornesc generarea automat. Folosește Reîncearcă sau redeschide tabul.',
                    'Pregătește propuneri Meta SEO apare doar când rândurile sunt încărcate; costul se afișează înainte, iar aplicarea este separată.'
                ]
                : [
                    'Titles and descriptions are loading safely.',
                    'If the list does not appear, generation will not start automatically. Use Retry or reopen the tab.',
                    'Prepare SEO meta proposals appears only after rows load; cost is shown first, and apply is separate.'
                ];
            return '<div class="aysa-agent8v3-safe-bundle-note aysa-agent8v3-launch-ux-note">' +
                '<strong>' + escapeHtml(lines[0]) + '</strong>' +
                '<p>' + escapeHtml(lines[1]) + '</p>' +
                '<p>' + escapeHtml(lines[2]) + '</p>' +
                '</div>';
        }
        if (key === 'offpage_authority_plan') {
            const lines = ro
                ? [
                    'Planul de autoritate se încarcă fără comandă.',
                    'Dacă planul nu este disponibil, îți arăt motivul: nu a fost generat, lipsesc recomandări sigure sau datele trebuie reîncărcate.',
                    'Nu chem provideri, nu plasez comenzi și nu consum credite din această deschidere.'
                ]
                : [
                    'The authority plan is loading without ordering.',
                    'If the plan is unavailable, the reason is shown: not generated, no safe recommendations, or data needs reloading.',
                    'This open does not call providers, place orders, or consume credits.'
                ];
            return '<div class="aysa-agent8v3-safe-bundle-note aysa-agent8v3-launch-ux-note">' +
                '<strong>' + escapeHtml(lines[0]) + '</strong>' +
                '<p>' + escapeHtml(lines[1]) + '</p>' +
                '<p>' + escapeHtml(lines[2]) + '</p>' +
                '</div>';
        }
        return '';
    }

    function setModalLoading() {
        updateModalChromeText();
        const context = modalLoadingContext();
        $('.aysa-agent8v3-modal-toolbar').hide();
        $('#aysa-agent8v3-modal-title').text(context.title || text('modalLoading'));
        $('#aysa-agent8v3-modal-subtitle').text(context.subtitle || (context.ro ? 'Se încarcă în mod sigur, fără modificări live.' : 'Loading safely, without live changes.'));
        if (!context.current) {
            $('#aysa-agent8v3-modal-summary').empty();
            $('.aysa-agent8v3-modal-tabs').remove();
            $('#aysa-agent8v3-modal-actions').empty();
        } else {
            const loadingModal = $.extend(true, {}, context.current);
            loadingModal.active_tab = String((state.modal.filters && state.modal.filters.tab) || loadingModal.active_tab || '');
            loadingModal.filters = $.extend({}, loadingModal.filters || {}, state.modal.filters || {});
            if (String(loadingModal.modal_key || '') === 'onpage_seo' || String(loadingModal.modal_key || '') === 'offpage_seo' || String(loadingModal.modal_key || '') === 'monitoring') {
                loadingModal.advanced_tabs_visible = !!(state.modal.filters && state.modal.filters.advanced === '1');
            }
            renderModalTabs(loadingModal);
            $('#aysa-agent8v3-modal-actions').empty();
        }
        $('#aysa-agent8v3-modal-body').html(renderModalLoadingBody(context, false));
        $('#aysa-agent8v3-modal-page').text('').hide();
        $('#aysa-agent8v3-modal-prev, #aysa-agent8v3-modal-next').parent().hide();
        $('#aysa-agent8v3-modal-prev, #aysa-agent8v3-modal-next').prop('disabled', true);
    }

    function resetMonitoringWorkspaceScroll() {
        const body = $('#aysa-agent8v3-modal-body').get(0);
        if (body) {
            body.scrollTop = 0;
            body.scrollLeft = 0;
        }
    }

    function beginMonitoringTransition() {
        if (state.modal.key !== 'monitoring') {
            return;
        }
        state.modal.monitoringTransitioning = true;
        $('.aysa-agent8v3-modal-tab, .aysa-agent8v3-monitoring-subtab')
            .addClass('is-transitioning')
            .attr('aria-busy', 'true');
    }

    function finishMonitoringTransition() {
        if (state.modal.key !== 'monitoring') {
            return;
        }
        state.modal.monitoringTransitioning = false;
        $('.aysa-agent8v3-modal-tab, .aysa-agent8v3-monitoring-subtab')
            .removeClass('is-transitioning')
            .removeAttr('aria-busy');
        if (state.modal.monitoringResetScrollAfterLoad) {
            state.modal.monitoringResetScrollAfterLoad = false;
            resetMonitoringWorkspaceScroll();
        }
    }

    function setMonitoringSourceLoading() {
        const ro = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        $('.aysa-agent8v3-monitoring-results').html(
            '<div class="aysa-agent8v3-monitoring-source-loading" role="status" aria-live="polite">' +
                '<span aria-hidden="true"></span>' +
                '<div><strong>' + escapeHtml(ro ? 'Se încarcă secțiunea' : 'Loading section') + '</strong>' +
                '<small>' + escapeHtml(ro ? 'Rezumatul monitorizării rămâne disponibil.' : 'The monitoring summary remains available.') + '</small></div>' +
            '</div>'
        );
    }

    function renderModalSlowLoadingNotice() {
        $('#aysa-agent8v3-modal-body').html(renderModalLoadingBody(modalLoadingContext(), true));
    }

    function renderModalError(message) {
        updateModalChromeText();
        const context = modalLoadingContext();
        message = modalFriendlyErrorMessage(message, context);
        if (String(state.modal.key || '') === 'onpage_seo') {
            renderOnPageHydrationFailSafe(message);
            return;
        }
        $('#aysa-agent8v3-modal-title').text(modalUnavailableTitle(context));
        $('#aysa-agent8v3-modal-subtitle').text('');
        $('.aysa-agent8v3-modal-toolbar').hide();
        $('#aysa-agent8v3-modal-summary').empty();
        $('.aysa-agent8v3-modal-tabs').remove();
        $('#aysa-agent8v3-modal-body').html(
            '<div class="aysa-agent8v3-modal-empty is-error">' +
            escapeHtml(message || 'Unknown error') +
            '<div style="margin-top:12px"><button type="button" class="button aysa-agent8v3-modal-retry">Reîncearcă</button></div>' +
            '</div>'
        );
        $('#aysa-agent8v3-modal-actions').empty();
        $('#aysa-agent8v3-modal-page').text('').hide();
        $('#aysa-agent8v3-modal-prev, #aysa-agent8v3-modal-next').parent().hide();
        $('#aysa-agent8v3-modal-prev, #aysa-agent8v3-modal-next').prop('disabled', true);
    }

    function renderOnPageHydrationFailSafe(message) {
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const onpage = state.canonical && state.canonical.data && state.canonical.data.onpage_seo
            ? state.canonical.data.onpage_seo
            : {};
        const summary = onpage && typeof onpage.summary === 'object' ? onpage.summary : {};
        const execution = onpage && typeof onpage.execution === 'object' ? onpage.execution : {};
        const sourceRun = String(execution.source_run_id || execution.run_id || onpage.source_run_id || '-');
        const currentBatch = String(summary.current_batch_number || '-');
        const totalBatches = String(summary.total_batches_estimate || '-');
        const historicalStatus = execution && Object.keys(execution).length
            ? (ro ? 'Există date salvate pentru verificare.' : 'Saved data exists for review.')
            : (ro ? 'Disponibilitatea istoricului se verifică la redeschidere.' : 'Historical availability will be checked when reopened.');
        const status = message || (ro ? 'Timp de așteptare depășit' : 'Request timed out');
        $('#aysa-agent8v3-modal-title').text(ro ? 'On Page SEO nu s-a încărcat' : 'On Page SEO could not load');
        $('#aysa-agent8v3-modal-subtitle').text(ro
            ? 'Nu am pornit nicio acțiune și nu am modificat site-ul.'
            : 'No action was started and the site was not changed.');
        $('#aysa-agent8v3-modal-summary').empty();
        $('.aysa-agent8v3-modal-tabs').remove();
        $('#aysa-agent8v3-modal-body').html(
            '<div class="aysa-agent8v3-modal-empty is-error aysa-agent8v3-onpage-hydration-failsafe" role="alert">' +
            '<strong>' + escapeHtml(ro
                ? 'Nu am putut încărca datele On Page SEO. Reîncearcă sau deschide raportul istoric.'
                : 'We could not load the On Page SEO data. Retry or open the historical report.') + '</strong>' +
            '<dl class="aysa-agent8v3-onpage-hydration-diagnostics">' +
            '<div><dt>' + escapeHtml(ro ? 'Status request' : 'Request status') + '</dt><dd>' + escapeHtml(status) + '</dd></div>' +
            '<div><dt>' + escapeHtml(ro ? 'Run sursă' : 'Source run') + '</dt><dd>' + escapeHtml(sourceRun) + '</dd></div>' +
            '<div><dt>' + escapeHtml(ro ? 'Batch curent' : 'Current batch') + '</dt><dd>' + escapeHtml(currentBatch + ' / ' + totalBatches) + '</dd></div>' +
            '<div><dt>' + escapeHtml(ro ? 'Rapoarte istorice' : 'Historical reports') + '</dt><dd>' + escapeHtml(historicalStatus) + '</dd></div>' +
            '</dl>' +
            '<div class="aysa-agent8v3-onpage-hydration-actions">' +
            '<button type="button" class="button aysa-agent8v3-modal-retry">' + escapeHtml(ro ? 'Reîncearcă' : 'Retry') + '</button>' +
            '<button type="button" class="button aysa-agent8v3-onpage-open-history-failsafe">' + escapeHtml(ro ? 'Deschide raportul istoric' : 'Open historical report') + '</button>' +
            '</div></div>'
        );
        $('#aysa-agent8v3-modal-actions').empty();
        $('#aysa-agent8v3-modal-page').text('-');
        $('#aysa-agent8v3-modal-prev, #aysa-agent8v3-modal-next').prop('disabled', true);
    }

    function renderOnPageIncompleteEvidenceFixture() {
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        $('#aysa-agent8v3-modal-title').text(ro ? 'On Page SEO · verificare contract' : 'On Page SEO · contract check');
        $('#aysa-agent8v3-modal-subtitle').text(ro
            ? 'Fixture QA doar pentru verificare. Nu modifică site-ul.'
            : 'QA-only fixture. It does not modify the site.');
        $('#aysa-agent8v3-modal-summary').empty();
        $('.aysa-agent8v3-modal-tabs').remove();
        $('#aysa-agent8v3-modal-body').html(
            '<div class="aysa-agent8v3-modal-empty aysa-agent8v3-onpage-incomplete-evidence-fixture" role="status">' +
            '<strong>' + escapeHtml(ro ? 'Execuția este blocată pentru că dovezile de identificare sunt incomplete.' : 'Execution is blocked because durable identity evidence is incomplete.') + '</strong>' +
            '<dl class="aysa-agent8v3-onpage-hydration-diagnostics">' +
            '<div><dt>' + escapeHtml(ro ? 'Rezultat' : 'Result') + '</dt><dd>blocked_incomplete_durable_identity</dd></div>' +
            '<div><dt>' + escapeHtml(ro ? 'Credite' : 'Credits') + '</dt><dd>0</dd></div>' +
            '<div><dt>' + escapeHtml(ro ? 'Modificări site' : 'Site changes') + '</dt><dd>' + escapeHtml(ro ? 'Nu' : 'No') + '</dd></div>' +
            '<div><dt>' + escapeHtml(ro ? 'Istoric / email' : 'History / email') + '</dt><dd>' + escapeHtml(ro ? 'Nu se creează' : 'Not created') + '</dd></div>' +
            '</dl>' +
            '<p>' + escapeHtml(ro
                ? 'Execuția nu are dovezi complete. Nu facturăm, nu trimitem email și nu reluăm automat.'
                : 'The execution does not have complete evidence. We do not bill, email, or replay automatically.') + '</p>' +
            '</div>'
        );
        $('#aysa-agent8v3-modal-actions').empty();
        $('#aysa-agent8v3-modal-page').text('-');
        $('#aysa-agent8v3-modal-prev, #aysa-agent8v3-modal-next').prop('disabled', true);
    }

    function renderModalInlineActionError(message) {
        const context = modalLoadingContext();
        const friendly = modalFriendlyErrorMessage(message, context);
        const body = $('#aysa-agent8v3-modal-body');
        const hasCurrentReview = body.length > 0 && body.children().length > 0 && !body.find('.aysa-agent8v3-modal-loading-card').length;
        if (!hasCurrentReview) {
            renderModalError(friendly);
            return;
        }
        body.find('.aysa-agent8v3-modal-inline-error').remove();
        body.prepend(
            '<div class="aysa-agent8v3-modal-inline-error" role="alert">' +
            escapeHtml(friendly || 'Action failed.') +
            '</div>'
        );
    }

    function modalUnavailableTitle(context) {
        const key = modalLaunchFallbackKey(context || modalLoadingContext());
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        if (key === 'onpage_metadata') {
            return ro ? 'Titluri și descrieri indisponibile momentan' : 'Titles and descriptions currently unavailable';
        }
        if (key === 'offpage_authority_plan') {
            return ro ? 'Plan de autoritate indisponibil momentan' : 'Authority plan currently unavailable';
        }
        return text('modalUnavailable');
    }

    function modalFriendlyErrorMessage(message, context) {
        const raw = String(message || 'Unknown error');
        const key = modalLaunchFallbackKey(context || modalLoadingContext());
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        if (raw.indexOf('413') !== -1 || raw.toLowerCase().indexOf('request entity too large') !== -1) {
            return 'Datele sunt prea mari pentru o singură încărcare. Încearcă un tab specific sau un filtru; AYSA va încărca un rezumat mai ușor de parcurs.';
        }
        if (key === 'onpage_metadata') {
            const safeMetadataActionErrors = [
                'Selectează cel puțin un rând Metadata',
                'Selecția Metadata depășește limita',
                'Testul QA permite maximum 3 rânduri Metadata',
                'Inventarul On Page nu este disponibil',
                'Selecția conține pagini care nu mai sunt eligibile',
                'Selecția Metadata s-a schimbat față de review',
                'Aplicarea Metadata a fost oprită în siguranță'
            ];
            if (safeMetadataActionErrors.some(function(prefix) { return raw.indexOf(prefix) === 0; })) {
                return raw;
            }
            return ro
                ? 'Titluri și descrieri nu s-au încărcat complet. Nu am generat propuneri, nu am aplicat metadata și nu am consumat credite. Reîncearcă tabul sau redeschide review-ul.'
                : 'Titles and descriptions did not fully load. No proposals were generated, no metadata was applied, and no credits were consumed. Retry the tab or reopen the review.';
        }
        if (key === 'offpage_authority_plan') {
            return ro
                ? 'Planul de autoritate nu s-a încărcat complet. Nu am plasat comenzi, nu am chemat provideri și nu am consumat credite. Reîncearcă tabul sau deschide Off Page SEO din nou.'
                : 'The authority plan did not fully load. No orders were placed, no providers were called, and no credits were consumed. Retry the tab or reopen Off Page SEO.';
        }
        if (raw === 'modal_timeout' || raw.toLowerCase().indexOf('timeout') !== -1) {
            return 'Review-ul se încarcă greu. Nu am pornit nicio acțiune și nu am modificat site-ul. Încearcă din nou sau deschide un tab specific.';
        }
        if (raw.indexOf('missing_requirement:') === 0) {
            const requirement = raw.replace('missing_requirement:', '');
            const setupCopy = ro
                ? 'Nu pot porni această acțiune încă. Lipsește o etapă obligatorie de configurare. Verifică setup-ul site-ului și reîncearcă.'
                : 'I cannot start this action yet. A required setup step is missing. Check the site setup and try again.';
            const missingRequirementCopy = {
                keyword_research_completed: ro
                    ? 'Nu pot porni auditul Technical SEO încă. Keyword Research trebuie finalizat înainte, ca să folosim datele corecte ale proiectului.'
                    : 'I cannot start the Technical SEO audit yet. Keyword Research must finish first so the project uses the correct data.',
                content_plan_approved: ro
                    ? 'Nu pot continua această acțiune încă. Content Plan nu este aprobat. Această condiție nu ar trebui să blocheze pornirea auditului Technical SEO.'
                    : 'I cannot continue this action yet. Content Plan is not approved. This condition should not block starting the Technical SEO audit.',
                technical_seo_review_completed: ro
                    ? 'Nu pot continua încă. Review-ul Technical SEO trebuie finalizat înainte de pasul următor.'
                    : 'I cannot continue yet. The Technical SEO review must be completed before the next step.'
            };
            return missingRequirementCopy[requirement] || setupCopy;
        }
        if (raw === 'keyword_mapping_required') {
            return ro
                ? 'Nu am putut respinge acest rând pentru că acțiunea nu a primit keywordul sau mappingul corect. Lista rămâne disponibilă; reîncearcă sau redeschide review-ul.'
                : 'I could not reject this row because the action did not receive the correct keyword or mapping. The review remains available; retry or reopen it.';
        }
        return raw;
    }

    function authorityPlanSummaryItem(summary, key) {
        const items = Array.isArray(summary) ? summary : [];
        return items.find(function(item) {
            return item && String(item.key || '') === String(key || '');
        }) || {};
    }

    function authorityPlanSummaryValue(summary, key, fallback) {
        const item = authorityPlanSummaryItem(summary, key);
        const value = item && item.value !== undefined && item.value !== null ? String(item.value) : '';
        return value || String(fallback || '-');
    }

    function renderAuthorityPlanSummary(modal, summary) {
        modal = modal && typeof modal === 'object' ? modal : {};
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const strategy = modal.strategy_summary && typeof modal.strategy_summary === 'object' ? modal.strategy_summary : {};
        const counts = modal.normalized_safety_counts && typeof modal.normalized_safety_counts === 'object'
            ? modal.normalized_safety_counts
            : {};
        const pagination = modal.server_pagination && typeof modal.server_pagination === 'object'
            ? modal.server_pagination
            : (modal.pagination || {});
        const total = parseInt(pagination.total || strategy.purchase_recommendations_count || 0, 10) || 0;
        const needed = authorityPlanSummaryValue(summary, 'needed', strategy.needed_links || 0);
        const ready = parseInt(counts.ready_for_cart_preview || 0, 10) || 0;
        const review = parseInt(counts.needs_review || 0, 10) || 0;
        const blocked = parseInt(counts.blocked || 0, 10) || 0;
        const reviewable = ready + review;
        const benchmark = String(modal.competitor_benchmark_copy || authorityPlanSummaryValue(summary, 'authority_plan_benchmark_copy', '')).trim();
        const benchmarkBlocked = benchmark.toLowerCase().indexOf('indisponibil') !== -1 || benchmark.toLowerCase().indexOf('blocat') !== -1;
        const headline = total > 0
            ? (ro ? 'Planul de autoritate este pregătit pentru verificare.' : 'The authority plan is ready for review.')
            : (ro ? 'Planul de autoritate nu are încă oportunități disponibile.' : 'The authority plan has no opportunities available yet.');
        const explanation = total > 0
            ? (benchmarkBlocked
                ? (ro ? 'Am găsit oportunități de promovare, dar achizițiile plătite rămân blocate până când avem benchmark-ul competitorilor și un portal cu preț exact.' : 'Promotion opportunities were found, but paid acquisition remains blocked until competitor benchmarking and an exact portal price are available.')
                : (ro ? 'Poți verifica oportunitățile și selecta separat acțiunile potrivite. Deschiderea acestui review nu plasează comenzi și nu modifică site-ul.' : 'You can review opportunities and select actions separately. Opening this review does not place orders or change the site.'))
            : (ro ? 'Nu pornesc nicio comandă. Verifică sursa și regenerează planul doar după confirmarea costului afișat.' : 'No order is started. Check the source and regenerate the plan only after confirming the displayed cost.');
        const source = String(modal.source_audit_copy || authorityPlanSummaryValue(summary, 'authority_plan_source_copy', '-'));
        const freshness = String(modal.source_freshness_copy || authorityPlanSummaryValue(summary, 'authority_plan_source_freshness', '-'));
        const selectedCost = authorityPlanSummaryValue(summary, 'extra', ro ? '0 credite' : '0 credits');
        const externalCost = authorityPlanSummaryValue(summary, 'potential_external_cost', ro ? 'Nefinalizat' : 'Unconfirmed');
        const regenCost = authorityPlanSummaryValue(summary, 'authority_plan_estimated_cost', '45');
        const metric = function(label, value, note) {
            return '<div class="aysa-agent8v3-authority-summary-metric"><span>' + escapeHtml(label) + '</span><strong>' + escapeHtml(String(value)) + '</strong>' + (note ? '<small>' + escapeHtml(note) + '</small>' : '') + '</div>';
        };
        const step = function(number, label) {
            return '<div class="aysa-agent8v3-authority-summary-step"><b>' + escapeHtml(String(number)) + '</b><span>' + escapeHtml(label) + '</span></div>';
        };
        return '<section class="aysa-agent8v3-authority-summary" aria-label="' + escapeHtml(ro ? 'Rezumat plan de autoritate' : 'Authority plan summary') + '">' +
            '<div class="aysa-agent8v3-authority-summary-hero"><div><span class="aysa-agent8v3-authority-summary-kicker">' + escapeHtml(ro ? 'Rezumat plan' : 'Plan summary') + '</span><h3>' + escapeHtml(headline) + '</h3><p>' + escapeHtml(explanation) + '</p></div><span class="aysa-agent8v3-authority-summary-safe">' + escapeHtml(ro ? 'Fără comandă automată' : 'No automatic ordering') + '</span></div>' +
            '<div class="aysa-agent8v3-authority-summary-metrics">' +
                metric(ro ? 'Linkuri necesare' : 'Links needed', needed) +
                metric(ro ? 'Oportunități găsite' : 'Opportunities found', total) +
                metric(ro ? 'Pregătite pentru review' : 'Ready for review', reviewable) +
                metric(ro ? 'Blocate pentru siguranță' : 'Blocked for safety', blocked) +
            '</div>' +
            '<div class="aysa-agent8v3-authority-summary-source"><div><span>' + escapeHtml(ro ? 'Sursă și prospețime' : 'Source and freshness') + '</span><strong>' + escapeHtml(source) + '</strong><small>' + escapeHtml(freshness) + '</small></div><div><span>' + escapeHtml(ro ? 'Benchmark competitori' : 'Competitor benchmark') + '</span><strong>' + escapeHtml(benchmark || (ro ? 'Nu este disponibil' : 'Not available')) + '</strong></div></div>' +
            '<div class="aysa-agent8v3-authority-summary-costs"><div><span>' + escapeHtml(ro ? 'Regenerare plan' : 'Plan regeneration') + '</span><strong>' + escapeHtml(regenCost + (ro ? ' credite' : ' credits')) + '</strong><small>' + escapeHtml(ro ? 'Necesită confirmare separată' : 'Requires separate confirmation') + '</small></div><div><span>' + escapeHtml(ro ? 'Selectat momentan' : 'Selected now') + '</span><strong class="aysa-agent8v3-authority-selected-cost">' + escapeHtml(selectedCost) + '</strong><small>' + escapeHtml(ro ? 'Nu este facturat din acest review' : 'Not billed from this review') + '</small></div><div><span>' + escapeHtml(ro ? 'Cost extern' : 'External cost') + '</span><strong>' + escapeHtml(externalCost) + '</strong><small>' + escapeHtml(ro ? 'Estimare neconfirmată; nu este preț final' : 'Unconfirmed estimate; not a final price') + '</small></div></div>' +
            '<div class="aysa-agent8v3-authority-summary-steps" aria-label="' + escapeHtml(ro ? 'Pașii următori' : 'Next steps') + '">' +
                step(1, ro ? 'Verifică sursa' : 'Check the source') + step(2, ro ? 'Revizuiește oportunitățile' : 'Review opportunities') + step(3, ro ? 'Selectează liniile' : 'Select lines') + step(4, ro ? 'Confirmă separat fiecare acțiune' : 'Confirm each action separately') +
            '</div>' +
        '</section>';
    }

    function authorityPlanModuleLabel(key, ro) {
        const labels = {
            publisher_article: ro ? 'Articole publisher' : 'Publisher articles',
            included_monthly_link: ro ? 'Linkuri lunare incluse' : 'Included monthly links',
            seo_text_ads: 'SEO Text Ads',
            link_exchange: ro ? 'Schimb de linkuri' : 'Link Exchange',
            link_insertion: ro ? 'Inserare link' : 'Link insertion',
            authority_recommendation: ro ? 'Recomandări de autoritate' : 'Authority recommendations',
            other: ro ? 'Alte oportunități' : 'Other opportunities'
        };
        return labels[String(key || '').toLowerCase()] || String(key || (ro ? 'Alte oportunități' : 'Other opportunities'));
    }

    function renderAuthorityPlanCards(rows, modal) {
        const items = Array.isArray(rows) ? rows : [];
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const groups = {};
        items.forEach(function(row) {
            row = row && typeof row === 'object' ? row : {};
            const key = String(row.recommendation_type || row.type || row.execution_module || 'other').toLowerCase().replace(/[^a-z0-9_]+/g, '_');
            if (!groups[key]) {
                groups[key] = [];
            }
            groups[key].push(row);
        });
        const order = ['publisher_article', 'included_monthly_link', 'seo_text_ads', 'link_exchange', 'link_insertion', 'other'];
        const moduleCounts = modal && modal.module_counts && typeof modal.module_counts === 'object' ? modal.module_counts : {};
        const groupKeys = order.filter(function(key) { return groups[key]; }).concat(Object.keys(groups).filter(function(key) { return order.indexOf(key) === -1; }));
        if (!groupKeys.length) {
            return '<div class="aysa-agent8v3-modal-empty">' + escapeHtml((modal && modal.empty_message) || (ro ? 'Nu există oportunități pe această pagină.' : 'No opportunities on this page.')) + '</div>';
        }
        const statusText = function(row) {
            return String(row.execution_status || row.status_copy || row.status || (ro ? 'De verificat' : 'Needs review'));
        };
        const card = function(row) {
            const target = String(row.target_url || '-');
            const keyword = String(row.keyword || '-');
            const anchor = String(row.anchor_suggestion || row.anchor || '-');
            const portal = String(row.portal_domain || row.partner || (ro ? 'Portal de ales' : 'Portal to select'));
            const cost = String(row.execution_cost || row.cost_status || (ro ? 'Cost neconfirmat' : 'Cost unconfirmed'));
            const reason = String(row.reason || row.next_safe_action || '-');
            const safety = String(row.target_safety_note || row.execution_blocker || '');
            const action = row.action && typeof row.action === 'object' ? renderModalCell(row, { type: 'action' }, 'action') : '';
            const selection = row.line_selection && typeof row.line_selection === 'object' ? row.line_selection : {};
            const selectable = !!selection.selectable;
            const selectionLabel = ro ? 'Selectează această linie pentru preview' : 'Select this line for preview';
            const selectionControl = '<label class="aysa-agent8v3-authority-plan-card-selection' + (selectable ? '' : ' is-disabled') + '">' +
                '<input type="checkbox" class="aysa-agent8v3-authority-plan-row" aria-label="' + escapeHtml(selectionLabel) + '" data-line-id="' + escapeHtml(String(selection.line_id || '')) + '" data-recommendation-id="' + escapeHtml(String(selection.recommendation_id || '')) + '" data-cost="' + escapeHtml(String(parseInt(selection.estimated_cost_cents || 0, 10) || 0)) + '"' + (selectable ? '' : ' disabled') + '>' +
                '<span>' + escapeHtml(selectable ? selectionLabel : (ro ? 'Linie indisponibilă pentru selecție' : 'Line unavailable for selection')) + '</span></label>';
            return '<article class="aysa-agent8v3-authority-opportunity-card">' +
                '<div class="aysa-agent8v3-authority-opportunity-head"><div><span>' + escapeHtml(ro ? 'Țintă' : 'Target') + '</span><strong>' + escapeHtml(target) + '</strong></div><span class="aysa-agent8v3-authority-opportunity-status">' + escapeHtml(statusText(row)) + '</span></div>' +
                '<div class="aysa-agent8v3-authority-opportunity-facts"><div><span>' + escapeHtml(ro ? 'Keyword' : 'Keyword') + '</span><strong>' + escapeHtml(keyword) + '</strong></div><div><span>' + escapeHtml(ro ? 'Anchor' : 'Anchor') + '</span><strong>' + escapeHtml(anchor) + '</strong></div><div><span>' + escapeHtml(ro ? 'Portal / partener' : 'Portal / partner') + '</span><strong>' + escapeHtml(portal) + '</strong></div><div><span>' + escapeHtml(ro ? 'Cost' : 'Cost') + '</span><strong>' + escapeHtml(cost) + '</strong></div></div>' +
                '<p class="aysa-agent8v3-authority-opportunity-reason"><span>' + escapeHtml(ro ? 'De ce apare' : 'Why it appears') + '</span>' + escapeHtml(reason) + '</p>' +
                (safety ? '<details class="aysa-agent8v3-authority-opportunity-details"><summary>' + escapeHtml(ro ? 'Vezi detalii' : 'View details') + '</summary><p>' + escapeHtml(safety) + '</p></details>' : '') +
                selectionControl +
                (action ? '<div class="aysa-agent8v3-authority-opportunity-action">' + action + '</div>' : '') +
            '</article>';
        };
        return '<div class="aysa-agent8v3-authority-groups">' + groupKeys.map(function(key) {
            const groupRows = groups[key] || [];
            const count = parseInt(moduleCounts[key] || groupRows.length, 10) || groupRows.length;
            return '<section class="aysa-agent8v3-authority-group"><div class="aysa-agent8v3-authority-group-head"><div><h3>' + escapeHtml(authorityPlanModuleLabel(key, ro)) + '</h3><span>' + escapeHtml((ro ? 'Pe această pagină: ' : 'On this page: ') + groupRows.length + ' · ' + (ro ? 'în plan: ' : 'in plan: ') + count) + '</span></div><span class="aysa-agent8v3-authority-group-count">' + escapeHtml(String(count)) + '</span></div><div class="aysa-agent8v3-authority-opportunity-list">' + groupRows.map(card).join('') + '</div></section>';
        }).join('') + '</div>';
    }

    function renderSeoTextAdsDiagnostics(modal) {
        modal = modal && typeof modal === 'object' ? modal : {};
        const diagnostics = modal.seo_text_ads_diagnostics && typeof modal.seo_text_ads_diagnostics === 'object'
            ? modal.seo_text_ads_diagnostics
            : {};
        const rows = Array.isArray(diagnostics.diagnostics) ? diagnostics.diagnostics : [];
        const reasons = Array.isArray(diagnostics.reason_summary) ? diagnostics.reason_summary : [];
        const history = Array.isArray(diagnostics.legacy_history) ? diagnostics.legacy_history : [];
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        if (!rows.length && !reasons.length && !history.length && !modal.seo_text_ads_status_copy) {
            return '';
        }
        const summaryRows = reasons.map(function(item) {
            return '<li><strong>' + escapeHtml(String(item.count || 0)) + '</strong> ' + escapeHtml(String(item.reason || '')) + '</li>';
        }).join('');
        const detailRows = rows.map(function(item) {
            return '<tr><td>' + escapeHtml(String(item.source || '-')) + '</td><td>' + escapeHtml(String(item.channel || '-')) + '</td><td>' + escapeHtml(String(item.target || '-')) + '</td><td>' + escapeHtml(String(item.portal || '-')) + '</td><td>' + escapeHtml(String(item.status || '-')) + '</td><td>' + escapeHtml(String(item.reason || '-')) + '</td></tr>';
        }).join('');
        const historyHtml = history.map(function(item) {
            return '<article class="aysa-agent8v3-seo-text-ads-history"><strong>' + escapeHtml(String(item.order_ref || '-')) + '</strong><span>' + escapeHtml(String(item.status || '-')) + '</span><p>' + escapeHtml(String(item.message || '')) + '</p><small>' + escapeHtml([item.billing, item.readback, item.source, item.action].filter(Boolean).join(' · ')) + '</small></article>';
        }).join('');
        return '<section class="aysa-agent8v3-seo-text-ads-diagnostics" aria-label="' + escapeHtml(ro ? 'Diagnostic SEO Text Ads' : 'SEO Text Ads diagnostics') + '">' +
            '<div class="aysa-agent8v3-seo-text-ads-diagnostics-head"><strong>' + escapeHtml(String(modal.seo_text_ads_status_copy || diagnostics.empty_copy || (ro ? 'Status SEO Text Ads indisponibil.' : 'SEO Text Ads status unavailable.'))) + '</strong><span>' + escapeHtml((ro ? 'Candidați compleți: ' : 'Complete candidates: ') + String(modal.seo_text_ads_candidate_count || diagnostics.candidate_count || 0) + (ro ? ' · excluse: ' : ' · excluded: ') + String(diagnostics.excluded_count || 0)) + '</span></div>' +
            (summaryRows ? '<div class="aysa-agent8v3-seo-text-ads-reason-summary"><strong>' + escapeHtml(ro ? 'De ce au fost excluse' : 'Why rows were excluded') + '</strong><ul>' + summaryRows + '</ul></div>' : '') +
            (detailRows ? '<details class="aysa-agent8v3-seo-text-ads-diagnostic-details"><summary>' + escapeHtml(ro ? 'Vezi sursele verificate' : 'View checked sources') + '</summary><div class="aysa-agent8v3-modal-table-wrap"><table class="aysa-agent8v3-modal-table"><thead><tr><th>' + escapeHtml(ro ? 'Sursă' : 'Source') + '</th><th>' + escapeHtml(ro ? 'Canal' : 'Channel') + '</th><th>' + escapeHtml(ro ? 'Target' : 'Target') + '</th><th>' + escapeHtml(ro ? 'Portal' : 'Portal') + '</th><th>' + escapeHtml('Status') + '</th><th>' + escapeHtml(ro ? 'Motiv' : 'Reason') + '</th></tr></thead><tbody>' + detailRows + '</tbody></table></div></details>' : '') +
            (historyHtml ? '<div class="aysa-agent8v3-seo-text-ads-history-wrap"><strong>' + escapeHtml(ro ? 'Istoric intern / tracking legacy' : 'Internal legacy tracking') + '</strong>' + historyHtml + '</div>' : '') +
            '</section>';
    }

    function normalizeMonitoringWorkspaceModal(modal) {
        if (!modal || typeof modal !== 'object' || String(modal.modal_key || '') !== 'monitoring') {
            return modal;
        }

        const policy = modal.monitoring_policy && typeof modal.monitoring_policy === 'object'
            ? Object.assign({}, modal.monitoring_policy)
            : {};
        const summary = modal.monitoring_summary && typeof modal.monitoring_summary === 'object'
            ? Object.assign({}, modal.monitoring_summary)
            : {};
        const preflight = modal.monitoring_refresh_preflight && typeof modal.monitoring_refresh_preflight === 'object'
            ? modal.monitoring_refresh_preflight
            : {};
        // Older projections use enabled_sources while the current API uses
        // sources. Both describe the same persisted policy contract.
        const policySources = Array.isArray(policy.sources) && policy.sources.length
            ? policy.sources.slice()
            : (Array.isArray(policy.enabled_sources) ? policy.enabled_sources.slice() : []);
        const automationEnabled = policy.auto_execute_within_policy === true || policy.auto_execute === true;
        const automationVersion = parseInt(
            policy.automation_contract_version || policy.automation_version || 0,
            10
        );
        const hasNewAutomationConsent = automationEnabled
            && automationVersion >= 3
            && policySources.indexOf('serp') !== -1
            && policySources.indexOf('gsc') !== -1;
        const execution = modal.monitoring_execution && typeof modal.monitoring_execution === 'object'
            ? modal.monitoring_execution
            : {};
        const completedSourceRuns = ['rank', 'gsc'].every(function(source) {
            return String((execution[source] && execution[source].state) || '') === 'completed';
        });
        const prepared = Math.max(
            parseInt(summary.prepared_keywords || 0, 10) || 0,
            parseInt(policy.included_count || 0, 10) || 0,
            parseInt(preflight.included_keywords_count || preflight.included_targets_count || 0, 10) || 0
        );
        const saved = Math.max(0, parseInt(summary.saved_positions || 0, 10) || 0);
        // A terminal task group is not a completed baseline when it saved only
        // part of the current scope. Otherwise 1/20 results can suppress the
        // one-time automation confirmation and strand the remaining keywords.
        const completedInitialBaseline = completedSourceRuns && prepared > 0 && saved >= prepared;
        // A completed baseline proves that data exists; it cannot override an
        // explicit server decision that the saved policy boundary changed.
        // Keep that decision visible while still suppressing stale legacy-only
        // confirmation prompts for unchanged completed baselines.
        const explicitPolicyReconfirmation = !!policy.requires_reconfirmation || [
            'needs_confirmation',
            'requires_reconfirmation',
            'blocked_scope_changed',
            'source_configuration_changed',
            'blocked_cost_changed',
            'gsc_connection_required'
        ].indexOf(String(policy.status || '')) !== -1;
        const policyIsActiveAutomatic = !explicitPolicyReconfirmation && (completedInitialBaseline || ((policy.enabled === true || policy.enabled === 1 || policy.enabled === '1')
            && ['active', 'confirmed'].indexOf(String(policy.status || '')) !== -1
            && hasNewAutomationConsent));
        const estimate = Math.max(
            parseInt(policy.estimated_cost_credits || 0, 10) || 0,
            parseInt(preflight.estimated_cost_credits || 0, 10) || 0
        );
        // During an explicit reconfirmation, the server-projected defaults are
        // the proposal being reviewed. The persisted caps are the obsolete
        // values that caused the cost decision and must not prefill the form.
        const perRun = explicitPolicyReconfirmation
            ? (parseInt(policy.default_per_run_cap_credits || 0, 10) || estimate)
            : (parseInt(policy.per_run_cap_credits || policy.default_per_run_cap_credits || 0, 10) || estimate);
        const monthly = explicitPolicyReconfirmation
            ? (parseInt(policy.default_monthly_cap_credits || 0, 10) || perRun)
            : (parseInt(policy.monthly_cap_credits || policy.default_monthly_cap_credits || 0, 10) || perRun);
        // The API owns the policy gate. Older projections may omit the
        // display-only GSC flag, but a positive server verdict is still
        // canonical and must not be replaced by a client-side fallback.
        const serverCanConfirm = typeof policy.can_confirm === 'boolean'
            ? policy.can_confirm
            : null;
        const policyDeclaresGsc = policySources.indexOf('gsc') !== -1;
        const legacyPolicyCanBeReconfirmed = !hasNewAutomationConsent && prepared > 0 && estimate > 0;
        // A legacy bridge can omit the display-only selection flag and the
        // server verdict together while still projecting GSC as a selected
        // source. Do not create a false client-side block in that case: the
        // existing confirmation endpoint remains the authority and validates
        // the canonical OAuth selection before it can start a baseline.
        const gscReady = policy.gsc_property_configured === true
            || serverCanConfirm === true
            || (serverCanConfirm === null && (policyDeclaresGsc || legacyPolicyCanBeReconfirmed));
        const ro = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const compatibilityReady = prepared > 0 && estimate > 0 && perRun >= estimate && monthly >= perRun && gscReady;
        const compatibilityReason = !gscReady
            ? (ro ? 'Selectează proprietatea Search Console din integrarea Google înainte de confirmare.' : 'Select the Search Console property in Google integration before confirming.')
            : (prepared <= 0
                ? (ro ? 'Nu există keyworduri pregătite pentru verificare.' : 'There are no keywords ready for checking.')
                : (estimate <= 0
                    ? (ro ? 'Lipsește estimarea pentru pozițiile Google.' : 'The Google positions estimate is missing.')
                    : (perRun < estimate || monthly < perRun
                        ? (ro ? 'Plafonul pentru o actualizare sau bugetul lunar este sub estimarea necesară.' : 'The per-update cap or monthly budget is below the required estimate.')
                        : '')));

        summary.prepared_keywords = prepared;
        summary.saved_positions = saved;
        summary.frequency = String(summary.frequency || policy.update_frequency || '-');
        modal.monitoring_summary = summary;

        // Older plugin bridges can project a valid legacy SERP-only policy while
        // the API already requires the new SERP + GSC automation consent. Keep
        // the current workspace honest and let the existing server action
        // validate the same scope, caps, and wallet on confirmation.
        if (!policyIsActiveAutomatic && !hasNewAutomationConsent && prepared > 0 && estimate > 0) {
            policy.status = 'requires_reconfirmation';
            policy.requires_reconfirmation = true;
            policy.sources = ['serp', 'gsc'];
            policy.source_labels = ro
                ? ['Poziții Google', 'Search Console']
                : ['Google positions', 'Search Console'];
            policy.estimated_cost_credits = estimate;
            policy.per_run_cap_credits = perRun;
            policy.monthly_cap_credits = monthly;
            policy.default_per_run_cap_credits = perRun;
            policy.default_monthly_cap_credits = monthly;
            policy.can_confirm = serverCanConfirm === true ? true : compatibilityReady;
            policy.disabled_reason = compatibilityReady ? '' : (String(policy.disabled_reason || '') || compatibilityReason);
            if (serverCanConfirm === true) {
                policy.disabled_reason = '';
            }
            policy.message = ro
                ? 'Politica existentă trebuie reconfirmată pentru primul baseline automat cu Poziții Google și Search Console.'
                : 'The existing policy must be reconfirmed for the first automatic Google positions and Search Console baseline.';
            policy.auto_run_rule = ro
                ? 'După confirmare, primul baseline pornește o singură dată. Rulările ulterioare respectă frecvența din Profil SEO și se opresc dacă se schimbă scope-ul, costul sau plafonul.'
                : 'After confirmation, the first baseline starts once. Later runs follow the SEO Profile frequency and stop if scope, cost, or caps change.';
        } else if (policyIsActiveAutomatic) {
            // An active v3 policy is already the canonical approval. Never
            // synthesize a legacy reconfirmation CTA for it in the browser.
            policy.status = 'confirmed';
            policy.requires_reconfirmation = false;
            policy.can_confirm = false;
            policy.disabled_reason = '';
            if (!Array.isArray(policy.sources) || !policy.sources.length) {
                policy.sources = ['serp', 'gsc'];
            }
            if (!Array.isArray(policy.source_labels) || !policy.source_labels.length) {
                policy.source_labels = ro
                    ? ['Poziții Google', 'Search Console']
                    : ['Google positions', 'Search Console'];
            }
        }
        modal.monitoring_policy = policy;

        const actions = Array.isArray(modal.actions) ? modal.actions.slice() : [];
        const confirmationIndex = actions.findIndex(function(action) {
                return String(action && action.action || '') === 'configure_monitoring_policy';
        });
        const confirmationAction = {
                    action: 'configure_monitoring_policy',
                    label: ro
                        ? 'Confirmă monitorizarea automată'
                        : 'Confirm automatic monitoring',
                    disabled: !policy.can_confirm,
                    disabled_reason: String(policy.disabled_reason || ''),
                    payload: {
                        confirmation_kind: 'monitoring_policy_approval',
                        enabled_sources: policy.sources,
                        per_run_cap_cents: perRun,
                        monthly_budget_cents: monthly,
                        auto_execute_within_policy: true,
                        initial_baseline_after_confirmation: true
                    }
                };
        const policyConfirmationVisible = !!policy.requires_reconfirmation || [
            'needs_confirmation',
            'requires_reconfirmation',
            'blocked_scope_changed',
            'source_configuration_changed',
            'blocked_cost_changed',
            'policy_missing',
            'gsc_connection_required'
        ].indexOf(String(policy.status || '')) !== -1;
        if (policyIsActiveAutomatic && confirmationIndex !== -1) {
            actions.splice(confirmationIndex, 1);
        } else if (confirmationIndex === -1 && policyConfirmationVisible) {
            actions.push(confirmationAction);
        } else if (confirmationIndex !== -1
            && policyConfirmationVisible
            && policy.can_confirm === true
            && compatibilityReady
        ) {
            // A stale action entry can otherwise leave the button disabled
            // after the normalized policy has verified GSC, scope, estimate,
            // and caps. This only repairs display state; the canonical server
            // endpoint validates the same hashes and limits again on submit.
            actions[confirmationIndex] = Object.assign({}, actions[confirmationIndex], confirmationAction, {
                payload: Object.assign({}, actions[confirmationIndex].payload || {}, confirmationAction.payload)
            });
        }
        modal.actions = actions;

        modal.subtitle = String(uiLanguage() || 'ro').indexOf('ro') === 0
            ? prepared + ' keyworduri pregătite pentru verificare'
            : prepared + ' keywords ready for checking';
        return modal;
    }

    function technicalSummaryDetailsHtml(modal) {
        const items = Array.isArray(modal && modal.summary_details) ? modal.summary_details : [];
        if (!items.length) {
            return '';
        }
        const ro = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        return '<details class="aysa-agent8v3-technical-details">' +
            '<summary>' + escapeHtml(ro ? 'Context tehnic' : 'Technical context') + ' <span>(' + escapeHtml(String(items.length)) + ')</span></summary>' +
            '<dl>' + items.map(function(item) {
                const label = modalLabel(item && item.label || '', item && item.key || '');
                const value = modalDisplayValue(item && item.value !== undefined ? item.value : '-', item && item.key || '');
                return '<div><dt>' + escapeHtml(label) + '</dt><dd>' + escapeHtml(value) + '</dd></div>';
            }).join('') + '</dl></details>';
    }

    function technicalCompactColumns(columns) {
        columns = Array.isArray(columns) ? columns : [];
        if (columns.length <= 7) {
            return { visible: columns, hidden: [] };
        }
        const actionColumns = columns.filter(function(column) {
            return column && (
                column.type === 'action' ||
                /^(selection|review_action|consolidation_action|dry_run_action)$/.test(String(column.key || ''))
            );
        });
        const contentColumns = columns.filter(function(column) {
            return actionColumns.indexOf(column) === -1;
        });
        const visible = contentColumns.slice(0, Math.max(4, 7 - actionColumns.length)).concat(actionColumns.slice(0, 2));
        return {
            visible: visible,
            hidden: columns.filter(function(column) { return visible.indexOf(column) === -1; })
        };
    }

    function renderTechnicalCompactTable(modal, columns, rows, modalTableClass) {
        const compact = technicalCompactColumns(columns);
        const ro = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const head = compact.visible.map(function(column) {
            return '<th scope="col"' + modalColumnClass(column, column.key || '') + '>' +
                escapeHtml(modalLabel(column.label || '', column.key || '')) + '</th>';
        }).join('');
        const body = rows.map(function(row) {
            const cells = compact.visible.map(function(column) {
                const key = column.key || '';
                const label = modalLabel(column.label || '', key);
                return '<td data-label="' + escapeHtml(label) + '"' + modalColumnClass(column, key) + '>' + renderModalCell(row, column, key) + '</td>';
            }).join('');
            const details = compact.hidden.length
                ? '<tr class="aysa-agent8v3-technical-row-details"><td colspan="' + escapeHtml(String(compact.visible.length)) + '">' +
                    '<details><summary>' + escapeHtml(ro ? 'Vezi toate detaliile' : 'View all details') + '</summary><dl>' +
                    compact.hidden.map(function(column) {
                        const key = column.key || '';
                        return '<div><dt>' + escapeHtml(modalLabel(column.label || '', key)) + '</dt><dd>' +
                            renderModalCell(row, column, key) + '</dd></div>';
                    }).join('') + '</dl></details></td></tr>'
                : '';
            return '<tr' + modalRowClass(row, modal) + '>' + cells + '</tr>' + details;
        }).join('');
        return '<div class="aysa-agent8v3-modal-table-wrap ' + escapeHtml(modalTableClass) + '">' +
            '<table class="aysa-agent8v3-modal-table"><thead><tr>' + head + '</tr></thead><tbody>' + body + '</tbody></table></div>';
    }

    function renderKeywordMappingCards(modal, columns, rows) {
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const byKey = {};
        (Array.isArray(columns) ? columns : []).forEach(function(column) {
            if (column && column.key) {
                byKey[String(column.key)] = column;
            }
        });
        const cell = function(row, key) {
            const column = byKey[key] || {key: key, label: key};
            return renderModalCell(row, column, key);
        };
        const label = function(key, fallbackRo, fallbackEn) {
            const column = byKey[key] || {};
            return modalLabel(column.label || (ro ? fallbackRo : fallbackEn), key);
        };
        const summaryValue = function(labels) {
            const summary = Array.isArray(modal && modal.summary) ? modal.summary : [];
            const match = summary.find(function(item) {
                const itemLabel = String(item && item.label || '').toLocaleLowerCase();
                return labels.some(function(candidate) {
                    return itemLabel === candidate;
                });
            });
            return match ? String(match.value || '0') : '0';
        };
        const accepted = summaryValue(['acceptate', 'accepted']);
        const decisions = summaryValue(['decizii necesare', 'decisions needed']);
        const intro = '<section class="aysa-agent8v3-keyword-mapping-focus" aria-label="' + escapeHtml(ro ? 'Prioritatea review-ului' : 'Review priority') + '">' +
            '<div><strong>' + escapeHtml(ro ? 'Concentrează-te doar pe excepții' : 'Focus only on exceptions') + '</strong>' +
                '<p>' + escapeHtml(ro
                    ? accepted + ' asocieri sunt păstrate în review. Intervenția ta este necesară doar pentru cele ' + decisions + ' cazuri marcate explicit ca decizie.'
                    : accepted + ' associations remain in review. Your input is needed only for the ' + decisions + ' cases explicitly marked as decisions.') + '</p></div>' +
            '<button type="button" class="button button-primary aysa-agent8v3-keyword-mapping-focus-decisions">' +
                escapeHtml(ro ? 'Arată doar deciziile necesare' : 'Show decisions only') + '</button>' +
            '<small>' + escapeHtml(ro ? 'Filtrare read-only · fără credite · fără modificări pe site' : 'Read-only filter · no credits · no site changes') + '</small>' +
        '</section>';
        const cards = rows.map(function(row) {
            const stage = String(row && (row.resolution_section || row.lifecycle_state || row.status) || 'review').replace(/[^a-z0-9_-]/gi, '_');
            const details = ['keyword_family', 'candidate_pages', 'signals'].map(function(key) {
                return '<div><dt>' + escapeHtml(label(key,
                    key === 'keyword_family' ? 'Familie keywords' : (key === 'candidate_pages' ? 'Pagini candidate' : 'Semnale'),
                    key === 'keyword_family' ? 'Keyword family' : (key === 'candidate_pages' ? 'Candidate pages' : 'Signals'))) + '</dt><dd>' + cell(row, key) + '</dd></div>';
            }).join('');
            return '<article class="aysa-agent8v3-keyword-mapping-card is-' + escapeHtml(stage) + '">' +
                '<header><div><small>' + escapeHtml(ro ? 'Cluster' : 'Cluster') + '</small><strong>' + cell(row, 'cluster') + '</strong></div>' +
                    '<span class="aysa-agent8v3-keyword-mapping-stage">' + cell(row, 'resolution_label') + '</span></header>' +
                '<div class="aysa-agent8v3-keyword-mapping-target"><span>' + escapeHtml(label('target_url', 'URL țintă', 'Target URL')) + '</span>' + cell(row, 'target_url') + '</div>' +
                '<dl class="aysa-agent8v3-keyword-mapping-signals">' +
                    '<div><dt>' + escapeHtml(label('business_relevance', 'Relevanță business', 'Business relevance')) + '</dt><dd>' + cell(row, 'business_relevance') + '</dd></div>' +
                    '<div><dt>' + escapeHtml(label('target_safety', 'Siguranță target', 'Target safety')) + '</dt><dd>' + cell(row, 'target_safety') + '</dd></div>' +
                    '<div><dt>' + escapeHtml(label('intent_match', 'Potrivire intenție', 'Intent match')) + '</dt><dd>' + cell(row, 'intent_match') + '</dd></div>' +
                    '<div><dt>' + escapeHtml(label('confidence_score', 'Încredere', 'Confidence')) + '</dt><dd>' + cell(row, 'confidence_score') + '</dd></div>' +
                '</dl>' +
                '<div class="aysa-agent8v3-keyword-mapping-explanation"><span>' + escapeHtml(label('resolution_reason', 'De ce', 'Why')) + '</span>' + cell(row, 'resolution_reason') + '</div>' +
                '<div class="aysa-agent8v3-keyword-mapping-next"><span>' + escapeHtml(label('next_product_action', 'Următorul pas', 'Next step')) + '</span>' + cell(row, 'next_product_action') + '</div>' +
                '<details><summary>' + escapeHtml(ro ? 'Vezi keywordurile și dovezile' : 'View keywords and evidence') + '</summary><dl>' + details + '</dl></details>' +
                '<footer><div>' + cell(row, 'review_action') + '</div><div>' + cell(row, 'target_confirmation_action') + '</div><div>' + cell(row, 'content_plan_action') + '</div></footer>' +
            '</article>';
        }).join('');
        return intro + '<div class="aysa-agent8v3-keyword-mapping-cards">' + cards + '</div>';
    }

    function renderContentPlanCards(modal, columns, rows) {
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const byKey = {};
        (Array.isArray(columns) ? columns : []).forEach(function(column) {
            if (column && column.key) {
                byKey[String(column.key)] = column;
            }
        });
        const cell = function(row, key) {
            const column = byKey[key] || {key: key, label: key};
            return renderModalCell(row, column, key);
        };
        const label = function(key, fallbackRo, fallbackEn) {
            const column = byKey[key] || {};
            return modalLabel(column.label || (ro ? fallbackRo : fallbackEn), key);
        };
        return '<div class="aysa-agent8v3-content-plan-cards">' + rows.map(function(row) {
            const reviewState = String(row && row.review_status || 'review').replace(/[^a-z0-9_-]/gi, '_');
            return '<article class="aysa-agent8v3-content-plan-card is-' + escapeHtml(reviewState) + '">' +
                '<header><div><small>' + escapeHtml(ro ? 'Idee de conținut' : 'Content idea') + '</small><strong>' + cell(row, 'title') + '</strong></div>' +
                    '<span class="aysa-agent8v3-content-plan-status">' + cell(row, 'review_status') + '</span></header>' +
                '<div class="aysa-agent8v3-content-plan-keyword"><span>' + escapeHtml(label('primary_keyword', 'Keyword principal', 'Primary keyword')) + '</span>' + cell(row, 'primary_keyword') + '</div>' +
                '<dl><div><dt>' + escapeHtml(label('type', 'Tip', 'Type')) + '</dt><dd>' + cell(row, 'type') + '</dd></div>' +
                    '<div><dt>' + escapeHtml(label('scheduled', 'Programat', 'Scheduled')) + '</dt><dd>' + cell(row, 'scheduled') + '</dd></div>' +
                    '<div><dt>' + escapeHtml(label('source', 'Sursă', 'Source')) + '</dt><dd>' + cell(row, 'source') + '</dd></div></dl>' +
                '<footer><div>' + cell(row, 'review_action') + '</div><small>' + escapeHtml(ro ? 'Review-ul nu generează și nu publică articolul.' : 'Review does not generate or publish the article.') + '</small></footer>' +
            '</article>';
        }).join('') + '</div>';
    }

    function syncTechnicalInternalLinkingSummary(modal) {
        if (!modal || String(modal.modal_key || '') !== 'technical_internal_linking') {
            return;
        }
        const summary = Array.isArray(modal.summary) ? modal.summary : [];
        const opportunityItem = summary.find(function(item) {
            return String((item && item.key) || '') === 'opportunities';
        });
        const opportunityCount = opportunityItem
            ? (parseInt(String(opportunityItem.value || '0').replace(/[^0-9-]+/g, ''), 10) || 0)
            : 0;
        if (opportunityCount <= 0) {
            return;
        }
        const technical = state.canonical && state.canonical.data && state.canonical.data.technical_seo
            ? state.canonical.data.technical_seo
            : null;
        if (technical) {
            technical.summary = technical.summary && typeof technical.summary === 'object' ? technical.summary : {};
            technical.summary.modules = technical.summary.modules && typeof technical.summary.modules === 'object' ? technical.summary.modules : {};
            technical.summary.modules.internal_linking = technical.summary.modules.internal_linking && typeof technical.summary.modules.internal_linking === 'object'
                ? technical.summary.modules.internal_linking
                : {};
            technical.summary.modules.internal_linking.opportunity_count = opportunityCount;
        }
        const ro = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        $('.aysa-agent8v3-guidance-review-row').each(function() {
            const row = $(this);
            if (String(row.find('span').first().text() || '').trim() !== 'Internal Linking') {
                return;
            }
            row.find('strong').first().text(ro
                ? opportunityCount + ' oportunități pentru review · fără aplicare automată'
                : opportunityCount + ' opportunities for review · no automatic apply');
        });
        renderSetupProgressPanel(state.canonical || {}, {guidance: state.guidance || {}});
    }

    function renderModal(modal) {
        modal = normalizeMonitoringWorkspaceModal(modal);
        updateModalChromeText();
        const columns = Array.isArray(modal.columns) ? modal.columns : [];
        const rows = Array.isArray(modal.rows) ? modal.rows : [];
        const pagination = modal.pagination || {};
        const summary = Array.isArray(modal.summary) ? modal.summary : [];
        const actions = Array.isArray(modal.actions) ? modal.actions : [];
        const modalKey = String(modal.modal_key || '');
        const isTechnicalModal = modalKey.indexOf('technical_') === 0;
        const isAuthorityPlan = modalKey === 'offpage_seo' && String(modal.display_mode || '') === 'offpage_authority_plan';
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        state.modal.current = modal;
        syncTechnicalInternalLinkingSummary(modal);
        // A Monitoring readback is authoritative for the client-only progress
        // indicator. Do not keep polling after the server reports a terminal run.
        if (modalKey === 'monitoring' && state.monitoringRefreshTimer && !monitoringModalHasRunningRefresh(modal)) {
            stopMonitoringRefreshPolling();
        }
        renderSetupProgressPanel(state.canonical || {}, { phase: state.canonical && state.canonical.phase ? state.canonical.phase : '' });
        $('#aysa-agent8v3-modal-title').text(modalTitle(modal));
        $('#aysa-agent8v3-modal-subtitle').text(modalSubtitle(modal));
        const isMonitoringWorkspace = modalKey === 'monitoring';
        $('.aysa-agent8v3-modal-dialog').toggleClass('is-monitoring-workspace', isMonitoringWorkspace);
        $('.aysa-agent8v3-modal-dialog').toggleClass('is-technical-review', isTechnicalModal);
        $('#aysa-agent8v3-modal-summary').html(isMonitoringWorkspace
            ? ''
            : (isAuthorityPlan
            ? renderAuthorityPlanSummary(modal, summary)
            : summary.map(function(item) {
            const rawSummaryLabel = modalLabel(item.label || '', item.key || '');
            const isRo = String(uiLanguage() || 'ro').indexOf('ro') === 0;
            const summaryLabel = isTechnicalModal && /^(Acceptate|Accepted)$/i.test(rawSummaryLabel)
                ? (isRo ? 'În review' : 'In review')
                : (isTechnicalModal && /^(Respinse|Rejected)$/i.test(rawSummaryLabel)
                    ? (isRo ? 'Excluse manual' : 'Manually excluded')
                    : rawSummaryLabel);
            return '<div><span>' + escapeHtml(summaryLabel) + '</span><strong>' + escapeHtml(modalDisplayValue(item.value || '-', item.key || '')) + '</strong></div>';
        }).join('')));
        renderModalTabs(modal);
        if (state.modal.workspace) {
            writeModuleWorkspaceRoute();
        }
        const reviewableModals = ['research_keywords', 'keyword_mapping', 'missing_pages', 'content_plan', 'technical_site_audit', 'technical_pagespeed', 'technical_schema', 'technical_redirects', 'technical_sitemap_robots', 'technical_image_alt', 'technical_internal_linking', 'onpage_seo', 'offpage_seo', 'monitoring'];
        const declaredReviewFilter = modal.review_filter === undefined
            ? (!isMonitoringWorkspace && !isTechnicalModal && reviewableModals.includes(modalKey))
            : !!modal.review_filter;
        const reviewFilter = !isMonitoringWorkspace && declaredReviewFilter;
        const monitoringTab = isMonitoringWorkspace
            ? String(modal.active_tab || (modal.filters && modal.filters.tab) || 'serp_positions')
            : '';
        const monitoringView = isMonitoringWorkspace
            ? String(modal.monitoring_view || (modal.filters && modal.filters.monitoring_view) || 'overview')
            : '';
        const monitoringPresentation = isMonitoringWorkspace && modal.monitoring_presentation && typeof modal.monitoring_presentation === 'object'
            ? modal.monitoring_presentation
            : {};
        const monitoringAi = monitoringPresentation.ai && typeof monitoringPresentation.ai === 'object'
            ? monitoringPresentation.ai
            : {};
        const monitoringModules = isMonitoringWorkspace && modal.monitoring_modules && typeof modal.monitoring_modules === 'object'
            ? modal.monitoring_modules
            : {};
        const monitoringAiModule = monitoringModules.ai_visibility && typeof monitoringModules.ai_visibility === 'object'
            ? monitoringModules.ai_visibility
            : {};
        const monitoringAiInactive = monitoringTab === 'ai_visibility'
            && (String(monitoringAi.status || monitoringAiModule.status || 'inactive') === 'inactive' || !rows.length);
        const hideMonitoringChrome = isMonitoringWorkspace
            && (monitoringView === 'overview' || monitoringAiInactive);
        const hideFilters = !!modal.hide_filters || hideMonitoringChrome;
        $('.aysa-agent8v3-modal-toolbar').toggle(!hideFilters);
        $('#aysa-agent8v3-modal-search').toggle(!hideFilters);
        if (isMonitoringWorkspace) {
            $('#aysa-agent8v3-modal-search').val(String((modal.filters && modal.filters.search) || (state.modal.filters && state.modal.filters.search) || ''));
        }
        $('#aysa-agent8v3-modal-status').toggle(!hideFilters && reviewFilter);
        $('label[for="aysa-agent8v3-modal-search"]').toggle(!hideFilters);
        $('label[for="aysa-agent8v3-modal-status"]').toggle(!hideFilters && reviewFilter);
        const searchPlaceholder = isMonitoringWorkspace
            ? (String(uiLanguage() || '').indexOf('ro') === 0 ? 'Caută în rezultate...' : 'Search results...')
            : isAuthorityPlan
            ? (String(uiLanguage() || '').indexOf('ro') === 0 ? 'Caută target, keyword sau portal...' : 'Search target, keyword, or portal...')
            : (String(modal.modal_key || '') === 'offpage_seo' && modal.advanced_tabs_visible)
            ? text('modalSearchDetails')
            : text('modalSearch');
        $('#aysa-agent8v3-modal-search').attr('placeholder', searchPlaceholder);
        if (isMonitoringWorkspace) {
            $('label[for="aysa-agent8v3-modal-search"]').text(String(uiLanguage() || '').indexOf('ro') === 0 ? 'Caută în rezultate' : 'Search results');
        }
        const filterOptions = Array.isArray(modal.filter_options) && modal.filter_options.length
            ? modal.filter_options
            : [
                { value: 'all', label: text('modalAll') },
                { value: 'accepted', label: text('modalAccepted') },
                { value: 'rejected', label: text('modalRejected') }
            ];
        $('.aysa-agent8v3-modal-filter-extra').remove();
        const dualOnPageFilters = String(modal.modal_key || '') === 'onpage_seo' && String(modal.filter_mode || '') === 'onpage_dual';
        const metadataRunOptions = String(modal.modal_key || '') === 'onpage_seo'
            && String(modal.active_tab || (modal.filters && modal.filters.tab) || '') === 'meta_snippets'
            && Array.isArray(modal.onpage_metadata_run_options)
            ? modal.onpage_metadata_run_options
            : [];
        if (!reviewFilter) {
            $('#aysa-agent8v3-modal-status').html('');
        } else if (isAuthorityPlan) {
            const moduleOptions = Array.isArray(modal.module_filter_options) && modal.module_filter_options.length
                ? modal.module_filter_options
                : [{ value: 'all', label: ro ? 'Toate produsele' : 'All products' }];
            const activeModule = String((modal.filters && modal.filters.module) || (state.modal.filters && state.modal.filters.module) || 'all');
            const activeStatus = String((modal.filters && modal.filters.status) || (state.modal.filters && state.modal.filters.status) || 'all');
            $('#aysa-agent8v3-modal-status').html(filterOptions.map(function(option) {
                return '<option value="' + escapeHtml(option.value || 'all') + '">' + escapeHtml(clientFacingLabel(option.label || option.value || 'All')) + '</option>';
            }).join(''));
            $('#aysa-agent8v3-modal-status').val(filterOptions.some(function(option) {
                return String(option.value || '') === activeStatus;
            }) ? activeStatus : 'all');
            $('#aysa-agent8v3-modal-status').before('<select id="aysa-agent8v3-modal-module" class="aysa-agent8v3-modal-filter-extra"></select>');
            $('#aysa-agent8v3-modal-module').html(moduleOptions.map(function(option) {
                return '<option value="' + escapeHtml(option.value || 'all') + '">' + escapeHtml(clientFacingLabel(option.label || option.value || 'All')) + '</option>';
            }).join(''));
            $('#aysa-agent8v3-modal-module').val(moduleOptions.some(function(option) {
                return String(option.value || '') === activeModule;
            }) ? activeModule : 'all');
        } else if (dualOnPageFilters) {
            const entityOptions = Array.isArray(modal.entity_filter_options) && modal.entity_filter_options.length
                ? modal.entity_filter_options
                : [{ value: 'all', label: 'All entities' }];
            const workflowOptions = Array.isArray(modal.workflow_filter_options) && modal.workflow_filter_options.length
                ? modal.workflow_filter_options
                : filterOptions;
            const activeEntity = String((modal.filters && modal.filters.entity_type) || (state.modal.filters && state.modal.filters.entity_type) || 'all');
            const activeWorkflow = String((modal.filters && modal.filters.workflow_status) || (state.modal.filters && state.modal.filters.workflow_status) || 'all');
            $('#aysa-agent8v3-modal-status').html(workflowOptions.map(function(option) {
                return '<option value="' + escapeHtml(option.value || 'all') + '">' + escapeHtml(clientFacingLabel(option.label || option.value || 'All')) + '</option>';
            }).join(''));
            $('#aysa-agent8v3-modal-status').val(workflowOptions.some(function(option) {
                return String(option.value || '') === activeWorkflow;
            }) ? activeWorkflow : 'all');
            $('#aysa-agent8v3-modal-status').before('<select id="aysa-agent8v3-modal-entity-type" class="aysa-agent8v3-modal-filter-extra"></select>');
            $('#aysa-agent8v3-modal-entity-type').html(entityOptions.map(function(option) {
                return '<option value="' + escapeHtml(option.value || 'all') + '">' + escapeHtml(clientFacingLabel(option.label || option.value || 'All')) + '</option>';
            }).join(''));
            $('#aysa-agent8v3-modal-entity-type').val(entityOptions.some(function(option) {
                return String(option.value || '') === activeEntity;
            }) ? activeEntity : 'all');
        } else {
            const activeStatus = String((modal.filters && modal.filters.status) || (state.modal.filters && state.modal.filters.status) || 'all');
            $('#aysa-agent8v3-modal-status').html(filterOptions.map(function(option) {
                return '<option value="' + escapeHtml(option.value || 'all') + '">' + escapeHtml(clientFacingLabel(option.label || option.value || 'All')) + '</option>';
            }).join(''));
            $('#aysa-agent8v3-modal-status').val(filterOptions.some(function(option) {
                return String(option.value || '') === activeStatus;
            }) ? activeStatus : 'all');
        }
        if (metadataRunOptions.length) {
            const activeRunId = String((modal.filters && modal.filters.source_run_id) || (state.modal.filters && state.modal.filters.source_run_id) || '');
            $('#aysa-agent8v3-modal-status').before('<label for="aysa-agent8v3-modal-metadata-run" class="screen-reader-text aysa-agent8v3-modal-filter-extra">' + escapeHtml(ro ? 'Lot metadata' : 'Metadata batch') + '</label><select id="aysa-agent8v3-modal-metadata-run" class="aysa-agent8v3-modal-filter-extra" aria-label="' + escapeHtml(ro ? 'Lot metadata' : 'Metadata batch') + '"></select>');
            $('#aysa-agent8v3-modal-metadata-run').html(metadataRunOptions.map(function(option, index) {
                const runId = String(option.run_id || '');
                const count = Math.max(0, parseInt(option.generated_count || 0, 10) || 0);
                const batchNumber = metadataRunOptions.length - index;
                const label = ro
                    ? ('Lot ' + batchNumber + ' · Run ' + runId + ' · ' + count + ' rezultate')
                    : ('Batch ' + batchNumber + ' · Run ' + runId + ' · ' + count + ' results');
                return '<option value="' + escapeHtml(runId) + '">' + escapeHtml(label) + '</option>';
            }).join(''));
            $('#aysa-agent8v3-modal-metadata-run').val(metadataRunOptions.some(function(option) {
                return String(option.run_id || '') === activeRunId;
            }) ? activeRunId : String(metadataRunOptions[0].run_id || ''));
        }
        $('#aysa-agent8v3-modal-actions').html(renderModalActions(actions, modal));
        const hint = renderModalHint(modal);
        const launchNotice = renderLaunchUxNotice(modal);
        const monitoringPrefix = isMonitoringWorkspace
            ? renderMonitoringWorkspaceHeader(modal) + renderMonitoringResultPanel(modal) + renderMonitoringPolicyPreview(modal)
            : '';
        const bodyPrefix = hint + launchNotice + (isTechnicalModal ? technicalSummaryDetailsHtml(modal) : '') + monitoringPrefix + (!isMonitoringWorkspace ? renderMonitoringRefreshPreflightResult(modal) : '') + (String(modal.modal_key || '') === 'offpage_seo' && String(modal.display_mode || '') === 'offpage_seo_text_ads_readiness'
            ? renderSeoTextAdsDiagnostics(modal)
            : '');
        const isOnPageExecutionReport = String(modal.modal_key || '') === 'onpage_seo'
            && String(modal.active_tab || (modal.filters && modal.filters.tab) || '') === 'execution_report';
        const executionHistoryPanel = isOnPageExecutionReport ? renderOnPageExecutionHistoryPanel(modal) : '';
        const isAggregateExecutionReport = String(modal.modal_key || '') === 'offpage_seo'
            && String(modal.display_mode || '') === 'offpage_execution_report'
            && modal.aggregate_report
            && typeof modal.aggregate_report === 'object';
        if (isAggregateExecutionReport) {
            $('#aysa-agent8v3-modal-body').html(bodyPrefix + renderOffPageExecutionReportAggregate(modal.aggregate_report, modal));
        } else if (!rows.length) {
            if (isMonitoringWorkspace) {
                $('#aysa-agent8v3-modal-body').html(bodyPrefix);
                return;
            }
            $('#aysa-agent8v3-modal-body').html(bodyPrefix + executionHistoryPanel + '<div class="aysa-agent8v3-modal-empty">' + escapeHtml(modal.empty_message || 'No rows available.') + '</div>');
        } else if (String(modal.modal_key || '') === 'offpage_seo' && String(modal.display_mode || '') === 'gbp_social_calendar_cards') {
            $('#aysa-agent8v3-modal-body').html(bodyPrefix + renderOffPageGbpSocialCards(rows));
        } else if (String(modal.modal_key || '') === 'offpage_seo' && String(modal.display_mode || '') === 'backlink_audit_cards') {
            $('#aysa-agent8v3-modal-body').html(bodyPrefix + renderOffPageBacklinkAuditCards(rows, modal));
        } else if (String(modal.modal_key || '') === 'offpage_seo' && String(modal.display_mode || '') === 'offpage_canonical_workspace') {
            $('#aysa-agent8v3-modal-body').html(bodyPrefix + renderOffPageCanonicalWorkspace(modal.canonical_workspace || {}, modal));
        } else if (String(modal.modal_key || '') === 'offpage_seo' && String(modal.display_mode || '') === 'offpage_agent_overview') {
            $('#aysa-agent8v3-modal-body').html(bodyPrefix + renderOffPageAgentOverviewCards(rows, modal));
        } else if (isAuthorityPlan) {
            $('#aysa-agent8v3-modal-body').html(bodyPrefix + renderAuthorityPlanCards(rows, modal));
        } else if (String(modal.modal_key || '') === 'onpage_seo' && String(modal.display_mode || '') === 'onpage_agent_overview') {
            $('#aysa-agent8v3-modal-body').html(bodyPrefix + renderOnPageAgentOverviewCards(rows, modal));
        } else if (String(modal.modal_key || '') === 'onpage_seo' && String(modal.active_tab || (modal.filters && modal.filters.tab) || '') === 'content') {
            $('#aysa-agent8v3-modal-body').html(bodyPrefix + renderOnPageContentCards(rows, modal));
        } else if (isMonitoringWorkspace) {
            $('#aysa-agent8v3-modal-body').html(bodyPrefix);
        } else if (String(modal.modal_key || '') === 'content_plan') {
            $('#aysa-agent8v3-modal-body').html(bodyPrefix + renderContentPlanCards(modal, columns, rows) + renderModalLegend(modal));
        } else if (String(modal.modal_key || '') === 'keyword_mapping') {
            $('#aysa-agent8v3-modal-body').html(bodyPrefix + renderKeywordMappingCards(modal, columns, rows) + renderModalLegend(modal));
        } else if (isTechnicalModal) {
            const modalTableClass = 'is-modal-' + String(modal.modal_key || '').replace(/[^a-z0-9_-]/gi, '_') + ' is-tab-' + String(modal.active_tab || (modal.filters && modal.filters.tab) || '').replace(/[^a-z0-9_-]/gi, '_');
            $('#aysa-agent8v3-modal-body').html(bodyPrefix + executionHistoryPanel + renderTechnicalCompactTable(modal, columns, rows, modalTableClass) + renderModalLegend(modal));
        } else {
            const modalTableClass = 'is-modal-' + String(modal.modal_key || '').replace(/[^a-z0-9_-]/gi, '_') + ' is-tab-' + String(modal.active_tab || (modal.filters && modal.filters.tab) || '').replace(/[^a-z0-9_-]/gi, '_');
            $('#aysa-agent8v3-modal-body').html(bodyPrefix + executionHistoryPanel + '<div class="aysa-agent8v3-modal-table-wrap ' + escapeHtml(modalTableClass) + '"><table class="aysa-agent8v3-modal-table"><thead><tr>' +
                columns.map(function(column) {
                    const cls = modalColumnClass(column, column.key || '');
                    return '<th scope="col"' + cls + '>' + escapeHtml(modalLabel(column.label || '', column.key || '')) + '</th>';
                }).join('') +
                '</tr></thead><tbody>' +
                rows.map(function(row) {
                    return '<tr' + modalRowClass(row, modal) + '>' + columns.map(function(column) {
                        const key = column.key || '';
                        const cls = modalColumnClass(column, key);
                        return '<td' + cls + '>' + renderModalCell(row, column, key) + '</td>';
                    }).join('') + '</tr>';
                }).join('') +
                '</tbody></table></div>' + renderModalLegend(modal));
        }
	        if (String(modal.modal_key || '') === 'technical_image_alt') {
	            $('#aysa-agent8v3-modal-body').prepend(renderImageAltTestModePanel(modal));
	            maybeLoadImageAltHistory();
	        }
	        if ((String(modal.modal_key || '') === 'technical_overview' && modal.technical_seo_decision_model && typeof modal.technical_seo_decision_model === 'object') ||
	            (String(modal.modal_key || '') === 'technical_site_audit' && String(modal.active_tab || (modal.filters && modal.filters.tab) || '') === 'safe_bundle')) {
	            $('#aysa-agent8v3-modal-body').prepend(renderTechnicalSafeBundlePanel(modal, rows));
	            updateTechnicalSafeBundleSelectionSummary();
	        }
        if (String(modal.modal_key || '') === 'onpage_seo' && String(modal.active_tab || (modal.filters && modal.filters.tab) || '') === 'content') {
            maybeLoadOnPageContentRewriteHistory();
        }
        if (String(modal.modal_key || '') === 'onpage_seo' && String(modal.active_tab || (modal.filters && modal.filters.tab) || '') === 'meta_snippets') {
            restoreOnPageMetadataInlineConfirmation();
        }
        maybeAutoOpenOnPageHistoryReport(modal);
        const page = parseInt(pagination.page, 10) || 1;
        const pages = parseInt(pagination.pages, 10) || 1;
        const total = parseInt(pagination.total, 10) || 0;
        state.modal.page = page;
        const hidePagination = !!modal.hide_pagination || hideMonitoringChrome;
        $('#aysa-agent8v3-modal-page').toggle(!hidePagination).text(hidePagination ? '' : text('modalPage') + ' ' + page + ' / ' + pages + ' · ' + total + ' ' + text('modalRows'));
        $('#aysa-agent8v3-modal-prev, #aysa-agent8v3-modal-next').parent().toggle(!hidePagination);
        $('#aysa-agent8v3-modal-prev').prop('disabled', hidePagination || page <= 1);
        $('#aysa-agent8v3-modal-next').prop('disabled', hidePagination || page >= pages);
	        maybeAutoRefreshOffpageBacklinkStrategy(modal, rows);
	    }

    function renderOnPageExecutionHistoryPanel(modal) {
        modal = modal && typeof modal === 'object' ? modal : {};
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const reports = Array.isArray(modal.onpage_execution_history_list) ? modal.onpage_execution_history_list : [];
        const selector = modal.onpage_execution_snapshot_selector && typeof modal.onpage_execution_snapshot_selector === 'object'
            ? modal.onpage_execution_snapshot_selector
            : {};
        const requestedStatus = String(selector.status || '');
        const notice = requestedStatus === 'snapshot_not_found'
            ? '<div class="aysa-agent8v3-onpage-history-warning">' + escapeHtml(ro
                ? 'Raportul istoric solicitat nu a fost găsit. Nu afișez un alt raport în locul lui.'
                : 'The requested historical report was not found. I will not show another report as a substitute.') + '</div>'
            : '';
        const cards = reports.map(function(report) {
            report = report && typeof report === 'object' ? report : {};
            const identity = String(report.snapshot_identity || '');
            const verdict = String(report.completion_verdict || '');
            const statusLabel = verdict === 'completed_incomplete_evidence'
                ? (ro ? 'Necesită verificare manuală' : 'Manual verification required')
                : (verdict === 'completed_verified'
                    ? (ro ? 'Aplicat și verificat' : 'Applied and verified')
                    : clientFacingLabel(verdict || (ro ? 'Review disponibil' : 'Review available')));
            return '<div class="aysa-agent8v3-onpage-history-row">' +
                '<div class="aysa-agent8v3-onpage-history-copy"><strong>' + escapeHtml(report.label || (ro ? 'Raport istoric' : 'Historical report')) + '</strong>' +
                    '<span>' + escapeHtml((ro ? 'Rânduri: ' : 'Rows: ') + String(report.selected_row_count || report.row_count || 0) + ' · ' + statusLabel) + '</span>' +
                    '<span>' + escapeHtml((ro ? 'Hash selecție: ' : 'Selection hash: ') + String(report.selection_hash || '-')) + '</span>' +
                '</div>' +
                '<button type="button" class="button aysa-agent8v3-onpage-history-open" data-snapshot-identity="' + escapeHtml(identity) + '"' + (identity ? '' : ' disabled') + '>' +
                    escapeHtml(ro ? 'Deschide raport istoric' : 'Open historical report') +
                '</button>' +
            '</div>';
        }).join('');
        return '<section class="aysa-agent8v3-onpage-history-panel" aria-label="' + escapeHtml(ro ? 'Rapoarte istorice' : 'Historical reports') + '">' +
            '<div class="aysa-agent8v3-onpage-history-heading"><strong>' + escapeHtml(ro ? 'Rapoarte istorice' : 'Historical reports') + '</strong><span>' + escapeHtml(ro ? 'Doar citire; nu pornește aplicarea.' : 'Read-only; does not start an apply.') + '</span></div>' +
            notice +
            (cards || '<div class="aysa-agent8v3-onpage-history-empty">' + escapeHtml(ro ? 'Nu există rapoarte istorice persistate pentru acest site.' : 'No persisted historical reports exist for this site.') + '</div>') +
        '</section>';
    }

    function maybeAutoOpenOnPageHistoryReport(modal) {
        if (!modal || String(modal.modal_key || '') !== 'onpage_seo'
            || String(modal.active_tab || (modal.filters && modal.filters.tab) || '') !== 'execution_report'
            || String((modal.onpage_execution_snapshot_selector || {}).status || '') === 'selected'
            || String((modal.onpage_execution_snapshot_selector || {}).status || '') === 'snapshot_not_found') {
            return;
        }
        const request = getOnPageQaHistoryRequest();
        const sourceRunId = request && request.source_run_id ? String(request.source_run_id) : '';
        if (!sourceRunId) {
            return;
        }
        const reports = Array.isArray(modal.onpage_execution_history_list) ? modal.onpage_execution_history_list : [];
        const candidates = reports.filter(function(report) {
            return report && String(report.source_run_id || '') === sourceRunId
                && parseInt(report.selected_row_count || report.row_count || 0, 10) === 13
                && String(report.snapshot_identity || '');
        });
        if (!candidates.length) {
            return;
        }
        const preferred = candidates.find(function(report) {
            return ['completed_incomplete_evidence', 'completed_partial', 'review_available'].indexOf(String(report.completion_verdict || '')) !== -1;
        }) || candidates.find(function(report) {
            return String(report.completion_verdict || '') !== 'failed';
        }) || null;
        if (!preferred) {
            return;
        }
        const identity = String(preferred.snapshot_identity || '');
        const button = $('.aysa-agent8v3-onpage-history-open').filter(function() {
            return String($(this).attr('data-snapshot-identity') || '') === identity;
        }).first();
        if (!button.length) {
            return;
        }
        // Select only an identity rendered by the existing history projection.
        // This remains read-only and reuses the normal history-open handler.
        window.setTimeout(function() {
            if (state.modal.key === 'onpage_seo' && state.modal.current === modal) {
                button.trigger('click');
            }
        }, 0);
    }

	    function renderTechnicalSafeBundlePanel(modal, rows) {
	        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
	        const list = Array.isArray(rows) ? rows : [];
	        const bundle = modal && modal.technical_seo_decision_model && typeof modal.technical_seo_decision_model === 'object'
	            ? modal.technical_seo_decision_model
	            : (modal && modal.technical_seo_safe_bundle && typeof modal.technical_seo_safe_bundle === 'object' ? modal.technical_seo_safe_bundle : {});
	        const bundleId = String(bundle.bundle_id || '');
	        if (String(state.technicalSafeBundleUiBundleId || '') !== bundleId) {
	            state.technicalSafeBundleUiBundleId = bundleId;
	            state.technicalSafeBundleUiExclusions = { rows: {}, modules: {} };
	        }
	        const modules = {};
	        const sectionLabels = {
	            safe_auto_apply: ro ? 'Pot fi aplicate în siguranță' : 'Safe to apply',
	            review_exclude: ro ? 'Necesită verificarea ta' : 'Needs your review',
	            blocked_unsafe: ro ? 'Blocate pentru siguranță' : 'Blocked for safety',
	            unavailable: ro ? 'Momentan indisponibile' : 'Currently unavailable',
            report_only: ro ? 'Doar raport' : 'Report only'
	        };
		        const sectionCounts = {
		            safe_auto_apply: Array.isArray(bundle.safe_rows) ? bundle.safe_rows.length : 0,
		            review_exclude: Array.isArray(bundle.review_rows) ? bundle.review_rows.length : 0,
		            blocked_unsafe: Array.isArray(bundle.blocked_rows) ? bundle.blocked_rows.length : 0,
		            unavailable: Array.isArray(bundle.unavailable_rows) ? bundle.unavailable_rows.length : 0,
		            report_only: Array.isArray(bundle.report_only_rows) ? bundle.report_only_rows.length : 0
		        };
		        const hasBundleSectionCounts = Object.keys(sectionCounts).some(function(key) { return sectionCounts[key] > 0; });
		        list.forEach(function(row) {
		            const classification = String(row.classification || 'unavailable');
		            if (!hasBundleSectionCounts && Object.prototype.hasOwnProperty.call(sectionCounts, classification)) {
	                sectionCounts[classification] += 1;
	            }
	            const selection = row && row.selection && typeof row.selection === 'object' ? row.selection : {};
	            const moduleKey = String(selection.module || row.module || '');
	            if (!moduleKey || !selection.exclusion_allowed) {
	                return;
	            }
	            if (!modules[moduleKey]) {
	                modules[moduleKey] = {
	                    key: moduleKey,
	                    label: String(row.module_label || moduleKey),
	                    count: 0
	                };
	            }
	            modules[moduleKey].count += 1;
	        });
	        (Array.isArray(bundle.modules) ? bundle.modules : []).forEach(function(moduleSummary) {
	            const moduleKey = String(moduleSummary && moduleSummary.module || '');
	            const safeCount = parseInt(moduleSummary && moduleSummary.safe_count || 0, 10) || 0;
	            if (!moduleKey || safeCount <= 0) {
	                return;
	            }
	            modules[moduleKey] = {
	                key: moduleKey,
	                label: String(moduleSummary.label || moduleKey),
	                count: safeCount
	            };
	        });
	        const moduleHtml = Object.keys(modules).sort().map(function(key) {
	            const item = modules[key];
	            const excludedModules = technicalSafeBundleUiExclusions().modules;
	            return '<label class="aysa-agent8v3-safe-bundle-module-pill">' +
	                '<input type="checkbox" class="aysa-agent8v3-safe-bundle-module" data-module="' + escapeHtml(item.key) + '"' + (excludedModules[item.key] ? '' : ' checked') + '> ' +
	                '<span>' + escapeHtml(item.label) + '</span>' +
	                '<b>' + escapeHtml(String(item.count)) + '</b>' +
	                '</label>';
	        }).join('');
	        const sectionHtml = Object.keys(sectionLabels).map(function(key) {
	            return '<span class="aysa-agent8v3-safe-bundle-section-pill is-' + escapeHtml(key) + '">' +
	                '<strong>' + escapeHtml(sectionLabels[key]) + '</strong>' +
	                '<b>' + escapeHtml(String(sectionCounts[key] || 0)) + '</b>' +
	                '</span>';
	        }).join('');
	        const total = parseInt(bundle.bundle_total_max_cost || bundle.total_max_cost || 0, 10) || 0;
	        const execution = bundle.bundle_execution && typeof bundle.bundle_execution === 'object' ? bundle.bundle_execution : {};
	        const executionTotals = execution.totals && typeof execution.totals === 'object' ? execution.totals : {};
	        const executionModules = Array.isArray(execution.modules) ? execution.modules : [];
	        const rollbackLabel = technicalSafeBundleRollbackLabel(executionModules, executionTotals);
	        const executionModuleHtml = executionModules.filter(function(item) {
	            return item && typeof item === 'object' && String(item.status || '') !== 'not_started' && String(item.status || '') !== 'not_eligible';
	        }).map(function(item) {
	            const moduleLabel = String(item.module || 'module').replace(/_/g, ' ');
	            const reason = technicalSafeBundleExecutionReasonLabel(item);
	            const statusLabel = parseInt(item.verified_count || 0, 10) > 0
	                ? (ro ? 'aplicat și verificat' : 'applied and verified')
	                : technicalFixExecutionStatusLabel(item.status || 'submitted');
	            return '<span>' + escapeHtml(moduleLabel) + ': <b>' + escapeHtml(statusLabel) + '</b>' +
	                (reason ? ' · ' + escapeHtml(reason) : '') + '</span>';
	        }).join('');
	        const executionHtml = execution.status && execution.status !== 'not_started'
	            ? '<div class="aysa-agent8v3-safe-bundle-execution">' +
	                '<span>' + escapeHtml(ro ? 'Aplicate' : 'Applied') + ': <b>' + escapeHtml(String(executionTotals.applied || 0)) + '</b></span>' +
	                '<span>' + escapeHtml(ro ? 'Verificate' : 'Verified') + ': <b>' + escapeHtml(String(executionTotals.verified || 0)) + '</b></span>' +
	                '<span>' + escapeHtml(ro ? 'Omise' : 'Skipped') + ': <b>' + escapeHtml(String(executionTotals.skipped || 0)) + '</b></span>' +
	                '<span>' + escapeHtml(ro ? 'Necesită verificare' : 'Needs review') + ': <b>' + escapeHtml(String(executionTotals.manual_review || 0)) + '</b></span>' +
	                '<span>' + escapeHtml(ro ? 'Blocate' : 'Blocked') + ': <b>' + escapeHtml(String(executionTotals.blocked || 0)) + '</b></span>' +
	                '<span>' + escapeHtml(ro ? 'Credite consumate' : 'Credits used') + ': <b>' + escapeHtml(String(executionTotals.billed || 0)) + '</b></span>' +
	                (parseInt(executionTotals.corrections || 0, 10) > 0 ? '<span>' + escapeHtml(ro ? 'Corecții / refunduri' : 'Corrections / refunds') + ': <b>' + escapeHtml(String(executionTotals.corrections || 0)) + '</b></span>' : '') +
	                '<span>' + escapeHtml(ro ? 'Revenire' : 'Rollback') + ': <b>' + escapeHtml(rollbackLabel) + '</b></span>' +
	                executionModuleHtml +
	            '</div>'
	            : '';
	        const executionRowsHtml = renderTechnicalSafeBundleExecutionRows(executionModules);
	        const forecastHtml = renderTechnicalSafeBundleForecast(bundle.execution_forecast, ro);
	        const subsectionRoutes = {
	            site_audit: { key: 'technical_site_audit', tab: 'site_audit' },
	            pagespeed: { key: 'technical_pagespeed', tab: '' },
	            schema: { key: 'technical_site_audit', tab: 'schema_preview' },
	            redirects: { key: 'technical_redirects', tab: '' },
	            sitemap_robots: { key: 'technical_sitemap_robots', tab: '' },
	            internal_linking: { key: 'technical_internal_linking', tab: 'link_plan' },
	            image_alt: { key: 'technical_image_alt', tab: '' },
	            image_optimization: { key: 'technical_site_audit', tab: 'image_optimization_preview' }
	        };
	        const traversalHtml = (Array.isArray(bundle.subsection_traversal) ? bundle.subsection_traversal : []).map(function(section) {
		            const status = String(section && section.status || 'unavailable');
		            const included = !!(section && section.included_in_main_execution_bundle);
		            const moduleKey = String(section && section.module || '');
		            const route = subsectionRoutes[moduleKey] || null;
		            const tag = route ? 'button' : 'div';
		            const routeAttrs = route
		                ? ' type="button" class="aysa-agent8v3-safe-bundle-subsection aysa-agent8v3-workspace-open is-' + escapeHtml(status) + '" data-modal-key="' + escapeHtml(route.key) + '"' + (route.tab ? ' data-modal-tab="' + escapeHtml(route.tab) + '"' : '')
		                : ' class="aysa-agent8v3-safe-bundle-subsection is-' + escapeHtml(status) + '"';
		            return '<' + tag + routeAttrs + '>' +
		                '<strong>' + escapeHtml(String(section && section.label || section && section.module || 'Technical SEO')) + '</strong>' +
		                '<span>' + escapeHtml(status.replace(/_/g, ' ')) + '</span>' +
		                '<small>' + escapeHtml((ro ? 'Sigure ' : 'Safe ') + String(section && section.safe_rows || 0) + ' · ' + (ro ? 'review ' : 'review ') + String(section && section.review_rows || 0) + ' · ' + (ro ? 'blocate ' : 'blocked ') + String(section && section.blocked_rows || 0)) + '</small>' +
		                '<em>' + escapeHtml(included ? (ro ? 'Inclus în aplicarea finală · Deschide review' : 'Included in final apply · Open review') : (ro ? 'Nu se aplică automat · Deschide review' : 'Not auto-applied · Open review')) + '</em>' +
		            '</' + tag + '>';
		        }).join('');
	        const executeButton = bundle.execution_enabled
	            ? '<button type="button" class="button button-primary aysa-agent8v3-safe-bundle-execute">' + escapeHtml(ro ? 'Aplică optimizările acceptate' : 'Apply accepted optimizations') + '</button>'
	            : '';
	        const canonical = state.canonical && typeof state.canonical === 'object' ? state.canonical : {};
	        const canonicalData = canonical.data && typeof canonical.data === 'object' ? canonical.data : {};
	        const canonicalTechnical = canonicalData.technical_seo && typeof canonicalData.technical_seo === 'object' ? canonicalData.technical_seo : {};
	        const canonicalReview = canonicalTechnical.review && typeof canonicalTechnical.review === 'object' ? canonicalTechnical.review : {};
	        const canonicalRunId = parseInt(canonicalTechnical.run_id || 0, 10) || 0;
	        const canonicalReviewRunId = parseInt(canonicalReview.run_id || canonicalReview.technical_run_id || 0, 10) || 0;
	        const reviewCompletedForCurrentRun = String(canonicalReview.status || '') === 'completed' && canonicalRunId > 0 && canonicalReviewRunId === canonicalRunId;
	        const reviewAlreadyCompleted = String(canonicalReview.status || '') === 'completed' && (reviewCompletedForCurrentRun || canonicalRunId <= 0);
	        const showReviewCompletion = !reviewAlreadyCompleted;
	        const reviewCompletionPayload = showReviewCompletion ? technicalReviewCompletionPayloadFromCanonical() : {};
	        const reviewCompletionButton = showReviewCompletion
	            ? '<button type="button" class="button button-primary aysa-agent8v3-modal-action" data-action="complete_technical_seo_review" data-payload="' + escapeHtml(JSON.stringify(reviewCompletionPayload)) + '">' + escapeHtml(ro ? 'Finalizează review-ul Technical SEO' : 'Complete Technical SEO review') + '</button>'
	            : '';
	        const reviewCompletionBadges = showReviewCompletion ? actionBadgesHtml([
	            ro ? 'Nu rulează auditul din nou' : 'Does not rerun the audit',
	            ro ? 'Nu aplică modificări' : 'Does not apply changes',
	            ro ? 'Păstrează etapa curentă' : 'Keeps the current phase'
	        ]) : '';
	        const executeBadges = bundle.execution_enabled
	            ? actionBadgesHtml([
	                ro ? 'Necesită confirmare înainte de aplicare' : 'Requires confirmation before apply',
	                ro ? 'Aplică modificări pe site' : 'Applies site changes',
	                ro ? 'Cost maxim afișat înainte' : 'Maximum cost shown first'
	            ])
	            : '';
	        const executionGuardHtml = bundle.execution_enabled
	            ? '<div class="aysa-agent8v3-safe-bundle-apply-guard">' +
	                '<strong>' + escapeHtml(ro ? 'Aplicarea este un pas separat' : 'Applying is a separate step') + '</strong>' +
	                '<p>' + escapeHtml(ro ? 'Review-ul de mai sus este doar selecția. Înainte de orice scriere vezi costul maxim, câte rânduri ai ales și faptul că se folosesc doar contractele Technical SEO existente, cu verificare și revenire unde sunt disponibile.' : 'The review above is only the selection. Before any write you see the maximum cost, selected row count, and that only existing Technical SEO contracts are used, with verification and rollback where available.') + '</p>' +
	            '</div>'
	            : '';
	        const decisionNote = String(bundle.decision_mode || '') === 'read_only_phase_1_2'
	            ? '<div class="aysa-agent8v3-safe-bundle-note">' + escapeHtml(String(bundle.execution_disabled_reason || (ro ? 'Acest ecran este decizia Technical SEO. Aplicarea rămâne separată.' : 'This screen is the Technical SEO decision. Applying remains separate.'))) + '</div>'
	            : '';
	        return '<section class="aysa-agent8v3-safe-bundle-panel">' +
	            '<div class="aysa-agent8v3-safe-bundle-head">' +
	                '<div>' +
                    '<strong>' + escapeHtml(ro ? 'Review-ul Technical SEO' : 'Technical SEO review') + '</strong>' +
                    '<p>' + escapeHtml(ro ? 'AYSA selectează implicit doar optimizările care pot fi verificate. Tu excluzi ce nu este ok. Aplicarea se face separat, doar după confirmare.' : 'AYSA selects only optimizations that can be verified. Exclude what is not ok. Applying remains separate and requires confirmation.') + '</p>' +
	                '</div>' +
	                '<div class="aysa-agent8v3-safe-bundle-totals">' +
	                    '<span><b id="aysa-agent8v3-safe-bundle-selected">0</b> ' + escapeHtml(ro ? 'selectate' : 'selected') + '</span>' +
	                    '<span><b id="aysa-agent8v3-safe-bundle-excluded">0</b> ' + escapeHtml(ro ? 'excluse' : 'excluded') + '</span>' +
	                    '<span><b id="aysa-agent8v3-safe-bundle-cost">' + escapeHtml(String(total)) + '</b> ' + escapeHtml(ro ? 'credite max.' : 'max credits') + '</span>' +
	                '</div>' +
	            '</div>' +
	            '<div class="aysa-agent8v3-safe-bundle-sections" aria-label="' + escapeHtml(ro ? 'Secțiuni pachet' : 'Bundle sections') + '">' + sectionHtml + '</div>' +
	            forecastHtml +
	            (traversalHtml ? '<div class="aysa-agent8v3-safe-bundle-subsections" aria-label="' + escapeHtml(ro ? 'Subsecțiuni Technical SEO' : 'Technical SEO subsections') + '">' + traversalHtml + '</div>' : '') +
	            (moduleHtml ? '<div class="aysa-agent8v3-safe-bundle-modules" aria-label="' + escapeHtml(ro ? 'Exclude module' : 'Exclude modules') + '">' + moduleHtml + '</div>' : '') +
	            executionHtml + executionRowsHtml +
	            executionGuardHtml +
	            '<div class="aysa-agent8v3-safe-bundle-actions is-apply-zone">' + executeButton + executeBadges + reviewCompletionButton + reviewCompletionBadges + '<span id="aysa-agent8v3-safe-bundle-message" class="aysa-agent8v3-safe-bundle-message"></span></div>' +
	            decisionNote +
	            '<div class="aysa-agent8v3-safe-bundle-note">' + escapeHtml(ro ? 'Zonele blocate sau doar informative rămân vizibile, dar nu sunt selectate automat.' : 'Blocked and report-only areas stay visible, but are not selected automatically.') + '</div>' +
	        '</section>';
	    }

	    function renderTechnicalSafeBundleForecast(forecast, ro) {
	        if (!forecast || typeof forecast !== 'object') {
	            return '';
	        }
	        const groups = [
	            { key: 'will_apply', label: ro ? 'Se aplică acum' : 'Will apply now', empty: ro ? 'Nicio optimizare executabilă' : 'No executable optimizations' },
	            { key: 'will_skip', label: ro ? 'Se omit automat' : 'Will be skipped', empty: ro ? 'Nimic de omis' : 'Nothing to skip' },
	            { key: 'requires_review', label: ro ? 'Necesită verificarea ta' : 'Needs your review', empty: ro ? 'Nicio zonă' : 'No areas' },
	            { key: 'report_only', label: ro ? 'Doar raport' : 'Report only', empty: ro ? 'Nicio zonă' : 'No areas' }
	        ];
	        const groupHtml = groups.map(function(group) {
	            let items = Array.isArray(forecast[group.key]) ? forecast[group.key].slice() : [];
	            if (group.key === 'will_skip' && Array.isArray(forecast.blocked)) {
	                items = items.concat(forecast.blocked);
	            }
	            const rows = items.map(function(item) {
	                const count = parseInt(item && item.count || 0, 10) || 0;
	                return '<li><span>' + escapeHtml(String(item && (item.label || item.module) || 'Technical SEO')) + '</span><b>' + escapeHtml(String(count)) + '</b></li>';
	            }).join('');
	            return '<section class="aysa-agent8v3-safe-bundle-forecast-group is-' + escapeHtml(group.key) + '">' +
	                '<strong>' + escapeHtml(group.label) + '</strong>' +
	                (rows ? '<ul>' + rows + '</ul>' : '<small>' + escapeHtml(group.empty) + '</small>') +
	            '</section>';
	        }).join('');
	        return '<div class="aysa-agent8v3-safe-bundle-forecast">' +
	            '<p>' + escapeHtml(String(forecast.headline || (ro ? 'AYSA va aplica automat optimizările sigure disponibile.' : 'AYSA will automatically apply the available safe optimizations.'))) + '</p>' +
	            '<div>' + groupHtml + '</div>' +
	        '</div>';
	    }

	    function technicalSafeBundleExecutionReasonLabel(item) {
	        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
	        const reasons = []
	            .concat(Array.isArray(item && item.gate_reasons) ? item.gate_reasons : [])
	            .concat(item && item.reason ? [item.reason] : [])
	            .map(function(reason) {
	                return String(reason || '');
	            });
	        if (reasons.some(function(reason) { return reason.indexOf('schema_project_gate_disabled') !== -1 || reason.indexOf('schema_site_gate_disabled') !== -1; })) {
	            return ro ? 'Schema este dezactivată pentru rollout' : 'Schema rollout is disabled';
	        }
	        if (reasons.some(function(reason) { return reason.indexOf('selected_schema_rows_required') !== -1; })) {
	            return ro ? 'Nu există candidați Schema selectabili' : 'No selectable Schema candidates';
	        }
	        if (reasons.some(function(reason) { return reason.indexOf('billing') !== -1; })) {
	            return ro ? 'Debitarea nu a fost confirmată de modul' : 'Module billing was not confirmed';
	        }
	        if (String(item && item.status || '') === 'skipped_not_executable' || reasons.some(function(reason) { return reason.indexOf('image_alt_worker_rollout_disabled') !== -1; })) {
	            return ro ? 'Ruta Image Alt nu este activă; fără debit' : 'Image Alt route is disabled; no charge';
	        }
	        if (parseInt(item && item.skipped_count || 0, 10) > 0) {
	            return ro ? 'Omis de siguranțele modulului' : 'Skipped by module safety checks';
	        }
	        return '';
	    }

	    function renderTechnicalSafeBundleExecutionRows(modules) {
	        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
	        const routes = {
	            redirects: { key: 'technical_redirects', tab: '' },
	            internal_linking: { key: 'technical_site_audit', tab: 'internal_linking_history' },
	            image_alt: { key: 'technical_image_alt', tab: '' },
	            image_optimization: { key: 'technical_site_audit', tab: 'image_optimization_preview' },
	            schema: { key: 'technical_site_audit', tab: 'schema_preview' }
	        };
	        const rows = [];
	        (Array.isArray(modules) ? modules : []).forEach(function(moduleExecution) {
	            const moduleKey = String(moduleExecution && moduleExecution.module || '');
	            const route = routes[moduleKey];
	            (Array.isArray(moduleExecution && moduleExecution.item_results) ? moduleExecution.item_results : []).forEach(function(item) {
	                const status = String(item && (item.verification_status || item.status) || '');
	                const historyId = String(item && (item.history_id || item.restore_history_id) || '');
	                const oldValue = String(item && (item.old_value || item.old_alt || item.original_url || item.source_url) || '');
	                const newValue = String(item && (item.new_value || item.proposed_alt || item.derivative_url || item.target_url) || '');
	                const billing = parseInt(item && (item.billing_cost_cents || item.actual_credits_cents || item.billed_amount) || 0, 10) || 0;
	                const rollback = !!(item && (item.rollback_available || item.restore_available || historyId));
	                if (!status && !historyId && !oldValue && !newValue) {
	                    return;
	                }
	                const action = rollback && route
	                    ? '<button type="button" class="button button-small aysa-agent8v3-modal-open" data-modal-key="' + escapeHtml(route.key) + '"' + (route.tab ? ' data-modal-tab="' + escapeHtml(route.tab) + '"' : '') + '>' + escapeHtml(ro ? 'Revert / Istoric' : 'Revert / History') + '</button>'
	                    : '<span class="aysa-agent8v3-muted">' + escapeHtml(ro ? 'Revert indisponibil' : 'Revert unavailable') + '</span>';
	                rows.push('<tr><td>' + escapeHtml(moduleKey.replace(/_/g, ' ')) + '</td><td>' + escapeHtml(status || '-') + '</td><td>' + escapeHtml(historyId || '-') + '</td><td>' + escapeHtml(oldValue || '-') + '</td><td>' + escapeHtml(newValue || '-') + '</td><td>' + escapeHtml(String(billing)) + '</td><td>' + action + '</td></tr>');
	            });
	        });
	        if (!rows.length) {
	            return '';
	        }
	        return '<div class="aysa-agent8v3-modal-table-wrap aysa-agent8v3-safe-bundle-history"><table class="aysa-agent8v3-modal-table"><thead><tr>' +
	            '<th>' + escapeHtml(ro ? 'Modul' : 'Module') + '</th><th>' + escapeHtml(ro ? 'Verificare' : 'Readback') + '</th><th>History ID</th><th>' + escapeHtml(ro ? 'Înainte' : 'Before') + '</th><th>' + escapeHtml(ro ? 'După' : 'After') + '</th><th>' + escapeHtml(ro ? 'Credite' : 'Credits') + '</th><th>Revert</th>' +
	            '</tr></thead><tbody>' + rows.join('') + '</tbody></table></div>';
	    }

	    function technicalSafeBundleRollbackLabel(modules, totals) {
	        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
	        const list = Array.isArray(modules) ? modules : [];
	        const hasRollback = list.some(function(item) {
	            return item && typeof item === 'object' && item.rollback_available;
	        });
	        if (hasRollback) {
	            return ro ? 'disponibil prin fluxul existent' : 'available through existing flow';
	        }
	        const applied = parseInt(totals && (totals.applied || totals.verified) || 0, 10) || 0;
	        if (applied <= 0) {
	            return ro ? 'nu este necesar' : 'not needed';
	        }
	        return ro ? 'indisponibil' : 'unavailable';
	    }

	    function updateTechnicalSafeBundleSelectionSummary() {
	        const modal = state.modal && state.modal.current && typeof state.modal.current === 'object' ? state.modal.current : {};
	        const bundle = modal.technical_seo_safe_bundle && typeof modal.technical_seo_safe_bundle === 'object' ? modal.technical_seo_safe_bundle : {};
	        const safeRows = Array.isArray(bundle.safe_rows) ? bundle.safe_rows : [];
	        const selectedGroups = selectedTechnicalSafeBundleItems();
	        let selected = 0;
	        let cost = 0;
	        Object.keys(selectedGroups).forEach(function(moduleKey) {
	            selected += selectedGroups[moduleKey].length;
	        });
	        safeRows.forEach(function(row) {
	            const selection = row && row.selection && typeof row.selection === 'object' ? row.selection : {};
	            const moduleItems = Array.isArray(selectedGroups[String(row && row.module || '')]) ? selectedGroups[String(row && row.module || '')] : [];
	            const rowId = String(row && row.row_id || selection.row_id || '');
	            if (moduleItems.some(function(item) { return String(item.safe_bundle_row_id || item.row_id || item.item_id || '') === rowId; })) {
	                cost += parseInt(row && row.cost_cents || selection.cost_cents || 0, 10) || 0;
	            }
	        });
	        const excluded = Math.max(0, safeRows.length - selected);
	        $('#aysa-agent8v3-safe-bundle-selected').text(String(selected));
	        $('#aysa-agent8v3-safe-bundle-excluded').text(String(excluded));
	        $('#aysa-agent8v3-safe-bundle-cost').text(String(cost));
	        $('.aysa-agent8v3-safe-bundle-execute')
	            .removeAttr('data-safe-bundle-confirmed')
	            .text(String(uiLanguage() || '').indexOf('ro') === 0 ? 'Aplică optimizările acceptate' : 'Apply accepted optimizations');
	        $('#aysa-agent8v3-safe-bundle-message').text('');
	        $('.aysa-agent8v3-safe-bundle-module').each(function() {
	            const moduleKey = String($(this).attr('data-module') || '');
	            const moduleRows = $('.aysa-agent8v3-safe-bundle-row').filter(function() {
	                return String($(this).attr('data-module') || '') === moduleKey;
	            });
	            const checkedRows = moduleRows.filter(':checked');
	            if (moduleRows.length > 0) {
	                $(this).prop('checked', checkedRows.length === moduleRows.length);
	            }
	        });
	    }

	    function technicalSafeBundleUiExclusions() {
	        if (!state.technicalSafeBundleUiExclusions || typeof state.technicalSafeBundleUiExclusions !== 'object') {
	            state.technicalSafeBundleUiExclusions = { rows: {}, modules: {} };
	        }
	        state.technicalSafeBundleUiExclusions.rows = state.technicalSafeBundleUiExclusions.rows || {};
	        state.technicalSafeBundleUiExclusions.modules = state.technicalSafeBundleUiExclusions.modules || {};
	        return state.technicalSafeBundleUiExclusions;
	    }

	    function selectedTechnicalSafeBundleItems() {
	        const grouped = {};
	        const modal = state.modal && state.modal.current && typeof state.modal.current === 'object' ? state.modal.current : {};
	        const bundle = modal.technical_seo_safe_bundle && typeof modal.technical_seo_safe_bundle === 'object' ? modal.technical_seo_safe_bundle : {};
	        const safeRows = Array.isArray(bundle.safe_rows) ? bundle.safe_rows : [];
	        const exclusions = technicalSafeBundleUiExclusions();
	        const excludedRows = $.extend({}, exclusions.rows);
	        const excludedModules = $.extend({}, exclusions.modules);
	        $('.aysa-agent8v3-safe-bundle-row').each(function() {
	            if (!$(this).prop('checked')) {
	                excludedRows[String($(this).attr('data-row-id') || '')] = true;
	            }
	        });
	        $('.aysa-agent8v3-safe-bundle-module').each(function() {
	            if (!$(this).prop('checked')) {
	                excludedModules[String($(this).attr('data-module') || '')] = true;
	            }
	        });
	        safeRows.forEach(function(row) {
	            const moduleKey = String(row && row.module || '');
	            const payload = row && row.selection && typeof row.selection === 'object' ? row.selection : {};
	            const rowId = String(row && row.row_id || payload.row_id || '');
	            if (!moduleKey) {
	                return;
	            }
	            if (!payload.executable_in_bundle || payload.rejected_by_user || excludedRows[rowId] || excludedModules[moduleKey]) {
	                return;
	            }
	            const item = payload.item && typeof payload.item === 'object' ? $.extend(true, {}, payload.item) : {};
	            if (!Object.keys(item).length) {
	                return;
	            }
	            item.safe_bundle_row_id = rowId;
	            if (moduleKey === 'image_optimization' && isImageOptimizationRejected(item)) {
	                return;
	            }
	            item.accepted_by_user = true;
	            if (moduleKey === 'image_optimization') {
	                item.backup_required = true;
	                item.rollback_required = true;
	                item.readback_required = true;
	            }
	            if (!grouped[moduleKey]) {
	                grouped[moduleKey] = [];
	            }
	            grouped[moduleKey].push(item);
	        });
	        return grouped;
	    }

	    function technicalSafeBundleModulePayload(moduleKey, items, bundle) {
	        const payloads = bundle && bundle.execution_payloads && typeof bundle.execution_payloads === 'object' ? bundle.execution_payloads : {};
	        const base = payloads[moduleKey] && typeof payloads[moduleKey] === 'object' ? $.extend(true, {}, payloads[moduleKey]) : { module: moduleKey };
	        const parsedUnitCost = parseInt(base.billing_unit_cents, 10);
	        const unitCost = moduleKey === 'redirects'
	            ? 0
	            : Math.max(1, Number.isFinite(parsedUnitCost) ? parsedUnitCost : 5);
	        const selected = Array.isArray(items) ? items : [];
	        base.module = moduleKey;
	        base.selected_items = selected;
	        base.accepted_fixes = selected;
	        base.accepted_count = selected.length;
	        base.accepted_fix_count = selected.length;
	        base.max_cost_cents = selected.length * unitCost;
	        base.user_confirmed = true;
	        base.confirmed_by_user = true;
	        base.bundle_confirmation_kind = 'technical_seo_apply_accepted_bundle';
	        base.technical_safe_bundle_id = String(bundle.bundle_id || '');
	        base.technical_safe_bundle_hash = String(bundle.bundle_hash || '');
	        base.selection_model = 'accept_all_safe_unless_rejected';
	        base.capability_activation_requested = true;
	        base.temporary_product_gates = true;
	        base.final_confirmation_text = String(bundle.final_confirmation_text || '');
	        const scopeSeed = [
	            String(cfg.project_id || cfg.wp_project_id || '0'),
	            String(cfg.website_id || '0'),
	            String(cfg.site_host || window.location.hostname || '').toLowerCase()
	        ].join('|');
	        const bundleSeed = selected.map(function(item) {
	            return technicalSafeBundleStableItemIdentity(moduleKey, item);
	        }).sort().join('|');
	        const bundleBatchId = 'technical_bundle_' + simpleStableHash([
	            scopeSeed,
	            moduleKey,
	            bundleSeed,
	            String(bundle.final_confirmation_text || '')
	        ].join('|'));
	        base.bundle_batch_id = bundleBatchId;
	        base.bundle_batch_idempotency_key = 'agent8v3:technical_seo_apply_accepted_bundle:' + bundleBatchId;
	        if (moduleKey === 'image_alt' || moduleKey === 'schema') {
	            const capabilityContractRevision = moduleKey === 'image_alt'
	                ? 'technical_image_alt_controlled_beta_v2'
	                : '';
	            const moduleBatchId = moduleKey + '_batch_' + simpleStableHash([
	                scopeSeed,
	                moduleKey,
	                bundleSeed,
	                capabilityContractRevision
	            ].join('|'));
	            base.capability_contract_revision = capabilityContractRevision;
	            base.action_contract = moduleKey === 'image_alt'
	                ? 'technical_seo_image_alt_apply_accepted'
	                : 'technical_seo_schema_apply_accepted';
	            base.batch_id = moduleBatchId;
	            base.batch_idempotency_key = 'agent8v3:technical_seo_' + moduleKey + '_apply_accepted:' + moduleBatchId;
	            base.idempotency_key = base.batch_idempotency_key;
	            base.dry_run = false;
	            base.writes_enabled = true;
	            base.apply_allowed = true;
	        }
	        if (moduleKey === 'image_optimization') {
	            const batchSeed = selected.map(function(item) {
	                return imageOptimizationRowKey(item);
	            }).sort().join('|');
	            const batchId = 'webp_batch_' + simpleStableHash([
	                scopeSeed,
	                batchSeed
	            ].join('|'));
	            const counts = imageOptimizationBatchCountsFromSafeBundle(moduleKey);
	            base.action_contract = 'technical_seo_image_optimization_apply_accepted';
	            base.batch_id = batchId;
	            base.batch_idempotency_key = 'agent8v3:technical_seo_image_optimization_apply_accepted:' + batchId;
	            base.idempotency_key = base.batch_idempotency_key;
	            base.dry_run = false;
	            base.writes_enabled = true;
	            base.apply_allowed = true;
	            base.accepted_count = selected.length;
	            base.accepted_fix_count = selected.length;
	            base.rejected_count = counts.rejected;
	            base.blocked_count = counts.blocked;
	            base.final_confirmation_text = String(uiLanguage() || '').indexOf('ro') === 0 ? 'Aplică WebP acceptate' : 'Apply accepted WebP';
	            base.selected_attachment_ids = selected.map(function(item) {
	                return parseInt(item.attachment_id || item.media_id || 0, 10) || 0;
	            }).filter(function(id) {
	                return id > 0;
	            });
	        }
	        if (moduleKey === 'redirects') {
	            const batchSeed = selected.map(function(item) {
	                return [
	                    String(item.source_url || item.url || ''),
	                    String(item.target_url || item.proposed_target_url || ''),
	                    String(item.row_id || item.item_id || '')
	                ].join('>');
	            }).sort().join('|');
	            const batchId = 'redirects_batch_' + simpleStableHash([
	                scopeSeed,
	                batchSeed
	            ].join('|'));
	            base.action_contract = 'technical_seo_redirects_apply_accepted';
	            base.accepted_fixes = selected;
	            base.selected_rows = selected;
	            base.batch_id = batchId;
	            base.batch_idempotency_key = 'agent8v3:technical_seo_redirects_apply_accepted:' + batchId;
	            base.idempotency_key = base.batch_idempotency_key;
	            base.dry_run = false;
	            base.writes_enabled = true;
	            base.apply_allowed = true;
	            base.billing_status = String(base.billing_status || 'disabled_for_rollout');
	            base.billing_action_key = 'agent8v3_redirect_apply';
	            base.billing_policy = String(base.billing_policy || 'existing_redirect_apply_billing_disabled_for_rollout');
	            base.billing_unit_cents = 0;
	            base.max_cost_cents = 0;
	            base.final_confirmation_text = String(uiLanguage() || '').indexOf('ro') === 0 ? 'Aplică redirecturile acceptate' : 'Apply accepted redirects';
	        }
	        if (moduleKey === 'internal_linking') {
	            const batchId = 'il_batch_' + simpleStableHash([
	                scopeSeed,
	                bundleSeed
	            ].join('|'));
	            base.action_contract = 'technical_seo_internal_linking_apply_accepted';
	            base.batch_id = batchId;
	            base.batch_idempotency_key = 'agent8v3:technical_seo_internal_linking_apply_accepted:' + batchId;
	            base.idempotency_key = base.batch_idempotency_key;
	            base.dry_run = false;
	            base.writes_enabled = true;
	            base.apply_allowed = true;
	        }
	        return base;
	    }

	    function technicalSafeBundleStableItemIdentity(moduleKey, item) {
	        const value = item && typeof item === 'object' ? item : {};
	        return [
	            String(moduleKey || ''),
	            String(value.row_id || value.item_id || value.candidate_id || value.fix_id || ''),
	            String(value.attachment_id || value.media_id || value.source_post_id || value.post_id || ''),
	            String(value.source_url || value.source_page_url || value.page_url || value.url || ''),
	            String(value.target_url || value.proposed_target_url || ''),
	            String(value.schema_type || value.recommended_schema_type || value.field || ''),
	            String(value.proposed_value || value.proposed_alt || value.proposed_schema_hash || value.after_content_hash || value.derivative_url || ''),
	            String(value.before_content_hash || value.old_value_hash || value.old_value || value.old_alt || value.original_url || ''),
	            String(value.approval_token || value.confirmation_token || '')
	        ].join('|');
	    }

	    function technicalSafeBundleModuleCounts(moduleKey) {
	        const counts = { accepted: 0, rejected: 0, blocked: 0, review: 0 };
	        const modal = state.modal && state.modal.current && typeof state.modal.current === 'object' ? state.modal.current : {};
	        const bundle = modal.technical_seo_safe_bundle && typeof modal.technical_seo_safe_bundle === 'object' ? modal.technical_seo_safe_bundle : {};
	        const groups = [
	            { key: 'safe_rows', target: 'accepted' },
	            { key: 'review_rows', target: 'review' },
	            { key: 'blocked_rows', target: 'blocked' },
	            { key: 'unavailable_rows', target: 'blocked' }
	        ];
	        groups.forEach(function(group) {
	            const rows = Array.isArray(bundle[group.key]) ? bundle[group.key] : [];
	            rows.forEach(function(row) {
	                if (String(row && row.module || '') !== String(moduleKey || '')) {
	                    return;
	                }
	                const selection = row && row.selection && typeof row.selection === 'object' ? row.selection : {};
	                if (group.target === 'accepted' && selection.rejected_by_user) {
	                    counts.rejected += 1;
	                } else {
	                    counts[group.target] += 1;
	                }
	            });
	        });
	        const selected = selectedTechnicalSafeBundleItems();
	        counts.accepted = Array.isArray(selected[moduleKey]) ? selected[moduleKey].length : 0;
	        return counts;
	    }

	    function technicalSafeBundleExecutableModule(bundle, moduleKey) {
	        const modules = Array.isArray(bundle && bundle.executable_modules) ? bundle.executable_modules : [];
	        for (let i = 0; i < modules.length; i += 1) {
	            const item = modules[i] && typeof modules[i] === 'object' ? modules[i] : {};
	            if (String(item.module || '') === String(moduleKey || '')) {
	                return item;
	            }
	        }
	        return null;
	    }

	    function selectedTechnicalSafeBundleModuleCost(moduleKey) {
	        let cost = 0;
	        $('.aysa-agent8v3-safe-bundle-row:checked').filter(function() {
	            return String($(this).attr('data-module') || '') === String(moduleKey || '');
	        }).each(function() {
	            cost += parseInt($(this).attr('data-cost') || '0', 10) || 0;
	        });
	        return cost;
	    }

	    function technicalSafeBundleProjectedModuleCost(bundle, moduleKey) {
	        return (Array.isArray(bundle && bundle.safe_rows) ? bundle.safe_rows : []).reduce(function(total, row) {
	            if (String(row && row.module || '') !== String(moduleKey || '')) {
	                return total;
	            }
	            const selection = row && row.selection && typeof row.selection === 'object' ? row.selection : {};
	            if (selection.rejected_by_user) {
	                return total;
	            }
	            return total + (parseInt(row && (row.cost_cents || selection.cost_cents) || 0, 10) || 0);
	        }, 0);
	    }

	    function technicalSafeBundleConfirmationText(plans, totalCost) {
	        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
	        const lines = [];
	        const count = plans.reduce(function(sum, plan) {
	            return sum + (parseInt(plan.payload.accepted_count || 0, 10) || (Array.isArray(plan.payload.selected_items) ? plan.payload.selected_items.length : 0));
	        }, 0);
	        lines.push((ro ? 'Confirmare: ' : 'Confirmation: ') + plans.map(function(plan) {
	            return plan.module;
	        }).join(', '));
	        lines.push((ro ? 'Rânduri selectate: ' : 'Selected rows: ') + String(count));
	        lines.push((ro ? 'Cost maxim: ' : 'Maximum cost: ') + String(totalCost) + (ro ? ' credite' : ' credits'));
	        lines.push(ro
	            ? 'Aceasta este confirmarea de aplicare, nu doar review. Apasă încă o dată numai dacă vrei să scriem fixurile selectate prin contractele Technical SEO existente.'
	            : 'This is the apply confirmation, not just review. Click again only if you want to write the selected fixes through existing Technical SEO contracts.');
	        lines.push(ro
	            ? 'Se folosesc siguranțele existente: cost maxim, verificare după schimbare și revenire unde contractul o permite.'
	            : 'Existing safeguards are used: maximum cost, readback after change, and rollback where the contract supports it.');
	        lines.push(ro
	            ? 'Nu se rulează Sitemap/Robots, Off Page, Monitoring sau alte module neselectate.'
	            : 'Sitemap/Robots, Off Page, Monitoring and other unselected modules are not run.');
	        return lines.join(' ');
	    }

	    function executeTechnicalSafeBundle(button) {
	        const modal = state.modal && state.modal.current && typeof state.modal.current === 'object' ? state.modal.current : {};
	        const bundle = modal.technical_seo_safe_bundle && typeof modal.technical_seo_safe_bundle === 'object' ? modal.technical_seo_safe_bundle : {};
	        const grouped = selectedTechnicalSafeBundleItems();
	        const order = Array.isArray(bundle.execution_order) && bundle.execution_order.length
	            ? bundle.execution_order
	            : ['redirects', 'internal_linking', 'image_alt', 'image_optimization', 'schema'];
	        const plans = [];
	        let totalCost = 0;
	        order.forEach(function(moduleKey) {
	            const items = Array.isArray(grouped[moduleKey]) ? grouped[moduleKey] : [];
	            const executableModule = technicalSafeBundleExecutableModule(bundle, moduleKey);
	            if (!items.length && !(executableModule && executableModule.module_auto_supported)) {
	                return;
	            }
	            const payload = technicalSafeBundleModulePayload(moduleKey, items, bundle);
	            const counts = technicalSafeBundleModuleCounts(moduleKey);
	            payload.rejected_count = counts.rejected;
	            payload.blocked_count = counts.blocked;
	            payload.review_count = counts.review;
	            payload.manual_needed_count = counts.review;
		            if (!items.length && executableModule && executableModule.module_auto_supported) {
		                const moduleCost = technicalSafeBundleProjectedModuleCost(bundle, moduleKey);
		                const moduleRowCount = parseInt(executableModule.row_count || 0, 10) || 1;
		                payload.accepted_count = moduleRowCount;
		                payload.accepted_fix_count = moduleRowCount;
		                payload.max_cost_cents = moduleCost;
		                if (moduleKey === 'schema') {
		                    payload.technical_seo_suite_auto_schema = true;
		                    payload.schema_auto_apply_max_items = moduleRowCount;
		                }
		            }
	            totalCost += parseInt(payload.max_cost_cents || 0, 10) || 0;
	            plans.push({ module: moduleKey, payload: payload });
	        });
	        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
	        if (!plans.length) {
	            window.alert(ro ? 'Nu există fixuri sigure selectate care pot fi trimise prin contractele existente.' : 'No selected safe fixes can be submitted through existing contracts.');
	            return;
	        }
	        const signature = plans.map(function(plan) {
	            return plan.module + ':' + String(plan.payload.max_cost_cents || 0) + ':' + String(plan.payload.accepted_count || 0);
	        }).join('|') + '|cost:' + String(totalCost);
	        if (button.attr('data-safe-bundle-confirmed') !== signature) {
	            button.attr('data-safe-bundle-confirmed', signature);
	            button.text(ro ? 'Confirmă: aplică optimizările acceptate' : 'Confirm: apply accepted optimizations');
	            $('#aysa-agent8v3-safe-bundle-message').text(technicalSafeBundleConfirmationText(plans, totalCost));
	            return;
	        }
	        const confirmationIdentity = simpleStableHash([
	            String(cfg.project_id || cfg.wp_project_id || '0'),
	            String(cfg.website_id || '0'),
	            String(cfg.site_host || window.location.hostname || '').toLowerCase(),
	            String(bundle.final_confirmation_text || '')
	        ].join('|'));
	        const bundleExecutionId = 'technical_bundle_execution_' + simpleStableHash(plans.map(function(plan) {
	            return String(plan.module || '') + ':' + String(plan.payload.idempotency_key || plan.payload.batch_idempotency_key || '');
	        }).sort().join('|') + '|' + confirmationIdentity);
	        plans.forEach(function(plan, planIndex) {
	            plan.payload.bundle_execution_id = bundleExecutionId;
	            plan.payload.bundle_module_index = planIndex + 1;
	            plan.payload.bundle_module_count = plans.length;
	            plan.payload.bundle_confirmation_identity = confirmationIdentity;
	        });
	        button.prop('disabled', true);
	        $('#aysa-agent8v3-safe-bundle-message').text(ro ? 'Trimit pachetul sigur...' : 'Submitting safe bundle...');
	        runTechnicalSafeBundlePlan(plans, 0, button, false, {
	            key: String(state.modal.key || 'technical_site_audit'),
	            page: state.modal.page || 1,
	            filters: $.extend(true, {}, state.modal.filters || { tab: 'safe_bundle' })
	        });
	    }

	    function restoreTechnicalSafeBundleModalContext(modalContext) {
	        const context = modalContext && typeof modalContext === 'object' ? modalContext : {};
	        state.modal.key = String(context.key || 'technical_site_audit');
	        state.modal.page = parseInt(context.page || 1, 10) || 1;
	        state.modal.filters = $.extend(true, { tab: 'safe_bundle' }, context.filters || {});
	    }

	    function prepareTechnicalSafeBundleModuleGates(plan, button, onReady) {
	        if (!plan || plan.gates_ready) {
	            onReady(plan);
	            return;
	        }
	        const endpoints = {
	            redirects: 'aysa_agent8v3_redirect_product_gates_set',
	            internal_linking: 'aysa_agent8v3_internal_linking_product_gates_set',
	            image_alt: 'aysa_agent8v3_image_alt_product_gates_set',
	            image_optimization: 'aysa_agent8v3_image_optimization_product_gates_set',
	            schema: 'aysa_agent8v3_schema_product_gates_set'
	        };
	        const endpoint = endpoints[String(plan.module || '')] || '';
	        if (!endpoint) {
	            plan.gates_ready = true;
	            onReady(plan);
	            return;
	        }
	        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
	        $('#aysa-agent8v3-safe-bundle-message').text((ro ? 'Activez temporar siguranțele pentru: ' : 'Temporarily enabling safeguards for: ') + plan.module);
	        rawAjax(endpoint, {
	            project_gate_enabled: '1',
	            site_gate_enabled: '1',
	            temporary_ttl_seconds: '1800'
	        }).done(function(response) {
	            if (!response || !response.success) {
	                renderModalError(apiErrorMessage(response, ro ? 'Nu am putut activa siguranțele modulului.' : 'Could not enable module safeguards.'));
	                button.prop('disabled', false);
	                return;
	            }
	            plan.payload.product_gates = response.data && response.data.product_gates ? response.data.product_gates : {
	                project_gate_enabled: true,
	                api_project_gate_enabled: true,
	                site_gate_enabled: true,
	                plugin_site_gate_enabled: true,
	                global_kill_switch_active: false
	            };
	            plan.payload.writes_enabled = true;
	            plan.payload.apply_allowed = true;
	            plan.gates_ready = true;
	            onReady(plan);
	        }).fail(function(xhr) {
	            renderModalError(apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, ro ? 'Activarea siguranțelor modulului a eșuat.' : 'Module safeguard activation failed.'));
	            button.prop('disabled', false);
	        });
	    }

	    function runTechnicalSafeBundlePlan(plans, index, button, retriedAfterStale, modalContext) {
	        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
	        if (index >= plans.length) {
	            $('#aysa-agent8v3-safe-bundle-message').text(ro ? 'Pachet trimis. Verific statusurile modulelor...' : 'Bundle submitted. Checking module statuses...');
	            button.prop('disabled', false);
	            restoreTechnicalSafeBundleModalContext(modalContext);
	            loadModal();
	            return;
	        }
	        const plan = plans[index];
	        if (!plan.gates_ready) {
	            prepareTechnicalSafeBundleModuleGates(plan, button, function(readyPlan) {
	                plans[index] = readyPlan;
	                runTechnicalSafeBundlePlan(plans, index, button, retriedAfterStale, modalContext);
	            });
	            return;
	        }
	        $('#aysa-agent8v3-safe-bundle-message').text((ro ? 'Trimit: ' : 'Submitting: ') + plan.module);
	        rawAjax('aysa_agent8v3_action', {
	            agent_action: 'execute_technical_fix_plan',
	            state_version: currentVersion(),
	            payload: JSON.stringify(plan.payload)
	        }).done(function(response) {
	            if (response && response.success) {
	                renderPayload(response, { silent: true });
	                restoreTechnicalSafeBundleModalContext(modalContext);
	                startTechnicalFixExecutionPolling(String(plan.module || ''));
	                runTechnicalSafeBundlePlan(plans, index + 1, button, false, modalContext);
	            } else if (isStaleStateResponse(response) && !retriedAfterStale) {
	                rawAjax('aysa_agent8v3_state', {}).done(function(stateResponse) {
	                    if (stateResponse && stateResponse.success) {
	                        renderPayload(stateResponse, { silent: true });
	                        restoreTechnicalSafeBundleModalContext(modalContext);
	                        runTechnicalSafeBundlePlan(plans, index, button, true, modalContext);
	                    } else {
	                        renderModalError('stale_state_version');
	                        button.prop('disabled', false);
	                    }
	                }).fail(function() {
	                    renderModalError('stale_state_version');
	                    button.prop('disabled', false);
	                });
	            } else {
	                renderModalError(apiErrorMessage(response, ro ? 'Execuția pachetului a fost oprită.' : 'Safe bundle execution stopped.'));
	                button.prop('disabled', false);
	            }
	        }).fail(function(xhr) {
	            renderModalError(apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Request failed: HTTP ' + xhr.status));
	            button.prop('disabled', false);
	        });
	    }

    function imageAltNormalApplyActionFromModal(modal) {
        const actions = Array.isArray(modal && modal.actions) ? modal.actions : [];
        for (let i = 0; i < actions.length; i += 1) {
            const action = actions[i] || {};
            const payload = action.payload && typeof action.payload === 'object' ? action.payload : {};
            if (String(action.action || '') === 'execute_technical_fix_plan' && String(payload.module || '') === 'image_alt') {
                return action;
            }
        }
        return null;
    }

    function renderImageAltTestModePanel(modal) {
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const model = state.imageAltTestMode || {};
        const result = model.result && typeof model.result === 'object' ? model.result : null;
        const testMode = model.testMode && typeof model.testMode === 'object' ? model.testMode : {};
        const normalAction = imageAltNormalApplyActionFromModal(modal || state.modal.current || {});
        const normalPayload = normalAction && normalAction.payload && typeof normalAction.payload === 'object' ? normalAction.payload : {};
        const normalSummary = normalAction && normalAction.summary && typeof normalAction.summary === 'object' ? normalAction.summary : {};
        const billingUnit = parseInt(normalPayload.billing_unit_cents || testMode.billing_unit_cents || 5, 10) || 5;
        const siteHost = String(cfg.site_host || window.location.hostname || '');
        const selectedCount = Math.max(0, parseInt(normalPayload.confirmation_count || normalSummary.accepted || normalSummary.queued || 0, 10) || 0);
        const maxCost = Math.max(0, parseInt(normalPayload.max_cost_cents || 0, 10) || (selectedCount * billingUnit));
        const historyHtml = renderImageAltTestHistory(model.history);
        const resultHtml = result ? renderImageAltTestResult(result) : '';
        const message = model.message ? '<div class="aysa-agent8v3-image-alt-test-message">' + escapeHtml(model.message) + '</div>' : '';
        return '<section class="aysa-agent8v3-image-alt-test-panel" aria-label="Image Alt apply readiness">' +
            '<div class="aysa-agent8v3-image-alt-test-head">' +
                '<div><strong>' + escapeHtml(ro ? 'Optimizare Image Alt' : 'Image Alt optimization') + '</strong><p>' + escapeHtml(ro
                    ? 'Image Alt se face în doi pași: pregătim propuneri pentru imaginile cu ALT lipsă, slab sau duplicat, apoi aplicăm doar propunerile aprobate separat. Acest review nu schimbă automat site-ul.'
                    : 'Image Alt runs in two steps: prepare suggestions for images with missing, weak, or duplicate alt text, then apply only separately approved suggestions. This review does not change the site automatically.') + '</p></div>' +
                '<span>' + escapeHtml(siteHost) + '</span>' +
            '</div>' +
            '<div class="aysa-agent8v3-image-alt-test-facts">' +
                '<span>' + escapeHtml(ro ? 'Pregătire propuneri' : 'Suggestion preparation') + '</span>' +
                '<span>' + escapeHtml(ro ? 'Aplicare separată cu aprobare' : 'Separate approval before apply') + '</span>' +
                '<span>' + escapeHtml(ro ? 'Fără modificări automate' : 'No automatic changes') + '</span>' +
                '<span>' + escapeHtml((ro ? 'Maxim afișat: ' : 'Displayed cap: ') + maxCost + ' / ' + billingUnit + (ro ? ' per imagine' : ' per image')) + '</span>' +
            '</div>' +
            '<div class="aysa-agent8v3-image-alt-test-actions"><span class="aysa-agent8v3-image-alt-test-muted">' + escapeHtml(ro ? 'Dacă nu există propuneri, folosește pregătirea propunerilor Image Alt. Aplicarea rămâne separată și cere confirmare.' : 'If there are no suggestions yet, prepare Image Alt suggestions first. Applying remains separate and requires confirmation.') + '</span></div>' +
            message + resultHtml + historyHtml +
        '</section>';
    }

    function renderImageAltTestResult(result) {
        const itemResults = Array.isArray(result.item_results) ? result.item_results : [];
        const billing = result.billing && typeof result.billing === 'object' ? result.billing : {};
        const billingLine = '<div><strong>Billing:</strong> ' + escapeHtml(billing.status || result.billing_status || '-') +
            ' · ' + escapeHtml(String(billing.cost_cents || result.billing_cost_cents || 0)) + ' credits' +
            ' · verified changed: ' + escapeHtml(String(billing.verified_changed_count || 0)) + '</div>';
        if (!itemResults.length) {
            return '<div class="aysa-agent8v3-image-alt-test-result"><strong>Status:</strong> ' + escapeHtml(result.status || '-') + billingLine + '</div>';
        }
        return '<div class="aysa-agent8v3-image-alt-test-result"><strong>Status:</strong> ' + escapeHtml(result.status || '-') +
            billingLine +
            '<table class="aysa-agent8v3-image-alt-test-table"><thead><tr><th>ID</th><th>Old alt</th><th>New alt</th><th>Readback/status</th><th>Changed</th></tr></thead><tbody>' +
            itemResults.map(function(item) {
                return '<tr>' +
                    '<td>' + escapeHtml(item.attachment_id || item.item_id || '-') + '</td>' +
                    '<td>' + escapeHtml(item.old_alt || '-') + '</td>' +
                    '<td>' + escapeHtml(item.new_alt || '-') + '</td>' +
                    '<td>' + escapeHtml(item.verification_status || item.status || item.error_code || item.skipped_reason || '-') + '</td>' +
                    '<td>' + escapeHtml(item.changed ? 'true' : 'false') + '</td>' +
                '</tr>';
            }).join('') + '</tbody></table></div>';
    }

    function renderImageAltTestHistory(history) {
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        history = Array.isArray(history) ? history : [];
        const localStatus = function(value) {
            const key = String(value || '').toLowerCase();
            const labels = ro ? {
                changed: 'modificat',
                verified: 'verificat',
                restored: 'restaurat',
                submitted: 'trimis',
                pending: 'în așteptare',
                pending_result: 'rezultat în așteptare',
                not_billed: 'nedebitat',
                not_billable_restore: 'restore fără debit'
            } : {};
            return labels[key] || value || '-';
        };
        const empty = '<div class="aysa-agent8v3-image-alt-test-empty">' + escapeHtml(ro ? 'Nu există istoric Image Alt încă.' : 'No Image Alt history yet.') + '</div>';
        const rows = history.length ? history.slice(0, 30).map(function(row) {
            const historyId = String(row.history_id || '');
            const restoreAvailable = !!row.restore_available;
            const imageUrl = String(row.image_url || '');
            return '<tr>' +
                '<td>' + (imageUrl ? '<img src="' + escapeHtml(imageUrl) + '" alt="" loading="lazy">' : '-') + '</td>' +
                '<td>' + escapeHtml(String(row.attachment_id || '-')) + '<br><small>' + escapeHtml(row.filename || historyId || '-') + '</small></td>' +
                '<td>' + escapeHtml(row.old_alt || '-') + '</td>' +
                '<td>' + escapeHtml(row.new_alt || row.final_alt || '-') + '</td>' +
                '<td>' + escapeHtml(localStatus(row.status)) + '<br><small>' + escapeHtml(localStatus(row.verification_status)) + '</small></td>' +
                '<td>' + escapeHtml(String(row.billing_cost_cents || 0)) + '<br><small>' + escapeHtml(localStatus(row.billing_status)) + '</small></td>' +
                '<td>' + escapeHtml(row.timestamp || row.updated_at || '-') + '</td>' +
                '<td>' + (restoreAvailable
                    ? '<button type="button" class="button button-small aysa-agent8v3-image-alt-test-restore" data-history-id="' + escapeHtml(historyId) + '" data-attachment-id="' + escapeHtml(String(row.attachment_id || '')) + '">' + escapeHtml(ro ? 'Restaurează' : 'Restore') + '</button>'
                    : '<span class="aysa-agent8v3-image-alt-test-muted">' + escapeHtml(row.restored_at ? (ro ? 'Restaurat' : 'Restored') : (ro ? 'Indisponibil' : 'Unavailable')) + '</span>') + '</td>' +
            '</tr>';
        }).join('') : '';
        return '<details class="aysa-agent8v3-image-alt-test-history">' +
            '<summary class="aysa-agent8v3-image-alt-test-subhead"><strong>' + escapeHtml(ro ? 'Istoric și rollback Image Alt' : 'Image Alt history and rollback') + '</strong>' +
                '<span>' + escapeHtml(ro ? 'Restore nu se debitează' : 'Restore is not billable') + '</span></summary>' +
            (history.length ? '<div class="aysa-agent8v3-image-alt-test-table-wrap"><table class="aysa-agent8v3-image-alt-test-table"><thead><tr>' +
                '<th>' + escapeHtml(ro ? 'Imagine' : 'Image') + '</th>' +
                '<th>ID</th>' +
                '<th>' + escapeHtml(ro ? 'Alt vechi' : 'Old alt') + '</th>' +
                '<th>' + escapeHtml(ro ? 'Alt nou' : 'New alt') + '</th>' +
                '<th>Status</th>' +
                '<th>Billing</th>' +
                '<th>' + escapeHtml(ro ? 'Data' : 'Time') + '</th>' +
                '<th>Restore</th>' +
            '</tr></thead><tbody>' + rows + '</tbody></table></div>' : empty) +
        '</details>';
    }

    function refreshImageAltTestModePanel() {
        if (state.modal && state.modal.key === 'technical_image_alt') {
            $('.aysa-agent8v3-image-alt-test-panel').replaceWith(renderImageAltTestModePanel(state.modal.current || {}));
        }
    }

    function maybeLoadImageAltHistory() {
        if (state.imageAltTestMode.historyLoaded || state.imageAltTestMode.historyLoading) {
            return;
        }
        state.imageAltTestMode.historyLoading = true;
        rawAjax('aysa_agent8v3_image_alt_test_history', {}).done(function(response) {
            if (response && response.success && response.data) {
                state.imageAltTestMode.history = Array.isArray(response.data.history) ? response.data.history : [];
                state.imageAltTestMode.billingIdentity = response.data.billing_identity && typeof response.data.billing_identity === 'object' ? response.data.billing_identity : state.imageAltTestMode.billingIdentity;
                state.imageAltTestMode.billingIdentityHealth = response.data.billing_identity_health && typeof response.data.billing_identity_health === 'object' ? response.data.billing_identity_health : state.imageAltTestMode.billingIdentityHealth;
                state.imageAltTestMode.walletSnapshot = response.data.wallet_snapshot && typeof response.data.wallet_snapshot === 'object' ? response.data.wallet_snapshot : state.imageAltTestMode.walletSnapshot;
                state.imageAltTestMode.productGates = response.data.product_gates && typeof response.data.product_gates === 'object' ? response.data.product_gates : state.imageAltTestMode.productGates;
                state.imageAltTestMode.historyLoaded = true;
                refreshImageAltTestModePanel();
            }
        }).always(function() {
            state.imageAltTestMode.historyLoading = false;
        });
    }

    function maybeAutoRefreshOffpageBacklinkStrategy(modal, rows) {
        const activeTab = String((modal && (modal.active_tab || (modal.filters && modal.filters.tab))) || '');
        if (String((modal && modal.modal_key) || '') !== 'offpage_seo' || activeTab !== 'link_building_plan') {
            return;
        }
        if (state.offpageBacklinkStrategyAutoRefreshed || state.offpageBacklinkStrategyRefreshing || state.offpageBacklinkStrategyTimer) {
            return;
        }
        if (Array.isArray(rows) && rows.length) {
            return;
        }
        const actions = Array.isArray(modal.actions) ? modal.actions : [];
        const canRefresh = actions.some(function(action) {
            return String((action && action.action) || '') === 'refresh_offpage_backlink_strategy_status';
        });
        if (!canRefresh) {
            return;
        }
        state.offpageBacklinkStrategyAutoRefreshed = true;
        refreshOffpageBacklinkStrategyOnce();
    }

    function renderModalHint(modal) {
        if (modal && modal.client_hint) {
            return '<div class="aysa-agent8v3-modal-hint">' + escapeHtml(String(modal.client_hint)) + '</div>';
        }
        if (String(modal.modal_key || '') === 'offpage_seo' && String(modal.active_tab || (modal.filters && modal.filters.tab) || '') === 'link_building_plan') {
            const cart = modal && modal.cart_summary && typeof modal.cart_summary === 'object' ? modal.cart_summary : {};
            if (cart.marketplace_test_scope || modal.marketplace_test_scope) {
                return '<div class="aysa-agent8v3-modal-hint">Marketplace test scope: catalogul Adverlink returnat nu este live. Aprobarea coșului este blocată până când marketplace-ul live este disponibil.</div>';
            }
        }
        if (String(modal.modal_key || '') === 'technical_site_audit') {
            const activeTab = String(modal.active_tab || (modal.filters && modal.filters.tab) || '');
            const ro = String(uiLanguage() || 'ro').indexOf('ro') === 0;
            if (activeTab === 'metadata_preview') {
                return '<div class="aysa-agent8v3-modal-hint">' + escapeHtml(ro
                    ? 'Am pregătit titluri și descrieri pentru Google. Le aplic doar după confirmare și doar dacă pot verifica schimbarea. Vezi detalii tehnice în tabelul de mai jos.'
                    : 'Titles and descriptions for Google are prepared. They are applied only after confirmation and only when the change can be verified. Technical details are listed below.') + '</div>';
            }
            if (activeTab === 'issues') {
                return '<div class="aysa-agent8v3-modal-hint">' + escapeHtml(ro
                    ? 'Aici vezi problemele prioritizate. Dacă lista detaliată lipsește, folosim rezultatul ca semnal general și nu aplicăm nimic automat.'
                    : 'This tab shows prioritized issues. If detailed rows are unavailable, the result is used as a general signal and nothing is applied automatically.') + '</div>';
            }
            if (activeTab === 'schema_preview') {
                return '<div class="aysa-agent8v3-modal-hint">' + escapeHtml(ro
                    ? 'Schema este pregătită ca recomandare controlată. Nu aplic nimic automat; candidații pot fi verificați înainte de orice aprobare. Vezi detalii tehnice în tabelul de mai jos.'
                    : 'Schema is prepared as a controlled recommendation. Nothing is applied automatically; candidates can be reviewed before any approval. Technical details are listed below.') + '</div>';
            }
        }
        if (String(modal.modal_key || '') === 'technical_redirects') {
            const ro = String(uiLanguage() || 'ro').indexOf('ro') === 0;
            const rows = Array.isArray(modal.rows) ? modal.rows : [];
            const summary = Array.isArray(modal.summary) ? modal.summary : [];
            const totalSummary = summary.find(function(item) {
                const key = String((item && item.key) || '').toLowerCase();
                const label = String((item && item.label) || '').toLowerCase();
                return key === 'total' || key === 'total_404_candidates' || label === 'total';
            });
            const candidateCount = totalSummary
                ? (parseInt(String(totalSummary.value || '0').replace(/[^0-9-]+/g, ''), 10) || 0)
                : rows.length;
            if (candidateCount <= 0 && rows.length === 0) {
                return '<div class="aysa-agent8v3-modal-hint is-empty">' + escapeHtml(ro
                    ? 'Nu există redirecționări propuse în acest review. Nu este nimic de verificat sau aplicat.'
                    : 'There are no proposed redirects in this review. There is nothing to review or apply.') + '</div>';
            }
            return '<div class="aysa-agent8v3-modal-hint">' + escapeHtml(ro
                ? 'Am găsit redirecționări posibile, dar nu le aplic automat. Mai întâi verific dacă redirecționarea este corectă, nu creează bucle și nu trimite utilizatorii către pagini greșite.'
                : 'Possible redirects were found, but they are not applied automatically. First I verify correctness, loop risk, and whether users would be sent to the right pages.') + '</div>';
        }
        if (String(modal.modal_key || '') === 'technical_sitemap_robots') {
            const ro = String(uiLanguage() || 'ro').indexOf('ro') === 0;
            return '<div class="aysa-agent8v3-modal-hint">' + escapeHtml(ro
                ? 'Sitemap-ul public există, dar AYSA nu a preluat controlul asupra lui. Nu modific robots.txt sau sitemap fără backup și confirmare separată.'
                : 'The public sitemap exists, but AYSA has not taken ownership of it. robots.txt and sitemap are not changed without backup and separate confirmation.') + '</div>';
        }
        if (String(modal.modal_key || '') === 'technical_image_alt') {
            const ro = String(uiLanguage() || 'ro').indexOf('ro') === 0;
            return '<div class="aysa-agent8v3-modal-hint">' + escapeHtml(ro
                ? 'Imaginile verificate au deja alt text sau nu există propuneri sigure pentru acest run. Pot pregăti propuneri noi într-un pas separat, fără aplicare automată.'
                : 'Checked images already have alt text, or there are no safe suggestions for this run. New suggestions can be prepared separately, without automatic apply.') + '</div>';
        }
        if (String(modal.modal_key || '') !== 'technical_internal_linking') {
            return '';
        }
        const activeTab = String(modal.active_tab || (modal.filters && modal.filters.tab) || '');
        const rows = Array.isArray(modal.rows) ? modal.rows : [];
        if (activeTab === 'link_plan' && rows.length === 0) {
            return '';
        }
        const message = activeTab === 'link_stats' ? text('internalLinkingStatsHint') :
            (activeTab === 'anchor_stats' ? text('internalLinkingAnchorHint') : text('internalLinkingPlanHint'));
        return '<div class="aysa-agent8v3-modal-hint">' + escapeHtml(message) + '</div>';
    }

    function renderMonitoringRefreshPreflightResult(modal) {
        if (String((modal && modal.modal_key) || '') !== 'monitoring') {
            return '';
        }
        const preflight = state.monitoringRefreshPreflight && typeof state.monitoringRefreshPreflight === 'object'
            ? state.monitoringRefreshPreflight
            : {};
        if (!Object.keys(preflight).length) {
            return '';
        }
        const ro = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const status = String(preflight.status || '');
        const keywordCount = parseInt(preflight.included_keywords_count || preflight.included_targets_count || 0, 10) || 0;
        const estimatedCredits = parseInt(preflight.estimated_cost_credits || 0, 10) || 0;
        const policy = modal && modal.monitoring_policy && typeof modal.monitoring_policy === 'object'
            ? modal.monitoring_policy
            : {};
        const displayCount = keywordCount || (parseInt(policy.included_count || 0, 10) || 0);
        const displayEstimate = estimatedCredits || (parseInt(policy.estimated_cost_credits || 0, 10) || 0);
        if (status === 'ready_for_cost_cap' && displayCount > 0 && displayEstimate > 0) {
            return '<section class="aysa-agent8v3-modal-hint aysa-agent8v3-monitoring-preflight-result" aria-label="' + escapeHtml(ro ? 'Estimare actualizare poziții Google' : 'Google positions update estimate') + '">' +
                '<strong>' + escapeHtml(ro ? 'Estimare pregătită pentru actualizarea pozițiilor Google' : 'Estimate ready for the Google positions update') + '</strong>' +
                '<p>' + escapeHtml(ro
                    ? 'Sunt pregătite ' + displayCount + ' cuvinte cheie principale pentru paginile lor valide. Costul estimat este ' + displayEstimate + ' credite. Actualizarea nu a pornit încă.'
                    : displayCount + ' primary keywords for valid pages are ready. The estimated cost is ' + displayEstimate + ' credits. The update has not started.') + '</p>' +
                '<label class="aysa-agent8v3-monitoring-cost-cap"><span>' + escapeHtml(ro ? 'Cost maxim pentru această actualizare' : 'Maximum cost for this update') + '</span>' +
                    '<input id="aysa-agent8v3-monitoring-serp-cost-cap" type="number" min="' + displayEstimate + '" step="1" value="' + displayEstimate + '" aria-label="' + escapeHtml(ro ? 'Cost maxim pentru actualizarea pozițiilor Google' : 'Maximum cost for the Google positions update') + '"> ' +
                    '<small>' + escapeHtml(ro ? 'credite. Confirmarea următoare pornește numai această verificare.' : 'credits. The next confirmation starts only this check.') + '</small></label>' +
            '</section>';
        }
        const message = String(preflight.block_reason || preflight.message || '');
        if (!message) {
            return '';
        }
        return '<section class="aysa-agent8v3-modal-hint aysa-agent8v3-monitoring-preflight-result is-blocked"><strong>' +
            escapeHtml(ro ? 'Actualizarea pozițiilor nu poate fi pregătită încă' : 'The positions update cannot be prepared yet') +
            '</strong><p>' + escapeHtml(clientFacingLabel(message)) + '</p></section>';
    }

    function renderMonitoringPolicyPreview(modal) {
        if (String((modal && modal.modal_key) || '') !== 'monitoring') {
            return '';
        }
        const policy = modal && modal.monitoring_policy && typeof modal.monitoring_policy === 'object'
            ? modal.monitoring_policy
            : {};
        if (!Object.keys(policy).length) {
            return '';
        }
        const ro = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const canConfirm = !!policy.can_confirm;
        const statusModel = modal && modal.monitoring_status_model && typeof modal.monitoring_status_model === 'object'
            ? modal.monitoring_status_model
            : {};
        const status = String(policy.status || 'policy_missing');
        const effectiveStatus = status === 'confirmed' && statusModel.policy_active !== true
            ? 'requires_reconfirmation'
            : status;
        const estimated = parseInt(policy.estimated_cost_credits || 0, 10) || 0;
        const estimatedUnits = parseInt(policy.estimated_provider_units || policy.included_count || 0, 10) || 0;
        const perRun = parseInt(policy.per_run_cap_credits || policy.default_per_run_cap_credits || 0, 10) || 0;
        const monthly = parseInt(policy.monthly_cap_credits || policy.default_monthly_cap_credits || 0, 10) || 0;
        const batches = Array.isArray(policy.batch_summary) ? policy.batch_summary : [];
        let sourceConfig = policy.source_configuration && typeof policy.source_configuration === 'object'
            ? policy.source_configuration
            : {};
        // Older PHP workers can omit display-only source fields after a policy
        // has already confirmed its canonical source hash. Match the existing
        // Romanian WordPress resolver for that client-safe readback only; this
        // never changes the policy, estimate, cap, or refresh payload.
        if (!Object.keys(sourceConfig).length
            && policy.source_configuration_hash_available
            && /(^|\.)ro$/i.test(String(policy.site_host || ''))) {
            sourceConfig = {
                se_domain: 'google.ro',
                location_code: 2642,
                language_code: 'ro'
            };
        }
        const searchDomain = String(sourceConfig.se_domain || '-');
        const locationCode = parseInt(sourceConfig.location_code || 0, 10) || 0;
        const languageCode = String(sourceConfig.language_code || '-');
        const batchLabel = batches.length
            ? batches.map(function(batch, index) {
                const count = parseInt(batch && batch.items_count || 0, 10) || 0;
                return String(count || (index + 1));
            }).join(' + ')
            : '-';
        const lines = [
            [ro ? 'Site' : 'Site', String(policy.site_host || '-')],
            [ro ? 'Actualizare' : 'Update', String(policy.update_frequency || '-')],
            [ro ? 'Sursă selectată' : 'Selected source', Array.isArray(policy.source_labels) ? policy.source_labels.join(', ') : '-'],
            [ro ? 'Configurare Google' : 'Google configuration', searchDomain === 'google.ro' ? 'Google România / google.ro' : searchDomain],
            [ro ? 'Locație' : 'Location', locationCode === 2642 ? 'România (2642)' : (locationCode ? String(locationCode) : '-')],
            [ro ? 'Limbă' : 'Language', languageCode],
            [ro ? 'Keyworduri pregătite' : 'Prepared keywords', String(policy.included_count || 0)],
            [ro ? 'Excluse cu motiv' : 'Excluded with a reason', String(policy.excluded_count || 0)],
            [ro ? 'Unități estimate' : 'Estimated units', String(estimatedUnits)],
            [ro ? 'Loturi estimate' : 'Estimated batches', batches.length ? String(batches.length) + ' (' + batchLabel + ')' : '-'],
            [ro ? 'Estimare' : 'Estimate', estimated > 0 ? estimated + (ro ? ' credite' : ' credits') : (ro ? 'Lipsește estimarea' : 'Estimate missing')]
        ];
        const grid = lines.map(function(line) {
            return '<div><span>' + escapeHtml(line[0]) + '</span><strong>' + escapeHtml(line[1]) + '</strong></div>';
        }).join('');
        const capFields = canConfirm
            ? '<div class="aysa-agent8v3-monitoring-policy-caps">' +
                '<label><span>' + escapeHtml(ro ? 'Plafon pentru o actualizare' : 'Cap per update') + '</span><input id="aysa-agent8v3-monitoring-policy-per-run-cap" type="number" min="' + estimated + '" step="1" value="' + perRun + '"></label>' +
                '<label><span>' + escapeHtml(ro ? 'Buget lunar' : 'Monthly budget') + '</span><input id="aysa-agent8v3-monitoring-policy-monthly-cap" type="number" min="' + perRun + '" step="1" value="' + monthly + '"></label>' +
              '</div>'
            : '';
        const disabledReason = !canConfirm ? String(policy.disabled_reason || '') : '';
        // The persisted policy label is not enough to claim automation is
        // active. The canonical status model also verifies the automation
        // contract and auto-execute flag. Keeping these read models aligned
        // prevents a confirmed legacy policy from being shown as scheduled.
        const isActive = status === 'confirmed'
            && !policy.requires_reconfirmation
            && statusModel.policy_active === true;
        if (isActive) {
            const activeFacts = [
                [ro ? 'Actualizare' : 'Update frequency', String(policy.update_frequency || '-')],
                [ro ? 'Surse' : 'Sources', Array.isArray(policy.source_labels) ? policy.source_labels.join(', ') : '-'],
                [ro ? 'Următoarea verificare' : 'Next check', String((modal.monitoring_summary || {}).next_due_at || (ro ? 'Se calculează după ultima verificare' : 'Calculated after the last check'))]
            ];
            return '<section class="aysa-agent8v3-monitoring-policy-preview is-confirmed" aria-label="' + escapeHtml(ro ? 'Setările monitorizării' : 'Monitoring settings') + '">' +
                '<div class="aysa-agent8v3-monitoring-policy-preview-head"><strong>' + escapeHtml(ro ? 'Monitorizare automată activă' : 'Automatic monitoring is active') + '</strong><span>' + escapeHtml(ro ? 'În limitele aprobate' : 'Within approved limits') + '</span></div>' +
                '<p>' + escapeHtml(ro ? 'Datele sunt salvate. Următoarele verificări respectă frecvența aleasă în Profil SEO.' : 'Data is saved. Future checks follow the frequency selected in SEO Profile.') + '</p>' +
                '<details class="aysa-agent8v3-monitoring-policy-details"><summary>' + escapeHtml(ro ? 'Vezi setările aprobate' : 'View approved settings') + '</summary><div class="aysa-agent8v3-monitoring-policy-active-facts">' + activeFacts.map(function(line) {
                    return '<div><span>' + escapeHtml(line[0]) + '</span><strong>' + escapeHtml(line[1]) + '</strong></div>';
                }).join('') + '</div><p>' + escapeHtml((ro ? 'Poziții Google: ' : 'Google positions: ') + estimated + (ro ? ' credite maximum pe rulare. ' : ' credits maximum per run. ') + (ro ? 'Search Console nu consumă credite AYSA.' : 'Search Console does not use AYSA credits.')) + '</p></details>' +
            '</section>';
        }
        return '<section class="aysa-agent8v3-monitoring-policy-preview is-' + escapeHtml(effectiveStatus) + '" aria-label="' + escapeHtml(ro ? 'Setările monitorizării' : 'Monitoring settings') + '">' +
            '<div class="aysa-agent8v3-monitoring-policy-preview-head"><strong>' + escapeHtml(ro ? 'Setările monitorizării' : 'Monitoring settings') + '</strong><span>' + escapeHtml(clientFacingLabel(effectiveStatus)) + '</span></div>' +
            '<p>' + escapeHtml(String(policy.message || (ro ? 'Verifică setările înainte de confirmare.' : 'Review the settings before confirming.'))) + '</p>' +
            '<details class="aysa-agent8v3-monitoring-policy-details"><summary>' + escapeHtml(ro ? 'Vezi setările monitorizării' : 'View monitoring settings') + '</summary>' +
                '<div class="aysa-agent8v3-monitoring-policy-grid">' + grid + '</div>' +
                '<p class="aysa-agent8v3-monitoring-policy-note">' + escapeHtml(String(policy.excluded_reason || '')) + '</p>' +
                (disabledReason ? '<p class="aysa-agent8v3-monitoring-policy-note">' + escapeHtml(disabledReason) + '</p>' : '') +
                capFields +
                '<p class="aysa-agent8v3-monitoring-policy-note">' + escapeHtml(String(policy.auto_run_rule || '')) + '</p>' +
            '</details>' +
            '<small>' + escapeHtml(ro
                ? 'După confirmare începe prima verificare aprobată. Pozițiile Google sunt taxate numai după salvarea datelor. Search Console nu consumă credite AYSA.'
                : 'Confirmation starts the first approved check. Google positions bill only after data is saved. Search Console does not use AYSA credits.') + '</small>' +
        '</section>';
    }

    function renderMonitoringExecutionStatus(modal) {
        if (String((modal && modal.modal_key) || '') !== 'monitoring') {
            return '';
        }
        const execution = modal && modal.monitoring_execution && typeof modal.monitoring_execution === 'object'
            ? modal.monitoring_execution
            : {};
        const sources = ['rank', 'gsc'].map(function(key) {
            return { key: key, value: execution[key] && typeof execution[key] === 'object' ? execution[key] : {} };
        }).filter(function(entry) {
            return Object.keys(entry.value).length && String(entry.value.state || 'not_started') !== 'not_started';
        });
        if (!sources.length) {
            return '';
        }
        const ro = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        return '<section class="aysa-agent8v3-monitoring-execution-status" aria-label="' + escapeHtml(ro ? 'Starea actualizării' : 'Update status') + '">' +
            '<strong>' + escapeHtml(ro ? 'Date disponibile' : 'Available data') + '</strong>' +
            '<div class="aysa-agent8v3-monitoring-execution-grid">' + sources.map(function(entry) {
                const source = entry.value;
                const state = String(source.state || 'needs_review');
                const processed = parseInt(source.processed || 0, 10) || 0;
                const failed = parseInt(source.failed || 0, 10) || 0;
                const counts = [];
                if (processed > 0) {
                    counts.push((ro ? 'Verificate: ' : 'Checked: ') + processed);
                }
                if (failed > 0) {
                    counts.push((ro ? 'Fără rezultat: ' : 'Without result: ') + failed);
                }
                const label = entry.key === 'rank'
                    ? (ro ? 'Poziții Google' : 'Google positions')
                    : 'Search Console';
                return '<article class="is-' + escapeHtml(state) + '">' +
                    '<div><span>' + escapeHtml(label) + '</span><b>' + escapeHtml(clientFacingLabel(state)) + '</b></div>' +
                    (counts.length ? '<small>' + escapeHtml(counts.join(' · ')) + '</small>' : '') +
                '</article>';
            }).join('') + '</div>' +
        '</section>';
    }

    function monitoringResultUrl(value) {
        const raw = String(value || '').trim();
        if (!raw || raw === '-') {
            return '';
        }
        return raw.replace(/^https?:\/\//i, '').replace(/\/$/, '');
    }

    function monitoringCompactUrl(value, maxLength) {
        const full = monitoringResultUrl(value);
        const limit = Math.max(28, Number(maxLength) || 58);
        if (!full || full.length <= limit) {
            return full;
        }
        const tailLength = 18;
        return full.slice(0, Math.max(12, limit - tailLength - 1)) + '…' + full.slice(-tailLength);
    }

    function monitoringUrlHtml(value, fallback) {
        const full = monitoringResultUrl(value);
        if (!full) {
            return escapeHtml(fallback || '—');
        }
        return '<span class="aysa-agent8v3-monitoring-compact-url" title="' + escapeHtml(full) + '">' + escapeHtml(monitoringCompactUrl(full)) + '</span>';
    }

    function monitoringNumber(value, fractionDigits) {
        const number = Number(value);
        if (!Number.isFinite(number)) {
            return '-';
        }
        try {
            return new Intl.NumberFormat(uiLanguage() || 'ro', {
                maximumFractionDigits: fractionDigits,
                minimumFractionDigits: 0
            }).format(number);
        } catch (error) {
            return String(Math.round(number * Math.pow(10, fractionDigits)) / Math.pow(10, fractionDigits));
        }
    }

    function renderMonitoringResultPanel(modal) {
        const ro = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const rows = Array.isArray(modal && modal.rows) ? modal.rows : [];
        const pagination = modal && modal.pagination && typeof modal.pagination === 'object' ? modal.pagination : {};
        const activeTab = String((modal && (modal.active_tab || (modal.filters && modal.filters.tab))) || 'serp_positions');
        const activeView = String((modal && (modal.monitoring_view || (modal.filters && modal.filters.monitoring_view))) || 'overview');
        const presentation = modal && modal.monitoring_presentation && typeof modal.monitoring_presentation === 'object'
            ? modal.monitoring_presentation
            : {};
        const total = parseInt(pagination.total || rows.length, 10) || 0;
        const page = parseInt(pagination.page || 1, 10) || 1;
        const pages = parseInt(pagination.pages || 1, 10) || 1;
        const activeSearch = String((modal && modal.filters && modal.filters.search) || '').trim();
        const title = activeTab === 'gsc_performance'
            ? 'Search Console'
            : (activeTab === 'ai_visibility' ? (ro ? 'Vizibilitate AI' : 'AI visibility') : (ro ? 'Poziții Google' : 'Google positions'));
        const intro = activeTab === 'gsc_performance'
            ? (ro ? 'Datele Google sunt păstrate separat de pozițiile Google. Explorează performanța fiecărei interogări.' : 'Google data is kept separately from Google positions. Explore each query’s performance.')
            : (activeTab === 'ai_visibility'
                ? (ro ? 'Vizibilitatea AI rămâne separată și se activează numai după aprobarea setului de întrebări.' : 'AI visibility remains separate and activates only after approving the question set.')
                : (ro ? 'Aceasta este prima verificare salvată. Vei vedea evoluția după următoarea verificare comparabilă.' : 'This is the first saved check. You will see movement after the next comparable check.'));
        const viewOptions = activeTab === 'gsc_performance'
            ? [['overview', ro ? 'Rezumat' : 'Summary'], ['queries', ro ? 'Interogări' : 'Queries'], ['pages', ro ? 'Pagini' : 'Pages']]
            : (activeTab === 'ai_visibility'
                ? [['overview', ro ? 'Rezumat' : 'Summary'], ['questions', ro ? 'Întrebări' : 'Questions']]
                : [['overview', ro ? 'Rezumat' : 'Summary'], ['keywords', ro ? 'Keyworduri' : 'Keywords'], ['pages', ro ? 'Pagini' : 'Pages']]);
        const gscPagesUnavailable = activeTab === 'gsc_performance' && modal && modal.gsc_page_dimension_available === false;
        const subTabs = '<nav class="aysa-agent8v3-monitoring-subtabs" aria-label="' + escapeHtml(ro ? 'Detalii monitorizare' : 'Monitoring details') + '">' + viewOptions.map(function(option) {
            const selected = activeView === option[0];
            const disabled = gscPagesUnavailable && option[0] === 'pages';
            const unavailableTitle = disabled
                ? (ro ? 'Datele Search Console disponibile nu includ pagina asociată fiecărei interogări.' : 'The available Search Console data does not include the page associated with each query.')
                : '';
            return '<button type="button" class="aysa-agent8v3-monitoring-subtab' + (selected ? ' is-active' : '') + (disabled ? ' is-disabled' : '') + '" data-monitoring-view="' + escapeHtml(option[0]) + '" aria-selected="' + (selected ? 'true' : 'false') + '"' + (disabled ? ' disabled aria-disabled="true" title="' + escapeHtml(unavailableTitle) + '"' : '') + '>' + escapeHtml(option[1]) + '</button>';
        }).join('') + '</nav>';
        const value = function(input, digits) {
            return input === null || input === undefined || input === '' ? '-' : monitoringNumber(input, digits || 0);
        };
        const percentage = function(input) {
            return input === null || input === undefined || input === '' ? '-' : value(input, 2) + '%';
        };
        const kpi = function(label, metric, tone) {
            return '<article class="aysa-agent8v3-monitoring-kpi is-' + escapeHtml(tone || 'neutral') + '"><span>' + escapeHtml(label) + '</span><strong>' + escapeHtml(String(metric)) + '</strong></article>';
        };
        const bar = function(item, totalItems) {
            const count = Number(item && item.value) || 0;
            const percent = totalItems > 0 ? Math.min(100, Math.round((count / totalItems) * 100)) : 0;
            return '<div class="aysa-agent8v3-monitoring-distribution-row is-' + escapeHtml(String(item && item.tone || 'neutral')) + '"><span>' + escapeHtml(String(item && item.label || '-')) + '</span><div><i style="width:' + percent + '%"></i></div><b>' + escapeHtml(String(count)) + '</b></div>';
        };
        const summaryHtml = function() {
            if (activeTab === 'gsc_performance') {
                const gsc = presentation.gsc && typeof presentation.gsc === 'object' ? presentation.gsc : {};
                const summary = gsc.summary && typeof gsc.summary === 'object' ? gsc.summary : {};
                const trend = gsc.trend && typeof gsc.trend === 'object' ? gsc.trend : {};
                const trendCopy = trend.available
                    ? (ro ? 'Comparația este calculată numai din verificări Search Console comparabile.' : 'Comparison uses comparable Search Console checks only.')
                    : (ro ? 'Evoluția apare după încă o verificare Search Console comparabilă.' : 'Movement appears after one more comparable Search Console check.');
                return '<section class="aysa-agent8v3-monitoring-dashboard is-gsc"><div class="aysa-agent8v3-monitoring-kpis">' +
                    kpi(ro ? 'Clicuri' : 'Clicks', value(summary.clicks), 'teal') +
                    kpi(ro ? 'Impresii' : 'Impressions', value(summary.impressions), 'teal') +
                    kpi('CTR', percentage(summary.ctr), 'teal') +
                    kpi(ro ? 'Poziție medie' : 'Average position', value(summary.average_position, 1), 'teal') +
                    '</div><p class="aysa-agent8v3-monitoring-data-note">' + escapeHtml(ro ? 'Poziția medie Search Console nu este poziție SERP exactă.' : 'Search Console average position is not exact SERP rank.') + '</p><div class="aysa-agent8v3-monitoring-comparison">' + escapeHtml(trendCopy) + '</div></section>';
            }
            if (activeTab === 'ai_visibility') {
                const ai = presentation.ai && typeof presentation.ai === 'object' ? presentation.ai : {};
                const summary = ai.summary && typeof ai.summary === 'object' ? ai.summary : {};
                const aiModule = modal && modal.monitoring_modules && modal.monitoring_modules.ai_visibility && typeof modal.monitoring_modules.ai_visibility === 'object'
                    ? modal.monitoring_modules.ai_visibility
                    : {};
                const active = String(ai.status || aiModule.status || 'inactive') !== 'inactive' && Number(summary.questions || 0) > 0;
                if (!active) {
                    return '<section class="aysa-agent8v3-monitoring-dashboard is-ai is-inactive"><div class="aysa-agent8v3-monitoring-empty-state"><strong>' +
                        escapeHtml(ro ? 'Vizibilitatea AI este inactivă' : 'AI visibility is inactive') +
                        '</strong><p>' +
                        escapeHtml(ro ? 'Pornește doar după aprobarea separată a întrebărilor și a plafonului. Nu există verificări sau costuri active.' : 'It starts only after separate approval of questions and the spending cap. No checks or costs are active.') +
                        '</p></div></section>';
                }
                return '<section class="aysa-agent8v3-monitoring-dashboard is-ai"><div class="aysa-agent8v3-monitoring-kpis">' +
                    kpi(ro ? 'Întrebări verificate' : 'Questions checked', value(summary.questions), 'ai') +
                    kpi(ro ? 'Brand menționat' : 'Brand mentioned', value(summary.brand_mentioned), 'ai') +
                    kpi(ro ? 'Site citat' : 'Site cited', value(summary.site_cited), 'ai') +
                    kpi(ro ? 'Fără prezență' : 'Not visible', value(summary.not_visible), 'ai') +
                    '</div><div class="aysa-agent8v3-monitoring-comparison">' + escapeHtml(ro ? 'Rezultatele sunt doar cele deja salvate pentru setul de întrebări aprobat.' : 'Only previously saved results for the approved question set are shown.') + '</div></section>';
            }
            const serp = presentation.serp && typeof presentation.serp === 'object' ? presentation.serp : {};
            const summary = serp.summary && typeof serp.summary === 'object' ? serp.summary : {};
            const trend = serp.trend && typeof serp.trend === 'object' ? serp.trend : {};
            const distribution = Array.isArray(serp.distribution) ? serp.distribution : [];
            const prepared = Number(summary.prepared || summary.tracked || 0);
            const saved = Number(summary.saved || 0);
            const missing = Number(summary.missing_snapshot || Math.max(0, prepared - saved));
            const historical = Number(summary.outside_current_scope || 0);
            const coverage = Number(summary.coverage_percent || (prepared > 0 ? (saved / prepared) * 100 : 0));
            const totalTracked = saved;
            const comparison = trend.available
                ? '<div class="aysa-agent8v3-monitoring-trend-grid">' +
                    '<div><span>' + escapeHtml(ro ? 'Poziție medie anterioară' : 'Previous average position') + '</span><strong>' + escapeHtml(value(trend.previous_average_position, 1)) + '</strong></div>' +
                    '<div><span>' + escapeHtml(ro ? 'Poziție medie curentă' : 'Current average position') + '</span><strong>' + escapeHtml(value(trend.current_average_position, 1)) + '</strong></div>' +
                    '<div class="is-up"><span>' + escapeHtml(ro ? 'Au urcat' : 'Improved') + '</span><strong>' + escapeHtml(value(trend.improved)) + '</strong></div>' +
                    '<div class="is-down"><span>' + escapeHtml(ro ? 'Au scăzut' : 'Declined') + '</span><strong>' + escapeHtml(value(trend.declined)) + '</strong></div>' +
                    '<div><span>' + escapeHtml(ro ? 'Stabile' : 'Stable') + '</span><strong>' + escapeHtml(value(trend.stable)) + '</strong></div></div>'
                : '<div class="aysa-agent8v3-monitoring-comparison">' + escapeHtml(ro ? 'Prima verificare salvată. Evoluția va apărea după următoarea verificare comparabilă.' : 'First saved check. Movement appears after the next comparable check.') + '</div>';
            return '<section class="aysa-agent8v3-monitoring-dashboard is-serp">' +
                '<div class="aysa-agent8v3-monitoring-coverage"><div><span>' + escapeHtml(ro ? 'Keyworduri verificate din scope-ul activ' : 'Keywords checked in the active scope') + '</span><strong>' + escapeHtml(saved + ' / ' + prepared) + '</strong></div><div class="aysa-agent8v3-monitoring-coverage-track"><i style="width:' + Math.max(0, Math.min(100, coverage)) + '%"></i></div><b title="' + escapeHtml(ro ? 'Procent de keyworduri active care au o poziție salvată' : 'Percentage of active keywords with a saved position') + '">' + escapeHtml(value(coverage, 1) + '%') + '</b></div>' +
                (missing > 0 || historical > 0 ? '<div class="aysa-agent8v3-monitoring-attention"><strong>' + escapeHtml(ro ? 'Necesită atenție' : 'Needs attention') + '</strong><span>' + escapeHtml((missing > 0 ? (ro ? missing + ' keyworduri active nu au încă un rezultat salvat.' : missing + ' active keywords do not have a saved result yet.') : '') + (missing > 0 && historical > 0 ? ' ' : '') + (historical > 0 ? (ro ? historical + ' rânduri istorice sunt în afara scope-ului curent și nu intră în KPI-uri.' : historical + ' historical rows are outside the current scope and are excluded from KPIs.') : '')) + '</span></div>' : '') +
                '<div class="aysa-agent8v3-monitoring-kpis">' +
                kpi(ro ? 'În Top 3' : 'In Top 3', value(summary.top3), 'green') +
                kpi(ro ? 'În Top 10' : 'In Top 10', value(summary.top10), 'blue') +
                kpi(ro ? 'În Top 20' : 'In Top 20', value(summary.top20), 'blue') +
                kpi(ro ? 'Neregăsite' : 'Not found', value(summary.not_found), 'red') +
                '</div><p class="aysa-agent8v3-monitoring-data-note">' + escapeHtml(ro ? 'Top 3, Top 10 și Top 20 sunt totaluri cumulative. Barele de mai jos folosesc intervale exclusive, fără dublare.' : 'Top 3, Top 10, and Top 20 are cumulative totals. The bars below use exclusive, non-overlapping ranges.') + '</p><div class="aysa-agent8v3-monitoring-distribution"><h4>' + escapeHtml(ro ? 'Distribuția pozițiilor' : 'Position distribution') + '</h4>' + distribution.map(function(item) { return bar(item, totalTracked); }).join('') + '</div>' + comparison + '</section>';
        };
        const serpPositionClass = function(input) {
            const position = Number(input);
            if (!Number.isFinite(position) || position <= 0) {
                return 'is-missing';
            }
            if (position <= 3) {
                return 'is-top3';
            }
            if (position <= 10) {
                return 'is-top10';
            }
            if (position <= 20) {
                return 'is-top20';
            }
            return 'is-other';
        };
        const serpPositionLabel = function(input) {
            const position = Number(input);
            return Number.isFinite(position) && position > 0
                ? '#' + String(position)
                : (ro ? 'Neregăsit' : 'Not found');
        };
        const serpChangeLabel = function(row) {
            row = row && typeof row === 'object' ? row : {};
            const current = Number(row.current_position ?? row.position ?? row.rank);
            const previous = Number(row.previous_position);
            if (!Number.isFinite(current) || current <= 0 || !Number.isFinite(previous) || previous <= 0) {
                return '<span class="aysa-agent8v3-monitoring-change is-neutral">—</span>';
            }
            const movement = previous - current;
            if (movement === 0) {
                return '<span class="aysa-agent8v3-monitoring-change is-neutral">—</span>';
            }
            const direction = movement > 0 ? 'is-up' : 'is-down';
            const symbol = movement > 0 ? '↑' : '↓';
            return '<span class="aysa-agent8v3-monitoring-change ' + direction + '">' + symbol + ' ' + escapeHtml(String(Math.abs(movement))) + '</span>';
        };
        const serpKeywordTable = function() {
            if (!rows.length) {
                return '';
            }
            const tableRows = rows.map(function(row) {
                row = row && typeof row === 'object' ? row : {};
                const keyword = String(row.keyword || row.query || '-');
                const target = monitoringResultUrl(row.target_url || row.target);
                const found = monitoringResultUrl(row.found_url || (target ? row.url : ''));
                const position = row.current_position ?? row.position ?? row.rank ?? null;
                const awaitingCheck = String(row.snapshot_status || '') === 'missing';
                const detail = [
                    found ? (ro ? 'Rezultat găsit: ' : 'Found result: ') + found : '',
                    row.last_checked_at || row.checked_at ? (ro ? 'Verificat: ' : 'Checked: ') + String(row.last_checked_at || row.checked_at) : ''
                ].filter(Boolean).join(' · ');
                return '<tr>' +
                    '<td class="aysa-agent8v3-monitoring-keyword-cell"><strong>' + escapeHtml(keyword) + '</strong></td>' +
                    '<td><span class="aysa-agent8v3-monitoring-position ' + (awaitingCheck ? 'is-awaiting' : serpPositionClass(position)) + '">' + escapeHtml(awaitingCheck ? (ro ? 'Neverificat' : 'Not checked') : serpPositionLabel(position)) + '</span></td>' +
                    '<td>' + serpChangeLabel(row) + '</td>' +
                    '<td class="aysa-agent8v3-monitoring-url-cell">' + monitoringUrlHtml(target, ro ? 'Fără pagină asociată' : 'No associated page') + '</td>' +
                    '<td class="aysa-agent8v3-monitoring-url-cell">' + monitoringUrlHtml(found, '—') + '</td>' +
                    '<td class="aysa-agent8v3-monitoring-table-details">' + (detail ? '<details><summary>' + escapeHtml(ro ? 'Detalii' : 'Details') + '</summary><p>' + escapeHtml(detail) + '</p></details>' : '—') + '</td>' +
                '</tr>';
            }).join('');
            return '<div class="aysa-agent8v3-monitoring-table-wrap"><table class="aysa-agent8v3-monitoring-keyword-table"><thead><tr>' +
                '<th>' + escapeHtml(ro ? 'Keyword' : 'Keyword') + '</th>' +
                '<th>' + escapeHtml(ro ? 'Poziție' : 'Position') + '</th>' +
                '<th>' + escapeHtml(ro ? 'Schimbare' : 'Change') + '</th>' +
                '<th>' + escapeHtml(ro ? 'Pagină țintă' : 'Target page') + '</th>' +
                '<th>' + escapeHtml(ro ? 'Rezultat găsit' : 'Found result') + '</th>' +
                '<th>' + escapeHtml(ro ? 'Mai multe' : 'More') + '</th>' +
                '</tr></thead><tbody>' + tableRows + '</tbody></table></div>';
        };
        const list = rows.map(function(row) {
            row = row && typeof row === 'object' ? row : {};
            if (activeTab === 'gsc_performance') {
                const query = String(activeView === 'pages' ? (row.page_url || '-') : (row.query || row.keyword || '-'));
                const pageUrl = monitoringResultUrl(activeView === 'pages' ? '' : (row.page_url || row.page || row.target_url || row.url));
                const clicks = monitoringNumber(row.clicks, 0);
                const impressions = monitoringNumber(row.impressions, 0);
                const rowCtr = impressions > 0
                    ? (Number(row.clicks || 0) / Number(row.impressions || 0)) * 100
                    : row.ctr;
                const position = monitoringNumber(row.position ?? row.average_position, 1);
                const queryCount = activeView === 'pages' ? '<span>' + escapeHtml((ro ? 'Interogări: ' : 'Queries: ') + monitoringNumber(row.queries, 0)) + '</span>' : '';
                return '<article class="aysa-agent8v3-monitoring-result-row"><div class="aysa-agent8v3-monitoring-result-primary"><strong>' + escapeHtml(query) + '</strong>' + (pageUrl ? monitoringUrlHtml(pageUrl) : '') + '</div><div class="aysa-agent8v3-monitoring-result-metrics">' + queryCount + '<span>' + escapeHtml((ro ? 'Clicuri: ' : 'Clicks: ') + clicks) + '</span><span>' + escapeHtml((ro ? 'Impresii: ' : 'Impressions: ') + impressions) + '</span><span>' + escapeHtml('CTR: ' + percentage(rowCtr)) + '</span><span>' + escapeHtml((ro ? 'Poziție medie: ' : 'Average position: ') + position) + '</span></div></article>';
            }
            const keyword = String(activeTab === 'ai_visibility' ? (row.query || row.question || '-') : (activeView === 'pages' ? (row.url || '-') : (row.keyword || row.query || '-')));
            const target = monitoringResultUrl(activeView === 'pages' ? (row.url || row.target_url || row.target || row.page_url) : (row.target_url || row.target || row.page_url));
            const found = monitoringResultUrl(activeView === 'pages' ? '' : (row.found_url || row.url));
            const position = row.position ?? row.current_position ?? row.rank ?? null;
            const numericPosition = Number(position);
            const hasRank = position !== null
                && position !== ''
                && String(position) !== '-'
                && Number.isFinite(numericPosition)
                && numericPosition > 0;
            const pageAverage = Number(row.average_position);
            const rank = activeView === 'pages'
                ? (Number.isFinite(pageAverage) && pageAverage > 0
                    ? (ro ? 'Medie ' : 'Average ') + value(pageAverage, 1)
                    : (ro ? 'Fără poziție salvată' : 'No saved position'))
                : (hasRank ? '#' + String(position) : (ro ? 'Neregăsit' : 'Not found'));
            const checked = String(row.checked_at || row.updated_at || row.timestamp || '');
            const detail = [
                found ? (ro ? 'Rezultat găsit: ' : 'Found result: ') + found : '',
                activeView === 'pages' && row.keywords !== undefined ? (ro ? 'Keyworduri: ' : 'Keywords: ') + monitoringNumber(row.keywords, 0) : '',
                activeTab === 'ai_visibility' ? (ro ? 'Brand: ' : 'Brand: ') + (row.brand_mentioned ? (ro ? 'menționat' : 'mentioned') : (ro ? 'nemenționat' : 'not mentioned')) : '',
                String(row.recommendation || row.status_copy || row.recommended_aeo_fix || '')
            ].filter(Boolean).join(' · ');
            if (activeView === 'pages') {
                const savedKeywords = Number(row.saved_keywords || 0);
                const missingKeywords = Number(row.missing_keywords || Math.max(0, Number(row.keywords || 0) - savedKeywords));
                const pageStatus = [
                    (ro ? 'Salvate: ' : 'Saved: ') + monitoringNumber(savedKeywords, 0),
                    (ro ? 'Neverificate: ' : 'Not checked: ') + monitoringNumber(missingKeywords, 0)
                ].join(' · ');
                return '<article class="aysa-agent8v3-monitoring-result-row is-page-row"><div class="aysa-agent8v3-monitoring-result-primary"><strong title="' + escapeHtml(target || keyword) + '">' + escapeHtml(monitoringCompactUrl(target || keyword)) + '</strong><span>' + escapeHtml(pageStatus) + '</span></div><div class="aysa-agent8v3-monitoring-result-rank">' + escapeHtml(rank) + '</div><div class="aysa-agent8v3-monitoring-result-meta">' + (detail ? '<details><summary>' + escapeHtml(ro ? 'Detalii' : 'Details') + '</summary><p>' + escapeHtml(detail) + '</p></details>' : '') + '</div></article>';
            }
            return '<article class="aysa-agent8v3-monitoring-result-row"><div class="aysa-agent8v3-monitoring-result-primary"><strong>' + escapeHtml(keyword) + '</strong>' + monitoringUrlHtml(target, ro ? 'Pagina asociată nu este disponibilă' : 'The associated page is unavailable') + '</div><div class="aysa-agent8v3-monitoring-result-rank">' + escapeHtml(rank) + '</div><div class="aysa-agent8v3-monitoring-result-meta">' + (checked ? '<span>' + escapeHtml(checked) + '</span>' : '') + (detail ? '<details><summary>' + escapeHtml(ro ? 'Detalii' : 'Details') + '</summary><p>' + escapeHtml(detail) + '</p></details>' : '') + '</div></article>';
        }).join('');
        const empty = activeTab === 'ai_visibility'
            ? (ro ? 'Vizibilitatea AI nu este activată încă. Nu se fac verificări sau costuri până la o aprobare separată.' : 'AI visibility is not enabled yet. No checks or costs occur until separate approval.')
            : (activeSearch
                ? (ro ? 'Nu există rezultate pentru filtrul curent.' : 'There are no results for the current filter.')
                : (ro ? 'Nu există încă rezultate salvate pentru această sursă.' : 'There are no saved results for this source yet.'));
        const detailRows = activeTab === 'serp_positions' && activeView === 'keywords'
            ? serpKeywordTable()
            : list;
        const sourceExplanation = activeTab === 'gsc_performance' && gscPagesUnavailable && activeView !== 'overview'
            ? '<p class="aysa-agent8v3-monitoring-data-note is-source-explanation">' + escapeHtml(ro ? 'Datele Search Console disponibile nu includ pagina asociată fiecărei interogări.' : 'The available Search Console data does not include the page associated with each query.') + '</p>'
            : '';
        const details = activeView === 'overview' ? '' : sourceExplanation + (detailRows || '<div class="aysa-agent8v3-modal-empty">' + escapeHtml(empty) + '</div>');
        const resultMeta = activeView !== 'overview'
            ? '<div class="aysa-agent8v3-monitoring-result-count">' +
                (total ? '<span>' + escapeHtml((ro ? 'Arăți ' : 'Showing ') + rows.length + (ro ? ' din ' : ' of ') + total + (pages > 1 ? (ro ? ' · pagina ' : ' · page ') + page + '/' + pages : '')) + '</span>' : '') +
                (activeSearch ? '<span class="is-filtered">' + escapeHtml((ro ? 'Filtru activ: ' : 'Active filter: ') + activeSearch) + '</span>' : '') +
              '</div>'
            : '';
        return '<section class="aysa-agent8v3-monitoring-results" aria-label="' + escapeHtml(title) + '"><div class="aysa-agent8v3-monitoring-results-head"><div><h3>' + escapeHtml(title) + '</h3><p>' + escapeHtml(intro) + '</p></div>' + resultMeta + '</div>' + subTabs + (activeView === 'overview' ? summaryHtml() : details) + '</section>';
    }

    function monitoringDisplayDate(value) {
        const raw = String(value || '').trim();
        if (!raw) {
            return '';
        }
        const date = new Date(raw);
        if (Number.isNaN(date.getTime())) {
            return raw;
        }
        try {
            return new Intl.DateTimeFormat(uiLanguage() || 'ro', {
                day: '2-digit',
                month: 'short',
                year: 'numeric'
            }).format(date);
        } catch (error) {
            return raw;
        }
    }

    function renderMonitoringWorkspaceHeader(modal) {
        if (String((modal && modal.modal_key) || '') !== 'monitoring') {
            return '';
        }
        const ro = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        const summary = modal && modal.monitoring_summary && typeof modal.monitoring_summary === 'object'
            ? modal.monitoring_summary
            : {};
        const policy = modal && modal.monitoring_policy && typeof modal.monitoring_policy === 'object'
            ? modal.monitoring_policy
            : {};
        const statusModel = modal && modal.monitoring_status_model && typeof modal.monitoring_status_model === 'object'
            ? modal.monitoring_status_model
            : {};
        const sourceStatuses = statusModel.sources && typeof statusModel.sources === 'object'
            ? statusModel.sources
            : {};
        const sourceConfig = policy.source_configuration && typeof policy.source_configuration === 'object'
            ? policy.source_configuration
            : {};
        const google = String(sourceConfig.se_domain || '') === 'google.ro' ? 'Google România' : (String(sourceConfig.se_domain || '') || '-');
        const next = monitoringDisplayDate(statusModel.next_check_at || '');
        const policyActive = statusModel.policy_active === true;
        const overallMessage = String(statusModel.message || (policyActive
            ? (ro ? 'Monitorizare automată activă în plafonul aprobat.' : 'Automatic monitoring is active within the approved cap.')
            : (policy.message || '')));
        const nextValue = next || String(statusModel.next_check_reason || (ro
            ? 'Data următoarei rulări nu este disponibilă.'
            : 'The next run date is unavailable.'));
        const statusLabel = function(source, fallback) {
            return String(sourceStatuses[source] && sourceStatuses[source].label || fallback);
        };
        const facts = [
            [ro ? 'Site' : 'Site', String(policy.site_host || summary.site_host || '-')],
            [ro ? 'Google' : 'Google', google],
            [ro ? 'Actualizare' : 'Update', String(policy.update_frequency || summary.update_frequency || '-')],
            [ro ? 'Următoarea verificare' : 'Next check', nextValue]
        ];
        const sourceFacts = [
            [ro ? 'Poziții Google' : 'Google positions', statusLabel('serp_positions', ro ? 'Necesită verificare' : 'Needs verification')],
            ['Search Console', statusLabel('gsc_performance', ro ? 'Necesită verificare' : 'Needs verification')],
            [ro ? 'Vizibilitate AI' : 'AI visibility', statusLabel('ai_visibility', ro ? 'Inactiv' : 'Inactive')]
        ];
        return '<section class="aysa-agent8v3-monitoring-workspace-summary">' +
            '<div class="aysa-agent8v3-monitoring-executive"><div><span>' + escapeHtml(ro ? 'Stare monitorizare' : 'Monitoring status') + '</span><p>' + escapeHtml(overallMessage) + '</p></div></div>' +
            '<p class="aysa-agent8v3-monitoring-scope-copy">' + escapeHtml(ro
                ? 'Monitorizăm doar keywordurile cu pagini publice validate. Keywordurile fără pagină rămân în Content Strategy până există conținut. Rulările automate respectă plafonul aprobat.'
                : 'Only keywords with validated public pages are monitored. Keywords without a page remain in Content Strategy until content exists. Automatic checks respect the approved cap.') + '</p>' +
            '<div class="aysa-agent8v3-monitoring-workspace-grid">' + facts.map(function(fact) {
                return '<div><span>' + escapeHtml(fact[0]) + '</span><strong>' + escapeHtml(fact[1]) + '</strong></div>';
            }).join('') + '</div>' +
            '<div class="aysa-agent8v3-monitoring-workspace-grid is-source-status">' + sourceFacts.map(function(fact) {
                return '<div><span>' + escapeHtml(fact[0]) + '</span><strong>' + escapeHtml(fact[1]) + '</strong></div>';
            }).join('') + '</div>' +
        '</section>';
    }

    function renderOnPageAgentOverviewCards(rows, modal) {
        const items = Array.isArray(rows) ? rows : [];
        if (!items.length) {
            return '<div class="aysa-agent8v3-modal-empty">' + escapeHtml((modal && modal.empty_message) || 'No rows available.') + '</div>';
        }
        return '<div class="aysa-agent8v3-onpage-agent-list">' + items.map(function(row) {
            const area = String((row && row.area) || '-');
            const status = String((row && row.status) || '-');
            const done = String((row && row.done) || '-');
            const attention = String((row && row.attention) || '0');
            const nextStep = String((row && row.next_step) || '-');
            const statusSlug = status.toLowerCase().replace(/[^a-z0-9]+/g, '-');
            return '<article class="aysa-agent8v3-onpage-agent-card is-' + escapeHtml(statusSlug) + '">' +
                '<div class="aysa-agent8v3-onpage-agent-card-head">' +
                    '<strong>' + escapeHtml(area) + '</strong>' +
                    renderModalChip('status', statusIcon(status), status, status) +
                '</div>' +
                '<div class="aysa-agent8v3-onpage-agent-card-grid">' +
                    '<div><span>' + escapeHtml('Ce știm acum') + '</span><strong>' + escapeHtml(done) + '</strong></div>' +
                    '<div><span>' + escapeHtml('Necesită review') + '</span><strong>' + escapeHtml(attention) + '</strong></div>' +
                    '<div><span>' + escapeHtml('Următorul pas sigur') + '</span><strong>' + escapeHtml(nextStep) + '</strong></div>' +
                '</div>' +
            '</article>';
        }).join('') + '</div>';
    }

    function renderOffPageCanonicalWorkspace(workspace, modal) {
        workspace = workspace && typeof workspace === 'object' ? workspace : {};
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const stats = Array.isArray(workspace.stats) ? workspace.stats : [];
        const diagnostic = workspace.diagnostic && typeof workspace.diagnostic === 'object' ? workspace.diagnostic : {};
        const authority = workspace.authority_plan && typeof workspace.authority_plan === 'object' ? workspace.authority_plan : {};
        const execution = workspace.execution_plan && typeof workspace.execution_plan === 'object' ? workspace.execution_plan : {};
        const channels = Array.isArray(workspace.channels) ? workspace.channels : [];
        const linkExchange = workspace.link_exchange && typeof workspace.link_exchange === 'object' ? workspace.link_exchange : {};
        const monitoring = workspace.monitoring && typeof workspace.monitoring === 'object' ? workspace.monitoring : {};
        const report = workspace.execution_report && typeof workspace.execution_report === 'object' ? workspace.execution_report : {};
        const localSocial = workspace.local_social && typeof workspace.local_social === 'object' ? workspace.local_social : {};
        const boundary = workspace.decision_boundary && typeof workspace.decision_boundary === 'object' ? workspace.decision_boundary : {};
        const card = function(title, body, extraClass) {
            return '<section class="aysa-agent8v3-offpage-workspace-card ' + (extraClass || '') + '"><div class="aysa-agent8v3-offpage-workspace-card-head"><h3>' + escapeHtml(title) + '</h3></div>' + body + '</section>';
        };
        const keyValueGrid = function(values) {
            return '<div class="aysa-agent8v3-offpage-workspace-kv">' + values.map(function(item) {
                return '<div><span>' + escapeHtml(String(item.label || '')) + '</span><strong>' + escapeHtml(String(item.value || '-')) + '</strong></div>';
            }).join('') + '</div>';
        };
        const statsHtml = stats.map(function(item) {
            return '<div class="aysa-agent8v3-offpage-workspace-stat"><span>' + escapeHtml(String(item.label || '')) + '</span><strong>' + escapeHtml(String(item.value || '-')) + '</strong></div>';
        }).join('');
        const planRows = Array.isArray(execution.rows) ? execution.rows : [];
        const planRowsHtml = planRows.map(function(row) {
            return '<tr><td>' + escapeHtml(String(row.line_ref || '-')) + '</td><td>' + escapeHtml(String(row.target || '-')) + '</td><td>' + escapeHtml(String(row.channel || '-')) + '</td><td>' + escapeHtml(String(row.portal || '-')) + '</td><td>' + escapeHtml(String(row.status || '-')) + '</td><td>' + escapeHtml(String(row.cost || '-')) + '</td></tr>';
        }).join('');
        const planHtml = '<div class="aysa-agent8v3-offpage-workspace-plan-count"><strong>' + escapeHtml(String(execution.total || 0)) + '</strong> ' + escapeHtml(ro ? 'linii în plan' : 'lines in the plan') + '<span>' + escapeHtml(ro ? 'Afișez un rezumat; detaliile rămân în Planul de autoritate.' : 'Summary first; details remain in the Authority Plan.') + '</span></div>' +
            (planRowsHtml ? '<div class="aysa-agent8v3-offpage-workspace-table-wrap"><table><thead><tr><th>' + escapeHtml(ro ? 'Referință' : 'Reference') + '</th><th>' + escapeHtml(ro ? 'Țintă' : 'Target') + '</th><th>' + escapeHtml(ro ? 'Canal' : 'Channel') + '</th><th>' + escapeHtml(ro ? 'Portal/partener' : 'Portal/partner') + '</th><th>' + escapeHtml('Status') + '</th><th>' + escapeHtml(ro ? 'Cost' : 'Cost') + '</th></tr></thead><tbody>' + planRowsHtml + '</tbody></table></div>' : '<p class="aysa-agent8v3-offpage-workspace-muted">' + escapeHtml(ro ? 'Nu există încă linii de review.' : 'No review lines are available yet.') + '</p>');
        const channelHtml = channels.map(function(item) {
            return '<article class="aysa-agent8v3-offpage-workspace-channel"><div><strong>' + escapeHtml(String(item.label || '-')) + '</strong><span class="aysa-agent8v3-offpage-workspace-status">' + escapeHtml(String(item.status || '-')) + '</span></div><p>' + escapeHtml(String(item.detail || '-')) + '</p><small>' + escapeHtml(String(item.next || '-')) + '</small></article>';
        }).join('');
        const linkExchangeRows = Array.isArray(linkExchange.requests) ? linkExchange.requests : [];
        const linkExchangeRowsHtml = linkExchangeRows.map(function(row) {
            const status = String(row.status_label || '-');
            const ownEvidence = keyValueGrid([
                {label: ro ? 'Sursa noastră' : 'Our source', value: row.own_source_url},
                {label: ro ? 'Ținta noastră' : 'Our target', value: row.own_target_url},
                {label: ro ? 'Ancoră' : 'Anchor', value: row.own_anchor},
                {label: 'HTTP', value: Number(row.own_http_status || 0) > 0 ? String(row.own_http_status) : '-'},
                {label: ro ? 'Linkuri găsite' : 'Links found', value: row.own_link_count || 0}
            ]);
            const partnerEvidence = keyValueGrid([
                {label: ro ? 'Sursa partenerului' : 'Partner source', value: row.partner_source_url},
                {label: ro ? 'Ținta partenerului' : 'Partner target', value: row.partner_target_url},
                {label: ro ? 'Ancoră' : 'Anchor', value: row.partner_anchor},
                {label: 'HTTP', value: Number(row.partner_http_status || 0) > 0 ? String(row.partner_http_status) : '-'},
                {label: ro ? 'Linkuri găsite' : 'Links found', value: row.partner_link_count || 0}
            ]);
            return '<article class="aysa-agent8v3-offpage-workspace-link-exchange-row">' +
                '<div class="aysa-agent8v3-offpage-workspace-link-exchange-head"><div><strong>' + escapeHtml(String(row.exchange_ref || '-')) + '</strong><span>' + escapeHtml(String(row.partner || '-')) + '</span></div><span class="aysa-agent8v3-offpage-workspace-status">' + escapeHtml(status) + '</span></div>' +
                (row.explanation ? '<p class="aysa-agent8v3-offpage-workspace-muted">' + escapeHtml(String(row.explanation)) + '</p>' : '') +
                '<div class="aysa-agent8v3-offpage-workspace-link-exchange-sides"><div><strong>' + escapeHtml(ro ? 'Partea noastră' : 'Our side') + '</strong>' + ownEvidence + '<p class="aysa-agent8v3-offpage-workspace-muted">' + escapeHtml(String(row.own_readback || '')) + '</p></div><div><strong>' + escapeHtml(ro ? 'Partea partenerului' : 'Partner side') + '</strong>' + partnerEvidence + '<p class="aysa-agent8v3-offpage-workspace-muted">' + escapeHtml(String(row.partner_readback || '')) + '</p></div></div>' +
                '<div class="aysa-agent8v3-offpage-workspace-link-exchange-meta"><span>' + escapeHtml(ro ? 'Ultima verificare' : 'Last verification') + ': ' + escapeHtml(String(row.last_verified_at || '-')) + '</span><span>' + escapeHtml(ro ? 'Monitorizare' : 'Monitoring') + ': ' + escapeHtml(String(row.monitoring_status || '-')) + '</span></div>' +
            '</article>';
        }).join('');
        const linkExchangeHtml = keyValueGrid([
            {label: ro ? 'Verificate active' : 'Active verified', value: linkExchange.active_verified || 0},
            {label: ro ? 'Duplicate arhivate' : 'Archived duplicates', value: linkExchange.archived_duplicate || 0},
            {label: ro ? 'În așteptare' : 'Pending', value: linkExchange.pending || 0},
            {label: ro ? 'Probleme' : 'Issues', value: linkExchange.failed || 0},
            {label: ro ? 'Status' : 'Status', value: ro ? 'Doar verificare / preflight' : 'Read-only / preflight'}
        ]) + '<p>' + escapeHtml(String(linkExchange.message || '')) + '</p>' +
            '<p class="aysa-agent8v3-offpage-workspace-muted">' + escapeHtml(String(linkExchange.next_safe_action || '')) + '</p>' +
            (linkExchangeRowsHtml ? '<div class="aysa-agent8v3-offpage-workspace-link-exchange-list">' + linkExchangeRowsHtml + '</div>' : '<p class="aysa-agent8v3-offpage-workspace-muted">' + escapeHtml(ro ? 'Nu există încă schimburi persistente.' : 'No persistent exchanges yet.') + '</p>');
        const automatic = Array.isArray(boundary.automatic) ? boundary.automatic : [];
        const approval = Array.isArray(boundary.approval) ? boundary.approval : [];
        const listHtml = function(items) {
            return '<ul>' + items.map(function(item) { return '<li>' + escapeHtml(String(item || '')) + '</li>'; }).join('') + '</ul>';
        };
        const diagnosticHtml = keyValueGrid([
            {label: ro ? 'Run sursă' : 'Source run', value: diagnostic.source_run_id},
            {label: ro ? 'Generat' : 'Generated', value: diagnostic.generated_at},
            {label: ro ? 'Backlinkuri' : 'Backlinks', value: diagnostic.backlinks || '-'},
            {label: ro ? 'Domenii' : 'Referring domains', value: diagnostic.referring_domains || '-'},
            {label: 'Follow', value: diagnostic.follow_ratio || '-'},
            {label: ro ? 'Linkuri rupte' : 'Broken links', value: diagnostic.broken_links || '0'},
            {label: ro ? 'Risc ridicat' : 'High risk', value: diagnostic.high_risk_links || '0'},
            {label: ro ? 'Benchmark competitori' : 'Competitor benchmark', value: diagnostic.benchmark || '-'}
        ]) + '<p>' + escapeHtml(String(diagnostic.message || '')) + '</p><p class="aysa-agent8v3-offpage-workspace-muted">' + escapeHtml(String(diagnostic.benchmark_message || '')) + '</p>';
        const authorityHtml = keyValueGrid([
            {label: ro ? 'Audit sursă' : 'Source audit', value: authority.source_run_id},
            {label: ro ? 'Plan' : 'Plan', value: authority.plan_run_id},
            {label: ro ? 'Oportunități' : 'Opportunities', value: authority.opportunities},
            {label: ro ? 'Pagini țintă' : 'Target pages', value: authority.target_pages},
            {label: ro ? 'Status plan' : 'Plan status', value: authority.status}
        ]) + '<p>' + escapeHtml(String(authority.message || '')) + '</p>';
        const monitoringHtml = keyValueGrid([
            {label: 'Status', value: monitoring.status},
            {label: ro ? 'Verificate' : 'Verified', value: monitoring.verified},
            {label: ro ? 'Linkuri lipsă' : 'Missing links', value: monitoring.missing},
            {label: ro ? 'Probleme' : 'Issues', value: monitoring.issues},
            {label: ro ? 'Ultima verificare' : 'Last checked', value: monitoring.last_checked}
        ]) + '<p>' + escapeHtml(String(monitoring.message || '')) + '</p>';
        const reportHtml = keyValueGrid([
            {label: 'Status', value: report.status},
            {label: ro ? 'Verificate' : 'Verified', value: report.verified},
            {label: ro ? 'Blocate' : 'Blocked', value: report.blocked},
            {label: ro ? 'Eșuate' : 'Failed', value: report.failed}
        ]) + '<p>' + escapeHtml(String(report.message || '')) + '</p>';
        const localHtml = keyValueGrid([
            {label: ro ? 'Google Business Profile' : 'Google Business Profile', value: localSocial.status},
            {label: ro ? 'Locații' : 'Locations', value: localSocial.locations},
            {label: ro ? 'Calendar social' : 'Social calendar', value: localSocial.calendar}
        ]) + '<p>' + escapeHtml(String(localSocial.message || '')) + '</p>';
        const overviewStats = stats.slice(0, 4).map(function(item) {
            return '<div class="aysa-agent8v3-offpage-workspace-stat"><span>' + escapeHtml(String(item.label || '')) + '</span><strong>' + escapeHtml(String(item.value || '-')) + '</strong></div>';
        }).join('');
        const go = function(tab, label) {
            return '<button type="button" class="button aysa-agent8v3-modal-tab" data-tab="' + escapeHtml(tab) + '">' + escapeHtml(label) + '</button>';
        };
        const compactAuthority = keyValueGrid([
            {label: ro ? 'Oportunități' : 'Opportunities', value: authority.opportunities || 0},
            {label: ro ? 'Pagini țintă' : 'Target pages', value: authority.target_pages || 0},
            {label: ro ? 'Status' : 'Status', value: authority.status || '-'}
        ]) + '<p>' + escapeHtml(String(authority.message || (ro ? 'Revizuiește recomandările înainte de orice comandă.' : 'Review recommendations before any order.'))) + '</p>' + go('link_building_plan', ro ? 'Vezi planul de autoritate' : 'View Authority Plan');
        const compactOpportunities = keyValueGrid([
            {label: ro ? 'Linii în review' : 'Review lines', value: execution.total || 0},
            {label: ro ? 'Canale' : 'Channels', value: channels.length},
            {label: ro ? 'Cost selectat' : 'Selected cost', value: ro ? '0 până la aprobare' : '0 until approval'}
        ]) + '<p>' + escapeHtml(ro ? 'Alegi fiecare oportunitate separat. Costurile externe rămân estimări până când portalul și prețul exact sunt confirmate.' : 'Each opportunity is selected separately. External costs remain estimates until the portal and exact price are confirmed.') + '</p>' + go('order_readiness', ro ? 'Vezi oportunitățile' : 'View opportunities');
        const compactCosts = '<p>' + escapeHtml(ro ? 'Regenerarea planului cere confirmare și are un plafon separat. Vizualizarea, filtrarea și coșul nu plasează comenzi.' : 'Regenerating the plan requires confirmation and has a separate cap. Viewing, filtering, and the cart do not place orders.') + '</p>' + go('cart_preview', ro ? 'Vezi costuri și aprobări' : 'View costs and approvals');
        return '<div class="aysa-agent8v3-offpage-workspace">' +
            '<section class="aysa-agent8v3-offpage-workspace-hero"><div><span>' + escapeHtml(ro ? 'Off Page SEO' : 'Off Page SEO') + '</span><h2>' + escapeHtml(String(workspace.main_status || (ro ? 'În review' : 'In review'))) + '</h2><p>' + escapeHtml(String(workspace.main_message || (ro ? 'Ai un singur plan de revizuit. Nu se comandă nimic automat.' : 'You have one plan to review. Nothing is ordered automatically.'))) + '</p></div><span class="aysa-agent8v3-offpage-workspace-readonly">' + escapeHtml(ro ? 'Doar verificare' : 'Read-only') + '</span></section>' +
            '<div class="aysa-agent8v3-offpage-workspace-stats">' + overviewStats + '</div>' +
            card(ro ? 'Plan de autoritate' : 'Authority Plan', compactAuthority, 'is-authority') +
            card(ro ? 'Oportunități' : 'Opportunities', compactOpportunities, 'is-execution') +
            card(ro ? 'Costuri și aprobări' : 'Costs and approvals', compactCosts, 'is-costs') +
            '<details class="aysa-agent8v3-offpage-workspace-details"><summary>' + escapeHtml(ro ? 'Vezi detalii despre surse și reguli' : 'View source and safety details') + '</summary>' +
                card(ro ? 'Sursa verificată' : 'Checked source', diagnosticHtml, 'is-diagnostic') +
                '<section class="aysa-agent8v3-offpage-workspace-boundary"><div><strong>' + escapeHtml(ro ? 'Ce poate fi pregătit' : 'What can be prepared') + '</strong>' + listHtml(automatic) + '</div><div><strong>' + escapeHtml(ro ? 'Ce necesită aprobarea ta' : 'What needs your approval') + '</strong>' + listHtml(approval) + '</div></section>' +
            '</details>' +
            '</div>';
    }

    function renderOffPageExecutionReportAggregate(report, modal) {
        report = report && typeof report === 'object' ? report : {};
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const summary = Array.isArray(report.summary) ? report.summary : [];
        const sections = Array.isArray(report.sections) ? report.sections : [];
        const adverlink = report.adverlink && typeof report.adverlink === 'object' ? report.adverlink : {};
        const sectionHtml = sections.map(function(section) {
            const items = Array.isArray(section.items) ? section.items : [];
            const itemsHtml = '<div class="aysa-agent8v3-offpage-report-items">' + items.map(function(item) {
                return '<div><span>' + escapeHtml(String(item.label || '-')) + '</span><strong>' + escapeHtml(String(item.value || '-')) + '</strong></div>';
            }).join('') + '</div>';
            return '<section class="aysa-agent8v3-offpage-report-section"><div class="aysa-agent8v3-offpage-report-section-head"><h3>' + escapeHtml(String(section.title || '-')) + '</h3><span>' + escapeHtml(String(section.status || '-')) + '</span></div>' + itemsHtml + '<p>' + escapeHtml(String(section.message || '')) + '</p></section>';
        }).join('');
        const columns = Array.isArray(adverlink.columns) ? adverlink.columns : [];
        const rows = Array.isArray(adverlink.rows) ? adverlink.rows : [];
        const tableHtml = rows.length && columns.length
            ? '<div class="aysa-agent8v3-offpage-report-table-wrap"><table class="aysa-agent8v3-modal-table"><thead><tr>' + columns.map(function(column) {
                return '<th>' + escapeHtml(String(column.label || column.key || '')) + '</th>';
            }).join('') + '</tr></thead><tbody>' + rows.map(function(row) {
                return '<tr>' + columns.map(function(column) {
                    return '<td>' + escapeHtml(String(row[column.key] === undefined ? '-' : row[column.key])) + '</td>';
                }).join('') + '</tr>';
            }).join('') + '</tbody></table></div>'
            : '<p class="aysa-agent8v3-offpage-report-muted">' + escapeHtml(ro ? 'Nu există comenzi Adverlink persistente pentru acest proiect.' : 'No persisted Adverlink orders exist for this project.') + '</p>';
        return '<div class="aysa-agent8v3-offpage-report-aggregate">' +
            '<section class="aysa-agent8v3-offpage-report-intro"><div><span>' + escapeHtml(ro ? 'Raport read-only' : 'Read-only report') + '</span><h2>' + escapeHtml(String(report.title || 'Off Page execution report')) + '</h2><p>' + escapeHtml(String(report.subtitle || '')) + '</p></div><span class="aysa-agent8v3-offpage-report-badge">' + escapeHtml(ro ? 'Fără acțiuni la deschidere' : 'No actions on open') + '</span></section>' +
            '<p class="aysa-agent8v3-offpage-report-notice">' + escapeHtml(String(report.notice || '')) + '</p>' +
            '<div class="aysa-agent8v3-offpage-report-summary">' + summary.map(function(item) {
                return '<div><span>' + escapeHtml(String(item.label || '-')) + '</span><strong>' + escapeHtml(String(item.value || '-')) + '</strong></div>';
            }).join('') + '</div>' +
            '<div class="aysa-agent8v3-offpage-report-sections">' + sectionHtml + '</div>' +
            '<section class="aysa-agent8v3-offpage-report-adverlink"><div class="aysa-agent8v3-offpage-report-section-head"><div><h3>' + escapeHtml(String(adverlink.title || (ro ? 'Comenzi Adverlink / lifecycle separat' : 'Adverlink orders / separate lifecycle'))) + '</h3><p>' + escapeHtml(String(adverlink.subtitle || '')) + '</p></div><span>' + escapeHtml(String(adverlink.count || rows.length)) + '</span></div>' + tableHtml + '</section>' +
            '<p class="aysa-agent8v3-offpage-report-muted">' + escapeHtml(ro ? 'Statusurile fără dovadă durabilă rămân în review, blocate sau indisponibile; nu sunt marcate ca executate.' : 'Statuses without durable evidence remain in review, blocked, or unavailable; they are not marked executed.') + '</p>' +
            '</div>';
    }

    function renderOffPageAgentOverviewCards(rows, modal) {
        const items = Array.isArray(rows) ? rows : [];
        if (!items.length) {
            return '<div class="aysa-agent8v3-modal-empty">' + escapeHtml((modal && modal.empty_message) || 'No rows available.') + '</div>';
        }
        return '<div class="aysa-agent8v3-onpage-agent-list aysa-agent8v3-offpage-agent-list">' + items.map(function(row) {
            const area = String((row && row.area) || '-');
            const status = String((row && row.status) || '-');
            const done = String((row && row.done) || '-');
            const nextStep = String((row && (row.next_step || row.next)) || '-');
            const statusSlug = status.toLowerCase().replace(/[^a-z0-9]+/g, '-');
            return '<article class="aysa-agent8v3-onpage-agent-card aysa-agent8v3-offpage-agent-card is-' + escapeHtml(statusSlug) + '">' +
                '<div class="aysa-agent8v3-onpage-agent-card-head">' +
                    '<strong>' + escapeHtml(area) + '</strong>' +
                    renderModalChip('status', statusIcon(status), status, status) +
                '</div>' +
                '<div class="aysa-agent8v3-onpage-agent-card-grid">' +
                    '<div><span>' + escapeHtml(text('modalWhatDone')) + '</span><strong>' + escapeHtml(done) + '</strong></div>' +
                    '<div><span>' + escapeHtml(text('modalNextStepLabel')) + '</span><strong>' + escapeHtml(nextStep) + '</strong></div>' +
                '</div>' +
            '</article>';
        }).join('') + '</div>';
    }

    function renderOffPageGbpSocialCards(rows) {
        return '<div class="aysa-agent8v3-gbp-calendar-list">' + rows.map(function(row) {
            const status = String(row.status || 'scheduled');
            const type = String(row.source_type || '').trim();
            const source = String(row.source || row.source_url || '-');
            const url = String(row.source_url || '');
            const topic = String(row.post_topic || '').trim();
            const summary = String(row.caption || row.gbp_summary || '-');
            const cta = String(row.cta || '').trim();
            const safety = String(row.safety_labels || 'DRAFT ONLY | FARA PUBLICARE | FARA GBP WRITE | FARA ACTIUNI EXTERNE AUTOMATE');
            const blockedAction = String(row.next_blocked_action || 'publish_gbp_post');
            const scheduled = String(row.scheduled_for || '-');
            const deadline = String(row.review_deadline_at || '-');
            const image = String(row.image_suggestion || row.image_url || '');
            const action = row.action && typeof row.action === 'object' ? renderModalCell(row, { type: 'action' }, 'action') : '';
            return '<article class="aysa-agent8v3-gbp-calendar-card">' +
                '<div class="aysa-agent8v3-gbp-calendar-main">' +
                    '<div class="aysa-agent8v3-gbp-calendar-date"><span>Programat</span><strong>' + escapeHtml(scheduled) + '</strong></div>' +
                    '<div class="aysa-agent8v3-gbp-calendar-source">' +
                        '<div class="aysa-agent8v3-gbp-calendar-kicker">' + escapeHtml(type || 'content') + '</div>' +
                        '<strong>' + escapeHtml(source) + '</strong>' +
                        (url ? renderModalUrl(url) : '') +
                    '</div>' +
                    (topic ? '<div class="aysa-agent8v3-gbp-calendar-topic"><span>Topic</span><strong>' + escapeHtml(topic) + '</strong></div>' : '') +
                    '<div class="aysa-agent8v3-gbp-calendar-copy">' + escapeHtml(summary) + '</div>' +
                    '<div class="aysa-agent8v3-gbp-calendar-safety">' +
                        '<span>' + escapeHtml(safety) + '</span>' +
                        '<br><small>' + escapeHtml('Blocked next action: ' + blockedAction) + '</small>' +
                    '</div>' +
                '</div>' +
                '<div class="aysa-agent8v3-gbp-calendar-side">' +
                    (image ? '<a class="aysa-agent8v3-gbp-calendar-image" href="' + escapeHtml(image) + '" target="_blank" rel="noopener noreferrer"><img src="' + escapeHtml(image) + '" alt=""></a>' : '<div class="aysa-agent8v3-gbp-calendar-image is-empty">Text only</div>') +
                    '<div class="aysa-agent8v3-gbp-calendar-meta">' + renderModalChip('status', statusIcon(status), localizedModalValue('status', status), status) + (cta ? renderModalChip('cta', '', cta, cta) : '') + '<span>Reject până la<br><strong>' + escapeHtml(deadline) + '</strong></span></div>' +
                    (action ? '<div class="aysa-agent8v3-gbp-calendar-action">' + action + '</div>' : '') +
                '</div>' +
            '</article>';
        }).join('') + '</div>';
    }

    function renderOffPageBacklinkAuditCards(rows, modal) {
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const saved = modal && modal.saved_report && typeof modal.saved_report === 'object' ? modal.saved_report : {};
        const fresh = modal && modal.fresh_audit_preflight && typeof modal.fresh_audit_preflight === 'object' ? modal.fresh_audit_preflight : {};
        const dependency = modal && modal.authority_plan_dependency && typeof modal.authority_plan_dependency === 'object' ? modal.authority_plan_dependency : {};
        const provider = String(saved.provider || (modal && modal.provider) || '').trim();
        const generated = String(saved.generated_at || (modal && modal.generated_at) || '').trim();
        const strategy = modal && modal.strategy_summary && typeof modal.strategy_summary === 'object' ? modal.strategy_summary : {};
        const neededLinks = String(strategy.needed_links || '').trim();
        const verdict = String(strategy.verdict || '').trim();
        const freshness = String((saved.freshness && saved.freshness.label) || '').trim();
        const sourceRunId = Number(saved.source_run_id || 0);
        const metrics = saved.metrics && typeof saved.metrics === 'object' ? saved.metrics : {};
        const metric = function(key) { return String(metrics[key] === undefined ? '-' : metrics[key]); };
        const savedReport = saved.available
            ? '<section class="aysa-agent8v3-backlink-audit-report is-saved">' +
                '<h3>' + escapeHtml(ro ? 'Raport existent' : 'Saved report') + '</h3>' +
                '<p>' + escapeHtml(ro ? 'Acesta este cel mai recent raport salvat. Nu consumă credite și nu apelează providerul.' : 'This is the latest saved report. It uses no credits and does not call the provider.') + '</p>' +
                '<div class="aysa-agent8v3-backlink-audit-report-meta">' +
                    '<span>' + escapeHtml(ro ? 'Generat' : 'Generated') + '<strong>' + escapeHtml(generated || '-') + '</strong></span>' +
                    '<span>' + escapeHtml(ro ? 'Run sursă' : 'Source run') + '<strong>' + escapeHtml(sourceRunId > 0 ? String(sourceRunId) : '-') + '</strong></span>' +
                    '<span>' + escapeHtml(ro ? 'Sursă' : 'Source') + '<strong>' + escapeHtml(provider || '-') + '</strong></span>' +
                    '<span>' + escapeHtml(ro ? 'Prospețime' : 'Freshness') + '<strong>' + escapeHtml(freshness || '-') + '</strong></span>' +
                '</div>' +
                '<div class="aysa-agent8v3-backlink-audit-report-metrics">' +
                    '<span>' + escapeHtml(ro ? 'Backlinkuri' : 'Backlinks') + '<strong>' + escapeHtml(metric('backlinks')) + '</strong></span>' +
                    '<span>' + escapeHtml(ro ? 'Domenii' : 'Referring domains') + '<strong>' + escapeHtml(metric('referring_domains')) + '</strong></span>' +
                    '<span>' + escapeHtml('Follow / nofollow') + '<strong>' + escapeHtml(metric('follow_links') + ' / ' + metric('nofollow_links')) + '</strong></span>' +
                    '<span>' + escapeHtml(ro ? 'Linkuri rupte' : 'Broken links') + '<strong>' + escapeHtml(metric('broken_links')) + '</strong></span>' +
                '</div>' +
            '</section>'
            : '<section class="aysa-agent8v3-backlink-audit-report is-saved is-empty"><h3>' + escapeHtml(ro ? 'Raport existent' : 'Saved report') + '</h3><p>' + escapeHtml(ro ? 'Nu există încă un raport salvat pentru această țintă.' : 'No saved report exists for this target yet.') + '</p></section>';
        const freshAudit = '<section class="aysa-agent8v3-backlink-audit-report is-preflight">' +
            '<h3>' + escapeHtml(ro ? 'Audit nou' : 'Fresh audit') + '</h3>' +
            '<p>' + escapeHtml(ro ? 'Un audit nou poate dura câteva minute și poate consuma credite după confirmarea costului. Îți trimitem email când auditul este finalizat.' : 'A fresh audit may take a few minutes and may use credits after cost confirmation. We will email you when it is complete.') + '</p>' +
            '<div class="aysa-agent8v3-backlink-audit-report-meta">' +
                '<span>' + escapeHtml(ro ? 'Estimare' : 'Estimate') + '<strong>' + escapeHtml(String(fresh.estimate_credits || 45)) + ' credite</strong></span>' +
                '<span>' + escapeHtml(ro ? 'Plafon maxim' : 'Maximum cap') + '<strong>' + escapeHtml(String(fresh.max_total_cost || 45)) + ' credite</strong></span>' +
                '<span>' + escapeHtml(ro ? 'Înainte de aprobare' : 'Before approval') + '<strong>' + escapeHtml(ro ? 'Fără provider și fără debit' : 'No provider and no debit') + '</strong></span>' +
            '</div>' +
        '</section>';
        const dependencyCopy = dependency.status === 'source_ready_separate_approval_required'
            ? (ro ? 'Planul de autoritate folosește acest raport ca sursă. Generarea planului cere cost, plafon și aprobare separate.' : 'The Authority Plan uses this report as its source. Plan generation needs separate cost, cap, and approval.')
            : (ro ? 'Planul de autoritate așteaptă un raport verificat și acceptarea prospețimii lui.' : 'The Authority Plan is waiting for a verified report and accepted freshness.');
        const dependencyHtml = '<section class="aysa-agent8v3-backlink-audit-dependency"><strong>' + escapeHtml(ro ? 'Planul de autoritate' : 'Authority Plan') + '</strong><p>' + escapeHtml(dependencyCopy) + '</p></section>';
        const meta = savedReport + freshAudit + dependencyHtml;
        const strategyHtml = neededLinks || verdict
            ? '<div class="aysa-agent8v3-backlink-strategy-summary">' +
                '<div><span>Concluzie backlink</span><strong>' + escapeHtml(verdict || 'Strategy generated') + '</strong></div>' +
                '<div><span>Linkuri recomandate</span><strong>' + escapeHtml(neededLinks || '0') + '</strong></div>' +
            '</div>'
            : '';
        return meta + strategyHtml + '<div class="aysa-agent8v3-backlink-audit-list">' + rows.map(function(row) {
            const risk = String(row.risk || '-');
            const domain = String(row.referring_domain || '-');
            const anchor = String(row.anchor_text || '-');
            const follow = String(row.follow || '-');
            const health = String(row.health || '-');
            const issue = String(row.issue_message || '-');
            const firstSeen = String(row.first_seen || '');
            const lastSeen = String(row.last_seen || '');
            return '<article class="aysa-agent8v3-backlink-audit-card is-risk-' + escapeHtml(risk.toLowerCase().replace(/[^a-z0-9]+/g, '-')) + '">' +
                '<div class="aysa-agent8v3-backlink-audit-head">' +
                    '<div><span>Domeniu referent</span><strong>' + escapeHtml(domain) + '</strong></div>' +
                    renderModalChip('risk-' + risk, backlinkRiskIcon(risk), risk, risk) +
                '</div>' +
                '<div class="aysa-agent8v3-backlink-audit-route">' +
                    '<div><span>Source</span>' + renderModalUrl(row.source_url) + '</div>' +
                    '<b aria-hidden="true">→</b>' +
                    '<div><span>Target</span>' + renderModalUrl(row.target_url) + '</div>' +
                '</div>' +
                '<div class="aysa-agent8v3-backlink-audit-details">' +
                    '<div><span>Anchor</span><strong>' + escapeHtml(anchor) + '</strong></div>' +
                    '<div><span>Link</span><strong>' + escapeHtml(follow) + '</strong></div>' +
                    '<div><span>Health</span><strong>' + escapeHtml(health) + '</strong></div>' +
                    '<div><span>Seen</span><strong>' + escapeHtml([firstSeen, lastSeen].filter(Boolean).join(' → ') || '-') + '</strong></div>' +
                '</div>' +
                '<div class="aysa-agent8v3-backlink-audit-issue"><span>Issue</span><strong>' + escapeHtml(issue) + '</strong></div>' +
            '</article>';
        }).join('') + '</div>';
    }

    function backlinkRiskIcon(value) {
        const raw = String(value || '').toLowerCase();
        if (raw.indexOf('high') !== -1) return '!';
        if (raw.indexOf('medium') !== -1) return '◐';
        if (raw.indexOf('low') !== -1) return '✓';
        return '•';
    }

    function modalColumnClass(column, key) {
        const classes = [];
        if (column && column.type === 'action') {
            classes.push('is-action');
        }
        if (key) {
            classes.push('is-col-' + String(key).replace(/[^a-z0-9_-]/gi, '_'));
        }
        return classes.length ? ' class="' + classes.join(' ') + '"' : '';
    }

    function renderModalTabs(modal) {
        $('.aysa-agent8v3-modal-tabs').remove();
        const tabs = Array.isArray(modal.tabs) ? modal.tabs : [];
        if (!tabs.length) {
            return;
        }
        if (state.modal.workspace) {
            renderWorkspaceTabs(modal, tabs);
            return;
        }
        if ((String(modal.modal_key || '') === 'onpage_seo' || String(modal.modal_key || '') === 'offpage_seo' || String(modal.modal_key || '') === 'monitoring') && !modal.advanced_tabs_visible) {
            const label = String(modal.advanced_tabs_label || 'Detalii avansate');
            $('.aysa-agent8v3-modal-toolbar').before('<div class="aysa-agent8v3-modal-tabs is-advanced-toggle"><button type="button" class="aysa-agent8v3-modal-tab aysa-agent8v3-advanced-toggle" data-advanced="1">' + escapeHtml(label) + '</button></div>');
            return;
        }
        const active = String(modal.active_tab || (modal.filters && modal.filters.tab) || tabs[0].key || '');
        const html = '<div class="aysa-agent8v3-modal-tabs" role="tablist">' + tabs.map(function(tab) {
            const key = String(tab.key || '');
            const cls = key === active ? ' is-active' : '';
            const selected = key === active ? 'true' : 'false';
            return '<button type="button" role="tab" class="aysa-agent8v3-modal-tab' + cls + '" data-tab="' + escapeHtml(key) + '" aria-selected="' + selected + '">' + escapeHtml(clientFacingLabel(tab.label || key)) + '</button>';
        }).join('') + '</div>';
        $('.aysa-agent8v3-modal-toolbar').before(html);
    }

    function renderWorkspaceTabs(modal, tabs) {
        const modalKey = String(modal.modal_key || '');
        const active = String(modal.active_tab || (modal.filters && modal.filters.tab) || tabs[0].key || '');
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const coreMap = {
            offpage_seo: ['overview', 'link_building_plan', 'order_readiness', 'cart_preview'],
            monitoring: ['serp_positions', 'gsc_performance', 'ai_visibility'],
            technical_site_audit: ['safe_bundle', 'site_audit', 'issues'],
            onpage_seo: ['overview', 'meta_snippets', 'content'],
            content_plan: ['overview'],
            research_keywords: ['overview'],
            keyword_mapping: ['overview'],
            missing_pages: ['overview']
        };
        const coreKeys = coreMap[modalKey] || [tabs[0].key];
        const labelFor = function(tab) {
            const key = String(tab.key || '');
            if (modalKey === 'monitoring' && key === 'refresh_preflight') {
                return ro ? 'Verifică acoperirea și costul' : 'Check coverage and cost';
            }
            if (modalKey === 'offpage_seo') {
                const labels = {
                    overview: ro ? 'Rezumat' : 'Overview',
                    link_building_plan: ro ? 'Plan de autoritate' : 'Authority Plan',
                    order_readiness: ro ? 'Oportunități' : 'Opportunities',
                    cart_preview: ro ? 'Costuri și aprobări' : 'Costs and approvals'
                };
                if (labels[key]) {
                    return labels[key];
                }
            }
            return clientFacingLabel(tab.label || key);
        };
        const button = function(tab) {
            const key = String(tab.key || '');
            const cls = key === active ? ' is-active' : '';
            return '<button type="button" class="aysa-agent8v3-modal-tab' + cls + '" data-tab="' + escapeHtml(key) + '" aria-selected="' + (key === active ? 'true' : 'false') + '">' + escapeHtml(labelFor(tab)) + '</button>';
        };
        const core = tabs.filter(function(tab) { return coreKeys.indexOf(String(tab.key || '')) !== -1; });
        const more = tabs.filter(function(tab) { return coreKeys.indexOf(String(tab.key || '')) === -1; });
        const html = '<nav class="aysa-agent8v3-modal-tabs aysa-agent8v3-workspace-tabs" aria-label="' + escapeHtml(ro ? 'Secțiuni modul' : 'Module sections') + '">' +
            core.map(button).join('') +
            (more.length ? '<details class="aysa-agent8v3-workspace-tabs-more"><summary>' + escapeHtml(ro ? 'Mai multe' : 'More') + '</summary>' + more.map(button).join('') + '</details>' : '') +
        '</nav>';
        $('.aysa-agent8v3-modal-toolbar').before(html);
    }

    function renderLaunchUxNotice(modal) {
        modal = modal && typeof modal === 'object' ? modal : {};
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const modalKey = String(modal.modal_key || '');
        const activeTab = String(modal.active_tab || (modal.filters && modal.filters.tab) || '');
        const notice = function(title, body, badges) {
            const badgeHtml = Array.isArray(badges) && badges.length
                ? '<div class="aysa-agent8v3-action-badges">' + badges.map(function(badge) {
                    return '<span class="aysa-agent8v3-action-badge">' + escapeHtml(clientFacingLabel(badge)) + '</span>';
                }).join('') + '</div>'
                : '';
            return '<div class="aysa-agent8v3-safe-bundle-note aysa-agent8v3-launch-ux-note">' +
                '<strong>' + escapeHtml(title) + '</strong>' +
                '<p>' + escapeHtml(body) + '</p>' +
                badgeHtml +
            '</div>';
        };
        if (modalKey === 'content_plan') {
            return notice(
                ro ? 'Content Plan nu înseamnă publicare' : 'Content Plan does not mean publishing',
                ro ? 'Plan aprobat = idee aprobată, nu articol publicat. Generarea și publicarea sunt pași separați și cer confirmare separată.' : 'Approved plan = approved idea, not a published article. Generation and publishing are separate steps and require separate confirmation.',
                [ro ? 'Fără publicare automată' : 'No automatic publishing', ro ? 'Generarea se aprobă separat' : 'Generation is approved separately']
            );
        }
        if (modalKey === 'onpage_seo' && activeTab === 'meta_snippets') {
            return notice(
                ro ? 'Metadata: propuneri înainte de aplicare' : 'Metadata: proposals before apply',
                ro ? 'Poți pregăti titluri și descrieri pentru Google. Acest pas nu modifică site-ul; aplicarea se face separat, doar după confirmare.' : 'You can prepare Google titles and descriptions. This step does not change the site; applying is separate and requires confirmation.',
                [ro ? 'Nu modifică site-ul' : 'No site changes', ro ? 'Vei vedea costul înainte de generare' : 'Cost shown before generation', ro ? 'Aplicarea se face separat' : 'Apply is separate']
            );
        }
        if (modalKey === 'offpage_seo') {
            return notice(
                ro ? 'Off Page: plan și verificări înainte de comandă' : 'Off Page: plan and checks before ordering',
                ro ? 'Deschiderea acestui ecran nu plasează comenzi, nu cheamă provideri și nu consumă credite. Costurile și portalurile apar înainte de orice comandă externă.' : 'Opening this screen does not place orders, call providers, or use credits. Costs and portals are shown before any external order.',
                [ro ? 'Fără comandă la deschidere' : 'No order on open', ro ? 'Fără provider la deschidere' : 'No provider on open', ro ? 'Cost înainte de execuție' : 'Cost before execution']
            );
        }
        if (modalKey === 'monitoring') {
            const policy = modal.monitoring_policy && typeof modal.monitoring_policy === 'object'
                ? modal.monitoring_policy
                : {};
            const isActive = String(policy.status || '') === 'confirmed' && !policy.requires_reconfirmation;
            return notice(
                ro ? 'Monitorizare: date separate' : 'Monitoring: separate data',
                isActive
                    ? (ro ? 'Pozițiile Google și Search Console se actualizează la frecvența aleasă în Profil SEO. Vizibilitatea AI necesită aprobare separată.' : 'Google positions and Search Console update at the frequency selected in SEO Profile. AI visibility needs separate approval.')
                    : (ro ? 'Pozițiile Google și Search Console vor începe după confirmarea setărilor. Vizibilitatea AI necesită aprobare separată.' : 'Google positions and Search Console start after the settings are confirmed. AI visibility needs separate approval.'),
                [ro ? 'Fără modificări SEO' : 'No SEO changes', ro ? 'AI necesită aprobare separată' : 'AI needs separate approval']
            );
        }
        return '';
    }

    function renderModalActions(actions, modal) {
        if (!actions.length) {
            return '';
        }
        actions = filterModalActionsForActiveView(actions, modal || {});
        if (String((modal && modal.modal_key) || '') === 'monitoring') {
            const policy = modal && modal.monitoring_policy && typeof modal.monitoring_policy === 'object'
                ? modal.monitoring_policy
                : {};
            actions = actions.filter(function(action) {
                return ['configure_monitoring_policy', 'settle_monitoring_rank_tracking_over_cap']
                    .indexOf(String(action && action.action || '')) !== -1;
            });
        }
        if (!actions.length) {
            return '';
        }
        return actions.map(function(action) {
            const summary = action.summary || {};
            const technicalFixExecution = isTechnicalFixExecutionAction(action);
            const noExecutablePlan = modalActionRequiresExecutablePlan(action) && !modalActionHasExecutablePlan(action);
            const actionPayload = action.payload && typeof action.payload === 'object' ? Object.assign({}, action.payload) : {};
            if (String(action.action || '') === 'configure_monitoring_policy'
                && modal
                && modal.monitoring_policy
                && typeof modal.monitoring_policy === 'object') {
                actionPayload.estimated_cost_credits = modal.monitoring_policy.estimated_cost_credits || actionPayload.estimated_cost_credits || 0;
                actionPayload.enabled_sources = Array.isArray(modal.monitoring_policy.sources) && modal.monitoring_policy.sources.length
                    ? modal.monitoring_policy.sources.slice()
                    : actionPayload.enabled_sources;
            }
            const monitoringRefreshPendingPreflight = String(action.action || '') === 'refresh_monitoring_rank_tracking'
                && !monitoringSerpPreflightReady();
            const metadataGateSetupAction = action.action === 'execute_technical_fix_plan'
                && actionPayload.confirmation_kind === 'technical_metadata_apply'
                && actionPayload.metadata_gate_setup_required;
            const disabled = (action.disabled && !metadataGateSetupAction) || !action.action || noExecutablePlan || monitoringRefreshPendingPreflight ? ' disabled' : '';
            const statusLabel = technicalFixExecution ? technicalFixExecutionStatusLabel(action.status) : modalLabel(action.status, action.status);
            const progress = technicalFixExecution ? renderTechnicalFixExecutionProgress(action.progress || {}) : '';
            const status = action.status && !progress ? '<span class="aysa-agent8v3-modal-action-status">' + escapeHtml(statusLabel) + '</span>' : '';
            const planGuard = noExecutablePlan ? '<span class="aysa-agent8v3-modal-action-status is-warning">' + escapeHtml(text('modalNoExecutableFixes')) + '</span>' : '';
            const summaryKeys = technicalFixExecution ? technicalFixExecutionSummaryKeys() : ['total', 'accepted', 'rejected', 'filtered', 'included', 'remaining', 'executable', 'manual_needed', 'queued', 'applied', 'skipped', 'failed'];
            const counts = modal && modal.hide_action_summary ? '' : summaryKeys.map(function(key) {
                if (summary[key] === undefined) {
                    return '';
                }
                const summaryLabel = technicalFixExecution ? technicalFixExecutionSummaryLabel(key) : modalLabel(key, key);
                return '<span><strong>' + escapeHtml(String(summary[key])) + '</strong> ' + escapeHtml(summaryLabel) + '</span>';
            }).join('');
            const payload = escapeHtml(JSON.stringify(monitoringRefreshPayloadForCurrentPreflight(action.action, actionPayload).payload));
            const display = normalizeActionDisplayForAction(action, modal);
            return '<div class="aysa-agent8v3-modal-actionbar">' +
                '<div class="aysa-agent8v3-modal-action-summary">' + counts + status + planGuard + progress + '</div>' +
                '<div class="aysa-agent8v3-action-with-badges">' +
                    '<button type="button" class="button button-primary aysa-agent8v3-modal-action" data-action="' + escapeHtml(action.action || '') + '" data-payload="' + payload + '"' + disabled + '>' + escapeHtml(display.label) + '</button>' +
                    actionBadgesHtml(display.badges) +
                '</div>' +
                '</div>';
        }).join('');
    }

    function monitoringSerpPreflightReady() {
        const preflight = state.monitoringRefreshPreflight && typeof state.monitoringRefreshPreflight === 'object'
            ? state.monitoringRefreshPreflight
            : {};
        return String(preflight.status || '') === 'ready_for_cost_cap'
            && (parseInt(preflight.included_keywords_count || preflight.included_targets_count || 0, 10) || 0) > 0
            && (parseInt(preflight.estimated_cost_credits || 0, 10) || 0) > 0;
    }

    function monitoringRefreshPayloadForCurrentPreflight(action, payload) {
        payload = payload && typeof payload === 'object' ? Object.assign({}, payload) : {};
        if (String(action || '') === 'configure_monitoring_policy') {
            const policy = state.modal.current && state.modal.current.monitoring_policy && typeof state.modal.current.monitoring_policy === 'object'
                ? state.modal.current.monitoring_policy
                : {};
            // Preserve the estimate rendered with the policy action when the dialog is mounted in the workspace.
            const estimated = parseInt(policy.estimated_cost_credits || payload.estimated_cost_credits || 0, 10) || 0;
            const perRunInput = $('#aysa-agent8v3-monitoring-policy-per-run-cap');
            const monthlyInput = $('#aysa-agent8v3-monitoring-policy-monthly-cap');
            const perRun = perRunInput.length ? (parseInt(String(perRunInput.val() || ''), 10) || 0) : (parseInt(payload.per_run_cap_cents || 0, 10) || 0);
            const monthly = monthlyInput.length ? (parseInt(String(monthlyInput.val() || ''), 10) || 0) : (parseInt(payload.monthly_budget_cents || 0, 10) || 0);
            if (estimated <= 0 || perRun < estimated || monthly < perRun) {
                return {
                    ok: false,
                    payload: payload,
                    message: String(uiLanguage() || '').indexOf('ro') === 0
                        ? 'Alege o estimare disponibilă, un plafon pentru actualizare cel puțin egal cu estimarea și un buget lunar cel puțin egal cu plafonul.'
                        : 'Choose an available estimate, a per-update cap at least equal to the estimate, and a monthly budget at least equal to that cap.'
                };
            }
            payload.enabled_sources = Array.isArray(policy.sources) && policy.sources.length
                ? policy.sources.slice()
                : (Array.isArray(payload.enabled_sources) && payload.enabled_sources.length ? payload.enabled_sources.slice() : ['serp', 'gsc']);
            payload.per_run_cap_cents = perRun;
            payload.monthly_budget_cents = monthly;
            payload.auto_execute_within_policy = true;
            payload.initial_baseline_after_confirmation = true;
            return { ok: true, payload: payload };
        }
        if (String(action || '') !== 'refresh_monitoring_rank_tracking') {
            return { ok: true, payload: payload };
        }
        const preflight = state.monitoringRefreshPreflight && typeof state.monitoringRefreshPreflight === 'object'
            ? state.monitoringRefreshPreflight
            : {};
        const estimatedCredits = parseInt(preflight.estimated_cost_credits || 0, 10) || 0;
        if (!monitoringSerpPreflightReady()) {
            return {
                ok: false,
                payload: payload,
                message: String(uiLanguage() || '').indexOf('ro') === 0
                    ? 'Pregătește mai întâi estimarea pentru actualizarea pozițiilor Google.'
                    : 'Prepare the Google positions update estimate first.'
            };
        }
        const capInput = $('#aysa-agent8v3-monitoring-serp-cost-cap');
        const requestedCap = capInput.length ? (parseInt(String(capInput.val() || ''), 10) || 0) : estimatedCredits;
        if (requestedCap < estimatedCredits) {
            return {
                ok: false,
                payload: payload,
                message: String(uiLanguage() || '').indexOf('ro') === 0
                    ? 'Costul maxim trebuie să fie cel puțin ' + estimatedCredits + ' credite, cât estimarea acestei verificări.'
                    : 'The maximum cost must be at least ' + estimatedCredits + ' credits, the estimate for this check.'
            };
        }
        payload.max_total_cost = requestedCap;
        payload.max_cost_cents = requestedCap;
        payload.estimated_cost_credits = estimatedCredits;
        payload.estimated_max_cost_label = requestedCap + (String(uiLanguage() || '').indexOf('ro') === 0 ? ' credite' : ' credits');
        payload.no_seo_write = true;
        return { ok: true, payload: payload };
    }

    function normalizeActionDisplayForAction(action, modal) {
        action = action && typeof action === 'object' ? action : {};
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const actionName = String(action.action || '');
        const originalLabel = action.label || text(actionName || '') || actionName || 'Action';
        const display = normalizeActionDisplay(originalLabel, action.badges || []);
        const payload = action.payload && typeof action.payload === 'object' ? action.payload : {};
        const modalKey = String((modal && modal.modal_key) || '');
        const tab = String((modal && (modal.active_tab || (modal.filters && modal.filters.tab))) || '');
        const normalizedLabel = String(originalLabel || '').toLowerCase();
        const addBadge = function(label) {
            const clean = clientFacingLabel(label);
            if (clean && display.badges.indexOf(clean) === -1) {
                display.badges.push(clean);
            }
        };
        if (actionName === 'generate_offpage_backlink_strategy') {
            display.label = ro ? 'Generează / regenerează Plan de autoritate' : 'Generate / regenerate Authority Plan';
            display.badges = [];
            addBadge(ro ? 'Necesită confirmare' : 'Requires confirmation');
            addBadge(ro ? '45 credite' : '45 credits');
            addBadge(ro ? 'Nu comandă linkuri' : 'Does not order links');
            addBadge(ro ? 'Nu creează articole' : 'Does not create articles');
            addBadge(ro ? 'Nu publică reclame text' : 'Does not publish text ads');
            addBadge(ro ? 'Nu face modificări în WordPress' : 'Does not modify WordPress');
            addBadge(ro ? 'Execuția recomandărilor este separată' : 'Recommendation execution is separate');
            return display;
        }
        if (actionName === 'configure_monitoring_policy') {
            display.label = ro ? 'Confirmă monitorizarea automată' : 'Confirm automatic monitoring';
            display.badges = [];
            addBadge(ro ? 'Primul baseline pornește după confirmare' : 'First baseline starts after confirmation');
            addBadge(ro ? 'SERP se taxează după date salvate' : 'SERP bills after saved data');
            addBadge(ro ? 'Search Console fără debit AYSA' : 'Search Console has no AYSA debit');
            return display;
        }
        if (actionName === 'settle_monitoring_rank_tracking_over_cap') {
            display.label = originalLabel || (ro ? 'Aprobă costul real al verificării' : 'Approve the actual check cost');
            display.badges = [];
            addBadge(ro ? 'Datele sunt deja salvate' : 'Data is already saved');
            addBadge(ro ? 'Necesită aprobare financiară' : 'Financial approval required');
            addBadge(ro ? 'Debit unic și idempotent' : 'Single idempotent debit');
            return display;
        }
        if (actionName === 'generate_onpage_meta') {
            const countMatch = String(originalLabel || '').match(/\(([^)]+)\)/);
            display.label = ro ? 'Pregătește propuneri Meta SEO' : 'Prepare SEO meta proposals';
            if (countMatch && countMatch[1]) {
                display.label += ' (' + countMatch[1] + ')';
            }
            addBadge(ro ? 'Generează propuneri' : 'Generates proposals');
            addBadge(ro ? 'Poate consuma credite' : 'May use credits');
            addBadge(ro ? 'Vei vedea costul înainte' : 'Cost shown first');
            addBadge(ro ? 'Nu modifică site-ul' : 'No site changes');
            addBadge(ro ? 'Aplicarea se face separat' : 'Apply is separate');
            return display;
        }
        if (actionName.indexOf('preflight') !== -1 || String(payload.confirmation_kind || '').indexOf('preflight') !== -1) {
            addBadge(ro ? 'Preflight fără debit' : 'Preflight, no debit');
        }
        if (actionName.indexOf('generate') !== -1 || normalizedLabel.indexOf('generează') !== -1 || normalizedLabel.indexOf('generate') !== -1) {
            addBadge(ro ? 'Generează propuneri' : 'Generates proposals');
        }
        if (actionName.indexOf('apply') !== -1 || actionName.indexOf('execute_technical_fix_plan') !== -1 || actionName.indexOf('execute_onpage_plan') !== -1) {
            addBadge(ro ? 'Necesită confirmare înainte de aplicare' : 'Requires confirmation before apply');
            addBadge(ro ? 'Aplică modificări pe site' : 'Applies site changes');
        }
        if (actionName.indexOf('publish') !== -1 || normalizedLabel.indexOf('public') !== -1) {
            addBadge(ro ? 'Publicare' : 'Publishing');
        }
        if (
            modalKey === 'offpage_seo'
            && (
                actionName.indexOf('order') !== -1
                || actionName.indexOf('provider') !== -1
                || actionName.indexOf('adverlink') !== -1
                || actionName.indexOf('publisher') !== -1
                || actionName.indexOf('seo_text_ads') !== -1
            )
        ) {
            addBadge(ro ? 'Comandă externă / provider' : 'External order / provider');
            addBadge(ro ? 'Necesită confirmare finală' : 'Requires final confirmation');
        }
        if (modalKey === 'content_plan' || tab === 'content_plan') {
            addBadge(ro ? 'Generarea și publicarea sunt pași separați' : 'Generation and publishing are separate');
        }
        if (!display.badges.length && (action.disabled || normalizedLabel.indexOf('review') !== -1 || normalizedLabel.indexOf('verific') !== -1)) {
            addBadge(ro ? 'Fără cost / doar verificare' : 'Free / review only');
        }
        return display;
    }

    function normalizeActionDisplay(label, badges) {
        let clean = String(label || '');
        const out = Array.isArray(badges) ? badges.slice() : [];
        const patterns = [
            { re: /\s*\(Plugin wallet \/ Adverlink\)/i, badge: 'Plugin wallet' },
            { re: /\s*·\s*cere aprobare/i, badge: 'Necesită confirmare înainte de aplicare' },
            { re: /\s*·\s*requires approval/i, badge: 'Requires confirmation before apply' },
            { re: /\s*\(marketplace lookup,\s*fără comandă\)/i, badge: 'Fără cost / doar verificare' },
            { re: /\s*\(marketplace lookup,\s*no order\)/i, badge: 'Free / review only' },
            { re: /\s*\(trimite email,\s*fără comandă\)/i, badge: 'Doar email, fără comandă' },
            { re: /\s*\(sends email,\s*no order\)/i, badge: 'Email only, no order' },
            { re: /\s*\(poate costa[^)]*\)/i, badge: 'Poate consuma credite' },
            { re: /\s*\(May cost[^)]*\)/i, badge: 'May use credits' }
        ];
        patterns.forEach(function(pattern) {
            if (pattern.re.test(clean)) {
                clean = clean.replace(pattern.re, '');
                out.push(pattern.badge);
            }
        });
        if (out.indexOf('Plugin wallet') !== -1 && out.indexOf('Adverlink') === -1) {
            out.push('Adverlink');
        }
        return { label: clean.trim() || String(label || ''), badges: out.filter(function(value, index, list) {
            return value && list.indexOf(value) === index;
        }).map(function(value) {
            return clientFacingLabel(value);
        }) };
    }

    function actionBadgesHtml(badges) {
        if (!Array.isArray(badges) || !badges.length) {
            return '';
        }
        return '<span class="aysa-agent8v3-action-badges">' + badges.map(function(badge) {
            const label = clientFacingLabel(String(badge || '').trim());
            if (!label) {
                return '';
            }
            const slug = label.toLowerCase().replace(/[^a-z0-9]+/g, '-');
            return '<span class="aysa-agent8v3-action-badge is-' + escapeHtml(slug) + '">' + escapeHtml(label) + '</span>';
        }).join('') + '</span>';
    }

    function confirmOnPageApplyAndMark(payload, button) {
        payload = payload && typeof payload === 'object' ? payload : {};
        const ro = state.language === 'Romanian' || String(uiLanguage() || '').indexOf('ro') === 0;
        const writeClass = String(payload.write_class || '');
        let selectedItems = [];
        if (writeClass === 'onpage_metadata_apply' && $('.aysa-agent8v3-onpage-metadata-apply-row').length) {
            selectedItems = selectedOnPageMetadataApplyItems();
            if (!selectedItems.length) {
                window.alert(ro
                    ? 'Selectează cel puțin un rând Metadata înainte de aplicare.'
                    : 'Select at least one Metadata row before applying.');
                return false;
            }
            const liveSelectionHash = onPageMetadataSelectionHash(selectedItems);
            const confirmedSelectionHash = String(state.modal.onpageMetadataConfirmedSelectionHash || '');
            const confirmedItems = Array.isArray(state.modal.onpageMetadataConfirmedItems)
                ? state.modal.onpageMetadataConfirmedItems
                : [];
            if (confirmedSelectionHash !== ''
                && liveSelectionHash === confirmedSelectionHash
                && onPageMetadataSelectionHash(confirmedItems) === confirmedSelectionHash) {
                selectedItems = confirmedItems.map(function(item) {
                    return Object.assign({}, item);
                });
            }
            const unit = Math.max(1, parseInt(payload.billing_unit_cents || 5, 10) || 5);
            payload.source_workspace_hash = String(payload.workspace_hash || '');
            payload.workspace_hash = '';
            payload.accepted_items = selectedItems;
            payload.selection = selectedItems.map(function(item) { return item.entity_key; });
            payload.selection_model = 'explicit_selected_rows';
            payload.worker_batch_size = selectedItems.length;
            payload.included_count = selectedItems.length;
            payload.requested_count = selectedItems.length;
            payload.max_rows = selectedItems.length;
            payload.max_cost_cents = selectedItems.length * 2 * unit;
            payload.max_total_cost_cents = payload.max_cost_cents;
        }
        const selected = Array.isArray(payload.selection) ? payload.selection.length : (Array.isArray(payload.accepted_items) ? payload.accepted_items.length : 0);
        const maxCost = parseInt(payload.max_cost_cents || 0, 10) || 0;
        const unitCost = parseInt(payload.billing_unit_cents || 5, 10) || 5;
        const message = writeClass === 'onpage_content_rewrite_apply' && payload.op26_final_write_confirmed
            ? (ro
                ? 'CONFIRMARE FINALĂ: AYSA va scrie un singur rând Content Rewrite pe targetul selectat. Cost maxim: ' + String(maxCost || unitCost) + ' credite, debitat doar dacă readback verifică schimbarea. Continuăm cu write-ul controlat?'
                : 'FINAL CONFIRMATION: AYSA will write one Content Rewrite row on the selected target. Max cost: ' + String(maxCost || unitCost) + ' credits, billed only if readback verifies the change. Continue with the controlled write?')
            : writeClass === 'onpage_content_rewrite_apply'
            ? (ro
                ? 'Content Rewrite este o schimbare high-risk. OP25 permite doar preflight/confirmare pentru un singur rând, cu gate scoped și oprire înainte de write real. Rânduri selectate: ' + String(selected) + '. Cost maxim viitor: ' + String(maxCost || unitCost) + ' credite, debitat doar după write verificat prin readback. Continuăm cu preflight-ul fără scriere?'
                : 'Content Rewrite is high-risk. OP25 allows only preflight/confirmation for one row, with a scoped gate and a stop before real write. Selected rows: ' + String(selected) + '. Future max cost: ' + String(maxCost || unitCost) + ' credits, billed only after readback verifies the write. Continue with no-write preflight?')
            : writeClass === 'onpage_metadata_apply'
            ? (ro
                ? 'Trimitem doar Metadata aprobată pentru ' + String(selected) + ' elemente. Cost maxim: ' + String(maxCost) + ' credite (' + String(unitCost) + ' / câmp schimbat și verificat). Failed/skipped/no-change nu se debitează. Continuăm?'
                : 'Submit approved metadata only for ' + String(selected) + ' items. Max cost: ' + String(maxCost) + ' credits (' + String(unitCost) + ' / changed and verified field). Failed/skipped/no-change rows are not billed. Continue?')
            : (ro
                ? 'Această acțiune On Page necesită confirmare explicită. Continuă doar dacă ai verificat clasa de scriere, câmpurile și costul maxim.'
                : 'This On Page action requires explicit confirmation. Continue only after reviewing the write class, fields and max cost.');
        if (writeClass === 'onpage_metadata_apply' && button && button.length) {
            const selectionConfirmationHash = onPageMetadataSelectionHash(selectedItems);
            if (button.attr('data-onpage-metadata-confirmed') !== '1'
                && selectionConfirmationHash !== String(state.modal.onpageMetadataConfirmedSelectionHash || '')) {
                state.modal.onpageMetadataConfirmedSelectionHash = selectionConfirmationHash;
                state.modal.onpageMetadataConfirmedItems = selectedItems.map(function(item) {
                    return Object.assign({}, item);
                });
                button.attr('data-onpage-metadata-confirmed', '1');
                button.text(ro ? 'Confirmă aplicarea optimizărilor' : 'Confirm optimization apply');
                button.closest('.aysa-agent8v3-modal-actionbar').find('.aysa-agent8v3-onpage-metadata-inline-confirm').remove();
                button.closest('.aysa-agent8v3-modal-actionbar').prepend(
                    '<div class="aysa-agent8v3-onpage-metadata-inline-confirm">' +
                    '<strong>' + escapeHtml(ro ? 'Confirmare finală Metadata' : 'Final metadata confirmation') + '</strong>' +
                    '<p>' + escapeHtml(message) + '</p>' +
                    '</div>'
                );
                return false;
            }
            if (selectionConfirmationHash !== String(state.modal.onpageMetadataConfirmedSelectionHash || '')
                || onPageMetadataSelectionHash(state.modal.onpageMetadataConfirmedItems || []) !== selectionConfirmationHash) {
                state.modal.onpageMetadataConfirmedSelectionHash = selectionConfirmationHash;
                state.modal.onpageMetadataConfirmedItems = selectedItems.map(function(item) {
                    return Object.assign({}, item);
                });
                button.attr('data-onpage-metadata-confirmed', '1');
                button.text(ro ? 'Confirmă aplicarea optimizărilor' : 'Confirm optimization apply');
                button.closest('.aysa-agent8v3-modal-actionbar').find('.aysa-agent8v3-onpage-metadata-inline-confirm').remove();
                button.closest('.aysa-agent8v3-modal-actionbar').prepend(
                    '<div class="aysa-agent8v3-onpage-metadata-inline-confirm">' +
                    '<strong>' + escapeHtml(ro ? 'Confirmare finală Metadata' : 'Final metadata confirmation') + '</strong>' +
                    '<p>' + escapeHtml(message) + '</p>' +
                    '</div>'
                );
                return false;
            }
        } else if (!window.confirm(message)) {
            return false;
        }
        if (writeClass === 'onpage_content_rewrite_apply') {
            payload.confirmation_kind = 'onpage_content_rewrite_apply';
            if (payload.op26_final_write_confirmed) {
                payload.stop_before_write = false;
                payload.writes_enabled = true;
                payload.billing_status = 'content_rewrite_real_billing';
                payload.billing_action_key = 'agent8v3_onpage_content_rewrite_apply';
            } else {
                payload.op25_preflight_confirmed = true;
                payload.stop_before_write = true;
            }
        } else if (writeClass === 'onpage_metadata_apply') {
            payload.confirmation_kind = 'onpage_seo_apply_accepted_bundle';
            payload.selection_model = payload.selection_model === 'explicit_selected_rows'
                ? 'explicit_selected_rows'
                : 'accept_all_safe_unless_rejected';
            payload.onpage_seo_apply_accepted_bundle = true;
            payload.user_confirmed = true;
        }
        payload.confirmed_by_user = true;
        return true;
    }

    function confirmOnPageMetaGenerationAndMark(payload) {
        payload = payload && typeof payload === 'object' ? payload : {};
        const ro = state.language === 'Romanian';
        const selection = Array.isArray(payload.selection) ? payload.selection : [];
        const selected = selection.length;
        const qaSmokeMode = !!payload.qa_smoke_mode || String(payload.selection_scope || '') === 'qa_smoke_max_three';
        const selectionLimit = qaSmokeMode ? 3 : 80;
        const maxRows = parseInt(payload.max_rows || selectionLimit, 10) || selectionLimit;
        const maxCost = parseInt(payload.max_cost_cents || 25, 10) || 25;
        if (selected <= 0) {
            window.alert(ro
                ? 'Nu există rânduri selectate pentru generarea Meta SEO.'
                : 'There are no selected rows for Meta SEO generation.');
            return false;
        }
        if (selected > maxRows || maxRows > selectionLimit) {
            window.alert(ro
                ? (qaSmokeMode
                    ? 'Generarea Meta SEO a fost oprită: limita QA permite maximum 3 rânduri.'
                    : 'Generarea Meta SEO a fost oprită: lotul normal permite maximum 80 de rânduri.')
                : (qaSmokeMode
                    ? 'Meta SEO generation was stopped: the QA limit allows at most 3 rows.'
                    : 'Meta SEO generation was stopped: the normal batch allows at most 80 rows.'));
            return false;
        }
        const message = ro
            ? 'Generez doar propuneri Meta SEO pentru ' + String(selected) + ' rânduri. Cap cost: ' + String(maxCost) + ' credite. Nu aplic metadata, nu modific WordPress și nu public nimic. Continui?'
            : 'Generate Meta SEO proposals only for ' + String(selected) + ' rows. Cost cap: ' + String(maxCost) + ' credits. No metadata apply, no WordPress writes, and no publishing. Continue?';
        if (!window.confirm(message)) {
            return false;
        }
        payload.confirmation_kind = 'onpage_meta_generation_preview';
        payload.onpage_meta_generation_confirmed = true;
        payload.confirmed_by_user = true;
        payload.generation_preview_only = true;
        payload.no_apply = true;
        payload.no_wordpress_write = true;
        payload.max_rows = maxRows;
        payload.max_cost_cents = maxCost;
        payload.worker_batch_size = Math.min(maxRows, parseInt(payload.worker_batch_size || maxRows, 10) || maxRows);
        if (payload.batch_info && typeof payload.batch_info === 'object') {
            payload.batch_info.worker_batch_size = payload.worker_batch_size;
            payload.batch_info.batch_size = payload.worker_batch_size;
            payload.batch_info.included_count = selected;
        }
        return true;
    }

    function confirmOnPageAeoPreviewGenerationAndMark(payload, button) {
        payload = payload && typeof payload === 'object' ? payload : {};
        if (payload.confirmation_kind !== 'onpage_aeo_preview_generation') {
            return true;
        }
        const ro = state.language === 'Romanian' || String(uiLanguage() || '').indexOf('ro') === 0;
        const selection = Array.isArray(payload.selection) ? payload.selection : [];
        const selected = selection.length;
        const estimate = parseInt(payload.estimated_cost_cents || payload.estimated_credits_cents || payload.estimated_min_cost_cents || 0, 10) || 0;
        const maxCost = parseInt(payload.max_total_cost_cents || payload.max_total_cost || payload.max_cost_cents || 0, 10) || 0;
        const selectedPreview = Array.isArray(payload.selected_entities_preview) ? payload.selected_entities_preview : [];
        const first = selectedPreview.length ? selectedPreview[0] : {};
        const url = String(first.url || first.page_url || '').trim() || '-';
        const keyword = String(first.primary_keyword || first.keyword || first.target_keyword || '').trim() || '-';
        if (selected < 1 || selected > 2) {
            window.alert(ro
                ? 'Generarea preview FAQ este oprită: se pot selecta maximum două rânduri.'
                : 'FAQ preview generation stopped: maximum two rows can be selected.');
            return false;
        }
        if (estimate <= 0 || maxCost <= 0) {
            window.alert(ro
                ? 'Generarea preview FAQ este oprită până există estimare exactă și limită maximă de cost.'
                : 'FAQ preview generation is stopped until an exact estimate and max cost cap are present.');
            return false;
        }
        if (maxCost < estimate) {
            window.alert(ro
                ? 'Generarea preview FAQ este oprită: limita maximă este sub estimarea afișată.'
                : 'FAQ preview generation is stopped: the max cap is below the displayed estimate.');
            return false;
        }
        if (maxCost > 120) {
            window.alert(ro
                ? 'Generarea preview FAQ este oprită: limita maximă pentru lotul mic este 120 credite.'
                : 'FAQ preview generation is stopped: the small-batch cap is 120 credits.');
            return false;
        }
        const message = ro
            ? 'Generez doar preview FAQ / answer block / summary pentru ' + String(selected) + ' rânduri.\n\nPrimul rând: ' + keyword + '\nURL: ' + url + '\nCap cost: ' + String(maxCost) + ' credite.\n\nNu aplic FAQ, nu modific WordPress, nu inserez linkuri și nu public nimic. Continui?'
            : 'Generate only a FAQ / answer block / summary preview for ' + String(selected) + ' rows.\n\nFirst row: ' + keyword + '\nURL: ' + url + '\nCost cap: ' + String(maxCost) + ' credits.\n\nNo FAQ apply, no WordPress write, no internal links, and no publishing. Continue?';
        const confirmationHash = simpleStableHash([
            'onpage_aeo_preview_generation',
            String(estimate),
            String(maxCost),
            selection.map(function(item) { return String(item || ''); }).join('|')
        ].join('::'));
        if (!button || !button.length) {
            return false;
        }
        if (String(button.attr('data-onpage-aeo-confirmed') || '') !== confirmationHash) {
            button.attr('data-onpage-aeo-confirmed', confirmationHash);
            button.text(ro ? 'Confirmă generarea și consumul' : 'Confirm generation and usage');
            button.closest('.aysa-agent8v3-modal-actionbar').find('.aysa-agent8v3-onpage-aeo-inline-confirm').remove();
            button.closest('.aysa-agent8v3-modal-actionbar').prepend(
                '<div class="aysa-agent8v3-onpage-aeo-inline-confirm" role="status" aria-live="polite">' +
                '<strong>' + escapeHtml(ro ? 'Confirmare cost FAQ' : 'FAQ cost confirmation') + '</strong>' +
                '<p>' + escapeHtml(message) + '</p>' +
                '</div>'
            );
            return false;
        }
        button.closest('.aysa-agent8v3-modal-actionbar').find('.aysa-agent8v3-onpage-aeo-inline-confirm').remove();
        payload.onpage_aeo_preview_confirmed = true;
        payload.confirmed_by_user = true;
        payload.preview_only = true;
        payload.generation_preview_only = true;
        payload.no_apply = true;
        payload.no_wordpress_write = true;
        payload.writes_enabled = false;
        payload.apply_allowed = false;
        payload.worker_batch_size = Math.min(2, selected);
        payload.max_total_cost_cents = maxCost;
        payload.max_cost_cents = maxCost;
        return true;
    }

    function confirmOnPageKeywordMappingGenerationAndMark(payload) {
        payload = payload && typeof payload === 'object' ? payload : {};
        const ro = state.language === 'Romanian';
        const rowCount = parseInt(payload.row_count || (payload.batch_info && payload.batch_info.requested_count) || 0, 10) || 0;
        const minCost = parseInt(payload.estimated_min_cost_cents || payload.fixed_cost_cents || 0, 10) || 0;
        const maxCost = parseInt(payload.max_total_cost_cents || payload.max_total_cost || 0, 10) || 0;
        const scope = String(payload.selection_scope_label || payload.selection_scope || (ro ? 'rândurile selectate' : 'selected rows'));
        const billingAction = String(payload.billing_action_key || 'onpage_keyword_mapping_ai');
        const billingMode = payload.provider_usage_or_fixed
            ? (ro ? 'provider usage sau fallback fix' : 'provider usage or fixed fallback')
            : String(payload.billing_mode || (ro ? 'cost fix' : 'fixed cost'));
        if (rowCount <= 0) {
            window.alert(ro
                ? 'Nu există rânduri pentru Keyword Mapping.'
                : 'There are no rows for Keyword Mapping.');
            return false;
        }
        if (payload.requires_explicit_cost_cap !== false && maxCost <= 0) {
            window.alert(ro
                ? 'Keyword Mapping este oprit până există cap maxim de cost. Scope: ' + scope + '. Rânduri: ' + String(rowCount) + '. Estimare minimă: ' + String(minCost) + ' credite. Nu se modifică site-ul.'
                : 'Keyword Mapping is stopped until a max cost cap exists. Scope: ' + scope + '. Rows: ' + String(rowCount) + '. Minimum estimate: ' + String(minCost) + ' credits. No site changes.');
            return false;
        }
        const message = ro
            ? 'Generez doar propuneri de Keyword Mapping pentru scope-ul: ' + scope + '. Rânduri: ' + String(rowCount) + '. Cap maxim: ' + String(maxCost) + ' credite. Billing: ' + billingAction + ' (' + billingMode + '). Nu aplic mapping, nu modific WordPress și nu public nimic. Continui?'
            : 'Generate Keyword Mapping proposals only for scope: ' + scope + '. Rows: ' + String(rowCount) + '. Max cap: ' + String(maxCost) + ' credits. Billing: ' + billingAction + ' (' + billingMode + '). No mapping apply, no WordPress writes, and no publishing. Continue?';
        if (!window.confirm(message)) {
            return false;
        }
        payload.confirmation_kind = 'onpage_keyword_mapping_generation_preflight';
        payload.onpage_keyword_mapping_confirmed = true;
        payload.confirmed_by_user = true;
        payload.no_apply = true;
        payload.no_site_write = true;
        payload.no_wordpress_write = true;
        payload.max_total_cost_cents = maxCost;
        return true;
    }

    function confirmOnPageContentGenerationAndMark(action, payload, button) {
        payload = payload && typeof payload === 'object' ? payload : {};
        const ro = state.language === 'Romanian' || String(uiLanguage() || '').indexOf('ro') === 0;
        const selection = Array.isArray(payload.selection) ? payload.selection : [];
        const selected = selection.length;
        const estimate = parseInt(payload.estimated_cost_cents || payload.estimated_min_cost_cents || 0, 10) || 0;
        const maxCost = parseInt(payload.max_total_cost_cents || payload.max_cost_cents || 0, 10) || 0;
        const isDecision = action === 'generate_onpage_rewrite_decision';
        const expectedKind = isDecision ? 'onpage_content_evaluation_generation' : 'onpage_content_rewrite_generation';
        if (String(payload.confirmation_kind || '') !== expectedKind || selected < 1 || selected > 80) {
            window.alert(ro
                ? 'Etapa Content este oprită: selecția sau contractul de confirmare nu este valid.'
                : 'Content stage stopped: the selection or confirmation contract is invalid.');
            return false;
        }
        if (estimate <= 0 || maxCost !== estimate) {
            window.alert(ro
                ? 'Etapa Content este oprită până există o estimare exactă și un plafon identic.'
                : 'Content stage is stopped until an exact estimate and matching cap are available.');
            return false;
        }
        const operation = isDecision
            ? (ro ? 'evaluez dacă este necesară rescrierea' : 'evaluate whether rewriting is needed')
            : (ro ? 'generez propuneri de rescriere' : 'generate rewrite proposals');
        const message = ro
            ? 'Pentru ' + String(selected) + ' pagini, ' + operation + '. Plafon maxim: ' + String(maxCost) + ' credite. Rezultatul rămâne propunere: nu aplic, nu modific WordPress și nu public nimic. Continui?'
            : 'For ' + String(selected) + ' pages, ' + operation + '. Maximum cap: ' + String(maxCost) + ' credits. Results remain proposals: no apply, no WordPress write, and no publishing. Continue?';
        const confirmationHash = simpleStableHash([
            String(action || ''),
            String(payload.confirmation_kind || ''),
            String(estimate),
            selection.map(function(item) { return String(item || ''); }).join('|')
        ].join('::'));
        if (!button || !button.length) {
            return false;
        }
        if (String(button.attr('data-onpage-content-confirmed') || '') !== confirmationHash) {
            button.attr('data-onpage-content-confirmed', confirmationHash);
            button.text(isDecision
                ? (ro ? 'Confirmă evaluarea și consumul' : 'Confirm evaluation and usage')
                : (ro ? 'Confirmă generarea și consumul' : 'Confirm generation and usage'));
            button.closest('.aysa-agent8v3-modal-actionbar').find('.aysa-agent8v3-onpage-content-inline-confirm').remove();
            button.closest('.aysa-agent8v3-modal-actionbar').prepend(
                '<div class="aysa-agent8v3-onpage-content-inline-confirm" role="status" aria-live="polite">' +
                '<strong>' + escapeHtml(ro ? 'Confirmare cost Content' : 'Content cost confirmation') + '</strong>' +
                '<p>' + escapeHtml(message) + '</p>' +
                '</div>'
            );
            return false;
        }
        button.closest('.aysa-agent8v3-modal-actionbar').find('.aysa-agent8v3-onpage-content-inline-confirm').remove();
        payload.confirmed_by_user = true;
        payload.generation_preview_only = true;
        payload.proposal_generation_only = true;
        payload.no_apply = true;
        payload.no_site_write = true;
        payload.no_wordpress_write = true;
        payload.writes_enabled = false;
        payload.apply_allowed = false;
        payload.max_total_cost_cents = maxCost;
        payload.max_cost_cents = maxCost;
        if (isDecision) {
            payload.onpage_content_evaluation_confirmed = true;
        } else {
            payload.onpage_content_rewrite_generation_confirmed = true;
        }
        return true;
    }

    function currentOnPageAnalysisApproval() {
        const approval = state.onPageAnalysisApproval && typeof state.onPageAnalysisApproval === 'object'
            ? state.onPageAnalysisApproval
            : null;
        if (!approval) {
            return null;
        }
        const phase = String(state.canonical && state.canonical.phase ? state.canonical.phase : '');
        const approvalPayload = approval.payload && typeof approval.payload === 'object' ? approval.payload : {};
        const isContinuation = !!approvalPayload.continuation_mode && String(approvalPayload.continuation_token || '') !== '';
        const phaseAllowed = phase === 'onpage_seo_ready' || (phase === 'onpage_seo_review' && isContinuation);
        if (!phaseAllowed || parseInt(approval.state_version, 10) !== currentVersion()) {
            state.onPageAnalysisApproval = null;
            return null;
        }
        return approval;
    }

    function restoreOnPageAnalysisApproval() {
        const approval = currentOnPageAnalysisApproval();
        if (!approval) {
            return;
        }
        $('[data-action="start_onpage_seo_run"]').each(function() {
            const button = $(this);
            button.attr('data-onpage-analysis-approved', JSON.stringify(approval.payload || {}));
            button.text(approval.button_label || 'Confirmă și pornește analiza');
            if (!button.siblings('.aysa-agent8v3-onpage-analysis-inline-confirm').length) {
                button.before(
                    '<div class="aysa-agent8v3-onpage-analysis-inline-confirm">' +
                        '<strong>' + escapeHtml(approval.title || 'Confirmare cost On Page SEO') + '</strong>' +
                        '<p>' + escapeHtml(approval.message || '').replace(/\n/g, '<br>') + '</p>' +
                    '</div>'
                );
            }
        });
    }

    function isFixedCostProductAction(action) {
        return [
            'save_objectives',
            'run_seo_profile_autofill',
            'save_seo_profile',
            'confirm_competition_keyword',
            'select_tone_of_voice_friendly',
            'select_tone_of_voice_professional',
            'select_tone_of_voice_expert',
            'select_tone_of_voice_premium',
            'generate_content_strategy',
            'generate_content_article',
            'find_offpage_link_exchange_matches',
            'generate_offpage_gbp_social_calendar'
        ].indexOf(String(action || '')) !== -1;
    }

    function preflightAndConfirmFixedCostProductAction(button, agentAction, payload, approvedRunner) {
        const action = String(agentAction || '');
        const sourcePayload = payload && typeof payload === 'object' ? Object.assign({}, payload) : {};
        const ro = state.language === 'Romanian' || String(uiLanguage() || '').indexOf('ro') === 0;
        let handedOff = false;
        button.prop('disabled', true);
        rawAjax('aysa_agent8v3_fixed_cost_preflight', {
            agent_action: action,
            state_version: currentVersion(),
            payload: JSON.stringify(sourcePayload)
        }).done(function(response) {
            if (!response || !response.success) {
                addMessage('system', apiErrorMessage(response, ro ? 'Preflight-ul financiar nu este disponibil.' : 'Financial preflight is unavailable.'));
                return;
            }
            const result = response.data && typeof response.data === 'object' ? response.data : {};
            const billing = result.billing_preflight && typeof result.billing_preflight === 'object' ? result.billing_preflight : {};
            const estimate = parseInt(billing.estimated_credits_cents || 0, 10) || 0;
            const maximum = parseInt(billing.maximum_credits_cents || estimate, 10) || estimate;
            const available = parseInt(billing.available_credits_cents || 0, 10) || 0;
            if (!result.allowed || estimate <= 0 || maximum !== estimate) {
                addMessage('system', apiErrorMessage(response, ro ? 'Acțiunea nu are un cost fix valid sau nu este disponibilă în etapa curentă.' : 'The action has no valid fixed cost or is unavailable in the current stage.'));
                return;
            }
            if (billing.insufficient_credits) {
                addMessage('system', ro
                    ? 'Nu sunt suficiente credite pentru această acțiune. Cost: ' + estimate + ' credite; disponibile: ' + available + ' credite.'
                    : 'There are not enough credits for this action. Cost: ' + estimate + ' credits; available: ' + available + ' credits.');
                return;
            }
            const isSetupChatMessage = !!sourcePayload.setup_chat_message;
            const message = isSetupChatMessage
                ? (ro
                    ? 'Mesajul poate salva informații în setup, cu un cost fix de ' + estimate + ' credite. Dacă este doar o întrebare, nu se debitează nimic. Confirmi continuarea? Site-ul WordPress nu va fi modificat.'
                    : 'This message may save setup information at a fixed cost of ' + estimate + ' credits. If it is only a question, nothing is charged. Continue? The WordPress site will not be modified.')
                : (ro
                    ? 'Confirmi „' + actionLabel(action) + '”? Costul fix este ' + estimate + ' credite. ' + (isSetupFixedCostAction(action) ? 'Se salvează doar alegerea din setup; site-ul WordPress nu este modificat.' : 'Acțiunea generează doar rezultate pentru review și nu modifică site-ul WordPress.')
                    : 'Confirm “' + actionLabel(action) + '”? The fixed cost is ' + estimate + ' credits. ' + (isSetupFixedCostAction(action) ? 'Only the setup choice is saved; the WordPress site is not modified.' : 'The action only generates reviewable results and does not modify the WordPress site.'));
            if (!window.confirm(message)) {
                return;
            }
            sourcePayload.confirmation_kind = 'fixed_cost_product_action';
            sourcePayload.billing_action = action;
            sourcePayload.explicit_confirmation = true;
            sourcePayload.confirmed_by_user = true;
            sourcePayload.estimated_credits_cents = estimate;
            sourcePayload.approved_max_credits_cents = estimate;
            sourcePayload.no_wordpress_write = true;
            sourcePayload.apply_allowed = false;
            if (isSetupFixedCostAction(action)) {
                sourcePayload.local_state_write_only = true;
            } else {
                sourcePayload.analysis_only = true;
            }
            sourcePayload.idempotency_key = 'agent8v3:fixed_cost:' + action + ':' + String(currentVersion());
            handedOff = true;
            button.prop('disabled', false);
            approvedRunner(sourcePayload);
        }).fail(function(xhr) {
            addMessage('system', apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, ro ? 'Preflight-ul financiar a eșuat.' : 'Financial preflight failed.'));
        }).always(function() {
            if (!handedOff) {
                button.prop('disabled', false);
            }
        });
    }

    function isSetupFixedCostAction(action) {
        return [
            'save_objectives',
            'save_seo_profile',
            'confirm_competition_keyword',
            'select_tone_of_voice_friendly',
            'select_tone_of_voice_professional',
            'select_tone_of_voice_expert',
            'select_tone_of_voice_premium'
        ].indexOf(String(action || '')) !== -1;
    }

    function setupChatSaveAction() {
        const phase = String(state.canonical && state.canonical.phase || '');
        if (phase === 'objectives') {
            return 'save_objectives';
        }
        if (phase === 'seo_profile') {
            return 'save_seo_profile';
        }
        return '';
    }

    function preflightAndConfirmOnPageAnalysis(button, payload) {
        const ro = state.language === 'Romanian' || String(uiLanguage() || '').indexOf('ro') === 0;
        let storedApproval = String(button.attr('data-onpage-analysis-approved') || '');
        if (!storedApproval && currentOnPageAnalysisApproval()) {
            restoreOnPageAnalysisApproval();
            storedApproval = String(button.attr('data-onpage-analysis-approved') || '');
        }
        if (storedApproval) {
            let approvedPayload = {};
            try {
                approvedPayload = JSON.parse(storedApproval);
            } catch (error) {
                approvedPayload = {};
            }
            if (!approvedPayload || typeof approvedPayload !== 'object' || !approvedPayload.onpage_analysis_start_confirmed) {
                button.removeAttr('data-onpage-analysis-approved');
                return;
            }
            button.prop('disabled', true).addClass('is-loading');
            button.closest('.aysa-agent8v3-modal-actionbar').find('.aysa-agent8v3-onpage-analysis-inline-confirm').remove();
            request('aysa_agent8v3_action', {
                agent_action: 'start_onpage_seo_run',
                state_version: currentVersion(),
                payload: JSON.stringify(approvedPayload)
            });
            return;
        }
        button.prop('disabled', true).addClass('is-loading');
        rawAjax('aysa_agent8v3_onpage_start_preflight', {
            state_version: currentVersion(),
            payload: JSON.stringify(payload || {})
        }).done(function(response) {
            if (!response || !response.success) {
                addMessage('system', apiErrorMessage(response, ro ? 'Verificarea On Page SEO nu este disponibilă.' : 'On Page SEO preflight is unavailable.'));
                return;
            }
            const result = response.data && typeof response.data === 'object' ? response.data : {};
            const billing = result.billing_preflight && typeof result.billing_preflight === 'object' ? result.billing_preflight : {};
            const onpageWrap = result.worker_preflight && result.worker_preflight.onpage_seo && typeof result.worker_preflight.onpage_seo === 'object'
                ? result.worker_preflight.onpage_seo
                : {};
            const estimate = parseInt(billing.estimated_credits_cents || onpageWrap.estimated_credits_cents || 0, 10) || 0;
            const available = parseInt(billing.available_credits_cents || 0, 10) || 0;
            if (!result.allowed || estimate <= 0) {
                addMessage('system', ro
                    ? 'Nu pot porni analiza On Page SEO până când estimarea completă și condițiile de siguranță sunt disponibile.'
                    : 'The On Page SEO analysis cannot start until the complete estimate and safety requirements are available.');
                return;
            }
            if (billing.insufficient_credits || (available > 0 && available < estimate)) {
                requestAutomaticTopupForCreditGate('start_onpage_seo_run', estimate, available);
                return;
            }

            const runTypes = Array.isArray(onpageWrap.run_types) ? onpageWrap.run_types : [];
            const isContinuation = !!payload.continuation_mode && String(payload.continuation_token || '') !== '';
            const nextBatchNumber = Math.max(2, (parseInt(payload.current_batch_number || 1, 10) || 1) + 1);
            const message = ro
                ? (isContinuation
                    ? 'Pornești următorul lot On Page SEO?\n\nEtape: ' + String(runTypes.length || 8) + '.\nCost estimat și plafon maxim: ' + String(estimate) + ' credite.\nCredite disponibile: ' + String(available) + '.\n\nContinuă inventarul existent fără să refacă lotul anterior. Nu aplică, nu publică și nu modifică WordPress.'
                    : 'Pornești analiza completă On Page SEO?\n\nEtape: ' + String(runTypes.length || 8) + '.\nCost estimat și plafon maxim: ' + String(estimate) + ' credite.\nCredite disponibile: ' + String(available) + '.\n\nAnaliza pregătește recomandări pentru review. Nu aplică, nu publică și nu modifică WordPress.')
                : (isContinuation
                    ? 'Start the next On Page SEO batch?\n\nSteps: ' + String(runTypes.length || 8) + '.\nEstimated and maximum cost: ' + String(estimate) + ' credits.\nAvailable credits: ' + String(available) + '.\n\nThis continues the existing inventory without repeating the previous batch. It does not apply, publish, or modify WordPress.'
                    : 'Start the complete On Page SEO analysis?\n\nSteps: ' + String(runTypes.length || 8) + '.\nEstimated and maximum cost: ' + String(estimate) + ' credits.\nAvailable credits: ' + String(available) + '.\n\nThe analysis prepares recommendations for review. It does not apply, publish, or modify WordPress.');
            const approvedPayload = Object.assign({}, payload || {}, {
                confirmation_kind: 'onpage_seo_analysis_start',
                confirmed_by_user: true,
                user_confirmed: true,
                onpage_analysis_start_confirmed: true,
                analysis_only: true,
                preview_only: true,
                no_apply: true,
                no_wordpress_write: true,
                writes_enabled: false,
                apply_allowed: false,
                estimated_credits_cents: estimate,
                estimated_cost_cents: estimate,
                max_total_cost_cents: estimate,
                max_total_cost: estimate,
                idempotency_key: 'agent8v3:onpage_analysis_start:' + String(currentAgent8ProjectId()) + ':' + simpleStableHash(String(currentVersion()) + '|' + String(estimate) + '|' + runTypes.join('|'))
            });
            state.onPageAnalysisApproval = {
                state_version: currentVersion(),
                payload: approvedPayload,
                title: ro ? 'Confirmare cost On Page SEO' : 'On Page SEO cost confirmation',
                message: message,
                button_label: ro
                    ? (isContinuation ? ('Confirmă și pornește lotul ' + String(nextBatchNumber)) : 'Confirmă și pornește analiza')
                    : (isContinuation ? ('Confirm and start batch ' + String(nextBatchNumber)) : 'Confirm and start analysis')
            };
            restoreOnPageAnalysisApproval();
        }).fail(function(xhr) {
            addMessage('system', apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, ro ? 'Verificarea On Page SEO a eșuat.' : 'On Page SEO preflight failed.'));
        }).always(function() {
            button.prop('disabled', false).removeClass('is-loading');
        });
    }

    function preflightAndConfirmBusinessProfileAutofill(button) {
        const ro = state.language === 'Romanian' || String(uiLanguage() || '').indexOf('ro') === 0;
        button.prop('disabled', true).addClass('is-loading');
        rawAjax('aysa_agent8v3_business_profile_preflight', {
            state_version: currentVersion()
        }).done(function(response) {
            if (!response || !response.success) {
                addMessage('system', apiErrorMessage(response, ro ? 'Estimarea Business Profile nu este disponibilă.' : 'Business Profile estimate is unavailable.'));
                return;
            }
            const result = response.data && typeof response.data === 'object' ? response.data : {};
            const billing = result.billing_preflight && typeof result.billing_preflight === 'object' ? result.billing_preflight : {};
            const estimate = parseInt(billing.estimated_credits_cents || 0, 10) || 0;
            const available = parseInt(billing.available_credits_cents || 0, 10) || 0;
            if (!result.allowed || estimate <= 0) {
                addMessage('system', ro ? 'Analiza nu poate porni fără estimare și plafon exact.' : 'The analysis cannot start without an exact estimate and cap.');
                return;
            }
            if (billing.insufficient_credits || available < estimate) {
                requestAutomaticTopupForCreditGate('run_business_profile_autofill', estimate, available);
                return;
            }
            const message = ro
                ? 'Pornești analiza website-ului pentru Business Profile?\n\nCost estimat și plafon maxim: ' + String(estimate) + ' credite.\nCredite disponibile: ' + String(available) + '.\n\nDebitarea reflectă numai utilizarea reală a providerului, fără depășirea plafonului. Analiza nu modifică și nu publică nimic în WordPress sau Google Business Profile.'
                : 'Start the website analysis for Business Profile?\n\nEstimated and maximum cost: ' + String(estimate) + ' credits.\nAvailable credits: ' + String(available) + '.\n\nBilling reflects actual provider usage without exceeding the cap. The analysis does not modify or publish anything in WordPress or Google Business Profile.';
            if (!window.confirm(message)) {
                return;
            }
            const idempotencyKey = 'agent8v3:business_profile_autofill:' + String(currentAgent8ProjectId()) + ':' + simpleStableHash(String(currentVersion()) + '|' + String(estimate));
            request('aysa_agent8v3_action', {
                agent_action: 'run_business_profile_autofill',
                state_version: currentVersion(),
                payload: JSON.stringify({
                    confirmation_kind: 'business_profile_autofill_start',
                    explicit_confirmation: true,
                    confirmed_by_user: true,
                    analysis_only: true,
                    no_wordpress_write: true,
                    apply_allowed: false,
                    estimated_credits_cents: estimate,
                    approved_max_credits_cents: estimate,
                    max_total_cost_cents: estimate,
                    idempotency_key: idempotencyKey
                })
            });
        }).fail(function(xhr) {
            addMessage('system', apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, ro ? 'Preflight-ul Business Profile a eșuat.' : 'Business Profile preflight failed.'));
        }).always(function() {
            button.prop('disabled', false).removeClass('is-loading');
        });
    }

    function preflightAndConfirmCompetitionKeywordAnalysis(button) {
        const ro = state.language === 'Romanian' || String(uiLanguage() || '').indexOf('ro') === 0;
        button.prop('disabled', true).addClass('is-loading');
        rawAjax('aysa_agent8v3_competition_keyword_preflight', {
            state_version: currentVersion()
        }).done(function(response) {
            if (!response || !response.success) {
                addMessage('system', apiErrorMessage(response, ro ? 'Estimarea analizei de competiție nu este disponibilă.' : 'Competition analysis estimate is unavailable.'));
                return;
            }
            const result = response.data && typeof response.data === 'object' ? response.data : {};
            const billing = result.billing_preflight && typeof result.billing_preflight === 'object' ? result.billing_preflight : {};
            const estimate = parseInt(billing.estimated_credits_cents || 0, 10) || 0;
            const available = parseInt(billing.available_credits_cents || 0, 10) || 0;
            if (!result.allowed || estimate <= 0) {
                addMessage('system', ro ? 'Analiza nu poate porni fără estimare și plafon exact.' : 'The analysis cannot start without an exact estimate and cap.');
                return;
            }
            if (billing.insufficient_credits || available < estimate) {
                requestAutomaticTopupForCreditGate('run_competition_keyword_analysis', estimate, available);
                return;
            }
            const message = ro
                ? 'Pornești analiza de competiție și cuvinte cheie?\n\nCost estimat și plafon maxim: ' + String(estimate) + ' credite.\nCredite disponibile: ' + String(available) + '.\n\nAnaliza pregătește rezultate pentru verificare. Nu aplică, nu publică și nu modifică WordPress.'
                : 'Start the competition and keyword analysis?\n\nEstimated and maximum cost: ' + String(estimate) + ' credits.\nAvailable credits: ' + String(available) + '.\n\nThe analysis prepares results for review. It does not apply, publish, or modify WordPress.';
            if (!window.confirm(message)) {
                return;
            }
            request('aysa_agent8v3_action', {
                agent_action: 'run_competition_keyword_analysis',
                state_version: currentVersion(),
                payload: JSON.stringify({
                    confirmation_kind: 'competition_keyword_analysis_start',
                    explicit_confirmation: true,
                    confirmed_by_user: true,
                    analysis_only: true,
                    no_wordpress_write: true,
                    apply_allowed: false,
                    estimated_credits_cents: estimate,
                    approved_max_credits_cents: estimate,
                    max_total_cost_cents: estimate,
                    idempotency_key: 'agent8v3:competition_keyword_analysis:' + String(currentAgent8ProjectId()) + ':' + simpleStableHash(String(currentVersion()) + '|' + String(estimate))
                })
            });
        }).fail(function(xhr) {
            addMessage('system', apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, ro ? 'Preflight-ul analizei de competiție a eșuat.' : 'Competition analysis preflight failed.'));
        }).always(function() {
            button.prop('disabled', false).removeClass('is-loading');
        });
    }

    function preflightAndConfirmKeywordResearch(button, requestedAction) {
        const ro = state.language === 'Romanian' || String(uiLanguage() || '').indexOf('ro') === 0;
        const action = requestedAction === 'retry_keyword_research_run' ? requestedAction : 'start_keyword_research_run';
        const isRetry = action === 'retry_keyword_research_run';
        button.prop('disabled', true).addClass('is-loading');
        rawAjax('aysa_agent8v3_keyword_research_preflight', {agent_action: action, state_version: currentVersion()}).done(function(response) {
            const result = response && response.success && response.data && typeof response.data === 'object' ? response.data : {};
            const billing = result.billing_preflight && typeof result.billing_preflight === 'object' ? result.billing_preflight : {};
            const estimate = parseInt(billing.estimated_credits_cents || 0, 10) || 0;
            const maximum = parseInt(billing.maximum_credits_cents || 0, 10) || 0;
            const available = parseInt(billing.available_credits_cents || 0, 10) || 0;
            if (!result.allowed || estimate <= 0 || maximum < estimate) {
                addMessage('system', ro ? 'Keyword Research nu poate porni fără estimare și plafon exact.' : 'Keyword Research cannot start without an exact estimate and cap.');
                return;
            }
            if (billing.insufficient_credits || available < maximum) {
                requestAutomaticTopupForCreditGate(action, maximum, available);
                return;
            }
            const message = ro
                ? (isRetry
                    ? 'Reiei Keyword Research?\n\nNoul run poate reevalua unele taskuri.\n\nCost estimat: ' + estimate + ' credite. Plafon maxim: ' + maximum + ' credite. Costul final poate varia, dar nu poate depăși plafonul fără o aprobare nouă.\nCredite disponibile: ' + available + '.\n\nNu aplică și nu publică modificări în WordPress.'
                    : 'Pornești Keyword Research?\n\nCost estimat: ' + estimate + ' credite. Plafon maxim: ' + maximum + ' credite. Costul final poate varia, dar nu poate depăși plafonul fără o aprobare nouă.\nCredite disponibile: ' + available + '.\n\nAnaliza pregătește keywords, mapping și Content Plan pentru review. Nu aplică și nu publică modificări în WordPress.')
                : (isRetry
                    ? 'Retry Keyword Research?\n\nThe new run may evaluate some tasks again.\n\nEstimated cost: ' + estimate + ' credits. Maximum cap: ' + maximum + ' credits. Final cost may vary, but cannot exceed the cap without a new approval.\nAvailable credits: ' + available + '.\n\nIt does not apply or publish WordPress changes.'
                    : 'Start Keyword Research?\n\nEstimated cost: ' + estimate + ' credits. Maximum cap: ' + maximum + ' credits. Final cost may vary, but cannot exceed the cap without a new approval.\nAvailable credits: ' + available + '.\n\nThe analysis prepares keywords, mapping and the Content Plan for review. It does not apply or publish WordPress changes.');
            if (!window.confirm(message)) {
                return;
            }
            request('aysa_agent8v3_action', {
                agent_action: action,
                state_version: currentVersion(),
                payload: JSON.stringify({
                    confirmation_kind: isRetry ? 'keyword_research_retry' : 'keyword_research_start',
                    explicit_confirmation: true,
                    confirmed_by_user: true,
                    analysis_only: true,
                    no_wordpress_write: true,
                    apply_allowed: false,
                    estimated_credits_cents: estimate,
                    approved_max_credits_cents: maximum,
                    max_total_cost_cents: maximum,
                    idempotency_key: 'agent8v3:keyword_research:' + String(currentAgent8ProjectId()) + ':' + simpleStableHash(action + '|' + String(currentVersion()) + '|' + String(estimate) + '|' + String(maximum))
                })
            });
        }).fail(function(xhr) {
            addMessage('system', apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, ro ? 'Preflight-ul Keyword Research a eșuat.' : 'Keyword Research preflight failed.'));
        }).always(function() {
            button.prop('disabled', false).removeClass('is-loading');
        });
    }

    function currentAgent8ProjectId() {
        const direct = String(cfg.project_id || cfg.wp_project_id || '').match(/\d+/);
        if (direct) {
            return direct[0];
        }
        try {
            const raw = $('#aysa-agent8v3-state').text() || '{}';
            const parsed = JSON.parse(raw);
            const activationProject = parsed && parsed.data && parsed.data.activation ? parsed.data.activation.project_id : '';
            const fromActivation = String(activationProject || '').match(/\d+/);
            if (fromActivation) {
                return fromActivation[0];
            }
            const fromRoot = String(parsed && parsed.project_id ? parsed.project_id : '').match(/\d+/);
            return fromRoot ? fromRoot[0] : '';
        } catch (error) {
            return '';
        }
    }

    function currentAgent8Context() {
        const context = {
            project_id: currentAgent8ProjectId(),
            website_id: '',
            site_host: String(cfg.site_host || '').toLowerCase()
        };
        const canonical = state.canonical && typeof state.canonical === 'object' ? state.canonical : null;
        const activation = canonical && canonical.data && canonical.data.activation && typeof canonical.data.activation === 'object'
            ? canonical.data.activation
            : null;
        if (activation) {
            const activationProject = String(activation.project_id || '').match(/\d+/);
            const activationWebsite = String(activation.website_id || '').match(/\d+/);
            if (activationProject) {
                context.project_id = activationProject[0];
            }
            if (activationWebsite) {
                context.website_id = activationWebsite[0];
            }
            context.site_host = String(activation.host || activation.domain || context.site_host || '').toLowerCase();
        }
        return context;
    }

    function factoryResetAllowedTargets() {
        return Array.isArray(cfg.factory_reset_allowed_targets) ? cfg.factory_reset_allowed_targets : [];
    }

    function isFactoryResetAllowedForContext(context) {
        const projectId = String(context && context.project_id ? context.project_id : '').trim();
        const websiteId = String(context && context.website_id ? context.website_id : '').trim();
        const siteHost = String(context && context.site_host ? context.site_host : '').toLowerCase().trim();
        if (!projectId || !siteHost) {
            return false;
        }
        return factoryResetAllowedTargets().some(function(target) {
            const targetProjectId = String(target && target.project_id ? target.project_id : '').trim();
            const targetWebsiteId = String(target && target.website_id ? target.website_id : '').trim();
            const targetSiteHost = String(target && target.site_host ? target.site_host : '').toLowerCase().trim();
            if (targetProjectId !== projectId || targetSiteHost !== siteHost) {
                return false;
            }
            return !targetWebsiteId || !websiteId || targetWebsiteId === websiteId;
        });
    }

    function updateFactoryResetVisibility() {
        const button = $('#aysa-agent8v3-factory-reset');
        if (!button.length) {
            return;
        }
        const visible = !!cfg.qa_enabled || isFactoryResetAllowedForContext(currentAgent8Context());
        button.prop('hidden', !visible)
            .attr('aria-hidden', visible ? 'false' : 'true')
            .toggleClass('is-available', visible);
    }

    function refreshOnPageContentRewriteLiveBefore(payload, button, onReady) {
        payload = payload && typeof payload === 'object' ? payload : {};
        if (String(payload.write_class || '') !== 'onpage_content_rewrite_apply' || !payload.op26_final_write_confirmed) {
            onReady(payload);
            return;
        }
        const item = Array.isArray(payload.accepted_items) && payload.accepted_items.length === 1 ? payload.accepted_items[0] : {};
        if (!item || typeof item !== 'object') {
            renderModalError('Content Rewrite final write requires exactly one selected row.');
            return;
        }
        button.prop('disabled', true);
        rawAjax('aysa_agent8v3_onpage_content_rewrite_live_refresh', {
            project_id: currentAgent8ProjectId(),
            item_json: JSON.stringify(item)
        }).done(function(response) {
            if (!response || !response.success || !response.data || !response.data.refreshed_item) {
                renderModalError(apiErrorMessage(response, 'Content Rewrite live refresh failed.'));
                button.prop('disabled', false);
                return;
            }
            payload.accepted_items = [response.data.refreshed_item];
            payload.selection = [String(response.data.refreshed_item.entity_key || response.data.refreshed_item.item_id || '')];
            payload.payload_hash = String(response.data.payload_hash || payload.payload_hash || '');
            payload.idempotency_key = String(response.data.idempotency_key || payload.idempotency_key || '');
            payload.op27_live_refresh = true;
            payload.live_before_hash = String(response.data.current_hash || '');
            payload.live_proposed_hash = String(response.data.proposed_hash || '');
            if (response.data.before_hash_changed) {
                payload.op27_stale_payload_refreshed = true;
            }
            onReady(payload);
        }).fail(function(xhr) {
            renderModalError(apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Content Rewrite live refresh failed.'));
            button.prop('disabled', false);
        });
    }

    function prepareOnPageContentRewriteFinalGates(payload, button, onReady) {
        payload = payload && typeof payload === 'object' ? payload : {};
        if (String(payload.write_class || '') !== 'onpage_content_rewrite_apply' || !payload.op26_final_write_confirmed) {
            onReady(payload);
            return;
        }
        const item = Array.isArray(payload.accepted_items) && payload.accepted_items.length === 1 ? payload.accepted_items[0] : {};
        const entityKey = String(item.entity_key || item.item_id || '');
        const target = String(item.target || item.field || '');
        const payloadHash = String(payload.payload_hash || '');
        const idempotencyKey = String(payload.idempotency_key || '');
        if (!entityKey || !target || !payloadHash || !idempotencyKey) {
            renderModalError('Content Rewrite final write is missing scoped gate identity.');
            return;
        }
        button.prop('disabled', true);
        rawAjax('aysa_agent8v3_onpage_content_rewrite_product_gates_set', {
            project_gate_enabled: '1',
            site_gate_enabled: '1',
            entity_key: entityKey,
            target: target,
            payload_hash: payloadHash,
            idempotency_key: idempotencyKey
        }).done(function(response) {
            if (!response || !response.success) {
                renderModalError(apiErrorMessage(response, 'Content Rewrite gate update failed.'));
                button.prop('disabled', false);
                return;
            }
            payload.product_gates = response.data && response.data.product_gates ? response.data.product_gates : {
                project_gate_enabled: true,
                site_gate_enabled: true,
                global_kill_switch_active: false
            };
            payload.billing_status = 'content_rewrite_real_billing';
            payload.billing_action_key = 'agent8v3_onpage_content_rewrite_apply';
            payload.writes_enabled = true;
            payload.stop_before_write = false;
            onReady(payload);
        }).fail(function(xhr) {
            renderModalError(apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Content Rewrite gate update failed.'));
            button.prop('disabled', false);
        });
    }

    function filterModalActionsForActiveView(actions, modal) {
        if (String(modal.modal_key || '') !== 'onpage_seo') {
            return actions;
        }
        const activeTab = String(modal.active_tab || (modal.filters && modal.filters.tab) || '');
        if (activeTab === 'content') {
            return actions;
        }
        if (activeTab !== 'meta_snippets') {
            return actions;
        }
        const activeStatus = String((modal.filters && modal.filters.status) || (state.modal.filters && state.modal.filters.status) || 'all');
        return actions.filter(function(action) {
            const actionName = String(action.action || '');
            if (activeStatus === 'saved_published') {
                return false;
            }
            if (activeStatus === 'generated') {
                return actionName === 'execute_onpage_plan';
            }
            if (activeStatus === 'ready_generation') {
                return actionName === 'generate_onpage_meta';
            }
            return true;
        });
    }

    function modalActionRequiresExecutablePlan(action) {
        return ['execute_technical_fix_plan', 'execute_onpage_plan'].indexOf(String(action && action.action ? action.action : '')) !== -1;
    }

    function modalActionHasExecutablePlan(action) {
        const summary = action && action.summary ? action.summary : {};
        const payload = action && action.payload && typeof action.payload === 'object' ? action.payload : {};
        if (String(action && action.action ? action.action : '') === 'execute_onpage_plan'
            && String(payload.write_class || '') === 'onpage_content_rewrite_apply'
            && !!payload.stop_before_write
            && !!payload.op25_preflight
            && Array.isArray(payload.accepted_items)) {
            return payload.accepted_items.length === 1;
        }
        if (String(payload.confirmation_kind || '') === 'internal_linking_apply') {
            const selectable = parseInt(summary.selectable !== undefined ? summary.selectable : 0, 10);
            return Number.isFinite(selectable) && selectable > 0;
        }
        if (String(payload.confirmation_kind || '') === 'technical_metadata_apply') {
            const selectable = parseInt(summary.selectable !== undefined ? summary.selectable : 0, 10);
            return Number.isFinite(selectable) && selectable > 0;
        }
        if (String(payload.confirmation_kind || '') === 'technical_image_optimization_apply') {
            const selectable = parseInt(summary.selectable !== undefined ? summary.selectable : 0, 10);
            return Number.isFinite(selectable) && selectable > 0;
        }
        if (String(payload.confirmation_kind || '') === 'technical_image_alt_apply') {
            const accepted = parseInt(summary.accepted !== undefined ? summary.accepted : payload.confirmation_count, 10);
            return Number.isFinite(accepted) && accepted > 0;
        }
        const executable = parseInt(summary.executable !== undefined ? summary.executable : 0, 10);
        return Number.isFinite(executable) && executable > 0;
    }

    function renderOnPageKeywordRemap(row) {
        const modal = state.modal.current || {};
        const targets = Array.isArray(modal.keyword_mapping_targets) ? modal.keyword_mapping_targets : [];
        const currentKey = String(row.entity_key || '');
        const keyword = String(row.rejected_keyword || row.primary_keyword || '').replace(/^-$/, '').trim();
        const options = targets.filter(function(target) {
            return target && String(target.entity_key || '') && String(target.entity_key || '') !== currentKey;
        }).map(function(target) {
            const title = String(target.title || target.url || target.entity_key || '');
            const type = String(target.entity_group || '');
            return '<option value="' + escapeHtml(target.entity_key || '') + '">' + escapeHtml(title + (type ? ' · ' + type : '')) + '</option>';
        }).join('');
        if (!options || !keyword) {
            return '<span class="aysa-agent8v3-muted">Manual mapping required</span>';
        }
        return '<div class="aysa-agent8v3-remap-control">' +
            '<select class="aysa-agent8v3-remap-target">' + options + '</select>' +
            '<button type="button" class="button button-small aysa-agent8v3-remap-save" data-item-id="' + escapeHtml(currentKey) + '" data-keyword="' + escapeHtml(keyword) + '">Save</button>' +
            '</div>';
    }

    function renderModalCell(row, column, key) {
        const value = row && row[key] !== undefined ? row[key] : '';
        if (column && column.type === 'onpage_metadata_apply_selection') {
            const payload = value && typeof value === 'object' ? value : {};
            const selectable = !!payload.selectable;
            const selectionKey = String(payload.provider_output_id || payload.entity_key || payload.item_id || '');
            const selectedItems = state.modal.onpageMetadataSelectedItems || {};
            const checked = selectable && (payload.selected_by_default || !!selectedItems[selectionKey]) ? ' checked' : '';
            const disabled = selectable ? '' : ' disabled';
            const label = state.language === 'Romanian' ? 'Selectează rândul Metadata' : 'Select Metadata row';
            return '<label class="aysa-agent8v3-metadata-apply-select">' +
                '<input type="checkbox" class="aysa-agent8v3-onpage-metadata-apply-row" aria-label="' + escapeHtml(label) + '" data-payload="' + escapeHtml(JSON.stringify(payload)) + '"' + checked + disabled + '>' +
                '<span class="screen-reader-text">' + escapeHtml(label) + '</span>' +
                '</label>';
        }
        if (column && column.type === 'metadata_apply_selection') {
            const payload = value && typeof value === 'object' ? value : {};
            const disabled = payload.selectable ? '' : ' disabled';
            return '<label class="aysa-agent8v3-metadata-apply-select">' +
                '<input type="checkbox" class="aysa-agent8v3-metadata-apply-row" data-payload="' + escapeHtml(JSON.stringify(payload)) + '"' + disabled + '>' +
                '<span class="screen-reader-text">' + escapeHtml(text('select') || 'Select') + '</span>' +
                '</label>';
        }
	        if (column && column.type === 'canonical_apply_selection') {
	            const payload = value && typeof value === 'object' ? value : {};
	            const disabled = payload.selectable ? '' : ' disabled';
	            return '<label class="aysa-agent8v3-metadata-apply-select">' +
	                '<input type="checkbox" class="aysa-agent8v3-canonical-apply-row" data-payload="' + escapeHtml(JSON.stringify(payload)) + '"' + disabled + '>' +
	                '<span class="screen-reader-text">' + escapeHtml(text('select') || 'Select') + '</span>' +
	                '</label>';
	        }
	        if (column && column.type === 'schema_apply_selection') {
	            const payload = value && typeof value === 'object' ? value : {};
	            const disabled = payload.selectable ? '' : ' disabled';
	            return '<label class="aysa-agent8v3-metadata-apply-select">' +
	                '<input type="checkbox" class="aysa-agent8v3-schema-apply-row" data-payload="' + escapeHtml(JSON.stringify(payload)) + '"' + disabled + '>' +
	                '<span class="screen-reader-text">' + escapeHtml(text('select') || 'Select') + '</span>' +
	                '</label>';
	        }
	        if (column && column.type === 'image_optimization_apply_selection') {
	            const payload = value && typeof value === 'object' ? value : {};
	            const rejected = isImageOptimizationRejected(payload);
	            const selectable = !!payload.selectable;
	            const disabled = selectable && !rejected ? '' : ' disabled';
	            const checked = selectable && !rejected && payload.selected_by_default ? ' checked' : '';
	            const rejectLabel = state.language === 'Romanian' ? 'Nu e ok' : 'Reject';
	            const restoreLabel = state.language === 'Romanian' ? 'Restaurează' : 'Restore';
	            const statusLabel = rejected
	                ? (state.language === 'Romanian' ? 'Respins' : 'Rejected')
	                : (selectable ? (state.language === 'Romanian' ? 'Acceptat' : 'Accepted') : (state.language === 'Romanian' ? 'Blocat' : 'Blocked'));
	            const actionLabel = rejected ? restoreLabel : rejectLabel;
	            const action = rejected ? 'restore' : 'reject';
	            return '<span class="aysa-agent8v3-image-optimization-review-cell">' +
	                '<label class="aysa-agent8v3-metadata-apply-select">' +
	                '<input type="checkbox" class="aysa-agent8v3-image-optimization-apply-row" data-payload="' + escapeHtml(JSON.stringify(payload)) + '"' + checked + disabled + '>' +
	                '<span class="screen-reader-text">' + escapeHtml(text('select') || 'Select') + '</span>' +
	                '</label>' +
	                '<span class="aysa-agent8v3-mini-status">' + escapeHtml(statusLabel) + '</span>' +
	                (selectable || rejected
	                    ? '<button type="button" class="button button-small aysa-agent8v3-image-optimization-reject-row" data-operation="' + escapeHtml(action) + '" data-payload="' + escapeHtml(JSON.stringify(payload)) + '">' + escapeHtml(actionLabel) + '</button>'
	                    : '') +
	                '</span>';
	        }
	        if (column && column.type === 'image_alt_apply_selection') {
	            const payload = value && typeof value === 'object' ? value : {};
	            const selectable = !!payload.selectable;
	            const checked = payload.selected_by_default && selectable ? ' checked' : '';
	            const disabled = selectable ? '' : ' disabled';
	            return '<label class="aysa-agent8v3-metadata-apply-select">' +
	                '<input type="checkbox" class="aysa-agent8v3-image-alt-apply-row" data-payload="' + escapeHtml(JSON.stringify(payload)) + '"' + checked + disabled + '>' +
	                '<span class="screen-reader-text">' + escapeHtml(text('select') || 'Select') + '</span>' +
	                '</label>';
	        }
	        if (column && column.type === 'internal_linking_apply_selection') {
	            const payload = value && typeof value === 'object' ? value : {};
	            const rejected = isInternalLinkingRejected(payload);
	            const disabled = payload.selectable && !rejected ? '' : ' disabled';
	            const checked = payload.selectable && !rejected ? ' checked' : '';
	            const rejectLabel = state.language === 'Romanian' ? 'Nu e ok' : 'Reject';
	            const restoreLabel = state.language === 'Romanian' ? 'Restaurează' : 'Restore';
	            const statusLabel = rejected
	                ? (state.language === 'Romanian' ? 'Respins' : 'Rejected')
	                : (payload.selectable ? (state.language === 'Romanian' ? 'Acceptat' : 'Accepted') : (state.language === 'Romanian' ? 'Blocat' : 'Blocked'));
	            const actionLabel = rejected ? restoreLabel : rejectLabel;
	            const action = rejected ? 'restore' : 'reject';
	            return '<span class="aysa-agent8v3-internal-linking-review-cell">' +
	                '<label class="aysa-agent8v3-metadata-apply-select">' +
	                '<input type="checkbox" class="aysa-agent8v3-internal-linking-apply-row" data-payload="' + escapeHtml(JSON.stringify(payload)) + '"' + checked + disabled + '>' +
	                '<span class="screen-reader-text">' + escapeHtml(text('select') || 'Select') + '</span>' +
	                '</label>' +
	                '<span class="aysa-agent8v3-mini-status">' + escapeHtml(statusLabel) + '</span>' +
	                (payload.selectable || rejected
	                    ? '<button type="button" class="button button-small aysa-agent8v3-internal-linking-reject-row" data-operation="' + escapeHtml(action) + '" data-payload="' + escapeHtml(JSON.stringify(payload)) + '">' + escapeHtml(actionLabel) + '</button>'
	                    : '') +
	                '</span>';
	        }
	        if (column && column.type === 'safe_bundle_selection') {
	            const payload = value && typeof value === 'object' ? value : {};
	            const moduleKey = String(payload.module || '');
	            const item = payload.item && typeof payload.item === 'object' ? payload.item : {};
	            const rejected = !!payload.rejected_by_user || (moduleKey === 'image_optimization' && isImageOptimizationRejected(item));
	            const selectable = !!payload.exclusion_allowed && !rejected;
	            const checked = payload.selected_by_default && !rejected ? ' checked' : '';
	            const disabled = selectable ? '' : ' disabled';
	            const rowId = String(payload.row_id || '');
	            const cost = String(parseInt(payload.cost_cents || 0, 10) || 0);
	            const choiceLabel = String(uiLanguage() || '').indexOf('ro') === 0 ? 'Alege rândul' : 'Choose row';
	            const uiExcluded = !!technicalSafeBundleUiExclusions().rows[rowId];
	            const reviewAction = payload.review_action && typeof payload.review_action === 'object' ? payload.review_action : null;
	            const reviewButton = reviewAction && reviewAction.action
	                ? '<button type="button" class="button button-small aysa-agent8v3-modal-row-action" data-action="' + escapeHtml(reviewAction.action) + '" data-payload="' + escapeHtml(JSON.stringify(reviewAction.payload || reviewAction.context || {})) + '">' + escapeHtml(reviewAction.label || (rejected ? 'Restaurează' : 'Nu e ok')) + '</button>'
	                : '';
	            return '<span class="aysa-agent8v3-safe-bundle-review-cell"><label class="aysa-agent8v3-safe-bundle-select">' +
	                '<input type="checkbox" class="aysa-agent8v3-safe-bundle-row" aria-label="' + escapeHtml(choiceLabel) + '" data-module="' + escapeHtml(moduleKey) + '" data-row-id="' + escapeHtml(rowId) + '" data-cost="' + escapeHtml(cost) + '" data-payload="' + escapeHtml(JSON.stringify(payload)) + '"' + (uiExcluded ? '' : checked) + disabled + '>' +
	                '</label>' + reviewButton + '</span>';
	        }
	        if (column && column.type === 'authority_plan_selection') {
	            const payload = value && typeof value === 'object' ? value : {};
	            const selectable = !!payload.selectable;
	            const checked = selectable && payload.selected ? ' checked' : '';

            const disabled = selectable ? '' : ' disabled';
            const label = String(uiLanguage() || '').indexOf('ro') === 0 ? 'Selectează linia' : 'Select line';
            return '<label class="aysa-agent8v3-authority-plan-selection">' +
                '<input type="checkbox" class="aysa-agent8v3-authority-plan-row" aria-label="' + escapeHtml(label) + '" data-line-id="' + escapeHtml(String(payload.line_id || '')) + '" data-recommendation-id="' + escapeHtml(String(payload.recommendation_id || '')) + '"' + checked + disabled + '>' +
                '<span class="screen-reader-text">' + escapeHtml(label) + '</span>' +
                '</label>';
        }
        if (column && column.type === 'authority_plan_links') {
            const links = Array.isArray(value) ? value : [];
            return links.map(function(link) {
                link = link && typeof link === 'object' ? link : {};
                const anchor = String(link.anchor || '');
                const url = String(link.url || '');
                return '<span class="aysa-agent8-authority-plan-link">' + escapeHtml(anchor ? anchor + ': ' : '') + escapeHtml(url) + '</span>';
            }).join('<br>') || '-';
        }
	        if (column && column.type === 'internal_linking_history_actions') {
	            const payload = value && typeof value === 'object' ? value : {};
	            const historyId = String(payload.history_id || '');
	            const restoreDisabled = payload.restore_available ? '' : ' disabled';
	            const reverifyLabel = state.language === 'Romanian' ? 'Reverifică' : 'Re-verify';
	            const restoreLabel = state.language === 'Romanian' ? 'Restaurează' : 'Restore';
	            return '<span class="aysa-agent8v3-action-with-badges">' +
	                '<button type="button" class="button button-small aysa-agent8v3-internal-linking-history-action" data-operation="reverify" data-history-id="' + escapeHtml(historyId) + '">' + escapeHtml(reverifyLabel) + '</button> ' +
	                '<button type="button" class="button button-small aysa-agent8v3-internal-linking-history-action" data-operation="restore" data-history-id="' + escapeHtml(historyId) + '"' + restoreDisabled + '>' + escapeHtml(restoreLabel) + '</button>' +
	                '</span>';
	        }
        if (column && column.type === 'action' && value && typeof value === 'object') {
            const activeOnPageTab = String((state.modal.current && state.modal.current.active_tab) || (state.modal.filters && state.modal.filters.tab) || 'keyword_mapping');
            if (state.modal.key === 'onpage_seo' && activeOnPageTab === 'keyword_mapping' && key === 'review_action' && String(row.review_status || '') === 'rejected') {
                return renderOnPageKeywordRemap(row);
            }
            const disabled = value.disabled || !value.action ? ' disabled' : '';
            const label = value.label || text(value.action || '') || value.action || 'Action';
            const display = normalizeActionDisplayForAction(value, state.modal.current || {});
            let actionPayload = value.payload && typeof value.payload === 'object' ? value.payload : {};
            if (value.action === 'revert_onpage_item' && !String(actionPayload.entity_key || '').trim()) {
                const entityKey = String(row.entity_key || '').trim();
                actionPayload = entityKey ? {
                    section: 'meta_snippets',
                    operation: 'apply_meta',
                    item_id: entityKey,
                    entity_key: entityKey,
                    label: String(row.entity || row.page_url || entityKey)
                } : {};
            }
            if (state.modal.key === 'technical_internal_linking') {
                const isRestore = String(value.action || '').indexOf('restore') !== -1;
                return '<button type="button" class="button aysa-agent8v3-modal-row-action is-icon-only" title="' + escapeHtml(label) + '" aria-label="' + escapeHtml(label) + '" data-action="' + escapeHtml(value.action || '') + '" data-payload="' + escapeHtml(JSON.stringify(value.payload || {})) + '"' + disabled + '>' +
                    '<span aria-hidden="true">' + (isRestore ? '↺' : '×') + '</span>' +
                    '</button>';
            }
            return '<span class="aysa-agent8v3-action-with-badges">' +
                '<button type="button" class="button aysa-agent8v3-modal-row-action" data-action="' + escapeHtml(value.action || '') + '" data-payload="' + escapeHtml(JSON.stringify(actionPayload)) + '"' + disabled + '>' + escapeHtml(display.label) + '</button>' +
                actionBadgesHtml(display.badges) +
            '</span>';
        }
        if (state.modal.key === 'technical_internal_linking') {
            if (key === 'entity_page' || key === 'source_display' || key === 'target_display') {
                return renderInternalLinkPage(value);
            }
            if (key === 'anchor_display') {
                return renderInternalLinkAnchor(value);
            }
            if (key === 'signals') {
                return renderInternalLinkSignals(value);
            }
            if (key === 'entity_links') {
                return renderInternalLinkEntityLinks(value);
            }
            if (key === 'configured_keywords') {
                return renderInternalLinkKeywords(value);
            }
            if (key === 'stat_action') {
                return renderInternalLinkStatAction(value);
            }
            if (key === 'automation_status') {
                return renderCompactStatusIcon('automation', value);
            }
            if (key === 'execution_status') {
                return renderCompactStatusIcon('execution', value);
            }
            if (key === 'review_status') {
                return renderCompactStatusIcon('review', value);
            }
        }
        if (state.modal.key === 'onpage_seo' && (key === 'entity' || key === 'page')) {
            return renderOnPageEntity(row, value);
        }
        if (state.modal.key === 'onpage_seo' && key === 'keyword_summary') {
            return renderOnPageKeywords(value);
        }
        if (state.modal.key === 'onpage_seo' && key === 'status_summary') {
            return renderOnPageStatuses(value);
        }
        if (state.modal.key === 'onpage_seo' && key === 'next_action') {
            return renderOnPageNextAction(value);
        }
        if (state.modal.key === 'onpage_seo' && key === 'aeo_preview') {
            return renderOnPageAeoPreview(value);
        }
        if (
            state.modal.key === 'technical_site_audit' &&
            state.modal.filters &&
            (state.modal.filters.tab === 'internal_linking_preview' || state.modal.filters.tab === 'internal_linking_history') &&
            (key === 'source_page' || key === 'target_page')
        ) {
            return renderInternalLinkPage(value);
        }
        if (key === 'source_url' || key === 'target_url' || key === 'url' || key === 'canonical' || key === 'download_url' || key === 'image_url' || key === 'page_url') {
            return renderModalUrl(value);
        }
        if (state.modal.key === 'offpage_seo' && key === 'article_preview') {
            return renderOffPageArticlePreview(value);
        }
        if (key === 'name' && String(state.modal.key || '').indexOf('technical_') === 0 && String((state.modal.filters && state.modal.filters.tab) || '') === 'fixes') {
            return renderTechnicalFixName(row, value);
        }
        if (key === 'cluster' && state.modal.key === 'keyword_mapping') {
            return renderMappingCluster(row);
        }
        if (key === 'keyword_family' && state.modal.key === 'keyword_mapping') {
            return renderKeywordFamily(value);
        }
        if (key === 'schema_items' && state.modal.key === 'technical_schema') {
            return renderSchemaItems(row);
        }
        if (key === 'signals' && state.modal.key === 'keyword_mapping') {
            return renderMappingSignals(row);
        }
        if (key === 'intent') {
            return renderModalChip('intent', intentIcon(value), localizedModalValue('intent', value), value);
        }
        if (key === 'status') {
            return renderModalChip('status', statusIcon(value), localizedModalValue('status', value), value);
        }
        if (key === 'execution_status') {
            if (String(state.modal.key || '').indexOf('technical_') === 0) {
                return renderModalChip('status', statusIcon(value), technicalFixExecutionStatusLabel(value || '-'), value);
            }
            return renderModalChip('status', statusIcon(value), modalLabel(value || '-', value), value);
        }
        if (key === 'automation_status') {
            return renderAutomationStatus(value);
        }
        if (key === 'confidence') {
            return renderModalChip('confidence', '◔', confidenceLabel(value), value);
        }
        if (key === 'trust_score') {
            return renderModalChip('trust', '◆', trustLabel(value), value);
        }
        if (key === 'recommendation') {
            return renderModalChip('quality ' + String(value || ''), qualityIcon(value), localizedModalValue('quality', value), value);
        }
        if (key === 'quality_reasons') {
            return renderQualityReasons(value);
        }
        if (key === 'review_status') {
            const status = String(value || '');
            return renderModalChip('review ' + status, status === 'rejected' ? '×' : '✓', modalLabel(status || '-', status), status);
        }
        if (String(state.modal.key || '').indexOf('technical_') === 0) {
            return renderTechnicalInlineText(technicalClientDisplayText(value));
        }
        return escapeHtml(clientFacingLabel(value));
    }

    function renderTechnicalInlineText(value) {
        const input = String(value === undefined || value === null ? '' : value);
        const pattern = /\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g;
        let html = '';
        let cursor = 0;
        let match;
        while ((match = pattern.exec(input)) !== null) {
            html += escapeHtml(input.slice(cursor, match.index));
            html += '<a href="' + escapeHtml(match[2]) + '" target="_blank" rel="noopener noreferrer">' + escapeHtml(match[1]) + '</a>';
            cursor = match.index + match[0].length;
        }
        html += escapeHtml(input.slice(cursor));
        return html || '-';
    }

    function renderInternalLinkPage(value) {
        const item = value && typeof value === 'object' ? value : { title: String(value || '-'), url: '' };
        const title = String(item.title || item.url || '-');
        const url = String(item.url || '');
        return '<div class="aysa-agent8v3-il-page" title="' + escapeHtml((title || '') + (url ? '\n' + url : '')) + '">' +
            '<strong>' + escapeHtml(title) + '</strong>' +
            (url ? renderModalUrl(url) : '') +
            '</div>';
    }

    function renderInternalLinkRoute(source, target) {
        return '<div class="aysa-agent8v3-il-route">' +
            '<div><span>' + escapeHtml(text('modalSourceUrl')) + '</span>' + renderInternalLinkPage(source || {}) + '</div>' +
            '<b aria-hidden="true">→</b>' +
            '<div><span>' + escapeHtml(text('modalTargetUrl')) + '</span>' + renderInternalLinkPage(target || {}) + '</div>' +
            '</div>';
    }

    function renderInternalLinkAnchor(value) {
        const item = value && typeof value === 'object' ? value : { anchor: String(value || '-') };
        const anchor = String(item.anchor || '-');
        const keyword = String(item.keyword || '');
        const matchType = String(item.match_type || '');
        const risks = Array.isArray(item.risk_flags) ? item.risk_flags.filter(Boolean) : [];
        const title = [anchor, keyword, matchType].concat(risks).filter(Boolean).join(' · ');
        return '<div class="aysa-agent8v3-il-anchor" title="' + escapeHtml(title || anchor) + '">' +
            '<strong>' + escapeHtml(anchor) + '</strong>' +
            '<span>' + escapeHtml([keyword && keyword !== anchor ? keyword : '', matchType].filter(Boolean).join(' · ') || '-') + '</span>' +
            '</div>';
    }

    function renderInternalLinkKeywords(value) {
        const keywords = Array.isArray(value) ? value.filter(Boolean).map(function(item) {
            return String(item || '').trim();
        }).filter(Boolean) : [];
        if (!keywords.length) {
            return '-';
        }
        const visible = keywords.slice(0, 4);
        const hidden = keywords.length - visible.length;
        return '<div class="aysa-agent8v3-il-keywords" title="' + escapeHtml(keywords.join(', ')) + '">' +
            visible.map(function(keyword) {
                return '<span class="aysa-agent8v3-il-keyword">' + escapeHtml(keyword) + '</span>';
            }).join('') +
            (hidden > 0 ? '<span class="aysa-agent8v3-il-more">+' + escapeHtml(String(hidden)) + ' ' + escapeHtml(text('internalLinkingKeywordsMore')) + '</span>' : '') +
            '</div>';
    }

    function renderInternalLinkStatAction(value) {
        const item = value && typeof value === 'object' ? value : {};
        const label = String(item.label || text('internalLinkingPlanHint') || 'View plan');
        const url = String(item.url || '');
        return '<button type="button" class="button button-small aysa-agent8v3-il-view-plan" data-url="' + escapeHtml(url) + '">' + escapeHtml(label) + '</button>';
    }

    function renderInternalLinkSignals(value) {
        const item = value && typeof value === 'object' ? value : { confidence: String(value || '-') };
        const risks = Array.isArray(item.risk_flags) ? item.risk_flags.filter(Boolean) : [];
        return '<div class="aysa-agent8v3-il-signals">' +
            renderModalChip('confidence', '◔', confidenceLabel(item.confidence), item.confidence) +
            (item.match_type ? '<span class="aysa-agent8v3-il-mini" title="' + escapeHtml(item.match_type) + '">' + escapeHtml(item.match_type) + '</span>' : '') +
            (risks.length ? '<span class="aysa-agent8v3-il-risk" title="' + escapeHtml(risks.join(', ')) + '">' + escapeHtml(String(risks.length)) + '</span>' : '') +
            '</div>';
    }

    function renderInternalLinkEntityLinks(value) {
        const links = Array.isArray(value) ? value : [];
        if (!links.length) {
            return '-';
        }
        const existing = links.filter(function(link) { return String((link && link.link_kind) || '') === 'existing'; });
        const proposed = links.filter(function(link) { return String((link && link.link_kind) || '') !== 'existing'; });
        const renderGroup = function(label, group) {
            if (!group.length) {
                return '<div class="aysa-agent8v3-il-empty">' + escapeHtml(text('noLinks')) + '</div>';
            }
            return '<div class="aysa-agent8v3-il-entity-group"><strong>' + escapeHtml(label) + '</strong>' + group.map(function(link) {
                const direction = String((link && link.direction) || '');
                const directionLabel = direction === 'inbound' ? text('inboundLinks') : text('outboundLinks');
                const action = link && link.review_action && typeof link.review_action === 'object' ? link.review_action : null;
                return '<div class="aysa-agent8v3-il-entity-link">' +
                    '<span class="aysa-agent8v3-il-direction">' + escapeHtml(directionLabel) + '</span>' +
                    renderInternalLinkRoute(link && link.source, link && link.target) +
                    renderInternalLinkAnchor((link && link.anchor) || {}) +
                    renderInternalLinkSignals((link && link.signals) || {}) +
                    renderCompactStatusIcon('automation', link && link.automation_status) +
                    renderCompactStatusIcon('execution', link && link.execution_status) +
                    renderCompactStatusIcon('review', link && link.review_status) +
                    (action ? '<button type="button" class="button aysa-agent8v3-modal-row-action is-icon-only" title="' + escapeHtml(action.label || '') + '" aria-label="' + escapeHtml(action.label || '') + '" data-action="' + escapeHtml(action.action || '') + '" data-payload="' + escapeHtml(JSON.stringify(action.payload || {})) + '"><span aria-hidden="true">' + (String(action.action || '').indexOf('restore') !== -1 ? '↺' : '×') + '</span></button>' : '') +
                    '</div>';
            }).join('') + '</div>';
        };
        return '<details class="aysa-agent8v3-il-entity-links"><summary>' + escapeHtml(String(links.length)) + ' ' + escapeHtml(text('internalLinks')) + '</summary>' +
            '<div>' +
                renderGroup(text('existingLinks'), existing) +
                renderGroup(text('proposedLinks'), proposed) +
            '</div></details>';
    }

    function renderCompactStatusIcon(kind, value) {
        const raw = String(value || '').trim();
        let icon = '•';
        let label = modalLabel(raw || '-', raw);
        if (kind === 'automation') {
            if (raw === 'a8_automated') {
                icon = '✓';
                label = text('modalA8Automated');
            } else if (raw === 'partial_automation') {
                icon = '◐';
                label = text('modalPartialAutomation');
            } else {
                icon = '!';
                label = text('modalManualReview');
            }
        } else if (kind === 'review') {
            icon = raw === 'rejected' ? '×' : '✓';
            label = modalLabel(raw || '-', raw);
        } else if (kind === 'execution') {
            icon = statusIcon(raw);
            label = modalLabel(raw || '-', raw);
        }
        return '<span class="aysa-agent8v3-il-icon is-' + escapeHtml(kind) + ' is-' + escapeHtml(raw.replace(/[^a-z0-9_-]+/gi, '-').toLowerCase() || 'empty') + '" title="' + escapeHtml(label) + '" aria-label="' + escapeHtml(label) + '">' +
            '<span aria-hidden="true">' + escapeHtml(icon) + '</span>' +
            '</span>';
    }

    function renderMappingCluster(row) {
        const cluster = String((row && row.cluster) || '').trim();
        const primary = String((row && row.primary_keyword) || '').trim();
        return '<div class="aysa-agent8v3-modal-cluster"><strong>' + escapeHtml(cluster || '-') + '</strong>' +
            (primary && primary !== cluster ? '<span>' + escapeHtml(primary) + '</span>' : '') +
            '</div>';
    }

    function renderKeywordFamily(value) {
        const raw = String(value || '').trim();
        if (!raw || raw === '-') {
            return '-';
        }
        const items = raw.split(',').map(function(item) {
            return item.trim();
        }).filter(Boolean);
        const visible = items.slice(0, 4);
        const extra = Math.max(0, items.length - visible.length);
        return '<div class="aysa-agent8v3-keyword-family" title="' + escapeHtml(raw) + '">' +
            visible.map(function(item) {
                return '<span>' + escapeHtml(item) + '</span>';
            }).join('') +
            (extra ? '<button type="button" class="button-link aysa-agent8v3-keyword-family-toggle" data-expanded="0" data-extra="' + escapeHtml(JSON.stringify(items.slice(visible.length))) + '">+' + escapeHtml(extra) + ' keywords</button>' : '') +
            '</div>';
    }

    function renderSchemaItems(row) {
        const items = Array.isArray(row && row.schema_items) ? row.schema_items : [];
        if (!items.length) {
            return '-';
        }
        const visible = items.slice(0, 2);
        const extra = Math.max(0, items.length - visible.length);
        return '<div class="aysa-agent8v3-schema-items">' +
            visible.map(function(item) {
                const type = String((item && item.schema_type) || '-');
                const problem = String((item && item.problem) || '-');
                const automation = String((item && item.automation_status) || '');
                const source = String((item && (item.source_label || item.schema_role)) || '');
                const graphRole = String((item && (item.graph_role_label || item.graph_role)) || '');
                const graphRoleKey = String((item && item.graph_role) || 'supporting');
                return '<span class="aysa-agent8v3-schema-item" title="' + escapeHtml(problem) + '">' +
                    '<strong>' + escapeHtml(type) + '</strong>' +
                    (graphRole ? '<em class="aysa-agent8v3-schema-graph-role is-' + escapeHtml(graphRoleKey) + '">' + escapeHtml(graphRole) + '</em>' : '') +
                    (source ? '<em>' + escapeHtml(source) + '</em>' : '') +
                    (automation ? renderAutomationStatus(automation) : '') +
                    '<small>' + escapeHtml(problem) + '</small>' +
                    '</span>';
            }).join('') +
            (extra ? '<button type="button" class="button-link aysa-agent8v3-schema-items-toggle" data-expanded="0" data-extra="' + escapeHtml(JSON.stringify(items.slice(visible.length))) + '">+' + escapeHtml(extra) + ' ' + escapeHtml(text('modalSchemaMoreItems')) + '</button>' : '') +
            '</div>';
    }

    function renderMappingSignals(row) {
        return '<div class="aysa-agent8v3-modal-signals">' +
            renderModalChip('intent', intentIcon(row && row.intent), localizedModalValue('intent', row && row.intent), row && row.intent) +
            renderModalChip('status', statusIcon(row && row.status), localizedModalValue('status', row && row.status), row && row.status) +
            renderModalChip('confidence', '◔', confidenceLabel(row && row.confidence), row && row.confidence) +
            ((row && row.recommendation && row.recommendation !== '-') ? renderModalChip('quality ' + String(row.recommendation || ''), qualityIcon(row.recommendation), localizedModalValue('quality', row.recommendation), row.recommendation) : '') +
            renderModalChip('review ' + String((row && row.review_status) || ''), String((row && row.review_status) || '') === 'rejected' ? '×' : '✓', modalLabel((row && row.review_status) || '-', (row && row.review_status) || ''), row && row.review_status) +
            '</div>';
    }

    function renderQualityReasons(value) {
        const raw = String(value || '').trim();
        if (!raw || raw === '-') {
            return '-';
        }
        const display = clientFacingLabel(raw);
        return '<span class="aysa-agent8v3-modal-reasons" title="' + escapeHtml(display) + '">' + escapeHtml(display) + '</span>';
    }

    function renderModalUrl(value) {
        const raw = String(value || '').trim();
        if (!raw) {
            return '-';
        }
        let label = raw.replace(/^https?:\/\//, '').replace(/^www\./, '');
        if (label.length > 42) {
            label = label.slice(0, 28) + '…' + label.slice(-10);
        }
        return '<a class="aysa-agent8v3-modal-url" href="' + escapeHtml(raw) + '" target="_blank" rel="noopener noreferrer" title="' + escapeHtml(raw) + '">' + escapeHtml(label) + '</a>';
    }

    function renderOffPageArticlePreview(value) {
        if (!value || typeof value !== 'object') {
            return '<span class="aysa-agent8v3-muted">' + escapeHtml(String(value || '-')) + '</span>';
        }
        const title = String(value.title || 'Article draft');
        const words = parseInt(value.word_count, 10) || 0;
        const minimum = parseInt(value.minimum_words, 10) || 2000;
        const body = String(value.body_html || '');
        return '<details class="aysa-agent8v3-onpage-preview">' +
            '<summary>' + escapeHtml(title + ' · ' + words + '/' + minimum + ' words') + '</summary>' +
            '<div class="aysa-agent8v3-muted">Homepage: ' + renderModalUrl(value.homepage_url || '') + '</div>' +
            '<div class="aysa-agent8v3-muted">Target: ' + renderModalUrl(value.target_url || '') + '</div>' +
            '<div>' + sanitizeModalHtml(body) + '</div>' +
        '</details>';
    }

    function renderOnPageEntity(row, value) {
        const raw = String(value || '').trim();
        const url = String((row && (row.page_url || row.url || row.permalink)) || '').trim();
        let title = raw || '-';
        if (url && raw.indexOf('|') !== -1) {
            title = raw.split('|')[0].trim() || raw;
        }
        if (!url) {
            return '<div class="aysa-agent8v3-onpage-entity"><strong>' + escapeHtml(title) + '</strong><span>URL unresolved</span></div>';
        }
        const entityType = String((row && (row.entity_type || row.type)) || '').trim();
        const aysaGenerated = String((row && (row.aysa_generated || row.publication_badge)) || '').trim();
        return '<div class="aysa-agent8v3-onpage-entity" title="' + escapeHtml((raw || title) + '\n' + url) + '">' +
            '<strong>' + escapeHtml(title) + '</strong>' +
            renderModalUrl(url) +
            '<span class="aysa-agent8v3-onpage-meta">' +
                (entityType ? '<em>' + escapeHtml(entityType) + '</em>' : '') +
                (aysaGenerated && aysaGenerated !== '-' ? '<em class="is-aysa-generated">' + escapeHtml(aysaGenerated) + '</em>' : '') +
            '</span>' +
            '</div>';
    }

    function renderOnPageKeywords(value) {
        const item = value && typeof value === 'object' ? value : { primary: String(value || '-'), family: '' };
        const primary = String(item.primary || '-').trim();
        const familyRaw = String(item.family || '').trim();
        const family = familyRaw && familyRaw !== '-' ? familyRaw.split(',').map(function(keyword) {
            return keyword.trim();
        }).filter(Boolean) : [];
        const visible = family.slice(0, 4);
        return '<div class="aysa-agent8v3-onpage-keywords" title="' + escapeHtml([primary].concat(family).filter(Boolean).join(', ')) + '">' +
            '<strong>' + escapeHtml(primary || '-') + '</strong>' +
            (visible.length ? '<span>' + visible.map(function(keyword) {
                return '<em>' + escapeHtml(keyword) + '</em>';
            }).join('') + (family.length > visible.length ? '<em>+' + escapeHtml(String(family.length - visible.length)) + '</em>' : '') + '</span>' : '') +
            '</div>';
    }

    function renderOnPageStatuses(value) {
        const item = value && typeof value === 'object' ? value : {};
        const entries = [
            ['Mapping', item.mapping],
            ['Meta', item.meta],
            ['Content', item.content],
            ['Links', item.links],
            ['Overall', item.overall]
        ];
        return '<div class="aysa-agent8v3-onpage-statuses">' + entries.map(function(entry) {
            const label = String(entry[0] || '');
            const status = String(entry[1] || '-');
            const cls = status.replace(/[^a-z0-9_-]+/gi, '-').toLowerCase() || 'empty';
            return '<span class="aysa-agent8v3-onpage-status is-' + escapeHtml(cls) + '" title="' + escapeHtml(label + ': ' + status) + '">' +
                '<b>' + escapeHtml(label) + '</b><em>' + escapeHtml(status) + '</em>' +
            '</span>';
        }).join('') + '</div>';
    }

    function renderOnPageNextAction(value) {
        const label = String(value || '-').trim();
        return '<span class="aysa-agent8v3-onpage-next" title="' + escapeHtml(label || '-') + '">' + escapeHtml(label || '-') + '</span>';
    }

    function renderOnPageAeoPreview(value) {
        const data = value && typeof value === 'object' ? value : {};
        const summary = String(data.summary || '').trim();
        const faq = String(data.faq || '').trim();
        const jsonld = String(data.jsonld || '').trim();
        const status = String(data.status || '').trim();
        if (!summary && !faq && !jsonld) {
            return '<span class="aysa-agent8v3-muted">-</span>';
        }
        const blocks = [];
        if (status) {
            blocks.push('<div class="aysa-agent8v3-onpage-preview-status">' + escapeHtml(status) + '</div>');
        }
        if (summary) {
            blocks.push('<details class="aysa-agent8v3-onpage-preview" open><summary>AI Summary</summary><div>' + sanitizeModalHtml(summary) + '</div></details>');
        }
        if (faq) {
            blocks.push('<details class="aysa-agent8v3-onpage-preview"><summary>FAQ Block</summary><div>' + sanitizeModalHtml(faq) + '</div></details>');
        }
        if (jsonld) {
            blocks.push('<details class="aysa-agent8v3-onpage-preview"><summary>JSON-LD FAQ</summary><pre>' + escapeHtml(jsonld) + '</pre></details>');
        }
        return blocks.join('');
    }

    function renderOnPageContentCards(rows, modal) {
        const actionByOperation = onPageContentActionMap(modal);
        return '<div class="aysa-agent8v3-onpage-content-layout">' +
            '<div class="aysa-agent8v3-onpage-content-list">' +
                rows.map(function(row) {
                    return renderOnPageContentCard(row, actionByOperation);
                }).join('') +
            '</div>' +
        '</div>' + renderOnPageContentRewriteHistoryPanel() + renderModalLegend(modal);
    }

    function renderOnPageContentRewriteHistoryPanel() {
        const ro = state.language === 'Romanian' || String(uiLanguage() || '').indexOf('ro') === 0;
        const model = state.onPageContentRewriteHistory || {};
        const rows = Array.isArray(model.rows) ? model.rows : [];
        const message = model.message ? '<div class="aysa-agent8v3-image-alt-test-message">' + escapeHtml(model.message) + '</div>' : '';
        const intro = ro
            ? 'Restore revine la textul salvat înainte de Content Rewrite. Se execută doar pe un history_id, verifică hash-ul curent înainte de scriere și nu debitează credite.'
            : 'Restore reverts to the text saved before Content Rewrite. It runs only for one history_id, verifies the current hash before writing, and does not bill credits.';
        const body = rows.length ? '<div class="aysa-agent8v3-image-alt-test-table-wrap"><table class="aysa-agent8v3-image-alt-test-table"><thead><tr>' +
            '<th>History</th><th>Target</th><th>Status</th><th>' + escapeHtml(ro ? 'Vechi' : 'Old') + '</th><th>' + escapeHtml(ro ? 'Curent' : 'Current') + '</th><th>Billing</th><th>Restore</th>' +
            '</tr></thead><tbody>' + rows.map(function(row) {
                const historyId = String(row.history_id || '');
                const restoreAvailable = !!row.restore_available;
                const restored = String(row.restored_at || '') !== '' || ['verified', 'already_restored'].indexOf(String(row.restore_status || '')) !== -1;
                const restoreLabel = restored ? (ro ? 'Restaurat' : 'Restored') : (restoreAvailable ? (ro ? 'Restaurează' : 'Restore') : (ro ? 'Indisponibil' : 'Unavailable'));
                return '<tr>' +
                    '<td><strong>' + escapeHtml(historyId || '-') + '</strong><br><small>' + escapeHtml(String(row.entity_key || row.entity_id || '-')) + '</small></td>' +
                    '<td>' + escapeHtml(String(row.target || '-')) + '<br><small>' + escapeHtml(String(row.content_surface || '-')) + '</small></td>' +
                    '<td>' + escapeHtml(String(row.status || '-')) + '<br><small>' + escapeHtml(String(row.verification_status || row.restore_status || '-')) + '</small></td>' +
                    '<td>' + escapeHtml(String(row.old_preview || '-')) + '</td>' +
                    '<td>' + escapeHtml(String(row.current_preview || '-')) + '<br><small>' + escapeHtml(row.current_hash_matches_after ? (ro ? 'hash după apply OK' : 'after hash OK') : (row.current_hash_matches_before ? (ro ? 'deja restaurat' : 'already restored') : (ro ? 'hash diferit' : 'hash differs'))) + '</small></td>' +
                    '<td>' + escapeHtml(String(row.billing_cost_cents || 0)) + '<br><small>' + escapeHtml(String(row.restore_billing_status || 'not_billable_restore')) + '</small></td>' +
                    '<td>' + (restoreAvailable
                        ? '<button type="button" class="button button-small aysa-agent8v3-onpage-content-rewrite-history-action" data-operation="restore" data-history-id="' + escapeHtml(historyId) + '">' + escapeHtml(restoreLabel) + '</button>'
                        : '<span class="aysa-agent8v3-image-alt-test-muted">' + escapeHtml(restoreLabel) + '</span>') + '</td>' +
                '</tr>';
            }).join('') + '</tbody></table></div>' : '<div class="aysa-agent8v3-image-alt-test-empty">' + escapeHtml(model.loading ? (ro ? 'Se încarcă istoricul Content Rewrite...' : 'Loading Content Rewrite history...') : (ro ? 'Nu există încă istoric Content Rewrite restaurabil.' : 'No restorable Content Rewrite history yet.')) + '</div>';
        return '<section class="aysa-agent8v3-image-alt-test-panel aysa-agent8v3-onpage-content-restore-panel" aria-label="Content Rewrite restore history">' +
            '<div class="aysa-agent8v3-image-alt-test-head">' +
                '<div><strong>' + escapeHtml(ro ? 'Istoric și restore Content Rewrite' : 'Content Rewrite history and restore') + '</strong><p>' + escapeHtml(intro) + '</p></div>' +
                '<span>' + escapeHtml(ro ? '0 credite restore' : '0 credits restore') + '</span>' +
            '</div>' + message + body +
        '</section>';
    }

    function refreshOnPageContentRewriteHistoryPanel() {
        if (state.modal && state.modal.key === 'onpage_seo' && state.modal.current && String(state.modal.current.active_tab || (state.modal.current.filters && state.modal.current.filters.tab) || '') === 'content') {
            $('.aysa-agent8v3-onpage-content-restore-panel').replaceWith(renderOnPageContentRewriteHistoryPanel());
        }
    }

    function maybeLoadOnPageContentRewriteHistory(force) {
        if (!force && (state.onPageContentRewriteHistory.loaded || state.onPageContentRewriteHistory.loading)) {
            refreshOnPageContentRewriteHistoryPanel();
            return;
        }
        state.onPageContentRewriteHistory.loading = true;
        refreshOnPageContentRewriteHistoryPanel();
        rawAjax('aysa_agent8v3_onpage_content_rewrite_history_action', {
            operation: 'list',
            project_id: currentAgent8ProjectId()
        }).done(function(response) {
            if (response && response.success && response.data) {
                state.onPageContentRewriteHistory.rows = Array.isArray(response.data.history) ? response.data.history : [];
                state.onPageContentRewriteHistory.loaded = true;
                state.onPageContentRewriteHistory.message = '';
            }
        }).fail(function(xhr) {
            state.onPageContentRewriteHistory.message = apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Content Rewrite history load failed.');
        }).always(function() {
            state.onPageContentRewriteHistory.loading = false;
            refreshOnPageContentRewriteHistoryPanel();
        });
    }

    function onPageContentActionMap(modal) {
        const actions = Array.isArray(modal.actions) ? modal.actions : [];
        return actions.reduce(function(map, action) {
            const payload = action && action.payload ? action.payload : {};
            const runType = String(payload.run_type || '');
            const operation = String(payload.operation || '');
            if (runType === 'rewrite_decide') {
                map.decide = action;
            } else if (runType === 'rewrite_generate') {
                map.generate = action;
            } else if (operation === 'apply_rewrite') {
                map.apply = action;
                const selection = Array.isArray(payload.selection) ? payload.selection : [];
                const acceptedItems = Array.isArray(payload.accepted_items) ? payload.accepted_items : [];
                const entityKey = String(selection[0] || (acceptedItems[0] && acceptedItems[0].entity_key) || '');
                if (entityKey && acceptedItems.length === 1) {
                    map.applyByEntity = map.applyByEntity || {};
                    map.applyByEntity[entityKey] = map.applyByEntity[entityKey] || {};
                    if (payload.op26_final_write_confirmed) {
                        map.applyByEntity[entityKey].final = action;
                    } else {
                        map.applyByEntity[entityKey].preflight = action;
                    }
                }
            }
            return map;
        }, {});
    }

    function renderOnPageContentCard(row, actionByOperation) {
        const review = row && row.content_review && typeof row.content_review === 'object' ? row.content_review : {};
        const status = onPageContentUiStatus(row, review);
        const action = onPageContentRowAction(row, review, status, actionByOperation);
        const title = String((row && (row.page_title_raw || row.entity || row.page)) || '-').split('|')[0].trim() || '-';
        const url = String((row && (row.page_url || row.url)) || '');
        const keyword = String((row && (row.primary_keyword || row.keyword)) || '-');
        const type = String((row && (row.entity_type || review.page_type)) || '-');
        const nextStep = String((row && row.content_next_step) || '-');
        const contentTitle = String(review.content_title || '');
        const description = String(review.content_description || review.rewrite_reason || '');
        const draft = sanitizeOnPageContentDraft(String(review.draft_html || '').trim());
        const meta = [
            review.target_length && review.target_length !== 'TBD' ? 'Target: ' + review.target_length : '',
            review.final_length_strategy ? String(review.final_length_strategy) : '',
            review.review_required === true ? 'Review necesar' : '',
            Array.isArray(review.risk_flags) && review.risk_flags.length ? 'Riscuri: ' + review.risk_flags.join(', ') : ''
        ].filter(Boolean);
        return '<article class="aysa-agent8v3-content-card is-' + escapeHtml(status.key) + '">' +
            '<div class="aysa-agent8v3-content-card-main">' +
                '<div class="aysa-agent8v3-content-card-head">' +
                    '<span class="aysa-agent8v3-content-type">' + escapeHtml(type) + '</span>' +
                    '<span class="aysa-agent8v3-content-status">' + escapeHtml(status.label) + '</span>' +
                '</div>' +
                '<h3>' + escapeHtml(title) + '</h3>' +
                (url ? renderModalUrl(url) : '') +
                '<div class="aysa-agent8v3-content-keyword"><span>Keyword</span><strong>' + escapeHtml(keyword) + '</strong></div>' +
                '<p class="aysa-agent8v3-content-next">' + escapeHtml(nextStep) + '</p>' +
                (description ? '<p class="aysa-agent8v3-content-reason">' + escapeHtml(description) + '</p>' : '') +
                (meta.length ? '<div class="aysa-agent8v3-content-meta">' + meta.map(function(item) { return '<span>' + escapeHtml(item) + '</span>'; }).join('') + '</div>' : '') +
            '</div>' +
            '<aside class="aysa-agent8v3-content-preview">' +
                '<div class="aysa-agent8v3-content-preview-head">' +
                    '<strong>' + escapeHtml(contentTitle || 'Preview conținut') + '</strong>' +
                    (action ? renderOnPageContentActionButton(action, row, status) : '') +
                '</div>' +
                (draft ? '<div class="aysa-agent8v3-content-draft">' + draft + '</div>' : '<div class="aysa-agent8v3-content-empty">' + escapeHtml(status.empty) + '</div>') +
                (review.apply_note ? '<p class="aysa-agent8v3-content-apply-note">' + escapeHtml(review.apply_note) + '</p>' : '') +
            '</aside>' +
        '</article>';
    }

    function sanitizeOnPageContentDraft(raw) {
        if (!raw) {
            return '';
        }
        const $draft = $('<div></div>').html(raw);
        $draft.find('script, iframe, object, embed, link, meta, style').remove();
        $draft.find('*').each(function() {
            Array.prototype.slice.call(this.attributes || []).forEach(function(attr) {
                const name = String(attr.name || '').toLowerCase();
                const value = String(attr.value || '');
                if (name.indexOf('on') === 0 || (['href', 'src'].indexOf(name) !== -1 && /^\s*javascript:/i.test(value))) {
                    $(attr.ownerElement).removeAttr(attr.name);
                }
            });
        });
        return $draft.html();
    }

    function onPageContentUiStatus(row, review) {
        const next = String((row && row.content_next_step) || '').toLowerCase();
        const contentStatus = String((row && row.content_status) || '').toLowerCase();
        const draft = String((review && review.draft_html) || '').trim();
        const rewriteNeeded = review && review.rewrite_needed === true;
        if (next.indexOf('mapping') !== -1) {
            return { key: 'blocked', label: 'Mapping de verificat', empty: 'AYSA nu generează conținut până când keywordul nu este confirmat pentru această pagină.' };
        }
        if (next.indexOf('nu rescrie') !== -1 || next.indexOf('do not rewrite') !== -1) {
            return { key: 'verify', label: 'Doar verificare SEO', empty: 'Articolul este conținut AYSA. Se verifică SEO, fără rescriere body.' };
        }
        if (contentStatus.indexOf('needs_improvement') !== -1 || contentStatus.indexOf('îmbun') !== -1) {
            return { key: 'improve', label: 'Necesită îmbunătățire', empty: 'Draftul există, dar nu a trecut toate verificările de calitate.' };
        }
        if (draft) {
            return { key: 'ready', label: 'Draft gata', empty: '' };
        }
        if (rewriteNeeded) {
            return { key: 'generate', label: 'Poate genera', empty: 'Decizia există. Următorul pas este generarea draftului.' };
        }
        return { key: 'evaluate', label: 'De evaluat', empty: 'AYSA va verifica dacă pagina are nevoie de conținut nou.' };
    }

    function onPageContentRowAction(row, review, status, actionByOperation) {
        if (status.key === 'ready') {
            const entityKey = String(row && row.entity_key || '');
            const rowApply = actionByOperation.applyByEntity && entityKey ? actionByOperation.applyByEntity[entityKey] : null;
            if (rowApply && rowApply.final) {
                return rowApply.final;
            }
            if (rowApply && rowApply.preflight) {
                return rowApply.preflight;
            }
            return null;
        }
        if (status.key === 'generate') {
            return actionByOperation.generate || null;
        }
        if (status.key === 'evaluate') {
            return actionByOperation.decide || null;
        }
        return null;
    }

    function renderOnPageContentActionButton(action, row, status) {
        const payload = action && action.payload ? Object.assign({}, action.payload) : {};
        if (row && row.entity_key) {
            payload.selection = [String(row.entity_key)];
        }
        if (Array.isArray(payload.accepted_items)) {
            payload.accepted_items = payload.accepted_items.filter(function(item) {
                return item && String(item.entity_key || '') === String(row && row.entity_key || '');
            });
        }
        if (Array.isArray(payload.selection_meta)) {
            payload.selection_meta = payload.selection_meta.filter(function(item) {
                return item && String(item.entity_key || '') === String(row && row.entity_key || '');
            });
        }
        const actionPayload = action && action.payload ? action.payload : {};
        const isContentRewriteApply = String(actionPayload.write_class || '') === 'onpage_content_rewrite_apply' || String(actionPayload.operation || '') === 'apply_rewrite';
        if (isContentRewriteApply && (!Array.isArray(payload.accepted_items) || payload.accepted_items.length !== 1)) {
            return '';
        }
        const label = status.key === 'ready'
            ? (isContentRewriteApply ? (payload.op26_final_write_confirmed ? 'Aplică rewrite controlat' : 'Preflight rewrite controlat') : 'Aplică')
            : (status.key === 'generate' ? 'Generează' : 'Evaluează');
        return '<button type="button" class="button button-primary aysa-agent8v3-modal-action aysa-agent8v3-content-action" data-action="' + escapeHtml(action.action || '') + '" data-payload="' + escapeHtml(JSON.stringify(payload)) + '">' + escapeHtml(label) + '</button>';
    }

    function currentModalFiltersFromControls() {
        const filters = {
            search: String($('#aysa-agent8v3-modal-search').val() || ''),
            status: String($('#aysa-agent8v3-modal-status').val() || 'all'),
            tab: String(state.modal.filters.tab || '')
        };
        if (state.modal.key === 'onpage_seo' && $('#aysa-agent8v3-modal-entity-type').length) {
            filters.entity_type = String($('#aysa-agent8v3-modal-entity-type').val() || 'all');
            filters.workflow_status = String($('#aysa-agent8v3-modal-status').val() || 'all');
            filters.status = 'all';
        }
        if (state.modal.key === 'onpage_seo' && state.modal.current && state.modal.current.advanced_tabs_visible) {
            filters.advanced = '1';
        }
        if (state.modal.key === 'onpage_seo' && $('#aysa-agent8v3-modal-metadata-run').length) {
            filters.source_run_id = String($('#aysa-agent8v3-modal-metadata-run').val() || '');
        } else if (state.modal.key === 'onpage_seo' && state.modal.filters && state.modal.filters.source_run_id) {
            filters.source_run_id = String(state.modal.filters.source_run_id || '');
        }
        if (state.modal.key === 'onpage_seo' && Object.prototype.hasOwnProperty.call(state.modal.filters || {}, '_sync_projection')) {
            filters._sync_projection = String(state.modal.filters._sync_projection || '0');
            filters._sync_projection_mode = String(state.modal.filters._sync_projection_mode || 'review');
        }
        if (state.modal.key === 'onpage_seo' && state.modal.filters && state.modal.filters.snapshot_identity) {
            filters.snapshot_identity = String(state.modal.filters.snapshot_identity || '');
        }
        if (state.modal.key === 'offpage_seo' && state.modal.current && state.modal.current.advanced_tabs_visible) {
            filters.advanced = '1';
        }
        if (state.modal.key === 'offpage_seo' && state.modal.current && String(state.modal.current.display_mode || '') === 'offpage_authority_plan' && $('#aysa-agent8v3-modal-module').length) {
            filters.module = String($('#aysa-agent8v3-modal-module').val() || 'all');
        }
        if (state.modal.key === 'monitoring' && state.modal.current && state.modal.current.advanced_tabs_visible) {
            filters.advanced = '1';
        }
        if (state.modal.key === 'monitoring' && state.modal.filters && state.modal.filters.monitoring_view) {
            filters.monitoring_view = String(state.modal.filters.monitoring_view);
        }
        return ensureOnPageProjectionSyncFilter(filters);
    }

    function monitoringFilterStateKey(tab, view) {
        return String(tab || 'serp_positions') + ':' + String(view || 'overview');
    }

    function rememberMonitoringFilterState(filters, page) {
        if (state.modal.key !== 'monitoring') {
            return;
        }
        filters = filters && typeof filters === 'object' ? filters : currentModalFiltersFromControls();
        const tab = String(filters.tab || 'serp_positions');
        const view = String(filters.monitoring_view || 'overview');
        state.modal.monitoringFilterState = state.modal.monitoringFilterState || {};
        state.modal.monitoringFilterState[monitoringFilterStateKey(tab, view)] = {
            page: Math.max(1, parseInt(page || state.modal.page || 1, 10) || 1),
            filters: Object.assign({}, filters, {
                tab: tab,
                monitoring_view: view,
                advanced: '1'
            })
        };
    }

    function monitoringFilterStateFor(tab, view) {
        const key = monitoringFilterStateKey(tab, view);
        const saved = state.modal.monitoringFilterState && state.modal.monitoringFilterState[key]
            ? state.modal.monitoringFilterState[key]
            : null;
        if (saved) {
            return {
                page: Math.max(1, parseInt(saved.page || 1, 10) || 1),
                filters: Object.assign({}, saved.filters || {})
            };
        }
        return {
            page: 1,
            filters: {
                search: '',
                status: 'all',
                tab: String(tab || 'serp_positions'),
                monitoring_view: String(view || 'overview'),
                advanced: '1'
            }
        };
    }

    function restoreMonitoringFilterState(tab, view) {
        const saved = monitoringFilterStateFor(tab, view);
        state.modal.page = saved.page;
        state.modal.filters = saved.filters;
        $('#aysa-agent8v3-modal-search').val(String(saved.filters.search || ''));
        $('#aysa-agent8v3-modal-status').val(String(saved.filters.status || 'all'));
    }

    function ensureOnPageProjectionSyncFilter(filters) {
        filters = filters && typeof filters === 'object' ? filters : {};
        if (state.modal.key === 'onpage_seo') {
            const canonical = state.canonical && typeof state.canonical === 'object' ? state.canonical : {};
            const data = canonical.data && typeof canonical.data === 'object' ? canonical.data : {};
            const onpage = data.onpage_seo && typeof data.onpage_seo === 'object' ? data.onpage_seo : {};
            const runIds = onpage.run_ids && typeof onpage.run_ids === 'object' ? onpage.run_ids : {};
            const currentMetaRunId = Math.max(0, parseInt(runIds.meta_generate || 0, 10) || 0);
            const tab = String(filters.tab || 'overview');
            if (tab !== 'execution_report' && !filters.source_run_id && currentMetaRunId > 0) {
                filters.source_run_id = String(currentMetaRunId);
            }
        }
        if (state.modal.key === 'onpage_seo' && !Object.prototype.hasOwnProperty.call(filters, '_sync_projection')) {
            const tab = String(filters.tab || 'overview');
            filters._sync_projection = (tab === 'overview' || tab === 'execution_report') ? '0' : '1';
            filters._sync_projection_mode = tab === 'execution_report' ? 'apply_readback' : 'review';
        }
        return filters;
    }

    function renderModalChip(kind, icon, label, title) {
        const safeKind = String(kind || '').replace(/[^a-z0-9_-]+/gi, '-').toLowerCase();
        return '<span class="aysa-agent8v3-modal-chip is-' + escapeHtml(safeKind) + '" title="' + escapeHtml(title || label || '-') + '">' +
            '<span aria-hidden="true">' + escapeHtml(icon || '•') + '</span><strong>' + escapeHtml(label || '-') + '</strong>' +
            '</span>';
    }

    function renderAutomationStatus(value) {
        const status = String(value || '').trim();
        const key = status.toLowerCase().replace(/[^a-z0-9ăâîșț]+/gi, '_');
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        if (status === 'schema_review_only' || key === 'doar_review_schema' || key === 'schema_review_only') {
            return renderModalChip('automation-schema_review_only', '•', ro ? 'Doar review Schema' : 'Schema review only', ro ? 'Nu aplică Schema din lista generală.' : 'Does not apply Schema from the general review list.');
        }
        if (status === 'a8_automated') {
            return renderModalChip('automation-a8_automated', '✓', text('modalA8Automated'), text('modalA8AutomatedTitle'));
        }
        if (status === 'partial_automation') {
            return renderModalChip('automation-partial_automation', '◐', text('modalPartialAutomation'), text('modalPartialAutomationTitle'));
        }
        return renderModalChip('automation-manual_review', '•', text('modalManualReview'), text('modalManualReviewTitle'));
    }

    function renderTechnicalFixName(row, value) {
        return '<span class="aysa-agent8v3-fix-name"><span>' + escapeHtml(value || '-') + '</span></span>';
    }

    function modalRowClass(row, modal) {
        if (String((modal && modal.modal_key) || '').indexOf('technical_') !== 0 || !row || typeof row.automation_status === 'undefined') {
            return '';
        }
        const status = String((row && row.automation_status) || 'manual_review').replace(/[^a-z0-9_-]+/gi, '-').toLowerCase();
        return ' class="is-automation-row is-' + escapeHtml(status || 'manual_review') + '"';
    }

    function localizedModalValue(kind, value) {
        const raw = String(value || '').trim();
        const normalized = raw.toLowerCase().replace(/[^a-z0-9]+/g, '_');
        const map = {
            intent: {
                local: 'modalLocal',
                commercial: 'modalCommercial',
                informational: 'modalInformational',
                navigational: 'modalNavigational'
            },
            status: {
                mapped: 'modalMapped',
                selected: 'selected',
                completed: 'completed',
                ready: 'statusReady',
                completed_with_warnings: 'statusCompletedWithWarnings',
                manual_needed: 'manualNeededHuman',
                not_executable: 'notExecutableHuman',
                needs_improvement: 'needsImprovementHuman',
                excellent: 'excellentHuman',
                failed: 'failed',
                running: 'running'
            },
            quality: {
                trusted: 'modalTrusted',
                recommended_reject: 'modalRecommendedReject',
                review: 'modalReviewNeeded'
            }
        };
        const key = map[kind] && map[kind][normalized] ? map[kind][normalized] : '';
        const fallback = key ? text(key) : (clientFacingLabel(raw) || '-');
        return String(state.modal && state.modal.key || '').indexOf('technical_') === 0
            ? technicalClientDisplayText(fallback)
            : fallback;
    }

    function qualityIcon(value) {
        const raw = String(value || '').toLowerCase();
        if (raw === 'trusted') {
            return '✓';
        }
        if (raw === 'recommended_reject' || raw === 'rejected') {
            return '×';
        }
        return '!';
    }

    function trustLabel(value) {
        const raw = String(value || '').trim();
        if (!raw || raw === '-') {
            return '-';
        }
        return raw.match(/%$/) ? raw : raw + '%';
    }

    function confidenceLabel(value) {
        const raw = String(value || '').trim();
        const numeric = parseFloat(raw);
        if (!Number.isNaN(numeric)) {
            const percentage = numeric <= 1 ? Math.round(numeric * 100) : Math.round(numeric);
            return percentage + '%';
        }
        return raw || '-';
    }

    function intentIcon(value) {
        const raw = String(value || '').toLowerCase();
        if (raw.indexOf('local') !== -1) return '⌖';
        if (raw.indexOf('commercial') !== -1) return '$';
        if (raw.indexOf('inform') !== -1) return 'i';
        if (raw.indexOf('navig') !== -1) return '↗';
        return '•';
    }

    function statusIcon(value) {
        const raw = String(value || '').toLowerCase();
        if (raw.indexOf('mapped') !== -1 || raw.indexOf('selected') !== -1) return '↔';
        if (raw.indexOf('complete') !== -1) return '✓';
        if (raw.indexOf('fail') !== -1) return '!';
        return '•';
    }

    function renderModalLegend(modal) {
        if (String(modal.modal_key || '') === 'technical_site_audit' && String(modal.active_tab || '') === 'fixes') {
            return '';
        }
        if (String(modal.modal_key || '') === 'technical_internal_linking') {
            return '<div class="aysa-agent8v3-modal-legend">' +
                '<span><strong>' + escapeHtml(text('outboundLinks')) + '</strong> ' + escapeHtml(text('proposedLinks')) + '</span>' +
                '<span><strong>3</strong> ' + escapeHtml(text('maxOutboundPerPage')) + '</span>' +
                '</div>';
        }
        if (String(modal.modal_key || '') !== 'keyword_mapping') {
            return '';
        }
        return '<div class="aysa-agent8v3-modal-legend">' +
            '<span><strong>⌖</strong> ' + escapeHtml(text('modalIntentLegend')) + '</span>' +
            '<span><strong>↔</strong> ' + escapeHtml(text('modalStatusLegend')) + '</span>' +
            '<span><strong>◔</strong> ' + escapeHtml(text('modalConfidenceLegend')) + '</span>' +
            '<span><strong>✓ / ×</strong> ' + escapeHtml(text('modalReviewLegend')) + '</span>' +
            '</div>';
    }

    function clearVolatileChatUi() {
        state.messages = [];
        state.ragContexts = [];
        state.workerTasks.forEach(function(task) {
            clearWorkerTimer(task.id);
        });
        state.workerTasks = [];
        renderMessages();
    }

    function fullResetToPreActivation() {
        if (!window.confirm(text('fullResetConfirm'))) {
            return;
        }
        const button = $('#aysa-agent8v3-full-reset');
        button.prop('disabled', true);
        setStatus('running');
        const canonical = state.canonical || {};
        if (canonical.pending_approval && canonical.pending_approval.action && canonical.pending_approval.action !== 'reset_lab') {
            addMessage('system', 'Finalizează aprobarea curentă înainte de reset complet.');
            button.prop('disabled', false);
            setStatus('failed');
            return;
        }
        const approve = function(version) {
            return rawAjax('aysa_agent8v3_approval', {
                approval: 'approve',
                state_version: version
            });
        };
        const resetFlow = canonical.pending_approval && canonical.pending_approval.action
            ? approve(currentVersion())
            : rawAjax('aysa_agent8v3_action', {
                agent_action: 'reset_lab',
                state_version: currentVersion(),
                payload: JSON.stringify({})
            }).then(function(response) {
                const nextVersion = response && response.success && response.data && response.data.state
                    ? response.data.state.state_version
                    : currentVersion();
                return approve(nextVersion);
            });

        resetFlow.done(function(response) {
            clearVolatileChatUi();
            renderPayload(response);
            setStatus('completed');
        }).fail(function(xhr) {
            const message = xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message
                ? xhr.responseJSON.data.message
                : 'reset_failed';
            addMessage('system', message);
            setStatus('failed');
        }).always(function() {
            button.prop('disabled', false);
        });
    }

    function summarizeFactoryResetCounts(payload) {
        const counts = payload && payload.counts && typeof payload.counts === 'object' ? payload.counts : {};
        const wordpress = counts.wordpress && typeof counts.wordpress === 'object' ? counts.wordpress : {};
        const api = counts.api && typeof counts.api === 'object' ? counts.api : {};
        const isRo = String(uiLanguage() || 'ro').indexOf('ro') === 0;
        return [
            (isRo ? 'Opțiuni WordPress: ' : 'WordPress options: ') + String(wordpress.options || 0),
            (isRo ? 'Rânduri WordPress user/meta: ' : 'WordPress user/meta rows: ') + String((wordpress.user_meta || 0) + (wordpress.custom_table_rows || 0)),
            (isRo ? 'Sesiuni API: ' : 'API sessions: ') + String(api.sessions || 0),
            (isRo ? 'Mesaje API: ' : 'API messages: ') + String(api.messages || 0),
            (isRo ? 'Rulări research: ' : 'Research runs: ') + String(api.research_runs || 0),
            (isRo ? 'Taskuri/evenimente research: ' : 'Research tasks/events: ') + String((api.research_tasks || 0) + (api.research_events || 0)),
            (isRo ? 'Versiuni stare Agent8: ' : 'Agent8 state versions: ') + String(api.agent8_state_versions || 0),
            (isRo ? 'Fișiere proiect/artifact worker: ' : 'Worker project/artifact files: ') + String((api.worker_project_files || 0) + (api.worker_task_artifacts || 0))
        ].join('\n');
    }

    function requestFactoryResetConfirmation(phrase, summary, onConfirm, onCancel) {
        const container = $('#aysa-agent8v3-messages');
        const id = 'aysa-agent8v3-factory-reset-confirmation-' + Date.now();
        const titleId = id + '-title';
        const bodyId = id + '-body';
        const summaryId = id + '-summary';
        const inputId = id + '-input';
        const errorId = id + '-error';
        container.find('.aysa-agent8v3-factory-reset-confirmation').remove();
        const html = '' +
            '<div id="' + id + '" class="aysa-agent8v3-message aysa-agent8v3-message-system aysa-agent8v3-factory-reset-confirmation" role="dialog" aria-labelledby="' + titleId + '" aria-describedby="' + bodyId + ' ' + summaryId + '">' +
                '<div class="aysa-agent8v3-bubble">' +
                    '<strong id="' + titleId + '">' + escapeHtml(text('factoryResetConfirmTitle')) + '</strong>' +
                    '<p id="' + bodyId + '">' + escapeHtml(text('factoryResetConfirmBody')) + '</p>' +
                    '<code class="aysa-agent8v3-reset-phrase">' + escapeHtml(phrase) + '</code>' +
                    '<pre id="' + summaryId + '" class="aysa-agent8v3-reset-summary">' + escapeHtml(summary) + '</pre>' +
                    '<label for="' + inputId + '" class="aysa-agent8v3-reset-confirm-label">' + escapeHtml(text('factoryResetInput')) + '</label>' +
                    '<input id="' + inputId + '" type="text" class="aysa-agent8v3-reset-confirm-input" autocomplete="off" spellcheck="false" aria-describedby="' + summaryId + ' ' + errorId + '" placeholder="' + escapeHtml(text('factoryResetInput')) + '">' +
                    '<div id="' + errorId + '" class="aysa-agent8v3-reset-confirm-error" role="status" aria-live="polite" hidden></div>' +
                    '<div class="aysa-agent8v3-reset-confirm-actions">' +
                        '<button type="button" class="button button-primary" data-agent8-reset-confirm="1" disabled>' + escapeHtml(text('factoryResetExecute')) + '</button>' +
                        '<button type="button" class="button" data-agent8-reset-cancel="1">' + escapeHtml(text('factoryResetCancel')) + '</button>' +
                    '</div>' +
                '</div>' +
            '</div>';
        container.append(html);
        const panel = $('#' + id);
        const input = panel.find('.aysa-agent8v3-reset-confirm-input');
        const confirmButton = panel.find('[data-agent8-reset-confirm]');
        const error = panel.find('.aysa-agent8v3-reset-confirm-error');
        const cleanup = function() {
            panel.remove();
            $('#aysa-agent8v3-factory-reset').trigger('focus');
        };
        panel.find('[data-agent8-reset-cancel]').on('click', function() {
            cleanup();
            if (typeof onCancel === 'function') {
                onCancel();
            }
        });
        panel.find('[data-agent8-reset-confirm]').on('click', function() {
            const entered = String(input.val() || '').trim();
            if (entered !== phrase) {
                error.text('Fraza de confirmare nu se potrivește. Verifică textul și încearcă din nou.').prop('hidden', false);
                input.trigger('focus').trigger('select');
                return;
            }
            cleanup();
            onConfirm();
        });
        input.on('input', function() {
            const matches = String(input.val() || '').trim() === phrase;
            confirmButton.prop('disabled', !matches);
            if (matches) {
                error.text('').prop('hidden', true);
            }
        });
        input.on('keydown', function(event) {
            if (event.key === 'Enter') {
                event.preventDefault();
                if (!confirmButton.prop('disabled')) {
                    confirmButton.trigger('click');
                }
            }
        });
        panel.on('keydown', function(event) {
            if (event.key === 'Escape') {
                event.preventDefault();
                panel.find('[data-agent8-reset-cancel]').trigger('click');
            }
        });
        input.trigger('focus');
        const el = document.getElementById('aysa-agent8v3-messages');
        if (el) {
            el.scrollTop = el.scrollHeight;
        }
    }

    function factoryResetTestFlow() {
        const button = $('#aysa-agent8v3-factory-reset');
        const resetContext = currentAgent8Context();
        if (!isFactoryResetAllowedForContext(resetContext)) {
            addMessage('system', 'Resetul la început este disponibil doar pentru proiectele de test allowlisted.');
            updateFactoryResetVisibility();
            return;
        }
        button.prop('disabled', true);
        setStatus('running');
        let executeStarted = false;
        addMessage('system', 'Pregătesc resetul complet pentru proiectul de test selectat.');
        rawAjax('aysa_agent8_factory_reset_dry_run', {
            project_id: resetContext.project_id,
            site_host: resetContext.site_host
        }, { timeout: 45000 }).done(function(dryRunResponse) {
            if (!dryRunResponse || dryRunResponse.success !== true || !dryRunResponse.data) {
                const message = dryRunResponse && dryRunResponse.data && dryRunResponse.data.message
                    ? dryRunResponse.data.message
                    : 'Resetul complet a eșuat la pregătire.';
                addMessage('system', message);
                setStatus('failed');
                return;
            }
            const dryRunPayload = dryRunResponse && dryRunResponse.success && dryRunResponse.data ? dryRunResponse.data : {};
            const phrase = String(dryRunPayload.confirmation_phrase || ('RESET AYSA PRE ACTIVATION ' + String(resetContext.project_id || '') + ' ' + String(resetContext.site_host || '')));
            const summary = summarizeFactoryResetCounts(dryRunPayload);
            requestFactoryResetConfirmation(phrase, summary, function() {
                addMessage('system', 'Execut resetul complet și curăț chatul Agent8 Lab.');
                executeStarted = true;
                rawAjax('aysa_agent8_factory_reset_execute', {
                    token: dryRunPayload.execute && dryRunPayload.execute.token ? dryRunPayload.execute.token : '',
                    confirmation_phrase: phrase,
                    project_id: resetContext.project_id,
                    site_host: resetContext.site_host
                }, { timeout: 180000 }).done(function(executeResponse) {
                    if (!executeResponse || executeResponse.success !== true || !executeResponse.data) {
                        const message = executeResponse && executeResponse.data && executeResponse.data.message
                            ? executeResponse.data.message
                            : 'Resetul complet a eșuat la execuție.';
                        addMessage('system', message);
                        setStatus('failed');
                        return;
                    }
                    const executePayload = executeResponse && executeResponse.success && executeResponse.data ? executeResponse.data : {};
                    clearVolatileChatUi();
                    addMessage('system', 'Resetul complet a fost executat. Reîncarc Agent8 înainte de activare.');
                    setStatus('completed');
                    if (executePayload.reload) {
                        window.setTimeout(function() {
                            window.location.reload();
                        }, 900);
                    } else {
                        request('aysa_agent8v3_state');
                    }
                }).fail(function(xhr) {
                    const message = xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message
                        ? xhr.responseJSON.data.message
                        : 'Resetul complet a eșuat la execuție.';
                    addMessage('system', message);
                    setStatus('failed');
                }).always(function() {
                    button.prop('disabled', false);
                });
            }, function() {
                setStatus('idle');
                button.prop('disabled', false);
            });
        }).fail(function(xhr) {
            const message = xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message
                ? xhr.responseJSON.data.message
                : 'Resetul complet a eșuat la pregătire.';
            addMessage('system', message);
            setStatus('failed');
        }).always(function() {
            if (!executeStarted) {
                button.prop('disabled', false);
            }
        });
    }

    function qaUuid() {
        if (window.crypto && typeof window.crypto.randomUUID === 'function') {
            return window.crypto.randomUUID();
        }
        return 'qa_' + Date.now() + '_' + Math.random().toString(16).slice(2);
    }

    function sample(items) {
        return items[Math.floor(Math.random() * items.length)];
    }

    function redact(value) {
        if (Array.isArray(value)) {
            return value.map(redact);
        }
        if (value && typeof value === 'object') {
            const out = {};
            Object.keys(value).forEach(function(key) {
                if (/nonce|token|secret|signature|key|password|authorization/i.test(key)) {
                    out[key] = '[redacted]';
                } else {
                    out[key] = redact(value[key]);
                }
            });
            return out;
        }
        return value;
    }

    function qaEvent(testName, layer, stepAction, requestPayload, responsePayload, before, after, expected, actual, status, duration, error) {
        const event = {
            event_id: qaUuid(),
            timestamp: new Date().toISOString(),
            test_run_id: state.qaRunId,
            test_name: testName,
            layer: layer,
            action: stepAction,
            request_payload: redact(requestPayload || {}),
            response_payload: redact(responsePayload || {}),
            state_before: before || {},
            state_after: after || {},
            expected: expected || {},
            actual: actual || {},
            status: status,
            duration_ms: duration || 0,
            error: error || null
        };
        state.qaEvents.push(event);
        rawAjax('aysa_agent8v3_qa_log', {
            events: JSON.stringify([event])
        });
        renderDiagnostics();
        return event;
    }

    function qaAssert(testName, expected, actual) {
        const passed = JSON.stringify(expected) === JSON.stringify(actual);
        qaEvent(testName, 'projection', 'assert', {}, {}, {}, {}, expected, actual, passed ? 'passed' : 'failed', 0, passed ? null : 'expected_actual_mismatch');
        return {
            test_name: testName,
            status: passed ? 'passed' : 'failed',
            expected: expected,
            actual: actual
        };
    }

    function qaStep(testName, layer, stepAction, ajaxAction, data, renderToChat) {
        const before = $.extend(true, {}, state.canonical || {});
        const started = Date.now();
        return rawAjax(ajaxAction, data).then(function(response) {
            const duration = Date.now() - started;
            const after = response && response.success && response.data && response.data.state ? response.data.state : {};
            const ok = !!(response && response.success);
            qaEvent(testName, layer, stepAction, data || {}, response || {}, before, after, {}, {}, ok ? 'passed' : 'failed', duration, ok ? null : ((response.data && response.data.message) || 'request_failed'));
            if (!ok) {
                throw new Error((response.data && response.data.message) || 'request_failed');
            }
            if (renderToChat !== false) {
                renderPayload(response);
            } else if (after && after.state_version) {
                state.canonical = after;
            }
            return response.data || {};
        }, function(xhr) {
            const duration = Date.now() - started;
            const message = xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message ? xhr.responseJSON.data.message : 'HTTP ' + (xhr ? xhr.status : 0);
            qaEvent(testName, layer, stepAction, data || {}, xhr && xhr.responseJSON ? xhr.responseJSON : {}, before, {}, {}, { error: message }, 'failed', duration, message);
            throw new Error(message);
        });
    }

    function qaRequest(action, data, downloadJson) {
        setStatus('running');
        return $.ajax({
            url: cfg.ajax_url,
            method: 'POST',
            dataType: 'json',
            data: $.extend({
                action: action,
                nonce: cfg.nonce
            }, data || {})
        }).done(function(response) {
            if (!response || !response.success) {
                const message = response && response.data && response.data.message ? response.data.message : 'QA request failed.';
                $('#aysa-agent8v3-qa-summary').text(message);
                setStatus('failed');
                return;
            }
            renderQa(response.data || {});
            if (downloadJson) {
                const blob = new Blob([JSON.stringify(response.data || {}, null, 2)], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                link.download = 'agent8-v3-qa-log.json';
                link.click();
                URL.revokeObjectURL(url);
            }
            setStatus('completed');
        }).fail(function(xhr) {
            $('#aysa-agent8v3-qa-summary').text('QA request failed: HTTP ' + xhr.status);
            setStatus('failed');
        });
    }

    function renderQa(data) {
        const summary = data.summary || {};
        if (Array.isArray(data.tests)) {
            state.qaResults = data.tests;
        }
        if (summary.total !== undefined) {
            state.activeTest = {
                name: data.suite || (state.stressRunning ? '15 Min Stress Test' : 'QA Run'),
                total: summary.total || 0,
                passed: summary.passed || 0,
                failed: summary.failed || 0
            };
        }
        if (summary.total !== undefined) {
            $('#aysa-agent8v3-qa-summary').text('run ' + (data.test_run_id || '') + ' | total ' + summary.total + ' | passed ' + summary.passed + ' | failed ' + summary.failed);
        } else if (data.cleared !== undefined) {
            $('#aysa-agent8v3-qa-summary').text('cleared ' + data.cleared + ' QA events');
        } else if (Array.isArray(data.events)) {
            $('#aysa-agent8v3-qa-summary').text('exported ' + data.events.length + ' QA events');
        }

        const tests = Array.isArray(data.tests) ? data.tests : [];
        const html = tests.map(function(test) {
            const status = test.status || 'failed';
            return '<div class="aysa-agent8v3-qa-test ' + escapeHtml(status) + '">' +
                '<div class="aysa-agent8v3-qa-test-title"><strong>' + escapeHtml(test.test_name) + '</strong><span>' + escapeHtml(status) + '</span></div>' +
                '<details><summary>Expected / actual</summary><pre>' + escapeHtml(JSON.stringify({ expected: test.expected, actual: test.actual }, null, 2)) + '</pre></details>' +
            '</div>';
        }).join('');
        const events = Array.isArray(data.events) ? data.events : [];
        const eventHtml = events.length
            ? '<details class="aysa-agent8v3-qa-events"><summary>Request / response trace (' + events.length + ')</summary><pre>' + escapeHtml(JSON.stringify(events, null, 2)) + '</pre></details>'
            : '';
        $('#aysa-agent8v3-qa-results').html((html || '') + eventHtml);
        renderDiagnostics();
    }

    function renderCredits() {
        const billing = state.billing || {};
        const wallet = state.walletSnapshot || {};
        const available = Number(
            wallet.available_credits_cents !== undefined ? wallet.available_credits_cents :
            wallet.available_credits !== undefined ? wallet.available_credits :
            billing.available_credits_cents !== undefined ? billing.available_credits_cents : 0
        );
        const used = Number(billing.actual_credits_cents || 0);
        const estimated = Number(billing.estimated_credits_cents || 0);
        const status = String(billing.status || 'free');
        const plan = String(wallet.plan_code || '-');
        const reference = String(billing.billing_reference || '-');
        const lastAction = String(billing.last_billable_action || '-');
        const legacy = state.legacyCommit || {};
        const legacyStatus = String(legacy.status || (legacy.available ? 'available' : 'not available'));
        $('#aysa-agent8v3-credits').html([
            '<div class="aysa-agent8v3-metric-row"><span>' + escapeHtml(text('availableCredits')) + '</span><strong>' + escapeHtml(formatCredits(available)) + '</strong></div>',
            '<div class="aysa-agent8v3-metric-row"><span>' + escapeHtml(text('estimatedCredits')) + '</span><strong>' + escapeHtml(formatCredits(estimated)) + '</strong></div>',
            '<div class="aysa-agent8v3-metric-row"><span>' + escapeHtml(text('stepUsed')) + '</span><strong>' + escapeHtml(formatCredits(used)) + '</strong></div>',
            '<div class="aysa-agent8v3-metric-row"><span>' + escapeHtml(text('lastBillableAction')) + '</span><strong>' + escapeHtml(actionLabel(lastAction)) + '</strong></div>',
            '<div class="aysa-agent8v3-metric-row"><span>' + escapeHtml(text('billingReference')) + '</span><strong>' + escapeHtml(shortId(reference)) + '</strong></div>',
            '<div class="aysa-agent8v3-metric-row"><span>' + escapeHtml(text('billingStatus')) + '</span><strong>' + escapeHtml(clientFacingLabel(status)) + '</strong></div>',
            '<div class="aysa-agent8v3-metric-row"><span>' + escapeHtml(text('plan')) + '</span><strong>' + escapeHtml(plan) + '</strong></div>',
            '<div class="aysa-agent8v3-metric-row"><span>' + escapeHtml(text('legacySync')) + '</span><strong>' + escapeHtml(clientFacingLabel(legacyStatus)) + '</strong></div>'
        ].join(''));
    }

    function formatCredits(value) {
        const amount = Math.max(0, Math.round(Number(value || 0)));
        return amount + ' credits';
    }

    function renderDiagnostics() {
        const canonical = state.canonical || {};
        const events = state.qaEvents || [];
        const recent = events.slice(-5).reverse();
        const durations = events.map(function(event) {
            return Number(event.duration_ms || 0);
        }).filter(function(value) {
            return value > 0;
        });
        const failed = events.filter(function(event) {
            return event.status === 'failed';
        }).length;
        const avg = durations.length ? Math.round(durations.reduce(function(total, value) {
            return total + value;
        }, 0) / durations.length) : 0;
        const firstTime = events.length ? Date.parse(events[0].timestamp || '') : 0;
        const elapsedSeconds = firstTime ? Math.max(1, Math.round((Date.now() - firstTime) / 1000)) : 0;
        const throughput = elapsedSeconds ? (events.length / elapsedSeconds).toFixed(2) : '0';
        const errorRate = events.length ? ((failed / events.length) * 100).toFixed(1) : '0';

        $('#aysa-agent8v3-active-test').html([
            '<div class="aysa-agent8v3-metric-row"><span>' + escapeHtml(text('name')) + '</span><strong>' + escapeHtml(state.activeTest ? state.activeTest.name : state.stressRunning ? '15 Min Stress Test' : text('idle')) + '</strong></div>',
            '<div class="aysa-agent8v3-metric-row"><span>' + escapeHtml(text('currentPhase')) + '</span><strong>' + escapeHtml(canonical.phase || '-') + '</strong></div>',
            '<div class="aysa-agent8v3-metric-row"><span>' + escapeHtml(text('steps')) + '</span><strong>' + escapeHtml(state.activeTest ? state.activeTest.total : events.length) + '</strong></div>',
            '<div class="aysa-agent8v3-metric-row"><span>' + escapeHtml(text('result')) + '</span><strong>' + escapeHtml(state.activeTest ? (state.activeTest.passed + ' passed / ' + state.activeTest.failed + ' failed') : '-') + '</strong></div>'
        ].join(''));

        $('#aysa-agent8v3-recent-actions').html(recent.map(function(event) {
            return '<div class="aysa-agent8v3-recent-action ' + escapeHtml(event.status || 'skipped') + '"><span></span>' +
                '<strong>' + escapeHtml(event.action || 'event') + '</strong> ' + escapeHtml(event.test_name || '') +
            '</div>';
        }).join('') || '<div class="aysa-agent8v3-recent-action skipped"><span></span>' + escapeHtml(text('noQaActions')) + '</div>');

        $('#aysa-agent8v3-performance').html([
            '<div class="aysa-agent8v3-metric-row"><span>' + escapeHtml(text('avgResponse')) + '</span><strong>' + avg + 'ms</strong></div>',
            '<div class="aysa-agent8v3-metric-row"><span>' + escapeHtml(text('throughput')) + '</span><strong>' + throughput + '/s</strong></div>',
            '<div class="aysa-agent8v3-metric-row"><span>' + escapeHtml(text('errorRate')) + '</span><strong>' + errorRate + '%</strong></div>'
        ].join(''));
    }

    function qaState() {
        return qaStep('load_canonical_state', 'ui', 'state_read', 'aysa_agent8v3_state', {}, false);
    }

    function resetUiQaToPreActivation() {
        return qaState().then(function() {
            const canonical = state.canonical || {};
            if (canonical.pending_approval && canonical.pending_approval.action) {
                return qaStep('reset_to_pre_activation', 'ui', 'approval', 'aysa_agent8v3_approval', {
                    approval: 'approve',
                    state_version: currentVersion()
                }, true);
            }
            if (canonical.phase === 'pre_activation') {
                return { state: canonical };
            }
            return qaStep('reset_to_pre_activation', 'ui', 'action', 'aysa_agent8v3_action', {
                agent_action: 'reset_lab',
                state_version: currentVersion(),
                payload: JSON.stringify({})
            }, true).then(function() {
                return qaStep('reset_to_pre_activation', 'ui', 'approval', 'aysa_agent8v3_approval', {
                    approval: 'approve',
                    state_version: currentVersion()
                }, true);
            });
        });
    }

    function resetUiQaToWelcome() {
        return resetUiQaToPreActivation();
    }

    function qaStartArchitecture() {
        return resetUiQaToWelcome().then(function() {
            const beforeVersion = currentVersion();
            return qaStep('start_architecture_test', 'ui', 'action', 'aysa_agent8v3_action', {
                agent_action: 'start_architecture_test',
                state_version: beforeVersion,
                payload: JSON.stringify({})
            }, true).then(function(response) {
                const after = response.state || {};
                return qaAssert('start_architecture_test', {
                    phase: 'business_type_test',
                    version_increment: 1
                }, {
                    phase: after.phase || '',
                    version_increment: (after.state_version || 0) - beforeVersion
                });
            });
        });
    }

    function qaSendRandomBusinessValid() {
        const message = sample([
            'vind flori online',
            'am magazin ecommerce',
            'e un shop online cu buchete',
            'floraria primeste comenzi online',
            'online flower shop'
        ]);
        addMessage('qa user', message);
        return qaStep('save_business_type_valid_ui_message', 'ui', 'message', 'aysa_agent8v3_message', {
            message: message,
            state_version: currentVersion()
        }, true).then(function(response) {
            const after = response.state || {};
            return qaAssert('save_business_type_valid_ui_message', {
                phase: 'goal_test',
                business_type: 'ecommerce',
                got_assistant_response: true
            }, {
                phase: after.phase || '',
                business_type: after.decisions ? after.decisions.business_type : '',
                got_assistant_response: !!(response.projection && response.projection.assistant_message)
            });
        });
    }

    function qaBusinessValid() {
        return qaStartArchitecture().then(qaSendRandomBusinessValid);
    }

    function qaBusinessInvalid() {
        return qaStartArchitecture().then(function() {
            const message = sample([
                'nu stiu exact',
                'inca nu m-am hotarat',
                'poate ceva online, dar nu sunt sigur',
                'nu pot spune acum',
                'not sure yet'
            ]);
            const beforeVersion = currentVersion();
            addMessage('qa user', message);
            return qaStep('save_business_type_invalid_ui_message', 'ui', 'message', 'aysa_agent8v3_message', {
                message: message,
                state_version: beforeVersion
            }, true).then(function(response) {
                const after = response.state || {};
                return qaAssert('save_business_type_invalid_ui_message', {
                    phase: 'business_type_test',
                    state_version: beforeVersion,
                    needs_clarification: true,
                    got_assistant_response: true
                }, {
                    phase: after.phase || '',
                    state_version: after.state_version || 0,
                    needs_clarification: !!(response.debug && response.debug.llm && response.debug.llm.needs_clarification),
                    got_assistant_response: !!(response.projection && response.projection.assistant_message)
                });
            });
        });
    }

    function qaGoalValid() {
        return qaStartArchitecture().then(qaSendRandomBusinessValid).then(function() {
            const message = sample([
                'vreau mai multe comenzi din Google',
                'scopul e sa cresc vanzarile organice',
                'sa vind mai mult fara reclame',
                'more organic sales from search',
                'mai multe buchete vandute din SEO'
            ]);
            addMessage('qa user', message);
            return qaStep('save_primary_goal_valid_ui_message', 'ui', 'message', 'aysa_agent8v3_message', {
                message: message,
                state_version: currentVersion()
            }, true).then(function(response) {
                const after = response.state || {};
                return qaAssert('save_primary_goal_valid_ui_message', {
                    phase: 'architecture_verified',
                    primary_goal: 'increase_organic_sales',
                    got_assistant_response: true
                }, {
                    phase: after.phase || '',
                    primary_goal: after.decisions ? after.decisions.primary_goal : '',
                    got_assistant_response: !!(response.projection && response.projection.assistant_message)
                });
            });
        });
    }

    function qaBootstrap() {
        return resetUiQaToPreActivation().then(function() {
            const canonical = state.canonical || {};
            return qaAssert('bootstrap_ui_state_load', {
                phase: 'pre_activation',
                allowed_action: 'request_activation_key'
            }, {
                phase: canonical.phase || '',
                allowed_action: Array.isArray(canonical.allowed_actions) ? canonical.allowed_actions[0] : ''
            });
        });
    }

    function qaInvalidAction() {
        return resetUiQaToWelcome().then(function() {
            const before = $.extend(true, {}, state.canonical || {});
            const started = Date.now();
            return rawAjax('aysa_agent8v3_action', {
                agent_action: 'save_primary_goal',
                state_version: currentVersion(),
                payload: JSON.stringify({ value: 'increase_organic_sales' })
            }).then(function(response) {
                const error = response && response.data && response.data.message ? response.data.message : '';
                qaEvent('invalid_action_ui_test', 'ui', 'action', { agent_action: 'save_primary_goal' }, response || {}, before, state.canonical || {}, { error: 'invalid_action_for_phase' }, { error: error }, error === 'invalid_action_for_phase' ? 'passed' : 'failed', Date.now() - started, error === 'invalid_action_for_phase' ? null : 'unexpected_result');
                return qaAssert('invalid_action_ui_test', { error: 'invalid_action_for_phase' }, { error: error });
            });
        });
    }

    function qaResetFlow() {
        return resetUiQaToPreActivation().then(function() {
            return qaStep('reset_approval_ui_test', 'ui', 'action', 'aysa_agent8v3_action', {
                agent_action: 'reset_lab',
                state_version: currentVersion(),
                payload: JSON.stringify({})
            }, true);
        }).then(function(pending) {
            return qaStep('reset_approval_ui_test', 'ui', 'approval', 'aysa_agent8v3_approval', {
                approval: 'approve',
                state_version: pending.state ? pending.state.state_version : currentVersion()
            }, true);
        }).then(function(response) {
            const after = response.state || {};
            return qaAssert('reset_approval_ui_test', { phase: 'pre_activation' }, { phase: after.phase || '' });
        });
    }

    function qaWorkerPing() {
        return qaState().then(function() {
            const beforeVersion = currentVersion();
            const workerTaskId = beginWorkerTask('run_worker_ping');
            return qaStep('worker_ping_ui_test', 'worker', 'action', 'aysa_agent8v3_action', {
                agent_action: 'run_worker_ping',
                state_version: beforeVersion,
                payload: JSON.stringify({})
            }, true).then(function(response) {
                completeWorkerTask(workerTaskId, response || {});
                const worker = response && response.debug && response.debug.worker ? response.debug.worker : {};
                const after = response.state || {};
                return qaAssert('worker_ping_ui_test', {
                    task_group: 'system_noop',
                    task_status: 'completed',
                    state_version_unchanged: true
                }, {
                    task_group: worker.task_group || '',
                    task_status: worker.task_status || '',
                    state_version_unchanged: (after.state_version || 0) === beforeVersion
                });
            }, function(error) {
                failWorkerTask(workerTaskId, error && error.message ? error.message : String(error || 'worker_ping_failed'));
                return $.Deferred().reject(error).promise();
            });
        });
    }

    function qaRagContext() {
        return qaState().then(function() {
            const beforeVersion = currentVersion();
            return qaStep('rag_context_ui_test', 'ui', 'rag_context', 'aysa_agent8v3_action', {
                agent_action: 'run_rag_context_test',
                state_version: beforeVersion,
                payload: JSON.stringify({ message: 'What should Agent8 know about this client before deciding?' })
            }, true).then(function(response) {
                const rag = response && response.debug && response.debug.rag ? response.debug.rag : {};
                const after = response.state || {};
                return qaAssert('rag_context_ui_test', {
                    authority: 'context_only',
                    writes_state: false,
                    has_aysa_source: true,
                    state_version_unchanged: true
                }, {
                    authority: rag.authority || '',
                    writes_state: !!rag.writes_state,
                    has_aysa_source: Array.isArray(rag.sources) && rag.sources.indexOf('aysa') !== -1,
                    state_version_unchanged: (after.state_version || 0) === beforeVersion
                });
            });
        });
    }

    function qaServerSetupSuite() {
        const before = $.extend(true, {}, state.canonical || {});
        const started = Date.now();
        return rawAjax('aysa_agent8v3_qa_run', {
            suite: 'setup'
        }).then(function(response) {
            const data = response && response.success ? (response.data || {}) : {};
            const summary = data.summary || {};
            const ok = !!(response && response.success && Number(summary.failed || 0) === 0);
            const serverEvents = Array.isArray(data.events) ? data.events : [];
            serverEvents.forEach(function(event) {
                state.qaEvents.push(redact(event));
            });
            qaEvent('setup_profile_controlled_server_suite', 'api', 'qa_run', { suite: 'setup' }, data, before, state.canonical || {}, {
                failed: 0
            }, {
                failed: Number(summary.failed || 0),
                total: Number(summary.total || 0)
            }, ok ? 'passed' : 'failed', Date.now() - started, ok ? null : 'setup_suite_failed');
            renderQa({
                test_run_id: data.test_run_id || state.qaRunId,
                summary: summary,
                tests: data.tests || [],
                events: state.qaEvents
            });
            return {
                test_name: 'setup_profile_controlled_server_suite',
                status: ok ? 'passed' : 'failed',
                expected: { failed: 0 },
                actual: { failed: Number(summary.failed || 0), total: Number(summary.total || 0) }
            };
        }, function(xhr) {
            const message = xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message ? xhr.responseJSON.data.message : 'HTTP ' + (xhr ? xhr.status : 0);
            qaEvent('setup_profile_controlled_server_suite', 'api', 'qa_run', { suite: 'setup' }, xhr && xhr.responseJSON ? xhr.responseJSON : {}, before, state.canonical || {}, { failed: 0 }, { error: message }, 'failed', Date.now() - started, message);
            throw new Error(message);
        });
    }

    function qaServerSetupStressSuite() {
        const before = $.extend(true, {}, state.canonical || {});
        const started = Date.now();
        return rawAjax('aysa_agent8v3_qa_run', {
            suite: 'setup_stress'
        }).then(function(response) {
            const data = response && response.success ? (response.data || {}) : {};
            const summary = data.summary || {};
            const ok = !!(response && response.success && Number(summary.failed || 0) === 0);
            const serverEvents = Array.isArray(data.events) ? data.events : [];
            serverEvents.forEach(function(event) {
                state.qaEvents.push(redact(event));
            });
            qaEvent('setup_profile_stress_server_suite', 'api', 'qa_run', { suite: 'setup_stress' }, data, before, state.canonical || {}, {
                failed: 0
            }, {
                failed: Number(summary.failed || 0),
                total: Number(summary.total || 0)
            }, ok ? 'passed' : 'failed', Date.now() - started, ok ? null : 'setup_stress_suite_failed');
            renderQa({
                test_run_id: data.test_run_id || state.qaRunId,
                summary: summary,
                tests: data.tests || [],
                events: state.qaEvents
            });
            return {
                test_name: 'setup_profile_stress_server_suite',
                status: ok ? 'passed' : 'failed',
                expected: { failed: 0 },
                actual: { failed: Number(summary.failed || 0), total: Number(summary.total || 0) }
            };
        }, function(xhr) {
            const message = xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message ? xhr.responseJSON.data.message : 'HTTP ' + (xhr ? xhr.status : 0);
            qaEvent('setup_profile_stress_server_suite', 'api', 'qa_run', { suite: 'setup_stress' }, xhr && xhr.responseJSON ? xhr.responseJSON : {}, before, state.canonical || {}, { failed: 0 }, { error: message }, 'failed', Date.now() - started, message);
            throw new Error(message);
        });
    }

    function qaServerSetupIntegrationStressSuite() {
        if (!window.confirm(text('integrationStressConfirm'))) {
            return $.Deferred().resolve({
                test_name: 'setup_profile_integration_stress_server_suite',
                status: 'skipped',
                expected: { confirmed: true },
                actual: { confirmed: false }
            }).promise();
        }
        const before = $.extend(true, {}, state.canonical || {});
        const started = Date.now();
        return rawAjax('aysa_agent8v3_qa_run', {
            suite: 'setup_integration_stress',
            confirm_integration_stress: 1
        }).then(function(response) {
            const data = response && response.success ? (response.data || {}) : {};
            const summary = data.summary || {};
            const ok = !!(response && response.success && Number(summary.failed || 0) === 0);
            const serverEvents = Array.isArray(data.events) ? data.events : [];
            serverEvents.forEach(function(event) {
                state.qaEvents.push(redact(event));
            });
            qaEvent('setup_profile_integration_stress_server_suite', 'api', 'qa_run', { suite: 'setup_integration_stress' }, data, before, state.canonical || {}, {
                failed: 0
            }, {
                failed: Number(summary.failed || 0),
                total: Number(summary.total || 0)
            }, ok ? 'passed' : 'failed', Date.now() - started, ok ? null : 'setup_integration_stress_suite_failed');
            renderQa({
                test_run_id: data.test_run_id || state.qaRunId,
                summary: summary,
                tests: data.tests || [],
                events: state.qaEvents
            });
            return {
                test_name: 'setup_profile_integration_stress_server_suite',
                status: ok ? 'passed' : 'failed',
                expected: { failed: 0 },
                actual: { failed: Number(summary.failed || 0), total: Number(summary.total || 0) }
            };
        }, function(xhr) {
            const message = xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message ? xhr.responseJSON.data.message : 'HTTP ' + (xhr ? xhr.status : 0);
            qaEvent('setup_profile_integration_stress_server_suite', 'api', 'qa_run', { suite: 'setup_integration_stress' }, xhr && xhr.responseJSON ? xhr.responseJSON : {}, before, state.canonical || {}, { failed: 0 }, { error: message }, 'failed', Date.now() - started, message);
            throw new Error(message);
        });
    }

    function qaLanguageMatrix() {
        const before = $.extend(true, {}, state.canonical || {});
        const started = Date.now();
        const requiredKeys = [
            'title', 'subtitle', 'active', 'conversation', 'execution', 'placeholder',
            'qaDiagnostics', 'controls', 'runAll', 'runState', 'runSetup', 'runLanguage',
            'runLegacySync', 'credits', 'availableCredits', 'estimatedCredits', 'stepUsed',
            'billingReference', 'lastBillableAction', 'billingStatus', 'plan', 'legacySync',
            'planning', 'executing', 'completed', 'running', 'thinking', 'failed',
            'start_google_integrations', 'continue_to_business_profile', 'confirm_business_profile',
            'confirm_objectives', 'confirm_seo_profile', 'run_competition_keyword_analysis',
            'confirm_competition_keyword', 'start_tone_of_voice', 'commit_setup_completed_to_legacy',
            'start_keyword_research_run', 'refresh_keyword_research_status', 'retry_keyword_research_run',
            'modalLoading', 'modalUnavailable', 'modalSearch', 'modalSearchDetails', 'chatProviderFallback',
            'modalWhatDone', 'modalNextStepLabel', 'modalAll', 'modalAccepted',
            'modalRejected', 'modalA8Automated', 'modalPartialAutomation', 'modalManualReview',
            'modalAutomationLegend', 'execute_technical_fix_plan', 'reject_technical_fix',
            'restore_technical_fix'
        ];
        const fallbackByLanguage = {};
        const missing = [];
        Object.keys(LANGUAGE_PACK).forEach(function(language) {
            const packKey = LANGUAGE_PACK[language] || language;
            const pack = I18N[packKey] || {};
            fallbackByLanguage[language] = [];
            requiredKeys.forEach(function(key) {
                if (!pack[key] && I18N.en[key]) {
                    fallbackByLanguage[language].push(key);
                }
                if (!pack[key] && !I18N.en[key]) {
                    missing.push(language + ':' + key);
                }
            });
        });
        applyInterfaceLanguage('ar-AE');
        const rtlApplied = $('.aysa-agent8v3-app').attr('dir') === 'rtl';
        applyInterfaceLanguage(uiLanguage());

        return rawAjax('aysa_agent8v3_qa_run', {
            suite: 'language'
        }).then(function(response) {
            const data = response && response.success ? (response.data || {}) : {};
            const summary = data.summary || {};
            const serverOk = Number(summary.failed || 0) === 0;
            const ok = serverOk && missing.length === 0 && rtlApplied;
            qaEvent('language_matrix_ui_test', 'ui', 'language', { required_keys: requiredKeys }, {
                server_summary: summary,
                fallback_by_language: fallbackByLanguage,
                rtl_applied: rtlApplied
            }, before, state.canonical || {}, {
                missing: [],
                rtl_applied: true,
                server_failed: 0
            }, {
                missing: missing,
                rtl_applied: rtlApplied,
                server_failed: Number(summary.failed || 0)
            }, ok ? 'passed' : 'failed', Date.now() - started, ok ? null : 'language_matrix_failed');
            return {
                test_name: 'language_matrix_ui_test',
                status: ok ? 'passed' : 'failed',
                expected: { missing: [], rtl_applied: true, server_failed: 0 },
                actual: {
                    missing: missing,
                    rtl_applied: rtlApplied,
                    server_failed: Number(summary.failed || 0),
                    fallback_languages: Object.keys(fallbackByLanguage).filter(function(language) {
                        return fallbackByLanguage[language].length > 0;
                    }).length
                }
            };
        });
    }

    function qaLegacySyncVerification() {
        const before = $.extend(true, {}, state.canonical || {});
        const started = Date.now();
        return rawAjax('aysa_agent8v3_qa_legacy_sync', {}).then(function(response) {
            const data = response && response.success ? (response.data || {}) : {};
            const summary = data.summary || {};
            const mismatches = Number(summary.mismatched || 0);
            const ok = !!(response && response.success) && mismatches === 0;
            qaEvent('legacy_sync_live_verification', 'wp_ajax', 'legacy_sync_read', {}, data, before, state.canonical || {}, {
                mismatched: 0
            }, {
                mismatched: mismatches,
                checked: Number(summary.checked || 0),
                skipped: Number(summary.skipped || 0)
            }, ok ? 'passed' : 'failed', Date.now() - started, ok ? null : 'legacy_sync_mismatch');
            return {
                test_name: 'legacy_sync_live_verification',
                status: ok ? 'passed' : 'failed',
                expected: { mismatched: 0 },
                actual: {
                    mismatched: mismatches,
                    checked: Number(summary.checked || 0),
                    skipped: Number(summary.skipped || 0),
                    checks: data.checks || []
                }
            };
        });
    }

    function stressMessageForPhase(phase) {
        if (phase === 'business_type_test') {
            return sample([
                'vind flori online',
                'am magazin ecommerce',
                'e un shop online cu buchete',
                'floraria primeste comenzi online',
                'online flower shop',
                'nu stiu exact',
                'poate ceva online, dar nu sunt sigur',
                'inca nu m-am hotarat'
            ]);
        }
        if (phase === 'goal_test') {
            return sample([
                'vreau mai multe comenzi din Google',
                'scopul e sa cresc vanzarile organice',
                'sa vind mai mult fara reclame',
                'more organic sales from search',
                'mai multe buchete vandute din SEO',
                'nu stiu care e prioritatea',
                'poate trafic, poate vanzari'
            ]);
        }
        return sample([
            'hai sa incepem',
            'testeaza arhitectura',
            'run the architecture lab',
            'vreau sa verificam sistemul'
        ]);
    }

    function stressStep(stepIndex) {
        return qaState().then(function() {
            const canonical = state.canonical || {};
            const phase = canonical.phase || 'welcome';
            const roll = Math.random();
            const testName = 'stress_15m_step_' + stepIndex + '_' + phase;
            addExecutionLog('step ' + stepIndex + ' phase=' + phase + ' version=' + (canonical.state_version || 0));

            if (canonical.pending_approval && canonical.pending_approval.action) {
                addExecutionLog('approval ' + canonical.pending_approval.action);
                return qaStep(testName, 'ui', 'approval', 'aysa_agent8v3_approval', {
                    approval: roll < 0.9 ? 'approve' : 'reject',
                    state_version: currentVersion()
                }, true);
            }

            if (phase === 'welcome') {
                if (roll < 0.25) {
                    const message = stressMessageForPhase(phase);
                    addExecutionLog('message ' + message);
                    addMessage('qa stress user', message);
                    return qaStep(testName, 'ui', 'message', 'aysa_agent8v3_message', {
                        message: message,
                        state_version: currentVersion()
                    }, true);
                }
                return qaStep(testName, 'ui', 'action', 'aysa_agent8v3_action', {
                    agent_action: 'start_architecture_test',
                    state_version: currentVersion(),
                    payload: JSON.stringify({})
                }, true);
            }

            if (phase === 'business_type_test') {
                if (roll < 0.72) {
                    const message = stressMessageForPhase(phase);
                    addExecutionLog('message ' + message);
                    addMessage('qa stress user', message);
                    return qaStep(testName, 'ui', 'message', 'aysa_agent8v3_message', {
                        message: message,
                        state_version: currentVersion()
                    }, true);
                }
                if (roll < 0.88) {
                    addExecutionLog('action reset_lab');
                    return qaStep(testName, 'ui', 'action', 'aysa_agent8v3_action', {
                        agent_action: 'reset_lab',
                        state_version: currentVersion(),
                        payload: JSON.stringify({})
                    }, true);
                }
                return rawAjax('aysa_agent8v3_action', {
                    agent_action: 'save_primary_goal',
                    state_version: currentVersion(),
                    payload: JSON.stringify({ value: 'increase_organic_sales' })
                }).then(function(response) {
                    qaEvent(testName, 'ui', 'invalid_action_probe', { agent_action: 'save_primary_goal' }, response || {}, canonical, state.canonical || {}, { error: 'invalid_action_for_phase' }, { error: response && response.data ? response.data.message : '' }, response && response.data && response.data.message === 'invalid_action_for_phase' ? 'passed' : 'failed', 0, null);
                    return response;
                });
            }

            if (phase === 'goal_test') {
                if (roll < 0.75) {
                    const message = stressMessageForPhase(phase);
                    addExecutionLog('message ' + message);
                    addMessage('qa stress user', message);
                    return qaStep(testName, 'ui', 'message', 'aysa_agent8v3_message', {
                        message: message,
                        state_version: currentVersion()
                    }, true);
                }
                addExecutionLog('action reset_lab');
                return qaStep(testName, 'ui', 'action', 'aysa_agent8v3_action', {
                    agent_action: 'reset_lab',
                    state_version: currentVersion(),
                    payload: JSON.stringify({})
                }, true);
            }

            if (phase === 'architecture_verified') {
                if (roll < 0.2) {
                    const message = stressMessageForPhase('goal_test');
                    addExecutionLog('message ' + message);
                    addMessage('qa stress user', message);
                    return qaStep(testName, 'ui', 'message', 'aysa_agent8v3_message', {
                        message: message,
                        state_version: currentVersion()
                    }, true);
                }
                addExecutionLog('action reset_lab');
                return qaStep(testName, 'ui', 'action', 'aysa_agent8v3_action', {
                    agent_action: 'reset_lab',
                    state_version: currentVersion(),
                    payload: JSON.stringify({})
                }, true);
            }

            return qaState();
        });
    }

    function runStressTest15m() {
        if (!cfg.qa_enabled) {
            $('#aysa-agent8v3-qa-summary').text('QA is disabled.');
            return $.Deferred().reject().promise();
        }
        if (state.stressRunning) {
            $('#aysa-agent8v3-qa-summary').text('Stress test is already running.');
            return $.Deferred().resolve().promise();
        }

        state.qaRunId = qaUuid();
        state.qaEvents = [];
        state.stressRunning = true;
        state.stressStopRequested = false;
        const deadline = Date.now() + (15 * 60 * 1000);
        const results = [];
        let stepIndex = 0;

        setStatus('running');
        $('#aysa-agent8v3-qa-results').empty();
        addMessage('system', '15 minute stress test started. The UI will jump across states, send random messages, reset, approve, and log every step.');
        addExecutionLog('starting 15 minute stress test');

        function renderProgress() {
            const remaining = Math.max(0, deadline - Date.now());
            const passed = results.filter(function(item) { return item.status === 'passed'; }).length;
            $('#aysa-agent8v3-qa-summary').text('Stress QA ' + state.qaRunId + ' | steps ' + results.length + ' | passed ' + passed + ' | failed ' + (results.length - passed) + ' | remaining ' + Math.ceil(remaining / 1000) + 's');
            renderQa({
                test_run_id: state.qaRunId,
                summary: {
                    total: results.length,
                    passed: passed,
                    failed: results.length - passed
                },
                tests: results.slice(-80),
                events: state.qaEvents.slice(-200)
            });
        }

        function loop() {
            if (state.stressStopRequested || Date.now() >= deadline) {
                state.stressRunning = false;
                setStatus(results.some(function(item) { return item.status === 'failed'; }) ? 'failed' : 'completed');
                addMessage('system', state.stressStopRequested ? 'Stress test stopped.' : '15 minute stress test completed.');
                addExecutionLog(state.stressStopRequested ? 'stress test stopped' : 'stress test completed');
                renderProgress();
                return $.Deferred().resolve().promise();
            }

            stepIndex += 1;
            return stressStep(stepIndex).then(function(response) {
                const canonical = state.canonical || (response && response.state) || {};
                results.push(qaAssert('stress_15m_state_projection_' + stepIndex, {
                    projection_matches_state: true,
                    has_known_phase: true
                }, {
                    projection_matches_state: true,
                    has_known_phase: ['welcome', 'business_type_test', 'goal_test', 'architecture_verified'].indexOf(canonical.phase || '') !== -1
                }));
                renderProgress();
            }, function(error) {
                results.push({
                    test_name: 'stress_15m_step_' + stepIndex,
                    status: 'failed',
                    expected: { recoverable: true },
                    actual: { error: error && error.message ? error.message : String(error || 'failed') }
                });
                qaEvent('stress_15m_step_' + stepIndex, 'ui', 'error', {}, {}, state.canonical || {}, {}, { recoverable: true }, results[results.length - 1].actual, 'failed', 0, results[results.length - 1].actual.error);
                renderProgress();
                return qaState();
            }).then(loop);
        }

        return loop();
    }

    function runUiQaSuite(suite) {
        if (!cfg.qa_enabled) {
            $('#aysa-agent8v3-qa-summary').text('QA is disabled.');
            return $.Deferred().reject().promise();
        }
        if (suite === 'stress_15m') {
            return runStressTest15m();
        }
        state.qaRunId = qaUuid();
        state.qaEvents = [];
        const suites = {
            state: [qaBootstrap],
            setup: [qaServerSetupSuite],
            setup_stress: [qaServerSetupStressSuite],
            setup_integration_stress: [qaServerSetupIntegrationStressSuite],
            action: [qaStartArchitecture, qaBusinessValid, qaGoalValid],
            llm: [qaBusinessValid, qaBusinessInvalid, qaGoalValid],
            worker: [qaWorkerPing],
            rag: [qaRagContext],
            language: [qaLanguageMatrix],
            legacy_sync: [qaLegacySyncVerification],
            invalid_action: [qaInvalidAction],
            reset: [qaResetFlow],
            all: [qaBootstrap, qaServerSetupSuite, qaLanguageMatrix, qaLegacySyncVerification, qaStartArchitecture, qaBusinessValid, qaBusinessInvalid, qaGoalValid, qaInvalidAction, qaWorkerPing, qaRagContext, qaResetFlow]
        };
        const tests = suites[suite] || suites.all;
        const results = [];
        let chain = $.Deferred().resolve().promise();
        setStatus('running');
        $('#aysa-agent8v3-qa-summary').text('running UI QA ' + state.qaRunId + '...');
        $('#aysa-agent8v3-qa-results').empty();
        addMessage('system', 'QA run started in the UI. Tests send random natural messages and render the real responses here.');

        tests.forEach(function(test) {
            chain = chain.then(function() {
                return test().then(function(result) {
                    if (result) {
                        results.push(result);
                    }
                    renderQa({
                        test_run_id: state.qaRunId,
                        summary: {
                            total: results.length,
                            passed: results.filter(function(item) { return item.status === 'passed'; }).length,
                            failed: results.filter(function(item) { return item.status !== 'passed'; }).length
                        },
                        tests: results,
                        events: state.qaEvents
                    });
                }, function(error) {
                    results.push({
                        test_name: test.name || 'ui_qa_test',
                        status: 'failed',
                        expected: {},
                        actual: { error: error && error.message ? error.message : String(error || 'failed') }
                    });
                    renderQa({
                        test_run_id: state.qaRunId,
                        summary: {
                            total: results.length,
                            passed: results.filter(function(item) { return item.status === 'passed'; }).length,
                            failed: results.filter(function(item) { return item.status !== 'passed'; }).length
                        },
                        tests: results,
                        events: state.qaEvents
                    });
                });
            });
        });

        return chain.always(function() {
            const passed = results.filter(function(item) { return item.status === 'passed'; }).length;
            $('#aysa-agent8v3-qa-summary').text('UI QA ' + state.qaRunId + ' | total ' + results.length + ' | passed ' + passed + ' | failed ' + (results.length - passed));
            setStatus(results.length === passed ? 'completed' : 'failed');
        });
    }

    function currentVersion() {
        return state.canonical && state.canonical.state_version ? state.canonical.state_version : 0;
    }

    function businessProfileNeedsRefresh() {
        const canonical = state.canonical || {};
        const data = canonical.data || {};
        const business = data.business_profile || {};
        const status = String(business.run_status || business.status || '');
        return canonical.phase === 'business_profile' &&
            parseInt(business.run_id, 10) > 0 &&
            ['queued', 'running'].indexOf(status) !== -1 &&
            canonical.allowed_actions &&
            canonical.allowed_actions.indexOf('refresh_business_profile_autofill_status') !== -1;
    }

    function syncBusinessProfileAutoRefresh() {
        if (!businessProfileNeedsRefresh()) {
            if (state.businessProfileTimer) {
                window.clearInterval(state.businessProfileTimer);
                state.businessProfileTimer = null;
            }
            state.businessProfileRefreshing = false;
            return;
        }
        if (state.businessProfileTimer) {
            return;
        }
        state.businessProfileTimer = window.setInterval(function() {
            if (!businessProfileNeedsRefresh()) {
                syncBusinessProfileAutoRefresh();
                return;
            }
            if (state.businessProfileRefreshing) {
                return;
            }
            state.businessProfileRefreshing = true;
            rawAjax('aysa_agent8v3_action', {
                agent_action: 'refresh_business_profile_autofill_status',
                state_version: currentVersion(),
                payload: JSON.stringify({})
            }).done(function(response) {
                if (response && response.success) {
                    renderProgressPayload(response, { preserveScroll: true });
                }
            }).always(function() {
                state.businessProfileRefreshing = false;
            });
        }, 8000);
    }

    function seoProfileNeedsRefresh() {
        const canonical = state.canonical || {};
        const data = canonical.data || {};
        const seo = data.seo_profile || {};
        const status = String(seo.autofill_status || seo.status || '');
        return canonical.phase === 'seo_profile' &&
            parseInt(seo.autofill_run_id || seo.run_id, 10) > 0 &&
            ['queued', 'running'].indexOf(status) !== -1 &&
            canonical.allowed_actions &&
            canonical.allowed_actions.indexOf('refresh_seo_profile_autofill_status') !== -1;
    }

    function syncSeoProfileAutoRefresh() {
        if (!seoProfileNeedsRefresh()) {
            if (state.seoProfileTimer) {
                window.clearInterval(state.seoProfileTimer);
                state.seoProfileTimer = null;
            }
            state.seoProfileRefreshing = false;
            return;
        }
        if (state.seoProfileTimer) {
            return;
        }
        state.seoProfileTimer = window.setInterval(function() {
            if (!seoProfileNeedsRefresh()) {
                syncSeoProfileAutoRefresh();
                return;
            }
            if (state.seoProfileRefreshing) {
                return;
            }
            state.seoProfileRefreshing = true;
            rawAjax('aysa_agent8v3_action', {
                agent_action: 'refresh_seo_profile_autofill_status',
                state_version: currentVersion(),
                payload: JSON.stringify({
                    _silent_refresh: true
                })
            }).done(function(response) {
                if (response && response.success) {
                    renderProgressPayload(response, { preserveScroll: true });
                } else if (response && response.data && response.data.error === 'stale_state_version') {
                    rawAjax('aysa_agent8v3_state', {}).done(function(stateResponse) {
                        if (stateResponse && stateResponse.success) {
                            renderProgressPayload(stateResponse, { preserveScroll: true });
                        }
                    });
                }
            }).always(function() {
                state.seoProfileRefreshing = false;
            });
        }, 5000);
    }

    function competitionKeywordNeedsRefresh() {
        const canonical = state.canonical || {};
        const data = canonical.data || {};
        const competition = data.competition_keyword || {};
        const completion = competition.completion || {};
        const status = String((completion.status === 'running' ? completion.status : competition.status) || '');
        return canonical.phase === 'competition_keyword' &&
            !canonical.pending_approval &&
            ['queued', 'running'].indexOf(status) !== -1 &&
            canonical.allowed_actions &&
            canonical.allowed_actions.indexOf('refresh_competition_keyword_analysis_status') !== -1;
    }

    function syncCompetitionKeywordAutoRefresh() {
        if (!competitionKeywordNeedsRefresh()) {
            if (state.competitionKeywordTimer) {
                window.clearInterval(state.competitionKeywordTimer);
                state.competitionKeywordTimer = null;
            }
            state.competitionKeywordRefreshing = false;
            return;
        }
        if (state.competitionKeywordTimer) {
            return;
        }
        state.competitionKeywordTimer = window.setInterval(function() {
            if (!competitionKeywordNeedsRefresh()) {
                syncCompetitionKeywordAutoRefresh();
                return;
            }
            if (state.competitionKeywordRefreshing) {
                return;
            }
            state.competitionKeywordRefreshing = true;
            rawAjax('aysa_agent8v3_action', {
                agent_action: 'refresh_competition_keyword_analysis_status',
                state_version: currentVersion(),
                payload: JSON.stringify({
                    _silent_refresh: true
                })
            }).done(function(response) {
                if (response && response.success) {
                    renderProgressPayload(response, { preserveScroll: true });
                } else if (response && response.data && response.data.error === 'stale_state_version') {
                    rawAjax('aysa_agent8v3_state', {}).done(function(stateResponse) {
                        if (stateResponse && stateResponse.success) {
                            renderProgressPayload(stateResponse, { preserveScroll: true });
                        }
                    });
                }
            }).always(function() {
                state.competitionKeywordRefreshing = false;
            });
        }, 5000);
    }

    function keywordResearchNeedsRefresh() {
        const canonical = state.canonical || {};
        const data = canonical.data || {};
        const research = data.research_handoff || {};
        const completion = research.completion || {};
        const status = String((completion.status === 'running' ? completion.status : research.status) || '');
        return canonical.phase === 'research_handoff_running' &&
            !canonical.pending_approval &&
            ['queued', 'running'].indexOf(status) !== -1 &&
            canonical.allowed_actions &&
            canonical.allowed_actions.indexOf('refresh_keyword_research_status') !== -1;
    }

    function syncKeywordResearchAutoRefresh() {
        if (!keywordResearchNeedsRefresh()) {
            if (state.keywordResearchTimer) {
                window.clearInterval(state.keywordResearchTimer);
                state.keywordResearchTimer = null;
            }
            state.keywordResearchRefreshing = false;
            return;
        }
        if (state.keywordResearchTimer) {
            return;
        }
        state.keywordResearchTimer = window.setInterval(function() {
            if (!keywordResearchNeedsRefresh()) {
                syncKeywordResearchAutoRefresh();
                return;
            }
            if (state.keywordResearchRefreshing) {
                return;
            }
            state.keywordResearchRefreshing = true;
            rawAjax('aysa_agent8v3_action', {
                agent_action: 'refresh_keyword_research_status',
                state_version: currentVersion(),
                payload: JSON.stringify({
                    _silent_refresh: true
                })
            }).done(function(response) {
                if (response && response.success) {
                    renderProgressPayload(response, { preserveScroll: true });
                } else if (response && response.data && response.data.error === 'stale_state_version') {
                    rawAjax('aysa_agent8v3_state', {}).done(function(stateResponse) {
                        if (stateResponse && stateResponse.success) {
                            renderProgressPayload(stateResponse, { preserveScroll: true });
                        }
                    });
                }
            }).always(function() {
                state.keywordResearchRefreshing = false;
            });
        }, 5000);
    }

    function technicalSeoNeedsRefresh() {
        const canonical = state.canonical || {};
        const data = canonical.data || {};
        const technical = data.technical_seo || {};
        const completion = technical.completion || {};
        const status = String((completion.status === 'running' ? completion.status : technical.status) || '');
        const hasRun = !!(technical.run_id || technical.job_id || technical.worker_ref);
        const hasProjection = !!technical.projection;
        const modules = technical.projection && technical.projection.modules ? technical.projection.modules : {};
        const redirectsModule = modules.redirects || {};
        const imageGeneration = technical.image_alt_generation && typeof technical.image_alt_generation === 'object' ? technical.image_alt_generation : {};
        const imageGenerationPackage = imageGeneration.image_alt_execution_package && typeof imageGeneration.image_alt_execution_package === 'object'
            ? imageGeneration.image_alt_execution_package
            : {};
        const imageGenerationRunId = parseInt(imageGeneration.worker_run_id || imageGenerationPackage.run_id || 0, 10) || 0;
        const imageGenerationNeedsRefresh = ['queued', 'running'].indexOf(String(imageGeneration.status || '')) !== -1 && imageGenerationRunId > 0;
        const redirectsModalNeedsRefresh = state.modal && state.modal.key === 'technical_redirects' &&
            String(redirectsModule.source || '') !== 'technical_redirects_run';
        return ['technical_seo_running', 'technical_seo_review'].indexOf(canonical.phase) !== -1 &&
            !canonical.pending_approval &&
            hasRun &&
            ((!hasProjection && ['queued', 'running', 'blocked'].indexOf(status) !== -1) || redirectsModalNeedsRefresh || imageGenerationNeedsRefresh) &&
            canonical.allowed_actions &&
            canonical.allowed_actions.indexOf('refresh_technical_seo_status') !== -1;
    }

    function syncTechnicalSeoAutoRefresh() {
        if (!technicalSeoNeedsRefresh()) {
            if (state.technicalSeoTimer) {
                window.clearInterval(state.technicalSeoTimer);
                state.technicalSeoTimer = null;
            }
            state.technicalSeoRefreshing = false;
            return;
        }
        if (state.technicalSeoTimer) {
            return;
        }
        state.technicalSeoTimer = window.setInterval(function() {
            if (!technicalSeoNeedsRefresh()) {
                syncTechnicalSeoAutoRefresh();
                return;
            }
            if (state.technicalSeoRefreshing) {
                return;
            }
            state.technicalSeoRefreshing = true;
            const technical = state.canonical && state.canonical.data && state.canonical.data.technical_seo ? state.canonical.data.technical_seo : {};
            const imageGeneration = technical.image_alt_generation && typeof technical.image_alt_generation === 'object' ? technical.image_alt_generation : {};
            const imagePackage = imageGeneration.image_alt_execution_package && typeof imageGeneration.image_alt_execution_package === 'object'
                ? imageGeneration.image_alt_execution_package
                : {};
            const imageRunId = parseInt(imageGeneration.worker_run_id || imagePackage.run_id || 0, 10) || 0;
            rawAjax('aysa_agent8v3_action', {
                agent_action: 'refresh_technical_seo_status',
                state_version: currentVersion(),
                payload: JSON.stringify({
                    _silent_refresh: true,
                    module: imageRunId > 0 ? 'image_alt' : '',
                    image_run_id: imageRunId
                })
            }).done(function(response) {
                if (response && response.success) {
                    renderProgressPayload(response, { preserveScroll: true });
                    if (state.modal && state.modal.key === 'technical_redirects') {
                        loadModal();
                    }
                } else if (response && response.data && response.data.error === 'stale_state_version') {
                    rawAjax('aysa_agent8v3_state', {}).done(function(stateResponse) {
                        if (stateResponse && stateResponse.success) {
                            renderProgressPayload(stateResponse, { preserveScroll: true });
                        }
                    });
                }
            }).always(function() {
                state.technicalSeoRefreshing = false;
            });
        }, 5000);
    }

    function maybeAutoStartTechnicalSeo() {
        // Technical SEO start policy: never auto-start the audit from render/state hydration.
        // The audit starts only from the visible CTA after the user explicitly clicks approval.
        state.technicalSeoAutoStartScheduled = false;
        state.technicalSeoAutoStarting = false;
    }

    function onPageSeoNeedsRefresh() {
        const canonical = state.canonical || {};
        const data = canonical.data || {};
        const onpage = data.onpage_seo || {};
        const completion = onpage.completion || {};
        const status = String((completion.status === 'running' ? completion.status : onpage.status) || '');
        const runs = onpage.runs || {};
        const hasActiveRun = Object.keys(runs).some(function(key) {
            const run = runs[key] || {};
            return ['queued', 'running'].indexOf(String(run.status || '')) !== -1;
        });
        const hasRun = !!(
            (onpage.run_ids && Object.keys(onpage.run_ids).length) ||
            (runs && Object.keys(runs).length)
        );
        return ['onpage_seo_running', 'onpage_seo_review'].indexOf(canonical.phase) !== -1 &&
            !canonical.pending_approval &&
            hasRun &&
            (['queued', 'running'].indexOf(status) !== -1 || hasActiveRun) &&
            canonical.allowed_actions &&
            canonical.allowed_actions.indexOf('refresh_onpage_seo_status') !== -1;
    }

    function syncOnPageSeoAutoRefresh() {
        if (!onPageSeoNeedsRefresh()) {
            if (state.onPageSeoTimer) {
                window.clearInterval(state.onPageSeoTimer);
                state.onPageSeoTimer = null;
            }
            state.onPageSeoRefreshing = false;
            return;
        }
        if (state.onPageSeoTimer) {
            return;
        }
        state.onPageSeoTimer = window.setInterval(function() {
            if (!onPageSeoNeedsRefresh()) {
                syncOnPageSeoAutoRefresh();
                return;
            }
            if (state.onPageSeoRefreshing) {
                return;
            }
            state.onPageSeoRefreshing = true;
            refreshOnPageSeoStatus(false);
        }, 5000);
        if (!state.onPageSeoRefreshing) {
            state.onPageSeoRefreshing = true;
            refreshOnPageSeoStatus(false);
        }
    }

    function refreshOnPageSeoStatus(retriedAfterStale) {
        rawAjax('aysa_agent8v3_action', {
            agent_action: 'refresh_onpage_seo_status',
            state_version: currentVersion(),
            payload: JSON.stringify({
                _silent_refresh: true
            })
        }).done(function(response) {
            if (response && response.success) {
                renderProgressPayload(response, { preserveScroll: true });
                if (state.modal && state.modal.key === 'onpage_seo' && !onPageSeoNeedsRefresh()) {
                    state.modal.filters = state.modal.filters && typeof state.modal.filters === 'object'
                        ? state.modal.filters
                        : {};
                    state.modal.filters._sync_projection = '1';
                    state.modal.filters._sync_projection_mode = 'apply_readback';
                    loadModal();
                }
            } else if (isStaleStateResponse(response) && !retriedAfterStale) {
                rawAjax('aysa_agent8v3_state', {}).done(function(stateResponse) {
                    if (stateResponse && stateResponse.success) {
                        renderProgressPayload(stateResponse, { preserveScroll: true });
                        refreshOnPageSeoStatus(true);
                    }
                }).fail(function() {
                    state.onPageSeoRefreshing = false;
                });
                return;
            }
            state.onPageSeoRefreshing = false;
        }).fail(function() {
            state.onPageSeoRefreshing = false;
        });
    }

    function stopImageAltGenerationPolling() {
        if (state.imageAltGenerationTimer) {
            window.clearInterval(state.imageAltGenerationTimer);
            state.imageAltGenerationTimer = null;
        }
        state.imageAltGenerationRefreshing = false;
    }

    function imageAltGenerationIsTerminal() {
        const technical = state.canonical && state.canonical.data && state.canonical.data.technical_seo
            ? state.canonical.data.technical_seo
            : {};
        const generation = technical.image_alt_generation && typeof technical.image_alt_generation === 'object'
            ? technical.image_alt_generation
            : {};
        return ['completed', 'completed_with_warnings', 'failed', 'cancelled', 'canceled'].indexOf(String(generation.status || '')) !== -1;
    }

    function startImageAltGenerationPolling() {
        stopImageAltGenerationPolling();
        if (imageAltGenerationIsTerminal()) {
            return;
        }
        state.imageAltGenerationAttempts = 0;
        state.imageAltGenerationTimer = window.setInterval(function() {
            if (state.imageAltGenerationRefreshing) {
                return;
            }
            state.imageAltGenerationAttempts += 1;
            state.imageAltGenerationRefreshing = true;
            rawAjax('aysa_agent8v3_action', {
                agent_action: 'refresh_technical_seo_status',
                state_version: currentVersion(),
                payload: JSON.stringify({
                    _silent_refresh: true,
                    module: 'image_alt'
                })
            }).done(function(response) {
                if (response && response.success) {
                    renderProgressPayload(response, { preserveScroll: true });
                    if (state.modal && state.modal.key === 'technical_image_alt') {
                        loadModal();
                    }
                    if (imageAltGenerationIsTerminal()) {
                        stopImageAltGenerationPolling();
                    }
                } else if (isStaleStateResponse(response)) {
                    rawAjax('aysa_agent8v3_state', {}).done(function(stateResponse) {
                        if (stateResponse && stateResponse.success) {
                            renderProgressPayload(stateResponse, { preserveScroll: true });
                        }
                    });
                }
            }).always(function() {
                state.imageAltGenerationRefreshing = false;
                if (imageAltGenerationIsTerminal() || state.imageAltGenerationAttempts >= 24 || !(state.modal && state.modal.key === 'technical_image_alt')) {
                    stopImageAltGenerationPolling();
                }
            });
        }, 5000);
    }

    function maybeAutoStartKeywordResearch(data) {
        const canonical = state.canonical || {};
        const allowed = Array.isArray(canonical.allowed_actions) ? canonical.allowed_actions : [];
        const decisions = canonical.decisions && typeof canonical.decisions === 'object' ? canonical.decisions : {};
        const setupProfile = canonical.data && canonical.data.setup_profile && typeof canonical.data.setup_profile === 'object' ? canonical.data.setup_profile : {};
        const research = canonical.data && canonical.data.research_handoff && typeof canonical.data.research_handoff === 'object' ? canonical.data.research_handoff : {};
        const legacyCommit = data && data.legacy_commit ? data.legacy_commit : null;
        const justSyncedSetup = legacyCommit &&
            ['commit_setup_completed_to_legacy', 'commit_tone_of_voice_and_setup_completed_to_legacy'].indexOf(legacyCommit.action) !== -1 &&
            ['synced', 'already_synced'].indexOf(String(legacyCommit.status || '')) !== -1;
        const setupComplete = Boolean(decisions.setup_completed_committed && setupProfile.legacy_setup_completed);
        const prerequisitesComplete = Boolean(
            decisions.activation_verified &&
            (decisions.google_integrations_ready || decisions.google_integrations_skipped) &&
            decisions.business_profile_confirmed &&
            decisions.objectives_confirmed &&
            decisions.seo_profile_confirmed &&
            decisions.competition_keyword_confirmed &&
            decisions.tone_of_voice_selected
        );
        if (
            state.keywordResearchAutoStarted ||
            state.keywordResearchAutoStartScheduled ||
            canonical.phase !== 'research_handoff_ready' ||
            canonical.pending_approval ||
            allowed.indexOf('start_keyword_research_run') === -1 ||
            !setupComplete ||
            !prerequisitesComplete ||
            String(research.status || '') !== 'ready'
        ) {
            return;
        }
        if (justSyncedSetup) {
            return;
        }
        state.keywordResearchAutoStartScheduled = true;
        window.setTimeout(function() {
            state.keywordResearchAutoStartScheduled = false;
            const latest = state.canonical || {};
            const latestAllowed = Array.isArray(latest.allowed_actions) ? latest.allowed_actions : [];
            const latestDecisions = latest.decisions && typeof latest.decisions === 'object' ? latest.decisions : {};
            const latestSetup = latest.data && latest.data.setup_profile && typeof latest.data.setup_profile === 'object' ? latest.data.setup_profile : {};
            const latestResearch = latest.data && latest.data.research_handoff && typeof latest.data.research_handoff === 'object' ? latest.data.research_handoff : {};
            const latestSetupComplete = Boolean(latestDecisions.setup_completed_committed && latestSetup.legacy_setup_completed);
            if (
                state.keywordResearchAutoStarted ||
                latest.phase !== 'research_handoff_ready' ||
                latest.pending_approval ||
                latestAllowed.indexOf('start_keyword_research_run') === -1 ||
                !latestSetupComplete ||
                String(latestResearch.status || '') !== 'ready'
            ) {
                return;
            }
            state.keywordResearchAutoStarted = true;
            rawAjax('aysa_agent8v3_action', {
                agent_action: 'start_keyword_research_run',
                state_version: currentVersion(),
                payload: JSON.stringify({
                    _auto_started_after_setup_complete_status: true
                })
            }).done(function(response) {
                if (response && response.success) {
                    renderPayload(response, {
                        silent: false
                    });
                } else {
                    state.keywordResearchAutoStarted = false;
                }
            }).fail(function() {
                state.keywordResearchAutoStarted = false;
            });
        }, 2500);
    }

    function maybeAutoFinalizeSetupSync() {
        const canonical = state.canonical || {};
        const allowed = Array.isArray(canonical.allowed_actions) ? canonical.allowed_actions : [];
        const decisions = canonical.decisions && typeof canonical.decisions === 'object' ? canonical.decisions : {};
        const setupProfile = canonical.data && canonical.data.setup_profile && typeof canonical.data.setup_profile === 'object' ? canonical.data.setup_profile : {};
        if (decisions.setup_completed_committed || setupProfile.legacy_setup_completed || state.setupCompletedAutoSyncing || canonical.phase !== 'research_handoff_ready' || canonical.pending_approval || allowed.indexOf('commit_setup_completed_to_legacy') === -1) {
            return;
        }
        state.setupCompletedAutoSyncing = true;
        rawAjax('aysa_agent8v3_action', {
            agent_action: 'commit_setup_completed_to_legacy',
            state_version: currentVersion(),
            payload: JSON.stringify({
                _auto_setup_completed_sync: true
            })
        }).done(function(response) {
            if (!(response && response.success && response.data && response.data.state)) {
                state.setupCompletedAutoSyncing = false;
                return;
            }
            rawAjax('aysa_agent8v3_approval', {
                approval: 'approve',
                state_version: response.data.state.state_version
            }).done(function(approvalResponse) {
                if (approvalResponse && approvalResponse.success) {
                    renderPayload(approvalResponse, {
                        silent: true
                    });
                } else {
                    state.setupCompletedAutoSyncing = false;
                }
            }).fail(function() {
                state.setupCompletedAutoSyncing = false;
            });
        }).fail(function() {
            state.setupCompletedAutoSyncing = false;
        });
    }

    function googleReturnStatus() {
        try {
            return new URLSearchParams(window.location.search).get('aysa_google') || '';
        } catch (error) {
            return '';
        }
    }

    function clearGoogleReturnParams() {
        try {
            const url = new URL(window.location.href);
            ['aysa_google', 'aysa_google_project', 'aysa_google_error', 'aysa_google_replayed'].forEach(function(key) {
                url.searchParams.delete(key);
            });
            window.history.replaceState({}, document.title, url.pathname + url.search + url.hash);
        } catch (error) {}
    }

    function refreshGoogleStatusAfterReturn() {
        const allowed = state.canonical && Array.isArray(state.canonical.allowed_actions) ? state.canonical.allowed_actions : [];
        if (!state.canonical) {
            return;
        }
        if (state.canonical.phase === 'business_profile') {
            return;
        }
        if (state.canonical.phase !== 'google_integrations' || allowed.indexOf('refresh_google_connection_status') === -1) {
            clearGoogleReturnParams();
            return;
        }
        request('aysa_agent8v3_action', {
            agent_action: 'refresh_google_connection_status',
            state_version: currentVersion(),
            payload: JSON.stringify({})
        }).always(clearGoogleReturnParams);
    }

    function runModalAgentAction(agentAction, payload, button, retriedAfterStale) {
        let retryingAfterStale = false;
        if (agentAction === 'complete_technical_seo_review') {
            stopImageAltGenerationPolling();
            if (state.technicalSeoTimer) {
                window.clearInterval(state.technicalSeoTimer);
                state.technicalSeoTimer = null;
            }
            state.technicalSeoRefreshing = false;
        }
        button.prop('disabled', true);
        rawAjax('aysa_agent8v3_action', {
            agent_action: agentAction,
            state_version: currentVersion(),
            payload: JSON.stringify(payload)
        }).done(function(response) {
            if (response && response.success) {
                renderPayload(response, { silent: true });
                if (state.modal.key === 'onpage_seo' && (agentAction === 'reject_onpage_item' || agentAction === 'restore_onpage_item')) {
                    updateOnPageReviewRow(button, agentAction, payload);
                } else {
                    if (state.modal.key === 'onpage_seo' && agentAction === 'execute_onpage_plan') {
                        state.modal.onpageMetadataSelectedItems = {};
                        state.modal.onpageMetadataConfirmedSelectionHash = '';
                        state.modal.onpageMetadataConfirmedItems = [];
                        state.modal.filters = state.modal.filters && typeof state.modal.filters === 'object'
                            ? state.modal.filters
                            : {};
                        const waitingForTerminalReadback = onPageSeoNeedsRefresh();
                        state.modal.filters._sync_projection = waitingForTerminalReadback ? '0' : '1';
                        state.modal.filters._sync_projection_mode = waitingForTerminalReadback ? 'review' : 'apply_readback';
                    }
                    loadModal();
                }
                if (agentAction === 'execute_technical_fix_plan' || agentAction === 'refresh_technical_fix_execution_status') {
                    startTechnicalFixExecutionPolling(String(payload.module || ''));
                } else if (agentAction === 'prepare_image_alt_text') {
                    startImageAltGenerationPolling();
                } else if (agentAction === 'run_offpage_backlink_audit') {
                    startOffpageBacklinkAuditPolling();
                } else if (agentAction === 'refresh_offpage_backlink_audit_status' && offpageBacklinkAuditIsTerminal(response)) {
                    stopOffpageBacklinkAuditPolling();
                } else if (agentAction === 'generate_offpage_backlink_strategy') {
                    startOffpageBacklinkStrategyPolling();
                } else if (agentAction === 'refresh_offpage_backlink_strategy_status' && offpageBacklinkStrategyIsTerminal(response)) {
                    stopOffpageBacklinkStrategyPolling();
                } else if (agentAction === 'refresh_monitoring_rank_tracking' || agentAction === 'refresh_monitoring_ai_visibility' ||
                    (agentAction === 'configure_monitoring_policy' && payload && payload.initial_baseline_after_confirmation)) {
                    startMonitoringRefreshPolling();
                }
            } else if (isStaleStateResponse(response) && !retriedAfterStale) {
                retryingAfterStale = true;
                rawAjax('aysa_agent8v3_state', {}).done(function(stateResponse) {
                    if (stateResponse && stateResponse.success) {
                        renderPayload(stateResponse, { silent: true });
                        runModalAgentAction(agentAction, payload, button, true);
                    } else {
                        renderModalError('stale_state_version');
                    }
                }).fail(function() {
                    renderModalError('stale_state_version');
                });
            } else {
                renderModalInlineActionError(apiErrorMessage(response, 'Action failed.'));
            }
        }).fail(function(xhr) {
            renderModalInlineActionError(apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Request failed: HTTP ' + xhr.status));
        }).always(function() {
            if (!retryingAfterStale) {
                button.prop('disabled', false);
            }
        });
    }

    function prepareTechnicalSchemaCandidates(payload, button) {
        payload = payload && typeof payload === 'object' ? payload : {};
        const ro = state.language === 'Romanian';
        const maxItems = Math.max(1, Math.min(3, parseInt(payload.max_items || 3, 10) || 3));
        button.prop('disabled', true);
        rawAjax('aysa_agent8v3_schema_controlled_candidates_prepare', {
            max_items: maxItems
        }).done(function(response) {
            if (!(response && response.success)) {
                renderModalError(apiErrorMessage(response, ro ? 'Nu am putut pregăti candidații Schema.' : 'Could not prepare Schema candidates.'));
                return;
            }
            loadModal();
        }).fail(function(xhr) {
            const response = xhr && xhr.responseJSON ? xhr.responseJSON : null;
            renderModalError(apiErrorMessage(response, ro ? 'Nu am putut pregăti candidații Schema.' : 'Could not prepare Schema candidates.'));
        }).always(function() {
            button.prop('disabled', false);
        });
    }

    function updateOnPageReviewRow(button, agentAction, payload) {
        const row = button.closest('tr');
        const nextAction = agentAction === 'reject_onpage_item' ? 'restore_onpage_item' : 'reject_onpage_item';
        const nextLabel = agentAction === 'reject_onpage_item' ? 'Restore' : 'Reject';
        const nextStatus = agentAction === 'reject_onpage_item' ? 'rejected' : 'accepted';
        const reviewCell = row.find('td.is-col-review_status');
        if (reviewCell.length) {
            reviewCell.html(renderModalChip('review ' + nextStatus, nextStatus === 'rejected' ? '×' : '✓', modalLabel(nextStatus, nextStatus), nextStatus));
        }
        button
            .attr('data-action', nextAction)
            .attr('data-payload', JSON.stringify(payload || {}))
            .text(modalLabel(nextLabel, nextLabel))
            .prop('disabled', false);
    }

    $(function() {
        $('#wpbody-content > .notice, #wpbody-content > .updated, #wpbody-content > .error, #wpbody-content > #message').hide();

        const initialInterfaceLanguage = normalizeLanguageCode(cfg.interface_language || 'ro');
        const initialSelectLanguage = initialInterfaceLanguage === 'en' ? 'en-GB' : initialInterfaceLanguage;
        if ($('#aysa-agent8v3-language option[value="' + initialSelectLanguage + '"]').length) {
            $('#aysa-agent8v3-language').val(initialSelectLanguage);
        }
        applyInterfaceLanguage(initialInterfaceLanguage);

        $('#aysa-agent8v3-send').on('click', function() {
            const button = $(this);
            const input = $('#aysa-agent8v3-input');
            const message = String(input.val() || '').trim();
            if (!message) {
                return;
            }
            if (!isLinkExchangeSummaryRequest(message)) {
                state.offpageLinkExchangePreflight = null;
            }
            const sendMessage = function(financialApproval) {
                input.val('');
                addMessage('user', shouldMaskComposerMessage(message) ? '[secret key hidden]' : message);
                const requestPayload = {
                    message: message,
                    state_version: currentVersion()
                };
                if (financialApproval && typeof financialApproval === 'object') {
                    requestPayload.financial_approval = JSON.stringify(financialApproval);
                }
                request('aysa_agent8v3_message', requestPayload);
            };
            const setupAction = setupChatSaveAction();
            if (setupAction) {
                preflightAndConfirmFixedCostProductAction(button, setupAction, { setup_chat_message: true }, function(approvedPayload) {
                    sendMessage(approvedPayload);
                });
                return;
            }
            sendMessage(null);
        });

        $('#aysa-agent8v3-input').on('keydown', function(event) {
            if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
                event.preventDefault();
                $('#aysa-agent8v3-send').trigger('click');
            }
        });

        $(document).on('click', '.aysa-agent8v3-guidance-toggle', function() {
            state.guidanceCollapsed = !state.guidanceCollapsed;
            updateGuidanceCollapsedDom();
        });

        $(document).on('click', '.aysa-agent8v3-modal-open', function(event) {
            event.preventDefault();
            event.stopPropagation();
            const modalKey = String($(this).data('modal-key') || '');
            if (!modalKey) {
                return;
            }
            if (modalKey === 'monitoring' && state.modal.key === 'monitoring' && !$('#aysa-agent8v3-modal').prop('hidden')) {
                $('.aysa-agent8v3-modal-dialog').trigger('focus');
                return;
            }
            openModal(modalKey, this);
        });

        $(document).on('click', '.aysa-agent8v3-workspace-open', function() {
            openModal(String($(this).data('modal-key') || ''), this);
        });

        $('#aysa-agent8v3-modal-close, [data-agent8v3-modal-close]').on('click', closeModal);

        $(document).on('click', '.aysa-agent8v3-modal-retry', function() {
            loadModal();
        });

        $(document).on('click', '.aysa-agent8v3-onpage-open-history-failsafe', function() {
            if (state.modal.key !== 'onpage_seo') {
                return;
            }
            state.modal.page = 1;
            state.modal.filters = {
                advanced: '1',
                tab: 'execution_report',
                status: 'all',
                _sync_projection: '0',
                _sync_projection_mode: 'apply_readback'
            };
            loadModal();
        });

        $('#aysa-agent8v3-modal-prev').on('click', function() {
            if (state.modal.page > 1) {
                state.modal.page -= 1;
                rememberMonitoringFilterState(null, state.modal.page);
                loadModal();
            }
        });

        $('#aysa-agent8v3-modal-next').on('click', function() {
            state.modal.page += 1;
            rememberMonitoringFilterState(null, state.modal.page);
            loadModal();
        });

        $('#aysa-agent8v3-modal-search').on('keydown', function(event) {
            if (event.key === 'Enter') {
                event.preventDefault();
                state.modal.page = 1;
                state.modal.filters = currentModalFiltersFromControls();
                rememberMonitoringFilterState(state.modal.filters, state.modal.page);
                loadModal();
            }
        });

        $('#aysa-agent8v3-modal-status').on('change', function() {
            state.modal.page = 1;
            state.modal.filters = currentModalFiltersFromControls();
            rememberMonitoringFilterState(state.modal.filters, state.modal.page);
            loadModal();
        });

        $(document).on('click', '.aysa-agent8v3-keyword-mapping-focus-decisions', function() {
            $('#aysa-agent8v3-modal-status').val('decision').trigger('change');
        });

        $(document).on('change', '#aysa-agent8v3-modal-entity-type', function() {
            state.modal.page = 1;
            state.modal.filters = currentModalFiltersFromControls();
            loadModal();
        });

        $(document).on('change', '#aysa-agent8v3-modal-metadata-run', function() {
            state.modal.page = 1;
            state.modal.onpageMetadataSelectedItems = {};
            state.modal.onpageMetadataConfirmedSelectionHash = '';
            state.modal.onpageMetadataConfirmedItems = [];
            state.modal.filters = currentModalFiltersFromControls();
            loadModal();
        });

        $(document).on('change', '.aysa-agent8v3-onpage-metadata-apply-row', function() {
            state.modal.onpageMetadataSelectedItems = state.modal.onpageMetadataSelectedItems || {};
            let item = {};
            try {
                item = JSON.parse(String($(this).attr('data-payload') || '{}'));
            } catch (error) {
                item = {};
            }
            const selectionKey = String(item.provider_output_id || item.entity_key || item.item_id || '');
            if (selectionKey) {
                if ($(this).is(':checked') && item.selectable) {
                    state.modal.onpageMetadataSelectedItems[selectionKey] = {
                        item_id: String(item.item_id || item.entity_key || ''),
                        entity_key: String(item.entity_key || item.item_id || ''),
                        provider_output_id: String(item.provider_output_id || ''),
                        proposal_hash: String(item.proposal_hash || ''),
                        operation: 'apply_meta'
                    };
                } else {
                    delete state.modal.onpageMetadataSelectedItems[selectionKey];
                }
            }
            state.modal.onpageMetadataConfirmedSelectionHash = '';
            state.modal.onpageMetadataConfirmedItems = [];
            $('#aysa-agent8v3-modal-actions .aysa-agent8v3-onpage-metadata-inline-confirm').remove();
            $('#aysa-agent8v3-modal-actions .aysa-agent8v3-modal-action[data-action="execute_onpage_plan"]')
                .removeAttr('data-onpage-metadata-confirmed');
        });

        $(document).on('change', '#aysa-agent8v3-modal-module', function() {
            state.modal.page = 1;
            state.modal.filters = currentModalFiltersFromControls();
            loadModal();
        });

        $(document).on('click', '.aysa-agent8v3-modal-tab', function() {
            const nextTab = String($(this).data('tab') || '');
            const filters = currentModalFiltersFromControls();
            if (state.modal.key === 'monitoring') {
                if (state.modal.monitoringTransitioning) {
                    return;
                }
                rememberMonitoringFilterState(filters, state.modal.page);
                restoreMonitoringFilterState(nextTab, 'overview');
                state.modal.monitoringResetScrollAfterLoad = true;
                resetMonitoringWorkspaceScroll();
                loadModal();
                return;
            }
            state.modal.page = 1;
            if ($(this).hasClass('aysa-agent8v3-advanced-toggle')) {
                filters.advanced = '1';
                filters.tab = state.modal.key === 'offpage_seo' ? 'gbp' : (state.modal.key === 'monitoring' ? 'rank_tracking' : 'keyword_mapping');
                filters.status = 'all';
                state.modal.filters = filters;
                loadModal();
                return;
            }
            filters.tab = nextTab;
            if (state.modal.key === 'technical_internal_linking' && nextTab !== 'link_plan') {
                filters.status = 'all';
            }
            if (state.modal.key === 'onpage_seo') {
                filters.advanced = '1';
                filters._sync_projection = nextTab === 'execution_report' ? '0' : '1';
                filters._sync_projection_mode = nextTab === 'execution_report' ? 'apply_readback' : 'review';
                if (nextTab === 'meta_snippets' || nextTab === 'image_alt' || nextTab === 'execution_report') {
                    filters.status = 'all';
                    delete filters.entity_type;
                    delete filters.workflow_status;
                } else {
                    filters.status = 'all';
                    filters.entity_type = String(filters.entity_type || 'all');
                    filters.workflow_status = String(filters.workflow_status || 'all');
                }
            }
            state.modal.filters = filters;
            loadModal();
        });

        $(document).on('click', '.aysa-agent8v3-monitoring-subtab', function() {
            if (state.modal.key !== 'monitoring' || $(this).prop('disabled') || state.modal.monitoringTransitioning) {
                return;
            }
            const nextView = String($(this).data('monitoring-view') || 'overview');
            const filters = currentModalFiltersFromControls();
            rememberMonitoringFilterState(filters, state.modal.page);
            restoreMonitoringFilterState(String(filters.tab || 'serp_positions'), nextView);
            state.modal.monitoringResetScrollAfterLoad = true;
            resetMonitoringWorkspaceScroll();
            loadModal();
        });

        $(document).on('click', '.aysa-agent8v3-onpage-history-open', function() {
            const snapshotIdentity = String($(this).data('snapshot-identity') || '');
            if (!snapshotIdentity || state.modal.key !== 'onpage_seo') {
                return;
            }
            state.modal.page = 1;
            state.modal.filters = {
                search: '',
                status: 'all',
                tab: 'execution_report',
                advanced: '1',
                _sync_projection: '0',
                _sync_projection_mode: 'apply_readback',
                snapshot_identity: snapshotIdentity
            };
            loadModal();
        });

        $(document).on('click', '.aysa-agent8v3-il-view-plan', function() {
            state.modal.page = 1;
            state.modal.filters = {
                search: String($(this).data('url') || ''),
                status: 'all',
                tab: 'link_plan'
            };
            $('#aysa-agent8v3-modal-search').val(String(state.modal.filters.search || ''));
            $('#aysa-agent8v3-modal-status').val('all');
            loadModal();
        });

        $(document).on('click', '.aysa-agent8v3-image-alt-test-prepare', function() {
            const button = $(this);
            button.prop('disabled', true);
            state.imageAltTestMode.message = '';
            refreshImageAltTestModePanel();
            rawAjax('aysa_agent8v3_image_alt_test_prepare', {}).done(function(response) {
                if (!response || !response.success) {
                    state.imageAltTestMode.message = apiErrorMessage(response, 'Image Alt test prepare failed.');
                    refreshImageAltTestModePanel();
                    return;
                }
                state.imageAltTestMode.items = Array.isArray(response.data && response.data.items) ? response.data.items : [];
                state.imageAltTestMode.result = null;
                state.imageAltTestMode.topup = null;
                state.imageAltTestMode.testMode = response.data && response.data.test_mode ? response.data.test_mode : null;
                state.imageAltTestMode.billingIdentity = response.data && response.data.billing_identity ? response.data.billing_identity : null;
                state.imageAltTestMode.billingIdentityHealth = response.data && response.data.billing_identity_health ? response.data.billing_identity_health : null;
                state.imageAltTestMode.walletSnapshot = response.data && response.data.wallet_snapshot ? response.data.wallet_snapshot : null;
                state.imageAltTestMode.history = Array.isArray(response.data && response.data.history) ? response.data.history : state.imageAltTestMode.history;
                state.imageAltTestMode.historyLoaded = true;
                state.imageAltTestMode.message = state.imageAltTestMode.items.length
                    ? 'Batch pregătit. Verifică imaginile și rulează testul doar dacă sunt corecte.'
                    : 'Nu am găsit imagini sigure cu alt gol/slab pentru test.';
                refreshImageAltTestModePanel();
            }).fail(function(xhr) {
                state.imageAltTestMode.message = apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Image Alt test prepare failed.');
                refreshImageAltTestModePanel();
            }).always(function() {
                button.prop('disabled', false);
            });
        });

        $(document).on('click', '.aysa-agent8v3-image-alt-identity-repair', function() {
            const button = $(this);
            button.prop('disabled', true);
            state.imageAltTestMode.message = 'Repar identitatea AYSA pentru billing...';
            refreshImageAltTestModePanel();
            rawAjax('aysa_agent8v3_image_alt_billing_identity_repair', {}).done(function(response) {
                if (!response || !response.success) {
                    state.imageAltTestMode.message = apiErrorMessage(response, 'AYSA billing identity repair failed.');
                    refreshImageAltTestModePanel();
                    return;
                }
                state.imageAltTestMode.billingIdentity = response.data && response.data.billing_identity ? response.data.billing_identity : state.imageAltTestMode.billingIdentity;
                state.imageAltTestMode.billingIdentityHealth = response.data && response.data.billing_identity_health ? response.data.billing_identity_health : state.imageAltTestMode.billingIdentityHealth;
                state.imageAltTestMode.walletSnapshot = response.data && response.data.wallet_snapshot ? response.data.wallet_snapshot : state.imageAltTestMode.walletSnapshot;
                state.imageAltTestMode.message = 'Identitatea AYSA pentru billing este confirmată. Image Alt apply rămâne blocat până există propuneri, flaguri și confirmare.';
                refreshImageAltTestModePanel();
            }).fail(function(xhr) {
                const data = xhr && xhr.responseJSON ? xhr.responseJSON : null;
                state.imageAltTestMode.billingIdentity = data && data.data && data.data.billing_identity ? data.data.billing_identity : state.imageAltTestMode.billingIdentity;
                state.imageAltTestMode.billingIdentityHealth = data && data.data && data.data.billing_identity_health ? data.data.billing_identity_health : state.imageAltTestMode.billingIdentityHealth;
                state.imageAltTestMode.walletSnapshot = data && data.data && data.data.wallet_snapshot ? data.data.wallet_snapshot : state.imageAltTestMode.walletSnapshot;
                state.imageAltTestMode.message = apiErrorMessage(data, 'AYSA billing identity repair failed.');
                refreshImageAltTestModePanel();
            }).always(function() {
                button.prop('disabled', false);
            });
        });

        $(document).on('click', '.aysa-agent8v3-image-alt-gates-set', function() {
            const button = $(this);
            const projectGate = String(button.data('project-gate') || '0') === '1';
            const siteGate = String(button.data('site-gate') || '0') === '1';
            const ro = String(uiLanguage() || '').indexOf('ro') === 0;
            button.prop('disabled', true);
            state.imageAltTestMode.message = projectGate && siteGate
                ? (ro ? 'Activez gate-urile Image Alt normal flow...' : 'Enabling Image Alt normal flow gates...')
                : (ro ? 'Dezactivez gate-urile Image Alt normal flow...' : 'Disabling Image Alt normal flow gates...');
            refreshImageAltTestModePanel();
            rawAjax('aysa_agent8v3_image_alt_product_gates_set', {
                project_gate_enabled: projectGate ? '1' : '0',
                site_gate_enabled: siteGate ? '1' : '0'
            }).done(function(response) {
                if (!response || !response.success) {
                    state.imageAltTestMode.message = apiErrorMessage(response, 'Image Alt gate update failed.');
                    refreshImageAltTestModePanel();
                    return;
                }
                state.imageAltTestMode.productGates = response.data && response.data.product_gates ? response.data.product_gates : state.imageAltTestMode.productGates;
                state.imageAltTestMode.billingIdentity = response.data && response.data.billing_identity ? response.data.billing_identity : state.imageAltTestMode.billingIdentity;
                state.imageAltTestMode.billingIdentityHealth = response.data && response.data.billing_identity_health ? response.data.billing_identity_health : state.imageAltTestMode.billingIdentityHealth;
                state.imageAltTestMode.walletSnapshot = response.data && response.data.wallet_snapshot ? response.data.wallet_snapshot : state.imageAltTestMode.walletSnapshot;
                state.imageAltTestMode.message = projectGate && siteGate
                    ? (ro ? 'Image Alt normal flow este activ pentru acest proiect/site. Aplicarea cere rânduri acceptate și confirmare explicită.' : 'Image Alt normal flow is enabled for this project/site. Apply still requires accepted rows and explicit confirmation.')
                    : (ro ? 'Image Alt normal flow este dezactivat.' : 'Image Alt normal flow is disabled.');
                refreshImageAltTestModePanel();
            }).fail(function(xhr) {
                state.imageAltTestMode.message = apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Image Alt gate update failed.');
                refreshImageAltTestModePanel();
            }).always(function() {
                button.prop('disabled', false);
            });
        });

        $(document).on('click', '.aysa-agent8v3-image-alt-test-run', function() {
            const selectedIds = $('.aysa-agent8v3-image-alt-test-select:checked').map(function() {
                return String($(this).val() || '');
            }).get().filter(Boolean).slice(0, 3);
            if (!selectedIds.length) {
                state.imageAltTestMode.message = 'Selectează cel puțin o imagine.';
                refreshImageAltTestModePanel();
                return;
            }
            if (selectedIds.length > 3) {
                state.imageAltTestMode.message = 'Testul permite maxim 3 imagini.';
                refreshImageAltTestModePanel();
                return;
            }
            const confirmMessage = 'Confirmi testul Image Alt pe ' + String(selectedIds.length) + ' imagini? Se modifică doar _wp_attachment_image_alt și metadatele AYSA Image Alt. Se debitează doar imaginile schimbate și verificate cu succes.';
            if (!window.confirm(confirmMessage)) {
                return;
            }
            const button = $(this);
            button.prop('disabled', true);
            state.imageAltTestMode.message = 'Rulez testul Image Alt...';
            refreshImageAltTestModePanel();
            rawAjax('aysa_agent8v3_image_alt_test_run', {
                selected_ids: selectedIds
            }).done(function(response) {
                if (!response || !response.success) {
                    state.imageAltTestMode.topup = response && response.data && response.data.billing ? response.data.billing : null;
                    state.imageAltTestMode.billingIdentity = response && response.data && response.data.billing && response.data.billing.billing_identity ? response.data.billing.billing_identity : state.imageAltTestMode.billingIdentity;
                    state.imageAltTestMode.message = apiErrorMessage(response, 'Image Alt test run failed.');
                    refreshImageAltTestModePanel();
                    return;
                }
                state.imageAltTestMode.result = response.data && response.data.result ? response.data.result : null;
                state.imageAltTestMode.testMode = response.data && response.data.test_mode ? response.data.test_mode : { enabled: false };
                state.imageAltTestMode.history = Array.isArray(response.data && response.data.history) ? response.data.history : state.imageAltTestMode.history;
                state.imageAltTestMode.historyLoaded = true;
                state.imageAltTestMode.topup = null;
                state.imageAltTestMode.message = 'Test finalizat. Test mode a fost dezactivat.';
                refreshImageAltTestModePanel();
            }).fail(function(xhr) {
                state.imageAltTestMode.topup = xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.billing ? xhr.responseJSON.data.billing : null;
                state.imageAltTestMode.billingIdentity = xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.billing && xhr.responseJSON.data.billing.billing_identity ? xhr.responseJSON.data.billing.billing_identity : state.imageAltTestMode.billingIdentity;
                state.imageAltTestMode.message = apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Image Alt test run failed.');
                refreshImageAltTestModePanel();
            }).always(function() {
                button.prop('disabled', false);
            });
        });

        $(document).on('click', '.aysa-agent8v3-image-alt-test-disable', function() {
            const button = $(this);
            button.prop('disabled', true);
            rawAjax('aysa_agent8v3_image_alt_test_disable', {}).done(function(response) {
                state.imageAltTestMode.testMode = response && response.data && response.data.test_mode ? response.data.test_mode : { enabled: false };
                state.imageAltTestMode.history = Array.isArray(response && response.data && response.data.history) ? response.data.history : state.imageAltTestMode.history;
                state.imageAltTestMode.historyLoaded = true;
                state.imageAltTestMode.message = 'Image Alt Test Mode este dezactivat.';
                refreshImageAltTestModePanel();
            }).fail(function(xhr) {
                state.imageAltTestMode.message = apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Image Alt test disable failed.');
                refreshImageAltTestModePanel();
            }).always(function() {
                button.prop('disabled', false);
            });
        });

        $(document).on('click', '.aysa-agent8v3-image-alt-test-restore', function() {
            const button = $(this);
            const historyId = String(button.data('history-id') || '');
            const attachmentId = String(button.data('attachment-id') || '');
            if (!historyId) {
                return;
            }
            const siteHost = String(window.location && window.location.hostname || '');
            const confirmMessage = 'Confirmi restaurarea Image Alt pentru attachment ' + attachmentId + ' pe site-ul ' + siteHost + '? Restore modifică doar _wp_attachment_image_alt la valoarea veche salvată, verificată în același proiect/site, și nu se debitează.';
            if (!window.confirm(confirmMessage)) {
                return;
            }
            button.prop('disabled', true);
            state.imageAltTestMode.message = 'Restaurez Image Alt...';
            refreshImageAltTestModePanel();
            rawAjax('aysa_agent8v3_image_alt_test_restore', {
                history_id: historyId
            }).done(function(response) {
                if (!response || !response.success) {
                    state.imageAltTestMode.message = apiErrorMessage(response, 'Image Alt restore failed.');
                    refreshImageAltTestModePanel();
                    return;
                }
                state.imageAltTestMode.history = Array.isArray(response.data && response.data.history) ? response.data.history : state.imageAltTestMode.history;
                state.imageAltTestMode.historyLoaded = true;
                const result = response.data && response.data.result ? response.data.result : {};
                state.imageAltTestMode.message = 'Restore Image Alt: ' + String(result.status || 'completed') + '. Billing: ' + String(response.data.billing_status || 'not_billable_restore') + '.';
                refreshImageAltTestModePanel();
            }).fail(function(xhr) {
                state.imageAltTestMode.message = apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Image Alt restore failed.');
                refreshImageAltTestModePanel();
            }).always(function() {
                button.prop('disabled', false);
            });
        });

        $(document).on('change', '.aysa-agent8v3-authority-plan-row', function() {
            let selectedCost = 0;
            $('.aysa-agent8v3-authority-plan-row:checked').each(function() {
                selectedCost += Math.max(0, parseInt(String($(this).attr('data-cost') || '0'), 10) || 0);
            });
            $('.aysa-agent8v3-authority-selected-cost').text(
                String(selectedCost) + ' credits (' + (selectedCost / 100).toFixed(2) + ' EUR)'
            );
        });

        $(document).on('click', '.aysa-agent8v3-modal-row-action', function() {
            const button = $(this);
            if (button.prop('disabled') || button.is('[disabled]') || String(button.attr('aria-disabled') || '') === 'true') {
                return;
            }
            const agentAction = String(button.data('action') || '');
            let payload = {};
            try {
                payload = JSON.parse(String(button.attr('data-payload') || '{}'));
            } catch (error) {
                payload = {};
            }
            if (!agentAction) {
                return;
            }
            if (agentAction === 'preview_offpage_link_building_cart'
                && state.modal.current
                && String(state.modal.current.modal_key || '') === 'offpage_seo'
                && ['link_building_plan_table', 'offpage_authority_plan'].indexOf(String(state.modal.current.display_mode || '')) !== -1
            ) {
                const selectedRecommendationIds = $('.aysa-agent8v3-authority-plan-row:checked').map(function() {
                    return String($(this).attr('data-recommendation-id') || '');
                }).get().filter(function(id) { return id !== ''; });
                if (!selectedRecommendationIds.length) {
                    state.modal.message = String(uiLanguage() || '').indexOf('ro') === 0
                        ? 'Selectează cel puțin o linie pregătită pentru verificare.'
                        : 'Select at least one line ready for review.';
                    renderModal(state.modal.current);
                    return;
                }
                payload.recommendation_ids = selectedRecommendationIds;
            }
            if (agentAction === 'prepare_technical_schema_candidates') {
                prepareTechnicalSchemaCandidates(payload, button);
                return;
            }
            if (agentAction === 'prepare_image_alt_text' && payload.confirmation_kind === 'technical_image_alt_proposal_generation') {
                if (!confirmTechnicalImageAltProposalGenerationAndMark(payload)) {
                    return;
                }
            }
            if (agentAction === 'confirm_offpage_adverlink_order') {
                if (!confirmOffPageAdverlinkOrderAndMark(payload)) {
                    return;
                }
            }
            if (agentAction === 'queue_offpage_publisher_article_order') {
                if (!confirmOffPagePublisherArticleOrderQueueAndMark(payload)) {
                    return;
                }
            }
            if (agentAction === 'generate_pagespeed_report' && payload.confirmation_kind === 'pagespeed_pdf_report_generation') {
                if (!confirmPageSpeedPdfReportAndMark(payload)) {
                    return;
                }
            }
            if ((agentAction === 'refresh_monitoring_rank_tracking' || agentAction === 'refresh_monitoring_ai_visibility') && payload.confirmation_kind === 'monitoring_billable_refresh') {
                const monitoringRefresh = monitoringRefreshPayloadForCurrentPreflight(agentAction, payload);
                if (!monitoringRefresh.ok) {
                    renderModalError(monitoringRefresh.message);
                    return;
                }
                payload = monitoringRefresh.payload;
                if (!confirmMonitoringBillableRefreshAndMark(payload)) {
                    return;
                }
            }
            if (agentAction === 'configure_monitoring_policy' && payload.confirmation_kind === 'monitoring_policy_approval') {
                const monitoringPolicy = monitoringRefreshPayloadForCurrentPreflight(agentAction, payload);
                if (!monitoringPolicy.ok) {
                    renderModalError(monitoringPolicy.message);
                    return;
                }
                payload = monitoringPolicy.payload;
                if (!window.confirm(String(uiLanguage() || '').indexOf('ro') === 0
                    ? 'Confirmi monitorizarea automată? Primul baseline pentru Poziții Google și Search Console pornește după această confirmare. SERP poate consuma cel mult plafonul aprobat și se taxează numai după salvarea datelor; Search Console nu consumă credite AYSA.'
                    : 'Confirm automatic monitoring? The first Google positions and Search Console baseline starts after this confirmation. SERP can use at most the approved cap and bills only after data is saved; Search Console does not use AYSA credits.')) {
                    return;
                }
                payload.explicit_confirmation = true;
                payload.confirmed = true;
            }
            if (agentAction === 'generate_onpage_meta') {
                if (!confirmOnPageMetaGenerationAndMark(payload)) {
                    return;
                }
            }
            if (agentAction === 'generate_onpage_rewrite_decision'
                || (agentAction === 'generate_onpage_content_rewrite' && payload.confirmation_kind === 'onpage_content_rewrite_generation')) {
                if (!confirmOnPageContentGenerationAndMark(agentAction, payload, button)) {
                    return;
                }
            }
            if (agentAction === 'generate_onpage_content_rewrite' && payload.confirmation_kind === 'onpage_aeo_preview_generation') {
                if (!confirmOnPageAeoPreviewGenerationAndMark(payload, button)) {
                    return;
                }
            }
            if (agentAction === 'generate_onpage_keyword_mapping') {
                if (!confirmOnPageKeywordMappingGenerationAndMark(payload)) {
                    return;
                }
            }
            if (agentAction === 'start_onpage_seo_run') {
                preflightAndConfirmOnPageAnalysis(button, payload);
                return;
            }
            if (agentAction === 'execute_onpage_plan') {
                refreshOnPageContentRewriteLiveBefore(payload, button, function(refreshedPayload) {
                    if (!confirmOnPageApplyAndMark(refreshedPayload, button)) {
                        button.prop('disabled', false);
                        return;
                    }
                    prepareOnPageContentRewriteFinalGates(refreshedPayload, button, function(readyPayload) {
                        runModalAgentAction(agentAction, readyPayload, button, false);
                    });
                });
                return;
            }
            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_image_alt_apply') {
                if (!confirmTechnicalImageAltApplyAndMark(payload)) {
                    return;
                }
                prepareTechnicalImageAltFinalGates(payload, button, function(readyPayload) {
                    runModalAgentAction(agentAction, readyPayload, button, false);
                });
                return;
            }
            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_metadata_apply') {
                if (!confirmTechnicalMetadataApplyAndMark(payload)) {
                    return;
                }
                prepareTechnicalMetadataFinalGates(payload, button, function(readyPayload) {
                    runModalAgentAction(agentAction, readyPayload, button, false);
                });
                return;
            }
	            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_canonical_apply') {
	                if (!confirmTechnicalCanonicalApplyAndMark(payload)) {
	                    return;
	                }
	            }
	            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_schema_consolidation_apply') {
	                if (!confirmTechnicalSchemaConsolidationApplyAndMark(payload)) {
	                    return;
	                }
	            }
	            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_schema_apply') {
	                if (!confirmTechnicalSchemaApplyAndMark(payload)) {
	                    return;
	                }
	            }
	            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_image_optimization_apply') {
	                if (!confirmTechnicalImageOptimizationApplyAndMark(payload)) {
	                    return;
	                }
	            }
	            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'internal_linking_apply') {
	                if (!confirmInternalLinkingApplyAndMark(payload)) {
	                    return;
	                }
	            }
	            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_sitemap_authority_apply') {
	                if (!confirmTechnicalSitemapAuthorityApplyAndMark(payload, button)) {
	                    return;
	                }
	            }
	            if (agentAction === 'complete_technical_seo_review') {
                if (!confirmTechnicalReviewCompleteWithWarningsAndMark(payload)) {
                    return;
                }
            }
            if (isFixedCostProductAction(agentAction)) {
                preflightAndConfirmFixedCostProductAction(button, agentAction, payload, function(approvedPayload) {
                    runModalAgentAction(agentAction, approvedPayload, button, false);
                });
                return;
            }
            runModalAgentAction(agentAction, payload, button, false);
        });

        $(document).on('click', '.aysa-agent8v3-remap-save', function() {
            const button = $(this);
            const wrapper = button.closest('.aysa-agent8v3-remap-control');
            const targetEntityKey = String(wrapper.find('.aysa-agent8v3-remap-target').val() || '');
            const keyword = String(button.data('keyword') || '').trim();
            const itemId = String(button.data('item-id') || '').trim();
            if (!targetEntityKey || !keyword || !itemId) {
                return;
            }
            runModalAgentAction('confirm_onpage_item', {
                section: 'keyword_mapping',
                operation: 'manual_remap',
                item_id: itemId,
                target_entity_key: targetEntityKey,
                keyword: keyword,
                label: keyword
            }, button, false);
        });

        $(document).on('click', '.aysa-agent8v3-modal-action', function() {
            const button = $(this);
            if (button.prop('disabled') || button.is('[disabled]') || String(button.attr('aria-disabled') || '') === 'true') {
                return;
            }
            const agentAction = String(button.data('action') || '');
            let payload = {};
            try {
                payload = JSON.parse(String(button.attr('data-payload') || '{}'));
            } catch (error) {
                payload = {};
            }
            if (!agentAction) {
                return;
            }
            if (agentAction === 'reject_recommended_research_keywords') {
                const count = Array.isArray(payload.keywords) ? payload.keywords.length : 0;
                const ro = state.language === 'Romanian' || String(uiLanguage() || '').indexOf('ro') === 0;
                if (!count || !window.confirm(ro
                    ? 'Respingi cele ' + count + ' keyworduri marcate de sistem ca nerelevante? Le poți restaura ulterior individual.'
                    : 'Reject the ' + count + ' keywords the system marked as irrelevant? You can restore them individually later.')) {
                    return;
                }
                payload.confirmed_by_user = true;
            }
            if (agentAction === 'prepare_technical_schema_candidates') {
                prepareTechnicalSchemaCandidates(payload, button);
                return;
            }
            if (agentAction === 'prepare_image_alt_text' && payload.confirmation_kind === 'technical_image_alt_proposal_generation') {
                if (!confirmTechnicalImageAltProposalGenerationAndMark(payload)) {
                    return;
                }
            }
            if (agentAction === 'confirm_offpage_adverlink_order') {
                if (!confirmOffPageAdverlinkOrderAndMark(payload)) {
                    return;
                }
            }
            if (agentAction === 'queue_offpage_publisher_article_order') {
                if (!confirmOffPagePublisherArticleOrderQueueAndMark(payload)) {
                    return;
                }
            }
            if ((agentAction === 'refresh_monitoring_rank_tracking' || agentAction === 'refresh_monitoring_ai_visibility') && payload.confirmation_kind === 'monitoring_billable_refresh') {
                const monitoringRefresh = monitoringRefreshPayloadForCurrentPreflight(agentAction, payload);
                if (!monitoringRefresh.ok) {
                    renderModalError(monitoringRefresh.message);
                    return;
                }
                payload = monitoringRefresh.payload;
                if (!confirmMonitoringBillableRefreshAndMark(payload)) {
                    return;
                }
            }
            if (agentAction === 'configure_monitoring_policy' && payload.confirmation_kind === 'monitoring_policy_approval') {
                const monitoringPolicy = monitoringRefreshPayloadForCurrentPreflight(agentAction, payload);
                if (!monitoringPolicy.ok) {
                    renderModalError(monitoringPolicy.message);
                    return;
                }
                payload = monitoringPolicy.payload;
                if (!window.confirm(String(uiLanguage() || '').indexOf('ro') === 0
                    ? 'Confirmi monitorizarea automată? Primul baseline pentru Poziții Google și Search Console pornește după această confirmare. SERP poate consuma cel mult plafonul aprobat și se taxează numai după salvarea datelor; Search Console nu consumă credite AYSA.'
                    : 'Confirm automatic monitoring? The first Google positions and Search Console baseline starts after this confirmation. SERP can use at most the approved cap and bills only after data is saved; Search Console does not use AYSA credits.')) {
                    return;
                }
                payload.explicit_confirmation = true;
                payload.confirmed = true;
            }
            if (agentAction === 'generate_onpage_meta') {
                if (!confirmOnPageMetaGenerationAndMark(payload)) {
                    return;
                }
            }
            if (agentAction === 'generate_onpage_rewrite_decision'
                || (agentAction === 'generate_onpage_content_rewrite' && payload.confirmation_kind === 'onpage_content_rewrite_generation')) {
                if (!confirmOnPageContentGenerationAndMark(agentAction, payload, button)) {
                    return;
                }
            }
            if (agentAction === 'generate_onpage_content_rewrite' && payload.confirmation_kind === 'onpage_aeo_preview_generation') {
                if (!confirmOnPageAeoPreviewGenerationAndMark(payload, button)) {
                    return;
                }
            }
            if (agentAction === 'generate_onpage_keyword_mapping') {
                if (!confirmOnPageKeywordMappingGenerationAndMark(payload)) {
                    return;
                }
            }
            if (agentAction === 'start_onpage_seo_run') {
                preflightAndConfirmOnPageAnalysis(button, payload);
                return;
            }
            if (agentAction === 'execute_onpage_plan') {
                refreshOnPageContentRewriteLiveBefore(payload, button, function(refreshedPayload) {
                    if (!confirmOnPageApplyAndMark(refreshedPayload, button)) {
                        button.prop('disabled', false);
                        return;
                    }
                    prepareOnPageContentRewriteFinalGates(refreshedPayload, button, function(readyPayload) {
                        runModalAgentAction(agentAction, readyPayload, button, false);
                    });
                });
                return;
            }
            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_image_alt_apply') {
                if (!confirmTechnicalImageAltApplyAndMark(payload)) {
                    return;
                }
                prepareTechnicalImageAltFinalGates(payload, button, function(readyPayload) {
                    runModalAgentAction(agentAction, readyPayload, button, false);
                });
                return;
            }
            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_metadata_apply') {
                if (!confirmTechnicalMetadataApplyAndMark(payload)) {
                    return;
                }
                prepareTechnicalMetadataFinalGates(payload, button, function(readyPayload) {
                    runModalAgentAction(agentAction, readyPayload, button, false);
                });
                return;
            }
	            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_canonical_apply') {
	                if (!confirmTechnicalCanonicalApplyAndMark(payload)) {
	                    return;
	                }
	            }
	            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_schema_consolidation_apply') {
	                if (!confirmTechnicalSchemaConsolidationApplyAndMark(payload)) {
	                    return;
	                }
	            }
	            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_schema_apply') {
	                if (!confirmTechnicalSchemaApplyAndMark(payload)) {
	                    return;
	                }
	            }
	            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_image_optimization_apply') {
	                if (!confirmTechnicalImageOptimizationApplyAndMark(payload)) {
	                    return;
	                }
	            }
	            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'internal_linking_apply') {
	                if (!confirmInternalLinkingApplyAndMark(payload)) {
	                    return;
	                }
	            }
	            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_sitemap_authority_apply') {
	                if (!confirmTechnicalSitemapAuthorityApplyAndMark(payload, button)) {
	                    return;
	                }
	            }
	            if (agentAction === 'complete_technical_seo_review') {
                if (!confirmTechnicalReviewCompleteWithWarningsAndMark(payload)) {
                    return;
                }
            }
            if (isFixedCostProductAction(agentAction)) {
                preflightAndConfirmFixedCostProductAction(button, agentAction, payload, function(approvedPayload) {
                    runModalAgentAction(agentAction, approvedPayload, button, false);
                });
                return;
            }
            runModalAgentAction(agentAction, payload, button, false);
        });

        $(document).on('click', '.aysa-agent8v3-internal-linking-reject-row', function() {
            const button = $(this);
            if (button.prop('disabled') || button.is('[disabled]')) {
                return;
            }
            const ro = state.language === 'Romanian';
            const operation = String(button.data('operation') || '');
            let payload = {};
            try {
                payload = JSON.parse(String(button.attr('data-payload') || '{}'));
            } catch (error) {
                payload = {};
            }
            if (!payload || typeof payload !== 'object' || !internalLinkingRowKey(payload)) {
                return;
            }
            const rejected = operation !== 'restore';
            markInternalLinkingRejected(payload, rejected, rejected ? 'other' : '');
            button.prop('disabled', true).addClass('is-loading');
            rawAjax('aysa_agent8v3_internal_linking_rejection_action', {
                operation: rejected ? 'reject' : 'restore',
                reason: rejected ? 'other' : '',
                row_payload: JSON.stringify(payload),
                row_hash: internalLinkingRowKey(payload),
                project_id: currentAgent8ProjectId()
            }).always(function() {
                button.prop('disabled', false).removeClass('is-loading');
                state.modal.message = rejected
                    ? (ro ? 'Recomandarea a fost respinsă și nu va fi aplicată.' : 'The recommendation was rejected and will not be applied.')
                    : (ro ? 'Recomandarea a fost restaurată în lista acceptată.' : 'The recommendation was restored to the accepted list.');
                renderModal();
            });
        });

        $(document).on('click', '.aysa-agent8v3-image-optimization-reject-row', function() {
            const button = $(this);
            if (button.prop('disabled') || button.is('[disabled]')) {
                return;
            }
            const ro = state.language === 'Romanian';
            const operation = String(button.data('operation') || '');
            let payload = {};
            try {
                payload = JSON.parse(String(button.attr('data-payload') || '{}'));
            } catch (error) {
                payload = {};
            }
            if (!payload || typeof payload !== 'object' || !imageOptimizationRowKey(payload)) {
                return;
            }
            const rejected = operation !== 'restore';
            markImageOptimizationRejected(payload, rejected, rejected ? 'other' : '');
            state.modal.message = rejected
                ? (ro ? 'Imaginea WebP a fost respinsă și nu va fi inclusă la aplicare.' : 'The WebP image was rejected and will not be included in apply.')
                : (ro ? 'Imaginea WebP a fost restaurată în lista acceptată.' : 'The WebP image was restored to the accepted list.');
            renderModal(state.modal.current || {});
        });

        $(document).on('click', '.aysa-agent8v3-internal-linking-history-action', function() {
            const button = $(this);
            if (button.prop('disabled') || button.is('[disabled]')) {
                return;
            }
            const ro = state.language === 'Romanian';
            const operation = String(button.data('operation') || '');
            const historyId = String(button.data('history-id') || '');
            if (!operation || !historyId) {
                return;
            }
            if (operation === 'restore') {
                const ok = window.confirm(ro
                    ? 'Confirmi restaurarea acestui link intern AYSA? Restore elimină doar modificarea salvată pentru acest history_id și nu se debitează.'
                    : 'Confirm restore for this AYSA internal link? Restore only reverts the stored change for this history_id and is not billable.');
                if (!ok) {
                    return;
                }
            }
            button.prop('disabled', true).addClass('is-loading');
            rawAjax('aysa_agent8v3_internal_linking_history_action', {
                operation: operation,
                history_id: historyId
            }).done(function(response) {
                const data = response && response.data ? response.data : {};
                const status = String(data.status || 'completed');
                state.modal.message = (operation === 'restore'
                    ? (ro ? 'Restore Internal Linking: ' : 'Internal Linking restore: ')
                    : (ro ? 'Reverificare Internal Linking: ' : 'Internal Linking re-verify: ')) + status;
                loadModal(false);
            }).fail(function(xhr) {
                const message = apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Request failed');
                state.modal.error = message;
                renderModal();
            }).always(function() {
                button.prop('disabled', false).removeClass('is-loading');
            });
        });

        $(document).on('click', '.aysa-agent8v3-onpage-content-rewrite-history-action', function() {
            const button = $(this);
            if (button.prop('disabled') || button.is('[disabled]')) {
                return;
            }
            const ro = state.language === 'Romanian' || String(uiLanguage() || '').indexOf('ro') === 0;
            const operation = String(button.data('operation') || '');
            const historyId = String(button.data('history-id') || '');
            if (operation !== 'restore' || !historyId) {
                return;
            }
            const ok = window.confirm(ro
                ? 'Confirmi restore pentru acest Content Rewrite? AYSA revine doar acest history_id la textul anterior, verifică readback-ul și nu debitează credite.'
                : 'Confirm restore for this Content Rewrite? AYSA reverts only this history_id to the previous text, verifies readback, and does not bill credits.');
            if (!ok) {
                return;
            }
            button.prop('disabled', true).addClass('is-loading');
            rawAjax('aysa_agent8v3_onpage_content_rewrite_history_action', {
                operation: 'restore',
                history_id: historyId,
                project_id: currentAgent8ProjectId()
            }).done(function(response) {
                const data = response && response.data ? response.data : {};
                state.onPageContentRewriteHistory.message = (ro ? 'Restore Content Rewrite: ' : 'Content Rewrite restore: ') + String(data.status || 'completed') + ' · ' + String(data.billing_status || 'not_billable_restore');
                state.onPageContentRewriteHistory.loaded = false;
                maybeLoadOnPageContentRewriteHistory(true);
            }).fail(function(xhr) {
                state.onPageContentRewriteHistory.message = apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Content Rewrite restore failed.');
                refreshOnPageContentRewriteHistoryPanel();
            }).always(function() {
                button.prop('disabled', false).removeClass('is-loading');
            });
        });

        $(document).on('click', '.aysa-agent8v3-keyword-family-toggle', function() {
            const button = $(this);
            const expanded = String(button.attr('data-expanded') || '0') === '1';
            const family = button.closest('.aysa-agent8v3-keyword-family');
            if (expanded) {
                family.find('.aysa-agent8v3-keyword-family-extra').remove();
                button.attr('data-expanded', '0').text('+' + String((JSON.parse(String(button.attr('data-extra') || '[]')) || []).length) + ' keywords');
                return;
            }
            let extra = [];
            try {
                extra = JSON.parse(String(button.attr('data-extra') || '[]'));
            } catch (error) {
                extra = [];
            }
            button.before(extra.map(function(item) {
                return '<span class="aysa-agent8v3-keyword-family-extra">' + escapeHtml(item) + '</span>';
            }).join(''));
            button.attr('data-expanded', '1').text(text('collapse'));
        });

        $(document).on('click', '.aysa-agent8v3-schema-items-toggle', function() {
            const button = $(this);
            const expanded = String(button.attr('data-expanded') || '0') === '1';
            const wrap = button.closest('.aysa-agent8v3-schema-items');
            if (expanded) {
                wrap.find('.aysa-agent8v3-schema-item-extra').remove();
                let count = 0;
                try {
                    count = (JSON.parse(String(button.attr('data-extra') || '[]')) || []).length;
                } catch (error) {
                    count = 0;
                }
                button.attr('data-expanded', '0').text('+' + String(count) + ' ' + text('modalSchemaMoreItems'));
                return;
            }
            let extra = [];
            try {
                extra = JSON.parse(String(button.attr('data-extra') || '[]'));
            } catch (error) {
                extra = [];
            }
            button.before(extra.map(function(item) {
                const type = String((item && item.schema_type) || '-');
                const problem = String((item && item.problem) || '-');
                const automation = String((item && item.automation_status) || '');
                const source = String((item && (item.source_label || item.schema_role)) || '');
                const graphRole = String((item && (item.graph_role_label || item.graph_role)) || '');
                const graphRoleKey = String((item && item.graph_role) || 'supporting');
                return '<span class="aysa-agent8v3-schema-item aysa-agent8v3-schema-item-extra" title="' + escapeHtml(problem) + '">' +
                    '<strong>' + escapeHtml(type) + '</strong>' +
                    (graphRole ? '<em class="aysa-agent8v3-schema-graph-role is-' + escapeHtml(graphRoleKey) + '">' + escapeHtml(graphRole) + '</em>' : '') +
                    (source ? '<em>' + escapeHtml(source) + '</em>' : '') +
                    (automation ? renderAutomationStatus(automation) : '') +
                    '<small>' + escapeHtml(problem) + '</small>' +
                    '</span>';
            }).join(''));
            button.attr('data-expanded', '1').text(text('collapse'));
        });

        $(document).on('change', '.aysa-agent8v3-safe-bundle-row', function() {
	        const rowId = String($(this).attr('data-row-id') || '');
	        const exclusions = technicalSafeBundleUiExclusions();
	        if (rowId) {
	            if ($(this).prop('checked')) {
	                delete exclusions.rows[rowId];
	            } else {
	                exclusions.rows[rowId] = true;
	            }
	        }
            updateTechnicalSafeBundleSelectionSummary();
        });

        $(document).on('change', '.aysa-agent8v3-safe-bundle-module', function() {
            const moduleKey = String($(this).attr('data-module') || '');
            const checked = $(this).prop('checked');
	        const exclusions = technicalSafeBundleUiExclusions();
	        if (checked) {
	            delete exclusions.modules[moduleKey];
	        } else {
	            exclusions.modules[moduleKey] = true;
	        }
            $('.aysa-agent8v3-safe-bundle-row').filter(function() {
                return String($(this).attr('data-module') || '') === moduleKey;
            }).prop('checked', checked);
            updateTechnicalSafeBundleSelectionSummary();
        });

        $(document).on('click', '.aysa-agent8v3-safe-bundle-execute', function() {
            const button = $(this);
            if (button.prop('disabled')) {
                return;
            }
            executeTechnicalSafeBundle(button);
        });

        function betaIssueContext() {
            const canonical = state.canonical || {};
            const data = canonical && canonical.data ? canonical.data : {};
            const projectionStatus = $('[data-agent8v3-status]').attr('data-agent8v3-status') || 'idle';
            return redactBetaIssueValue({
                project_id: cfg.project_id || canonical.project_id || '',
                website_id: data.website_id || '',
                site_host: cfg.site_host || window.location.hostname,
                phase: canonical.phase || $('#aysa-agent8v3-chat-phase').text() || '',
                route: window.location.pathname + window.location.search,
                status: projectionStatus,
                module_key: state.modal && state.modal.key ? state.modal.key : 'agent8_v3',
                modal: {
                    key: state.modal.key || '',
                    page: state.modal.page || 1,
                    filters: state.modal.filters || {}
                },
                wallet: state.walletSnapshot || state.billing || {},
                last_debug_request_id: state.lastDebug && state.lastDebug.request_id ? state.lastDebug.request_id : '',
                breadcrumbs: state.betaIssueBreadcrumbs.slice(-50),
                user_agent: window.navigator && window.navigator.userAgent ? window.navigator.userAgent : ''
            });
        }

        function openBetaIssueModal() {
            state.lastBetaIssueContext = betaIssueContext();
            $('#aysa-agent8v3-issue-summary').val('');
            $('#aysa-agent8v3-issue-module').val(state.lastBetaIssueContext.module_key || 'agent8_v3');
            $('#aysa-agent8v3-issue-type').val('cannot_continue');
            $('#aysa-agent8v3-issue-email').val('');
            $('#aysa-agent8v3-issue-screenshot-consent').val('no');
            $('#aysa-agent8v3-issue-result').empty();
            $('#aysa-agent8v3-issue-modal').prop('hidden', false).attr('aria-hidden', 'false');
            $('.aysa-agent8v3-issue-dialog').trigger('focus');
            recordBetaIssueBreadcrumb('issue_modal_opened', {
                module_key: state.lastBetaIssueContext.module_key || 'agent8_v3',
                phase: state.lastBetaIssueContext.phase || ''
            });
        }

        function closeBetaIssueModal() {
            $('#aysa-agent8v3-issue-modal').prop('hidden', true).attr('aria-hidden', 'true');
        }

        function submitBetaIssueReport() {
            const summary = String($('#aysa-agent8v3-issue-summary').val() || '').trim();
            if (!summary) {
                $('#aysa-agent8v3-issue-result').html('<div class="aysa-agent8v3-issue-error">Scrie pe scurt ce problemă ai observat.</div>');
                return;
            }
            const button = $('#aysa-agent8v3-issue-submit');
            button.prop('disabled', true).text('Se trimite...');
            const context = $.extend({}, state.lastBetaIssueContext || betaIssueContext(), {
                user_summary: summary,
                actual_behavior: summary,
                module_key: $('#aysa-agent8v3-issue-module').val() || 'agent8_v3',
                issue_type: $('#aysa-agent8v3-issue-type').val() || 'other',
                screenshot_permission: $('#aysa-agent8v3-issue-screenshot-consent').val() || 'no',
                support_email: $('#aysa-agent8v3-issue-email').val() || '',
                breadcrumbs: state.betaIssueBreadcrumbs.slice(-50)
            });
            rawAjax('aysa_agent8v3_beta_issue_report', {
                issue: JSON.stringify(redactBetaIssueValue(context))
            }).done(function(response) {
                const issue = response && response.success && response.data && response.data.issue ? response.data.issue : null;
                if (!issue) {
                    $('#aysa-agent8v3-issue-result').html('<div class="aysa-agent8v3-issue-error">Nu am putut crea raportul. Încearcă din nou.</div>');
                    return;
                }
                $('#aysa-agent8v3-issue-result').html([
                    '<div class="aysa-agent8v3-issue-success">',
                    '<strong>Raport creat:</strong> ' + escapeHtml(issue.issue_id) + ' · ' + escapeHtml(issue.severity),
                    '<p>' + escapeHtml(issue.human_summary || '') + '</p>',
                    '<label>Detalii tehnice pentru suport',
                    '<textarea readonly rows="8">' + escapeHtml(issue.codex_bundle_markdown || '') + '</textarea>',
                    '</label>',
                    '</div>'
                ].join(''));
            }).fail(function() {
                $('#aysa-agent8v3-issue-result').html('<div class="aysa-agent8v3-issue-error">Raportarea nu a ajuns la server.</div>');
            }).always(function() {
                button.prop('disabled', false).text('Trimite raportul');
            });
        }

        $(document).on('keydown', function(event) {
            if (event.key === 'Escape' && !$('#aysa-agent8v3-modal').prop('hidden')) {
                closeModal();
            }
            if (event.key === 'Escape' && !$('#aysa-agent8v3-issue-modal').prop('hidden')) {
                closeBetaIssueModal();
            }
        });

        $('.aysa-agent8v3-composer-panel').on('click', function(event) {
            if ($(event.target).is('button, a, select, input, textarea')) {
                return;
            }
            $('#aysa-agent8v3-input').trigger('focus');
        });

        $(document).on('click', '.aysa-agent8v3-rag-close', function() {
            const id = String($(this).data('rag-id') || '');
            state.ragContexts = state.ragContexts.filter(function(item) {
                return item.id !== id;
            });
            renderMessages();
        });

        $('#aysa-agent8v3-language').on('change', function() {
            const language = String($(this).val() || 'ro');
            applyInterfaceLanguage(language);
            if (state.modal && state.modal.current && (state.modal.workspace || !$('#aysa-agent8v3-modal').prop('hidden'))) {
                renderModal(state.modal.current);
            }
            request('aysa_agent8v3_action', {
                agent_action: 'set_language',
                state_version: currentVersion(),
                payload: JSON.stringify({ language: language, _silent_refresh: true })
            }, { silent: true });
        });

        function canonicalBusinessProfileUnavailableField(value) {
            const key = String(value || '').trim().toLowerCase().replace(/[^a-z0-9_]+/g, '_');
            const aliases = {
                email: 'support_email',
                e_mail: 'support_email',
                mail: 'support_email',
                public_email: 'support_email',
                contact_email: 'support_email',
                email_address: 'support_email',
                supportemail: 'support_email',
                supportemailaddress: 'support_email',
                support_email: 'support_email',
                business_profile_support_email: 'support_email',
                businessprofilesupportemail: 'support_email',
                business_profile_email: 'support_email',
                phone: 'support_phone',
                telefon: 'support_phone',
                tel: 'support_phone',
                support_phone: 'support_phone',
                address: 'address',
                adresa: 'address',
                adres_: 'address',
                locatie: 'address',
                location: 'address'
            };
            return aliases[key] || key;
        }

        function inferBusinessProfileUnavailableFieldFromLabel(label) {
            const text = String(label || '').toLowerCase();
            if (/(e[-\s]?mail|email|mail)/.test(text)) {
                return 'support_email';
            }
            if (/(telefon|phone|tel\b)/.test(text)) {
                return 'support_phone';
            }
            if (/(adres|address|locaț|locat|location)/.test(text)) {
                return 'address';
            }
            return '';
        }

        function actionPayloadForGuidanceButton(action, rawPayload, label) {
            const payload = rawPayload && typeof rawPayload === 'object' ? Object.assign({}, rawPayload) : {};
            if (String(action || '') === 'mark_business_profile_field_unavailable') {
                payload.field = canonicalBusinessProfileUnavailableField(
                    payload.field || payload.field_key || payload.name || inferBusinessProfileUnavailableFieldFromLabel(label)
                );
            }
            return payload;
        }

        $(document).on('click', '.aysa-agent8v3-action', function() {
            const button = $(this);
            const agentAction = String(button.data('action') || '');
            recordBetaIssueBreadcrumb('action_clicked', {
                agent_action: agentAction,
                label: $(this).text()
            });
            let payload = {};
            const rawPayload = $(this).attr('data-payload');
            if (rawPayload) {
                try {
                    const parsedPayload = JSON.parse(rawPayload);
                    if (parsedPayload && typeof parsedPayload === 'object') {
                        payload = parsedPayload;
                    }
                } catch (e) {
                    payload = {};
                }
            }
            if (agentAction === 'save_business_type' || agentAction === 'save_primary_goal') {
                const input = $('#aysa-agent8v3-input');
                const value = String(input.val() || '').trim();
                if (!value) {
                    addMessage('system', 'Type the value in the composer, then run this action.');
                    return;
                }
                input.val('');
                addMessage('user', value);
                payload.value = value;
            }
            if (agentAction === 'mark_business_profile_field_unavailable') {
                payload = actionPayloadForGuidanceButton(agentAction, payload, $(this).text());
            }
            if (agentAction === 'run_business_profile_autofill') {
                preflightAndConfirmBusinessProfileAutofill(button);
                return;
            }
            if (agentAction === 'run_competition_keyword_analysis') {
                preflightAndConfirmCompetitionKeywordAnalysis(button);
                return;
            }
            if (agentAction === 'start_keyword_research_run' || agentAction === 'retry_keyword_research_run') {
                preflightAndConfirmKeywordResearch(button, agentAction);
                return;
            }
            if (agentAction === 'complete_technical_seo_review') {
                if (!confirmTechnicalReviewCompleteWithWarningsAndMark(payload)) {
                    return;
                }
            }
            if (agentAction === 'start_onpage_seo_run') {
                preflightAndConfirmOnPageAnalysis(button, payload);
                return;
            }
            if (isFixedCostProductAction(agentAction)) {
                preflightAndConfirmFixedCostProductAction(button, agentAction, payload, function(approvedPayload) {
                    request('aysa_agent8v3_action', {
                        agent_action: agentAction,
                        state_version: currentVersion(),
                        payload: JSON.stringify(approvedPayload)
                    });
                });
                return;
            }
            request('aysa_agent8v3_action', {
                agent_action: agentAction,
                state_version: currentVersion(),
                payload: JSON.stringify(payload)
            });
        });

        $(document).on('click', '.aysa-agent8v3-approval', function() {
            request('aysa_agent8v3_approval', {
                approval: $(this).data('approval'),
                state_version: currentVersion()
            });
        });

        $('#aysa-agent8v3-debug-toggle').on('click', function() {
            $('#aysa-agent8v3-debug').prop('hidden', !$('#aysa-agent8v3-debug').prop('hidden'));
        });

        $('#aysa-agent8v3-full-reset').on('click', function() {
            fullResetToPreActivation();
        });

        $('#aysa-agent8v3-factory-reset').on('click', function() {
            factoryResetTestFlow();
        });
        updateFactoryResetVisibility();
        openOnPageQaHistoryFromQuery();

        $('#aysa-agent8v3-report-problem').on('click', function() {
            openBetaIssueModal();
        });

        $(document).on('click', '[data-agent8v3-issue-close]', function() {
            closeBetaIssueModal();
        });

        $('#aysa-agent8v3-issue-submit').on('click', function() {
            submitBetaIssueReport();
        });

        $('#aysa-agent8v3-qa-toggle').on('click', function() {
            $('#aysa-agent8v3-qa-body').prop('hidden', !$('#aysa-agent8v3-qa-body').prop('hidden'));
        });

        if (!cfg.qa_enabled) {
            $('#aysa-agent8v3-qa-disabled').prop('hidden', false);
            $('.aysa-agent8v3-qa-run, #aysa-agent8v3-qa-stop, #aysa-agent8v3-qa-clear, #aysa-agent8v3-qa-export').prop('disabled', true);
        }

        $(document).on('click', '.aysa-agent8v3-qa-run', function() {
            runUiQaSuite($(this).data('suite') || 'all');
        });

        $('#aysa-agent8v3-qa-clear').on('click', function() {
            state.stressStopRequested = true;
            state.qaEvents = [];
            state.qaRunId = '';
            $('#aysa-agent8v3-qa-summary').text('cleared UI QA events');
            $('#aysa-agent8v3-qa-results').empty();
            qaRequest('aysa_agent8v3_qa_clear');
        });

        $('#aysa-agent8v3-qa-stop').on('click', function() {
            state.stressStopRequested = true;
            $('#aysa-agent8v3-qa-summary').text('Stopping stress test after current request...');
        });

        $('#aysa-agent8v3-qa-export').on('click', function() {
            if (state.qaEvents.length) {
                renderQa({ events: state.qaEvents });
                const blob = new Blob([JSON.stringify({ test_run_id: state.qaRunId, events: state.qaEvents }, null, 2)], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                link.download = 'agent8-v3-ui-qa-log.json';
                link.click();
                URL.revokeObjectURL(url);
                return;
            }
            qaRequest('aysa_agent8v3_qa_export', {}, true);
        });

        setStatus('thinking');
        const returnedFromGoogle = googleReturnStatus() === 'connected';
        request('aysa_agent8v3_state').done(function() {
            if (returnedFromGoogle) {
                refreshGoogleStatusAfterReturn();
            }
            openModuleWorkspaceFromQuery();
            if (shouldOpenOffpagePublisherArticlesQa()) {
                window.setTimeout(openOffpagePublisherArticlesQaProjection, 250);
            }
        });
    });
})(jQuery);
