<?php

namespace App\Campaigns;

use Illuminate\Support\Carbon;

/**
 * Numbers and sentences for one campaign recommendation.
 *
 * The chat copies analysis.table and analysis.lines. It does not recalculate
 * them, so a rate or a price in the answer has to be produced here.
 */
class CampaignFunnelAnalysis
{
    /**
     * @param  array<string, mixed>  $delivery
     * @param  list<array<string, mixed>>  $dailyRows
     * @param  list<array<string, mixed>>  $previousDailyRows
     * @param  list<array<string, mixed>>  $adRows
     * @param  list<array<string, mixed>>  $creatives
     * @param  list<array<string, mixed>>  $landingPages
     * @param  array<string, mixed>|null  $roi
     * @param  array<string, float>  $actions
     * @return array<string, mixed>
     */
    public function build(
        string $campaignId,
        ?string $name,
        string $from,
        string $to,
        ?float $dailyBudget,
        ?string $optimizationGoal,
        array $delivery,
        array $dailyRows,
        array $previousDailyRows,
        array $adRows,
        array $creatives,
        array $landingPages,
        ?array $roi,
        array $actions,
    ): array {
        $spend = round((float) ($delivery['spend'] ?? 0), 2);
        $impressions = (int) ($delivery['impressions'] ?? 0);
        $outboundExplicit = array_key_exists('outbound_clicks', $delivery) && $delivery['outbound_clicks'] !== null;
        $outbound = $outboundExplicit
            ? (int) $delivery['outbound_clicks']
            : (int) ($delivery['clicks'] ?? 0);
        $allClicks = array_key_exists('all_clicks', $delivery) && $delivery['all_clicks'] !== null
            ? (int) $delivery['all_clicks']
            : (int) ($delivery['clicks'] ?? 0);
        $conversions = array_key_exists('conversions', $delivery) && $delivery['conversions'] !== null
            ? round((float) $delivery['conversions'], 2)
            : null;
        $subscriptions = is_array($roi) && array_key_exists('subscriptions', $roi)
            ? round((float) $roi['subscriptions'], 2)
            : null;
        $offer = $this->offer($creatives);
        $landing = $this->landing($landingPages);
        $lpv = $this->landingPageViews($actions, $outbound);
        $costPerConversion = $conversions !== null && $conversions > 0 ? round($spend / $conversions, 2) : null;
        $costPerSubscription = $subscriptions !== null && $subscriptions > 0 ? round($spend / $subscriptions, 2) : null;
        $outboundCtr = $impressions > 0 ? $outbound / $impressions : null;
        $conversionRate = $outbound > 0 && $conversions !== null ? $conversions / $outbound : null;
        $cpc = $allClicks > 0 ? round($spend / $allClicks, 2) : null;
        $trend = $this->trend($from, $to, $dailyRows, $previousDailyRows, $outboundExplicit);
        $ads = $this->ads($adRows);
        $clickLabel = $outboundExplicit ? 'outbound clicks' : 'clicks';
        $lines = $this->lines(
            $spend,
            $impressions,
            $outbound,
            $outboundExplicit,
            $outboundCtr,
            $conversions,
            $conversionRate,
            $costPerConversion,
            $subscriptions,
            $lpv,
            $offer,
            $landing,
            $dailyBudget,
            $optimizationGoal,
            $trend,
            $ads,
            $creatives,
        );

        return [
            'campaign_id' => $campaignId,
            'name' => $name,
            'from' => $from,
            'to' => $to,
            'table' => $this->table(
                $spend,
                $impressions,
                $outbound,
                $outboundExplicit,
                $outboundCtr,
                $lpv,
                $conversions,
                $subscriptions,
                $costPerConversion,
                $costPerSubscription,
                $cpc,
            ),
            'funnel' => [
                'spend' => $spend,
                'impressions' => $impressions,
                'outbound_clicks' => $outboundExplicit ? $outbound : null,
                'clicks' => $allClicks,
                'outbound_ctr' => $outboundCtr !== null ? round($outboundCtr, 4) : null,
                'landing_page_views' => $lpv,
                'conversions' => $conversions,
                'subscriptions' => $subscriptions,
                'cost_per_conversion' => $costPerConversion,
                'cost_per_subscription' => $costPerSubscription,
                'cpc' => $cpc,
                'conversion_rate' => $conversionRate !== null ? round($conversionRate, 4) : null,
            ],
            'offer' => $offer,
            'landing' => $landing,
            'trend' => $trend,
            'ads' => $ads,
            'optimization_goal' => $optimizationGoal,
            'daily_budget' => $dailyBudget,
            'lines' => $lines,
            'click_label' => $clickLabel,
        ];
    }

    /**
     * Numbers for one follow-up window. This does not build the performance table or its sentences.
     *
     * @param  array<string, mixed>  $delivery
     * @param  array<string, float>  $actions
     * @return array{
     *     spend: float,
     *     spend_label: string,
     *     impressions: int,
     *     outbound_clicks: int,
     *     click_basis: string,
     *     outbound_ctr: float|null,
     *     outbound_ctr_label: string|null,
     *     landing_page_views: int|null,
     *     conversions: float|null,
     *     cost_per_conversion: float|null,
     *     cost_per_conversion_label: string|null,
     *     cpc: float|null,
     *     cpc_label: string|null
     * }
     */
    public function windowMetrics(array $delivery, array $actions): array
    {
        $spend = round((float) ($delivery['spend'] ?? 0), 2);
        $impressions = (int) ($delivery['impressions'] ?? 0);
        $outboundExplicit = array_key_exists('outbound_clicks', $delivery) && $delivery['outbound_clicks'] !== null;
        $outbound = $outboundExplicit
            ? (int) $delivery['outbound_clicks']
            : (int) ($delivery['clicks'] ?? 0);
        $allClicks = array_key_exists('all_clicks', $delivery) && $delivery['all_clicks'] !== null
            ? (int) $delivery['all_clicks']
            : (int) ($delivery['clicks'] ?? 0);
        $conversions = array_key_exists('conversions', $delivery) && $delivery['conversions'] !== null
            ? round((float) $delivery['conversions'], 2)
            : null;
        $lpv = $this->landingPageViews($actions, $outbound);
        $outboundCtr = $impressions > 0 ? round($outbound / $impressions, 4) : null;
        $costPerConversion = $conversions !== null && $conversions > 0 ? round($spend / $conversions, 2) : null;
        $cpc = $allClicks > 0 ? round($spend / $allClicks, 2) : null;

        return [
            'spend' => $spend,
            'spend_label' => $this->money($spend),
            'impressions' => $impressions,
            'outbound_clicks' => $outbound,
            'click_basis' => $outboundExplicit ? 'outbound_clicks' : 'clicks',
            'outbound_ctr' => $outboundCtr,
            'outbound_ctr_label' => $outboundCtr !== null ? $this->percent($outboundCtr) : null,
            'landing_page_views' => $lpv,
            'conversions' => $conversions,
            'cost_per_conversion' => $costPerConversion,
            'cost_per_conversion_label' => $costPerConversion !== null ? $this->money($costPerConversion) : null,
            'cpc' => $cpc,
            'cpc_label' => $cpc !== null ? $this->money($cpc) : null,
        ];
    }

    /**
     * @return list<array{0: string, 1: string}>
     */
    private function table(
        float $spend,
        int $impressions,
        int $outbound,
        bool $outboundExplicit,
        ?float $outboundCtr,
        ?int $lpv,
        ?float $conversions,
        ?float $subscriptions,
        ?float $costPerConversion,
        ?float $costPerSubscription,
        ?float $cpc,
    ): array {
        $rows = [
            ['Spend', $this->money($spend)],
            ['Impressions', (string) $impressions],
        ];

        if ($outboundExplicit) {
            $rows[] = ['Outbound clicks', (string) $outbound];
            if ($outboundCtr !== null) {
                $rows[] = ['Outbound CTR', $this->percent($outboundCtr)];
            }
        } else {
            $rows[] = ['Clicks', (string) $outbound];
            if ($outboundCtr !== null) {
                $rows[] = ['CTR', $this->percent($outboundCtr)];
            }
        }

        if ($lpv !== null && $outbound > 0) {
            $rows[] = ['Landing page views', (string) $lpv];
            $rows[] = ['LPV / outbound click', $this->percent($lpv / $outbound)];
            $rows[] = ['LPV cost', $this->money($spend / $lpv)];
        }

        if ($conversions !== null) {
            $rows[] = ['Conversions', $this->count($conversions)];
        }

        if ($subscriptions !== null) {
            $rows[] = ['Subscriptions', $this->count($subscriptions)];
        }

        if ($costPerConversion !== null) {
            $rows[] = ['Cost per conversion', $this->money($costPerConversion)];
        }

        if ($costPerSubscription !== null) {
            $rows[] = ['Cost per subscription', $this->money($costPerSubscription)];
        }

        if ($cpc !== null) {
            $rows[] = ['CPC', $this->money($cpc)];
        }

        return $rows;
    }

    /**
     * @param  array<string, mixed>  $offer
     * @param  array<string, mixed>  $landing
     * @param  array<string, mixed>  $trend
     * @param  list<array<string, mixed>>  $ads
     * @param  list<array<string, mixed>>  $creatives
     * @return array<string, string|null>
     */
    private function lines(
        float $spend,
        int $impressions,
        int $outbound,
        bool $outboundExplicit,
        ?float $outboundCtr,
        ?float $conversions,
        ?float $conversionRate,
        ?float $costPerConversion,
        ?float $subscriptions,
        ?int $lpv,
        array $offer,
        array $landing,
        ?float $dailyBudget,
        ?string $optimizationGoal,
        array $trend,
        array $ads,
        array $creatives,
    ): array {
        $clickLabel = $outboundExplicit ? 'outbound clicks' : 'clicks';
        $ctrLabel = $outboundExplicit ? 'outbound CTR' : 'CTR';

        return [
            'working' => $this->workingLine($outbound, $impressions, $outboundCtr, $ctrLabel, $clickLabel, $lpv),
            'problem' => $this->problemLine($outbound, $clickLabel, $conversions, $conversionRate, $costPerConversion, $subscriptions, $trend),
            'budget' => $this->budgetLine($spend, $dailyBudget, $conversions, $costPerConversion, $offer),
            'landing' => $this->landingLine($outbound, $outboundCtr, $landing, $offer, $creatives),
            'creatives' => $this->creativeLine($outboundCtr, $ctrLabel, $offer, $creatives),
            'fatigue' => $this->fatigueLine($trend),
            'ads' => $this->adsLine($ads),
            'event' => $this->eventLine($optimizationGoal),
            'next' => $this->nextLine($spend),
        ];
    }

    private function workingLine(int $outbound, int $impressions, ?float $ctr, string $ctrLabel, string $clickLabel, ?int $lpv): ?string
    {
        if ($impressions <= 0 && $outbound <= 0) {
            return 'There is no delivery in this window, so there is nothing to judge yet.';
        }

        $line = $outbound.' '.$clickLabel.' on '.$impressions.' impressions';
        $article = preg_match('/^[aeiou]/i', $ctrLabel) === 1 ? 'an' : 'a';
        $line .= $ctr !== null ? ' is '.$article.' '.$ctrLabel.' of '.$this->percent($ctr).'.' : '.';

        if ($ctr !== null && $ctr >= 0.01) {
            $line .= ' That click rate is high enough to test the page. Do not replace the offer.';
        }

        if ($lpv !== null && $outbound > 0) {
            $line .= ' Landing page views are '.$lpv.', '.$this->percent($lpv / $outbound).' of '.$clickLabel.', so the click is reaching the page.';
        } elseif ($outbound > 0) {
            $line .= ' Landing page views are not on file, so a page-load problem is not confirmed and is not ruled out.';
        }

        return $line;
    }

    /**
     * @param  array<string, mixed>  $trend
     */
    private function problemLine(
        int $outbound,
        string $clickLabel,
        ?float $conversions,
        ?float $conversionRate,
        ?float $costPerConversion,
        ?float $subscriptions,
        array $trend,
    ): ?string {
        if ($outbound <= 0 && $conversions === null) {
            return null;
        }

        if ($conversions === null) {
            return 'Conversions are not on file for this window, so the post-click result cannot be judged from Whale delivery.';
        }

        $line = 'The constraint is after the click. '.$outbound.' '.$clickLabel.' produced '.$this->count($conversions).' conversions';
        $line .= $conversionRate !== null ? ' ('.$this->percent($conversionRate).').' : '.';

        if ($costPerConversion !== null) {
            $line .= ' Cost per conversion is '.$this->money($costPerConversion).'.';
        }

        if ($subscriptions !== null) {
            $line .= ' ROI subscriptions are '.$this->count($subscriptions).'. The result used is Whale conversions, not subscriptions.';
        }

        if (($trend['comparable'] ?? false) === true && is_array($trend['change'] ?? null)) {
            $changes = $this->changeClause($trend['change'], (string) ($trend['label'] ?? 'the prior window'));

            if ($changes !== '') {
                $line .= ' '.$changes;
            }
        }

        return $line;
    }

    /**
     * @param  array<string, mixed>  $offer
     */
    private function budgetLine(float $spend, ?float $dailyBudget, ?float $conversions, ?float $costPerConversion, array $offer): ?string
    {
        if ($spend <= 0) {
            return 'There is no spend in this window. Do not change the budget.';
        }

        $budget = $dailyBudget !== null ? ' Daily budget is '.$this->money($dailyBudget).'.' : '';
        $price = isset($offer['price']) ? ' That is above the '.$this->money((float) $offer['price']).$this->priceUnit($offer).' price in the ads.' : '';

        if ($conversions === null) {
            return 'Do not scale. Do not increase the daily budget until conversions are on file.'.$budget;
        }

        if ($conversions <= 0) {
            return 'Do not scale. Spend is '.$this->money($spend).' and conversions are 0. Do not increase the daily budget.'.$budget;
        }

        if ($costPerConversion !== null && isset($offer['price']) && $costPerConversion > (float) $offer['price']) {
            return 'Do not scale. Cost per conversion is '.$this->money($costPerConversion).'.'.$price.' Do not increase the daily budget.'.$budget;
        }

        if ($costPerConversion !== null) {
            return 'Do not scale yet. Cost per conversion is '.$this->money($costPerConversion).'. Do not increase the daily budget.'.$budget;
        }

        return 'Do not increase the daily budget.'.$budget;
    }

    /**
     * @param  array<string, mixed>  $landing
     * @param  array<string, mixed>  $offer
     * @param  list<array<string, mixed>>  $creatives
     */
    private function landingLine(int $outbound, ?float $ctr, array $landing, array $offer, array $creatives): ?string
    {
        if ($outbound <= 0) {
            return null;
        }

        $url = is_string($landing['url'] ?? null) && $landing['url'] !== '' ? $landing['url'] : null;
        $where = $url !== null ? ' at '.$url : '';

        if ($ctr !== null && $ctr < 0.01) {
            return 'The landing page'.$where.' is not the first test. The click rate is under 1%, so fix the ad before rewriting the page.';
        }

        if (($landing['text_available'] ?? false) === true) {
            $heading = is_string($landing['heading'] ?? null) && $landing['heading'] !== '' ? $landing['heading'] : null;
            $quoted = $heading !== null ? ' Use the page heading "'.$heading.'".' : '';

            return 'The first test is the landing page'.$where.'. Page text is on file. Put the offer and one call to action above the fold.'.$quoted.' Do not add sections before that call to action.';
        }

        $headline = $this->firstHeadline($creatives);
        $offerBit = isset($offer['price'])
            ? ' State the '.$this->money((float) $offer['price']).$this->priceUnit($offer).' price.'
            : '';
        $headlineBit = $headline !== null ? ' Use the existing headline "'.$headline.'".' : '';

        return 'The first test is the landing page'.$where.'. The live page text was not read. Test one above-the-fold block from the current ads.'.$headlineBit.$offerBit.' Then show the product and one get-started call to action, with nothing else before that call to action.';
    }

    /**
     * @param  array<string, mixed>  $offer
     * @param  list<array<string, mixed>>  $creatives
     */
    private function creativeLine(?float $ctr, string $ctrLabel, array $offer, array $creatives): ?string
    {
        if ($ctr === null || $ctr < 0.01 || $creatives === []) {
            return null;
        }

        $angles = $this->angles($offer, $creatives);

        if ($angles === []) {
            return null;
        }

        return 'Keep the current offer. '.ucfirst($ctrLabel).' is '.$this->percent($ctr).'. Add creatives on that same offer: '.implode(' ', $angles);
    }

    /**
     * @param  array<string, mixed>  $trend
     */
    private function fatigueLine(array $trend): ?string
    {
        if (($trend['comparable'] ?? false) !== true) {
            return null;
        }

        $ctr = $trend['change']['ctr'] ?? null;

        if (! is_numeric($ctr) || (float) $ctr >= 0) {
            return null;
        }

        return 'CTR changed '.$this->signedPercent((float) $ctr).' '.$trend['label'].'. Add fresh creatives. Do not raise the budget to offset that drop.';
    }

    /**
     * @param  list<array<string, mixed>>  $ads
     */
    private function adsLine(array $ads): ?string
    {
        if ($ads === []) {
            return 'Ad-level spend is not on file, so no ad is named a winner.';
        }

        $parts = [];
        $small = [];

        foreach ($ads as $ad) {
            $name = (string) ($ad['name'] ?? 'Ad');
            $spend = (float) ($ad['spend'] ?? 0);
            $conversions = (float) ($ad['conversions'] ?? 0);
            $sentence = $name.': spend '.$this->money($spend).', '.$this->conversionCount($conversions);

            if ($conversions > 0) {
                $sentence .= ', cost per conversion '.$this->money($spend / $conversions);
            }

            $sentence .= '.';

            if (($ad['enough_spend'] ?? false) === true) {
                $parts[] = $sentence;
            } else {
                $small[] = $name.' ('.$this->money($spend).')';
            }
        }

        if ($small !== []) {
            $parts[] = 'Too little spend to judge: '.implode(', ', $small).'.';
        }

        $winner = $this->winner($ads);
        $parts[] = $winner === null
            ? 'There is no clear winner.'
            : 'The lower cost is '.$winner.'.';

        return implode(' ', $parts);
    }

    private function eventLine(?string $optimizationGoal): ?string
    {
        $goal = trim((string) $optimizationGoal);

        if ($goal === '') {
            return 'The optimization goal is not on file. Count a conversion only after the paid result is completed, not when checkout or account creation starts.';
        }

        return 'Optimization goal is '.$goal.'. The conversion event name is not on file. Count a conversion only after that goal is completed, not when checkout or account creation starts.';
    }

    private function nextLine(float $spend): ?string
    {
        if ($spend <= 0) {
            return null;
        }

        return 'Add the new creatives and one landing-page variant. Judge after 14 days on conversion rate and cost per conversion.';
    }

    /**
     * @param  array<string, float|null>  $change
     */
    private function changeClause(array $change, string $label): string
    {
        $bits = [];

        foreach ([
            'ctr' => 'CTR',
            'cvr' => 'conversion rate',
            'cpr' => 'cost per result',
            'cpm' => 'CPM',
        ] as $key => $name) {
            if (! is_numeric($change[$key] ?? null)) {
                continue;
            }

            $bits[] = $name.' '.$this->signedPercent((float) $change[$key]);
        }

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

        return ucfirst($label).': '.implode(', ', $bits).'.';
    }

    /**
     * @param  list<array<string, mixed>>  $currentRows
     * @param  list<array<string, mixed>>  $previousRows
     * @return array<string, mixed>
     */
    private function trend(string $from, string $to, array $currentRows, array $previousRows, bool $outboundExplicit): array
    {
        $previous = $this->half($previousRows, $outboundExplicit);
        $usePrevious = $previous['days'] >= 7 && $previous['impressions'] >= 100;

        if ($usePrevious) {
            $current = $this->half($currentRows, $outboundExplicit);

            return $this->trendResult($current, $previous, 'versus the previous window');
        }

        $start = Carbon::parse($from)->startOfDay();
        $end = Carbon::parse($to)->startOfDay();
        $length = $start->diffInDays($end) + 1;
        $firstDays = intdiv($length, 2);
        $mid = $start->copy()->addDays(max(0, $firstDays - 1))->toDateString();
        $first = [];
        $second = [];

        foreach ($currentRows as $row) {
            $date = (string) ($row['date'] ?? '');

            if ($date === '' || $date < $from || $date > $to) {
                continue;
            }

            if ($date <= $mid) {
                $first[] = $row;
            } else {
                $second[] = $row;
            }
        }

        return $this->trendResult(
            $this->half($second, $outboundExplicit),
            $this->half($first, $outboundExplicit),
            'in the second half of this window versus the first half',
        );
    }

    /**
     * @param  array{days: int, impressions: int, outbound: int, spend: float, conversions: float, ctr: ?float, cvr: ?float, cpr: ?float, cpm: ?float}  $current
     * @param  array{days: int, impressions: int, outbound: int, spend: float, conversions: float, ctr: ?float, cvr: ?float, cpr: ?float, cpm: ?float}  $previous
     * @return array<string, mixed>
     */
    private function trendResult(array $current, array $previous, string $label): array
    {
        $comparable = $current['days'] >= 5
            && $previous['days'] >= 5
            && $current['impressions'] >= 100
            && $previous['impressions'] >= 100;

        return [
            'comparable' => $comparable,
            'label' => $label,
            'change' => [
                'ctr' => $this->percentChange($current['ctr'], $previous['ctr']),
                'cvr' => $this->percentChange($current['cvr'], $previous['cvr']),
                'cpr' => $this->percentChange($current['cpr'], $previous['cpr']),
                'cpm' => $this->percentChange($current['cpm'], $previous['cpm']),
            ],
        ];
    }

    /**
     * @param  list<array<string, mixed>>  $rows
     * @return array{days: int, impressions: int, outbound: int, spend: float, conversions: float, ctr: ?float, cvr: ?float, cpr: ?float, cpm: ?float}
     */
    private function half(array $rows, bool $outboundExplicit): array
    {
        $days = 0;
        $impressions = 0;
        $outbound = 0;
        $spend = 0.0;
        $conversions = 0.0;

        foreach ($rows as $row) {
            $rowImpressions = (int) ($row['impressions'] ?? 0);

            if ($rowImpressions <= 0 && (float) ($row['spend'] ?? 0) <= 0) {
                continue;
            }

            $days++;
            $impressions += $rowImpressions;
            $spend += (float) ($row['spend'] ?? 0);
            $conversions += (float) ($row['conversions'] ?? 0);
            $outbound += $outboundExplicit && array_key_exists('outbound_clicks', $row) && $row['outbound_clicks'] !== null
                ? (int) $row['outbound_clicks']
                : (int) ($row['clicks'] ?? 0);
        }

        $spend = round($spend, 2);

        return [
            'days' => $days,
            'impressions' => $impressions,
            'outbound' => $outbound,
            'spend' => $spend,
            'conversions' => $conversions,
            'ctr' => $impressions > 0 ? $outbound / $impressions : null,
            'cvr' => $outbound > 0 ? $conversions / $outbound : null,
            'cpr' => $conversions > 0 ? $spend / $conversions : null,
            'cpm' => $impressions > 0 ? ($spend / $impressions) * 1000 : null,
        ];
    }

    /**
     * @param  list<array<string, mixed>>  $adRows
     * @return list<array<string, mixed>>
     */
    private function ads(array $adRows): array
    {
        $names = array_map(static fn (array $row): string => (string) ($row['name'] ?? 'Ad'), $adRows);
        $nameCounts = array_count_values($names);
        $ads = [];

        foreach ($adRows as $row) {
            $spend = round((float) ($row['spend'] ?? 0), 2);

            if ($spend <= 0 && (float) ($row['conversions'] ?? 0) <= 0) {
                continue;
            }

            $conversions = round((float) ($row['conversions'] ?? 0), 2);
            $name = (string) ($row['name'] ?? 'Ad');
            $adId = trim((string) ($row['ad_id'] ?? ''));

            if (($nameCounts[$name] ?? 0) > 1 && $adId !== '') {
                $name .= ' ('.$adId.')';
            }

            $ads[] = [
                'name' => $name,
                'spend' => $spend,
                'conversions' => $conversions,
                'cost_per_conversion' => $conversions > 0 ? round($spend / $conversions, 2) : null,
                'enough_spend' => $spend >= 20 || $conversions >= 1,
            ];
        }

        usort($ads, fn (array $left, array $right): int => $right['spend'] <=> $left['spend']);

        return $ads;
    }

    /**
     * @param  list<array<string, mixed>>  $ads
     */
    private function winner(array $ads): ?string
    {
        $qualified = array_values(array_filter(
            $ads,
            fn (array $ad): bool => (float) ($ad['conversions'] ?? 0) >= 1 && isset($ad['cost_per_conversion']),
        ));

        if (count($qualified) < 2) {
            return null;
        }

        usort($qualified, fn (array $left, array $right): int => $left['cost_per_conversion'] <=> $right['cost_per_conversion']);
        $best = $qualified[0];
        $next = $qualified[1];

        if ((float) $best['conversions'] < 2) {
            return null;
        }

        if ((float) $best['cost_per_conversion'] > (float) $next['cost_per_conversion'] * 0.75) {
            return null;
        }

        return (string) $best['name'];
    }

    /**
     * @param  array<string, float>  $actions
     */
    private function landingPageViews(array $actions, int $outbound): ?int
    {
        $counts = [];

        foreach ($actions as $name => $count) {
            if (in_array(strtolower((string) $name), ['landing_page_view', 'omni_landing_page_view'], true)) {
                $counts[] = (float) $count;
            }
        }

        if ($counts === [] || $outbound <= 0) {
            return null;
        }

        $views = (int) round(max($counts));

        if ($views <= 0 || ($views / $outbound) < 0.5) {
            return null;
        }

        return $views;
    }

    /**
     * @param  list<array<string, mixed>>  $creatives
     * @return array{price: float|null, compared_price: float|null, unit: string|null}
     */
    private function offer(array $creatives): array
    {
        $blob = $this->creativeBlob($creatives);
        preg_match_all('/\$(\d+(?:\.\d{1,2})?)/', $blob, $matches);
        $prices = array_values(array_unique(array_map(static fn (string $price): float => (float) $price, $matches[1] ?? [])));
        sort($prices);
        $unit = preg_match('/\/mo\b|\/month\b|\bmonth\b/i', $blob) === 1 ? 'month' : null;
        $price = $prices[0] ?? null;
        $compared = null;

        if (count($prices) >= 2 && $prices[0] > 0 && $prices[count($prices) - 1] >= $prices[0] * 5) {
            $compared = $prices[count($prices) - 1];
        }

        return [
            'price' => $price,
            'compared_price' => $compared,
            'unit' => $unit,
        ];
    }

    /**
     * @param  array<string, mixed>  $offer
     * @param  list<array<string, mixed>>  $creatives
     * @return list<string>
     */
    private function angles(array $offer, array $creatives): array
    {
        $angles = [];
        $blob = $this->creativeBlob($creatives);

        if (isset($offer['price'], $offer['compared_price'])) {
            $angles[] = 'Price: keep '.$this->money((float) $offer['price']).$this->priceUnit($offer).' against the '.$this->money((float) $offer['compared_price']).' already in the ads.';
        } elseif (isset($offer['price'])) {
            $angles[] = 'Price: keep the '.$this->money((float) $offer['price']).$this->priceUnit($offer).' offer already in the ads.';
        }

        if (preg_match('/workflow|jumping between|between tools/i', $blob) === 1) {
            $angles[] = 'Workflow: keep the line already in the primary text about not jumping between tools.';
        }

        $headline = $this->firstHeadline($creatives);

        if ($headline !== null) {
            $angles[] = 'Product: keep the existing headline "'.$headline.'".';
        }

        return $angles;
    }

    /**
     * @param  list<array<string, mixed>>  $pages
     * @return array{url: ?string, text_available: bool, heading: ?string}
     */
    private function landing(array $pages): array
    {
        $page = $pages[0] ?? [];
        $text = trim((string) ($page['text'] ?? ''));
        $headings = is_array($page['headings'] ?? null) ? $page['headings'] : [];
        $heading = null;

        foreach ($headings as $value) {
            if (is_string($value) && trim($value) !== '') {
                $heading = trim($value);
                break;
            }
        }

        return [
            'url' => is_string($page['url'] ?? null) && $page['url'] !== '' ? $page['url'] : null,
            'text_available' => $text !== '',
            'heading' => $heading,
        ];
    }

    /**
     * @param  list<array<string, mixed>>  $creatives
     */
    private function creativeBlob(array $creatives): string
    {
        $parts = [];

        foreach ($creatives as $creative) {
            foreach ($this->headlines($creative['headlines'] ?? null) as $headline) {
                $parts[] = $headline;
            }

            if (is_string($creative['primary_text'] ?? null)) {
                $parts[] = $creative['primary_text'];
            }
        }

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

    /**
     * @param  list<array<string, mixed>>  $creatives
     */
    private function firstHeadline(array $creatives): ?string
    {
        foreach ($creatives as $creative) {
            foreach ($this->headlines($creative['headlines'] ?? null) as $headline) {
                $headline = trim($headline);

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

        return null;
    }

    /**
     * @return list<string>
     */
    private function headlines(mixed $value): array
    {
        if (is_array($value)) {
            return array_values(array_filter($value, 'is_string'));
        }

        if (! is_string($value) || trim($value) === '') {
            return [];
        }

        $decoded = json_decode($value, true);

        if (is_array($decoded)) {
            return array_values(array_filter($decoded, 'is_string'));
        }

        return [$value];
    }

    /**
     * @param  array<string, mixed>  $offer
     */
    private function priceUnit(array $offer): string
    {
        return ($offer['unit'] ?? null) === 'month' ? '/month' : '';
    }

    private function percentChange(?float $current, ?float $previous): ?float
    {
        if ($current === null || $previous === null || $previous == 0.0) {
            return null;
        }

        return round((($current - $previous) / $previous) * 100, 1);
    }

    private function money(float $amount): string
    {
        return '$'.number_format($amount, 2);
    }

    private function percent(float $ratio): string
    {
        return number_format($ratio * 100, 2).'%';
    }

    private function signedPercent(float $change): string
    {
        return ($change > 0 ? '+' : '').number_format($change, 1).'%';
    }

    private function conversionCount(float $value): string
    {
        $count = $this->count($value);

        return $count.' '.($count === '1' ? 'conversion' : 'conversions');
    }

    private function count(float $value): string
    {
        return fmod($value, 1.0) === 0.0 ? (string) (int) $value : number_format($value, 2);
    }
}
