<?php

namespace Tests\Unit;

use App\Library\CampaignDecision\CampaignMarketingPlanPresenter;
use Tests\TestCase;

class CampaignMarketingPlanPresenterTest extends TestCase
{
    public function test_it_builds_labeled_steps_from_a_structured_plan(): void
    {
        $presentation = CampaignMarketingPlanPresenter::forRow([
            'marketing_plan' => [
                'Checked the last 7 days.',
                'Improve the creative.',
                '800 impressions produced 0 clicks.',
            ],
            'marketing_lever' => 'improve_creative',
        ]);

        $this->assertSame('Creative', $presentation['lever_label']);
        $this->assertCount(3, $presentation['steps']);
        $this->assertSame('Window', $presentation['steps'][0]['label']);
        $this->assertSame('Change', $presentation['steps'][1]['label']);
        $this->assertSame('Why', $presentation['steps'][2]['label']);
        $this->assertStringContainsString('<strong class="mb-perf-plan-em">800</strong>', $presentation['steps'][2]['html']);
    }

    public function test_it_highlights_currency_without_allowing_html_injection(): void
    {
        $html = CampaignMarketingPlanPresenter::richText('<script>alert(1)</script> $12.10 spend');

        $this->assertStringNotContainsString('<script>', $html);
        $this->assertStringContainsString('$12.10', $html);
        $this->assertStringContainsString('mb-perf-plan-em', $html);
        $this->assertStringContainsString('>2026-10-06 00:00:00<', CampaignMarketingPlanPresenter::richText('from 2026-10-06 00:00:00'));
    }

    public function test_it_builds_markdown_bullets_for_chat_and_board_parity(): void
    {
        $markdown = CampaignMarketingPlanPresenter::toMarkdownBullets([
            'marketing_plan' => [
                'Checked the last 7 days.',
                'Improve the creative.',
                '800 impressions produced 0 clicks.',
            ],
            'marketing_lever' => 'improve_creative',
        ]);

        $this->assertStringContainsString('**Primary lever:** Creative', $markdown);
        $this->assertStringContainsString('- **Window:** Checked the last 7 days.', $markdown);
        $this->assertStringContainsString('- **Change:** Improve the creative.', $markdown);
    }

    public function test_a_landing_suggestion_is_shown_after_the_plan(): void
    {
        $presentation = CampaignMarketingPlanPresenter::forRow([
            'marketing_plan' => [
                'Checked the last 7 days.',
                'Fix the landing page.',
                'CTR is 3.5% on 21 clicks.',
            ],
            'marketing_lever' => 'fix_landing_page',
            'landing_suggestion' => [
                'problem' => 'The page opens on a logo and never states the offer.',
                'flow' => 'Open with the risk, then the proof, then one next step.',
                'content' => 'Headline: See the risk before you merge. Button: Review my repo.',
            ],
        ]);

        $this->assertSame('Landing page', $presentation['steps'][3]['label']);
        $this->assertSame('landing', $presentation['steps'][3]['kind']);
        $this->assertStringContainsString('never states the offer', $presentation['steps'][3]['html']);
        $this->assertStringContainsString('Open with the risk, then the proof, then one next step.', $presentation['steps'][3]['html']);
        $this->assertStringContainsString('See the risk before you merge', $presentation['steps'][3]['html']);
        $this->assertCount(4, $presentation['steps']);
    }

    public function test_a_stored_review_adds_creative_landing_and_test_sections(): void
    {
        $presentation = CampaignMarketingPlanPresenter::forRow([
            'marketing_plan' => [
                'Checked the last 7 days.',
                'Fix the landing page.',
                'CTR is 3.5% on 21 clicks.',
            ],
            'marketing_lever' => 'fix_landing_page',
            'review' => [
                'budget' => 'Keep the daily budget at $20.00.',
                'creatives' => [[
                    'creative_id' => '925887686918149',
                    'current_headline' => 'Browser for Mac',
                    'action' => 'change',
                    'why' => 'The headline does not name the offer.',
                    'replacement_headline' => 'Browser for Mac search',
                    'replacement_primary_text' => 'Search the web from the Mac browser.',
                    'replacement_secondary_text' => 'Free on Mac.',
                    'replacement_cta' => 'Download',
                    'image_prompt' => 'A Mac screen showing a search box and a download button, with no extra claims.',
                ]],
                'landing' => [
                    'problem' => 'The page opens on a logo.',
                    'flow' => 'Offer, proof, then the next step.',
                    'headline' => 'See the risk before you merge',
                    'cta' => 'Review my repo',
                    'prompt' => 'This is an offsite sign-up page, not a download page. Open with the headline, then one sign-up button, then the proof.',
                ],
                'tests' => 'Replace the headline and watch CTR.',
            ],
        ]);

        $labels = array_column($presentation['steps'], 'label');

        $this->assertContains('Budget', $labels);
        $this->assertContains('Browser for Mac', $labels);
        $this->assertContains('Landing page', $labels);
        $this->assertContains('Tests', $labels);
        $creative = collect($presentation['steps'])->firstWhere('label', 'Browser for Mac');
        $landing = collect($presentation['steps'])->firstWhere('kind', 'landing');
        $this->assertIsArray($creative);
        $this->assertIsArray($landing);
        $this->assertStringContainsString('mb-perf-ad-subtitle">Creative', $creative['html']);
        $this->assertStringContainsString('Browser for Mac search', $creative['html']);
        $this->assertStringContainsString('Search the web from the Mac browser.', $creative['html']);
        $this->assertStringContainsString('>Primary text<', $creative['html']);
        $this->assertStringNotContainsString('>New text<', $creative['html']);
        $this->assertStringContainsString('>Secondary text<', $creative['html']);
        $this->assertStringContainsString('Free on Mac.', $creative['html']);
        $this->assertStringContainsString('>Image prompt<', $creative['html']);
        $this->assertStringContainsString('Creative ID 925887686918149', $creative['html']);
        $this->assertStringContainsString('>Download<', $creative['html']);
        $this->assertStringContainsString('is-change', $creative['html']);
        $this->assertStringNotContainsString('Replacement headline', $creative['html']);
        $this->assertStringContainsString('mb-perf-ad-subtitle">Landing page', $landing['html']);
        $this->assertStringContainsString('See the risk before you merge', $landing['html']);
        $this->assertStringContainsString('Review My Repo', $landing['html']);
        $this->assertStringContainsString('The page opens on a logo.', $landing['html']);
        $this->assertStringContainsString('>Landing page prompt<', $landing['html']);
        $this->assertStringContainsString('offsite sign-up page', $landing['html']);
    }

    public function test_a_full_analysis_replaces_the_short_plan(): void
    {
        $analysis = "Current performance\nSpend: 12.10\nClicks: 21\n\nWhat is working. The click rate is healthy.\nThe bottleneck. Results after the click are the constraint.\nRecommendations\n1. Keep the 20 budget. Rewrite the first screen.\n2. Test a new headline.\n3. Add product proof above the button.\n4. Judge CTR and results after the next spend period.\n<script>alert(1)</script>";
        $presentation = CampaignMarketingPlanPresenter::forRow([
            'marketing_plan' => [
                'Checked the last 7 days.',
                'Fix the landing page.',
                'CTR is 1.75% on 246 clicks.',
            ],
            'marketing_lever' => 'fix_landing_page',
            'review' => [
                'analysis' => $analysis,
            ],
        ]);

        $this->assertCount(1, $presentation['steps']);
        $this->assertSame('analysis', $presentation['steps'][0]['kind']);

        $html = $presentation['steps'][0]['html'];

        $this->assertStringContainsString('Rewrite the first screen', $html);
        $this->assertStringContainsString('Test a new headline', $html);
        $this->assertSame(1, substr_count($html, 'Rewrite the first screen'));
        $this->assertStringNotContainsString('Action', $presentation['steps'][0]['label']);
        $this->assertStringContainsString('mb-perf-analysis-heading', $html);
        $this->assertStringContainsString('Current Performance', $html);
        $this->assertStringContainsString('Recommendations', $html);
        $this->assertStringContainsString('mb-perf-analysis-metrics', $html);
        $this->assertStringContainsString('>Spend</dt>', $html);
        $this->assertStringContainsString('mb-perf-analysis-list', $html);
        $this->assertStringContainsString('&lt;script&gt;', $html);
        $this->assertStringNotContainsString('<script>', $html);
    }

    public function test_ad_changes_replace_the_long_recommendation_paragraph(): void
    {
        $presentation = CampaignMarketingPlanPresenter::forRow([
            'review' => [
                'analysis' => "Current performance\nSpend: 12.10\n\nWhat is working. The ads earn clicks.\nThe bottleneck. Nothing happens after the click.\nRecommendations\n1. Review each ad against the lead goal. The file-change ad spent 4.06 for 0 clicks and the comparison ad spent 19.75 for 6 clicks, so change the visual and copy to tell the same story across the headline, the picture, and the button before the next spend period starts.\n2. Pause the 20 budget.",
                'creatives' => [[
                    'current_headline' => 'One Wrong File Change Can Cost You 20 Minutes',
                    'action' => 'change',
                    'why' => 'The picture shows the old way of working, not the approval step.',
                    'replacement_headline' => 'Review the Change Before It Touches Your Code',
                    'replacement_primary_text' => 'Lucos reviews every step before it touches your code.',
                    'replacement_cta' => 'SEE_DETAILS',
                ]],
            ],
        ]);

        $analysis = collect($presentation['steps'])->firstWhere('kind', 'analysis');
        $creative = collect($presentation['steps'])->firstWhere('kind', 'creative');

        $this->assertIsArray($analysis);
        $this->assertIsArray($creative);
        $this->assertStringNotContainsString('change the visual and copy', $analysis['html']);
        $this->assertStringContainsString('Pause the 20 budget.', $analysis['html']);
        $this->assertStringContainsString('Review the Change Before It Touches Your Code', $creative['html']);
        $this->assertStringContainsString('Lucos reviews every step before it touches your code.', $creative['html']);
        $this->assertStringContainsString('See Details', $creative['html']);
        $this->assertStringContainsString('>Change<', $creative['html']);
        $this->assertStringContainsString('>Primary text<', $creative['html']);
    }

    public function test_a_creative_id_from_the_snapshot_is_shown_when_the_review_omits_it(): void
    {
        $presentation = CampaignMarketingPlanPresenter::forRow([
            'reason' => 'Change the picture.',
            'review' => [
                'creatives' => [[
                    'ad_id' => '120252007591870626',
                    'current_headline' => 'One Wrong File Change Can Cost You 20 Minutes',
                    'action' => 'change',
                    'why' => 'The picture shows the old way of working.',
                    'replacement_headline' => 'Review the Change Before It Touches Your Code',
                    'replacement_primary_text' => 'Lucos reviews every step before it touches your code.',
                ]],
            ],
            'creative_context' => [
                'ads' => [[
                    'ad_id' => '120252007591870626',
                    'headline' => 'One Wrong File Change Can Cost You 20 Minutes',
                    'images' => [[
                        'ad_id' => '120252007591870626',
                        'creative_id' => '925887686918149',
                    ]],
                ]],
            ],
        ]);

        $creative = collect($presentation['steps'])->firstWhere('kind', 'creative');

        $this->assertIsArray($creative);
        $this->assertStringContainsString('Ad ID 120252007591870626', $creative['html']);
        $this->assertStringContainsString('Creative ID 925887686918149', $creative['html']);
    }

    public function test_suggestion_window_metrics_match_the_dashboard_windows(): void
    {
        $presentation = CampaignMarketingPlanPresenter::forRow([
            'windows' => [
                '7d' => [
                    'spend' => 65.41,
                    'impressions' => 1200,
                    'clicks' => 40,
                    'ctr' => 0.0333,
                    'cpc' => 1.6353,
                    'conversions' => 2,
                    'conversion_value' => 18.5,
                ],
                '30d' => [
                    'spend' => 232.96,
                    'impressions' => 8000,
                    'clicks' => 210,
                    'ctr' => 0.0263,
                    'cpc' => 1.1093,
                    'conversions' => 6,
                    'conversion_value' => 40,
                ],
            ],
            'review' => [
                'analysis' => "Current performance\nSpend: 1.00\nClicks: 9\n\nWhat is working. The click rate is healthy.\nThe bottleneck. Results after the click are the constraint.\nRecommendations\n1. Keep the current ads and rewrite the weaker headline.\n2. Judge the next period on the same 7-day and 30-day windows.\n3. Leave the budget unchanged until those windows move.\n4. Review the landing page before changing the offer.",
            ],
        ]);

        $html = $presentation['steps'][0]['html'];

        $this->assertStringContainsString('7-day spend', $html);
        $this->assertStringContainsString('$65.41', $html);
        $this->assertStringContainsString('30-day spend', $html);
        $this->assertStringContainsString('$232.96', $html);
        $this->assertStringNotContainsString('$1.00', $html);
        $this->assertCount(1, $presentation['steps']);
        $this->assertSame(1, substr_count($html, 'rewrite the weaker headline'));
        $this->assertStringNotContainsString('>Action<', $html);
    }

    public function test_each_ad_set_is_a_card_with_recommendations_like_a_creative(): void
    {
        $presentation = CampaignMarketingPlanPresenter::forRow([
            'review' => [
                'analysis' => "Current performance\nSpend: 40.00\n\nWhat is working. The ads earn clicks.\nThe bottleneck. Results after the click are the constraint.\nRecommendations\n1. Pause the budget.",
                'creatives' => [[
                    'creative_id' => '925887686918149',
                    'current_headline' => 'Browser for Mac',
                    'action' => 'change',
                    'why' => 'The headline does not name the offer.',
                    'replacement_headline' => 'Browser for Mac search',
                ]],
            ],
            'ad_set_optimization' => [
                'ad_sets' => [[
                    'ad_set_id' => 'set-1',
                    'name' => 'LP visitors <script>',
                    'optimization_goal' => 'OFFSITE_CONVERSIONS',
                    'optimization_event' => 'SUBSCRIBE',
                    'learning_status' => 'FAIL',
                    'audience' => [
                        'type' => 'retargeting',
                        'advantage_audience' => true,
                        'audience_size_lower' => 1000,
                        'audience_size_upper' => 1000,
                        'included_audiences' => [
                            ['id' => 'aud-1', 'name' => 'LP Visitors - 30d', 'subtype' => 'WEBSITE'],
                        ],
                    ],
                    'bid' => [
                        'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP',
                        'daily_budget' => 8,
                    ],
                    'delivery' => [
                        'spend' => 40,
                        'conversions' => 0,
                    ],
                    'breakdowns' => [
                        'placements' => [
                            ['label' => 'Facebook Feed', 'spend' => 40, 'conversions' => 0],
                        ],
                        'countries' => [
                            ['country' => 'US', 'spend' => 40, 'conversions' => 0],
                        ],
                    ],
                ]],
            ],
        ]);

        $adSet = collect($presentation['steps'])->firstWhere('kind', 'adset');
        $creative = collect($presentation['steps'])->firstWhere('kind', 'creative');

        $this->assertIsArray($adSet);
        $this->assertIsArray($creative);
        $this->assertSame('LP visitors <script>', $adSet['label']);
        $this->assertStringContainsString('class="mb-perf-ad"', $adSet['html']);
        $this->assertStringContainsString('mb-perf-ad-subtitle">Ad set', $adSet['html']);
        $this->assertStringContainsString('mb-perf-ad-id">set-1', $adSet['html']);
        $this->assertStringContainsString('is-change', $adSet['html']);
        $this->assertStringContainsString('>Change<', $adSet['html']);
        $this->assertStringNotContainsString('>Pause<', $adSet['html']);
        $this->assertStringContainsString('Meta learning', $adSet['html']);
        $this->assertStringContainsString('FAIL', $adSet['html']);
        $this->assertStringContainsString('>Audience<', $adSet['html']);
        $this->assertStringContainsString('Keep this retargeting list.', $adSet['html']);
        $this->assertStringContainsString('Audience size on file is 1000-1000.', $adSet['html']);
        $this->assertStringContainsString('Highest volume', $adSet['html']);
        $this->assertStringContainsString('>Bidding strategy<', $adSet['html']);
        $this->assertStringContainsString('>Event<', $adSet['html']);
        $this->assertStringContainsString('Judge the next test on SUBSCRIBE.', $adSet['html']);
        $this->assertStringContainsString('>Placements<', $adSet['html']);
        $this->assertStringContainsString('Facebook Feed first', $adSet['html']);
        $this->assertStringContainsString('>Country<', $adSet['html']);
        $this->assertStringContainsString('Start the next test in US', $adSet['html']);
        $this->assertStringContainsString('Use this budget for the next test.', $adSet['html']);
        $this->assertStringNotContainsString('<script>', $adSet['html']);
        $this->assertLessThan(
            array_search($creative, $presentation['steps'], true),
            array_search($adSet, $presentation['steps'], true),
        );
        $this->assertSame('analysis', $presentation['steps'][0]['kind']);
        $this->assertSame('adset', $presentation['steps'][1]['kind']);

        $paused = CampaignMarketingPlanPresenter::forRow([
            'status' => 'pause',
            'budget_summary' => 'Pause the campaign and stop all of the $10.00 daily budget.',
            'ad_set_optimization' => [
                'ad_sets' => [[
                    'ad_set_id' => 'set-1',
                    'name' => 'LP visitors',
                    'optimization_event' => 'SUBSCRIBE',
                    'learning_status' => 'FAIL',
                    'audience' => ['type' => 'retargeting'],
                    'bid' => ['bid_strategy' => 'LOWEST_COST_WITHOUT_CAP', 'daily_budget' => 8],
                    'delivery' => ['spend' => 40, 'conversions' => 0],
                    'breakdowns' => [],
                ]],
            ],
        ]);
        $pausedCard = collect($paused['steps'])->firstWhere('kind', 'adset');
        $this->assertIsArray($pausedCard);
        $this->assertStringContainsString('>Pause<', $pausedCard['html']);
        $this->assertStringContainsString('is-pause', $pausedCard['html']);
        $this->assertStringNotContainsString('Do not increase', $pausedCard['html']);
        $this->assertStringNotContainsString('Hold the daily budget', $pausedCard['html']);
        $this->assertStringNotContainsString('Use this budget for the next test', $pausedCard['html']);

        $developers = CampaignMarketingPlanPresenter::forRow([
            'name' => 'Lucos - Retargeting - LP Visitors',
            'status' => 'pause',
            'review' => [
                'landing' => ['headline' => 'Build and Review Code With Lucos'],
                'creatives' => [[
                    'current_headline' => 'Lucos vs. Copilot vs. Cursor',
                    'action' => 'keep',
                    'why' => 'The comparison drew clicks.',
                ]],
            ],
            'ad_set_optimization' => [
                'ad_sets' => [[
                    'ad_set_id' => 'set-1',
                    'name' => 'LP visitors',
                    'audience' => ['type' => 'retargeting'],
                    'delivery' => ['spend' => null, 'conversions' => null],
                ]],
            ],
        ]);
        $developerCard = collect($developers['steps'])->firstWhere('kind', 'adset');
        $this->assertIsArray($developerCard);
        $this->assertStringContainsString('Keep this retargeting list.', $developerCard['html']);
        $this->assertStringContainsString('Software (computers &amp; electronics)', $developerCard['html']);
        $this->assertStringContainsString('Web development (websites)', $developerCard['html']);
    }

    public function test_frozen_tracking_omits_creative_and_landing_cards_from_detail_layers(): void
    {
        $row = [
            'snapshot' => [
                'performance_strategy' => [
                    'broken_step' => 'tracking',
                    'ad_roster' => ['frozen' => true, 'ads' => []],
                ],
            ],
            'review' => [
                'analysis' => 'Check tracking first.',
                'creatives' => [[
                    'ad_id' => '1',
                    'current_headline' => 'Lucos vs Copilot',
                    'action' => 'change',
                    'why' => 'Write a new comparison ad.',
                    'replacement_headline' => 'Switch from Cursor',
                    'replacement_primary_text' => 'Keep the same price.',
                ]],
                'landing' => [
                    'headline' => 'Switch from Cursor page',
                    'problem' => 'The page never asks for subscribe.',
                ],
            ],
        ];

        $steps = CampaignMarketingPlanPresenter::detailSupportSteps($row);
        $html = implode('', array_column($steps, 'html'));

        $this->assertNotContains('creative', array_column($steps, 'kind'));
        $this->assertNotContains('landing', array_column($steps, 'kind'));
        $this->assertStringNotContainsString('Switch from Cursor', $html);
    }

    public function test_long_prose_with_colons_is_rendered_as_paragraphs_not_metrics(): void
    {
        $analysis = "Current performance. Optimization event: results (conversion); the campaign objective is not set. Reporting window: 2026-10-30 to 2026-11-05. Meta learning stage: not on file; campaign verdict: learning.\n"
            ."Spend: $3.23\n"
            ."Impressions: 55\n"
            ."Cost per landing page view: $0.81\n"
            ."Daily history: 4 of 30 expected days on file, from 2026-10-07 to 2026-11-05. The 3-day window shows $3.23 spent.\n"
            ."The bottleneck. Tracking is the constraint: Meta reports 2 conversions, but internal records show 0, so the objective result cannot yet be trusted.\n"
            ."Proposed changes.\n"
            .'1. Fix tracking first: in Events Manager, check the pixel.';

        $presentation = CampaignMarketingPlanPresenter::forRow([
            'review' => ['analysis' => $analysis],
        ]);

        $html = $presentation['steps'][0]['html'];

        $this->assertStringContainsString('Current Performance', $html);
        $this->assertStringContainsString('The Bottleneck', $html);
        $this->assertStringContainsString('Proposed Changes', $html);

        $this->assertStringContainsString('>Spend</dt><dd>$3.23</dd>', $html);
        $this->assertStringContainsString('>Impressions</dt><dd>55</dd>', $html);
        $this->assertStringContainsString('>Cost per landing page view</dt><dd>$0.81</dd>', $html);

        $this->assertStringContainsString('class="mb-perf-analysis-copy">Optimization event: results (conversion)', $html);
        $this->assertStringContainsString('class="mb-perf-analysis-copy">Daily history: 4 of 30 expected days on file', $html);
        $this->assertStringContainsString('class="mb-perf-analysis-copy">Tracking is the constraint: Meta reports 2 conversions', $html);
        $this->assertStringNotContainsString('>Tracking is the constraint</dt>', $html);
        $this->assertStringNotContainsString('>Optimization event</dt>', $html);
        $this->assertStringNotContainsString('>Daily history</dt>', $html);
    }

    public function test_integer_metric_values_ending_with_period_and_window_are_properly_formatted(): void
    {
        $analysis = "Current performance. Optimization event: results; the campaign objective is not set.\n"
            ."Window: 2026-10-30 to 2026-11-05 (7 days).\n"
            ."Spend: 0.\n"
            ."Impressions: 0.\n"
            ."Clicks: 0.\n"
            ."Link clicks: 0.\n"
            ."Landing page views: 0.\n"
            ."Daily history: 4 of 30 expected days on file.\n"
            ."The bottleneck. Delivery is the constraint.\n"
            ."Proposed changes.\n"
            ."1. Confirm the campaign objective.\n"
            .'2. Inspect delivery settings.';

        $presentation = CampaignMarketingPlanPresenter::forRow([
            'review' => ['analysis' => $analysis],
        ]);

        $html = $presentation['steps'][0]['html'];

        $this->assertStringContainsString('class="mb-perf-analysis-copy">Window: 2026-10-30 to 2026-11-05 (7 days).', $html);
        $this->assertStringNotContainsString('>Window</dt>', $html);

        $this->assertStringContainsString('>Spend</dt><dd>0</dd>', $html);
        $this->assertStringContainsString('>Impressions</dt><dd>0</dd>', $html);
        $this->assertStringContainsString('>Clicks</dt><dd>0</dd>', $html);
        $this->assertStringContainsString('>Link clicks</dt><dd>0</dd>', $html);
        $this->assertStringContainsString('>Landing page views</dt><dd>0</dd>', $html);

        $this->assertStringNotContainsString('<p class="mb-perf-analysis-copy">Spend:</p>', $html);
        $this->assertStringNotContainsString('<p class="mb-perf-analysis-copy">0.</p>', $html);

        $this->assertStringContainsString('<div class="mb-perf-analysis-proposed">', $html);
        $this->assertStringContainsString('class="mb-perf-analysis-heading is-proposed"', $html);
        $this->assertStringContainsString('bi-lightning-charge-fill', $html);
        $this->assertStringContainsString('class="mb-perf-analysis-list is-proposed"', $html);
        $this->assertStringContainsString('<li>Confirm the campaign objective.</li>', $html);
        $this->assertStringContainsString('<li>Inspect delivery settings.</li>', $html);
    }

    public function test_mid_sentence_heading_words_do_not_create_duplicate_headings(): void
    {
        $analysis = "Ad-by-ad. Ad_2 (123): too_early.\n"
            ."Fatigue. Frequency is 1.32, and CTR is 0% versus 0% in the previous seven days; that does not establish fatigue. Duplicate copy is not flagged, so saturation cannot be established.\n"
            .'Creative. No replacement is warranted.';

        $presentation = CampaignMarketingPlanPresenter::forRow([
            'review' => ['analysis' => $analysis],
        ]);

        $html = $presentation['steps'][0]['html'];

        $this->assertSame(1, substr_count($html, 'Fatigue</h3>'));
        $this->assertStringContainsString('that does not establish fatigue. Duplicate copy is not flagged', $html);
    }

    public function test_metrics_with_arbitrary_numbers_and_inline_notes_remain_unified_in_grid(): void
    {
        $analysis = "Current performance. Optimization event: purchases.\n"
            ."Window: 2026-10-30 to 2026-11-05; the decision uses 7 days, not 15 days.\n"
            ."Spend: $24.02.\n"
            ."Impressions: 652.\n"
            ."Link clicks: 5.\n"
            ."Link-click CTR: 0.77%.\n"
            ."CPC: $4.80.\n"
            ."CPM: $36.84.\n"
            ."Reach: 95.\n"
            ."Frequency: 6.86 over 7 days.\n"
            ."Landing page views: 0 in the performance strategy; ad-level landing page views are not on file.\n"
            ."Conversions: 0.\n"
            ."Conversion value: 0.\n"
            ."Orders: 0.\n"
            ."Revenue: 0.\n"
            ."Platform results: 0.\n"
            ."Internal results: 0.\n"
            ."Per-ad spend, 1604032403: $24.02.\n"
            ."The bottleneck. Creative is the diagnosed constraint: 652 impressions produced 5 link clicks.\n"
            ."Proposed changes.\n"
            .'1. Keep ad unchanged.';

        $presentation = CampaignMarketingPlanPresenter::forRow([
            'review' => ['analysis' => $analysis],
        ]);

        $html = $presentation['steps'][0]['html'];

        $this->assertSame(1, substr_count($html, 'mb-perf-analysis-metrics'));
        $this->assertStringContainsString('>Impressions</dt><dd>652</dd>', $html);
        $this->assertStringContainsString('>Link clicks</dt><dd>5</dd>', $html);
        $this->assertStringContainsString('>Reach</dt><dd>95</dd>', $html);
        $this->assertStringContainsString('>Landing page views</dt><dd>0</dd>', $html);
        $this->assertStringContainsString('>Per-ad spend, 1604032403</dt><dd>$24.02</dd>', $html);

        $this->assertStringNotContainsString('Impressions:</p>', $html);
        $this->assertStringNotContainsString('Link clicks:</p>', $html);
        $this->assertStringNotContainsString('Reach:</p>', $html);

        $this->assertStringContainsString('class="mb-perf-analysis-copy">Creative is the diagnosed constraint: 652 impressions produced 5 link clicks.', $html);
        $this->assertStringNotContainsString('>Creative is the diagnosed constraint</dt>', $html);
    }

    public function test_it_cleans_historical_meta_isms_for_linkedin_campaigns(): void
    {
        $analysis = "Current performance. Optimization event: purchases.\n"
            ."Spend: $10.00\n"
            ."Impressions: 500\n"
            ."Daily history: 2 of 30 expected days on file. Meta learning stage is not on file; campaign is paused on Meta. Meta reports 2 results. Check Events Manager.\n"
            ."The bottleneck. Delivery is constrained.\n";

        $presentation = CampaignMarketingPlanPresenter::forRow([
            'platform' => 'linkedin',
            'review' => ['analysis' => $analysis],
        ]);

        $html = $presentation['steps'][0]['html'];

        $this->assertStringNotContainsString('Meta learning stage', $html);
        $this->assertStringNotContainsString('paused on Meta', $html);
        $this->assertStringNotContainsString('Meta reports', $html);
        $this->assertStringNotContainsString('Events Manager', $html);
        $this->assertStringContainsString('LinkedIn learning stage', $html);
        $this->assertStringContainsString('paused on LinkedIn', $html);
        $this->assertStringContainsString('LinkedIn reports', $html);
        $this->assertStringContainsString('Campaign Manager and conversion tracking', $html);
    }

    public function test_it_does_not_split_metric_grid_when_metrics_have_notes_or_missing_status(): void
    {
        $analysis = "Current performance. Optimization event: leads.\n"
            ."Spend: $0.00\n"
            ."Impressions: 29\n"
            ."Clicks: 0\n"
            ."Link clicks: 0\n"
            ."Cost per recorded landing page view, 7-day ad-set delivery: $20.15.\n"
            ."Conversions recorded in the window: 0.\n"
            ."Internal results: 0 reported; internal outcome data is unavailable.\n"
            ."Quality ranking: not on file\n"
            ."Audience size: unavailable\n"
            ."Per-ad spend, Ad_1_19Aug2026 (1556623856): $0.00.\n"
            ."Daily history: 27 of 30 expected days on file.\n"
            ."The bottleneck. Delivery is too thin.\n";

        $presentation = CampaignMarketingPlanPresenter::forRow([
            'platform' => 'linkedin',
            'review' => ['analysis' => $analysis],
        ]);

        $html = $presentation['steps'][0]['html'];

        $this->assertSame(1, substr_count($html, 'mb-perf-analysis-metrics'));
        $this->assertStringContainsString('>Cost per recorded landing page view, 7-day ad-set delivery</dt><dd>$20.15</dd>', $html);
        $this->assertStringContainsString('>Conversions recorded in the window</dt><dd>0</dd>', $html);
        $this->assertStringContainsString('>Internal results</dt><dd>0</dd>', $html);
        $this->assertStringContainsString('>Quality ranking</dt><dd>not on file</dd>', $html);
        $this->assertStringContainsString('>Audience size</dt><dd>unavailable</dd>', $html);
        $this->assertStringContainsString('>Per-ad spend, Ad_1_19Aug2026 (1556623856)</dt><dd>$0.00</dd>', $html);
    }

    public function test_it_cleans_robotic_bottleneck_boilerplate_and_prompt_leakage(): void
    {
        $rawBottleneck = "Current Performance\nSpend: $0.00\n\nThe Bottleneck\n"
            .'No delivery yet at a level that supports a diagnosis: 58 impressions, no clicks, and no spend in the seven-day window. '
            .'Tracking has no platform or internal conversions on file; the funnel has too little activity to assess, economics are inconclusive, and stability cannot be judged. '
            .'The campaign name identifies Attestpath as a SOC 2 website-conversion offer, but the ad copy and landing text do not specify the offer or buyer. '
            ."SOC 2 software pages commonly explain evidence collection and audit readiness and invite buyers to see the product; that is category context, not evidence that this ad or its destination makes those promises. ([attestpath.ai](https://attestpath.ai/soc-2?utm_source=openai))\n\n"
            ."Proposed Changes\n1. Inspect delivery settings.\n";

        $presentation = CampaignMarketingPlanPresenter::forRow([
            'platform' => 'linkedin',
            'review' => ['analysis' => $rawBottleneck],
        ]);

        $html = $presentation['steps'][0]['html'];

        $this->assertStringNotContainsString('category context, not evidence', $html);
        $this->assertStringNotContainsString('utm_source=openai', $html);
        $this->assertStringNotContainsString('supports a diagnosis', $html);
        $this->assertStringNotContainsString('the funnel has too little activity to assess, economics are inconclusive', $html);

        $this->assertStringContainsString('Delivery is the primary constraint: 58 impressions, no clicks, and no spend in the seven-day window.', $html);
        $this->assertStringContainsString('downstream funnel and conversion economics cannot yet be assessed.', $html);
    }
}
