<?php

if (!defined('ABSPATH')) {
    exit;
}

final class Aysa_AI_Visibility_Module {
    public static function boot() {
        if (!defined('AYSA_AI_VISIBILITY_ENABLED') || !AYSA_AI_VISIBILITY_ENABLED) {
            return;
        }
        $client = new Aysa_AI_Visibility_API_Client();
        (new Aysa_AI_Visibility_Ajax_Controller($client))->register();
        add_action('admin_menu', array(__CLASS__, 'register_menu'), 30);
        add_action('admin_enqueue_scripts', array(__CLASS__, 'enqueue_assets'));
    }

    public static function register_menu() {
        add_submenu_page(
            'aysa',
            aysa_interface_text('Vizibilitate AI', 'AI Visibility'),
            aysa_interface_text('Vizibilitate AI', 'AI Visibility'),
            'manage_options',
            'aysa-ai-visibility',
            array(__CLASS__, 'render')
        );
    }

    public static function enqueue_assets($hook) {
        if (strpos((string) $hook, 'aysa-ai-visibility') === false) {
            return;
        }
        wp_enqueue_style(
            'aysa-ai-visibility',
            AYSA_PLUGIN_URL . 'admin/css/aysa-ai-visibility.css',
            array(),
            AYSA_VERSION
        );
        wp_enqueue_style(
            'aysa-ai-visibility-action-plan',
            AYSA_PLUGIN_URL . 'admin/css/aysa-ai-visibility-action-plan.css',
            array('aysa-ai-visibility'),
            AYSA_VERSION
        );
        wp_enqueue_style(
            'aysa-ai-visibility-impact',
            AYSA_PLUGIN_URL . 'admin/css/aysa-ai-visibility-impact.css',
            array('aysa-ai-visibility'),
            AYSA_VERSION
        );
        wp_enqueue_style(
            'aysa-ai-visibility-signals',
            AYSA_PLUGIN_URL . 'admin/css/aysa-ai-visibility-signals.css',
            array('aysa-ai-visibility'),
            AYSA_VERSION
        );
        wp_enqueue_style(
            'aysa-ai-visibility-run',
            AYSA_PLUGIN_URL . 'admin/css/aysa-ai-visibility-run.css',
            array('aysa-ai-visibility'),
            AYSA_VERSION
        );
        wp_enqueue_style(
            'aysa-ai-visibility-content-analyzer',
            AYSA_PLUGIN_URL . 'admin/css/aysa-ai-visibility-content-analyzer.css',
            array('aysa-ai-visibility'),
            AYSA_VERSION
        );
        wp_enqueue_style(
            'aysa-ai-visibility-commerce',
            AYSA_PLUGIN_URL . 'admin/css/aysa-ai-visibility-commerce.css',
            array('aysa-ai-visibility'),
            AYSA_VERSION
        );
        wp_enqueue_style(
            'aysa-ai-visibility-correlation',
            AYSA_PLUGIN_URL . 'admin/css/aysa-ai-visibility-correlation.css',
            array('aysa-ai-visibility'),
            AYSA_VERSION
        );
        wp_enqueue_style(
            'aysa-ai-visibility-knowledge-base',
            AYSA_PLUGIN_URL . 'admin/css/aysa-ai-visibility-knowledge-base.css',
            array('aysa-ai-visibility'),
            AYSA_VERSION
        );
        wp_enqueue_style(
            'aysa-ai-visibility-product-shell',
            AYSA_PLUGIN_URL . 'admin/css/aysa-ai-visibility-product-shell.css',
            array('aysa-ai-visibility'),
            @filemtime(AYSA_PLUGIN_DIR . 'admin/css/aysa-ai-visibility-product-shell.css') ?: AYSA_VERSION
        );
        wp_enqueue_script(
            'aysa-ai-visibility',
            AYSA_PLUGIN_URL . 'admin/js/aysa-ai-visibility.js',
            array(),
            @filemtime(AYSA_PLUGIN_DIR . 'admin/js/aysa-ai-visibility.js') ?: AYSA_VERSION,
            true
        );
        wp_enqueue_script(
            'aysa-ai-visibility-product-shell',
            AYSA_PLUGIN_URL . 'admin/js/aysa-ai-visibility-product-shell.js',
            array('aysa-ai-visibility'),
            @filemtime(AYSA_PLUGIN_DIR . 'admin/js/aysa-ai-visibility-product-shell.js') ?: AYSA_VERSION,
            true
        );
        wp_enqueue_script(
            'aysa-ai-visibility-commerce',
            AYSA_PLUGIN_URL . 'admin/js/aysa-ai-visibility-commerce.js',
            array('aysa-ai-visibility'),
            AYSA_VERSION,
            true
        );
        wp_enqueue_script(
            'aysa-ai-visibility-correlation',
            AYSA_PLUGIN_URL . 'admin/js/aysa-ai-visibility-correlation.js',
            array('aysa-ai-visibility'),
            AYSA_VERSION,
            true
        );
        wp_enqueue_script(
            'aysa-ai-visibility-knowledge-base',
            AYSA_PLUGIN_URL . 'admin/js/aysa-ai-visibility-knowledge-base.js',
            array('aysa-ai-visibility'),
            AYSA_VERSION,
            true
        );
        $switched_to_english = function_exists('switch_to_locale') && switch_to_locale('en_US');
        $english_strings = array(
                'checkingTitle' => __('Checking configuration…', 'aysaaiseo'),
                'checkingCopy' => __('No providers are run and no credits are used.', 'aysaaiseo'),
                'unavailableTitle' => __('AI Visibility is currently unavailable', 'aysaaiseo'),
                'retry' => __('Retry', 'aysaaiseo'),
                'timeout' => __('The configuration check took too long.', 'aysaaiseo'),
                'failed' => __('The configuration could not be loaded.', 'aysaaiseo'),
                'available' => __('AI Visibility is available', 'aysaaiseo'),
                'notConfigured' => __('AI Visibility is not configured yet', 'aysaaiseo'),
                'temporarilyUnavailable' => __('AI Visibility is temporarily unavailable', 'aysaaiseo'),
                'noRuns' => __('No AI Visibility measurement has been run yet.', 'aysaaiseo'),
                'runInProgress' => __('Measurement in progress', 'aysaaiseo'),
                'runComplete' => __('Latest measurement complete', 'aysaaiseo'),
                'runPartial' => __('Latest measurement completed with partial coverage', 'aysaaiseo'),
                'runFailed' => __('Latest measurement needs attention', 'aysaaiseo'),
                'insufficientData' => __('Insufficient data', 'aysaaiseo'),
                'moreEligibleNeeded' => __('{count} more eligible conversation(s) needed (minimum {minimum}).', 'aysaaiseo'),
                'metricRequirementMissing' => __('An additional metric requirement is not met; review Technical details.', 'aysaaiseo'),
                'additionalMetrics' => __('Additional metrics', 'aysaaiseo'),
                'viewLoading' => __('Loading {module}…', 'aysaaiseo'),
                'viewSlow' => __('{module} is taking longer than expected. You can wait or retry manually if it fails.', 'aysaaiseo'),
                'viewFailed' => __('{module} could not be loaded.', 'aysaaiseo'),
                'moduleLabels' => array(
                    'measurement' => __('New measurement', 'aysaaiseo'),
                    'evidence' => __('Evidence', 'aysaaiseo'),
                    'trends' => __('Trends', 'aysaaiseo'),
                    'signals' => __('Signals', 'aysaaiseo'),
                    'content_analyzer' => __('Content Analyzer', 'aysaaiseo'),
                    'actions' => __('Actions', 'aysaaiseo'),
                    'impact' => __('Impact', 'aysaaiseo'),
                    'setup' => __('Setup', 'aysaaiseo'),
                    'commerce' => __('Commerce', 'aysaaiseo'),
                    'correlation' => __('Source correlation', 'aysaaiseo'),
                    'knowledge_base' => __('Knowledge Base', 'aysaaiseo'),
                ),
                'noEvidence' => __('No conversation evidence is available yet.', 'aysaaiseo'),
                'question' => __('Question', 'aysaaiseo'),
                'answerExcerpt' => __('Answer evidence', 'aysaaiseo'),
                'interpretation' => __('What this means', 'aysaaiseo'),
                'sources' => __('Sources', 'aysaaiseo'),
                'technicalDetails' => __('Technical details', 'aysaaiseo'),
                'evidenceRecommended' => __('The business was explicitly recommended in this answer.', 'aysaaiseo'),
                'evidenceCited' => __('The site was cited, without an explicit recommendation.', 'aysaaiseo'),
                'evidenceMentioned' => __('The business was mentioned, without an explicit recommendation or first-party citation.', 'aysaaiseo'),
                'evidenceNoSignal' => __('No eligible business mention, recommendation or first-party citation was detected.', 'aysaaiseo'),
                'ownershipLabels' => array(
                    'first_party' => __('First-party source', 'aysaaiseo'),
                    'competitor' => __('Competitor source', 'aysaaiseo'),
                    'third_party' => __('Third-party source', 'aysaaiseo'),
                    'unknown' => __('Unclassified source', 'aysaaiseo'),
                ),
                'recommendationLabels' => array(
                    'explicit_best_choice' => __('Explicit recommendation', 'aysaaiseo'),
                    'included_in_recommended_set' => __('Included in the recommended options', 'aysaaiseo'),
                    'mentioned_not_recommended' => __('Mentioned, not recommended', 'aysaaiseo'),
                ),
                'testTypeLabels' => array(
                    'discovery' => __('Discovery', 'aysaaiseo'),
                    'recommendation' => __('Recommendation', 'aysaaiseo'),
                    'comparison' => __('Comparison', 'aysaaiseo'),
                    'fact_check' => __('Fact check', 'aysaaiseo'),
                    'citation' => __('Citation', 'aysaaiseo'),
                    'recommendation_journey' => __('Recommendation journey', 'aysaaiseo'),
                    'brand_perception' => __('Brand perception', 'aysaaiseo'),
                    'competitive_comparison' => __('Competitive comparison', 'aysaaiseo'),
                    'brand_fact_check' => __('Brand fact check', 'aysaaiseo'),
                ),
                'setupChecklist' => __('Setup readiness', 'aysaaiseo'),
                'setupReady' => __('Ready', 'aysaaiseo'),
                'setupNeedsAttention' => __('Needs attention', 'aysaaiseo'),
                'setupRecommended' => __('Recommended', 'aysaaiseo'),
                'profileDraft' => __('Autosaved draft — explicit confirmation is still required.', 'aysaaiseo'),
                'profileConfirmedState' => __('Profile explicitly confirmed.', 'aysaaiseo'),
                'entityQualityHint' => __('Personas improve question realism, competitors enable valid comparisons, and confirmed claims enable factual accuracy checks.', 'aysaaiseo'),
                'setupBrand' => __('Brand profile', 'aysaaiseo'),
                'setupTopics' => __('Confirmed topics', 'aysaaiseo'),
                'setupScenarios' => __('Confirmed scenarios', 'aysaaiseo'),
                'setupCompetitors' => __('Confirmed competitors', 'aysaaiseo'),
                'setupClaims' => __('Confirmed claims', 'aysaaiseo'),
                'setupEngines' => __('Ready engines', 'aysaaiseo'),
                'entityStatusLabels' => array(
                    'confirmed' => __('Confirmed', 'aysaaiseo'),
                    'proposed' => __('Draft', 'aysaaiseo'),
                    'waiting_for_confirmation' => __('Awaiting confirmation', 'aysaaiseo'),
                ),
                'competitorClassLabels' => array(
                    'unconfirmed' => __('Unconfirmed', 'aysaaiseo'),
                    'direct' => __('Direct competitor', 'aysaaiseo'),
                    'indirect' => __('Indirect competitor', 'aysaaiseo'),
                    'marketplace' => __('Marketplace', 'aysaaiseo'),
                    'publisher' => __('Publisher', 'aysaaiseo'),
                    'sub_brand' => __('Sub-brand', 'aysaaiseo'),
                ),
                'commerceMetricLabels' => array(
                    'product_visibility' => __('Product visibility', 'aysaaiseo'),
                    'product_recommendation_rate' => __('Product recommendation rate', 'aysaaiseo'),
                    'product_recommendation_coverage' => __('Product recommendation coverage', 'aysaaiseo'),
                    'product_share_of_voice' => __('Product share of voice', 'aysaaiseo'),
                ),
                'commerceReadinessLabels' => array(
                    'product_schema' => __('Rendered Product schema', 'aysaaiseo'),
                    'offer_schema' => __('Rendered Offer schema', 'aysaaiseo'),
                    'identifiers' => __('Product identifiers', 'aysaaiseo'),
                    'price_consistency' => __('Price consistency', 'aysaaiseo'),
                    'availability_consistency' => __('Availability consistency', 'aysaaiseo'),
                    'crawlability_rendering' => __('Crawlability and rendering', 'aysaaiseo'),
                    'merchant_policies' => __('Merchant policies', 'aysaaiseo'),
                    'shipping_returns' => __('Shipping and returns', 'aysaaiseo'),
                    'product_feed' => __('Product feed', 'aysaaiseo'),
                    'purchase_steps' => __('Purchase steps', 'aysaaiseo'),
                ),
                'readinessStatusLabels' => array(
                    'pass' => __('Ready', 'aysaaiseo'),
                    'partial' => __('Partially ready', 'aysaaiseo'),
                    'missing' => __('Not ready', 'aysaaiseo'),
                ),
                'ucpStatusLabels' => array(
                    'verified_capability_evidence' => __('Capability evidence verified', 'aysaaiseo'),
                    'not_verified' => __('Capability not verified', 'aysaaiseo'),
                ),
                'commerceObservationLabels' => array(
                    'recommended' => __('Recommended', 'aysaaiseo'),
                    'mentioned' => __('Mentioned', 'aysaaiseo'),
                ),
                'commerceInsufficientReasonLabels' => array(
                    'minimum_sample_size_not_met' => __('More eligible product conversations are required.', 'aysaaiseo'),
                    'competitor_set_required' => __('Confirm a competitor product set before calculating product share of voice.', 'aysaaiseo'),
                ),
                'correlationDirectionLabels' => array(
                    'unknown' => __('No comparison yet', 'aysaaiseo'),
                    'increased' => __('Increased', 'aysaaiseo'),
                    'decreased' => __('Decreased', 'aysaaiseo'),
                    'unchanged' => __('Unchanged', 'aysaaiseo'),
                ),
                'correlationMetricLabels' => array(
                    'ai_visibility' => __('AI Visibility', 'aysaaiseo'),
                    'first_party_citations' => __('First-party citations', 'aysaaiseo'),
                    'gsc_impressions' => __('Search Console impressions', 'aysaaiseo'),
                    'gsc_clicks' => __('Search Console clicks', 'aysaaiseo'),
                    'ga_sessions' => __('Analytics sessions', 'aysaaiseo'),
                    'ga_conversions' => __('Analytics conversions', 'aysaaiseo'),
                    'identifiable_ai_referrals' => __('Identifiable AI referral sessions', 'aysaaiseo'),
                    'gbp_visibility' => __('Business Profile visibility', 'aysaaiseo'),
                    'gbp_actions' => __('Business Profile actions', 'aysaaiseo'),
                ),
                'correlationSourceLabels' => array(
                    'ai_visibility' => __('AYSA AI Visibility', 'aysaaiseo'),
                    'first_party_citations' => __('AYSA AI Visibility', 'aysaaiseo'),
                    'gsc_impressions' => __('Google Search Console', 'aysaaiseo'),
                    'gsc_clicks' => __('Google Search Console', 'aysaaiseo'),
                    'ga_sessions' => __('Google Analytics', 'aysaaiseo'),
                    'ga_conversions' => __('Google Analytics', 'aysaaiseo'),
                    'identifiable_ai_referrals' => __('Google Analytics referral evidence', 'aysaaiseo'),
                    'gbp_visibility' => __('Google Business Profile', 'aysaaiseo'),
                    'gbp_actions' => __('Google Business Profile', 'aysaaiseo'),
                ),
                'correlationStatusLabels' => array(
                    'not_available' => __('No saved observation', 'aysaaiseo'),
                    'baseline_only' => __('One saved observation; two are required for comparison', 'aysaaiseo'),
                    'comparison_available' => __('Comparable observations available', 'aysaaiseo'),
                ),
                'correlationScopeLabels' => array(
                    'referrer_identified_only' => __('Only sessions with an identifiable referrer', 'aysaaiseo'),
                    'source_metric_only' => __('Read independently in its source; no cross-source attribution', 'aysaaiseo'),
                ),
                'knowledgeSourceTypeLabels' => array(
                    'wordpress_snapshot' => __('Published WordPress snapshot', 'aysaaiseo'),
                    'manual_claim_source' => __('Manually supplied brand facts', 'aysaaiseo'),
                    'url_snapshot' => __('Controlled URL snapshot', 'aysaaiseo'),
                    'document' => __('Uploaded document', 'aysaaiseo'),
                    'snippet' => __('Manual text excerpt', 'aysaaiseo'),
                ),
                'knowledgeVerificationLabels' => array(
                    'official_source_review_required' => __('Official source — factual review required', 'aysaaiseo'),
                    'proposed' => __('Proposed — review required', 'aysaaiseo'),
                    'verified' => __('Verified', 'aysaaiseo'),
                ),
                'contentScoreLabels' => array(
                    'brand_favorability' => __('Brand favorability', 'aysaaiseo'),
                    'question_coverage' => __('Question coverage', 'aysaaiseo'),
                    'citation_standing' => __('Citation readiness', 'aysaaiseo'),
                    'brand_fit' => __('Brand and topic fit', 'aysaaiseo'),
                ),
                'contentCheckLabels' => array(
                    'answer_first' => __('Direct answer near the start', 'aysaaiseo'),
                    'question_coverage' => __('Questions have direct answers', 'aysaaiseo'),
                    'citation_standing' => __('Authoritative sources', 'aysaaiseo'),
                    'brand_fit' => __('Clear brand identification', 'aysaaiseo'),
                    'geo_structure' => __('Answer-friendly structure', 'aysaaiseo'),
                    'readability' => __('Readable sentences', 'aysaaiseo'),
                    'findability' => __('Findable canonical page', 'aysaaiseo'),
                    'schema_rendered_output' => __('Verified rendered schema', 'aysaaiseo'),
                    'entity_clarity' => __('Clear brand and offering relationship', 'aysaaiseo'),
                    'factual_support' => __('Factual claims have sources', 'aysaaiseo'),
                    'content_elements' => __('Useful headings, tables or FAQs', 'aysaaiseo'),
                    'intent_fit' => __('Content matches the selected intent', 'aysaaiseo'),
                    'data_freshness' => __('Current facts and dates', 'aysaaiseo'),
                    'trust_signals' => __('Author, About and Contact signals', 'aysaaiseo'),
                    'cannibalization' => __('No competing target pages', 'aysaaiseo'),
                    'target_page_fit' => __('Confirmed target page', 'aysaaiseo'),
                    'internal_linking' => __('Relevant internal links', 'aysaaiseo'),
                    'external_authority' => __('Primary external references', 'aysaaiseo'),
                    'knowledge_base_consistency' => __('Consistency with confirmed brand facts', 'aysaaiseo'),
                ),
                'contentCheckGuidance' => array(
                    'answer_first' => __('Place one concise factual answer immediately after the main heading.', 'aysaaiseo'),
                    'question_coverage' => __('Give every selected user question one evidence-backed direct answer.', 'aysaaiseo'),
                    'citation_standing' => __('Support material claims with relevant primary or authoritative sources.', 'aysaaiseo'),
                    'brand_fit' => __('Name the canonical brand naturally and connect it to the page topic.', 'aysaaiseo'),
                    'geo_structure' => __('Use descriptive sections, concise answers and a useful table or FAQ.', 'aysaaiseo'),
                    'readability' => __('Shorten long sentences and keep one main idea per paragraph.', 'aysaaiseo'),
                    'findability' => __('Confirm the canonical URL, title, description and indexability.', 'aysaaiseo'),
                    'schema_rendered_output' => __('Validate structured data on the rendered page in Technical SEO.', 'aysaaiseo'),
                    'entity_clarity' => __('State who provides the product or service, where and for whom.', 'aysaaiseo'),
                    'factual_support' => __('Attach an official source to every material factual claim.', 'aysaaiseo'),
                    'content_elements' => __('Add only useful headings, tables, FAQs and direct answers.', 'aysaaiseo'),
                    'intent_fit' => __('Align the page with the confirmed topic and user intent.', 'aysaaiseo'),
                    'data_freshness' => __('Verify time-sensitive facts and record the latest update.', 'aysaaiseo'),
                    'trust_signals' => __('Connect genuine author, About and Contact evidence.', 'aysaaiseo'),
                    'cannibalization' => __('Consolidate or remap pages that compete for the same intent.', 'aysaaiseo'),
                    'target_page_fit' => __('Confirm one canonical destination or create it through Content Plan.', 'aysaaiseo'),
                    'internal_linking' => __('Connect relevant source, anchor and target pages.', 'aysaaiseo'),
                    'external_authority' => __('Cite primary sources for material external facts.', 'aysaaiseo'),
                    'knowledge_base_consistency' => __('Resolve conflicts against confirmed brand facts before publishing.', 'aysaaiseo'),
                ),
                'contentCheckStatusLabels' => array(
                    'pass' => __('Passed', 'aysaaiseo'),
                    'needs_improvement' => __('Needs improvement', 'aysaaiseo'),
                ),
                'contentImpactLabels' => array(
                    'maintain' => __('Maintain', 'aysaaiseo'),
                    'low' => __('Low impact', 'aysaaiseo'),
                    'medium' => __('Medium impact', 'aysaaiseo'),
                    'high' => __('High impact', 'aysaaiseo'),
                ),
                'passedChecks' => __('passed checks', 'aysaaiseo'),
                'checksNeedImprovement' => __('checks need improvement', 'aysaaiseo'),
                'evidenceLabel' => __('Evidence', 'aysaaiseo'),
                'impactOutcomeLabels' => array(
                    'improved' => __('Improved', 'aysaaiseo'),
                    'regressed' => __('Regressed', 'aysaaiseo'),
                    'no_material_change' => __('No material change', 'aysaaiseo'),
                    'insufficient_data' => __('Not enough comparable data', 'aysaaiseo'),
                ),
                'impactStatementLabels' => array(
                    'improved' => __('An improvement was observed in a comparable cohort; this does not by itself prove causality.', 'aysaaiseo'),
                    'regressed' => __('A regression was observed in a comparable cohort; this does not by itself prove causality.', 'aysaaiseo'),
                    'no_material_change' => __('No material change was observed in the comparable cohort.', 'aysaaiseo'),
                    'insufficient_data' => __('Impact cannot yet be assessed because comparable data is missing or insufficient.', 'aysaaiseo'),
                ),
                'interventionStatusLabels' => array(
                    'proposal_dispatched' => __('Proposal sent for review', 'aysaaiseo'),
                    'proposals_dispatched' => __('Proposals sent for review', 'aysaaiseo'),
                    'applied_verified' => __('Applied and verified', 'aysaaiseo'),
                    'monitoring' => __('Monitoring', 'aysaaiseo'),
                    'applied_monitoring' => __('Applied — monitoring impact', 'aysaaiseo'),
                ),
                'riskLabels' => array(
                    'low' => __('Low', 'aysaaiseo'),
                    'medium' => __('Medium', 'aysaaiseo'),
                    'high' => __('High', 'aysaaiseo'),
                ),
                'canonicalProposalFor' => __('Canonical proposal for {lane}', 'aysaaiseo'),
                'verificationRequired' => __('Verified readback is required before completion.', 'aysaaiseo'),
                'rollbackAvailable' => __('The canonical workflow retains a rollback or recovery path.', 'aysaaiseo'),
                'seriesBreakLabels' => array(
                    'baseline_missing' => __('First observation in this comparison series', 'aysaaiseo'),
                    'methodology_version_changed' => __('Methodology changed — a new comparison series starts here', 'aysaaiseo'),
                    'cohort_hash_changed' => __('Cohort changed — a new comparison series starts here', 'aysaaiseo'),
                    'scenario_set_hash_changed' => __('Scenario set changed — a new comparison series starts here', 'aysaaiseo'),
                    'engine_set_hash_changed' => __('Engine set changed — a new comparison series starts here', 'aysaaiseo'),
                    'locale_location_hash_changed' => __('Locale or location changed — a new comparison series starts here', 'aysaaiseo'),
                    'eligibility_policy_version_changed' => __('Eligibility policy changed — a new comparison series starts here', 'aysaaiseo'),
                ),
                'trendNotComparable' => __('The latest two observations are not comparable, so no delta is shown.', 'aysaaiseo'),
                'recordedMetric' => __('Recorded metric', 'aysaaiseo'),
                'recordedSource' => __('Recorded source', 'aysaaiseo'),
                'recordedItem' => __('Recorded item', 'aysaaiseo'),
                'recordedRecommendation' => __('Recorded recommendation', 'aysaaiseo'),
                'recordedWorkflow' => __('Canonical workflow', 'aysaaiseo'),
                'additionalConversationsShort' => __('{count} additional eligible conversation(s) required to reach {minimum}.', 'aysaaiseo'),
                'conversationSingular' => __('conversation', 'aysaaiseo'),
                'baselineLabel' => __('Baseline', 'aysaaiseo'),
                'baselineDate' => __('Date', 'aysaaiseo'),
                'baselineSample' => __('Sample', 'aysaaiseo'),
                'baselineCohort' => __('Cohort', 'aysaaiseo'),
                'baselineMethodology' => __('Methodology', 'aysaaiseo'),
                'baselineContextUnavailable' => __('Baseline context is no longer available for this owned measurement.', 'aysaaiseo'),
                'notRecorded' => __('Not recorded', 'aysaaiseo'),
                'technicalReason' => __('Technical reason', 'aysaaiseo'),
                'recommendationOnlyState' => __('Recommendation only — no changes have been applied.', 'aysaaiseo'),
                'costQuotedBeforeApproval' => __('Any execution cost is quoted before approval.', 'aysaaiseo'),
                'groundingLabels' => array(
                    'grounded_correct' => __('Supported by confirmed business evidence', 'aysaaiseo'),
                    'grounded_incorrect' => __('Contradicts confirmed business evidence', 'aysaaiseo'),
                    'not_grounded' => __('Not yet verified against confirmed business evidence', 'aysaaiseo'),
                ),
                'sentimentLabels' => array(
                    'positive' => __('Positive', 'aysaaiseo'),
                    'neutral' => __('Neutral', 'aysaaiseo'),
                    'negative' => __('Negative', 'aysaaiseo'),
                ),
                'factClassificationLabels' => array(
                    'supported' => __('Supported', 'aysaaiseo'),
                    'contradicted' => __('Contradicted', 'aysaaiseo'),
                    'indecisive' => __('Not enough evidence', 'aysaaiseo'),
                ),
                'signalMethodLabels' => array(
                    'provider_annotation' => __('Observed provider query', 'aysaaiseo'),
                    'response_extraction' => __('Extracted from the saved answer', 'aysaaiseo'),
                ),
                'measurementNotReady' => __('Measurement setup is not ready.', 'aysaaiseo'),
                'measurementNotReadyHint' => __('Confirm at least one Scenario and configure an answer engine first.', 'aysaaiseo'),
                'measurementTitle' => __('Prepare an exact measurement quote', 'aysaaiseo'),
                'measurementHint' => __('Review the exact cohort, prompts and maximum cost before starting a paid run.', 'aysaaiseo'),
                'scenarios' => __('Scenarios', 'aysaaiseo'),
                'answerEngines' => __('Answer engines', 'aysaaiseo'),
                'recordedEngine' => __('Recorded answer engine', 'aysaaiseo'),
                'engineLabels' => array(
                    'google_ai_mode' => __('Google AI Mode', 'aysaaiseo'),
                    'dataforseo_ai_mode' => __('Google AI Mode', 'aysaaiseo'),
                    'dataforseo_chatgpt' => __('ChatGPT', 'aysaaiseo'),
                    'dataforseo_gemini' => __('Gemini', 'aysaaiseo'),
                    'chatgpt' => __('ChatGPT', 'aysaaiseo'),
                    'gemini' => __('Gemini', 'aysaaiseo'),
                    'chatgpt_api' => __('ChatGPT API', 'aysaaiseo'),
                    'gemini_api' => __('Gemini API', 'aysaaiseo'),
                ),
                'errorLabels' => array(
                    'ai_visibility_engine_multi_turn_unsupported' => __('The selected engine does not support multi-turn scenarios. Choose ChatGPT or Gemini, or deselect the multi-turn scenarios.', 'aysaaiseo'),
                    'ai_visibility_ai_mode_multi_turn_unsupported' => __('Google AI Mode currently supports single-turn scenarios only. Deselect the multi-turn scenarios.', 'aysaaiseo'),
                    'ai_visibility_insufficient_credits' => __('There are not enough available credits for this measurement.', 'aysaaiseo'),
                    'ai_visibility_wallet_snapshot_unavailable' => __('The current wallet balance could not be verified. Try the quote again before starting.', 'aysaaiseo'),
                ),
                'multiTurnEngineUnsupported' => __('This engine does not support the selected multi-turn scenarios and was deselected.', 'aysaaiseo'),
                'availabilityLabels' => array(
                    'ready' => __('Ready', 'aysaaiseo'),
                    'not_configured' => __('Not configured', 'aysaaiseo'),
                    'partial' => __('Configuration incomplete', 'aysaaiseo'),
                    'unsupported' => __('Not implemented yet', 'aysaaiseo'),
                    'temporarily_unavailable' => __('Temporarily unavailable', 'aysaaiseo'),
                    'unavailable' => __('Unavailable', 'aysaaiseo'),
                ),
                'channelLabels' => array(
                    'licensed_serp_provider' => __('Licensed SERP provider', 'aysaaiseo'),
                    'official_api' => __('Official API', 'aysaaiseo'),
                ),
                'replicates' => __('Replicates', 'aysaaiseo'),
                'location' => __('Location', 'aysaaiseo'),
                'calculateExactQuote' => __('Calculate exact quote', 'aysaaiseo'),
                'measurementSelectionRequired' => __('Choose at least one Scenario and answer engine.', 'aysaaiseo'),
                'calculatingQuote' => __('Compiling exact prompts and cost…', 'aysaaiseo'),
                'exactQuote' => __('Exact quote', 'aysaaiseo'),
                'turns' => __('turns', 'aysaaiseo'),
                'dataPreview' => __('Exact data sent to providers', 'aysaaiseo'),
                'policyReady' => __('The canonical Monitoring policy and exact scope are ready.', 'aysaaiseo'),
                'policyRequired' => __('Approve a manual-only Monitoring budget and this exact scope before starting.', 'aysaaiseo'),
                'noChargeForQuote' => __('This quote did not call a provider or use credits.', 'aysaaiseo'),
                'availableCredits' => __('Available credits', 'aysaaiseo'),
                'insufficientCreditsForRun' => __('This measurement needs a maximum of {required} credits, but only {available} are currently available. Add credits and calculate the quote again.', 'aysaaiseo'),
                'openAgent8ForApproval' => __('Open Agent8 Monitoring', 'aysaaiseo'),
                'monthlyBudget' => __('Monthly Monitoring budget', 'aysaaiseo'),
                'perRunCap' => __('Maximum credits for this run', 'aysaaiseo'),
                'preparePolicyApproval' => __('Review Monitoring approval', 'aysaaiseo'),
                'confirmPolicyApproval' => __('Confirm manual-only Monitoring policy', 'aysaaiseo'),
                'policyApprovalNotice' => __('This authorizes manual measurements only. It does not enable a schedule.', 'aysaaiseo'),
                'monitoringActivationRequired' => __('The policy is approved, but Monitoring must be active in Agent8 before a manual run can start.', 'aysaaiseo'),
                'confirmRunCost' => __('I approve this exact cohort and maximum cost.', 'aysaaiseo'),
                'startMeasurement' => __('Start measurement', 'aysaaiseo'),
                'startingMeasurement' => __('Creating the durable measurement run…', 'aysaaiseo'),
                'measurementQueued' => __('Measurement queued. Provider work will continue in the background.', 'aysaaiseo'),
                'cancelMeasurement' => __('Cancel measurement', 'aysaaiseo'),
                'cancelMeasurementConfirm' => __('Cancel this measurement? New provider work will stop. Work already completed remains recorded and may still count as actual usage.', 'aysaaiseo'),
                'cancellingMeasurement' => __('Cancelling measurement…', 'aysaaiseo'),
                'measurementCancelled' => __('Measurement cancelled', 'aysaaiseo'),
                'reviewRetry' => __('Review retryable work', 'aysaaiseo'),
                'checkingRetry' => __('Checking retryable work…', 'aysaaiseo'),
                'noRetryableWork' => __('No safely retryable failed work is available.', 'aysaaiseo'),
                /* Client-side placeholders are replaced only after the read-only review response. */
                'retryMeasurementConfirm' => __('Queue one additional attempt for {count} retryable task(s)? Completed provider responses will be reused. New usage is possible only if a new provider result is produced.', 'aysaaiseo'),
                'reviewReprocess' => __('Review extraction reprocess', 'aysaaiseo'),
                'checkingReprocess' => __('Checking source evidence…', 'aysaaiseo'),
                'reprocessConfirm' => __('Create {count} review-only extraction candidate(s), from {source} to {target}? The answer provider and wallet will not be called, and current metrics will not change.', 'aysaaiseo'),
                'reprocessQueued' => __('Versioned extraction candidates were queued for review. Current metrics remain unchanged.', 'aysaaiseo'),
                'scheduleTitle' => __('Automatic AI Visibility schedule', 'aysaaiseo'),
                'scheduleHint' => __('Uses the canonical Monitoring frequency, exact cohort and approved monthly budget. Existing users are never enrolled automatically.', 'aysaaiseo'),
                'reviewSchedule' => __('Review automatic schedule', 'aysaaiseo'),
                'scheduleConsent' => __('I authorize recurring paid measurements for this exact cohort, frequency and budget.', 'aysaaiseo'),
                'confirmSchedule' => __('Confirm automatic schedule', 'aysaaiseo'),
                'scheduleConfirmed' => __('Automatic schedule confirmed.', 'aysaaiseo'),
                'scheduleFrequency' => __('Frequency', 'aysaaiseo'),
                'nextScheduledRun' => __('Next scheduled run', 'aysaaiseo'),
                'scheduleActive' => __('Schedule active', 'aysaaiseo'),
                'schedulePaused' => __('Schedule paused — reconfirmation required', 'aysaaiseo'),
                'disableSchedule' => __('Disable schedule', 'aysaaiseo'),
                'disableScheduleConfirm' => __('Disable this AI Visibility schedule? Existing measurements and evidence will remain unchanged.', 'aysaaiseo'),
                'scheduleDisabled' => __('Schedule disabled. Existing results were preserved.', 'aysaaiseo'),
                'exportCsv' => __('Export CSV', 'aysaaiseo'),
                'printReport' => __('Print / Save PDF', 'aysaaiseo'),
                'noTrends' => __('No trend data is available yet.', 'aysaaiseo'),
                'measurements' => __('measurements', 'aysaaiseo'),
                'noSignals' => __('No extracted signals are available yet.', 'aysaaiseo'),
                'noSignalsInGroup' => __('No signals in this run.', 'aysaaiseo'),
                'perceptions' => __('Perceptions', 'aysaaiseo'),
                'facts' => __('Fact checks', 'aysaaiseo'),
                'competitorMentions' => __('Competitor mentions', 'aysaaiseo'),
                'citations' => __('Citations', 'aysaaiseo'),
                'queryExpansions' => __('Query expansions', 'aysaaiseo'),
                'contentAnalyzerTitle' => __('Content Analyzer AEO/GEO', 'aysaaiseo'),
                'contentAnalyzerHint' => __('Analyze a controlled page snapshot. This does not fetch the URL, call a provider, use credits or change WordPress.', 'aysaaiseo'),
                'analyzeContent' => __('Analyze content snapshot', 'aysaaiseo'),
                'analyzingContent' => __('Analyzing the supplied snapshot…', 'aysaaiseo'),
                'contentUrl' => __('Canonical page URL', 'aysaaiseo'),
                'contentTitle' => __('Page title', 'aysaaiseo'),
                'contentMeta' => __('Meta description', 'aysaaiseo'),
                'contentBody' => __('Rendered content or text snapshot', 'aysaaiseo'),
                'contentQuestions' => __('Questions, one per line', 'aysaaiseo'),
                'contentAnswers' => __('Direct answers, one per line', 'aysaaiseo'),
                'contentKeywords' => __('Target terms, one per line', 'aysaaiseo'),
                'needsImprovement' => __('Needs improvement', 'aysaaiseo'),
                'whyItMatters' => __('Why it matters', 'aysaaiseo'),
                'recommendedChange' => __('Recommended change', 'aysaaiseo'),
                'estimatedImpact' => __('Estimated impact', 'aysaaiseo'),
                'addSelectedToPlan' => __('Add selected recommendations to Action Plan', 'aysaaiseo'),
                'addingToPlan' => __('Adding proposal-only recommendations…', 'aysaaiseo'),
                'addedToPlan' => __('Recommendations added to Action Plan. Review and approve them there.', 'aysaaiseo'),
                'baselineRequired' => __('Complete an AI Visibility measurement before adding analyzer recommendations to Action Plan.', 'aysaaiseo'),
                'commerceTitle' => __('Product Visibility & Commerce Readiness', 'aysaaiseo'),
                'commerceHint' => __('Analyze the published WooCommerce catalog against an existing completed AI Visibility measurement. No provider is called, no credits are used and no product is changed.', 'aysaaiseo'),
                'analyzeCommerce' => __('Analyze current WooCommerce catalog', 'aysaaiseo'),
                'analyzingCommerce' => __('Analyzing the catalog against existing conversation evidence…', 'aysaaiseo'),
                'commerceBaselineRequired' => __('Complete an AI Visibility measurement before analyzing product visibility.', 'aysaaiseo'),
                'commerceCatalog' => __('Catalog products', 'aysaaiseo'),
                'commerceObservations' => __('Product observations', 'aysaaiseo'),
                'commerceConfusions' => __('Potential product, price or availability confusions', 'aysaaiseo'),
                'commerceReadiness' => __('Commerce readiness checks', 'aysaaiseo'),
                'correlationTitle' => __('Source correlation', 'aysaaiseo'),
                'correlationHint' => __('Compare saved AI Visibility, citation, Search Console, Analytics, identifiable referral and Business Profile observations without blending them or claiming complete attribution.', 'aysaaiseo'),
                'correlationCaveat' => __('Co-movement is not causal attribution. Missing source data remains explicitly unavailable.', 'aysaaiseo'),
                'knowledgeBaseTitle' => __('Knowledge Base', 'aysaaiseo'),
                'knowledgeBaseHint' => __('Keep versioned first-party source snapshots for Agent8. Full content is encrypted and never becomes confirmed factual truth automatically.', 'aysaaiseo'),
                'syncWordPressKnowledge' => __('Sync published WordPress content', 'aysaaiseo'),
                'syncingKnowledge' => __('Creating and encrypting a read-only snapshot…', 'aysaaiseo'),
                'knowledgeReviewRequired' => __('Official source — factual review required', 'aysaaiseo'),
                'knowledgeEmpty' => __('No active Knowledge Base sources yet.', 'aysaaiseo'),
                'setupProposal' => __('Review these proposed setup values before confirming them.', 'aysaaiseo'),
                'previous' => __('Previous', 'aysaaiseo'),
                'next' => __('Next', 'aysaaiseo'),
                'confirmProfile' => __('Confirm profile', 'aysaaiseo'),
                'autosaveHint' => __('Changes are saved automatically as a draft.', 'aysaaiseo'),
                'brandRequired' => __('Brand name is required.', 'aysaaiseo'),
                'saving' => __('Saving…', 'aysaaiseo'),
                'saved' => __('Saved.', 'aysaaiseo'),
                'profileConfirmed' => __('Profile confirmed.', 'aysaaiseo'),
                'setupEntities' => __('Personas, topics and evidence setup', 'aysaaiseo'),
                'showArchived' => __('Show archived', 'aysaaiseo'),
                'saveEntity' => __('Save item', 'aysaaiseo'),
                'clear' => __('Clear', 'aysaaiseo'),
                'edit' => __('Edit', 'aysaaiseo'),
                'archive' => __('Archive', 'aysaaiseo'),
                'restore' => __('Restore', 'aysaaiseo'),
                'noEntities' => __('No items yet.', 'aysaaiseo'),
                'target' => __('Target', 'aysaaiseo'),
                'bundlePreview' => __('Approval bundle preview', 'aysaaiseo'),
                'bundleVersion' => __('Version', 'aysaaiseo'),
                'risk' => __('Risk', 'aysaaiseo'),
                'credits' => __('credits', 'aysaaiseo'),
                'targetMissing' => __('Target page must be confirmed', 'aysaaiseo'),
                'verification' => __('Verification', 'aysaaiseo'),
                'rollback' => __('Rollback', 'aysaaiseo'),
                'prepareApproval' => __('Prepare approval', 'aysaaiseo'),
                'proposalOnly' => __('Approval creates proposals in canonical AYSA lanes; it does not apply changes.', 'aysaaiseo'),
                'preparingApproval' => __('Preparing exact approval…', 'aysaaiseo'),
                'approvalReady' => __('Exact bundle is ready for approval.', 'aysaaiseo'),
                'approveBundle' => __('Approve proposal bundle', 'aysaaiseo'),
                'approvalConfirm' => __('Approve this exact proposal bundle? No changes will be applied yet.', 'aysaaiseo'),
                'bundleApproved' => __('Bundle approved for proposal dispatch.', 'aysaaiseo'),
                'noApplyPerformed' => __('No provider, wallet or apply operation was performed.', 'aysaaiseo'),
                'noInsights' => __('No evidence-backed recommendations yet.', 'aysaaiseo'),
                'runFirst' => __('Complete a measurement to generate the Action Plan.', 'aysaaiseo'),
                'recommendations' => __('Evidence-backed recommendations', 'aysaaiseo'),
                'selectRecommendations' => __('Select recommendations for one versioned approval bundle.', 'aysaaiseo'),
                'buildBundle' => __('Build approval bundle', 'aysaaiseo'),
                'evidenceRefs' => __('evidence references', 'aysaaiseo'),
                'selectAtLeastOne' => __('Select at least one recommendation.', 'aysaaiseo'),
                'singleBaseline' => __('Choose recommendations from one baseline run.', 'aysaaiseo'),
                'buildingBundle' => __('Building exact bundle…', 'aysaaiseo'),
                'createProposals' => __('Create canonical proposals', 'aysaaiseo'),
                'creatingProposals' => __('Creating canonical review proposals…', 'aysaaiseo'),
                'proposalsCreated' => __('Canonical proposals created for review.', 'aysaaiseo'),
                'noInterventions' => __('No verified intervention yet.', 'aysaaiseo'),
                'interventionHint' => __('Impact appears after canonical lane apply and readback are complete.', 'aysaaiseo'),
                'intervention' => __('Intervention', 'aysaaiseo'),
                'waitingImpact' => __('Waiting for a comparable after run.', 'aysaaiseo'),
                'assessLatest' => __('Assess latest comparable run', 'aysaaiseo'),
                'assessing' => __('Assessing durable metrics…', 'aysaaiseo'),
                'metricVisibility' => __('AI Visibility', 'aysaaiseo'),
                'metricRecommendationRate' => __('AI Recommendation Rate', 'aysaaiseo'),
                'metricRecommendationCoverage' => __('AI Recommendation Coverage', 'aysaaiseo'),
                'metricShareOfVoice' => __('AI Share of Voice', 'aysaaiseo'),
                'metricCitationRate' => __('First-party Citation Rate', 'aysaaiseo'),
                'metricFactAccuracy' => __('Fact Accuracy', 'aysaaiseo'),
                'insightLabels' => array(
                    'critical_visibility_gap' => __('Critical visibility gap', 'aysaaiseo'),
                    'recommendation_gap' => __('Recommendation gap', 'aysaaiseo'),
                    'citation_authority_gap' => __('Citation authority gap', 'aysaaiseo'),
                    'brand_fact_gap' => __('Brand fact gap', 'aysaaiseo'),
                ),
                'insightExplanations' => array(
                    'critical_visibility_gap' => __('Visibility is below the configured target.', 'aysaaiseo'),
                    'recommendation_gap' => __('The brand is recommended in too few eligible conversations.', 'aysaaiseo'),
                    'citation_authority_gap' => __('Answer engines rarely cite an owned source.', 'aysaaiseo'),
                    'brand_fact_gap' => __('Confirmed brand facts are contradicted or missing.', 'aysaaiseo'),
                ),
                'laneLabels' => array(
                    'content_plan' => __('Content Plan', 'aysaaiseo'),
                    'on_page' => __('On-Page SEO', 'aysaaiseo'),
                    'off_page_adverlink' => __('Off-Page / AdverLink', 'aysaaiseo'),
                    'technical_seo' => __('Technical SEO', 'aysaaiseo'),
                    'monitoring' => __('Monitoring', 'aysaaiseo'),
                ),
                'priorityLabels' => array(
                    'high' => __('High priority', 'aysaaiseo'),
                    'medium' => __('Medium priority', 'aysaaiseo'),
                    'low' => __('Low priority', 'aysaaiseo'),
                ),
                'conversations' => __('conversations', 'aysaaiseo'),
                'confidenceInterval' => __('95% CI', 'aysaaiseo'),
                'fieldBrand' => __('Brand', 'aysaaiseo'),
                'fieldDomain' => __('Canonical domain', 'aysaaiseo'),
                'fieldCategory' => __('Category', 'aysaaiseo'),
                'fieldPrimaryLanguage' => __('Primary language', 'aysaaiseo'),
                'fieldDescription' => __('Description', 'aysaaiseo'),
                'fieldProducts' => __('Products', 'aysaaiseo'),
                'fieldServices' => __('Services', 'aysaaiseo'),
                'fieldDifferentiators' => __('Differentiators', 'aysaaiseo'),
                'fieldMarkets' => __('Markets', 'aysaaiseo'),
                'fieldLocations' => __('Locations', 'aysaaiseo'),
                'fieldLanguages' => __('Languages', 'aysaaiseo'),
                'fieldClaim' => __('Claim', 'aysaaiseo'),
                'fieldName' => __('Name', 'aysaaiseo'),
                'fieldCompetitorDomain' => __('Competitor domain', 'aysaaiseo'),
                'fieldClassification' => __('Classification', 'aysaaiseo'),
                'fieldPriority' => __('Priority 0–100', 'aysaaiseo'),
                'fieldTopic' => __('Topic', 'aysaaiseo'),
                'fieldPersona' => __('Persona', 'aysaaiseo'),
                'fieldTestType' => __('Test type', 'aysaaiseo'),
                'confirmed' => __('Confirmed', 'aysaaiseo'),
                'entityAliases' => __('Aliases', 'aysaaiseo'),
                'entityPersonas' => __('Personas', 'aysaaiseo'),
                'entityTopics' => __('Topics', 'aysaaiseo'),
                'entityScenarios' => __('Scenarios', 'aysaaiseo'),
                'entityCompetitors' => __('Competitors', 'aysaaiseo'),
                'entityClaims' => __('Claims', 'aysaaiseo'),
        );
        if ($switched_to_english) {
            restore_previous_locale();
        }
        $interface_language = Aysa_AI_Visibility_I18n::cached_agent8_language();
        $english_shell = Aysa_AI_Visibility_I18n::shell('en');
        $romanian_shell = Aysa_AI_Visibility_I18n::shell('ro');
        wp_localize_script('aysa-ai-visibility', 'aysaAiVisibility', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('aysa_ai_visibility'),
            'locale' => $interface_language,
            'requestTimeoutMs' => 15000,
            'agent8Url' => admin_url('admin.php?page=aysa-agent8-v3-lab'),
            'strings' => Aysa_AI_Visibility_I18n::strings($english_strings, $interface_language),
            'stringsByLanguage' => array(
                'en' => $english_strings,
                'ro' => Aysa_AI_Visibility_I18n::strings($english_strings, 'ro'),
            ),
            'shellByLanguage' => array('en' => $english_shell, 'ro' => $romanian_shell),
        ));
    }

    public static function render() {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to access this page.', 'aysaaiseo'));
        }
        $interface_language = Aysa_AI_Visibility_I18n::cached_agent8_language();
        $shell = Aysa_AI_Visibility_I18n::shell($interface_language);
        require AYSA_PLUGIN_DIR . 'admin/partials/aysa-ai-visibility.php';
    }
}
