<?php

namespace Tests\Feature;

use App\Campaigns\PerformanceBoard;
use App\Models\Campaign;
use App\Models\CampaignDecision;
use App\Models\CampaignPerformanceSuggestion;
use App\Models\CampaignPerformanceVerdictLog;
use App\Models\GoogleAdsCampaign;
use App\Models\User;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Schema;
use Tests\Concerns\CreatesAdopsWhaleTables;
use Tests\TestCase;

class CampaignPerformancePageTest extends TestCase
{
    use CreatesAdopsWhaleTables;
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();

        $this->createAdopsWhaleTables();
    }

    public function test_the_owner_sees_name_spend_and_reason(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        $this->seedBoard($user, 'Italy packages', '1201', 12.10, "Checked the last 7 days.\nImprove the creative.\n800 impressions produced 0 clicks.", [
            'trend' => 'improving',
            'trend_summary' => 'CPC improved 20% vs prior 7 days.',
            'marketing_diagnosis' => [
                'primary_lever' => 'improve_creative',
                'plan' => [
                    'Checked the last 7 days.',
                    'Improve the creative.',
                    '800 impressions produced 0 clicks.',
                ],
            ],
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance'))
            ->assertOk()
            ->assertSee('Campaign performance', false)
            ->assertSee('title="Campaign performance"', false)
            ->assertSee('bi-graph-up-arrow', false)
            ->assertSee('Italy packages', false)
            ->assertSee('$12.10', false)
            ->assertSee('Pause', false)
            ->assertSee('7-day spend', false)
            ->assertSee('7-day impressions', false)
            ->assertSee('View details', false)
            ->assertSee('Improving', false)
            ->assertSee('Whale 7-day', false)
            ->assertSee('Impr 7d', false)
            ->assertSee('Pause the campaign and stop all spend.', false);
    }

    public function test_guests_are_redirected_to_login(): void
    {
        $this->get(route('campaigns.performance'))
            ->assertRedirect(route('login'));
    }

    public function test_the_page_lives_at_campaign_performance(): void
    {
        $user = User::factory()->create();

        $this->actingAs($user)
            ->get('/campaign-performance')
            ->assertOk();

        $this->actingAs($user)
            ->get('/campaigns')
            ->assertRedirect('/campaign-performance');
    }

    public function test_another_users_campaign_is_not_listed(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $owner = User::factory()->create();
        $stranger = User::factory()->create();
        $this->seedBoard($stranger, 'Secret campaign', '9999', 40.00, 'Keep this secret.');

        $this->actingAs($owner)
            ->get(route('campaigns.performance'))
            ->assertOk()
            ->assertDontSee('Secret campaign', false);

        $this->actingAs($owner)
            ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '9999']))
            ->assertNotFound();
    }

    public function test_the_page_does_not_call_ad_platforms(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        $this->seedBoard($user, 'Italy packages', '1201', 12.10, 'Pause this campaign.');

        Http::fake();

        $this->actingAs($user)
            ->get(route('campaigns.performance'))
            ->assertOk();

        $this->actingAs($user)
            ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '1201']))
            ->assertOk();

        Http::assertNothingSent();
    }

    public function test_detail_shows_the_ad_roster_and_hides_creative_cards_when_tracking_is_frozen(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        $this->seedBoard($user, 'Lucos Retargeting', '1201', 227.00, 'Check tracking first.', [
            'performance_strategy' => [
                'broken_step' => 'tracking',
                'primary_result_label' => 'subscriptions',
                'primary_result_event' => 'subscribe',
                'platform_results' => 0,
                'delivery' => [
                    'spend_7d' => 227,
                    'landing_page_views' => 61,
                    'cost_per_lpv' => 3.72,
                    'frequency' => 1.63,
                ],
                'ad_roster' => [
                    'frozen' => true,
                    'ads' => [
                        [
                            'ad_id' => 'winner-1',
                            'name' => 'New Leads Ad – Copy',
                            'headline' => 'Lucos vs Copilot vs Cursor',
                            'spend' => 78.52,
                            'impressions' => 1700,
                            'clicks' => 80,
                            'ctr_percent' => 4.71,
                            'cpc' => 1.96,
                            'label' => 'winner',
                            'duplicate_copy' => false,
                        ],
                        [
                            'ad_id' => 'early-1',
                            'name' => 'New Leads Ad Copy 3',
                            'spend' => 11.96,
                            'impressions' => 130,
                            'clicks' => 4,
                            'ctr_percent' => 3.08,
                            'cpc' => 2.99,
                            'label' => 'too_early',
                        ],
                        [
                            'ad_id' => 'dead-1',
                            'name' => 'New Leads Ad - Copy',
                            'spend' => 0,
                            'impressions' => 0,
                            'clicks' => 0,
                            'label' => 'dead',
                            'duplicate_copy' => true,
                        ],
                    ],
                ],
            ],
            'review' => [
                'analysis' => 'Pause this campaign after tracking fails.',
                'creatives' => [[
                    'ad_id' => 'winner-1',
                    'current_headline' => 'Lucos vs Copilot vs Cursor',
                    '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',
                    'cta' => 'Sign up',
                    'problem' => 'The page never asks for subscribe.',
                ],
            ],
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '1201']))
            ->assertOk()
            ->assertSee('Ad-by-ad', false)
            ->assertSee('Winner', false)
            ->assertSee('Too early', false)
            ->assertSee('Dead', false)
            ->assertSee('Check Events Manager', false)
            ->assertSee('Ad fatigue', false)
            ->assertDontSee('Switch from Cursor', false)
            ->assertDontSee('Switch from Cursor page', false);

        $this->actingAs($user)
            ->get(route('campaigns.performance'))
            ->assertOk()
            ->assertSee('Lucos Retargeting', false)
            ->assertDontSee('Ad-by-ad', false)
            ->assertDontSee('Switch from Cursor', false);
    }

    public function test_status_chips_filter_the_listing(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        $this->seedBoard($user, 'Italy packages', '1201', 12.10, 'Pause this campaign.');

        $this->actingAs($user)
            ->get(route('campaigns.performance', ['status' => 'pause']))
            ->assertOk()
            ->assertSee('Italy packages', false);

        $this->actingAs($user)
            ->get(route('campaigns.performance', ['status' => 'continue']))
            ->assertOk()
            ->assertDontSee('Italy packages', false)
            ->assertSee('No live campaigns yet', false);
    }

    public function test_a_campaign_past_the_learning_window_does_not_say_day_n_of_m(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        $this->seedBoard($user, 'Italy packages', '1201', 52.65, 'Keep running.', [
            'days_live' => 7,
            'learning_window_days' => 3,
            'max_test_spend' => 40,
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '1201']))
            ->assertOk()
            ->assertSee('7 days live', false)
            ->assertSee('$52.65 spend vs $40.00 test cap', false)
            ->assertDontSee('Day 7 of 3', false);
    }

    public function test_learning_uses_the_start_date_and_spend_against_the_test_cap(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        $this->seedBoard($user, 'Lucos', '1201', 131.06, 'Hold comes first: 10 clicks are not enough.', [
            'campaign_profile' => [
                'started_at' => '2026-09-13',
            ],
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '1201']))
            ->assertOk()
            ->assertSee('10 days live', false)
            ->assertSee('$131.06 spend vs $40.00 test cap', false)
            ->assertDontSee('Learning day 1 of 3', false)
            ->assertDontSee('$131.06 of $40.00 test spend', false);
    }

    public function test_what_to_do_follows_live_delivery_instead_of_the_saved_learning_hold(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        $this->seedAdopsCampaignMeta('1201', 'Lucos');
        $this->seedAdopsDaily('1201', '2026-09-20', 40, 20, 1000);
        $this->seedAdopsDaily('1201', '2026-09-21', 50, 25, 1200);
        $this->seedAdopsDaily('1201', '2026-09-22', 41.06, 15, 800);
        $this->seedBoard($user, 'Lucos', '1201', 10, 'Hold comes first: the campaign is in its learning period, and 10 clicks are not enough to choose among spending more, improving creative, or fixing the landing page.', [
            'campaign_profile' => [
                'started_at' => '2026-09-13',
                'daily_budget' => 10,
            ],
            'marketing_diagnosis' => [
                'primary_lever' => 'hold',
                'window_used' => '7d',
                'plan' => [
                    'Hold comes first: the campaign is in its learning period, and 10 clicks are not enough to choose among spending more, improving creative, or fixing the landing page.',
                    'Leave the $10.00 daily budget unchanged while the campaign is learning.',
                ],
            ],
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '1201']))
            ->assertOk()
            ->assertSee('10 days live', false)
            ->assertSee('$131.06 spend vs $40.00 test cap', false)
            ->assertSee('$131.06', false)
            ->assertDontSee('10 clicks are not enough', false)
            ->assertDontSee('Learning day 1 of 3', false)
            ->assertDontSee('while the campaign is learning', false);
    }

    public function test_the_detail_page_lists_historic_daily_stats(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        $this->seedBoard($user, 'Italy packages', '1201', 12.10, 'Pause this campaign.', [
            'trend' => 'improving',
            'trend_summary' => 'CPC improved 20% vs prior 7 days.',
            'verdicts' => [
                'run_type' => 'daily',
                'windows' => [
                    '3h' => [
                        'window' => '3h',
                        'from' => '2026-09-22 09:00:00',
                        'to' => '2026-09-22 11:00:00',
                        'spend' => 0,
                        'clicks' => 0,
                        'cpc' => null,
                        'verdict' => 'pause',
                        'reason' => '3H: $0.00 spend, 0 clicks. Suggestion: pause this campaign.',
                    ],
                    '7d' => [
                        'window' => '7d',
                        'from' => '2026-09-16 00:00:00',
                        'to' => '2026-09-22 00:00:00',
                        'spend' => 12.10,
                        'clicks' => 0,
                        'cpc' => null,
                        'verdict' => 'pause',
                        'reason' => '7D: $12.10 spend, 0 clicks. Suggestion: pause this campaign.',
                    ],
                ],
            ],
        ]);

        $this->seedAdopsCampaignMeta('1201', 'Italy packages');
        $this->seedAdopsDaily('1201', '2026-09-21', 8.50, 2, 400);
        $this->seedAdopsDaily('1201', '2026-09-22', 12.10, 0, 800);
        $this->seedAdopsHourly('1201', '2026-09-21 10:00:00', 3.00, 1, 150);
        $this->seedAdopsHourly('1201', '2026-09-21 14:00:00', 5.50, 1, 250);

        $this->actingAs($user)
            ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '1201']))
            ->assertOk()
            ->assertSee('Italy packages', false)
            ->assertSee('Pause the campaign and stop all spend.', false)
            ->assertSee('pause this campaign.', false)
            ->assertSee('Daily history', false)
            ->assertSee('mb-perf-day-entry', false)
            ->assertSee('Hourly breakdown', false)
            ->assertSee('10:00 AM', false)
            ->assertSee('2:00 PM', false)
            ->assertSee('2026-09-21', false)
            ->assertSee('2026-09-22', false)
            ->assertSee('$8.50', false)
            ->assertSee('7-day spend', false)
            ->assertSee('CPC improved 20% vs prior 7 days.', false)
            ->assertSee('Daily performance', false)
            ->assertDontSee('ROI conversions', false)
            ->assertSee('data-perf-range-toggle', false)
            ->assertSee('data-perf-range-min="2026-06-25"', false)
            ->assertSee('data-perf-range-max="2026-09-22"', false)
            ->assertSee('Date range', false)
            ->assertSee('Recommendation', false)
            ->assertSee('3H:', false)
            ->assertSee('7D:', false)
            ->assertSee('mb-perf-chart', false)
            ->assertSee('mb-perf-line', false);
    }

    public function test_the_detail_page_shows_roi_stats_when_rows_exist_for_the_campaign(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        $this->seedBoard($user, 'Italy packages', '1201', 12.10, 'Pause this campaign.');
        $this->seedAdopsCampaignMeta('1201', 'Italy packages');

        Schema::connection('whale')->dropIfExists('roi_dashboard_campaign_stats');
        Schema::connection('whale')->create('roi_dashboard_campaign_stats', function (Blueprint $table): void {
            $table->id();
            $table->date('date');
            $table->string('platform');
            $table->string('campaign_id');
            $table->decimal('spent', 12, 2)->default(0);
            $table->decimal('conversions', 12, 4)->default(0);
            $table->decimal('subscriptions', 12, 4)->default(0);
            $table->decimal('cancellations', 12, 4)->default(0);
            $table->decimal('installs', 12, 4)->default(0);
            $table->decimal('bookings', 12, 4)->default(0);
            $table->decimal('leads', 12, 4)->default(0);
            $table->decimal('estimated_revenue', 12, 4)->default(0);
            $table->decimal('arb_orders', 12, 4)->default(0);
            $table->decimal('arb_sales_amount', 12, 4)->default(0);
        });
        DB::connection('whale')->table('roi_dashboard_campaign_stats')->insert([
            [
                'date' => '2026-09-01',
                'platform' => 'Meta',
                'campaign_id' => '1201',
                'spent' => 80,
                'conversions' => 100,
                'subscriptions' => 0,
                'cancellations' => 0,
                'installs' => 0,
                'bookings' => 0,
                'leads' => 0,
                'estimated_revenue' => 0,
                'arb_orders' => 0,
                'arb_sales_amount' => 0,
            ],
            [
                'date' => '2026-09-22',
                'platform' => 'Meta',
                'campaign_id' => '1201',
                'spent' => 5,
                'conversions' => 6,
                'subscriptions' => 1,
                'cancellations' => 0,
                'installs' => 2,
                'bookings' => 0,
                'leads' => 4,
                'estimated_revenue' => 3,
                'arb_orders' => 1,
                'arb_sales_amount' => 9,
            ],
            [
                'date' => '2026-09-21',
                'platform' => 'Meta',
                'campaign_id' => '1201',
                'spent' => 2,
                'conversions' => 4,
                'subscriptions' => 0,
                'cancellations' => 0,
                'installs' => 0,
                'bookings' => 0,
                'leads' => 0,
                'estimated_revenue' => 0,
                'arb_orders' => 0,
                'arb_sales_amount' => 0,
            ],
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '1201']))
            ->assertOk()
            ->assertSee('data-roi-range="7"', false)
            ->assertSee('ROI spent', false)
            ->assertSee('ROI conversions', false)
            ->assertSee('7 days · 2026-09-16 – 2026-09-22', false)
            ->assertSeeInOrder(['data-roi-total="spent"', '$7.00'], false)
            ->assertSeeInOrder(['data-roi-total="conversions"', '10.00'], false)
            ->assertSee('ROI sales', false)
            ->assertSeeInOrder(['data-roi-total="sales"', '$9.00'], false);

        Schema::connection('whale')->dropIfExists('roi_dashboard_campaign_stats');
    }

    public function test_the_detail_profile_shows_whale_objective_and_region(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        $schema = Schema::connection('whale');

        if (! $schema->hasColumn('arb_adops_campaigns', 'objective')) {
            $schema->table('arb_adops_campaigns', function (Blueprint $table): void {
                $table->string('objective')->nullable();
            });
        }

        $schema->dropIfExists('arb_adops_targeting');
        $schema->create('arb_adops_targeting', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('entity_level');
            $table->string('entity_id');
            $table->text('countries')->nullable();
            $table->text('regions')->nullable();
        });
        $schema->dropIfExists('arb_adops_stats_geo_daily_202609');
        $schema->create('arb_adops_stats_geo_daily_202609', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('campaign_id');
            $table->date('stat_date');
            $table->string('country')->nullable();
            $table->string('region')->nullable();
        });
        $schema->dropIfExists('arb_adops_stats_breakdown_daily_202609');
        $schema->create('arb_adops_stats_breakdown_daily_202609', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('campaign_id');
            $table->string('dimension');
            $table->string('value_1')->nullable();
        });

        try {
            $this->seedAdopsCampaignMeta('88001', 'Country campaign');
            $this->seedAdopsCampaignMeta('88002', 'Region campaign');
            $this->seedAdopsCampaignMeta('88003', 'Geo campaign');
            $this->seedAdopsCampaignMeta('88004', 'Breakdown campaign');
            DB::connection('whale')->table('arb_adops_campaigns')->where('campaign_id', '88001')->update(['objective' => 'OUTCOME_LEADS']);
            DB::connection('whale')->table('arb_adops_campaigns')->where('campaign_id', '88002')->update(['objective' => 'OUTCOME_SALES']);
            DB::connection('whale')->table('arb_adops_adsets')->insert([
                ['platform' => 'meta', 'account_id' => 'act_111', 'campaign_id' => '88001', 'adset_id' => 'adset-88001', 'name' => 'US ad set'],
                ['platform' => 'meta', 'account_id' => 'act_111', 'campaign_id' => '88002', 'adset_id' => 'adset-88002', 'name' => 'State ad set'],
            ]);
            DB::connection('whale')->table('arb_adops_targeting')->insert([
                [
                    'platform' => 'meta',
                    'entity_level' => 'adset',
                    'entity_id' => 'adset-88001',
                    'countries' => '["US"]',
                    'regions' => null,
                ],
                [
                    'platform' => 'meta',
                    'entity_level' => 'adset',
                    'entity_id' => 'adset-88002',
                    'countries' => '["US"]',
                    'regions' => json_encode([
                        ['name' => 'California', 'country' => 'US'],
                        ['name' => 'New York', 'country' => 'US'],
                    ]),
                ],
            ]);
            DB::connection('whale')->table('arb_adops_stats_geo_daily_202609')->insert([
                'platform' => 'meta',
                'campaign_id' => '88003',
                'stat_date' => '2026-09-20',
                'country' => 'GB',
                'region' => '',
            ]);
            DB::connection('whale')->table('arb_adops_stats_breakdown_daily_202609')->insert([
                'platform' => 'meta',
                'campaign_id' => '88004',
                'dimension' => 'region',
                'value_1' => 'Texas',
            ]);

            $this->seedBoard($user, 'Country campaign', '88001', 10, 'Keep going.');
            $this->seedBoard($user, 'Region campaign', '88002', 10, 'Keep going.');
            $this->seedBoard($user, 'Geo campaign', '88003', 10, 'Keep going.');
            $this->seedBoard($user, 'Breakdown campaign', '88004', 10, 'Keep going.');

            $this->actingAs($user)
                ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '88001']))
                ->assertOk()
                ->assertSeeInOrder(['Objective', 'OUTCOME_LEADS', 'Region', 'US'], false);

            $this->actingAs($user)
                ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '88002']))
                ->assertOk()
                ->assertSeeInOrder(['Objective', 'OUTCOME_SALES', 'Region', 'California, New York'], false);

            $this->actingAs($user)
                ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '88003']))
                ->assertOk()
                ->assertSeeInOrder(['Region', 'GB'], false);

            $this->actingAs($user)
                ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '88004']))
                ->assertOk()
                ->assertSeeInOrder(['Region', 'Texas'], false);
        } finally {
            $schema->dropIfExists('arb_adops_targeting');
            $schema->dropIfExists('arb_adops_stats_geo_daily_202609');
            $schema->dropIfExists('arb_adops_stats_breakdown_daily_202609');
        }
    }

    public function test_the_detail_history_table_is_paginated(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        config(['campaign-performance.adops_list_all' => true]);

        $this->seedAdopsCampaignMeta('1201', 'Italy packages');

        foreach (range(0, 11) as $offset) {
            $this->seedAdopsDaily(
                '1201',
                now()->subDays(11 - $offset)->toDateString(),
                $offset === 0 ? 1.11 : ($offset === 11 ? 9.99 : 2.00),
                1,
            );
        }

        $this->actingAs($user)
            ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '1201']))
            ->assertOk()
            ->assertSee('Daily performance', false)
            ->assertSee('Whale days loaded for this page', false)
            ->assertSee('$9.99', false);
    }

    public function test_a_whale_campaign_without_a_local_row_still_opens(): void
    {
        $this->travelTo('2026-09-22 12:00:00');
        config(['campaign-performance.adops_list_all' => true]);

        $user = User::factory()->create();

        $this->seedAdopsCampaignMeta('120251607606470626', 'Campaign 120251607606470626');
        $this->seedAdopsDaily('120251607606470626', '2026-09-22', 5.00, 1, 100);

        $this->actingAs($user)
            ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '120251607606470626']))
            ->assertOk()
            ->assertSee('Campaign 120251607606470626', false)
            ->assertSee('Daily history', false)
            ->assertSee('7-day spend', false)
            ->assertSee('$5.00', false);
    }

    public function test_the_campaign_page_shows_the_90_day_totals_once_when_the_last_week_is_empty(): void
    {
        $this->travelTo('2026-09-22 12:00:00');
        config(['campaign-performance.adops_list_all' => true]);

        $user = User::factory()->create();
        $this->seedAdopsCampaignMeta('1209', 'Older delivery');
        $this->seedAdopsDaily('1209', '2026-08-13', 80.00, 10, 1000);
        $this->seedAdopsDaily('1209', '2026-09-22', 0, 0, 0);

        $this->actingAs($user)
            ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '1209']))
            ->assertOk()
            ->assertSee('90-day spend', false)
            ->assertSee('$80.00', false)
            ->assertSee('90-day clicks', false)
            ->assertSee('10', false)
            ->assertDontSee('7-day spend', false);

        $this->actingAs($user)
            ->get(route('campaigns.performance'))
            ->assertOk()
            ->assertSee('Spend 90d', false)
            ->assertSee('Whale 90-day', false)
            ->assertSee('$80.00', false);
    }

    public function test_guests_cannot_open_a_campaign_detail(): void
    {
        $this->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '1201']))
            ->assertRedirect(route('login'));
    }

    public function test_the_detail_page_shows_an_expandable_verdict_log(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        $this->seedBoard($user, 'Italy packages', '1201', 12.10, 'Pause this campaign.');

        CampaignPerformanceVerdictLog::create([
            'user_id' => $user->id,
            'platform' => 'meta',
            'external_campaign_id' => '1201',
            'evaluated_at' => now(),
            'run_type' => 'daily',
            'final_verdict' => 'stop',
            'final_reason' => 'Multiple windows agree: pause campaign now.',
            'windows' => [
                '3h' => [
                    'window' => '3h',
                    'verdict' => 'pause',
                    'spend' => 4.2,
                    'clicks' => 0,
                    'cpc' => null,
                    'reason' => '3H: $4.20 spend, 0 clicks. Suggestion: pause this campaign.',
                ],
                '7d' => [
                    'window' => '7d',
                    'verdict' => 'pause',
                    'spend' => 42.0,
                    'clicks' => 0,
                    'cpc' => null,
                    'reason' => '7D: $42.00 spend, 0 clicks. Suggestion: pause this campaign.',
                ],
            ],
            'source' => 'php',
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '1201']))
            ->assertOk()
            ->assertSee('Campaign profile', false)
            ->assertSee('Legacy verdict log', false)
            ->assertSee('mb-perf-log-entry', false)
            ->assertSee('Multiple windows agree: pause campaign now.', false)
            ->assertSee('3H: $4.20 spend, 0 clicks. Suggestion: pause this campaign.', false);
    }

    public function test_verdict_log_filters_by_run_type(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        $this->seedBoard($user, 'Italy packages', '1201', 12.10, 'Pause this campaign.');

        CampaignPerformanceVerdictLog::create([
            'user_id' => $user->id,
            'platform' => 'meta',
            'external_campaign_id' => '1201',
            'evaluated_at' => now()->subHour(),
            'run_type' => 'hourly',
            'final_verdict' => 'pause',
            'final_reason' => 'Hourly intraday pause signal.',
            'windows' => [
                '3h' => ['window' => '3h', 'verdict' => 'pause', 'spend' => 4.2, 'clicks' => 0, 'reason' => 'Hourly window bad.'],
            ],
            'hourly_verdict' => ['verdict' => 'pause', 'reason' => 'Hourly check: pause.'],
            'source' => 'php',
        ]);

        CampaignPerformanceVerdictLog::create([
            'user_id' => $user->id,
            'platform' => 'meta',
            'external_campaign_id' => '1201',
            'evaluated_at' => now(),
            'run_type' => 'daily',
            'final_verdict' => 'stop',
            'final_reason' => 'Daily stop signal.',
            'windows' => [
                '7d' => ['window' => '7d', 'verdict' => 'pause', 'spend' => 42.0, 'clicks' => 0, 'reason' => 'Daily window bad.'],
            ],
            'source' => 'php',
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance.show', [
                'platform' => 'meta',
                'campaign' => '1201',
                'log_run_type' => 'hourly',
            ]))
            ->assertOk()
            ->assertSee('Hourly intraday pause signal.', false)
            ->assertDontSee('Daily window bad.', false);
    }

    public function test_hourly_only_campaigns_still_appear_on_the_listing(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();

        CampaignPerformanceSuggestion::create([
            'user_id' => $user->id,
            'platform' => 'meta',
            'external_campaign_id' => '120252303208750683',
            'status' => 'no_action',
            'source' => 'php',
            'reason' => 'Keep monitoring.',
            'action_state' => 'pending',
            'snapshot' => [
                'campaign' => 'WirelessHeadphones_OfficeDepot_20260717',
            ],
            'suggested_at' => now(),
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance'))
            ->assertOk()
            ->assertSee('WirelessHeadphones_OfficeDepot_20260717', false)
            ->assertSee('120252303208750683', false);
    }

    public function test_suggestion_section_shows_affiliate_conversion_and_cpc(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        $this->seedBoard($user, 'Italy packages', '1201', 12.10, 'Continue monitoring.', [
            'affiliate' => [
                'matched' => true,
                'campaign_id' => '1201',
                '3d' => [
                    'clicks' => 10,
                    'sum_cpc' => 1.50,
                    'orders' => 1,
                    'net_revenue' => 25.00,
                ],
                '7d' => [
                    'clicks' => 42,
                    'sum_cpc' => 5.25,
                    'orders' => 3,
                    'net_revenue' => 89.44,
                ],
            ],
            'verdicts' => [
                'run_type' => 'daily',
                'windows' => [
                    '3d' => [
                        'window' => '3d',
                        'from' => '2026-09-20 00:00:00',
                        'to' => '2026-09-22 00:00:00',
                        'spend' => 8.00,
                        'clicks' => 2,
                        'cpc' => 4.00,
                        'verdict' => 'no_action',
                        'reason' => '3D: within test budget.',
                    ],
                    '7d' => [
                        'window' => '7d',
                        'from' => '2026-09-16 00:00:00',
                        'to' => '2026-09-22 00:00:00',
                        'spend' => 12.10,
                        'clicks' => 0,
                        'cpc' => null,
                        'verdict' => 'no_action',
                        'reason' => '7D: affiliate revenue supports continue.',
                    ],
                ],
            ],
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '1201']))
            ->assertOk()
            ->assertSee('Recommendation', false)
            ->assertSee('Meta conversion', false)
            ->assertSee('Whale DB — actual conversion (7 days)', false)
            ->assertSee('Sum CPC', false)
            ->assertSee('$89.44', false)
            ->assertSee('$1.50', false)
            ->assertSee('7D: affiliate revenue supports continue.', false);
    }

    public function test_the_decision_states_how_many_of_the_last_30_days_it_used(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        $this->seedAdopsCampaignMeta('1201', 'Italy packages');
        $this->seedAdopsDaily('1201', '2026-09-20', 10, 2, 100);
        $this->seedAdopsDaily('1201', '2026-09-21', 15, 3, 200);
        $this->seedBoard($user, 'Italy packages', '1201', 12.10, "Checked the last 7 days.\nImprove the creative.\n800 impressions produced 0 clicks.", [
            'marketing_diagnosis' => [
                'primary_lever' => 'improve_creative',
                'window_used' => '7d',
                'plan' => [
                    'Checked the last 7 days.',
                    'Improve the creative.',
                    '800 impressions produced 0 clicks.',
                ],
            ],
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance.show', ['platform' => 'meta', 'campaign' => '1201']))
            ->assertOk()
            ->assertSee('$25.00', false)
            ->assertDontSee('Checked the last 7 days.', false);
    }

    public function test_the_list_uses_snapshot_name_over_placeholder_local_name(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();

        CampaignPerformanceSuggestion::create([
            'user_id' => $user->id,
            'platform' => 'meta',
            'external_campaign_id' => '1201',
            'local_campaign_id' => null,
            'status' => 'pause',
            'source' => 'php',
            'reason' => 'Pause this campaign.',
            'action_state' => 'pending',
            'snapshot' => [
                'campaign' => 'Italy packages live',
            ],
            'suggested_at' => now(),
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance'))
            ->assertOk()
            ->assertSee('Italy packages live', false)
            ->assertDontSee('Campaign 1201', false);
    }

    public function test_linkedin_platform_filter_does_not_show_a_coming_soon_notice(): void
    {
        $user = User::factory()->create();

        $this->actingAs($user)
            ->get(route('campaigns.performance', ['platform' => 'linkedin']))
            ->assertOk()
            ->assertDontSee('coming soon', false)
            ->assertDontSee('in development', false)
            ->assertSee('No live campaigns yet', false);
    }

    public function test_linkedin_published_campaigns_do_not_show_an_info_notice(): void
    {
        $user = User::factory()->create();

        Campaign::create([
            'user_id' => $user->id,
            'name' => 'LinkedIn promo',
            'platform' => 'linkedin',
            'status' => 'published',
            'budget' => 50,
            'ad_account_id' => '123',
            'external_campaign_id' => 'urn:li:sponsoredCampaign:999',
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance'))
            ->assertOk()
            ->assertDontSee('LinkedIn campaign performance is in development', false)
            ->assertDontSee('Google performance is not in Whale yet', false);
    }

    public function test_the_top_search_matches_a_campaign_name_or_id(): void
    {
        $this->travelTo('2026-10-06 15:00:00');
        $user = User::factory()->create();
        $this->seedBoard($user, 'Compression socks', '120210204616200436', 10, 'Keep the socks campaign.');
        $this->seedBoard($user, 'Dark armpit remover', '120210203455400436', 8, 'Pause the remover campaign.');
        $this->seedDecision($user, '120210204616200436', 'Compression socks', 'pause', 'PAUSE', 'Pause socks.', '2026-10-06 08:00:00');
        $this->seedDecision($user, '120210203455400436', 'Dark armpit remover', 'watch', 'NONE', 'Watch the remover.', '2026-10-06 09:00:00');

        $this->actingAs($user)
            ->get(route('campaigns.performance', ['q' => 'compression', 'date' => '2026-10-06']))
            ->assertOk()
            ->assertSee('Search by name or campaign ID', false)
            ->assertSee('Compression socks', false)
            ->assertDontSee('Dark armpit remover', false);

        $this->actingAs($user)
            ->get(route('campaigns.performance', ['q' => '120210203455400436', 'date' => '2026-10-06']))
            ->assertOk()
            ->assertSee('Dark armpit remover', false)
            ->assertDontSee('Compression socks', false);
    }

    public function test_data_issue_decisions_are_listed_after_other_verdicts(): void
    {
        $this->travelTo('2026-10-06 15:00:00');
        $user = User::factory()->create();

        $this->seedDecision($user, '1209', 'Missing metrics', 'data_issue', 'NONE', 'No hourly or daily rows in Whale.', '2026-10-06 14:50:00');
        $this->seedDecision($user, '1208', 'Still spending', 'pause', 'PAUSE', 'Pause the spending campaign.', '2026-10-06 08:00:00');

        $decisions = app(PerformanceBoard::class)->decisionsOnDate(now())->getCollection();
        $ids = $decisions->pluck('external_campaign_id')->all();

        $this->assertSame(['1208', '1209'], $ids);
        $this->assertIsArray($decisions->first()['ad_set_optimization']);
    }

    public function test_data_issue_campaigns_stay_below_higher_spend_rows(): void
    {
        $this->travelTo('2026-09-22 12:00:00');
        $user = User::factory()->create();
        $this->seedBoard($user, 'Broken ingest', '1301', 90, 'No hourly or daily rows in Whale.', [], 'data_issue');
        $this->seedBoard($user, 'Small spender', '1302', 4, 'Pause the small spender.');

        $ids = app(PerformanceBoard::class)
            ->forUser($user, ['per_page' => 10])['rows']
            ->getCollection()
            ->pluck('external_campaign_id')
            ->all();

        $this->assertSame(['1302', '1301'], $ids);
    }

    public function test_the_date_view_shows_the_latest_decision_per_campaign_for_that_day(): void
    {
        $this->travelTo('2026-10-06 15:00:00');
        $user = User::factory()->create();

        $this->seedDecision($user, '1201', 'Italy packages', 'pause', 'PAUSE', 'Morning pause.', '2026-10-06 08:00:00');
        $this->seedDecision($user, '1201', 'Italy packages', 'maintain', 'NONE', 'Afternoon keep it.', '2026-10-06 14:00:00');
        $this->seedDecision($user, '1202', 'Spain packages', 'scale_up', 'INCREASE_BUDGET', 'Scale Spain.', '2026-10-06 14:30:00', 10);
        $this->seedDecision($user, '1203', 'Yesterday only', 'pause', 'PAUSE', 'Old day.', '2026-10-05 14:00:00');

        $viewer = User::factory()->create();

        $this->actingAs($viewer)
            ->get(route('campaigns.performance', ['date' => '2026-10-06']))
            ->assertOk()
            ->assertSee('Decisions for Oct 6, 2026', false)
            ->assertSee('Italy packages', false)
            ->assertSee('Spain packages', false)
            ->assertViewHas('decision_rows', fn ($rows): bool => $rows->contains(
                fn (array $row): bool => $row['external_campaign_id'] === '1201' && $row['reason'] === 'Afternoon keep it.',
            ))
            ->assertDontSee('Pause the campaign', false)
            ->assertSee('Increase the daily budget by 10%.', false)
            ->assertDontSee('Morning pause.', false)
            ->assertDontSee('Yesterday only', false);
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private function seedBoard(User $user, string $name, string $externalId, float $spend, string $reason, array $snapshot = [], string $status = 'pause'): void
    {
        CampaignPerformanceSuggestion::create([
            'user_id' => $user->id,
            'platform' => 'meta',
            'external_campaign_id' => $externalId,
            'local_campaign_id' => null,
            'status' => $status,
            'source' => 'php',
            'reason' => $reason,
            'action_state' => 'pending',
            'snapshot' => array_merge([
                'campaign' => $name,
                'last_7_days' => [
                    'spend' => $spend,
                    'clicks' => 0,
                    'impressions' => 800,
                ],
                'lifetime' => [
                    'spend' => $spend,
                    'clicks' => 0,
                    'impressions' => 800,
                ],
            ], $snapshot),
            'suggested_at' => now(),
        ]);
    }

    private function seedDecision(
        User $user,
        string $externalId,
        string $name,
        string $verdict,
        string $action,
        string $reason,
        string $evaluatedAt,
        int $budgetChange = 0,
    ): void {
        CampaignDecision::query()->create([
            'user_id' => $user->id,
            'platform' => 'meta',
            'account_id' => 'act_111',
            'external_campaign_id' => $externalId,
            'campaign_name' => $name,
            'engine_version' => 'v2',
            'trigger' => 'scheduled_hourly',
            'evaluated_at' => $evaluatedAt,
            'verdict' => $verdict,
            'confidence' => 0.8,
            'recommended_action' => $action,
            'recommended_budget_change_percent' => $budgetChange,
            'reason' => $reason,
            'snapshot_json' => [
                'reason' => $reason,
                'ai_reason' => $reason,
                'windows' => [
                    '7d' => ['spend' => 12.1, 'clicks' => 4, 'impressions' => 100],
                ],
            ],
            'metrics_json' => [
                'windows' => [
                    '7d' => ['spend' => 12.1, 'clicks' => 4, 'impressions' => 100],
                ],
            ],
        ]);
    }

    public function test_owner_sees_published_linkedin_campaign_from_local_database(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        Campaign::create([
            'user_id' => $user->id,
            'name' => 'B2B Leads LinkedIn',
            'platform' => 'linkedin',
            'status' => 'published',
            'budget' => 50,
            'ad_account_id' => '556447014',
            'external_campaign_id' => '917007016',
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance'))
            ->assertOk()
            ->assertSee('B2B Leads LinkedIn', false)
            ->assertSee('LinkedIn', false)
            ->assertSee('917007016', false);
    }

    public function test_owner_sees_published_google_ads_campaign_from_local_database(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        GoogleAdsCampaign::create([
            'user_id' => $user->id,
            'name' => 'Google Search Campaign',
            'status' => 'ENABLED',
            'daily_budget' => 30,
            'google_campaign_id' => '88889999',
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance'))
            ->assertOk()
            ->assertSee('Google Search Campaign', false)
            ->assertSee('Google', false)
            ->assertSee('88889999', false);
    }

    public function test_platform_filter_works_for_linkedin_and_google(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        Campaign::create([
            'user_id' => $user->id,
            'name' => 'LinkedIn Campaign Alpha',
            'platform' => 'linkedin',
            'status' => 'published',
            'budget' => 50,
            'ad_account_id' => '556447014',
            'external_campaign_id' => '917007016',
        ]);
        GoogleAdsCampaign::create([
            'user_id' => $user->id,
            'name' => 'Google Campaign Beta',
            'status' => 'ENABLED',
            'daily_budget' => 30,
            'google_campaign_id' => '88889999',
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance', ['platform' => 'linkedin']))
            ->assertOk()
            ->assertSee('LinkedIn Campaign Alpha', false)
            ->assertDontSee('Google Campaign Beta', false);

        $this->actingAs($user)
            ->get(route('campaigns.performance', ['platform' => 'google']))
            ->assertOk()
            ->assertSee('Google Campaign Beta', false)
            ->assertDontSee('LinkedIn Campaign Alpha', false);
    }

    public function test_detail_view_shows_linkedin_campaign(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();
        Campaign::create([
            'user_id' => $user->id,
            'name' => 'LinkedIn Detail Campaign',
            'platform' => 'linkedin',
            'status' => 'published',
            'budget' => 75,
            'ad_account_id' => '556447014',
            'external_campaign_id' => '917007016',
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance.show', ['platform' => 'linkedin', 'campaign' => '917007016']))
            ->assertOk()
            ->assertSee('LinkedIn Detail Campaign', false)
            ->assertSee('LinkedIn', false);
    }

    public function test_performance_page_ui_has_platform_filter_on_top_and_proper_card_titles(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();

        $this->actingAs($user)
            ->get(route('campaigns.performance'))
            ->assertOk()
            ->assertSee('mb-platform-filter-bar', false)
            ->assertSee('All Platforms', false)
            ->assertSee('Google Ads', false)
            ->assertSee('LinkedIn', false)
            ->assertSee('Daily Optimization Decisions', false)
            ->assertSee('Decisions for Sep 22, 2026', false)
            ->assertSee('All Monitored Campaigns', false)
            ->assertSee('id="perf-card-decisions-body"', false)
            ->assertSee('id="perf-card-campaigns-body"', false)
            ->assertSee('class="collapse show"', false)
            ->assertSee('mb-card-collapse-toggle', false);
    }

    public function test_verdict_filter_chips_reflect_platform_campaigns_and_filter_both_cards(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();

        CampaignPerformanceSuggestion::create([
            'user_id' => $user->id,
            'platform' => 'linkedin',
            'external_campaign_id' => 'li-101',
            'status' => 'learning',
            'source' => 'php',
            'reason' => 'LinkedIn campaign in learning mode.',
            'action_state' => 'pending',
            'snapshot' => [
                'campaign' => 'LinkedIn Enterprise Ads',
                'last_7_days' => ['spend' => 24.0, 'clicks' => 5, 'impressions' => 120],
                'lifetime' => ['spend' => 24.0, 'clicks' => 5, 'impressions' => 120],
            ],
            'suggested_at' => now(),
        ]);
        CampaignDecision::create([
            'user_id' => $user->id,
            'platform' => 'linkedin',
            'account_id' => 'act_li_1',
            'external_campaign_id' => 'li-101',
            'campaign_name' => 'LinkedIn Enterprise Ads',
            'engine_version' => 'v2',
            'trigger' => 'scheduled_hourly',
            'evaluated_at' => '2026-09-22 10:00:00',
            'verdict' => 'learning',
            'confidence' => 0.8,
            'recommended_action' => 'Hold steady',
            'recommended_budget_change_percent' => 0,
            'reason' => 'Learning phase on LinkedIn',
            'snapshot_json' => [
                'windows' => ['7d' => ['spend' => 24.0, 'clicks' => 5, 'impressions' => 120]],
            ],
            'metrics_json' => [
                'windows' => ['7d' => ['spend' => 24.0, 'clicks' => 5, 'impressions' => 120]],
            ],
        ]);

        CampaignPerformanceSuggestion::create([
            'user_id' => $user->id,
            'platform' => 'linkedin',
            'external_campaign_id' => 'li-102',
            'status' => 'maintain',
            'source' => 'php',
            'reason' => 'LinkedIn campaign maintaining steady ROAS.',
            'action_state' => 'pending',
            'snapshot' => [
                'campaign' => 'LinkedIn Brand Awareness',
                'last_7_days' => ['spend' => 50.0, 'clicks' => 15, 'impressions' => 400],
                'lifetime' => ['spend' => 50.0, 'clicks' => 15, 'impressions' => 400],
            ],
            'suggested_at' => now(),
        ]);
        CampaignDecision::create([
            'user_id' => $user->id,
            'platform' => 'linkedin',
            'account_id' => 'act_li_1',
            'external_campaign_id' => 'li-102',
            'campaign_name' => 'LinkedIn Brand Awareness',
            'engine_version' => 'v2',
            'trigger' => 'scheduled_hourly',
            'evaluated_at' => '2026-09-22 10:00:00',
            'verdict' => 'maintain',
            'confidence' => 0.9,
            'recommended_action' => 'Keep running',
            'recommended_budget_change_percent' => 0,
            'reason' => 'Healthy delivery on LinkedIn',
            'snapshot_json' => [
                'windows' => ['7d' => ['spend' => 50.0, 'clicks' => 15, 'impressions' => 400]],
            ],
            'metrics_json' => [
                'windows' => ['7d' => ['spend' => 50.0, 'clicks' => 15, 'impressions' => 400]],
            ],
        ]);

        CampaignPerformanceSuggestion::create([
            'user_id' => $user->id,
            'platform' => 'meta',
            'external_campaign_id' => 'meta-201',
            'status' => 'pause',
            'source' => 'php',
            'reason' => 'Meta campaign high CPA.',
            'action_state' => 'pending',
            'snapshot' => [
                'campaign' => 'Meta Promo Campaign',
                'last_7_days' => ['spend' => 100.0, 'clicks' => 2, 'impressions' => 500],
                'lifetime' => ['spend' => 100.0, 'clicks' => 2, 'impressions' => 500],
            ],
            'suggested_at' => now(),
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance', ['platform' => 'linkedin']))
            ->assertOk()
            ->assertSee('LinkedIn Enterprise Ads', false)
            ->assertSee('LinkedIn Brand Awareness', false)
            ->assertDontSee('Meta Promo Campaign', false)
            ->assertSee('Learning <span class="mb-perf-chip-count">1</span>', false)
            ->assertSee('Maintain <span class="mb-perf-chip-count">1</span>', false)
            ->assertSee('Pause <span class="mb-perf-chip-count">0</span>', false);

        $this->actingAs($user)
            ->get(route('campaigns.performance', ['platform' => 'linkedin', 'status' => 'learning']))
            ->assertOk()
            ->assertSee('LinkedIn Enterprise Ads', false)
            ->assertDontSee('LinkedIn Brand Awareness', false)
            ->assertDontSee('Meta Promo Campaign', false);

        $this->actingAs($user)
            ->get(route('campaigns.performance', ['platform' => 'linkedin', 'status' => 'maintain']))
            ->assertOk()
            ->assertSee('LinkedIn Brand Awareness', false)
            ->assertDontSee('LinkedIn Enterprise Ads', false)
            ->assertDontSee('Meta Promo Campaign', false);
    }

    public function test_marketing_plan_analysis_metrics_render_with_metric_cell_elements(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();

        CampaignPerformanceSuggestion::create([
            'user_id' => $user->id,
            'platform' => 'linkedin',
            'external_campaign_id' => 'li-metrics-1',
            'status' => 'learning',
            'source' => 'php',
            'reason' => 'Review recommendation',
            'action_state' => 'pending',
            'snapshot' => [
                'campaign' => 'LinkedIn Metric Grid Campaign',
                'last_7_days' => ['spend' => 10.0, 'clicks' => 2, 'impressions' => 50],
                'lifetime' => ['spend' => 10.0, 'clicks' => 2, 'impressions' => 50],
                'review' => [
                    'analysis' => "Current performance\nSpend: 10.00\nImpressions: 50\nClicks: 2\n\nRecommendation\n1. Keep running.",
                ],
            ],
            'suggested_at' => now(),
        ]);

        $this->actingAs($user)
            ->get(route('campaigns.performance', ['platform' => 'linkedin']))
            ->assertOk()
            ->assertSee('mb-perf-analysis-metrics', false)
            ->assertSee('mb-perf-analysis-metric-cell', false)
            ->assertSee('>Spend</dt>', false)
            ->assertSee('>10.00</dd>', false);
    }

    public function test_roi_totals_preserve_numeric_string_campaign_ids(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();

        Campaign::create([
            'user_id' => $user->id,
            'platform' => 'meta',
            'external_campaign_id' => '23851234567890',
            'name' => 'ROI Numeric Campaign',
            'status' => 'ACTIVE',
            'budget' => 50.0,
        ]);

        $board = app(PerformanceBoard::class);
        $data = $board->forUser($user, ['platform' => 'meta', 'q' => 'ROI Numeric Campaign']);

        $campaignRow = $data['rows']->getCollection()->firstWhere('external_campaign_id', '23851234567890');
        $this->assertNotNull($campaignRow);
        $this->assertSame('ROI Numeric Campaign', $campaignRow['name']);
    }

    public function test_performance_page_uses_pill_bar_without_duplicate_select(): void
    {
        $this->travelTo('2026-09-22 12:00:00');

        $user = User::factory()->create();

        $this->actingAs($user)
            ->get(route('campaigns.performance'))
            ->assertOk()
            ->assertSee('mb-platform-pills', false)
            ->assertSee('mb-platform-pill', false)
            ->assertDontSee('name="platform" aria-label="Filter by platform"', false);
    }
}
