@php
    use App\Enums\OrderStatus;
    use App\Models\Setting;

    $timelineDefs = [
        ['status' => OrderStatus::Pending, 'label' => 'Order Placed', 'icon' => 'shopping-bag'],
        ['status' => OrderStatus::Confirmed, 'label' => 'Confirmed', 'icon' => 'clipboard-check'],
        ['status' => OrderStatus::Packing, 'label' => 'Packing', 'icon' => 'package'],
        ['status' => OrderStatus::Shipped, 'label' => 'Shipped', 'icon' => 'truck'],
        ['status' => OrderStatus::Delivered, 'label' => 'Delivered', 'icon' => 'package-check'],
    ];

    $isCancelled = $order->order_status === OrderStatus::Cancelled;
    $currentIndex = collect($timelineDefs)->search(fn ($s) => $s['status'] === $order->order_status);
    // Oldest-first so a status reached more than once keys on its first
    // occurrence — the timeline shows when a step was *first* reached.
    $historyByStatus = $order->statusHistories->sortBy('created_at')->keyBy('status');

    $timelineSteps = collect($timelineDefs)->map(fn ($step, $i) => [
        'label' => $step['label'],
        'icon' => $step['icon'],
        'completed' => ! $isCancelled && $currentIndex !== false && $i <= $currentIndex,
        'current' => ! $isCancelled && $i === $currentIndex,
        'timestamp' => $historyByStatus->get($step['status']->value)?->created_at,
    ])->all();
    foreach ($timelineSteps as $i => &$step) {
        $step['lineAfterCompleted'] = $timelineSteps[$i + 1]['completed'] ?? false;
    }
    unset($step);

    // The order can go through several payments (a rejected EasyPaisa
    // attempt followed by a fresh one) — the latest verification date is
    // the one worth showing on a receipt.
    $paymentDate = $order->payments->pluck('verified_at')->filter()->max();
@endphp
<x-layouts.frontend title="Order {{ $order->order_number }}">
    <section class="receipt-page mx-auto max-w-4xl px-6 py-14">
        <div class="no-print mb-8 text-center" data-reveal-self>
            <span class="inline-flex h-16 w-16 items-center justify-center rounded-full bg-gradient-to-br from-success/20 to-success/5 text-success shadow-[var(--shadow-soft)]">
                <x-icon name="check" class="h-7 w-7" :stroke-width="2.5" />
            </span>
            <p class="mt-4 text-xs font-semibold uppercase tracking-[0.15em] text-champagne-light">Thank You</p>
            <h1 class="mt-1 font-display text-3xl text-ink">Order Confirmed</h1>

            <div class="mt-6 flex flex-wrap items-center justify-center gap-2">
                <x-frontend.button type="button" variant="outline" size="sm" onclick="window.print()">
                    <x-icon name="printer" class="h-3.5 w-3.5" /> Print Receipt
                </x-frontend.button>
                <x-frontend.button href="{{ route('shop.index') }}" size="sm">
                    Continue Shopping
                </x-frontend.button>
            </div>
        </div>

        <div class="receipt-card relative overflow-hidden rounded-2xl border border-black/5 bg-white shadow-[var(--shadow-card)]" data-reveal-self>
            {{-- Faint brand watermark — the kind of subtle security-paper
                 touch a premium invoice carries, invisible until you look. --}}
            <img
                src="{{ asset('images/logo.png') }}" alt="" aria-hidden="true"
                class="receipt-watermark pointer-events-none absolute left-1/2 top-1/2 w-[150%] max-w-none -translate-x-1/2 -translate-y-1/2 select-none opacity-[0.035]"
            >

            <div class="receipt-card-body relative p-8 sm:p-10">
                {{-- Header --}}
                <div class="receipt-section avoid-break flex flex-col gap-6 border-b border-black/5 pb-8 sm:flex-row sm:items-start sm:justify-between">
                    <div>
                        <img src="{{ asset('images/logo.png') }}" alt="{{ config('niyarasa.brand_name') }}" class="h-11 w-auto">
                        <p class="mt-2 text-xs text-ink/40">{{ config('niyarasa.brand_tagline') }}</p>
                    </div>
                    <div class="sm:text-right">
                        <p class="text-xs font-semibold uppercase tracking-[0.2em] text-champagne-light">Order Receipt</p>
                        <p class="mt-1 text-xs uppercase tracking-wide text-ink/40">Order / Invoice No.</p>
                        <p class="font-mono text-lg font-semibold text-ink">{{ $order->order_number }}</p>
                        <p class="mt-1 text-xs text-ink/40">Placed {{ $order->created_at->format('d M Y, h:i A') }}</p>
                        @if ($paymentDate)
                            <p class="text-xs text-ink/40">Paid {{ $paymentDate->format('d M Y, h:i A') }}</p>
                        @endif
                    </div>
                </div>

                {{-- Customer + Shipping + Payment --}}
                <div class="receipt-section avoid-break grid grid-cols-1 gap-4 border-b border-black/5 py-8 sm:grid-cols-3">
                    <div class="receipt-card-inner rounded-xl border border-black/5 bg-cream/25 p-5">
                        <p class="mb-3 flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-ink/40">
                            <x-icon name="circle-user" class="h-3.5 w-3.5 text-champagne-light" /> Billed To
                        </p>
                        <p class="text-sm font-medium text-ink">{{ $order->customer_name }}</p>
                        <p class="mt-1.5 flex items-center gap-2 text-sm text-ink/60">
                            <x-icon name="phone" class="h-3.5 w-3.5 shrink-0 text-ink/30" /> {{ $order->customer_phone }}
                        </p>
                        @if ($order->customer_email)
                            <p class="mt-1 flex items-center gap-2 text-sm text-ink/60">
                                <x-icon name="mail" class="h-3.5 w-3.5 shrink-0 text-ink/30" /> {{ $order->customer_email }}
                            </p>
                        @endif
                    </div>

                    <div class="receipt-card-inner rounded-xl border border-black/5 bg-cream/25 p-5">
                        <p class="mb-3 flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-ink/40">
                            <x-icon name="map-pin" class="h-3.5 w-3.5 text-champagne-light" /> Ship To
                        </p>
                        <p class="text-sm text-ink/70">{{ $order->shipping_address }}</p>
                        <p class="mt-1 text-sm text-ink/70">{{ $order->shipping_area }}, {{ $order->shipping_city }}</p>
                    </div>

                    <div class="receipt-card-inner rounded-xl border border-black/5 bg-cream/25 p-5">
                        <p class="mb-3 flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-ink/40">
                            <x-icon name="credit-card" class="h-3.5 w-3.5 text-champagne-light" /> Payment
                        </p>
                        <p class="text-sm font-medium text-ink">{{ $order->payment_method->label() }}</p>
                        <div class="mt-2.5 flex flex-wrap items-center gap-1.5">
                            <x-admin.badge :color="$order->payment_status->color()">{{ $order->payment_status->label() }}</x-admin.badge>
                            <x-admin.badge :color="$order->order_status->color()">{{ $order->order_status->label() }}</x-admin.badge>
                        </div>
                    </div>
                </div>

                {{-- Order Status Timeline --}}
                <div class="receipt-section avoid-break border-b border-black/5 py-8">
                    <p class="mb-6 text-xs font-semibold uppercase tracking-wide text-ink/40">Order Progress</p>

                    @if ($isCancelled)
                        <div class="flex items-center gap-3 rounded-xl border border-danger/20 bg-danger/5 p-4">
                            <span class="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-danger/10 text-danger">
                                <x-icon name="x" class="h-4 w-4" />
                            </span>
                            <div>
                                <p class="text-sm font-semibold text-danger">Order Cancelled</p>
                                @if ($order->cancelled_reason)
                                    <p class="text-xs text-ink/50">{{ $order->cancelled_reason }}</p>
                                @endif
                            </div>
                        </div>
                    @else
                        <div class="overflow-x-auto">
                            <div class="flex min-w-[560px] items-start sm:min-w-0">
                                @foreach ($timelineSteps as $i => $step)
                                    <div class="flex flex-1 flex-col items-center text-center">
                                        <div class="flex w-full items-center">
                                            <div class="h-px flex-1 {{ $i === 0 ? 'bg-transparent' : ($step['completed'] ? 'bg-champagne' : 'bg-black/10') }}"></div>
                                            <span
                                                class="flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-xs transition-colors duration-300 {{ $step['completed'] ? 'bg-champagne text-ink' : 'border-2 border-black/10 bg-white text-ink/30' }} {{ $step['current'] ? 'ring-4 ring-champagne/20' : '' }}"
                                            >
                                                {{-- The current/completed step's circle is already the gold
                                                     `bg-champagne` fill with a glow ring — that *is* the "highlighted
                                                     in gold" treatment; a gold-gradient stroke on top of a gold
                                                     background would just lose contrast against itself. --}}
                                                <x-icon :name="$step['completed'] ? 'check' : $step['icon']" class="h-4 w-4" />
                                            </span>
                                            <div class="h-px flex-1 {{ $loop->last ? 'bg-transparent' : ($step['lineAfterCompleted'] ? 'bg-champagne' : 'bg-black/10') }}"></div>
                                        </div>
                                        <p class="mt-2 text-[0.7rem] font-medium {{ $step['completed'] ? 'text-ink' : 'text-ink/40' }}">{{ $step['label'] }}</p>
                                        @if ($step['timestamp'])
                                            <p class="text-[0.6rem] text-ink/35">{{ $step['timestamp']->format('d M, h:i A') }}</p>
                                        @endif
                                    </div>
                                @endforeach
                            </div>
                        </div>
                    @endif
                </div>

                {{-- Items --}}
                <div class="receipt-section py-8">
                    <p class="mb-4 text-xs font-semibold uppercase tracking-wide text-ink/40">Order Items</p>
                    <div class="overflow-x-auto rounded-xl border border-black/5">
                        <table class="w-full text-left text-sm">
                            <thead>
                                <tr class="bg-cream/50 text-xs uppercase tracking-wide text-ink/40">
                                    <th class="py-3 pl-4 font-semibold">Product</th>
                                    <th class="py-3 font-semibold">Variant</th>
                                    <th class="py-3 text-center font-semibold">Qty</th>
                                    <th class="py-3 text-right font-semibold">Unit Price</th>
                                    <th class="py-3 pr-4 text-right font-semibold">Total</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-black/5">
                                @foreach ($order->items as $item)
                                    @php $itemImage = $item->product?->primaryImage?->image_path; @endphp
                                    <tr class="{{ $loop->even ? 'bg-cream/20' : '' }}">
                                        <td class="py-3 pl-4">
                                            <div class="flex items-center gap-3">
                                                <div class="receipt-item-thumb h-12 w-10 shrink-0 overflow-hidden rounded-lg bg-cream">
                                                    @if ($itemImage)
                                                        <img src="{{ Storage::url($itemImage) }}" alt="" class="h-full w-full object-cover" loading="lazy" decoding="async">
                                                    @else
                                                        <div class="flex h-full w-full items-center justify-center text-ink/15"><x-icon name="shirt" class="h-5 w-5" :stroke-width="1.5" /></div>
                                                    @endif
                                                </div>
                                                <div class="min-w-0">
                                                    <p class="truncate font-medium text-ink">{{ $item->product_name }}</p>
                                                    @if ($item->sku)
                                                        <p class="text-xs text-ink/35">SKU: {{ $item->sku }}</p>
                                                    @endif
                                                </div>
                                            </div>
                                        </td>
                                        <td class="py-3 text-ink/60">{{ $item->variant_label ?? '—' }}</td>
                                        <td class="py-3 text-center tabular-nums text-ink/60">{{ $item->quantity }}</td>
                                        <td class="py-3 text-right tabular-nums text-ink/60">{{ config('niyarasa.currency.symbol') }} {{ number_format((float) $item->price) }}</td>
                                        <td class="py-3 pr-4 text-right tabular-nums font-semibold text-ink">{{ config('niyarasa.currency.symbol') }} {{ number_format((float) $item->subtotal) }}</td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>

                {{-- Totals --}}
                <div class="receipt-section avoid-break flex justify-end pb-2">
                    <dl class="w-full max-w-sm space-y-2.5 text-sm">
                        <div class="flex justify-between">
                            <dt class="text-ink/50">Subtotal</dt>
                            <dd class="tabular-nums text-ink">{{ config('niyarasa.currency.symbol') }} {{ number_format((float) $order->subtotal) }}</dd>
                        </div>
                        @if ((float) $order->discount_amount > 0)
                            <div class="flex justify-between">
                                <dt class="text-ink/50">Discount {{ $order->coupon_code ? "({$order->coupon_code})" : '' }}</dt>
                                <dd class="tabular-nums text-success">− {{ config('niyarasa.currency.symbol') }} {{ number_format((float) $order->discount_amount) }}</dd>
                            </div>
                        @endif
                        <div class="flex justify-between">
                            <dt class="text-ink/50">Shipping</dt>
                            <dd class="tabular-nums text-ink">
                                @if ((float) $order->shipping_charge > 0)
                                    {{ config('niyarasa.currency.symbol') }} {{ number_format((float) $order->shipping_charge) }}
                                @else
                                    <span class="text-success">Free</span>
                                @endif
                            </dd>
                        </div>

                        <div class="receipt-total-highlight mt-3 flex items-center justify-between rounded-xl bg-gradient-to-r from-ink via-charcoal to-ink px-5 py-4 text-ivory">
                            <span class="text-xs font-semibold uppercase tracking-[0.15em] text-champagne-light">Grand Total</span>
                            <span class="font-display text-2xl">{{ config('niyarasa.currency.symbol') }} {{ number_format((float) $order->grand_total) }}</span>
                        </div>
                    </dl>
                </div>

                @if ($order->order_notes)
                    <div class="mt-6 rounded-lg bg-black/5 px-4 py-3 text-sm text-ink/60">
                        <span class="font-medium text-ink/70">Order Notes:</span> {{ $order->order_notes }}
                    </div>
                @endif

                @if ($order->payment_method->value === 'easypaisa' && $order->payment_status->value === 'pending')
                    <div class="flex items-center rounded-lg border border-champagne/30 bg-champagne/10 px-4 py-3 text-sm text-champagne-light">
                        <x-icon name="info" class="mr-1.5 h-4 w-4 shrink-0" />
                        Your payment is pending verification. We'll confirm it shortly.
                    </div>
                @endif

                {{-- Footer --}}
                <div class="receipt-section mt-10 border-t border-black/5 pt-8 text-center">
                    <p class="font-display text-lg text-ink">Thank You for Shopping with {{ config('niyarasa.brand_name') }}</p>
                    <p class="mt-1 text-xs text-ink/40">Questions about your order? We're happy to help.</p>

                    <div class="mt-4 flex flex-wrap items-center justify-center gap-x-6 gap-y-2 text-xs text-ink/50">
                        @if (Setting::config('contact.email'))
                            <span class="inline-flex items-center"><x-icon name="mail" class="mr-1.5 h-3.5 w-3.5 text-champagne-light" />{{ Setting::config('contact.email') }}</span>
                        @endif
                        @if (Setting::config('contact.phone'))
                            <span class="inline-flex items-center"><x-icon name="phone" class="mr-1.5 h-3.5 w-3.5 text-champagne-light" />{{ Setting::config('contact.phone') }}</span>
                        @endif
                        <span class="inline-flex items-center"><x-icon name="globe" class="mr-1.5 h-3.5 w-3.5 text-champagne-light" />{{ config('app.url') }}</span>
                    </div>

                    @if (Setting::config('social.facebook') || Setting::config('social.whatsapp_number'))
                        <div class="no-print mt-4 flex items-center justify-center gap-3 text-ink/40">
                            @if (Setting::config('social.facebook'))
                                <x-icon-button
                                    :href="Setting::config('social.facebook')" target="_blank" rel="noopener noreferrer" label="Facebook"
                                    name="brand-facebook" variant="chip-light" icon-class="h-3.5 w-3.5"
                                    class="icon-chip--facebook min-h-9! min-w-9!"
                                />
                            @endif
                            @if (Setting::config('social.whatsapp_number'))
                                <x-icon-button
                                    href="https://wa.me/{{ preg_replace('/[^0-9]/', '', Setting::config('social.whatsapp_number')) }}" target="_blank" rel="noopener noreferrer" label="Chat on WhatsApp"
                                    name="brand-whatsapp" variant="chip-light" icon-class="h-3.5 w-3.5"
                                    class="icon-chip--whatsapp min-h-9! min-w-9!"
                                />
                            @endif
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </section>
</x-layouts.frontend>
