(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,
        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,
        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: ''
        },
        offpageBacklinkAuditTimer: null,
        offpageBacklinkAuditRefreshing: false,
        offpageBacklinkStrategyTimer: null,
        offpageBacklinkStrategyRefreshing: false,
        offpageBacklinkStrategyAutoRefreshed: false,
        monitoringRefreshTimer: null,
        monitoringRefreshTicks: 0,
        completedRunMessages: {},
        pendingChat: null,
        typewriterTimers: {},
        modal: {
            key: '',
            page: 1,
            perPage: 25,
            filters: {},
            lastTrigger: null
        }
    };

    function setStatus(status) {
        $('[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 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',
            '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 linkifySafeText(value, sanitizeCopy) {
        const safeValue = sanitizeCopy ? customerText(value) : value;
        return escapeHtml(safeValue).replace(/https:\/\/app\.aysa\.ai\/websites/g, '<a href="https://app.aysa.ai/websites" target="_blank" rel="noopener noreferrer">https://app.aysa.ai/websites</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 Agent 8 V3 Lab', subtitle: 'Deterministic execution system', active: 'Active', conversation: 'Conversation',
            execution: 'Agent8 V3 Execution', waiting: 'waiting for updates', placeholder: 'Describe the task for AYSA Agent 8...',
            authenticated: 'Authenticated', unauthenticated: 'Unauthenticated', automatedSeo: 'Automated SEO', qaDiagnostics: 'QA Diagnostics', controls: 'Controls',
            fullReset: 'Full reset', fullResetConfirm: 'Reset Agent8 V3 Lab to pre-activation and clear chat history, setup data, and local saved results?', fullResetDone: 'Agent8 V3 Lab was reset.',
            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: '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: 'Canonical 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', approve: 'Approve', reject: 'Reject',
            expand: 'Expand', collapse: 'Collapse',
            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',
            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: 'retry Keyword Research', start_technical_seo_run: 'start Technical SEO', refresh_technical_seo_status: 'check Technical SEO', complete_technical_seo_review: 'complete review and continue to On Page', 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...', 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...', 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: 'Mapped clusters and target pages from the research projection.',
            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 Agent 8 V3 Lab', subtitle: 'Sistem de execuție determinist', active: 'Activ', conversation: 'Conversație',
            execution: 'Execuție Agent8 V3', waiting: 'așteaptă actualizări', placeholder: 'Descrie sarcina pentru AYSA Agent 8...',
            authenticated: 'Autentificat', unauthenticated: 'Neautentificat', automatedSeo: 'SEO Automatizat', qaDiagnostics: 'QA Diagnostics', controls: 'Controale',
            fullReset: 'Reset complet', fullResetConfirm: 'Resetezi Agent8 V3 Lab la preactivare și cureți istoricul chatului, datele setup și rezultatele salvate local?', fullResetDone: 'Agent8 V3 Lab a fost resetat.',
            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 state', 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: 'State canonic',
            idle: 'Inactiv', approvalRequired: 'Necesită aprobare', approve: 'Aprobă', reject: 'Respinge',
            expand: 'Extinde', collapse: 'Restrânge',
            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',
            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: 'repornește Keyword Research', start_technical_seo_run: 'pornește Technical SEO', refresh_technical_seo_status: 'verifică Technical SEO', complete_technical_seo_review: 'finalizează review-ul și continuă către On Page', skip_technical_seo: 'sari peste Technical SEO', planning: 'Planificare', executing: 'Execuție', completed: 'finalizat', completed_with_warnings: 'necesită review manual',
            running: 'rulează', thinking: 'gândește', failed: 'eșuat',
            approve_content_plan: 'Aprobă planul',
            modalLoading: 'Se încarcă', modalLoadingData: 'Se încarcă datele de review...', 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...', 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: 'Clustere mapate și pagini țintă din proiecția research.',
            modalCluster: 'Cluster', modalTargetUrl: 'URL țintă', modalPrimaryKeyword: 'Keyword principal', modalKeywordFamily: 'Familie keywords', modalSignals: 'Semnale', modalIntent: 'Intent', modalStatus: 'Status', modalConfidence: 'Încredere', modalTrust: 'Trust', modalRecommendation: 'Recomandare', modalReasons: 'Motive', modalTrusted: 'Trusted', modalRecommendedReject: 'Recomandat respins', modalReviewNeeded: 'Review', modalReview: 'Review', 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 Agent 8 V3 Lab', subtitle: 'Système d’exécution déterministe', active: 'Actif', conversation: 'Conversation',
            execution: 'Exécution Agent8 V3', 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 Agent 8 V3 Lab', subtitle: 'Deterministisches Ausführungssystem', active: 'Aktiv', conversation: 'Konversation',
            execution: 'Agent8 V3 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 Agent 8 V3 Lab', subtitle: 'Sistema de ejecución determinista', active: 'Activo', conversation: 'Conversación',
            execution: 'Ejecución Agent8 V3', 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 Agent 8 V3 Lab', subtitle: 'Sistema di esecuzione deterministico', active: 'Attivo', conversation: 'Conversazione',
            execution: 'Esecuzione Agent8 V3', 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 Agent 8 V3 Lab', subtitle: 'Sistema de execução determinístico', active: 'Ativo', conversation: 'Conversa',
            execution: 'Execução Agent8 V3', 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 Agent 8 V3 Lab', subtitle: 'Deterministisch uitvoeringssysteem', active: 'Actief', conversation: 'Gesprek',
            execution: 'Agent8 V3 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 Agent 8 V3 Lab', subtitle: 'Deterministyczny system wykonania', active: 'Aktywny', conversation: 'Rozmowa',
            execution: 'Wykonanie Agent8 V3', 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 V3', 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 V3 Lab en préactivation et effacer l’historique du chat, les données de configuration et les résultats locaux enregistrés?', fullResetDone: 'Agent8 V3 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 V3 Lab auf Voraktivierung zurücksetzen und Chatverlauf, Setup-Daten und lokal gespeicherte Ergebnisse löschen?', fullResetDone: 'Agent8 V3 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 Agent 8 V3 Lab', subtitle: 'Sistema de ejecución determinista', active: 'Activo', conversation: 'Conversación', execution: 'Ejecución Agent8 V3', 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 Agent 8 V3 Lab', subtitle: 'Sistema di esecuzione deterministico', active: 'Attivo', conversation: 'Conversazione', execution: 'Esecuzione Agent8 V3', 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 Agent 8 V3 Lab', subtitle: 'Sistema de execução determinístico', active: 'Ativo', conversation: 'Conversa', execution: 'Execução Agent8 V3', 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 Agent 8 V3 Lab', subtitle: 'Deterministisch uitvoeringssysteem', active: 'Actief', conversation: 'Gesprek', execution: 'Agent8 V3 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 Agent 8 V3 Lab', subtitle: 'Deterministyczny system wykonania', active: 'Aktywny', conversation: 'Rozmowa', execution: 'Wykonanie Agent8 V3', 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 V3 Lab إلى ما قبل التفعيل ومسح سجل المحادثة وبيانات الإعداد والنتائج المحلية؟', fullResetDone: 'تمت إعادة ضبط Agent8 V3 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 Agent 8 V3 Lab',subtitle:'Sistem ekzekutimi determinist',active:'Aktiv',conversation:'Bisedë',execution:'Ekzekutim Agent8 V3',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 Agent 8 V3 Lab',subtitle:'Դետերմինիստական կատարման համակարգ',active:'Ակտիվ',conversation:'Զրույց',execution:'Agent8 V3 կատարում',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 Agent 8 V3 Lab',subtitle:'Deterministik icra sistemi',active:'Aktiv',conversation:'Söhbət',execution:'Agent8 V3 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 Agent 8 V3 Lab',subtitle:'Exekuzio sistema determinista',active:'Aktibo',conversation:'Elkarrizketa',execution:'Agent8 V3 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 Agent 8 V3 Lab',subtitle:'Дэтэрмінаваная сістэма выканання',active:'Актыўны',conversation:'Размова',execution:'Выкананне Agent8 V3',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 Agent 8 V3 Lab',subtitle:'Deterministički sistem izvršavanja',active:'Aktivan',conversation:'Razgovor',execution:'Agent8 V3 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 Agent 8 V3 Lab',subtitle:'Детерминистична система за изпълнение',active:'Активен',conversation:'Разговор',execution:'Изпълнение Agent8 V3',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 Agent 8 V3 Lab',subtitle:'Sistema d’execució determinista',active:'Actiu',conversation:'Conversa',execution:'Execució Agent8 V3',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 Agent 8 V3 Lab',subtitle:'Deterministički sustav izvršavanja',active:'Aktivan',conversation:'Razgovor',execution:'Izvršavanje Agent8 V3',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 Agent 8 V3 Lab',subtitle:'Deterministický systém spouštění',active:'Aktivní',conversation:'Konverzace',execution:'Spuštění Agent8 V3',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 Agent 8 V3 Lab',subtitle:'Deterministisk eksekveringssystem',active:'Aktiv',conversation:'Samtale',execution:'Agent8 V3 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 Agent 8 V3 Lab',subtitle:'Deterministlik täitmissüsteem',active:'Aktiivne',conversation:'Vestlus',execution:'Agent8 V3 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 Agent 8 V3 Lab',subtitle:'Deterministinen suoritusjärjestelmä',active:'Aktiivinen',conversation:'Keskustelu',execution:'Agent8 V3 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 Agent 8 V3 Lab',subtitle:'Sistema de execución determinista',active:'Activo',conversation:'Conversa',execution:'Execución Agent8 V3',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 Agent 8 V3 Lab',subtitle:'დეტერმინისტული შესრულების სისტემა',active:'აქტიური',conversation:'საუბარი',execution:'Agent8 V3 შესრულება',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 Agent 8 V3 Lab',subtitle:'Ντετερμινιστικό σύστημα εκτέλεσης',active:'Ενεργό',conversation:'Συνομιλία',execution:'Εκτέλεση Agent8 V3',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 Agent 8 V3 Lab',subtitle:'Determinisztikus végrehajtási rendszer',active:'Aktív',conversation:'Beszélgetés',execution:'Agent8 V3 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 Agent 8 V3 Lab',subtitle:'Ákveðið keyrslukerfi',active:'Virkt',conversation:'Samtal',execution:'Agent8 V3 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 Agent 8 V3 Lab',subtitle:'Córas forghníomhaithe cinntitheach',active:'Gníomhach',conversation:'Comhrá',execution:'Forghníomhú Agent8 V3',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 Agent 8 V3 Lab',subtitle:'Deterministiska izpildes sistēma',active:'Aktīvs',conversation:'Saruna',execution:'Agent8 V3 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 Agent 8 V3 Lab',subtitle:'Deterministinė vykdymo sistema',active:'Aktyvus',conversation:'Pokalbis',execution:'Agent8 V3 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 Agent 8 V3 Lab',subtitle:'Deterministescht Ausféierungssystem',active:'Aktiv',conversation:'Gespréich',execution:'Agent8 V3 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 Agent 8 V3 Lab',subtitle:'Детерминистички систем за извршување',active:'Активен',conversation:'Разговор',execution:'Извршување Agent8 V3',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 Agent 8 V3 Lab',subtitle:'Sistema ta’ eżekuzzjoni deterministika',active:'Attiv',conversation:'Konverżazzjoni',execution:'Eżekuzzjoni Agent8 V3',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 Agent 8 V3 Lab',subtitle:'Deterministisk utførelsessystem',active:'Aktiv',conversation:'Samtale',execution:'Agent8 V3 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 Agent 8 V3 Lab',subtitle:'Детерминированная система выполнения',active:'Активен',conversation:'Диалог',execution:'Выполнение Agent8 V3',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 Agent 8 V3 Lab',subtitle:'Детерминистички систем извршавања',active:'Активан',conversation:'Разговор',execution:'Извршавање Agent8 V3',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 Agent 8 V3 Lab',subtitle:'Deterministický systém vykonávania',active:'Aktívny',conversation:'Konverzácia',execution:'Vykonávanie Agent8 V3',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 Agent 8 V3 Lab',subtitle:'Deterministični sistem izvajanja',active:'Aktiven',conversation:'Pogovor',execution:'Izvajanje Agent8 V3',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 Agent 8 V3 Lab',subtitle:'Deterministiskt körningssystem',active:'Aktiv',conversation:'Konversation',execution:'Agent8 V3 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 Agent 8 V3 Lab',subtitle:'Deterministik yürütme sistemi',active:'Aktif',conversation:'Konuşma',execution:'Agent8 V3 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 Agent 8 V3 Lab',subtitle:'Детермінована система виконання',active:'Активний',conversation:'Розмова',execution:'Виконання Agent8 V3',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 Agent 8 V3 Lab',subtitle:'System weithredu benderfynol',active:'Gweithredol',conversation:'Sgwrs',execution:'Gweithredu Agent8 V3',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 Agent 8 V3 Lab',subtitle:'דיטערמיניסטישע אויספיר סיסטעם',active:'אַקטיוו',conversation:'שמועס',execution:'Agent8 V3 אויספיר',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 uiLanguage() {
        const canonical = state.canonical || {};
        return String((canonical.data && canonical.data.language) || (canonical.decisions && canonical.decisions.language) || $('#aysa-agent8v3-language').val() || '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 actionLabel(action) {
        return text(action) || String(action || '').replace(/_/g, ' ');
    }

    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) {
        const packKey = LANGUAGE_PACK[language] || language;
        const isRtl = packKey === 'ar';
        $('.aysa-agent8v3-app').attr('lang', language || 'ro').attr('dir', isRtl ? 'rtl' : 'ltr');
        $('.aysa-agent8v3-brand h1').text(text('title'));
        $('.aysa-agent8v3-subtitle').text(text('subtitle'));
        $('.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'));
        updateAuthPill(state.canonical);
        $('.aysa-agent8v3-mode-pill').text(text('automatedSeo'));
        $('#aysa-agent8v3-full-reset').text(text('fullReset'));
        $('.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 shouldMaskComposerMessage(message) {
        const raw = String(message || '').trim();
        if (!raw) {
            return false;
        }

        const placeholder = String($('#aysa-agent8v3-input').attr('placeholder') || '').toLowerCase();
        if (placeholder.indexOf('secret key') !== -1 || placeholder.indexOf('activation key') !== -1) {
            return true;
        }

        const phase = String(state.canonical && state.canonical.phase ? state.canonical.phase : '').toLowerCase();
        if (phase.indexOf('activation') !== -1 || phase.indexOf('pre_activation') !== -1) {
            return true;
        }

        const guidance = state.guidance && typeof state.guidance === 'object' ? state.guidance : {};
        const action = String(guidance.allowed_action || guidance.action || '').toLowerCase();
        if (action.indexOf('activation_key') !== -1 || action.indexOf('secret_key') !== -1) {
            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 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;
        let lastAssistantIndex = -1;
        let lastGuidanceIndex = -1;
        state.messages.forEach(function(message, index) {
            if (String(message.role || '') === 'assistant') {
                lastAssistantIndex = index;
                if (message.guidance && typeof message.guidance === 'object') {
                    lastGuidanceIndex = index;
                }
            }
        });

        const messageHtml = state.messages.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(message.body, true)) + '</div>' +
                '</div>' +
            '</div>';
            const guidanceHtml = '';
            return assistantHtml + guidanceHtml;
        }).join('');
        const ragHtml = state.ragContexts.map(ragContextHtml).join('');
        const guidanceHtml = '';
        const guidanceDialogueHtml = guidanceDialogueMessageHtml(state.guidance);
        const html = messageHtml + ragHtml + 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 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 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 || '');
        return (optionAction && optionAction === primaryAction) || (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) : '';
        const display = normalizeActionDisplay(primaryCta.label || actionLabel(action || modalKey), primaryCta.badges || []);
        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 = primaryCta.payload && typeof primaryCta.payload === 'object' ? primaryCta.payload : {};
        return '<span class="aysa-agent8v3-action-with-badges is-header-cta">' +
            '<button type="button" class="button button-primary aysa-agent8v3-guidance-option aysa-agent8v3-action is-primary" 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 = option.payload && typeof option.payload === 'object' ? option.payload : {};
            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 = 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;
        $('.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 || []);
        }, []);
        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 = 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')
            : (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 || {});
            const groupClass = groupWarning ? 'is-active' : (isFlowComplete || activeIndex > groupEnd ? 'is-done' : (boundedIndex >= groupStart && boundedIndex <= groupEnd ? 'is-active' : 'is-pending'));
            const groupStateText = groupClass === 'is-done'
                ? (isRo ? 'Finalizat' : 'Done')
                : (groupWarning ? (isRo ? 'Finalizat cu verificări' : 'Done with checks') : (groupClass === 'is-active' ? activeStepText : (isRo ? 'Urmează' : 'Next')));
            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')));
                return '<li class="' + stateClass + '"' + currentAttr + '>' +
                    '<span class="aysa-agent8v3-progress-dot">' + (stateClass === 'is-active' && stepState.showLoader ? '<i></i>' : '') + '</span>' +
                    '<span><strong>' + escapeHtml(step.label) + '</strong><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 = warning
            ? (isRo ? 'Necesită atenție' : 'Needs attention')
            : (progressState.status || (isFlowComplete ? (isRo ? 'Flow finalizat' : 'Flow complete') : (isRo ? 'În lucru' : 'In progress')));
        const nowText = isFlowComplete
            ? (isRo ? 'Flow-ul principal este finalizat.' : 'The main flow is complete.')
            : ((isRo ? 'Acum: ' : 'Now: ') + currentStep.label);
        const nextText = 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')));
        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>' +
            (ctaHtml ? '<div class="aysa-agent8v3-progress-next"><small>' + escapeHtml(isRo ? 'Următorul pas' : 'Next step') + '</small>' + ctaHtml + '</div>' : '')
        );
    }

    function rightPanelProgressHtml(progress, isRo) {
        const percent = Math.max(0, Math.min(100, parseInt(progress.percent, 10) || 0));
        const status = String(progress.status || 'running');
        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(percent + '%') + '</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 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 summaryModule = moduleKey && summaryModules[moduleKey] && typeof summaryModules[moduleKey] === 'object' ? summaryModules[moduleKey] : {};
        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: 'included_links',
            offpage_publishers: 'publisher_articles',
            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 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 offpageModule = offpageModuleKey && (offpageModules[offpageModuleKey] || offpageStateModules[offpageModuleKey] || offpageIncluded[offpageModuleKey])
            ? Object.assign({}, offpageModules[offpageModuleKey] || {}, offpageStateModules[offpageModuleKey] || {}, offpageIncluded[offpageModuleKey] || {})
            : null;
        const monitoringMap = {
            monitoring_rank: 'rank_tracking',
            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 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') {
                stateClass = 'is-done';
                if (offpageModuleKey === 'included_links') {
                    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 {
                    stateText = 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 === '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';
            }
        }
        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] : {};
        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 ? 'Research & strategie' : 'Research & strategy',
                steps: [
                    {key: 'keyword_research', label: isRo ? 'Keyword Research' : 'Keyword Research'},
                    {key: 'research_keywords', label: isRo ? 'Keywords' : 'Keywords'},
                    {key: 'keyword_mapping', label: isRo ? 'Keyword Mapping' : 'Keyword Mapping'},
                    {key: 'missing_pages', label: isRo ? 'Pagini lipsă' : '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 ? 'Optimizare imagini' : 'Image Optimization'}
                ]
            },
            {
                key: 'onpage_seo',
                label: isRo ? 'On Page SEO' : 'On Page SEO',
                steps: [
                    {key: 'onpage_keyword_mapping', label: isRo ? 'Keyword Mapping' : 'Keyword Mapping'},
                    {key: 'onpage_meta', label: isRo ? 'Meta & Snippets' : 'Meta & Snippets'},
                    {key: 'onpage_content', label: isRo ? 'Content' : 'Content'},
                    {key: 'onpage_aeo', label: isRo ? 'AEO Content QA' : 'AEO Content QA'},
                    {key: 'onpage_links', label: isRo ? 'Links & Authority' : 'Links & Authority'},
                    {key: 'onpage_alt_text', label: isRo ? 'Alt text' : 'Alt text'},
                    {key: 'onpage_execution_report', label: isRo ? 'Execution Report' : 'Execution Report'}
                ]
            },
            {
                key: 'offpage_seo',
                label: isRo ? 'Off Page SEO' : 'Off Page SEO',
                steps: [
                    {key: 'offpage_gbp', label: isRo ? 'Google Business Profile' : 'Google Business Profile'},
                    {key: 'offpage_gbp_social', label: isRo ? 'Calendar social' : 'Social calendar'},
                    {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 AYSA' : 'AYSA link exchange'},
                    {key: 'offpage_publishers', label: isRo ? 'Articole publisher' : 'Publisher articles'},
                    {key: 'offpage_execution_report', label: isRo ? 'Raport execuție' : 'Execution report'}
                ]
            },
            {
                key: 'monitoring',
                label: isRo ? 'Monitorizare' : 'Monitoring',
                steps: [
                    {key: 'monitoring_rank', label: isRo ? 'Poziții în Google' : 'Google positions'},
                    {key: 'monitoring_ai', label: isRo ? 'Vizibilitate în AI' : 'AI visibility'},
                    {key: 'monitoring_opportunities', label: isRo ? 'Oportunități' : 'Opportunities'},
                    {key: 'monitoring_history', label: isRo ? 'Istoric și alerte' : 'History and alerts'},
                    {key: 'continuous_optimization', label: isRo ? 'Optimizare continuă' : 'Continuous optimization'}
                ]
            }
        ];
    }

    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 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 = {
            pre_activation: 0,
            activation_key_requested: 0,
            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 (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: 11,
            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: 32,
            monitoring_ready: 32,
            monitoring_review: 32,
            monitoring_active: 32,
            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 (/_(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 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 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>Lipsește / incert</span><strong>' + escapeHtml(missing.slice(0, 8).join(', ')) + '</strong></div>' : '';
        const warningsHtml = warnings.length ? '<div class="aysa-agent8v3-guidance-review-note"><span>Observații</span><strong>' + escapeHtml(warnings.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>' +
            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;
        if (!dialogue) {
            return '';
        }
        const details = Array.isArray(dialogue.details) ? dialogue.details : [];
        const missing = Array.isArray(dialogue.missing) ? dialogue.missing : [];
        const body = [
            dialogue.summary || '',
            details.join(' '),
            missing.length ? 'Mai am nevoie punctual de: ' + missing.slice(0, 6).join(', ') + '.' : '',
            dialogue.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 (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 authenticated = activationVerified(canonical);
        $('.aysa-agent8v3-auth-pill')
            .toggleClass('is-authenticated', authenticated)
            .toggleClass('is-unauthenticated', !authenticated)
            .text(authenticated ? text('authenticated') : text('unauthenticated'));
    }

    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 nextGuidance = projection && projection.guidance ? projection.guidance : null;
        const nextGuidanceIdentity = guidanceIdentity(nextGuidance);
        const sameGuidance = nextGuidanceIdentity && nextGuidanceIdentity === state.guidanceIdentity;
        state.guidance = nextGuidance;
        state.guidanceIdentity = nextGuidanceIdentity;
        state.guidanceCollapsed = sameGuidance ? state.guidanceCollapsed : !!(state.guidance && state.guidance.collapsible);
        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;
        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);

        $('#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();
        maybeAutoStartKeywordResearch(data || {});
        syncKeywordResearchAutoRefresh();
        syncTechnicalSeoAutoRefresh();
        syncOnPageSeoAutoRefresh();

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

    function renderPayload(payload, options) {
        const context = applyPayloadContext(payload, options || {});
        const projection = context.projection || {};
        const debug = context.debug || {};
        const silent = !!(options && options.silent);
        const allowTranscriptHydrate = !!(options && options.allowTranscriptHydrate);

        if (!silent && allowTranscriptHydrate && Array.isArray(projection.transcript) && projection.transcript.length) {
            hydrateTranscript(projection.transcript);
        } 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 (debug.rag && context.showRag) {
            addRagContextCard(debug.rag);
        }
    }

    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 guidanceHtml = '';
        const dialogueHtml = guidanceDialogueMessageHtml(state.guidance);
        replaceLiveBlock(container, '.aysa-agent8v3-guidance-message', guidanceHtml, '.aysa-agent8v3-guidance-dialogue-message');
        replaceLiveBlock(container, '.aysa-agent8v3-guidance-dialogue-message', dialogueHtml, '');
        renderActions(state.canonical || {}, {});
    }

    function replaceLiveBlock(container, selector, html, beforeSelector) {
        const existing = container.children(selector).last();
        if (!html) {
            existing.remove();
            return;
        }
        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
                        ? 'Auditul Technical SEO este gata. Am grupat rezultatele pe priorități, ca să nu fie nevoie să intri în fiecare detaliu tehnic. Uită-te întâi la recomandările critice și importante. Poți respinge ce nu vrei să păstrăm. După ce finalizezi review-ul, trecem la On Page SEO.'
                        : 'The Technical SEO audit is ready. I grouped results by priority so you do not have to read every technical detail first. Start with critical and important recommendations. You can reject anything you do not want to keep. After you complete the review, we continue to On Page SEO.')
                : (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) {
        state.messages = transcript.map(function(item) {
            const body = String(item.message || '').trim();
            if (/^(State-ul canonic Agent8 V3 a fost încărcat\.|Agent8 V3 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';
            return {
                role: role,
                body: body,
                guidance: 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 !== '';
        });
        renderMessages();
    }

    function renderActions(canonical, projection) {
        const pending = canonical.pending_approval;
        let html = offpageExecutionHtml(state.offpageExecution);
        html += phaseGuidanceCardHtml(state.guidance, state.externalAction, state.guidanceCollapsed);
        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 && 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));
    }

    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.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 || 'completed';
        const action = execution.action_key || 'offpage_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 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 (isChatRequest) {
                    removeThinkingMessage();
                    state.pendingChat = null;
                }
                const message = apiErrorMessage(response, 'Agent8 V3 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, {
                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 V3 request failed.';
    }

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

    function rawAjax(action, data, options) {
        return $.ajax($.extend({
            url: cfg.ajax_url,
            method: 'POST',
            dataType: 'json',
            data: $.extend({
                action: action,
                nonce: cfg.nonce
            }, data || {})
        }, options || {}));
    }

    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.clearInterval(state.monitoringRefreshTimer);
            state.monitoringRefreshTimer = null;
        }
        state.monitoringRefreshTicks = 0;
    }

    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();
        state.monitoringRefreshTimer = window.setInterval(function() {
            state.monitoringRefreshTicks += 1;
            if (state.modal.key === 'monitoring') {
                loadModal();
                if (!monitoringModalHasRunningRefresh(state.modal.current || {}) || state.monitoringRefreshTicks >= 60) {
                    stopMonitoringRefreshPolling();
                }
            } else {
                stopMonitoringRefreshPolling();
            }
        }, 6000);
    }

    function openModal(modalKey, trigger) {
        state.modal.key = String(modalKey || '');
        state.modal.page = 1;
        state.modal.filters = state.modal.key === 'technical_internal_linking' ? { tab: 'link_plan' } : {};
        state.modal.lastTrigger = trigger || 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 closeModal() {
        $('#aysa-agent8v3-modal').prop('hidden', true).attr('aria-hidden', 'true');
        state.modal.key = '';
        if (state.modal.lastTrigger && typeof state.modal.lastTrigger.focus === 'function') {
            state.modal.lastTrigger.focus();
        }
    }

    function loadModal(retriedAfterStale) {
        if (!state.modal.key) {
            return;
        }
        const modalTimeout = ['keyword_mapping', 'research_keywords', 'content_plan', 'technical_sitemap_robots'].indexOf(String(state.modal.key || '')) !== -1 ? 30000 : 10000;
        setModalLoading();
        rawAjax('aysa_agent8v3_modal', {
            modal_key: state.modal.key,
            state_version: 0,
            page: state.modal.page,
            per_page: state.modal.perPage,
            filters: JSON.stringify(state.modal.filters || {})
        }, { timeout: modalTimeout }).done(function(response) {
            if (!response || !response.success || !response.data || !response.data.modal) {
                if (isStaleStateResponse(response) && !retriedAfterStale) {
                    rawAjax('aysa_agent8v3_state', {}).done(function(stateResponse) {
                        if (stateResponse && stateResponse.success) {
                            renderPayload(stateResponse, {
                                silent: true
                            });
                            loadModal(true);
                        } else {
                            renderModalError('stale_state_version');
                        }
                    }).fail(function() {
                        renderModalError('stale_state_version');
                    });
                    return;
                }
                renderModalError(apiErrorMessage(response, 'Modal request failed.'));
                return;
            }
            renderModal(response.data.modal);
        }).fail(function(xhr, statusText) {
            renderModalError(statusText === 'timeout'
                ? 'modal_timeout'
                : apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Request failed: HTTP ' + xhr.status));
        });
    }

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

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

    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]) : (label || key || '');
    }

    function modalDisplayValue(value, key) {
        const raw = String(value || '');
        if (String(key || '') === 'status' || String(key || '') === 'execution_status') {
            return modalLabel(raw, raw);
        }
        return raw;
    }

    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ă review manual' : 'manual review needed',
            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 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 count = parseInt(payload.confirmation_count || 0, 10) || 0;
        const examples = Array.isArray(payload.confirmation_examples) ? payload.confirmation_examples.slice(0, 5) : [];
        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;
        }
        payload.user_confirmed = true;
        payload.confirmed_by_user = 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 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';
        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 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 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') {
	                    item.accepted_by_user = true;
	                    items.push(item);
	                }
	            } catch (error) {
	                // Ignore malformed row payloads; the API validates selected_items again.
	            }
	        });
	        return items;
	    }

	    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_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 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') {
	                    item.accepted_by_user = true;
	                    items.push(item);
	                }
	            } catch (error) {
	                // The API validates selected_items again; malformed row payloads are ignored here.
	            }
	        });
	        return items;
	    }

	    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 lines = [];
	        lines.push(ro ? 'Inserăm linkurile interne selectate?' : 'Insert selected internal links?');
	        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 linkurile inserate și verificate prin readback. Failed/skipped/no-change nu se debitează.'
	            : 'Only inserted links verified by readback are charged. Failed/skipped/no-change 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;
	        }
	        payload.selected_items = selected;
	        payload.accepted_fixes = 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 confirmTechnicalSitemapAuthorityApplyAndMark(payload) {
	        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 (!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;
	        return true;
	    }

	    function confirmTechnicalReviewCompleteWithWarningsAndMark(payload) {
        payload = payload && typeof payload === 'object' ? payload : {};
        if (payload.confirmation_kind !== 'technical_review_complete_with_warnings') {
            return true;
        }
        if (!window.confirm(text('technicalReviewWarningConfirm'))) {
            return false;
        }
        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 setModalLoading() {
        $('#aysa-agent8v3-modal-title').text(text('modalLoading'));
        $('#aysa-agent8v3-modal-subtitle').text('');
        $('#aysa-agent8v3-modal-summary').empty();
        $('.aysa-agent8v3-modal-tabs').remove();
        $('#aysa-agent8v3-modal-body').html('<div class="aysa-agent8v3-modal-empty">' + escapeHtml(text('modalLoadingData')) + '</div>');
        $('#aysa-agent8v3-modal-actions').empty();
        $('#aysa-agent8v3-modal-page').text('-');
        $('#aysa-agent8v3-modal-prev, #aysa-agent8v3-modal-next').prop('disabled', true);
    }

    function renderModalError(message) {
        message = modalFriendlyErrorMessage(message);
        $('#aysa-agent8v3-modal-title').text(text('modalUnavailable'));
        $('#aysa-agent8v3-modal-subtitle').text('');
        $('#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('-');
        $('#aysa-agent8v3-modal-prev, #aysa-agent8v3-modal-next').prop('disabled', true);
    }

    function modalFriendlyErrorMessage(message) {
        const raw = String(message || 'Unknown error');
        if (raw.indexOf('413') !== -1 || raw.toLowerCase().indexOf('request entity too large') !== -1) {
            return 'Review data is too large for one request. Try a specific tab or filter; AYSA will load a compact review payload.';
        }
        if (raw === 'modal_timeout' || raw.toLowerCase().indexOf('timeout') !== -1) {
            return 'Review-ul se încarcă greu. Încearcă un tab specific sau reîmprospătează datele On Page.';
        }
        return raw;
    }

    function renderModal(modal) {
        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 : [];
        state.modal.current = modal;
        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));
        $('#aysa-agent8v3-modal-summary').html(summary.map(function(item) {
            return '<div><span>' + escapeHtml(modalLabel(item.label || '', item.key || '')) + '</span><strong>' + escapeHtml(modalDisplayValue(item.value || '-', item.key || '')) + '</strong></div>';
        }).join(''));
        renderModalTabs(modal);
        const reviewableModals = ['research_keywords', 'keyword_mapping', '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 reviewFilter = modal.review_filter === undefined
            ? reviewableModals.includes(String(modal.modal_key || ''))
            : !!modal.review_filter;
        const hideFilters = !!modal.hide_filters;
        $('.aysa-agent8v3-modal-toolbar').toggle(!hideFilters);
        $('#aysa-agent8v3-modal-search').toggle(!hideFilters);
        $('#aysa-agent8v3-modal-status').toggle(!hideFilters && reviewFilter);
        const searchPlaceholder = (String(modal.modal_key || '') === 'offpage_seo' && modal.advanced_tabs_visible)
            ? text('modalSearchDetails')
            : text('modalSearch');
        $('#aysa-agent8v3-modal-search').attr('placeholder', searchPlaceholder);
        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';
        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(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(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(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-actions').html(renderModalActions(actions, modal));
        const hint = renderModalHint(modal);
        if (!rows.length) {
            $('#aysa-agent8v3-modal-body').html(hint + '<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(hint + renderOffPageGbpSocialCards(rows));
        } else if (String(modal.modal_key || '') === 'offpage_seo' && String(modal.display_mode || '') === 'backlink_audit_cards') {
            $('#aysa-agent8v3-modal-body').html(hint + renderOffPageBacklinkAuditCards(rows, modal));
        } else if (String(modal.modal_key || '') === 'offpage_seo' && String(modal.display_mode || '') === 'offpage_agent_overview') {
            $('#aysa-agent8v3-modal-body').html(hint + renderOffPageAgentOverviewCards(rows, modal));
        } else if (String(modal.modal_key || '') === 'onpage_seo' && String(modal.display_mode || '') === 'onpage_agent_overview') {
            $('#aysa-agent8v3-modal-body').html(hint + 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(hint + renderOnPageContentCards(rows, 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(hint + '<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();
        }
        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;
        $('#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 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 billingIdentity = model.billingIdentity && typeof model.billingIdentity === 'object' ? model.billingIdentity : {};
        const billingIdentityHealth = model.billingIdentityHealth && typeof model.billingIdentityHealth === 'object' ? model.billingIdentityHealth : {};
        const walletSnapshot = model.walletSnapshot && typeof model.walletSnapshot === 'object' ? model.walletSnapshot : {};
        const productGates = model.productGates && typeof model.productGates === 'object' ? model.productGates : {};
        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 enabled = !!testMode.enabled;
        const expiresAt = testMode.expires_at ? new Date(parseInt(testMode.expires_at, 10) * 1000).toLocaleString() : '-';
        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 identityPresent = !!(billingIdentity.remote_identity_present || billingIdentityHealth.remote_identity_present);
        const identityHtml = renderImageAltBillingIdentity(billingIdentity, walletSnapshot, billingUnit, maxCost, billingIdentityHealth);
        const gatesHtml = renderImageAltProductGates(productGates, identityPresent);
        const topupHtml = renderImageAltTestTopup(model.topup);
        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 ? 'Image Alt normal apply readiness' : 'Image Alt normal apply readiness') + '</strong><p>' + escapeHtml(ro
                    ? ('Aplicarea normală pornește doar din rândurile acceptate și confirmate. Modifică doar textul alt al imaginilor selectate. Se debitează ' + billingUnit + ' credite pentru fiecare imagine verificată și schimbată.')
                    : ('Normal apply starts only from accepted and confirmed rows. It changes only selected image alt text. Bills ' + billingUnit + ' credits for each verified changed image.')) + '</p></div>' +
                '<span>' + escapeHtml(siteHost) + '</span>' +
            '</div>' +
            '<div class="aysa-agent8v3-image-alt-test-facts">' +
                '<span>' + escapeHtml(ro ? 'Image Alt only' : 'Image Alt only') + '</span>' +
                '<span>' + escapeHtml(ro ? 'Doar Image Alt' : 'Image Alt only') + '</span>' +
                '<span>' + escapeHtml((ro ? 'Debit real: ' : 'Real billing: ') + billingUnit + '/imagine verificată') + '</span>' +
                '<span>' + escapeHtml(productGates.normal_flow_enabled ? (ro ? 'Normal flow ON' : 'Normal flow ON') : (ro ? 'Normal flow OFF' : 'Normal flow OFF')) + '</span>' +
                '<span>' + escapeHtml(enabled ? ((ro ? 'Test activ până la ' : 'Test active until ') + expiresAt) : (ro ? 'Test mode OFF' : 'Test mode OFF')) + '</span>' +
            '</div>' +
            identityHtml + gatesHtml +
            '<div class="aysa-agent8v3-image-alt-test-actions"><span class="aysa-agent8v3-image-alt-test-muted">' + escapeHtml(ro ? 'Aplicarea normală se face din butonul principal al modalului, după selectarea/acceptarea rândurilor.' : 'Normal apply runs from the main modal button after rows are selected/accepted.') + '</span></div>' +
            message + topupHtml + resultHtml + historyHtml +
        '</section>';
    }

    function renderImageAltProductGates(gates, identityPresent) {
        gates = gates && typeof gates === 'object' ? gates : {};
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const projectOn = !!gates.project_gate_enabled;
        const siteOn = !!gates.site_gate_enabled;
        const kill = !!gates.global_kill_switch_active;
        const ready = !!identityPresent && projectOn && siteOn && !kill;
        return '<div class="aysa-agent8v3-image-alt-test-identity' + (ready ? '' : ' is-blocked') + '">' +
            '<div><strong>' + escapeHtml(ready ? (ro ? 'Normal flow pregătit' : 'Normal flow ready') : (ro ? 'Normal flow blocat' : 'Normal flow blocked')) + '</strong>' +
                '<p>' + escapeHtml(ro ? 'Gate-urile sunt administrabile și default OFF. Kill switch-ul global blochează orice write chiar dacă gate-urile sunt ON.' : 'Gates are admin-controlled and default OFF. The global kill switch blocks writes even when gates are ON.') + '</p></div>' +
            '<dl>' +
                '<div><dt>Project gate</dt><dd>' + escapeHtml(projectOn ? 'ON' : 'OFF') + '</dd></div>' +
                '<div><dt>Site gate</dt><dd>' + escapeHtml(siteOn ? 'ON' : 'OFF') + '</dd></div>' +
                '<div><dt>Global kill switch</dt><dd>' + escapeHtml(kill ? 'ON' : 'OFF') + '</dd></div>' +
                '<div><dt>Readiness</dt><dd>' + escapeHtml(ready ? 'ready' : 'blocked') + '</dd></div>' +
            '</dl>' +
            '<div class="aysa-agent8v3-image-alt-test-actions">' +
                '<button type="button" class="button aysa-agent8v3-image-alt-gates-set" data-project-gate="1" data-site-gate="1"' + (kill ? ' disabled' : '') + '>' + escapeHtml(ro ? 'Activează Image Alt normal flow' : 'Enable Image Alt normal flow') + '</button>' +
                '<button type="button" class="button aysa-agent8v3-image-alt-gates-set" data-project-gate="0" data-site-gate="0">' + escapeHtml(ro ? 'Dezactivează Image Alt normal flow' : 'Disable Image Alt normal flow') + '</button>' +
            '</div>' +
        '</div>';
    }

    function renderImageAltBillingIdentity(identity, wallet, unitCost, maxCost, health) {
        identity = identity && typeof identity === 'object' ? identity : {};
        wallet = wallet && typeof wallet === 'object' ? wallet : {};
        health = health && typeof health === 'object' ? health : {};
        const ro = String(uiLanguage() || '').indexOf('ro') === 0;
        const projectId = parseInt(identity.project_id || health.project_id || wallet.project_id || 0, 10) || 0;
        const websiteId = parseInt(identity.website_id || health.website_id || 0, 10) || 0;
        const userId = parseInt(identity.aysa_user_id || health.aysa_user_id || 0, 10) || 0;
        const balance = parseInt(wallet.balance_cents || 0, 10) || 0;
        const spendable = parseInt(wallet.spendable_cents || health.spendable_credits || 0, 10) || 0;
        const reserved = parseInt(wallet.reserved_links_cents || 0, 10) || 0;
        const present = !!(identity.remote_identity_present || health.remote_identity_present);
        const diagnostic = String(health.diagnostic_code || identity.diagnostic_code || (present ? 'identity_present' : 'identity_missing'));
        const source = String(health.identity_source || identity.identity_source || identity.source || '-');
        const domain = String(health.normalized_domain || '');
        const authDomain = String(health.auth_domain || identity.auth_domain || '');
        const wpUserId = parseInt(health.current_wp_user_id || 0, 10) || 0;
        const authRowPresent = !!health.current_wp_user_auth_row_present;
        const optionPresent = !!health.option_aysa_user_id_present;
        const walletAvailable = !!health.wallet_snapshot_available || !!wallet.available;
        const status = present
            ? (ro ? 'Identitate AYSA confirmată' : 'AYSA billing identity confirmed')
            : (ro ? 'Identitatea AYSA lipsește - write blocat' : 'AYSA billing identity missing - write blocked');
        const repairButton = present ? '' : '<button type="button" class="button aysa-agent8v3-image-alt-identity-repair">' + escapeHtml(ro ? 'Repară identitatea AYSA' : 'Repair AYSA identity') + '</button>';
        return '<div class="aysa-agent8v3-image-alt-test-identity' + (present ? '' : ' is-blocked') + '">' +
            '<div><strong>' + escapeHtml(status) + '</strong>' +
                '<p>' + escapeHtml(ro
                    ? 'Identitatea AYSA este obligatorie înainte de orice Image Alt apply plătit. Nu folosim emailul administratorului WordPress ca identitate de billing.'
                    : 'AYSA billing identity is required before paid Image Alt apply. WordPress admin email is not used as billing identity.') + '</p>' + repairButton + '</div>' +
            '<dl>' +
                '<div><dt>AYSA project</dt><dd>' + escapeHtml(projectId ? String(projectId) : '-') + '</dd></div>' +
                '<div><dt>Website</dt><dd>' + escapeHtml(websiteId ? String(websiteId) : '-') + '</dd></div>' +
                '<div><dt>AYSA account</dt><dd>' + escapeHtml(userId ? String(userId) : '-') + '</dd></div>' +
                '<div><dt>WP user</dt><dd>' + escapeHtml(wpUserId ? String(wpUserId) : '-') + '</dd></div>' +
                '<div><dt>' + escapeHtml(ro ? 'Sold' : 'Balance') + '</dt><dd>' + escapeHtml(String(balance)) + '</dd></div>' +
                '<div><dt>' + escapeHtml(ro ? 'Disponibil' : 'Available') + '</dt><dd>' + escapeHtml(String(spendable)) + '</dd></div>' +
                '<div><dt>' + escapeHtml(ro ? 'Rezervat linkuri' : 'Reserved links') + '</dt><dd>' + escapeHtml(String(reserved)) + '</dd></div>' +
                '<div><dt>' + escapeHtml(ro ? 'Cost maxim' : 'Max cost') + '</dt><dd>' + escapeHtml(String(maxCost || 0)) + '</dd></div>' +
                '<div><dt>Domain</dt><dd>' + escapeHtml(domain || '-') + '</dd></div>' +
                '<div><dt>Auth domain</dt><dd>' + escapeHtml(authDomain || '-') + '</dd></div>' +
                '<div><dt>Auth row</dt><dd>' + escapeHtml(authRowPresent ? 'present' : 'missing') + '</dd></div>' +
                '<div><dt>Option id</dt><dd>' + escapeHtml(optionPresent ? 'present' : 'missing') + '</dd></div>' +
                '<div><dt>Wallet</dt><dd>' + escapeHtml(walletAvailable ? 'available' : 'missing') + '</dd></div>' +
                '<div><dt>Source</dt><dd>' + escapeHtml(source || '-') + '</dd></div>' +
                '<div><dt>Diagnostic</dt><dd>' + escapeHtml(diagnostic || '-') + '</dd></div>' +
            '</dl>' +
            '<p class="aysa-agent8v3-image-alt-test-identity-note">' + escapeHtml((ro ? 'Cost: ' : 'Cost: ') + String(unitCost || 5) + (ro ? ' credite pentru fiecare imagine schimbată și verificată. Skipped/no-change/failed nu se debitează. Nu modificăm redirects, schema, sitemap, robots sau conținut.' : ' credits for each changed and verified image. Skipped/no-change/failed items are not charged. No redirects, schema, sitemap, robots or content are changed.')) + '</p>' +
        '</div>';
    }

    function renderImageAltTestTopup(topup) {
        if (!topup || typeof topup !== 'object') {
            return '';
        }
        const order = topup.topup_order && typeof topup.topup_order === 'object' ? topup.topup_order : {};
        const link = String(order.payment_link || order.checkout_url || '').trim();
        const amount = parseInt(order.amount_cents || topup.suggested_topup_cents || 0, 10) || 0;
        const amountLabel = amount > 0 ? (amount / 100).toFixed(2) + ' EUR' : '-';
        return '<div class="aysa-agent8v3-image-alt-test-topup">' +
            '<strong>Credite insuficiente</strong>' +
            '<span>Disponibil: ' + escapeHtml(String(topup.spendable_cents || 0)) + ' · necesar: ' + escapeHtml(String(topup.max_cost_cents || 0)) + ' · top-up sugerat: ' + escapeHtml(amountLabel) + '</span>' +
            (link ? '<a class="button button-primary" href="' + escapeHtml(link) + '" target="_blank" rel="noopener noreferrer">Plătește top-up</a>' : '<span>Nu am putut genera linkul de plată: ' + escapeHtml(topup.topup_unavailable_reason || '-') + '</span>') +
        '</div>';
    }

    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 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(row.status || '-') + '<br><small>' + escapeHtml(row.verification_status || '-') + '</small></td>' +
                '<td>' + escapeHtml(String(row.billing_cost_cents || 0)) + '<br><small>' + escapeHtml(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 '<div class="aysa-agent8v3-image-alt-test-history">' +
            '<div 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></div>' +
            (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) +
        '</div>';
    }

    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 (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_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 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 am făcut') + '</span><strong>' + escapeHtml(done) + '</strong></div>' +
                    '<div><span>' + escapeHtml('Necesită atenție') + '</span><strong>' + escapeHtml(attention) + '</strong></div>' +
                    '<div><span>' + escapeHtml('Următorul pas') + '</span><strong>' + escapeHtml(nextStep) + '</strong></div>' +
                '</div>' +
            '</article>';
        }).join('') + '</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 summary = String(row.gbp_summary || '-');
            const scheduled = String(row.scheduled_for || '-');
            const deadline = String(row.review_deadline_at || '-');
            const image = String(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>' +
                    '<div class="aysa-agent8v3-gbp-calendar-copy">' + escapeHtml(summary) + '</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) + '<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 provider = String((modal && modal.provider) || '').trim();
        const generated = String((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 meta = provider || generated
            ? '<div class="aysa-agent8v3-backlink-audit-note">' +
                (provider ? '<span>Source: <strong>' + escapeHtml(provider) + '</strong></span>' : '') +
                (generated ? '<span>Generated: <strong>' + escapeHtml(generated) + '</strong></span>' : '') +
            '</div>'
            : '';
        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 ((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(tab.label || key) + '</button>';
        }).join('') + '</div>';
        $('.aysa-agent8v3-modal-toolbar').before(html);
    }

    function renderModalActions(actions, modal) {
        if (!actions.length) {
            return '';
        }
        actions = filterModalActionsForActiveView(actions, modal || {});
        if (!actions.length) {
            return '';
        }
        return actions.map(function(action) {
            const summary = action.summary || {};
            const technicalFixExecution = isTechnicalFixExecutionAction(action);
            const noExecutablePlan = modalActionRequiresExecutablePlan(action) && !modalActionHasExecutablePlan(action);
            const disabled = action.disabled || !action.action || noExecutablePlan ? ' 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(action.payload || {}));
            const display = normalizeActionDisplay(action.label || text(action.action || '') || action.action || 'Action', action.badges || []);
            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 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: 'Requires approval' },
            { re: /\s*·\s*requires approval/i, badge: 'Requires approval' },
            { re: /\s*\(marketplace lookup,\s*fără comandă\)/i, badge: 'Read-only' },
            { re: /\s*\(marketplace lookup,\s*no order\)/i, badge: 'Read-only' },
            { re: /\s*\(trimite email,\s*fără comandă\)/i, badge: 'Email only' },
            { re: /\s*\(sends email,\s*no order\)/i, badge: 'Email only' },
            { re: /\s*\(poate costa[^)]*\)/i, badge: 'Billable API' },
            { re: /\s*\(May cost[^)]*\)/i, badge: 'Billable API' }
        ];
        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;
        }) };
    }

    function actionBadgesHtml(badges) {
        if (!Array.isArray(badges) || !badges.length) {
            return '';
        }
        return '<span class="aysa-agent8v3-action-badges">' + badges.map(function(badge) {
            const label = 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 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(payload.confirmation_kind || '') === 'internal_linking_apply') {
            const selectable = parseInt(summary.selectable !== undefined ? summary.selectable : 0, 10);
            return Number.isFinite(selectable) && selectable > 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 === '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 disabled = payload.selectable ? '' : ' disabled';
	            return '<label class="aysa-agent8v3-metadata-apply-select">' +
	                '<input type="checkbox" class="aysa-agent8v3-image-optimization-apply-row" data-payload="' + escapeHtml(JSON.stringify(payload)) + '"' + 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 disabled = payload.selectable ? '' : ' disabled';
	            return '<label class="aysa-agent8v3-metadata-apply-select">' +
	                '<input type="checkbox" class="aysa-agent8v3-internal-linking-apply-row" data-payload="' + escapeHtml(JSON.stringify(payload)) + '"' + disabled + '>' +
	                '<span class="screen-reader-text">' + escapeHtml(text('select') || 'Select') + '</span>' +
	                '</label>';
	        }
	        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 = normalizeActionDisplay(label, value.badges || []);
            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(value.payload || {})) + '"' + 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);
        }
        return escapeHtml(value);
    }

    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 '-';
        }
        return '<span class="aysa-agent8v3-modal-reasons" title="' + escapeHtml(raw) + '">' + escapeHtml(raw) + '</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();
        if (!summary && !faq && !jsonld) {
            return '<span class="aysa-agent8v3-muted">-</span>';
        }
        const blocks = [];
        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>' + renderModalLegend(modal);
    }

    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;
            }
            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 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 (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') {
            return actionByOperation.apply || 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 label = status.key === 'ready'
            ? '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';
        }
        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();
        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) {
        const status = String((row && row.automation_status) || '');
        const marker = status === 'a8_automated'
            ? '<span class="aysa-agent8v3-fix-auto-mark" title="' + escapeHtml(text('modalA8AutomatedTitle')) + '">✓</span>'
            : '';
        return '<span class="aysa-agent8v3-fix-name">' + marker + '<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] : '';
        return key ? text(key) : (raw || '-');
    }

    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 '<div class="aysa-agent8v3-modal-legend">' +
                '<span><strong>✓</strong> ' + escapeHtml(text('modalAutomationLegend')) + '</span>' +
                '</div>';
        }
        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>✓ / ×</strong> ' + escapeHtml(text('modalReviewLegend')) + '</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 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(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(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 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) &&
            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;
            rawAjax('aysa_agent8v3_action', {
                agent_action: 'refresh_technical_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 === '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 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()) {
                    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 startImageAltGenerationPolling() {
        stopImageAltGenerationPolling();
        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();
                    }
                } 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 (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 legacyCommit = data && data.legacy_commit ? data.legacy_commit : state.legacyCommit;
        const syncedSetup = 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;
        if (!syncedSetup || state.keywordResearchAutoStarted || canonical.phase !== 'research_handoff_ready' || allowed.indexOf('start_keyword_research_run') === -1) {
            return;
        }
        state.keywordResearchAutoStarted = true;
        rawAjax('aysa_agent8v3_action', {
            agent_action: 'start_keyword_research_run',
            state_version: currentVersion(),
            payload: JSON.stringify({
                _auto_started_after_setup_sync: true
            })
        }).done(function(response) {
            if (response && response.success) {
                renderProgressPayload(response, { preserveScroll: true });
            } else {
                state.keywordResearchAutoStarted = false;
            }
        }).fail(function() {
            state.keywordResearchAutoStarted = false;
        });
    }

    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;
        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 {
                    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') {
                    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 {
                renderModalError(apiErrorMessage(response, 'Action failed.'));
            }
        }).fail(function(xhr) {
            renderModalError(apiErrorMessage(xhr && xhr.responseJSON ? xhr.responseJSON : null, 'Request failed: HTTP ' + xhr.status));
        }).always(function() {
            if (!retryingAfterStale) {
                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();

        $('#aysa-agent8v3-send').on('click', function() {
            const input = $('#aysa-agent8v3-input');
            const message = String(input.val() || '').trim();
            if (!message) {
                return;
            }
            input.val('');
            addMessage('user', shouldMaskComposerMessage(message) ? '[secret key hidden]' : message);
            request('aysa_agent8v3_message', {
                message: message,
                state_version: currentVersion()
            });
        });

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

        $('#aysa-agent8v3-input').on('input', function() {
            if (state.guidance && state.guidance.collapsible && String($(this).val() || '').trim() !== '' && !state.guidanceCollapsed) {
                state.guidanceCollapsed = true;
                renderActions(state.canonical || {}, {});
            }
        });

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

        $(document).on('click', '.aysa-agent8v3-modal-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();
        });

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

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

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

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

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

        $(document).on('click', '.aysa-agent8v3-modal-tab', function() {
            const nextTab = String($(this).data('tab') || '');
            state.modal.page = 1;
            const filters = currentModalFiltersFromControls();
            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';
                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-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 confirmMessage = 'Confirmi restaurarea Image Alt pentru attachment ' + attachmentId + '? Restore modifică doar _wp_attachment_image_alt la valoarea veche salvată ș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('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 === 'execute_onpage_plan') {
                const confirmMessage = state.language === 'Romanian'
                    ? 'Aplicăm selecția confirmată în WordPress. Continuă doar dacă ai verificat recomandările On Page.'
                    : 'Apply the confirmed selection in WordPress. Continue only if you reviewed the On Page recommendations.';
                if (!window.confirm(confirmMessage)) {
                    return;
                }
                payload.confirmed_by_user = true;
            }
            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_image_alt_apply') {
                if (!confirmTechnicalImageAltApplyAndMark(payload)) {
                    return;
                }
            }
            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_metadata_apply') {
                if (!confirmTechnicalMetadataApplyAndMark(payload)) {
                    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_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)) {
	                    return;
	                }
	            }
	            if (agentAction === 'complete_technical_seo_review') {
                if (!confirmTechnicalReviewCompleteWithWarningsAndMark(payload)) {
                    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 === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_image_alt_apply') {
                if (!confirmTechnicalImageAltApplyAndMark(payload)) {
                    return;
                }
            }
            if (agentAction === 'execute_technical_fix_plan' && payload.confirmation_kind === 'technical_metadata_apply') {
                if (!confirmTechnicalMetadataApplyAndMark(payload)) {
                    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_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)) {
	                    return;
	                }
	            }
	            if (agentAction === 'complete_technical_seo_review') {
                if (!confirmTechnicalReviewCompleteWithWarningsAndMark(payload)) {
                    return;
                }
            }
            runModalAgentAction(agentAction, payload, button, false);
        });

        $(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-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('keydown', function(event) {
            if (event.key === 'Escape' && !$('#aysa-agent8v3-modal').prop('hidden')) {
                closeModal();
            }
        });

        $('.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);
            request('aysa_agent8v3_action', {
                agent_action: 'set_language',
                state_version: currentVersion(),
                payload: JSON.stringify({ language: language })
            });
        });

        $(document).on('click', '.aysa-agent8v3-action', function() {
            const agentAction = String($(this).data('action') || '');
            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 === 'complete_technical_seo_review') {
                if (!confirmTechnicalReviewCompleteWithWarningsAndMark(payload)) {
                    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-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();
            }
        });
    });
})(jQuery);
