@php
    $record = $getRecord();
    $activities = \App\Models\ActivityLog::where('loggable_type', get_class($record))
        ->where('loggable_id', $record->id)
        ->with('user')
        ->orderBy('created_at', 'desc')
        ->get();

    $getIconConfig = function ($action, $properties) {
        if ($action === 'created') {
            return [
                'icon'  => 'heroicon-o-plus-circle',
                'bg'    => '#f0fdf4',
                'color' => '#16a34a',
                'ring'  => '#bbf7d0',
            ];
        }
        if ($action === 'deleted') {
            return [
                'icon'  => 'heroicon-o-trash',
                'bg'    => '#fff1f2',
                'color' => '#e11d48',
                'ring'  => '#fecdd3',
            ];
        }

        $attributes = $properties['attributes'] ?? [];

        if (isset($attributes['status'])) {
            return match ($attributes['status']) {
                'pending'    => ['icon' => 'heroicon-o-clock',           'bg' => '#eff6ff', 'color' => '#1d4ed8', 'ring' => '#bfdbfe'],
                'processing' => ['icon' => 'heroicon-o-arrow-path',      'bg' => '#fffbeb', 'color' => '#b45309', 'ring' => '#fde68a'],
                'shipped'    => ['icon' => 'heroicon-o-truck',           'bg' => '#f0f9ff', 'color' => '#0369a1', 'ring' => '#bae6fd'],
                'delivered'  => ['icon' => 'heroicon-o-check-circle',    'bg' => '#f0fdf4', 'color' => '#16a34a', 'ring' => '#bbf7d0'],
                'cancelled'  => ['icon' => 'heroicon-o-x-circle',        'bg' => '#fff1f2', 'color' => '#e11d48', 'ring' => '#fecdd3'],
                default      => ['icon' => 'heroicon-o-pencil-square',   'bg' => '#fafafa', 'color' => '#64748b', 'ring' => '#e2e8f0'],
            };
        }

        if (isset($attributes['payment_status'])) {
            return match ($attributes['payment_status']) {
                'paid'     => ['icon' => 'heroicon-o-banknotes',          'bg' => '#f0fdf4', 'color' => '#16a34a', 'ring' => '#bbf7d0'],
                'failed'   => ['icon' => 'heroicon-o-exclamation-triangle','bg' => '#fff1f2', 'color' => '#e11d48', 'ring' => '#fecdd3'],
                'refunded' => ['icon' => 'heroicon-o-arrow-uturn-left',   'bg' => '#eff6ff', 'color' => '#1d4ed8', 'ring' => '#bfdbfe'],
                default    => ['icon' => 'heroicon-o-credit-card',        'bg' => '#fffbeb', 'color' => '#b45309', 'ring' => '#fde68a'],
            };
        }

        return ['icon' => 'heroicon-o-pencil-square', 'bg' => '#fafafa', 'color' => '#64748b', 'ring' => '#e2e8f0'];
    };

    $getStatusBadge = function ($value, $type = 'status') {
        if ($type === 'status') {
            [$bg, $color, $border, $label] = match (strtolower($value ?? '')) {
                'pending'    => ['#eff6ff', '#1d4ed8', '#bfdbfe', 'Pending'],
                'processing' => ['#fffbeb', '#b45309', '#fde68a', 'Processing'],
                'shipped'    => ['#f0f9ff', '#0369a1', '#bae6fd', 'Shipped'],
                'delivered'  => ['#f0fdf4', '#15803d', '#bbf7d0', 'Delivered'],
                'cancelled'  => ['#fff1f2', '#be123c', '#fecdd3', 'Cancelled'],
                default      => ['#f8fafc', '#475569', '#e2e8f0', ucfirst($value ?? '—')],
            };
        } else {
            [$bg, $color, $border, $label] = match (strtolower($value ?? '')) {
                'paid'     => ['#f0fdf4', '#15803d', '#bbf7d0', 'Paid'],
                'pending'  => ['#eff6ff', '#1d4ed8', '#bfdbfe', 'Pending'],
                'failed'   => ['#fff1f2', '#be123c', '#fecdd3', 'Failed'],
                'refunded' => ['#f0f9ff', '#0369a1', '#bae6fd', 'Refunded'],
                default    => ['#f8fafc', '#475569', '#e2e8f0', ucfirst($value ?? '—')],
            };
        }
        return "<span style=\"display:inline-flex;align-items:center;padding:1px 8px;border-radius:9999px;font-size:11px;font-weight:600;background:{$bg};color:{$color};border:1px solid {$border};white-space:nowrap;\">{$label}</span>";
    };
@endphp


<div style="padding: 4px 12px 4px 0; max-height: 550px; overflow-y: auto; overflow-x: hidden;">
    @forelse ($activities as $index => $activity)
        @php
            $properties  = $activity->properties ?? [];
            $iconConfig  = $getIconConfig($activity->action, $properties);
            $isLast      = $loop->last;
            $attrs       = $properties['attributes'] ?? [];
            $old         = $properties['old'] ?? [];

            // Build clean description
            $desc = $activity->description ?? '';
            if ($activity->action === 'updated' && str_contains($desc, 'updated:')) {
                $desc = trim(explode('updated:', $desc)[0]) . ' updated';
            }

            // Build diff items
            $diffs = [];
            if ($activity->action === 'updated' && !empty($attrs)) {
                foreach ($attrs as $field => $newVal) {
                    $oldVal = $old[$field] ?? null;
                    if ($oldVal === $newVal || $field === 'updated_at') continue;
                    $diffs[] = ['field' => $field, 'old' => $oldVal, 'new' => $newVal];
                }
            }
        @endphp

        <div style="display:flex;gap:12px;{{ !$isLast ? 'margin-bottom:0;' : '' }}">

            {{-- Left: icon + connector --}}
            <div style="display:flex;flex-direction:column;align-items:center;flex-shrink:0;">
                <div style="
                    width:32px;height:32px;border-radius:50%;
                    background:{{ $iconConfig['bg'] }};
                    border:2px solid {{ $iconConfig['ring'] }};
                    display:flex;align-items:center;justify-content:center;
                    flex-shrink:0;z-index:1;
                ">
                    <x-filament::icon
                        icon="{{ $iconConfig['icon'] }}"
                        style="width:15px;height:15px;color:{{ $iconConfig['color'] }};"
                    />
                </div>
                @if (!$isLast)
                    <div style="width:2px;flex:1;background:#e2e8f0;margin:3px 0;min-height:20px;"></div>
                @endif
            </div>

            {{-- Right: content --}}
            <div style="flex:1;padding-bottom:{{ $isLast ? '4px' : '16px' }}; min-width: 0;">

                {{-- Header row --}}
                <div style="display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:4px;flex-wrap:wrap;">
                    <div style="display:flex;align-items:center;gap:6px;">
                        <span style="font-size:12px;font-weight:600;color:#1e293b;">
                            {{ $activity->user?->name ?? 'System' }}
                        </span>
                        @if ($activity->action === 'created')
                            <span style="display:inline-flex;align-items:center;padding:1px 7px;border-radius:9999px;font-size:10px;font-weight:600;background:#f0fdf4;color:#15803d;border:1px solid #bbf7d0;">Created</span>
                        @elseif ($activity->action === 'updated')
                            <span style="display:inline-flex;align-items:center;padding:1px 7px;border-radius:9999px;font-size:10px;font-weight:600;background:#fffbeb;color:#b45309;border:1px solid #fde68a;">Updated</span>
                        @elseif ($activity->action === 'deleted')
                            <span style="display:inline-flex;align-items:center;padding:1px 7px;border-radius:9999px;font-size:10px;font-weight:600;background:#fff1f2;color:#be123c;border:1px solid #fecdd3;">Deleted</span>
                        @endif
                    </div>
                    <span
                        title="{{ $activity->created_at->format('M j, Y H:i:s') }}"
                        style="font-size:11px;color:#94a3b8;white-space:nowrap;flex-shrink:0;"
                    >
                        {{ $activity->created_at->diffForHumans() }}
                    </span>
                </div>

                {{-- Description --}}
                <p style="font-size:12px;color:#475569;margin:0 0 6px 0;line-height:1.4;">
                    {{ $desc }}
                </p>

                {{-- Diff pills --}}
                @if (!empty($diffs))
                    @php
                        // Separate status/payment_status from other fields
                        $statusDiffs  = array_filter($diffs, fn($d) => in_array($d['field'], ['status', 'payment_status']));
                        $otherDiffs   = array_filter($diffs, fn($d) => !in_array($d['field'], ['status', 'payment_status']));

                        $fmt = function ($v) {
                            if (is_null($v))  return '—';
                            if (is_bool($v))  return $v ? 'true' : 'false';
                            $s = (string) $v;
                            if (str_starts_with($s, '<p>') && str_ends_with($s, '</p>')) {
                                $s = substr($s, 3, -4);
                            }
                            return trim($s);
                        };
                    @endphp

                    <div style="display:flex;flex-direction:column;gap:5px;">

                        {{-- Status + Payment Status: stacked block layout --}}
                        @if (!empty($statusDiffs))
                            <div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
                                @foreach ($statusDiffs as $diff)
                                    @php
                                        $isPayment = ($diff['field'] === 'payment_status');
                                        $type = $isPayment ? 'payment' : 'status';
                                    @endphp
                                    <div style="display:flex;flex-direction:column;gap:3px;align-items:flex-start;">
                                        <span style="font-size:9px;font-weight:600;color:#94a3b8;text-transform:uppercase;letter-spacing:.04em;">
                                            {{ $isPayment ? 'Payment Status' : 'Order Status' }}
                                        </span>
                                        <div style="display:inline-flex;align-items:center;gap:5px;white-space:nowrap;">
                                            {!! $getStatusBadge($fmt($diff['old']), $type) !!}
                                            <span style="color:#cbd5e1;font-size:11px;">→</span>
                                            {!! $getStatusBadge($fmt($diff['new']), $type) !!}
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        @endif

                        {{-- Other field changes --}}
                        @foreach ($otherDiffs as $diff)
                            <div style="display:flex;flex-direction:column;gap:3px;align-items:flex-start;">
                                <span style="font-size:9px;font-weight:600;color:#94a3b8;text-transform:uppercase;letter-spacing:.04em;">
                                    {{ str_replace('_', ' ', $diff['field']) }}
                                </span>
                                <div style="display:inline-flex;align-items:center;gap:5px;flex-wrap:wrap;">
                                    <span style="font-size:11px;font-family:monospace;color:#ef4444;text-decoration:line-through;background:#fff1f2;padding:0 5px;border-radius:4px;word-break:break-all;">{{ $fmt($diff['old']) }}</span>
                                    <span style="color:#cbd5e1;font-size:11px;">→</span>
                                    <span style="font-size:11px;font-family:monospace;color:#16a34a;font-weight:600;background:#f0fdf4;padding:0 5px;border-radius:4px;word-break:break-all;">{{ $fmt($diff['new']) }}</span>
                                </div>
                            </div>
                        @endforeach

                    </div>
                @endif

            </div>
        </div>
    @empty
        <div style="text-align:center;padding:24px 0;">
            <div style="width:40px;height:40px;background:#f1f5f9;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 10px;">
                <x-filament::icon icon="heroicon-o-clock" style="width:20px;height:20px;color:#94a3b8;" />
            </div>
            <p style="font-size:13px;color:#94a3b8;margin:0;">No activity recorded yet.</p>
        </div>
    @endforelse
</div>
