(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,
        guidanceCollapsed: false,
        externalAction: null,
        billing: null,
        walletSnapshot: null,
        legacyCommit: null,
        languageFallbacks: [],
        businessProfileTimer: null,
        businessProfileRefreshing: false,
        competitionKeywordTimer: null,
        competitionKeywordRefreshing: false,
        keywordResearchTimer: null,
        keywordResearchRefreshing: false,
        keywordResearchAutoStarted: false,
        technicalSeoTimer: null,
        technicalSeoRefreshing: false,
        technicalFixExecutionTimer: null,
        technicalFixExecutionRefreshing: false,
        technicalFixExecutionModule: '',
        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];
        });
    }

    const I18N = {
        en: {
            title: 'AYSA Agent 8 V3 Lab', subtitle: 'Deterministic execution system', active: 'Active', conversation: 'Conversation',
            execution: 'Agent8 V3 Execution', waiting: 'waiting for state', 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 the chat history?', fullResetDone: 'Agent8 V3 Lab was reset.',
            integrationStressConfirm: 'Run the real integration stress test? This can start workers 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 billable action', billingStatus: 'Status', plan: 'Plan', legacySync: 'Legacy sync',
            idle: 'Idle', approvalRequired: 'Approval Required', approve: 'Approve', reject: 'Reject',
            expand: 'Expand', collapse: 'Collapse',
            writesState: 'writes_state: true', requiresApproval: 'requires_approval: true', billableFalse: 'billable: false',
            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 Technical SEO review', skip_technical_seo: 'skip Technical SEO', planning: 'Planning', executing: 'Executing', completed: 'completed', completed_with_warnings: 'completed with warnings',
            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...', 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 execute this fix after Save & Execute.', 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 executed by AYSA after Save & Execute', 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: 'Save & Execute', 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 needed', execution_status: 'Execution', not_executable_yet: 'not executable yet', submitted: 'submitted', synced: 'synced', queued: 'queued', skipped: 'skipped', applied: 'applied'
        },
        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ă state', 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?', fullResetDone: 'Agent8 V3 Lab a fost resetat.',
            integrationStressConfirm: 'Rulezi stress testul de integrare reală? Poate porni workeri ș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 billable', billingStatus: 'Status', plan: 'Plan', legacySync: 'Legacy sync',
            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',
            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 Technical SEO', skip_technical_seo: 'sari peste Technical SEO', planning: 'Planificare', executing: 'Execuție', completed: 'finalizat', completed_with_warnings: 'finalizat cu observații',
            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ă...', 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 executa acest fix după Salvează și execută.', 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 executat de AYSA după Salvează și execută', 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: 'Salvează și execută', 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: 'manual necesar', execution_status: 'Execuție', not_executable_yet: 'neexecutabil încă', submitted: 'trimis', synced: 'sincronizat', queued: 'în coadă', skipped: 'sărite', applied: 'aplicate'
        },
        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 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(text('controls'));
        $('.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) {
        if (String(role || '').indexOf('qa') === 0 || role === 'execution') {
            appendQaLiveLine(role, body);
            return;
        }

        state.messages.push({
            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()
        });
        renderMessages();
    }

    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() {
        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">' + escapeHtml(message.body) + '</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">' + escapeHtml(message.body) + '</div>' +
                '</div>' +
            '</div>';
            const guidance = message.guidance && typeof message.guidance === 'object' ? message.guidance : null;
            const guidanceHtml = guidance && shouldRenderTranscriptGuidance(guidance, index, lastGuidanceIndex) ? phaseGuidanceCardHtml(guidance, null, !!guidance.collapsed) : '';
            return assistantHtml + guidanceHtml;
        }).join('');
        const ragHtml = state.ragContexts.map(ragContextHtml).join('');
        const guidanceHtml = phaseGuidanceCardHtml(state.guidance, state.externalAction, state.guidanceCollapsed);
        const html = messageHtml + ragHtml + guidanceHtml;
        $('#aysa-agent8v3-messages').html(html);
        const el = document.getElementById('aysa-agent8v3-messages');
        if (el) {
            el.scrollTop = el.scrollHeight;
        }
    }

    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 phaseGuidanceCardHtml(guidance, externalAction, collapsed) {
        if (!guidance || typeof guidance !== 'object') {
            return '';
        }
        collapsed = !!(collapsed && guidance.collapsible);
        const options = Array.isArray(guidance.options) ? guidance.options : [];
        const externalUrl = externalAction && externalAction.url ? String(externalAction.url) : '';
        const buttons = options.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');
            return '<button type="button" class="button aysa-agent8v3-guidance-option aysa-agent8v3-action is-' + escapeHtml(kind) + '" data-action="' + escapeHtml(action) + '">' +
                escapeHtml(option.label || actionLabel(action)) +
            '</button>';
        }).join('') + (externalUrl ? '<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 hasProgress = guidance.progress && typeof guidance.progress === 'object';
        const hasReview = guidance.review && typeof guidance.review === 'object';
        const hasBody = String(guidance.body || '').trim() !== '';
        if (!buttons && !hasProgress && !hasReview && !hasBody) {
            return '';
        }
        const optionsHtml = buttons ? '<div class="aysa-agent8v3-guidance-options">' + buttons + '</div>' : '';
        return '<div class="aysa-agent8v3-message assistant aysa-agent8v3-guidance-message' + (collapsed ? ' is-collapsed' : '') + '">' +
            '<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>' +
                    (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">' +
                    '<p>' + escapeHtml(guidance.body || '') + '</p>' +
                    guidanceProgressHtml(guidance.progress) +
                    guidanceReviewHtml(guidance.review) +
                    optionsHtml +
                '</div>' +
            '</div>' +
        '</div>';
    }

    function guidanceReviewHtml(review) {
        if (!review || typeof review !== 'object') {
            return '';
        }
        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) {
            return '<div class="aysa-agent8v3-guidance-review-row">' +
                '<span>' + escapeHtml(row.label || '') + '</span>' +
                '<strong>' + escapeHtml(row.value || '-') + '</strong>' +
            '</div>';
        }).join('');
        const detailsHtml = 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 +
            '<p class="aysa-agent8v3-guidance-review-instruction">' + escapeHtml(review.instruction || '') + '</p>' +
        '</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 renderPayload(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);
        const silent = !!(options && options.silent);
        state.canonical = canonical;
        state.lastDebug = debug;
        state.guidance = projection && projection.guidance ? projection.guidance : null;
        state.guidanceCollapsed = !!(state.guidance && state.guidance.collapsed);
        state.externalAction = projection && projection.external_action ? projection.external_action : 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);

        if (!silent && Array.isArray(projection.transcript) && projection.transcript.length) {
            hydrateTranscript(projection.transcript);
        } else if (!silent && projection.assistant_message) {
            addMessage('assistant', projection.assistant_message);
        } else if (silent) {
            renderMessages();
        }
        if (debug.rag && showRag) {
            addRagContextCard(debug.rag);
        }

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

    function hydrateTranscript(transcript) {
        state.messages = transcript.map(function(item) {
            const role = String(item.role || '') === 'user' ? 'user' : 'assistant';
            const payload = item.payload && typeof item.payload === 'object' ? item.payload : {};
            return {
                role: role,
                body: item.message || '',
                guidance: payload.guidance_snapshot && typeof payload.guidance_snapshot === 'object' ? payload.guidance_snapshot : 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.body !== '';
        });
        renderMessages();
    }

    function renderActions(canonical, projection) {
        const pending = canonical.pending_approval;
        let html = '';
        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>';
        }
        $('#aysa-agent8v3-actions').html(html);
        $('.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 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) {
        const workerTaskId = data && isWorkerAction(data.agent_action) ? beginWorkerTask(data.agent_action) : '';
        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 = 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);
                        }
                    });
                }
                if (workerTaskId) {
                    failWorkerTask(workerTaskId, message);
                }
                setStatus('failed');
                return;
            }
            renderPayload(response, {
                showRag: !!(data && data.agent_action === 'run_rag_context_test')
            });
            if (workerTaskId) {
                completeWorkerTask(workerTaskId, response.data || {});
            }
            setStatus('completed');
        }).fail(function(xhr) {
            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 : {};
        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 === '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) {
        return $.ajax({
            url: cfg.ajax_url,
            method: 'POST',
            dataType: 'json',
            data: $.extend({
                action: action,
                nonce: cfg.nonce
            }, data || {})
        });
    }

    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.worker_status || execution.status)) || '').toLowerCase();
        return ['completed', 'failed', 'cancelled', 'canceled', 'synced', 'already_synced'].indexOf(status) !== -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) {
                    renderPayload(response, { silent: 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 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;
        $('#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;
        }
        setModalLoading();
        rawAjax('aysa_agent8v3_modal', {
            modal_key: state.modal.key,
            state_version: currentVersion(),
            page: state.modal.page,
            per_page: state.modal.perPage,
            filters: JSON.stringify(state.modal.filters || {})
        }).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) {
            renderModalError(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',
            manual_needed: 'manual_needed',
            queued: 'queued',
            skipped: 'skipped',
            applied: 'applied',
            failed: 'failed',
            not_executable_yet: 'not_executable_yet',
            submitted: 'submitted',
            synced: 'synced',
            trusted: 'modalTrusted',
            recommended_reject: 'modalRecommendedReject',
            review: 'modalReviewNeeded'
        };
        return labels[key] ? text(labels[key]) : (label || key || '');
    }

    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) {
        $('#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>');
        $('#aysa-agent8v3-modal-actions').empty();
        $('#aysa-agent8v3-modal-page').text('-');
        $('#aysa-agent8v3-modal-prev, #aysa-agent8v3-modal-next').prop('disabled', true);
    }

    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 : [];
        $('#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(item.value || '-') + '</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;
        $('#aysa-agent8v3-modal-status').toggle(reviewFilter);
        $('#aysa-agent8v3-modal-search').attr('placeholder', text('modalSearch'));
        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));
        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 {
            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));
        }
        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;
        $('#aysa-agent8v3-modal-page').text(text('modalPage') + ' ' + page + ' / ' + pages + ' · ' + total + ' ' + text('modalRows'));
        $('#aysa-agent8v3-modal-prev').prop('disabled', page <= 1);
        $('#aysa-agent8v3-modal-next').prop('disabled', page >= pages);
    }

    function renderModalHint(modal) {
        if (String(modal.modal_key || '') !== 'technical_internal_linking') {
            return '';
        }
        const activeTab = String(modal.active_tab || (modal.filters && modal.filters.tab) || '');
        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 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;
        }
        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) {
        if (!actions.length) {
            return '';
        }
        return actions.map(function(action) {
            const summary = action.summary || {};
            const noExecutablePlan = modalActionRequiresExecutablePlan(action) && !modalActionHasExecutablePlan(action);
            const disabled = action.disabled || !action.action || noExecutablePlan ? ' disabled' : '';
            const status = action.status ? '<span class="aysa-agent8v3-modal-action-status">' + escapeHtml(modalLabel(action.status, action.status)) + '</span>' : '';
            const planGuard = noExecutablePlan ? '<span class="aysa-agent8v3-modal-action-status is-warning">' + escapeHtml(text('modalNoExecutableFixes')) + '</span>' : '';
            const counts = ['total', 'accepted', 'rejected', 'filtered', 'included', 'remaining', 'executable', 'manual_needed', 'queued', 'applied', 'skipped', 'failed'].map(function(key) {
                if (summary[key] === undefined) {
                    return '';
                }
                return '<span><strong>' + escapeHtml(String(summary[key])) + '</strong> ' + escapeHtml(modalLabel(key, key)) + '</span>';
            }).join('');
            const payload = escapeHtml(JSON.stringify(action.payload || {}));
            return '<div class="aysa-agent8v3-modal-actionbar">' +
                '<div class="aysa-agent8v3-modal-action-summary">' + counts + status + planGuard + '</div>' +
                '<button type="button" class="button button-primary aysa-agent8v3-modal-action" data-action="' + escapeHtml(action.action || '') + '" data-payload="' + payload + '"' + disabled + '>' + escapeHtml(action.label || text(action.action || '') || action.action || 'Action') + '</button>' +
                '</div>';
        }).join('');
    }

    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 executable = parseInt(summary.executable !== undefined ? summary.executable : 0, 10);
        return Number.isFinite(executable) && executable > 0;
    }

    function renderModalCell(row, column, key) {
        const value = row && row[key] !== undefined ? row[key] : '';
        if (column && column.type === 'action' && value && typeof value === 'object') {
            const disabled = value.disabled || !value.action ? ' disabled' : '';
            const label = value.label || text(value.action || '') || value.action || 'Action';
            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 '<button type="button" class="button aysa-agent8v3-modal-row-action" data-action="' + escapeHtml(value.action || '') + '" data-payload="' + escapeHtml(JSON.stringify(value.payload || {})) + '"' + disabled + '>' + escapeHtml(label) + '</button>';
        }
        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 (key === 'source_url' || key === 'target_url' || key === 'url' || key === 'canonical' || key === 'download_url' || key === 'image_url' || key === 'page_url') {
            return renderModalUrl(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') {
            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 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 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';
        }
        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',
                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', '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) {
                    renderPayload(response);
                }
            }).always(function() {
                state.businessProfileRefreshing = false;
            });
        }, 8000);
    }

    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) {
                    renderPayload(response, {
                        silent: true
                    });
                } else if (response && response.data && response.data.error === 'stale_state_version') {
                    rawAjax('aysa_agent8v3_state', {}).done(function(stateResponse) {
                        if (stateResponse && stateResponse.success) {
                            renderPayload(stateResponse, {
                                silent: 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) {
                    renderPayload(response, {
                        silent: true
                    });
                } else if (response && response.data && response.data.error === 'stale_state_version') {
                    rawAjax('aysa_agent8v3_state', {}).done(function(stateResponse) {
                        if (stateResponse && stateResponse.success) {
                            renderPayload(stateResponse, {
                                silent: 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) {
                    renderPayload(response, {
                        silent: 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) {
                            renderPayload(stateResponse, {
                                silent: 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 hasRun = !!(onpage.run_ids && Object.keys(onpage.run_ids).length);
        return ['onpage_seo_running', 'onpage_seo_review'].indexOf(canonical.phase) !== -1 &&
            !canonical.pending_approval &&
            hasRun &&
            ['queued', 'running'].indexOf(status) !== -1 &&
            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);
    }

    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) {
                renderPayload(response, {
                    silent: true
                });
                if (state.modal && state.modal.key === 'onpage_seo') {
                    loadModal();
                }
            } else if (isStaleStateResponse(response) && !retriedAfterStale) {
                rawAjax('aysa_agent8v3_state', {}).done(function(stateResponse) {
                    if (stateResponse && stateResponse.success) {
                        renderPayload(stateResponse, {
                            silent: 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) {
                    renderPayload(response, { silent: 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) {
                            renderPayload(stateResponse, { silent: 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) {
                renderPayload(response);
            } 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 || 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 });
                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 (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() {
        $('#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', 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;
                renderMessages();
            }
        });

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

        $(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);

        $('#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();
            filters.tab = nextTab;
            if (state.modal.key === 'technical_internal_linking' && nextTab !== 'link_plan') {
                filters.status = 'all';
            }
            if (state.modal.key === 'onpage_seo') {
                if (nextTab === 'meta_snippets') {
                    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-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;
            }
            runModalAgentAction(agentAction, payload, 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;
            }
            runModalAgentAction(agentAction, payload, button, false);
        });

        $(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') || '');
            const 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;
            }
            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);
