@php
    /**
     * The campaign as stored, with where each value came from.
     *
     * Rendered server side from the database rather than from the chat, so what
     * is shown and what would be published can never disagree.
     */
    $dot = fn (?string $source) => match ($source) {
        'user_stated' => ['bg-success', 'you said this'],
        'platform_returned' => ['bg-primary', 'returned by the platform'],
        'model_inferred' => ['bg-warning', 'worked out from context'],
        'fallback' => ['bg-danger', 'guessed, needs confirming'],
        default => ['bg-secondary-subtle', 'not set'],
    };

    $row = function (string $label, $value, ?string $source) use ($dot) {
        [$colour, $title] = $dot($source);

        return [$label, $value, $colour, $title];
    };

    $linkedinLivePrompt = function (string $label) use ($campaign): string {
        $name = $campaign->name;

        return match ($label) {
            'Daily budget', 'Lifetime budget' => 'Change the budget amount for '.$name.'. Call edit_linkedin_campaign. Do not switch daily and lifetime, and do not use a Meta tool.',
            'Bidding' => 'Change the bidding for '.$name.'. Call edit_linkedin_campaign. Do not use a Meta tool.',
            'Target cost' => 'Change the target cost for '.$name.'. Call edit_linkedin_campaign. Do not use a Meta tool.',
            'Schedule' => 'Change the end date for '.$name.'. A running LinkedIn campaign cannot move its start. Call edit_linkedin_campaign. Do not use a Meta tool.',
            'Placements' => 'Change the placements for '.$name.'. Call edit_linkedin_campaign with placements as an empty list so LinkedIn feed and Audience Network can both be picked. Do not use a Meta tool.',
            'Countries' => 'Change the locations for '.$name.'. Ask which place to search if none was named, then call edit_linkedin_campaign with location_query. LinkedIn\'s matches can be picked together. Do not use a Meta tool.',
            'Target audience' => 'Change the target audience for '.$name.'. Call edit_linkedin_campaign with audience as an empty list so LinkedIn audience attributes, matched audiences, and Audience Expansion can be picked. Do not use a Meta tool.',
            default => 'The '.$label.' for '.$name.' cannot be changed after it is on LinkedIn. Say that and do not try to change it.',
        };
    };

    /**
     * What this platform actually has, so the panel stops describing every
     * campaign as a Meta one.
     *
     * A Google campaign was shown a Facebook Page, an Instagram account and a
     * pixel, none of which it can ever hold, all reading "—" forever. An empty
     * row is not neutral: it reads as an unanswered question.
     *
     * Asked of the platform's own rules rather than listed here, so a platform
     * added later gets the right panel by declaring its rules and nothing else.
     */
    // Null for a conversation with no campaign yet, and for any caller that
    // renders this without saying which platform it is looking at, which shows
    // every row rather than silently hiding one.
    $rules ??= null;
    $platforms ??= null;

    /**
     * The platform's own word for a field, taken from its step list.
     *
     * Meta calls it a pixel and Google calls it a conversion action, and each
     * already says so in steps(). Reading the label from there means the panel
     * and the progress list can never drift apart, and neither needs its own
     * table of names.
     */
    $named = function (string $key, string $fallback) use ($rules): string {
        $label = collect($rules?->steps() ?? [])->firstWhere('key', $key)['label'] ?? $fallback;

        return ucfirst($label);
    };

    $has = function (string $field) use ($rules): bool {
        if (! $rules) {
            return true;
        }

        return match ($field) {
            'page' => $rules->requiresPage(),
            'placements' => $rules->placements() !== [],
            'instagram' => in_array('instagram', $rules->placements(), true),
            'devices' => $rules->key() !== 'linkedin',
            // No single objective decides it: the row is worth showing if this
            // platform has the concept at all.
            'pixel' => collect($rules->objectives())
                ->contains(fn (string $objective): bool => $rules->requiresPixel($objective)),
            // Asked of the flow, not of conversionEvent(), which LinkedIn also
            // answers: it maps objectives to events for its own publisher while
            // having no step to choose one and no tool that would accept it. A
            // row nothing can ever fill is the permanent grey dot this panel
            // already warns about above.
            'conversion_event' => collect($rules->steps())
                ->contains(fn (array $step): bool => ($step['key'] ?? null) === 'conversion_event'),
            default => true,
        };
    };

    $platformName = function ($key) use ($platforms): string {
        $platforms ??= app(\App\Campaigns\Platforms\Platforms::class);

        return $platforms->supports((string) $key)
            ? $platforms->for((string) $key)->name()
            : ucfirst((string) $key);
    };

    $selectedLocationRows = $campaign?->targetingSet?->locations()
        ->where('kind', '!=', 'country')
        ->orderBy('id')
        ->get(['country_code', 'display_label', 'operation']) ?? collect();
    $selectedPlaces = $selectedLocationRows
        ->map(fn ($place): string => $place->operation === 'exclude' ? 'Excluded: '.$place->display_label : $place->display_label)
        ->all();
    $narrowedCountries = in_array($campaign?->platform, ['meta', 'google'], true)
        ? $selectedLocationRows->where('operation', 'include')->pluck('country_code')->filter()->all()
        : [];
    $countryCodes = $campaign
        ? app(\App\Campaigns\Targeting\TargetingSelections::class)->countries($campaign)
        : [];
    $countrySummary = implode(', ', array_map(
        fn (string $code): string => in_array($code, $narrowedCountries, true)
            ? $code.' (selected places only)'
            : $code,
        $countryCodes,
    ));
    $linkedinPlaces = $campaign?->platform === 'linkedin'
        ? array_values(array_filter(array_map(
            fn (mixed $place): string => is_array($place) ? trim((string) ($place['name'] ?? '')) : '',
            (array) ($campaign->locations['linkedin_places'] ?? []),
        )))
        : [];
    if ($linkedinPlaces !== []) {
        $countrySummary = implode('; ', $linkedinPlaces);
    }
    $linkedinAudienceSummary = '';
    if ($campaign?->platform === 'linkedin') {
        $audienceParts = [];
        foreach ((array) ($campaign->audience['linkedin_facets'] ?? []) as $facet => $urns) {
            if (is_array($urns) && $urns !== []) {
                $audienceParts[] = \App\Services\LinkedIn\LinkedInTargetingFacets::label((string) $facet);
            }
        }
        $matchedNames = array_values(array_filter(array_map(
            fn (mixed $row): string => is_array($row) ? trim((string) ($row['name'] ?? '')) : '',
            (array) ($campaign->audience['linkedin_matched'] ?? []),
        )));
        if ($matchedNames !== []) {
            $audienceParts[] = implode(', ', array_slice($matchedNames, 0, 3));
        }
        if (array_key_exists('linkedin_audience_expansion', (array) ($campaign->meta ?? []))) {
            $audienceParts[] = ($campaign->meta['linkedin_audience_expansion'] ?? false) ? 'Expansion on' : 'Expansion off';
        }
        $linkedinAudienceSummary = implode('; ', $audienceParts);
    }

    foreach (['cities' => 'city', 'regions' => 'region'] as $field => $kind) {
        foreach ((array) ($campaign?->locations['meta_geo_locations'][$field] ?? []) as $place) {
            if (filled($place['key'] ?? null)) {
                $selectedPlaces[] = 'Imported Meta '.$kind.' ID '.$place['key'];
            }
        }
    }

    foreach ((array) ($campaign?->locations['google_location_criteria'] ?? []) as $criterion) {
        if (strtolower((string) ($criterion['target_type'] ?? '')) === 'country' && ! ($criterion['negative'] ?? false)) {
            continue;
        }

        $selectedPlaces[] = sprintf(
            'Imported Google %s%s: %s',
            ($criterion['negative'] ?? false) ? 'excluded ' : '',
            strtolower((string) ($criterion['target_type'] ?? 'location')),
            (string) ($criterion['name'] ?: $criterion['geo_target'] ?? 'unknown'),
        );
    }

    foreach ((array) ($campaign?->locations['google_proximity_criteria'] ?? []) as $proximity) {
        $selectedPlaces[] = sprintf(
            'Imported Google radius: %s %s around %s, %s',
            (string) ($proximity['radius'] ?? '?'),
            (string) ($proximity['radius_unit'] ?? '?'),
            (string) ($proximity['latitude'] ?? '?'),
            (string) ($proximity['longitude'] ?? '?'),
        );
    }

    $importedSearchKeywords = [];
    $importedGoogleAudiences = [];
    $importedMetaAudiences = [];
    $targetingOptions = (array) ($campaign?->targetingSet?->options ?? []);
    $selectedAudienceLists = match ($campaign?->platform) {
        'google' => ($campaign?->campaign_type ?: 'search') === 'search' ? (array) ($targetingOptions['google_user_lists'] ?? []) : [],
        'meta' => (array) ($targetingOptions['meta_audiences'] ?? []),
        'linkedin' => (array) ($targetingOptions['linkedin_segments'] ?? []),
        default => [],
    };
    $targetingRevision = (int) ($campaign?->targetingSet?->revision ?? 0);
    foreach ((array) ($campaign?->external_ids['meta_custom_audience_criteria'] ?? []) as $adSetAudience) {
        foreach (['custom_audiences' => 'include', 'excluded_custom_audiences' => 'exclude'] as $field => $operation) {
            foreach ((array) ($adSetAudience[$field] ?? []) as $audience) {
                $importedMetaAudiences[] = $operation.' Meta audience ID '.($audience['id'] ?? '?')
                    .' on ad set '.($adSetAudience['adset_id'] ?? '?');
            }
        }
    }
    foreach ((array) ($campaign?->external_ids['google_ad_group_criteria'] ?? []) as $criterion) {
        $groupId = basename((string) ($criterion['ad_group'] ?? ''));
        if (($criterion['type'] ?? null) === 'KEYWORD') {
            $importedSearchKeywords[] = sprintf(
                '%s%s [%s], ad group %s (%s)',
                ($criterion['negative'] ?? false) ? 'exclude ' : '',
                (string) ($criterion['text'] ?? ''),
                (string) ($criterion['match_type'] ?? ''),
                $groupId,
                strtolower((string) ($criterion['status'] ?? '')),
            );
        } elseif (($criterion['type'] ?? null) === 'USER_LIST') {
            $importedGoogleAudiences[] = sprintf(
                '%s%s, ad group %s (%s; %s)',
                ($criterion['negative'] ?? false) ? 'exclude ' : 'include ',
                (string) ($criterion['user_list'] ?? ''),
                $groupId,
                ($criterion['audience_bid_only'] ?? false) ? 'observation' : 'targeting',
                strtolower((string) ($criterion['status'] ?? '')),
            );
        }
    }

    $metaAudience = (array) ($campaign?->audience ?? []);
    $metaAudienceMode = match ($metaAudience['meta_audience_mode'] ?? null) {
        'broad' => 'Broad audience',
        'custom' => 'Custom audience',
        default => null,
    };
    $metaInterestNames = collect((array) ($metaAudience['meta_interests'] ?? []))
        ->map(fn (array $interest): string => trim((string) ($interest['name'] ?? '')))
        ->filter()
        ->unique()
        ->values()
        ->all();
    $metaDetailedSummary = collect((array) ($metaAudience['meta_detailed'] ?? []))
        ->map(function (mixed $items, string $field): ?string {
            if (! is_array($items)) {
                return null;
            }

            $names = collect($items)
                ->map(fn (mixed $item): string => is_array($item) ? trim((string) ($item['name'] ?? '')) : '')
                ->filter()
                ->unique()
                ->implode(', ');

            return $names === '' ? null : \App\Services\Meta\MetaTargetingCatalog::fieldLabel($field).': '.$names;
        })
        ->filter()
        ->implode('; ');
    $metaAgeMin = isset($metaAudience['age_min']) ? (int) $metaAudience['age_min'] : null;
    $metaAgeMax = isset($metaAudience['age_max']) ? (int) $metaAudience['age_max'] : null;
    $metaAgeRange = $metaAgeMin !== null && $metaAgeMax !== null
        ? ($metaAgeMax >= 65 ? $metaAgeMin.'+' : $metaAgeMin.'–'.$metaAgeMax)
        : null;
    $metaGenders = array_values(array_filter(array_map(
        fn (int $gender): ?string => match ($gender) {
            1 => 'Men',
            2 => 'Women',
            default => null,
        },
        array_map('intval', (array) ($metaAudience['genders'] ?? [])),
    )));
    $metaGenderLabel = $metaGenders !== []
        ? implode(', ', $metaGenders)
        : (($metaAudience['meta_audience_mode'] ?? null) === 'custom' ? 'All genders' : null);
    $scheduleParts = [];
    if ($campaign?->starts_at !== null) {
        $scheduleParts[] = 'Starts '.$campaign->starts_at->toDateString();
    }
    if ($campaign?->ends_at !== null) {
        $scheduleParts[] = 'Ends '.$campaign->ends_at->toDateString();
    }
    if ($scheduleParts === [] && array_key_exists('ends_at', (array) ($sources ?? []))) {
        $scheduleParts[] = 'Continuous';
    }
    $scheduleSummary = implode('; ', $scheduleParts);
    $showSchedule = ($campaign?->usesLifetimeBudget() ?? false)
        || $scheduleSummary !== '';
    $adAccountName = trim((string) data_get($campaign?->meta, 'ad_account.name', ''));
    $adAccountValue = $adAccountName !== ''
        ? $adAccountName.' ('.$campaign->ad_account_id.')'
        : $campaign?->ad_account_id;
    if (filled($campaign?->currency)) {
        $adAccountValue = trim((string) $adAccountValue.' · '.$campaign->currency);
    }
    /*
     * Meta calls it a pixel and Google a conversion action, and each writes
     * its own key. This read pixel.name only, so a Google campaign fell
     * through to pixel_id and the row showed a bare resource name - and said
     * nothing at all about the other actions the campaign counts, which is
     * four of them on a Google Sales campaign. Reported as "all the
     * conversion events are still missing".
     */
    $countedActions = collect((array) data_get($campaign?->meta, 'google_conversion_action_names', []))
        ->pluck('name')
        ->filter()
        ->values();

    $metaPixelName = trim((string) data_get($campaign?->meta, 'pixel.name', ''));
    $googleActionName = trim((string) data_get($campaign?->meta, 'conversion_action.name', ''));

    $pixelValue = match (true) {
        // Every action this campaign counts, by name. Google only: Meta
        // optimises toward one pixel event.
        $countedActions->count() > 1 => $countedActions->implode(', '),
        // Meta keeps the id beside the name, which is a short number worth
        // reading. Google's is a resource path, so the name stands alone.
        $metaPixelName !== '' => $metaPixelName.' ('.$campaign->pixel_id.')',
        $googleActionName !== '' => $googleActionName,
        default => $campaign?->pixel_id,
    };
    $identityWarnings = array_filter([
        'Page' => data_get($campaign?->meta, 'facebook_page.brand_mismatch'),
        'Pixel' => data_get($campaign?->meta, 'pixel.brand_mismatch'),
        'Conversion goal' => data_get($campaign?->meta, 'pixel.goal_mismatch'),
    ]);
@endphp

{{-- A conversation can hold several campaigns, including two on the same platform. --}}
@if (($campaigns ?? collect())->count() > 1)
    <div class="mb-campaign-switch mb-campaign-nav-tabs" role="tablist" aria-label="Campaign Platforms">
        @foreach ($campaigns as $option)
            <button type="button"
                    class="mb-campaign-tab mb-campaign-nav-tab{{ $campaign && $option->id === $campaign->id ? ' active' : '' }}"
                    role="tab"
                    aria-selected="{{ $campaign && $option->id === $campaign->id ? 'true' : 'false' }}"
                    data-focus-campaign="{{ $option->id }}">
                {{ $campaigns->where('platform', $option->platform)->count() > 1 ? $option->name : $platformName($option->platform) }}
            </button>
        @endforeach
    </div>
@endif

{{-- Looking at one campaign while the chat is working on another.
     A tab click only changes what is on screen, so without this somebody
     reads one campaign and answers about a different one. --}}
@if (! empty($workingOn))
    <p class="mb-campaign-note mb-2">
        Looking at this one. Your next answer goes to <strong>{{ $workingOn }}</strong>,
        unless you say otherwise.
    </p>
@endif

@if (! $campaign)
    <p class="text-body-secondary small mb-0">No campaign yet. It appears here as the chat fills it in.</p>
@else
    <div class="d-flex justify-content-between align-items-start mb-2">
        @if ($campaign->platform === 'linkedin' && $campaign->isPublished())
            <strong data-row-prompt="Change the ad set name for {{ $campaign->name }}. Call edit_linkedin_campaign with the new name. Do not use a Meta tool." title="Click to ask AI about the ad set name">{{ $campaign->name }}</strong>
        @else
            <strong>{{ $campaign->name }}</strong>
        @endif
        <div class="d-flex align-items-center gap-2">
            <button type="button" class="btn btn-outline-secondary btn-sm" data-duplicate-campaign="{{ $campaign->id }}">Duplicate</button>
            <span class="badge {{ $campaign->status === 'published' ? 'text-bg-success' : 'text-bg-secondary' }}">
                {{ $campaign->status }}
            </span>
        </div>
    </div>

    @foreach ($identityWarnings as $label => $warning)
        <div class="alert alert-warning py-2 small" role="status">
            <strong>Confirm {{ strtolower($label) }}:</strong> {{ $warning }}
        </div>
    @endforeach

    {{-- Where they are in the build.

         The flow has always known which step comes next, because that is how it
         decides what to ask. It was never shown, so the product could lead
         somebody through fourteen steps without ever telling them how many there
         were or how far along they had got. Steps that do not apply to this
         campaign are already absent: a traffic campaign has no pixel step, so it
         is not counted against them. --}}
    @if (! empty($progress))
        @php
            $settled = collect($progress)->where('done', true)->count();
            $total = count($progress);
        @endphp

        <div class="mb-progress">
            <div class="mb-progress-head">
                <span class="mb-progress-count">{{ $settled }} of {{ $total }}</span>
                {{-- A live campaign is not partway through the launch flow, and
                     not "everything answered" either: these steps describe
                     building it up to its first publish, and it is past that.
                     Counting it toward a launch it already completed is what
                     made the panel read "9 of 10, next: creatives" on a campaign
                     that had been on Meta for days. --}}
                @if ($campaign->isPublished())
                    <span class="mb-progress-next is-ready">On {{ $platformName($campaign->platform) }}</span>
                @elseif ($nextStep)
                    <span class="mb-progress-next">Next: {{ $nextStep['label'] }}</span>
                @elseif (! empty($blocking))
                    <span class="mb-progress-next">Answers done, publish checks left</span>
                @else
                    <span class="mb-progress-next is-ready">Everything answered</span>
                @endif
            </div>

            <div class="mb-progress-track" role="progressbar"
                 aria-valuenow="{{ $settled }}" aria-valuemin="0" aria-valuemax="{{ $total }}"
                 aria-label="Campaign setup progress">
                <span class="mb-progress-fill" style="width: {{ $total ? round($settled / $total * 100) : 0 }}%"></span>
            </div>

            <ol class="mb-progress-steps">
                @foreach ($progress as $step)
                    {{-- The campaign is named, never called "this campaign".
                         This panel shows whichever campaign is being looked at,
                         which is not always the one the chat is working on, so
                         "this campaign" resolved to whichever the agent had in
                         focus and a click could quietly edit the other one. --}}
                    @php
                        $reviewsAudience = $campaign->platform === 'linkedin' && $step['key'] === 'linkedin_audience';
                        $stepPrompt = ($step['done'] ? 'Review or change the ' : 'Help me configure the ') . $step['label'] . ' for ' . $campaign->name;
                        if ($step['done'] && $step['key'] === 'copy') {
                            $stepPrompt = 'Show the complete ad-copy variations and the Regenerate ad-copy option for ' . $campaign->name . '. Do not offer separate headline or body choices.';
                        } elseif ($reviewsAudience) {
                            $stepPrompt = 'Show the LinkedIn audience refinement choices for ' . $campaign->name . '. Keep the current targeting until I choose a change.';
                        }
                    @endphp
                    <li class="mb-progress-step{{ $step['done'] ? ' is-done' : '' }}{{ $nextStep && $nextStep['key'] === $step['key'] ? ' is-next' : '' }}"
                        data-step-prompt="{{ $stepPrompt }}"
                        @if ($reviewsAudience && ! $campaign->isPublished() && filled($campaign->ad_account_id))
                            data-panel-action="review_linkedin_audience" data-panel-campaign="{{ $campaign->id }}"
                        @endif
                        title="{{ $step['done'] ? 'Completed: ' . $step['label'] . ' (click to change)' : 'Click to prompt AI for ' . $step['label'] }}">
                        <i class="bi {{ $step['done'] ? 'bi-check-circle-fill' : 'bi-circle' }}"></i>
                        {{ $step['label'] }}
                    </li>
                @endforeach
            </ol>
        </div>
    @endif

    <table class="table table-sm mb-3">
        <tbody>
            @foreach (array_values(array_filter([
                $row('Platform', $campaign->platform, $sources['platform'] ?? null),
                $row('Objective', $campaign->objective ? ucwords(strtolower(str_replace('_', ' ', preg_replace('/^OUTCOME_/', '', $campaign->objective)))) : null, $sources['objective'] ?? null),
                $row('Landing page', $campaign->landing_url, $sources['landing_url'] ?? null),
                {{-- Shown even when it is nothing, because "no tracking" is a
                     decision with consequences and an empty row reads as one
                     nobody made. --}}
                $row(
                    'Click tracking',
                    $campaign->utm === null ? null : ($campaign->utm === '' ? 'none' : $campaign->utm),
                    $sources['utm'] ?? null,
                ),
                {{-- Labelled by what it actually is. "Daily budget" was shown
                     for every campaign whatever the arrangement, and it never
                     said the money sits on the ad set rather than the campaign. --}}
                $row(
                    $campaign->usesLifetimeBudget() ? 'Lifetime budget' : 'Daily budget',
                    $campaign->budget
                        ? $campaign->currency.' '.$campaign->budget
                            .($campaign->usesCampaignBudget() ? ', on the campaign' : ', on the ad set')
                        : null,
                    $sources['budget'] ?? null,
                ),
                $showSchedule ? $row('Schedule', $scheduleSummary, $sources['ends_at'] ?? $sources['starts_at'] ?? null) : null,
                $row('Bidding', collect($rules?->bidStrategyOptions() ?? [])->firstWhere('value', $campaign->bid_strategy)['label'] ?? $campaign->bid_strategy, $sources['bid_strategy'] ?? null),
                $row('Target cost', $campaign->bid_amount, $sources['bid_amount'] ?? null),
                $row('Countries', $countrySummary, $sources['locations'] ?? null),
                $campaign?->platform === 'linkedin' && $campaign->isPublished()
                    ? $row('Target audience', $linkedinAudienceSummary !== '' ? $linkedinAudienceSummary : 'Add attributes or a matched audience', $sources['audience'] ?? null)
                    : null,
                $selectedPlaces !== [] ? $row('Cities / regions', implode('; ', $selectedPlaces), $sources['locations'] ?? null) : null,
                $importedSearchKeywords !== [] ? $row('Imported Search keywords', implode('; ', $importedSearchKeywords), $sources['locations'] ?? null) : null,
                $importedGoogleAudiences !== [] ? $row('Imported Google audiences', implode('; ', $importedGoogleAudiences), $sources['locations'] ?? null) : null,
                $importedMetaAudiences !== [] ? $row('Imported Meta audiences', implode('; ', $importedMetaAudiences), $sources['audience'] ?? null) : null,
                {{-- Meta calls these placements and Google calls them networks,
                     which is the same distinction the step list already draws. --}}
                $has('placements')
                    ? $row(
                        str_contains($named('targeting', 'placements'), 'networks') ? 'Networks' : 'Placements',
                        implode(', ', $campaign->placements ?? []),
                        $sources['placements'] ?? null,
                    )
                    : null,
                    $campaign->platform === 'meta' && $metaAudienceMode !== null ? $row('Audience', $metaAudienceMode, $sources['audience'] ?? null) : null,
                    $campaign->platform === 'meta' && $metaInterestNames !== [] ? $row('Audience interests', implode(', ', $metaInterestNames), $sources['audience'] ?? null) : null,
                    $campaign->platform === 'meta' && $metaDetailedSummary !== '' ? $row('Detailed targeting', $metaDetailedSummary, $sources['audience'] ?? null) : null,
                    $campaign->platform === 'meta' && $metaAgeRange !== null ? $row('Age range', $metaAgeRange, $sources['audience'] ?? null) : null,
                    $campaign->platform === 'meta' && $metaGenderLabel !== null ? $row('Gender', $metaGenderLabel, $sources['audience'] ?? null) : null,
                $has('devices') ? $row('Devices', implode(', ', $campaign->audience['devices'] ?? []) ?: null, $sources['audience'] ?? null) : null,
                $row('Ad account', $adAccountValue, $sources['ad_account_id'] ?? null),
                $has('page') ? $row('Page', ($campaign->meta[$campaign->platform === 'linkedin' ? 'linkedin_page' : 'facebook_page']['name'] ?? null) ?: $campaign->page_id, $sources['page_id'] ?? null) : null,
                $campaign->platform === 'linkedin' && filled($campaign->external_ids['campaign_group_id'] ?? null) ? $row('Campaign group', $campaign->external_ids['campaign_group_id'], null) : null,
                $campaign->platform === 'linkedin' && $campaign->objective === 'LEAD_GENERATION' ? $row('Lead Gen Form', $campaign->meta['linkedin_setup']['lead_form']['name'] ?? null, null) : null,
                $campaign->platform === 'linkedin' && $campaign->objective === 'WEBSITE_CONVERSIONS' ? $row('Conversion rule', $campaign->meta['linkedin_setup']['conversion']['name'] ?? null, null) : null,
                $campaign->platform === 'linkedin' && isset($campaign->meta['linkedin_state']) ? $row('Remote campaign status', $campaign->meta['linkedin_state']['campaign_status'] ?? 'Unknown', null) : null,
                $campaign->platform === 'linkedin' && isset($campaign->meta['linkedin_state']) ? $row('Remote group status', $campaign->meta['linkedin_state']['group_status'] ?? 'Unknown', null) : null,
                $campaign->platform === 'linkedin' && isset($campaign->meta['linkedin_state']) ? $row('Status refreshed', $campaign->meta['linkedin_state']['refreshed_at'] ?? null, null) : null,
                {{-- Empty string means asked and there is none, which is not the
                     same as never asked. Shown so an Instagram placement running
                     under the Page is visible rather than assumed. --}}
                $has('instagram')
                    ? $row(
                        'Instagram',
                        $campaign->instagram_account_id === null
                            ? null
                            : ($campaign->instagram_account_id ?: 'runs under the Page'),
                        $sources['instagram_account_id'] ?? null,
                    )
                    : null,
                $has('pixel') ? $row($named('pixel', 'pixel'), $pixelValue, $sources['pixel_id'] ?? null) : null,
                // Shown as the pixel spells it rather than as the enum, because
                // "Subscribe" is what the buyer picked and what they will look
                // for in Events Manager. SUBSCRIBE is Meta's word for it.
                $has('conversion_event')
                    ? $row(
                        'optimises toward',
                        \App\Campaigns\MetaPromotedConversion::label($campaign->conversion_event),
                        $sources['conversion_event'] ?? null,
                    )
                    : null,
            ])) as [$label, $value, $colour, $title])
                <tr class="mb-panel-row" data-row-prompt="{{ $campaign->platform === 'linkedin' && $campaign->isPublished() ? $linkedinLivePrompt($label) : 'I want to update the '.$label.' for '.$campaign->name.'.' }}" title="Click to ask AI about {{ $label }}">
                    <td class="text-body-secondary" style="width: 38%;">
                        <span class="mb-dot {{ $colour }}" title="{{ $title }}"></span>
                        {{ $label }}
                    </td>
                    <td class="text-break">{{ filled($value) ? $value : '—' }}</td>
                </tr>
            @endforeach
        </tbody>
    </table>

    @if ($selectedAudienceLists !== [])
        <div class="border rounded p-2 mb-3 small" data-audience-sizing
             data-campaign-id="{{ $campaign->id }}" data-targeting-revision="{{ $targetingRevision }}">
            <div class="d-flex justify-content-between align-items-center gap-2">
                <strong>Audience list sizes</strong>
                <button type="button" class="btn btn-sm btn-outline-secondary" data-refresh-audience-sizing>Refresh</button>
            </div>
            <div data-audience-sizing-result role="status" aria-live="polite">Loading provider list sizes…</div>
            <div class="text-body-secondary">List sizes are estimates for individual lists, not campaign reach.</div>
        </div>
    @endif

    {{-- The ad sets past the first.

         The rows above describe the first one, which is what the campaign's own
         attributes address, so without this an ad set added to a live campaign
         was invisible here: the buyer asked for a second audience, it went to
         Meta, and the panel carried on showing one. Shown only when there is
         more than one, so the ordinary single-ad-set campaign is unchanged. --}}
    @php
        // Skipping the first rather than filtering on position, so an ad set
        // numbered oddly - one removed and another added - is still listed.
        $otherAdSets = $campaign->adSets()->get()->skip(1);
    @endphp

    @if ($otherAdSets->isNotEmpty())
        <div class="small text-body-secondary mb-1">Other ad sets</div>

        <table class="table table-sm mb-panel-table">
            <tbody>
                @foreach ($otherAdSets as $adSet)
                    <tr class="mb-panel-row"
                        data-row-prompt="Tell me about the ad set {{ $adSet->name }} on {{ $campaign->name }}."
                        title="Click to ask AI about this ad set">
                        <td class="text-body-secondary" style="width: 38%;">
                            {{ $adSet->name }}
                        </td>
                        <td class="text-break">
                            {{ implode(', ', $adSet->locations['countries'] ?? []) ?: '—' }}
                            @if ($adSet->effectiveBudget())
                                · {{ $campaign->currency }} {{ number_format($adSet->effectiveBudget(), 2) }}
                                {{ $adSet->effectiveBudgetMode() === 'lifetime' ? 'total' : 'a day' }}
                            @endif
                            {{-- Said plainly, because an ad set that is on the
                                 platform and one that is only written here are
                                 very different things to be looking at. --}}
                            · {{ $adSet->isPublished() ? 'on '.ucfirst($campaign->platform).', paused' : 'not sent yet' }}
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>
    @endif

    {{-- Not shown where ads carry no creative at all. A Google search ad is
         headlines and descriptions, so "Creatives: 0 attached" reads as
         something outstanding rather than something that does not apply. --}}
    @if (! $rules || $rules->requiresCreativeAsset($campaign))
        <div class="small text-body-secondary mb-1">
            Creatives: {{ $assets->count() }} attached
        </div>
    @endif

    {{-- Copy alone did not say which creative each ad carries, which is the
         question the panel exists to answer once creatives are attached. Only
         the public disk is web served, so an uploaded file has no preview and
         says so rather than rendering a broken image. --}}
    @if ($campaign->ads()->exists())
        <div class="mb-preview-toggle-bar">
            <button type="button" class="mb-preview-toggle-btn active" data-ad-view="mockup">Live Ad Preview</button>
            <button type="button" class="mb-preview-toggle-btn" data-ad-view="list">Ad Variations ({{ $campaign->ads->count() }})</button>
        </div>

        @php
            // The preview was a single fixed width whatever the ad set targets,
            // so a desktop-only campaign was reviewed at phone width and a
            // mobile-only one at desktop width. Meta renders the two
            // differently, and the headline is what gets truncated.
            //
            // Only the devices the campaign actually targets are offered. A
            // toggle to a placement this ad set will never serve is a preview of
            // something that cannot happen.
            $targetedDevices = array_values(array_intersect(
                ['mobile', 'desktop'],
                $campaign->audience['devices'] ?? [],
            ));

            // Nothing chosen yet means both are still possible, so show both
            // rather than silently picking one.
            $previewDevices = $targetedDevices ?: ['mobile', 'desktop'];

            // Mobile first where both are targeted: it is the larger share of
            // Meta inventory, which the device question says on screen.
            $defaultDevice = $previewDevices[0];
        @endphp

        @if (count($previewDevices) > 1)
            <div class="mb-preview-device-bar" role="group" aria-label="Preview device">
                @foreach ($previewDevices as $device)
                    <button type="button"
                            class="mb-preview-device-btn{{ $device === $defaultDevice ? ' active' : '' }}"
                            data-ad-device="{{ $device }}"
                            aria-pressed="{{ $device === $defaultDevice ? 'true' : 'false' }}">
                        <i class="bi bi-{{ $device === 'mobile' ? 'phone' : 'display' }}"></i>
                        {{ ucfirst($device) }}
                    </button>
                @endforeach
            </div>
        @else
            <div class="mb-preview-device-note">
                Previewing on {{ $defaultDevice }}, the only device this ad set targets.
            </div>
        @endif

        <div id="adViewMockup" class="mb-ad-mockups mb-3 is-{{ $defaultDevice }}">
            @foreach ($campaign->ads as $ad)
                @php($asset = $ad->asset)
                @if ($campaign->platform === 'google')
                    <div class="mb-ad-mockup-google">
                        <div>
                            <span class="mb-mockup-google-badge">Sponsored</span>
                            <span class="mb-mockup-google-url">{{ parse_url($campaign->landing_url ?? 'https://example.com', PHP_URL_HOST) ?? 'example.com' }}</span>
                        </div>
                        <div class="mb-mockup-google-title">{{ $ad->headline }}</div>
                        <div class="mb-mockup-google-desc">{{ $ad->primary_text }}</div>
                    </div>
                @else
                    @foreach (($previewIdentities ?? []) ?: [['platform' => $platformName($campaign->platform), 'name' => $campaign->name, 'icon' => $campaign->platform === 'linkedin' ? 'linkedin' : 'meta']] as $identity)
                    <div class="mb-ad-mockup-meta">
                        <div class="mb-mockup-header">
                            <div class="mb-mockup-avatar">
                                <i class="bi bi-{{ $identity['icon'] }}" aria-label="{{ $identity['platform'] }}"></i>
                            </div>
                            <div class="mb-mockup-meta-info">
                                <div class="mb-mockup-page-name">{{ $identity['name'] }}</div>
                                <div class="mb-mockup-sponsored">{{ $identity['platform'] }} &middot; Sponsored</div>
                            </div>
                        </div>
                        <div class="mb-mockup-body">{{ $ad->primary_text }}</div>
                        @if ($asset && $asset->hasStill())
                            <div class="mb-mockup-media">
                                <img src="{{ route('assets.preview', $asset) }}" alt="">
                            </div>
                        @endif
                        <div class="mb-mockup-footer">
                            <div class="mb-mockup-link-info">
                                <div class="mb-mockup-domain">{{ parse_url($campaign->landing_url ?? 'https://example.com', PHP_URL_HOST) ?? 'example.com' }}</div>
                                <div class="mb-mockup-headline">{{ $ad->headline }}</div>
                            </div>
                            <span class="mb-mockup-cta-btn">{{ str_replace('_', ' ', $ad->cta ?? 'LEARN MORE') }}</span>
                        </div>
                    </div>
                    @endforeach
                @endif
            @endforeach
        </div>

        <div id="adViewList" class="small mb-3 d-none">
            @foreach ($campaign->ads as $ad)
                @php($asset = $ad->asset)
                <div class="border rounded p-2 mb-1 mb-ad">
                    @if ($asset && $asset->hasStill())
                        <span class="mb-ad-thumb-wrap">
                            <img class="mb-ad-thumb" src="{{ route('assets.preview', $asset) }}" alt="">
                            @if ($asset->kind === 'video')
                                <i class="bi bi-play-btn mb-ad-thumb-play" title="Video creative"></i>
                            @endif
                        </span>
                    @else
                        <span class="mb-ad-thumb mb-ad-thumb-empty"
                              title="{{ $asset ? 'Video creative' : 'No creative attached' }}">
                            <i class="bi bi-{{ $asset ? ($asset->kind === 'video' ? 'play-btn' : 'image') : 'dash' }}"></i>
                        </span>
                    @endif

                    <div class="mb-ad-body">
                        <div class="fw-semibold">{{ $ad->headline }}</div>
                        <div class="text-body-secondary">{{ $ad->primary_text }}</div>
                        <span class="badge text-bg-light">{{ $ad->cta }}</span>
                        @unless ($asset)
                            <span class="badge text-bg-warning">no creative</span>
                        @endunless
                    </div>
                </div>
            @endforeach
        </div>
    @endif

    @if ($pending || $needsRebuild)
        <div class="alert alert-warning small py-2">
            <div class="fw-semibold mb-1">Not yet on the platform</div>

            @foreach ($pending as $field => $change)
                <div>
                    {{ str_replace('_', ' ', $field) }}:
                    <span class="text-decoration-line-through">{{ $change['from'] ?? 'not set' }}</span>
                    &rarr; <strong>{{ $change['to'] ?? 'not set' }}</strong>
                </div>
            @endforeach

            @foreach ($needsRebuild as $reason)
                <div>{{ $reason }}</div>
            @endforeach

            @if ($pending)
                <div class="mt-1">Ask in the chat to push these changes.</div>
            @endif
        </div>
    @endif

    {{-- Was a raw json_encode of the ids, which is unreadable in a narrow panel
         and is the first thing anyone needs when checking Ads Manager. --}}
    @php($createdIds = \App\Campaigns\CreatedIds::rows($campaign))
    @if ($createdIds)
        <div class="alert alert-success small py-2">
            <div class="fw-semibold mb-1">Created on the platform</div>
            <dl class="mb-ids mb-0">
                @foreach ($createdIds as $row)
                    <dt>
                        {{ $row['label'] }}
                        @if ($row['hint'])
                            <span class="mb-ids-hint">{{ $row['hint'] }}</span>
                        @endif
                    </dt>
                    <dd class="font-monospace">{{ implode(', ', $row['ids']) }}</dd>
                @endforeach
            </dl>
        </div>
    @endif

    @if ($campaign->last_error)
        <div class="alert alert-danger small py-2">{{ $campaign->last_error }}</div>
    @endif

    @if ($campaign->isPublished())
        <div class="alert alert-success small py-2 mb-0">Published. Delivery status must be checked on the platform.</div>
    @elseif ($blocking)
        <div class="small">
            {{-- Named for what it gates. The strip above counts every step in
                 the flow and this counts only what stops a publish, so the two
                 legitimately disagree: bid strategy and click tracking are
                 asked for but not required. Unlabelled, that read as a bug. --}}
            <div class="text-body-secondary mb-1">Still needed to publish</div>
            <ul class="ps-3 mb-0">
                @foreach ($blocking as $reason)
                    <li>{{ $reason }}</li>
                @endforeach
            </ul>
        </div>
    @else
        <div class="alert alert-success small py-2 mb-0">Ready to publish.</div>
    @endif
@endif
