<?php

namespace App\Library\CampaignDecision;

use App\Campaigns\AdSetAudienceAction;
use App\Campaigns\AdSetOptimizationCards;

/**
 * Turns marketing plan lines into labeled, HTML-safe rich text for the performance UI.
 */
class CampaignMarketingPlanPresenter
{
    /**
     * @param  array<string, mixed>  $row
     * @return array{
     *     steps: list<array{kind: string, label: string, text: string, html: string}>,
     *     lever: ?string,
     *     lever_label: ?string
     * }
     */
    /**
     * Listing cards show the stored review memo unless the engine verdict is
     * already keep-running. That avoids Pause copy on a Maintain campaign.
     *
     * @param  array<string, mixed>  $row
     */
    public static function listingUsesStoredAnalysis(array $row, mixed $verdict): bool
    {
        if ($verdict === CampaignDecisionVerdict::Maintain || $verdict === CampaignDecisionVerdict::ScaleUp) {
            return false;
        }

        return (self::forRow($row)['steps'][0]['kind'] ?? '') === 'analysis';
    }

    public static function forRow(array $row): array
    {
        $lever = is_string($row['marketing_lever'] ?? null) ? (string) $row['marketing_lever'] : null;
        $analysis = trim((string) data_get($row, 'review.analysis', ''));

        if ($analysis !== '') {
            $platform = strtolower(trim((string) ($row['platform'] ?? 'meta')));
            if ($platform !== 'meta' && $platform !== '') {
                $platLabel = match ($platform) {
                    'linkedin' => 'LinkedIn',
                    'google' => 'Google',
                    default => ucfirst($platform),
                };
                $analysis = str_ireplace(
                    [
                        'Meta learning stage: not on file',
                        'Meta learning stage',
                        'Meta learning guardrail',
                        'is paused on Meta',
                        'paused on Meta',
                        'Meta reports',
                        'Events Manager',
                    ],
                    [
                        $platLabel.' learning stage: not on file',
                        $platLabel.' learning stage',
                        $platLabel.' learning guardrail',
                        'is paused on '.$platLabel,
                        'paused on '.$platLabel,
                        $platLabel.' reports',
                        $platLabel === 'LinkedIn' ? 'Campaign Manager and conversion tracking' : ($platLabel === 'Google' ? 'Google Tag and conversions' : 'Events Manager'),
                    ],
                    $analysis,
                );
            }

            $windows = is_array($row['windows'] ?? null) ? $row['windows'] : [];
            $analysis = self::alignAnalysisToWindows($analysis, $windows);
            $review = is_array($row['review'] ?? null) ? $row['review'] : [];

            if (self::hasCreativeActions($review)) {
                $analysis = self::withoutLongRecommendationItems($analysis);
            }

            $analysis = self::cleanBottleneckText($analysis);

            $steps = [];

            if (trim($analysis) !== '') {
                $steps[] = self::step('analysis', 'Recommendation', $analysis);
            }

            return self::finish(array_merge($steps, self::reviewSteps($review, $row)), $lever, $row);
        }

        $lines = self::linesFromRow($row);

        if ($lines === []) {
            $fallback = trim((string) ($row['reason'] ?? ''));

            if ($fallback === '') {
                return self::finish([], $lever, $row);
            }

            return self::finish([
                self::step('summary', 'Suggestion', $fallback),
            ], $lever, $row);
        }

        $kinds = ['window', 'action', 'why'];
        $labels = ['Window', 'Change', 'Why'];

        $steps = [];

        foreach ($lines as $index => $line) {
            $kind = $kinds[$index] ?? 'why';
            $label = $labels[$index] ?? 'Detail';
            $steps[] = self::step($kind, $label, $line);
        }

        $review = $row['review'] ?? null;

        if (is_array($review)) {
            $steps = array_merge($steps, self::reviewSteps($review, $row));
        } else {
            $frozen = CampaignAdRoster::creativeAdviceFrozen(
                is_array($row['snapshot'] ?? null) ? $row['snapshot'] : $row,
            );
            $suggestion = $row['landing_suggestion'] ?? null;
            $card = (! $frozen && is_array($suggestion)) ? self::landingStep($suggestion) : null;

            if ($card !== null) {
                $steps[] = $card;
            }
        }

        return self::finish($steps, $lever, $row);
    }

    /**
     * Ad-set cards always; creative and landing cards only when tracking is not frozen.
     *
     * @param  array<string, mixed>  $row
     * @return list<array{kind: string, label: string, text: string, html: string}>
     */
    public static function detailSupportSteps(array $row): array
    {
        $frozen = CampaignAdRoster::creativeAdviceFrozen(
            is_array($row['snapshot'] ?? null) ? $row['snapshot'] : $row,
        );
        $allowed = $frozen ? ['adset'] : ['adset', 'creative', 'landing'];

        return array_values(array_filter(
            self::forRow($row)['steps'],
            fn (array $step): bool => in_array($step['kind'], $allowed, true),
        ));
    }

    /**
     * @param  list<array{kind: string, label: string, text: string, html: string}>  $steps
     * @param  array<string, mixed>  $row
     * @return array{
     *     steps: list<array{kind: string, label: string, text: string, html: string}>,
     *     lever: ?string,
     *     lever_label: ?string
     * }
     */
    private static function finish(array $steps, ?string $lever, array $row): array
    {
        return [
            'steps' => self::insertAdSetSteps($steps, self::adSetSteps($row)),
            'lever' => $lever,
            'lever_label' => self::leverLabel($lever),
        ];
    }

    /**
     * @param  list<array{kind: string, label: string, text: string, html: string}>  $steps
     * @param  list<array{kind: string, label: string, text: string, html: string}>  $adSetSteps
     * @return list<array{kind: string, label: string, text: string, html: string}>
     */
    private static function insertAdSetSteps(array $steps, array $adSetSteps): array
    {
        if ($adSetSteps === []) {
            return $steps;
        }

        foreach ($steps as $index => $step) {
            if ($step['kind'] === 'analysis') {
                array_splice($steps, $index + 1, 0, $adSetSteps);

                return $steps;
            }
        }

        return array_merge($steps, $adSetSteps);
    }

    /**
     * Markdown bullet list aligned with the performance board plan block.
     *
     * @param  array<string, mixed>  $row
     */
    public static function toMarkdownBullets(array $row): string
    {
        $presentation = self::forRow($row);
        $lines = [];

        if ($presentation['lever_label'] !== null) {
            $lines[] = '**Primary lever:** '.$presentation['lever_label'];
        }

        foreach ($presentation['steps'] as $step) {
            if ($step['kind'] === 'analysis') {
                $lines[] = $step['text'];

                continue;
            }

            $lines[] = '- **'.$step['label'].':** '.$step['text'];
        }

        return implode("\n", $lines);
    }

    /**
     * @param  array<string, mixed>  $row
     * @return list<string>
     */
    private static function linesFromRow(array $row): array
    {
        $plan = $row['marketing_plan'] ?? null;

        if (is_array($plan) && $plan !== []) {
            return self::withBudget(array_values(array_filter(array_map(
                fn (mixed $line): string => is_string($line) ? trim($line) : '',
                $plan,
            ))), $row);
        }

        $reason = trim((string) ($row['reason'] ?? ''));

        if ($reason === '') {
            return [];
        }

        $split = preg_split('/\r\n|\r|\n/', $reason) ?: [];

        return self::withBudget(array_values(array_filter(array_map('trim', $split))), $row);
    }

    /**
     * @param  list<string>  $lines
     * @param  array<string, mixed>  $row
     * @return list<string>
     */
    private static function withBudget(array $lines, array $row): array
    {
        $summary = is_string($row['budget_summary'] ?? null) ? $row['budget_summary'] : null;

        return CampaignBudgetRecommendation::mergeIntoPlan($lines, $summary);
    }

    /**
     * @param  array<string, mixed>  $review
     * @param  array<string, mixed>  $row
     * @return list<array{kind: string, label: string, text: string, html: string}>
     */
    private static function reviewSteps(array $review, array $row): array
    {
        $steps = [];
        $budget = trim((string) ($review['budget'] ?? ''));

        if ($budget !== '') {
            $steps[] = self::step('budget', 'Budget', $budget);
        }

        $frozen = CampaignAdRoster::creativeAdviceFrozen(
            is_array($row['snapshot'] ?? null) ? $row['snapshot'] : $row,
        );
        $creatives = $review['creatives'] ?? [];

        if (! $frozen && is_array($creatives)) {
            foreach ($creatives as $creative) {
                if (! is_array($creative)) {
                    continue;
                }

                $name = trim((string) ($creative['current_headline'] ?? ''));

                if ($name === '') {
                    $name = trim((string) ($creative['ad_id'] ?? ''));
                }

                $creative['creative_id'] = self::creativeId($creative, $row);
                $roster = CampaignAdRoster::rowForAd(
                    is_array($row['snapshot'] ?? null) ? $row['snapshot'] : $row,
                    trim((string) ($creative['ad_id'] ?? '')),
                );

                if (is_array($roster)) {
                    $creative['format'] = $creative['format'] ?? ($roster['format'] ?? '');
                    $creative['ad_id'] = trim((string) ($creative['ad_id'] ?? '')) !== ''
                        ? $creative['ad_id']
                        : ($roster['ad_id'] ?? '');
                    $creative['status'] = $creative['status'] ?? ($roster['status'] ?? '');
                }

                $card = self::creativeStep($creative, $name !== '' ? $name : 'Ad');

                if ($card !== null) {
                    $steps[] = $card;
                }
            }
        }

        $landing = $review['landing'] ?? null;

        if (! $frozen && is_array($landing)) {
            $card = self::landingStep($landing);

            if ($card !== null) {
                $steps[] = $card;
            }
        }

        foreach ([
            'tests' => ['tests', 'Tests'],
        ] as $key => [$kind, $label]) {
            $text = trim((string) ($review[$key] ?? ''));

            if ($text !== '') {
                $steps[] = self::step($kind, $label, $text);
            }
        }

        return $steps;
    }

    /**
     * @param  array<string, mixed>  $windows
     */
    private static function alignAnalysisToWindows(string $analysis, array $windows): string
    {
        $metrics = self::windowMetricLines($windows);

        if ($metrics === []) {
            return $analysis;
        }

        $lines = self::analysisLines($analysis);
        $aligned = [];
        $inPerformance = false;
        $inserted = false;

        foreach ($lines as $line) {
            $heading = self::headingRemainder($line);
            $isPerformance = $heading !== null && strcasecmp($heading[0], 'Current Performance') === 0;

            if ($isPerformance) {
                $inPerformance = true;
                $aligned[] = 'Current performance';
                array_push($aligned, ...$metrics);
                $inserted = true;

                if ($heading[1] !== '' && self::metricPair($heading[1]) === null && self::numberedItem($heading[1]) === null) {
                    $aligned[] = $heading[1];
                }

                continue;
            }

            if ($inPerformance && ($heading !== null || self::numberedItem($line) !== null)) {
                $inPerformance = false;
            }

            if ($inPerformance && self::metricPair($line) !== null) {
                continue;
            }

            $aligned[] = $line;
        }

        if (! $inserted) {
            array_unshift($aligned, ...$metrics);
            array_unshift($aligned, 'Current performance');
        }

        return implode("\n", $aligned);
    }

    /**
     * @param  array<string, mixed>  $windows
     * @return list<string>
     */
    private static function windowMetricLines(array $windows): array
    {
        $lines = [];

        foreach ([
            '3d' => '3-day',
            '7d' => '7-day',
            '15d' => '15-day',
            '30d' => '30-day',
        ] as $key => $label) {
            $window = $windows[$key] ?? null;

            if (! is_array($window) || ! array_key_exists('spend', $window)) {
                continue;
            }

            $lines[] = $label.' spend: $'.number_format((float) $window['spend'], 2);
            $lines[] = $label.' impressions: '.number_format((int) ($window['impressions'] ?? 0));
            $lines[] = $label.' clicks: '.number_format((int) ($window['clicks'] ?? 0));

            if (is_numeric($window['ctr'] ?? null)) {
                $lines[] = $label.' CTR: '.number_format(((float) $window['ctr']) * 100, 2).'%';
            }

            if (is_numeric($window['cpc'] ?? null)) {
                $lines[] = $label.' CPC: $'.number_format((float) $window['cpc'], 2);
            }

            $lines[] = $label.' conversions: '.number_format((int) ($window['conversions'] ?? 0));
            $lines[] = $label.' conversion value: $'.number_format((float) ($window['conversion_value'] ?? 0), 2);
        }

        return $lines;
    }

    /**
     * @return array{kind: string, label: string, text: string, html: string}
     */
    private static function step(string $kind, string $label, string $text, ?string $html = null): array
    {
        return [
            'kind' => $kind,
            'label' => $label,
            'text' => $text,
            'html' => $html ?? ($kind === 'analysis' ? self::analysisHtml($text) : self::richText($text)),
        ];
    }

    /**
     * @param  array<string, mixed>  $review
     */
    private static function hasCreativeActions(array $review): bool
    {
        $creatives = $review['creatives'] ?? null;

        if (! is_array($creatives)) {
            return false;
        }

        foreach ($creatives as $creative) {
            if (! is_array($creative)) {
                continue;
            }

            if (trim((string) ($creative['replacement_headline'] ?? '')) !== ''
                || trim((string) ($creative['replacement_primary_text'] ?? '')) !== ''
                || trim((string) ($creative['replacement_secondary_text'] ?? '')) !== ''
                || trim((string) ($creative['image_prompt'] ?? '')) !== ''
                || in_array(strtolower(trim((string) ($creative['action'] ?? ''))), ['keep', 'change'], true)) {
                return true;
            }
        }

        return false;
    }

    private static function withoutLongRecommendationItems(string $analysis): string
    {
        $lines = [];
        $skipping = false;
        $heading = null;

        foreach (self::analysisLines($analysis) as $line) {
            $parsed = self::headingRemainder($line);

            if ($parsed !== null && self::isRecommendationHeading($parsed[0])) {
                $skipping = true;
                $heading = $parsed[1] === '' ? $parsed[0] : $line;

                continue;
            }

            if ($parsed !== null) {
                $skipping = false;
                $heading = null;
            }

            if ($skipping) {
                $item = self::numberedItem($line);

                if ($item === null || mb_strlen($item) > 240) {
                    continue;
                }

                if ($heading !== null) {
                    $lines[] = $heading;
                    $heading = null;
                }
            }

            $lines[] = $line;
        }

        return implode("\n", $lines);
    }

    private static function cleanBottleneckText(string $analysis): string
    {
        // 1. Remove prompt-leakage meta-phrases and trailing links
        $analysis = preg_replace('/[A-Z][^.\n]*?(?:commonly explain|commonly emphasize|marketed around|marketed to|marketing emphasizes)[^.\n]*?(?:category context|not evidence)[^.\n]*\.(?:\s*\(\[[^\)]+\)\))?/iu', '', $analysis) ?? $analysis;
        $analysis = preg_replace('/\s*(?:that is|this is)\s+category context,?\s+not evidence[^\n.]*\.(?:\s*\(\[[^\)]+\)\))?/iu', '', $analysis) ?? $analysis;
        $analysis = preg_replace('/\s*The campaign name (?:identifies|indicates) [^.\n]*?from its empty copy fields\./iu', '', $analysis) ?? $analysis;
        $analysis = preg_replace('/\s*The campaign name (?:identifies|indicates) [^.\n]*?but the (?:ad copy|landing text|supplied ads)[^.\n]*?\./iu', '', $analysis) ?? $analysis;

        // 2. Clean up robotic boilerplate phrasing into punchy media-buyer terms
        $analysis = preg_replace('/No delivery yet at a level that supports (?:a diagnosis|an optimization decision):/iu', 'Delivery is the primary constraint:', $analysis) ?? $analysis;
        $analysis = preg_replace('/;\s*the funnel has too little activity to assess, economics are inconclusive, and stability cannot be judged\./iu', '; downstream funnel and conversion economics cannot yet be assessed.', $analysis) ?? $analysis;
        $analysis = preg_replace('/;\s*the funnel and economics are inconclusive, and stability cannot be judged\./iu', '; conversion economics cannot yet be assessed.', $analysis) ?? $analysis;
        $analysis = preg_replace('/No delivery yet is the single constraint[:.]/iu', 'Delivery is the constraint:', $analysis) ?? $analysis;

        return trim(preg_replace('/[ \t]{2,}/', ' ', $analysis));
    }

    private static function isRecommendationHeading(string $heading): bool
    {
        return in_array(strtolower($heading), [
            'proposed changes',
            'recommendations',
            'my recommendations',
            'what to run next',
            "what i'd do next",
            'what i would do next',
        ], true);
    }

    /**
     * @param  array<string, mixed>  $creative
     * @param  array<string, mixed>  $row
     */
    private static function creativeId(array $creative, array $row): string
    {
        $stored = trim((string) ($creative['creative_id'] ?? ''));

        if ($stored !== '') {
            return $stored;
        }

        $adId = trim((string) ($creative['ad_id'] ?? ''));
        $headline = trim((string) ($creative['current_headline'] ?? ''));

        foreach (self::creativeCatalog($row) as $ad) {
            $id = self::idOnAd($ad);

            if ($id === '') {
                continue;
            }

            $candidateAd = trim((string) ($ad['ad_id'] ?? ''));
            $candidateHeadline = trim((string) ($ad['headline'] ?? ''));

            if ($adId !== '' && $candidateAd === $adId) {
                return $id;
            }

            if ($headline !== '' && $candidateHeadline === $headline) {
                return $id;
            }
        }

        return '';
    }

    /**
     * @param  array<string, mixed>  $ad
     */
    private static function idOnAd(array $ad): string
    {
        $id = trim((string) ($ad['creative_id'] ?? ''));

        if ($id !== '') {
            return $id;
        }

        foreach (is_array($ad['images'] ?? null) ? $ad['images'] : [] as $image) {
            if (! is_array($image)) {
                continue;
            }

            $id = trim((string) ($image['creative_id'] ?? ''));

            if ($id !== '') {
                return $id;
            }
        }

        return '';
    }

    /**
     * @param  array<string, mixed>  $row
     * @return list<array<string, mixed>>
     */
    private static function creativeCatalog(array $row): array
    {
        $catalog = [];

        foreach (['ads', 'creatives'] as $key) {
            $rows = data_get($row, 'creative_context.'.$key, []);

            if (! is_array($rows)) {
                continue;
            }

            foreach ($rows as $ad) {
                if (is_array($ad)) {
                    $catalog[] = $ad;
                }
            }
        }

        $images = data_get($row, 'creative_context.images', []);

        if (is_array($images)) {
            foreach ($images as $image) {
                if (is_array($image)) {
                    $catalog[] = $image;
                }
            }
        }

        return $catalog;
    }

    /**
     * @param  array<string, mixed>  $creative
     * @return array{kind: string, label: string, text: string, html: string}|null
     */
    private static function creativeStep(array $creative, string $name): ?array
    {
        $action = strtolower(trim((string) ($creative['action'] ?? '')));
        $headline = trim((string) ($creative['replacement_headline'] ?? ''));
        $primary = trim((string) ($creative['replacement_primary_text'] ?? ''));
        $secondary = trim((string) ($creative['replacement_secondary_text'] ?? ''));
        $imagePrompt = trim((string) ($creative['image_prompt'] ?? ''));
        $creativeId = trim((string) ($creative['creative_id'] ?? ''));
        $adId = trim((string) ($creative['ad_id'] ?? ''));
        $format = strtolower(trim((string) ($creative['format'] ?? '')));
        $cta = self::buttonLabel((string) ($creative['replacement_cta'] ?? ''));
        $why = self::shortWhy((string) ($creative['why'] ?? ''));

        if ($action === '' && $headline === '' && $primary === '' && $secondary === '' && $imagePrompt === '' && $why === '') {
            return null;
        }

        $actionLabel = match ($action) {
            'keep' => 'Keep',
            'change' => 'Change',
            default => $action !== '' ? ucfirst($action) : 'Ad',
        };
        $fields = [];

        if ($headline !== '') {
            $fields[] = ['New headline', $headline];
        }

        if ($primary !== '') {
            $fields[] = ['Primary text', $primary];
        }

        if ($secondary !== '') {
            $fields[] = ['Secondary text', $secondary];
        }

        if ($cta !== '') {
            $fields[] = ['Button', $cta];
        }

        if ($imagePrompt !== '') {
            $fields[] = ['Image prompt', $imagePrompt];
        }

        $html = '<article class="mb-perf-ad">';
        $html .= '<header class="mb-perf-ad-head"><div class="mb-perf-ad-title">';
        $html .= '<p class="mb-perf-ad-subtitle">';
        $html .= $format === 'video' ? 'Video ad' : ($format === 'image' ? 'Image ad' : 'Creative');

        if ($adId !== '') {
            $html .= ' <span class="mb-perf-ad-id">Ad ID '.e($adId).'</span>';
        }

        if ($creativeId !== '' && $creativeId !== $adId) {
            $html .= ' <span class="mb-perf-ad-id">Creative ID '.e($creativeId).'</span>';
        }

        $html .= '</p>';
        $html .= '<h3>'.e($name).'</h3></div>';
        $html .= '<span class="mb-perf-ad-action is-'.e($action !== '' ? $action : 'note').'">'.e($actionLabel).'</span></header>';

        if ($why !== '') {
            $html .= '<p class="mb-perf-ad-why">'.e($why).'</p>';
        }

        if ($fields !== []) {
            $html .= '<dl class="mb-perf-ad-fields">';

            foreach ($fields as [$label, $value]) {
                $html .= '<div><dt>'.e($label).'</dt><dd>'.e($value).'</dd></div>';
            }

            $html .= '</dl>';
        }

        $html .= '</article>';
        $plain = $actionLabel;

        if ($headline !== '') {
            $plain .= '. New headline: '.$headline;
        }

        if ($primary !== '') {
            $plain .= '. Primary text: '.$primary;
        }

        if ($secondary !== '') {
            $plain .= '. Secondary text: '.$secondary;
        }

        if ($cta !== '') {
            $plain .= '. Button: '.$cta;
        }

        if ($imagePrompt !== '') {
            $plain .= '. Image prompt: '.$imagePrompt;
        }

        if ($creativeId !== '') {
            $plain .= '. Creative id: '.$creativeId;
        }

        return self::step('creative', $name, $plain, $html);
    }

    /**
     * @param  array<string, mixed>  $landing
     * @return array{kind: string, label: string, text: string, html: string}|null
     */
    private static function landingStep(array $landing): ?array
    {
        $problem = self::shortWhy((string) ($landing['problem'] ?? ''));
        $flow = trim((string) ($landing['flow'] ?? ''));
        $headline = trim((string) ($landing['headline'] ?? ''));
        $section = trim((string) ($landing['section'] ?? ''));
        $content = trim((string) ($landing['content'] ?? ''));
        $cta = self::buttonLabel((string) ($landing['cta'] ?? ''));
        $prompt = trim((string) ($landing['prompt'] ?? ''));
        $body = $section !== '' ? $section : $content;

        if ($problem === '' && $flow === '' && $headline === '' && $body === '' && $cta === '' && $prompt === '') {
            return null;
        }

        $fields = [];

        if ($headline !== '') {
            $fields[] = ['New headline', $headline];
        }

        if ($body !== '') {
            $fields[] = ['First section', $body];
        }

        if ($flow !== '' && $flow !== $body) {
            $fields[] = ['Page order', $flow];
        }

        if ($cta !== '') {
            $fields[] = ['Button', $cta];
        }

        if ($prompt !== '') {
            $fields[] = ['Landing page prompt', $prompt];
        }

        $html = '<article class="mb-perf-ad">';
        $html .= '<header class="mb-perf-ad-head"><div class="mb-perf-ad-title">';
        $html .= '<p class="mb-perf-ad-subtitle">Landing page</p>';

        if ($headline !== '') {
            $html .= '<h3>'.e($headline).'</h3>';
        }

        $html .= '</div>';
        $html .= '<span class="mb-perf-ad-action is-change">Change</span></header>';

        if ($problem !== '') {
            $html .= '<p class="mb-perf-ad-why">'.e($problem).'</p>';
        }

        if ($fields !== []) {
            $html .= '<dl class="mb-perf-ad-fields">';

            foreach ($fields as [$label, $value]) {
                $html .= '<div><dt>'.e($label).'</dt><dd>'.e($value).'</dd></div>';
            }

            $html .= '</dl>';
        }

        $html .= '</article>';
        $plain = 'Change the landing page.';

        if ($headline !== '') {
            $plain .= ' New headline: '.$headline.'.';
        }

        if ($body !== '') {
            $plain .= ' First section: '.$body.'.';
        }

        if ($cta !== '') {
            $plain .= ' Button: '.$cta.'.';
        }

        if ($prompt !== '') {
            $plain .= ' Landing page prompt: '.$prompt.'.';
        }

        return self::step('landing', 'Landing page', $plain, $html);
    }

    /**
     * @param  array<string, mixed>  $row
     */
    private static function spendPosture(array $row): string
    {
        $status = strtolower(trim((string) ($row['status'] ?? '')));
        $budget = strtolower(trim((string) ($row['budget_summary'] ?? '').' '.(string) data_get($row, 'review.budget', '')));

        if ($status === 'pause' || str_contains($budget, 'pause the campaign') || str_contains($budget, 'stop all')) {
            return 'pause';
        }

        if ($status === 'decrease_budget' || str_contains($budget, 'decrease the daily budget')) {
            return 'decrease';
        }

        return 'hold';
    }

    /**
     * @param  array<string, mixed>  $row
     * @return list<array{kind: string, label: string, text: string, html: string}>
     */
    private static function adSetSteps(array $row): array
    {
        $optimization = $row['ad_set_optimization'] ?? null;

        if (! is_array($optimization)) {
            return [];
        }

        $cards = is_array($optimization['cards'] ?? null)
            ? $optimization['cards']
            : AdSetOptimizationCards::cards($optimization, self::spendPosture($row), AdSetAudienceAction::contextFromRow($row), (string) ($row['platform'] ?? 'meta'));
        $steps = [];

        foreach ($cards as $card) {
            if (! is_array($card)) {
                continue;
            }

            $step = self::adSetStep($card);

            if ($step !== null) {
                $steps[] = $step;
            }
        }

        return $steps;
    }

    /**
     * @param  array<string, mixed>  $card
     * @return array{kind: string, label: string, text: string, html: string}|null
     */
    private static function adSetStep(array $card): ?array
    {
        $name = trim((string) ($card['name'] ?? ''));
        $adSetId = trim((string) ($card['ad_set_id'] ?? ''));
        $action = strtolower(trim((string) ($card['action'] ?? '')));
        $why = self::shortWhy((string) ($card['why'] ?? ''));
        $fields = [];

        foreach (is_array($card['fields'] ?? null) ? $card['fields'] : [] as $field) {
            if (! is_array($field)) {
                continue;
            }

            $label = trim((string) ($field['label'] ?? ''));
            $value = trim((string) ($field['value'] ?? ''));

            if ($label !== '' && $value !== '') {
                $fields[] = [$label, $value];
            }
        }

        if ($name === '' && $adSetId === '' && $why === '' && $fields === []) {
            return null;
        }

        if ($name === '') {
            $name = 'Ad set';
        }

        $actionLabel = match ($action) {
            'keep' => 'Keep',
            'pause' => 'Pause',
            'paused' => 'Paused',
            'review' => 'Review',
            'change' => 'Change',
            default => $action !== '' ? ucfirst($action) : 'Ad set',
        };
        $html = '<article class="mb-perf-ad">';
        $html .= '<header class="mb-perf-ad-head"><div class="mb-perf-ad-title">';
        $html .= '<p class="mb-perf-ad-subtitle">Ad set';

        if ($adSetId !== '') {
            $html .= ' <span class="mb-perf-ad-id">'.e($adSetId).'</span>';
        }

        $html .= '</p>';
        $html .= '<h3>'.e($name).'</h3></div>';
        $html .= '<span class="mb-perf-ad-action is-'.e($action !== '' ? $action : 'note').'">'.e($actionLabel).'</span></header>';

        if ($why !== '') {
            $html .= '<p class="mb-perf-ad-why">'.e($why).'</p>';
        }

        if ($fields !== []) {
            $html .= '<dl class="mb-perf-ad-fields">';

            foreach ($fields as [$label, $value]) {
                $html .= '<div><dt>'.e($label).'</dt><dd>'.e($value).'</dd></div>';
            }

            $html .= '</dl>';
        }

        $html .= '</article>';
        $plain = $actionLabel;

        foreach ($fields as [$label, $value]) {
            $plain .= '. '.$label.': '.$value;
        }

        if ($adSetId !== '') {
            $plain .= '. Ad set id: '.$adSetId;
        }

        return self::step('adset', $name, $plain, $html);
    }

    private static function buttonLabel(string $cta): string
    {
        $cta = trim(str_replace('_', ' ', $cta));

        if ($cta === '') {
            return '';
        }

        return mb_convert_case(mb_strtolower($cta), MB_CASE_TITLE, 'UTF-8');
    }

    private static function shortWhy(string $why): string
    {
        $why = trim(preg_replace('/\s+/', ' ', $why) ?? '');

        if ($why === '' || mb_strlen($why) <= 180) {
            return $why;
        }

        $sentence = preg_split('/(?<=\.)\s+/u', $why, 2)[0] ?? $why;

        if (! is_string($sentence) || $sentence === '' || mb_strlen($sentence) > 180) {
            return '';
        }

        return $sentence;
    }

    private const ANALYSIS_HEADINGS = [
        'current performance',
        'what is working',
        'the good news',
        'the bottleneck',
        'the main problem',
        'ad-by-ad',
        'fatigue',
        'creative not yet',
        'creative',
        'proposed changes',
        'recommendations',
        'my recommendations',
        'what to run next',
        "what i'd do next",
        'what i would do next',
    ];

    private static function analysisHtml(string $text): string
    {
        $blocks = [];
        $currentHeading = 'Current Performance';

        foreach (self::analysisLines($text) as $line) {
            $heading = self::headingRemainder($line);

            if ($heading !== null) {
                $currentHeading = $heading[0];
                $blocks[] = ['type' => 'heading', 'text' => $heading[0]];
                $line = $heading[1];

                if ($line === '') {
                    continue;
                }
            }

            $item = self::numberedItem($line);

            if ($item !== null) {
                $blocks[] = ['type' => 'item', 'text' => $item];

                continue;
            }

            $metric = strcasecmp($currentHeading, 'Current Performance') === 0
                ? self::metricPair($line)
                : null;

            if ($metric !== null) {
                $blocks[] = ['type' => 'metric', 'label' => $metric[0], 'text' => $metric[1]];

                continue;
            }

            $blocks[] = ['type' => 'paragraph', 'text' => $line];
        }

        if ($blocks === []) {
            return '';
        }

        $html = '<div class="mb-perf-analysis">';
        $index = 0;
        $count = count($blocks);
        $inProposed = false;

        while ($index < $count) {
            $block = $blocks[$index];

            if ($block['type'] === 'heading') {
                if ($inProposed) {
                    $html .= '</div>';
                    $inProposed = false;
                }

                if (self::isRecommendationHeading($block['text'])) {
                    $inProposed = true;
                    $html .= '<div class="mb-perf-analysis-proposed">';
                    $html .= '<h3 class="mb-perf-analysis-heading is-proposed"><i class="bi bi-lightning-charge-fill mb-perf-proposed-icon"></i> '.e($block['text']).'</h3>';
                    $index++;

                    continue;
                }

                $html .= '<h3 class="mb-perf-analysis-heading">'.e($block['text']).'</h3>';
                $index++;

                continue;
            }

            if ($block['type'] === 'metric') {
                $html .= '<dl class="mb-perf-analysis-metrics">';

                while ($index < $count && $blocks[$index]['type'] === 'metric') {
                    $html .= '<div class="mb-perf-analysis-metric-cell"><dt>'.e($blocks[$index]['label']).'</dt><dd>'.e($blocks[$index]['text']).'</dd></div>';
                    $index++;
                }

                $html .= '</dl>';

                continue;
            }

            if ($block['type'] === 'item') {
                $listClass = $inProposed ? 'mb-perf-analysis-list is-proposed' : 'mb-perf-analysis-list';
                $html .= '<ol class="'.$listClass.'">';

                while ($index < $count && $blocks[$index]['type'] === 'item') {
                    $html .= '<li>'.e($blocks[$index]['text']).'</li>';
                    $index++;
                }

                $html .= '</ol>';

                continue;
            }

            $copyClass = $inProposed ? 'mb-perf-analysis-copy is-proposed' : 'mb-perf-analysis-copy';
            $html .= '<p class="'.$copyClass.'">'.e($block['text']).'</p>';
            $index++;
        }

        if ($inProposed) {
            $html .= '</div>';
        }

        return $html.'</div>';
    }

    /**
     * @return list<string>
     */
    private static function analysisLines(string $text): array
    {
        $text = str_replace(["\r\n", "\r"], "\n", $text);
        $sortedHeadings = self::ANALYSIS_HEADINGS;
        usort($sortedHeadings, static fn (string $a, string $b): int => strlen($b) <=> strlen($a));
        $headings = implode('|', array_map(
            static fn (string $heading): string => preg_quote($heading, '/'),
            $sortedHeadings,
        ));
        $text = preg_replace('/(?<=[.!?])\s+(?=(?:'.$headings.')[:.]\s*)/i', "\n", $text) ?? $text;
        $text = preg_replace('/(?<=[.!?])\s+(?=[1-9]\d{0,1}\.\s+[A-Z\x22\x27“‘])/u', "\n", $text) ?? $text;
        $lines = preg_split('/\n/', $text) ?: [];

        return array_values(array_filter(array_map(
            static fn (string $line): string => trim($line),
            $lines,
        ), static fn (string $line): bool => $line !== ''));
    }

    /**
     * @return array{0: string, 1: string}|null
     */
    private static function headingRemainder(string $line): ?array
    {
        $sortedHeadings = self::ANALYSIS_HEADINGS;
        usort($sortedHeadings, static fn (string $a, string $b): int => strlen($b) <=> strlen($a));

        foreach ($sortedHeadings as $heading) {
            $pattern = '/^'.preg_quote($heading, '/').'\b[:.]?\s*(.*)$/i';

            if (preg_match($pattern, $line, $matches) !== 1) {
                continue;
            }

            return [ucwords($heading), trim((string) $matches[1])];
        }

        return null;
    }

    private static function numberedItem(string $line): ?string
    {
        if (preg_match('/^\d+\.\s+(.+)$/', $line, $matches) !== 1) {
            return null;
        }

        $item = trim((string) $matches[1]);

        return $item !== '' ? $item : null;
    }

    /**
     * @return array{0: string, 1: string}|null
     */
    private static function metricPair(string $line): ?array
    {
        if (preg_match('/^([^:\n]{2,70}):\s+(\S.*)$/u', $line, $matches) !== 1) {
            return null;
        }

        $label = trim((string) $matches[1]);
        $value = rtrim(trim((string) $matches[2]), '.,');

        if (in_array(strtolower($label), [
            'window',
            'reporting window',
            'reporting period',
            'date window',
            'date range',
            'daily history',
            'history',
            'optimization event',
            'optimization goal',
            'optimization',
            'the bottleneck',
            'ad-by-ad',
            'fatigue',
            'creative',
            'proposed changes',
            'from',
            'to',
        ], true)) {
            return null;
        }

        if (preg_match('/[.;—–?!]/u', $label) === 1 || substr_count($label, ' ') > 8) {
            return null;
        }

        if (preg_match('/\b(is|was|are|were|has|have|had|will|would|can|could|should|blocks)\b/i', $label) === 1) {
            return null;
        }

        if (substr_count($value, ';') > 1 || substr_count($value, '$') > 1) {
            return null;
        }

        if (in_array(strtolower($value), [
            'not on file',
            'none',
            'n/a',
            'unknown',
            'too early',
            'too_early',
            'unavailable',
            'not reported',
            'not set',
            'not available',
            '—',
            '-',
        ], true)) {
            return [$label, $value];
        }

        if (preg_match('/^(\$?[\d,]+(?:\.\d+)?%?)(?:[,\s;(]|$)/i', $value, $valMatch)) {
            $token = rtrim($valMatch[1], ',');
            if (preg_match('/^\d{10,}$/', $token) === 1) {
                return null;
            }

            return [$label, $token];
        }

        if (strlen($value) <= 25 && preg_match('/^[a-z0-9\s—–\/-]+$/i', $value) === 1) {
            return [$label, $value];
        }

        return null;
    }

    public static function richText(string $text): string
    {
        $escaped = e($text);

        $escaped = preg_replace_callback(
            '/\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}(?::\d{2})?)?|\$[\d,]+(?:\.\d+)?|\d{1,2}:\d{2}(?::\d{2})?|\d[\d,]*(?:\.\d+)?%|\b\d[\d,]*(?:\.\d+)?\b|\b[a-z0-9](?:[a-z0-9-]*\.)+[a-z]{2,}(?:\/[^\s<]*)?/i',
            static function (array $matches): string {
                $token = $matches[0];

                if (preg_match('/^\d+$/', $token) === 1 && strlen($token) < 2) {
                    return $token;
                }

                return '<strong class="mb-perf-plan-em">'.$token.'</strong>';
            },
            $escaped,
        ) ?? $escaped;

        return $escaped;
    }

    private static function leverLabel(?string $lever): ?string
    {
        return match ($lever) {
            'spend_more' => 'Spend more',
            'improve_creative' => 'Creative',
            'fix_landing_page' => 'Landing page',
            'hold' => 'Hold',
            default => null,
        };
    }
}
