@use('App\Campaigns\Manager\ManagerFormat')
@use('App\Models\CampaignPlatformDrift')
@use('App\Models\CampaignEntityEdit')
@use('App\Campaigns\Manager\Editing\EditCapabilities')
@use('Illuminate\Support\Str')
@php
    $fresh = ManagerFormat::freshness($campaign->latestSyncRun, $campaign->latestSuccessfulSyncRun, $staleAfter);
    $platformName = ManagerFormat::platform($campaign->platform);
    $lastGood = $campaign->latestSuccessfulSyncRun;
@endphp
<div class="mb-page mb-cm" wire:init="refreshIfStale">
    @push('styles')
        <link href="{{ asset('assets/mb/css/campaigns.css') }}?v={{ filemtime(public_path('assets/mb/css/campaigns.css')) }}" rel="stylesheet">
        <link href="{{ asset('assets/mb/css/campaign-manager.css') }}?v={{ filemtime(public_path('assets/mb/css/campaign-manager.css')) }}" rel="stylesheet">
    @endpush

    <div class="mb-page-inner">
        <a href="{{ route('campaign-manager.index') }}" class="mb-cm-back" wire:navigate><i class="bi bi-arrow-left"></i> All campaigns</a>

        <div class="mb-cm-hero">
            <div class="mb-cm-hero-main">
                <span class="mb-cm-mark is-lg is-{{ $campaign->platform }}" aria-hidden="true"><i class="bi {{ ManagerFormat::platformIcon($campaign->platform) }}"></i></span>
                <div class="min-w-0">
                    <h1 class="mb-cm-hero-title">{{ $campaign->name }}</h1>
                    <div class="mb-cm-chips">
                        <span class="mb-tag mb-platform-tag is-{{ $campaign->platform }}"><i class="bi {{ ManagerFormat::platformIcon($campaign->platform) }}"></i> {{ $platformName }}</span>
                        <span class="mb-tag" title="Campaign id on {{ $platformName }}"><i class="bi bi-hash"></i> <span class="mb-cm-mono">{{ $campaign->external_campaign_id }}</span></span>
                        @if ($campaign->ad_account_id)
                            <span class="mb-tag" title="Ad account"><i class="bi bi-building"></i> <span class="mb-cm-mono">{{ $campaign->ad_account_id }}</span></span>
                        @endif
                        <span class="mb-tag" title="Currency budgets and bids are shown in"><i class="bi bi-currency-exchange"></i> {{ $campaign->currency ?: 'Account currency' }}</span>
                    </div>
                </div>
            </div>
            <div class="mb-cm-hero-actions">
                <span class="mb-status is-{{ $fresh['class'] }}"><span class="mb-dot"></span>{{ $fresh['label'] }}</span>
                <button type="button" class="mb-btn-ghost" wire:click="refresh" wire:loading.attr="disabled" wire:target="refresh,refreshIfStale">
                    <i class="bi bi-arrow-clockwise"></i>
                    <span wire:loading.remove wire:target="refresh,refreshIfStale">Refresh from {{ $platformName }}</span>
                    <span wire:loading wire:target="refresh,refreshIfStale">Reading…</span>
                </button>
            </div>
        </div>

        @if ($problem)
            <div class="mb-cm-alert is-err" role="alert"><i class="bi bi-exclamation-octagon"></i><div>{{ $problem }}</div></div>
        @endif
        @if ($notice)
            <div class="mb-cm-alert is-info" role="status"><i class="bi bi-info-circle"></i><div>{{ $notice }}</div></div>
        @endif
        @if ($lastGood?->gaps)
            <div class="mb-cm-alert is-warn" role="status">
                <i class="bi bi-exclamation-triangle"></i>
                <div>
                    <strong>The last read was incomplete.</strong>
                    <ul>
                        @foreach ($lastGood->gaps as $gap)
                            <li>{{ $gap }}</li>
                        @endforeach
                    </ul>
                </div>
            </div>
        @endif

        <div class="mb-stats">
            <div class="mb-stat">
                <span class="mb-stat-icon is-all"><i class="bi bi-diagram-3"></i></span>
                <div>
                    <div class="mb-stat-num">{{ $entityCount }}</div>
                    <div class="mb-stat-label">
                        @if ($typeCounts->isEmpty())
                            Objects
                        @else
                            {{ $typeCounts->map(fn ($count, $type) => $count.' '.strtolower(ManagerFormat::type($type)).($count === 1 ? '' : 's'))->implode(' · ') }}
                        @endif
                    </div>
                </div>
            </div>
            <div class="mb-stat">
                <span class="mb-stat-icon {{ $recentDriftCount > 0 ? 'is-run' : 'is-ok' }}"><i class="bi bi-activity"></i></span>
                <div>
                    <div class="mb-stat-num">{{ $recentDriftCount }}</div>
                    <div class="mb-stat-label">Changes seen in 7 days</div>
                </div>
            </div>
            <div class="mb-stat">
                <span class="mb-stat-icon is-all"><i class="bi bi-pencil-square"></i></span>
                <div>
                    <div class="mb-stat-num">{{ $edits->count() }}</div>
                    <div class="mb-stat-label">Recent edits made here</div>
                </div>
            </div>
            <div class="mb-stat">
                <span class="mb-stat-icon {{ $fresh['class'] === 'completed' ? 'is-ok' : ($fresh['class'] === 'failed' ? 'is-err' : 'is-run') }}"><i class="bi bi-clock-history"></i></span>
                <div>
                    <div class="mb-stat-num" @if ($lastGood) title="{{ $lastGood->started_at->toDayDateTimeString() }}" @endif>{{ $lastGood ? $lastGood->started_at->diffForHumans(short: true) : 'Never' }}</div>
                    <div class="mb-stat-label">Last good read</div>
                </div>
            </div>
        </div>

        <section class="mb-card mb-4">
            <div class="mb-cm-body">
                <h2 class="h5">Spend, bids and budgets</h2>
                <p class="mb-cm-note">Available for active and paused campaigns. Budgets and bids appear on the objects below; lifetime spend is retrieved separately from {{ $platformName }}.</p>
                <button type="button" class="mb-btn-ghost" wire:click="loadDelivery" wire:loading.attr="disabled" wire:target="loadDelivery">
                    <i class="bi bi-wallet2"></i> Retrieve lifetime spend
                </button>
                @if ($delivery !== null)
                    <dl class="mt-3 mb-0">
                        <dt>Lifetime spend</dt>
                        <dd>{{ number_format($delivery['spend'], \App\Support\CurrencyMinorUnits::decimals($campaign->currency ?: 'USD')) }} {{ $campaign->currency }}</dd>
                        <dt>Lifetime impressions</dt>
                        <dd>{{ number_format($delivery['impressions']) }}</dd>
                        <dt>Retrieved</dt>
                        <dd>{{ $delivery['read_at'] }}</dd>
                    </dl>
                @endif
            </div>
        </section>

        <section class="mb-card">
            <div class="mb-perf-card-head">
                <div class="mb-perf-card-title-wrap">
                    <div class="mb-perf-card-title-row">
                        <span class="mb-perf-card-icon mb-cm-perf-icon"><i class="bi bi-diagram-3"></i></span>
                        <h2 class="mb-perf-card-title">Structure <span class="mb-perf-title-sub">{{ $entityCount }} object(s)</span></h2>
                    </div>
                </div>
            </div>
            <div class="mb-cm-body">
                <p class="mb-cm-note">
                    @if ($lastGood)
                        As {{ $platformName }} reported on {{ $lastGood->started_at->toDayDateTimeString() }} ({{ $lastGood->started_at->diffForHumans() }}).
                    @else
                        Not read from the platform yet.
                    @endif
                    Budgets and bids are in {{ $campaign->currency ?: 'the account currency' }}.
                </p>
                @if ($roots->isEmpty())
                    <div class="mb-empty">
                        <div class="mb-empty-icon"><i class="bi bi-diagram-3"></i></div>
                        <div class="mb-empty-title">Nothing read yet</div>
                        <div>Use Refresh to read this campaign from the platform.</div>
                    </div>
                @else
                    <ul class="mb-cm-tree">
                        @foreach ($roots as $entity)
                            @include('livewire.campaign-manager.partials.entity', ['entity' => $entity, 'depth' => 0])
                        @endforeach
                    </ul>
                @endif
            </div>
        </section>

        <section class="mb-card">
            <div class="mb-perf-card-head">
                <div class="mb-perf-card-title-wrap">
                    <div class="mb-perf-card-title-row">
                        <span class="mb-perf-card-icon mb-cm-perf-icon is-warn"><i class="bi bi-activity"></i></span>
                        <h2 class="mb-perf-card-title">Changes seen on the platform <span class="mb-perf-title-sub">latest {{ $drifts->count() }}</span></h2>
                    </div>
                    <div class="mb-cell-meta">Differences between successive reads: from Ads Manager, the Google Ads UI, LinkedIn Campaign Manager, automated rules, or edits made here.</div>
                </div>
            </div>
            @if ($drifts->isEmpty())
                <div class="mb-cm-body">
                    <p class="mb-cm-note">No changes recorded yet. The first read is the starting point; later reads are compared with it.</p>
                </div>
            @else
                <div class="mb-table-wrap">
                    <table class="mb-table">
                        <thead>
                            <tr><th>Noticed</th><th>Object</th><th>Change</th><th>Before → after</th></tr>
                        </thead>
                        <tbody>
                            @foreach ($drifts as $drift)
                                <tr wire:key="drift-{{ $drift->id }}">
                                    <td class="text-nowrap" title="{{ $drift->detected_at->toDayDateTimeString() }}">{{ $drift->detected_at->diffForHumans() }}</td>
                                    <td>
                                        <div class="mb-cm-object">{{ $drift->entity?->name ?: '(no name)' }}</div>
                                        <div class="mb-cell-meta">{{ ManagerFormat::type($drift->entity?->entity_type) }} · <span class="mb-cm-mono">{{ $drift->entity?->external_id }}</span></div>
                                    </td>
                                    <td>
                                        @switch($drift->kind)
                                            @case(CampaignPlatformDrift::Added) <span class="mb-cm-flag is-mine"><i class="bi bi-plus-circle"></i> Appeared</span> @break
                                            @case(CampaignPlatformDrift::Removed) <span class="mb-cm-flag is-gone"><i class="bi bi-dash-circle"></i> No longer returned</span> @break
                                            @case(CampaignPlatformDrift::Restored) <span class="mb-cm-flag is-mine"><i class="bi bi-arrow-counterclockwise"></i> Returned again</span> @break
                                            @default <strong>{{ ManagerFormat::field($drift->field) }}</strong>
                                        @endswitch
                                        @isset($ownDrifts[$drift->id])
                                            <span class="mb-cm-flag is-mine" title="The read-back of a change confirmed from this campaign manager"><i class="bi bi-check2-circle"></i> Edited here</span>
                                        @endisset
                                    </td>
                                    <td>
                                        @if ($drift->kind !== CampaignPlatformDrift::Changed)
                                            <span class="mb-cell-meta">—</span>
                                        @elseif (ManagerFormat::isLong($drift->before) || ManagerFormat::isLong($drift->after))
                                            <details>
                                                <summary class="mb-cell-meta">Show before and after</summary>
                                                <div class="mb-cell-meta mt-2">Before</div><pre>{{ ManagerFormat::value($drift->before) }}</pre>
                                                <div class="mb-cell-meta mt-2">After</div><pre>{{ ManagerFormat::value($drift->after) }}</pre>
                                            </details>
                                        @else
                                            @php $show = fn (mixed $value): string => $drift->entity && str_starts_with((string) $drift->field, 'settings.') ? ManagerFormat::setting(Str::after($drift->field, 'settings.'), $value, $drift->entity) : ManagerFormat::readable($value); @endphp
                                            <span class="mb-cm-before">{{ $show($drift->before) }}</span><i class="bi bi-arrow-right mb-cm-arrow"></i><span class="mb-cm-after">{{ $show($drift->after) }}</span>
                                        @endif
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            @endif
        </section>

        @if ($edits->isNotEmpty())
            <section class="mb-card">
                <div class="mb-perf-card-head">
                    <div class="mb-perf-card-title-wrap">
                        <div class="mb-perf-card-title-row">
                            <span class="mb-perf-card-icon mb-cm-perf-icon is-ok"><i class="bi bi-pencil-square"></i></span>
                            <h2 class="mb-perf-card-title">Changes made here</h2>
                        </div>
                    </div>
                </div>
                <div class="mb-table-wrap">
                    <table class="mb-table">
                        <thead><tr><th>When</th><th>Object</th><th>Change</th><th>Outcome</th><th>By</th></tr></thead>
                        <tbody>
                            @foreach ($edits as $edit)
                                <tr wire:key="edit-{{ $edit->id }}">
                                    <td class="text-nowrap" title="{{ $edit->created_at->toDayDateTimeString() }}">{{ $edit->created_at->diffForHumans() }}</td>
                                    <td>
                                        <div class="mb-cm-object">{{ $edit->entity?->name ?: '(no name)' }}</div>
                                        <div class="mb-cell-meta">{{ ManagerFormat::type($edit->entity_type) }} · <span class="mb-cm-mono">{{ $edit->external_id }}</span></div>
                                    </td>
                                    <td>
                                        @if ($edit->isStructural())
                                            <div><strong>{{ $edit->summary() }}</strong></div>
                                        @endif
                                        @foreach (EditCapabilities::ordered($edit->entity, (array) $edit->changes) as $field => $change)
                                            <div><strong>{{ ManagerFormat::field($field) }}:</strong> @if ($edit->entity && EditCapabilities::isMoney($field) && is_numeric($change['before']) && is_numeric($change['after'])){{ EditCapabilities::money((float) $change['before'], $cur = EditCapabilities::currency($edit->entity)) }} → {{ EditCapabilities::money((float) $change['after'], $cur) }} {{ $cur }}@elseif ($edit->entity){{ EditCapabilities::display($edit->entity, $field, $change['before']) }} → {{ EditCapabilities::display($edit->entity, $field, $change['after']) }}@else{{ ManagerFormat::value($change['before']) }} → {{ ManagerFormat::value($change['after']) }}@endif</div>
                                        @endforeach
                                    </td>
                                    <td>
                                        @php
                                            $outcome = match ($edit->state) {
                                                CampaignEntityEdit::Applied => ['completed', 'Applied and confirmed'],
                                                CampaignEntityEdit::Proposed => ['queued', 'Waiting for confirmation'],
                                                CampaignEntityEdit::Unconfirmed => ['generating', 'Sent, not confirmed'],
                                                CampaignEntityEdit::Stale => ['queued', 'Not sent: changed on platform'],
                                                default => ['failed', 'Not applied'],
                                            };
                                        @endphp
                                        <span class="mb-status is-static is-{{ $outcome[0] }}" @if ($edit->error) title="{{ $edit->error }}" @endif><span class="mb-dot"></span>{{ $outcome[1] }}</span>
                                    </td>
                                    <td>{{ $edit->user?->name }}</td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </section>
        @endif

        <details class="mb-card mb-cm-collapse">
            <summary class="mb-perf-card-head">
                <div class="mb-perf-card-title-wrap">
                    <div class="mb-perf-card-title-row">
                        <span class="mb-perf-card-icon mb-cm-perf-icon is-muted"><i class="bi bi-clock-history"></i></span>
                        <h2 class="mb-perf-card-title">Recent reads <span class="mb-perf-title-sub">{{ $runs->count() }}</span></h2>
                    </div>
                </div>
                <i class="bi bi-chevron-down mb-card-chevron"></i>
            </summary>
            <div class="mb-table-wrap">
                <table class="mb-table">
                    <thead><tr><th>Started</th><th>Trigger</th><th>Result</th><th>Objects</th><th>Changes</th><th>Detail</th></tr></thead>
                    <tbody>
                        @forelse ($runs as $run)
                            <tr wire:key="run-{{ $run->id }}">
                                <td class="text-nowrap" title="{{ $run->started_at->toDayDateTimeString() }}">{{ $run->started_at->diffForHumans() }}</td>
                                <td>{{ ucfirst($run->trigger) }}</td>
                                <td>
                                    @php $runClass = match ($run->status) { 'succeeded' => 'completed', 'failed' => 'failed', 'running', 'partial' => 'generating', default => 'queued' }; @endphp
                                    <span class="mb-status is-static is-{{ $runClass }}"><span class="mb-dot"></span>{{ ucfirst($run->status) }}</span>
                                </td>
                                <td>{{ $run->succeeded() ? $run->entity_count : '—' }}</td>
                                <td>{{ $run->succeeded() ? $run->drift_count : '—' }}</td>
                                <td class="mb-cell-meta">{{ $run->error ?? collect($run->gaps)->implode(' ') }}</td>
                            </tr>
                        @empty
                            <tr><td colspan="6" class="mb-cell-meta">No reads yet.</td></tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </details>
    </div>
</div>
