@php
    $storedStatus = is_string($row['status'] ?? null) ? $row['status'] : null;
    $engineVerdict = \App\Library\CampaignDecision\CampaignDecisionVerdict::tryFromStored($storedStatus)
        ?? \App\Campaigns\PerformanceVerdict::tryFromStored($storedStatus);
    $aiVerdict = \App\Library\CampaignDecision\CampaignDecisionVerdict::tryFromStored($row['ai_status'] ?? null);
    $verdict = $aiVerdict ?? $engineVerdict;
    $statusClass = $verdict?->statusClass() ?? 'queued';
    $statusLabel = $verdict?->label() ?? 'No verdict yet';
    $trendLabel = match ($row['trend'] ?? null) {
        'improving' => 'Improving',
        'declining' => 'Declining',
        'flat' => 'Flat',
        default => '—',
    };
    $adPlatform = match (strtolower((string) ($row['platform'] ?? ''))) {
        'google' => 'Google',
        'linkedin' => 'LinkedIn',
        default => 'Meta',
    };
    $detailUrl = route('campaigns.performance.show', [$row['platform'], $row['external_campaign_id']]);
    $platformStatus = is_string($row['platform_status'] ?? null) && $row['platform_status'] !== ''
        ? str_replace('_', ' ', ucwords(strtolower((string) $row['platform_status'])))
        : null;
    $headline = is_array($row['headline'] ?? null) ? $row['headline'] : null;
    $ctrValue = $headline['ctr'] ?? ($row['ctr_7d'] ?? null);
    $ctrLabel = $ctrValue === null
        ? '—'
        : number_format(((float) $ctrValue) * 100, 2).'%';
    $brief = is_array($row['brief'] ?? null) ? $row['brief'] : [];
    $cpcValue = $headline['cpc'] ?? $row['cpc_7d'];
    $writtenRecommendation = \App\Library\CampaignDecision\CampaignMarketingPlanPresenter::listingUsesStoredAnalysis($row, $verdict);
@endphp
<article class="mb-perf-campaign-card">
    <div class="mb-perf-campaign-head">
        <div class="mb-perf-campaign-title">
            <a href="{{ $detailUrl }}" class="mb-perf-campaign-name" wire:navigate>{{ $row['name'] }}</a>
            <div class="mb-perf-campaign-meta">
                <span>{{ $row['external_campaign_id'] }}</span>
                @if (! empty($row['account_id']))
                    <span>Account {{ $row['account_id'] }}</span>
                @endif
                @if ($row['daily_budget'] !== null && $row['daily_budget'] !== '')
                    <span>${{ number_format((float) $row['daily_budget'], 2) }}/day</span>
                @endif
                @if ($row['region_label'])
                    <span>{{ $row['region_label'] }}</span>
                @endif
            </div>
        </div>
        <div class="mb-perf-campaign-badges">
            <span class="mb-tag mb-platform-tag is-{{ strtolower($adPlatform) }}">
                <i class="bi bi-{{ strtolower($adPlatform) === 'google' ? 'google' : (strtolower($adPlatform) === 'linkedin' ? 'linkedin' : 'meta') }}"></i>
                {{ $adPlatform }}
            </span>
            @if ($platformStatus)
                <span class="mb-tag">{{ $platformStatus }}</span>
            @endif
            <span class="mb-status is-{{ $statusClass }}"><span class="mb-dot"></span>verdict: {{ $statusLabel }}</span>
        </div>
    </div>

    <div class="mb-perf-campaign-metrics">
        <div><span class="mb-perf-metric-label">{{ $headline['compact_spend'] ?? 'Spend 7d' }}</span><strong>${{ number_format($headline['spend'] ?? $row['spend_7d'], 2) }}</strong></div>
        <div><span class="mb-perf-metric-label">{{ $headline['compact_impressions'] ?? 'Impr 7d' }}</span><strong>{{ number_format($headline['impressions'] ?? $row['impressions_7d']) }}</strong></div>
        <div><span class="mb-perf-metric-label">{{ $headline['compact_clicks'] ?? 'Clicks 7d' }}</span><strong>{{ number_format($headline['clicks'] ?? $row['clicks_7d']) }}</strong></div>
        <div><span class="mb-perf-metric-label">CPC</span><strong>{{ $cpcValue === null ? '—' : '$'.number_format((float) $cpcValue, 2) }}</strong></div>
        <div><span class="mb-perf-metric-label">CTR</span><strong>{{ $ctrLabel }}</strong></div>
        <div><span class="mb-perf-metric-label">{{ $headline['compact_conversions'] ?? $adPlatform.' conv.' }}</span><strong>{{ number_format((int) ($headline['conversions'] ?? $row['platform_conversions_7d'] ?? 0)) }}</strong></div>
    </div>

    @if ($row['affiliate_matched'] ?? false)
        <div class="mb-perf-campaign-metrics is-affiliate">
            <div><span class="mb-perf-metric-label">Whale orders</span><strong>{{ number_format((float) ($row['affiliate_orders_7d'] ?? 0), 2) }}</strong></div>
            <div><span class="mb-perf-metric-label">Net revenue</span><strong>${{ number_format((float) ($row['affiliate_net_revenue_7d'] ?? 0), 2) }}</strong></div>
            @php
                $roasMetric = collect($brief['metrics'] ?? [])->first(fn ($m) => ($m['label'] ?? '') === 'ROAS');
                $cpaMetric = collect($brief['metrics'] ?? [])->first(fn ($m) => ($m['label'] ?? '') === 'CPA');
            @endphp
            <div><span class="mb-perf-metric-label">ROAS</span><strong>{{ is_array($roasMetric) ? $roasMetric['value'] : '—' }}</strong></div>
            <div><span class="mb-perf-metric-label">CPA</span><strong>{{ is_array($cpaMetric) ? $cpaMetric['value'] : '—' }}</strong></div>
        </div>
    @elseif (! empty($row['roi_performance']))
        <div class="mb-perf-campaign-metrics is-affiliate">
            <div><span class="mb-perf-metric-label">ROI spent</span><strong>${{ number_format((float) $row['roi_performance']['spent'], 2) }}</strong></div>
            <div><span class="mb-perf-metric-label">ROI sales</span><strong>${{ number_format((float) $row['roi_performance']['arb_sales_amount'], 2) }}</strong></div>
            <div><span class="mb-perf-metric-label">Subscriptions</span><strong>{{ number_format((float) $row['roi_performance']['subscriptions'], 2) }}</strong></div>
            <div><span class="mb-perf-metric-label">ARB orders</span><strong>{{ number_format((float) $row['roi_performance']['arb_orders'], 2) }}</strong></div>
        </div>
    @endif

    <div class="mb-perf-campaign-action">
        @if ($writtenRecommendation)
            @include('campaigns.partials.performance-plan-lines', ['fallback' => 'No AI reason yet. Mapping has not run for this campaign.'])
            @if (! empty($row['verdict_reason']))
                <span class="mb-perf-metric-label">Why this verdict</span>
                <p class="mb-perf-verdict-reason">{{ $row['verdict_reason'] }}</p>
                @if (! empty($row['verdict_reasons']))
                    <ul class="mb-perf-verdict-reasons">
                        @foreach ($row['verdict_reasons'] as $reasonRow)
                            @if (is_array($reasonRow))
                                <li>{{ \App\Library\CampaignDecision\CampaignDecisionReasonFormatter::line($reasonRow) }}</li>
                            @endif
                        @endforeach
                    </ul>
                @endif
            @endif
            @if (! empty($row['ai_status_label']))
                <span class="mb-perf-metric-label">AI status</span>
                <p class="mb-perf-reason">{{ $row['ai_status_label'] }}</p>
            @endif
        @else
            @include('campaigns.partials.performance-brief-short', ['fallback' => 'No suggestion yet. Mapping has not run for this campaign.'])
        @endif
        <div class="mb-perf-campaign-context">
            <span>{{ $row['learning'] }}</span>
            @if ($row['trend_summary'])
                <span>· {{ $row['trend_summary'] }}</span>
            @endif
            @if ($row['platform_learning_label'])
                <span>· {{ $row['platform_learning_label'] }}</span>
            @endif
        </div>
    </div>

    @if (! empty($row['last_error']))
        <div class="mb-note is-error" role="alert">
            <i class="bi bi-exclamation-triangle"></i>
            <div><strong>Last sync failed.</strong> {{ $row['last_error'] }}</div>
        </div>
    @endif

    <div class="mb-perf-campaign-foot">
        <div class="mb-perf-campaign-context">
            <span>{{ $headline['source_label'] ?? 'Whale 7-day' }}</span>
            <span>· Trend {{ $trendLabel }}</span>
            <span>· {{ $row['updated_at']?->diffForHumans() ?? 'Not mapped yet' }}</span>
        </div>
        <a href="{{ $detailUrl }}" class="mb-row-btn" wire:navigate>
            <i class="bi bi-eye"></i>View details
        </a>
    </div>
</article>
