<div x-data="{ showStatusModal: @entangle('showStatusModal'), showCancelModal: @entangle('showCancelModal') }">

    {{-- Header --}}
    <div class="flex items-center gap-3 mb-6">
        <a href="{{ route('admin.pesanan') }}" wire:navigate
            class="p-1.5 rounded-lg text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition-colors">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"/>
            </svg>
        </a>
        <div class="flex-1">
            <h1 class="text-2xl font-bold text-slate-800 font-mono">{{ $order->order_number }}</h1>
            <p class="text-sm text-slate-500 mt-0.5">
                Dipesan {{ $order->created_at->translatedFormat('d F Y, H:i') }} WIB
            </p>
        </div>

        @php
            $statusColor = match($order->status->value) {
                'pending'    => 'bg-slate-100 text-slate-600',
                'paid'       => 'bg-blue-100 text-blue-700',
                'processing' => 'bg-blue-100 text-blue-700',
                'delivering' => 'bg-orange-100 text-orange-700',
                'completed'  => 'bg-green-100 text-green-700',
                'cancelled'  => 'bg-red-100 text-red-700',
                default      => 'bg-slate-100 text-slate-600',
            };
        @endphp
        <span class="inline-flex px-3 py-1.5 rounded-full text-sm font-semibold {{ $statusColor }}">
            {{ $order->status->label() }}
        </span>
    </div>

    {{-- Aksi --}}
    <div class="flex flex-wrap gap-2 mb-6">
        <a href="{{ route('admin.pesanan.invoice', $order->id) }}" target="_blank"
            class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-slate-700 bg-white border border-slate-300 rounded-lg hover:bg-slate-50 transition-colors">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6.72 13.829c-.24.03-.48.062-.72.096m.72-.096a42.415 42.415 0 0110.56 0m-10.56 0L6.34 18m10.94-4.171c.24.03.48.062.72.096m-.72-.096L17.66 18m0 0l.229 2.523a1.125 1.125 0 01-1.12 1.227H7.231c-.662 0-1.18-.568-1.12-1.227L6.34 18m11.32 0H6.34m-1.93-3.171a48.355 48.355 0 00-1.232.063m1.232-.063L6.34 18m11.32 0l.232-2.481a48.355 48.355 0 00-1.232-.063m-9.044 0a48.474 48.474 0 011.232-.063m6.58 0c.41.024.82.05 1.23.077m0 0L18.16 18M5.65 14.829c-.41.024-.82.05-1.23.077M2.25 6.75h19.5M4.5 6.75v-1.5a2.25 2.25 0 012.25-2.25h10.5a2.25 2.25 0 012.25 2.25v1.5"/>
            </svg>
            Print Invoice
        </a>

        @can('order.update-status')
            @if (!$order->isFinal())
                <button type="button" wire:click="openStatusModal"
                    class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-orange-500 rounded-lg hover:bg-orange-600 transition-colors">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
                    </svg>
                    Ubah Status
                </button>
            @endif
        @endcan

        @can('order.cancel')
            @if ($order->isCancellable())
                <button type="button" wire:click="openCancelModal"
                    class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-red-600 bg-white border border-red-200 rounded-lg hover:bg-red-50 transition-colors">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18 6L6 18M6 6l12 12"/>
                    </svg>
                    Batalkan Pesanan
                </button>
            @endif
        @endcan
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-4 lg:gap-6">

        {{-- Kolom kiri (2/3) --}}
        <div class="lg:col-span-2 space-y-5">

            {{-- Customer --}}
            <div class="bg-white rounded-xl border border-slate-200 p-5">
                <h2 class="font-semibold text-slate-800 mb-4">Informasi Customer</h2>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
                    <div>
                        <p class="text-xs text-slate-400 mb-0.5">Nama</p>
                        <p class="font-medium text-slate-800">{{ $order->customer_name }}</p>
                    </div>
                    <div>
                        <p class="text-xs text-slate-400 mb-0.5">Nomor HP</p>
                        <a href="https://wa.me/{{ preg_replace('/^0/', '62', $order->customer_phone) }}" target="_blank"
                            class="font-medium text-green-600 hover:text-green-700">
                            {{ $order->customer_phone }}
                        </a>
                    </div>
                    <div class="sm:col-span-2">
                        <p class="text-xs text-slate-400 mb-0.5">Alamat Pengiriman</p>
                        <p class="text-slate-700">{{ $order->delivery_address_snapshot }}</p>
                        <a href="https://www.google.com/maps/search/?api=1&query={{ urlencode($order->delivery_address_snapshot) }}"
                            target="_blank"
                            class="inline-flex items-center gap-1 mt-1 text-xs text-blue-600 hover:text-blue-700">
                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10.5a3 3 0 11-6 0 3 3 0 016 0z"/>
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19.5 10.5c0 7.142-7.5 11.25-7.5 11.25S4.5 17.642 4.5 10.5a7.5 7.5 0 1115 0z"/>
                            </svg>
                            Lihat di Google Maps
                        </a>
                    </div>
                    @if ($order->customer_notes)
                        <div class="sm:col-span-2">
                            <p class="text-xs text-slate-400 mb-0.5">Catatan Customer</p>
                            <p class="text-slate-700 bg-slate-50 rounded-lg px-3 py-2">{{ $order->customer_notes }}</p>
                        </div>
                    @endif
                </div>
            </div>

            {{-- Produk --}}
            <div class="bg-white rounded-xl border border-slate-200 overflow-hidden">
                <div class="px-5 py-4 border-b border-slate-100">
                    <h2 class="font-semibold text-slate-800">Produk Dipesan</h2>
                </div>
                <div class="divide-y divide-slate-100">
                    @foreach ($order->items as $item)
                        <div class="flex items-center gap-3 px-5 py-3">
                            <div class="w-12 h-12 rounded-lg bg-slate-100 overflow-hidden shrink-0 flex items-center justify-center">
                                @if ($item->product_image)
                                    <img src="{{ Storage::url($item->product_image) }}" alt="{{ $item->product_name }}" class="w-full h-full object-cover" />
                                @else
                                    <svg class="w-5 h-5 text-slate-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 7.5l-9-5.25L3 7.5m18 0l-9 5.25m9-5.25v9l-9 5.25M3 7.5l9 5.25M3 7.5v9l9 5.25m0-9v9"/>
                                    </svg>
                                @endif
                            </div>
                            <div class="flex-1 min-w-0">
                                <p class="font-medium text-slate-800 truncate">{{ $item->product_name }}</p>
                                <p class="text-xs text-slate-400">
                                    Rp {{ number_format($item->sell_price, 0, ',', '.') }} × {{ $item->quantity }}
                                </p>
                                @if ($item->notes)
                                    <p class="text-xs text-orange-600 mt-0.5 italic">📝 {{ $item->notes }}</p>
                                @endif
                            </div>
                            <p class="font-semibold text-slate-800 whitespace-nowrap">
                                Rp {{ number_format($item->subtotal, 0, ',', '.') }}
                            </p>
                        </div>
                    @endforeach
                </div>

                {{-- Ringkasan --}}
                <div class="px-5 py-4 bg-slate-50 border-t border-slate-100 space-y-1.5 text-sm">
                    <div class="flex justify-between text-slate-600">
                        <span>Subtotal</span>
                        <span>Rp {{ number_format($order->subtotal, 0, ',', '.') }}</span>
                    </div>
                    @if ($order->voucher)
                        <div class="flex justify-between text-green-600">
                            <span>Voucher ({{ $order->voucher->code }})</span>
                            <span>− Rp {{ number_format($order->discount_amount, 0, ',', '.') }}</span>
                        </div>
                    @elseif ($order->discount_amount > 0)
                        <div class="flex justify-between text-green-600">
                            <span>Diskon</span>
                            <span>− Rp {{ number_format($order->discount_amount, 0, ',', '.') }}</span>
                        </div>
                    @endif
                    <div class="flex justify-between text-slate-600">
                        <span>Ongkos Kirim @if($order->deliveryArea) ({{ $order->deliveryArea->name }}) @endif</span>
                        <span>Rp {{ number_format($order->delivery_cost, 0, ',', '.') }}</span>
                    </div>
                    <div class="flex justify-between text-base font-bold text-slate-800 pt-1.5 border-t border-slate-200">
                        <span>Grand Total</span>
                        <span>Rp {{ number_format($order->grand_total, 0, ',', '.') }}</span>
                    </div>
                </div>
            </div>

            {{-- Timeline --}}
            <div class="bg-white rounded-xl border border-slate-200 p-5">
                <h2 class="font-semibold text-slate-800 mb-4">Riwayat Status</h2>

                <div class="space-y-0">
                    @foreach ($timeline as $i => $step)
                        <div class="flex gap-3 pb-4 relative" wire:key="step-{{ $i }}">
                            {{-- Garis vertikal penghubung antar step --}}
                            @if (! $loop->last)
                                <div class="absolute left-[7px] top-4 bottom-0 w-px
                                    {{ $step['done'] || $step['active'] ? 'bg-orange-200' : 'bg-slate-200' }}">
                                </div>
                            @endif

                            {{-- Dot status --}}
                            @if ($step['active'])
                                {{-- Step aktif: dot oranye besar --}}
                                <div class="w-4 h-4 rounded-full bg-orange-500 ring-4 ring-orange-100 shrink-0 mt-0.5 z-10"></div>
                            @elseif ($step['done'])
                                {{-- Step selesai: dot oranye solid --}}
                                <div class="w-4 h-4 rounded-full bg-orange-400 shrink-0 mt-0.5 z-10"></div>
                            @else
                                {{-- Step belum terjadi: dot abu-abu kosong --}}
                                <div class="w-4 h-4 rounded-full border-2 border-slate-300 bg-white shrink-0 mt-0.5 z-10"></div>
                            @endif

                            <div class="flex-1 -mt-0.5">
                                <p class="text-sm font-medium
                                    {{ $step['active'] ? 'text-orange-600' : ($step['done'] ? 'text-slate-700' : 'text-slate-400') }}">
                                    {{ $step['label'] }}
                                    @if ($step['active'])
                                        <span class="ml-1.5 inline-flex items-center px-1.5 py-0.5 rounded text-xs font-semibold bg-orange-100 text-orange-700">Saat ini</span>
                                    @endif
                                </p>
                                @if ($step['timestamp'])
                                    <p class="text-xs text-slate-400">
                                        {{ $step['timestamp']->translatedFormat('d F Y, H:i') }} WIB
                                        @if ($step['causer'])
                                            oleh {{ $step['causer']->name }}
                                        @endif
                                    </p>
                                @elseif (! $step['done'] && ! $step['active'])
                                    <p class="text-xs text-slate-300">Belum terjadi</p>
                                @endif
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>

        </div>

        {{-- Kolom kanan (1/3) --}}
        <div class="space-y-5">

            {{-- Pembayaran --}}
            <div class="bg-white rounded-xl border border-slate-200 p-5">
                <h2 class="font-semibold text-slate-800 mb-4">Pembayaran</h2>
                <div class="space-y-3 text-sm">
                    <div>
                        <p class="text-xs text-slate-400 mb-0.5">Metode</p>
                        <p class="font-medium text-slate-800">{{ $order->payment_method->label() }}</p>
                    </div>
                    <div>
                        <p class="text-xs text-slate-400 mb-0.5">Status Pembayaran</p>
                        @if ($order->payment)
                            @php
                                $payColor = match($order->payment->status->value) {
                                    'verified' => 'bg-green-100 text-green-700',
                                    'rejected' => 'bg-red-100 text-red-700',
                                    default    => 'bg-yellow-100 text-yellow-700',
                                };
                            @endphp
                            <span class="inline-flex px-2.5 py-1 rounded-full text-xs font-semibold {{ $payColor }}">
                                {{ $order->payment->status->label() }}
                            </span>
                            @if ($order->payment->verifiedBy)
                                <p class="text-xs text-slate-400 mt-1">
                                    Diverifikasi oleh {{ $order->payment->verifiedBy->name }}
                                    @if ($order->payment->verified_at)
                                        · {{ $order->payment->verified_at->translatedFormat('d M Y, H:i') }}
                                    @endif
                                </p>
                            @endif
                            @if ($order->payment->proof_image)
                                <a href="{{ Storage::url($order->payment->proof_image) }}" target="_blank" class="block mt-2">
                                    <img src="{{ Storage::url($order->payment->proof_image) }}"
                                        class="w-full rounded-lg border border-slate-200" />
                                </a>
                            @endif
                        @else
                            <span class="inline-flex px-2.5 py-1 rounded-full text-xs font-semibold bg-slate-100 text-slate-500">
                                Belum Bayar
                            </span>
                        @endif
                    </div>
                </div>
            </div>

            {{-- Penanganan — hanya tampil jika ada assigned admin atau catatan admin --}}
            @if ($order->assignedAdmin || $order->admin_notes)
            <div class="bg-white rounded-xl border border-slate-200 p-5">
                <h2 class="font-semibold text-slate-800 mb-4">Penanganan</h2>
                <div class="space-y-3 text-sm">
                    @if ($order->assignedAdmin)
                    <div>
                        <p class="text-xs text-slate-400 mb-0.5">Ditangani oleh</p>
                        <p class="font-medium text-slate-800">{{ $order->assignedAdmin->name }}</p>
                    </div>
                    @endif
                    @if ($order->admin_notes)
                        <div>
                            <p class="text-xs text-slate-400 mb-0.5">Catatan Admin</p>
                            <p class="text-slate-700 bg-slate-50 rounded-lg px-3 py-2 whitespace-pre-line">{{ $order->admin_notes }}</p>
                        </div>
                    @endif
                </div>
            </div>
            @endif

        </div>
    </div>

    {{-- ── Modal Ubah Status ───────────────────────────────────────────── --}}
    <div x-show="showStatusModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4"
        x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100">
        <div class="absolute inset-0 bg-black/50" @click="$wire.set('showStatusModal', false)"></div>
        <div class="relative bg-white rounded-2xl shadow-xl w-full max-w-md" @click.stop>
            <div class="p-6">
                <h3 class="text-lg font-semibold text-slate-800 mb-4">Ubah Status Pesanan</h3>

                <form wire:submit.prevent="updateStatus" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Status Baru <span class="text-red-500">*</span></label>
                        <select wire:model="newStatus"
                            class="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-orange-500 bg-white">
                            <option value="">— Pilih Status —</option>
                            @php
                                $isCod           = $order->payment_method === \App\Enums\PaymentMethod::Cod;
                                $paymentVerified = $order->payment?->status === \App\Enums\PaymentStatus::Verified;
                                $operationalNext = [\App\Enums\OrderStatus::Processing, \App\Enums\OrderStatus::Delivering, \App\Enums\OrderStatus::Completed];
                            @endphp
                            @foreach ($order->status->allowedTransitions() as $next)
                                @if ($next === \App\Enums\OrderStatus::Paid)
                                    {{-- BFS v1.1 Rule-1: paid hanya dari verifyPayment(), tidak ditampilkan di sini --}}
                                    @continue
                                @endif
                                @if (in_array($next, $operationalNext) && ! $isCod && ! $paymentVerified)
                                    {{-- BFS v1.1 Rule-2/3: operasional disembunyikan jika payment belum verified (non-COD) --}}
                                    @continue
                                @endif
                                <option value="{{ $next->value }}">{{ $next->label() }}</option>
                            @endforeach
                        </select>
                        @error('newStatus') <p class="mt-1 text-xs text-red-600">{{ $message }}</p> @enderror
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Catatan (opsional)</label>
                        <textarea wire:model="statusNote" rows="2" placeholder="Catatan internal untuk perubahan ini..."
                            class="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-orange-500 resize-none"></textarea>
                    </div>

                    <div class="flex gap-3 justify-end pt-2">
                        <button type="button" wire:click="$set('showStatusModal', false)"
                            class="px-4 py-2 text-sm font-medium text-slate-700 bg-white border border-slate-300 rounded-lg hover:bg-slate-50">
                            Batal
                        </button>
                        <button type="submit"
                            class="px-4 py-2 text-sm font-medium text-white bg-orange-500 rounded-lg hover:bg-orange-600"
                            wire:loading.attr="disabled">
                            <span wire:loading.remove wire:target="updateStatus">Simpan</span>
                            <span wire:loading wire:target="updateStatus">Menyimpan...</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    {{-- ── Modal Batalkan ──────────────────────────────────────────────── --}}
    <div x-show="showCancelModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4"
        x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100">
        <div class="absolute inset-0 bg-black/50" @click="$wire.set('showCancelModal', false)"></div>
        <div class="relative bg-white rounded-2xl shadow-xl w-full max-w-md" @click.stop>
            <div class="p-6">
                <div class="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mb-4">
                    <svg class="w-6 h-6 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"/>
                    </svg>
                </div>
                <h3 class="text-lg font-semibold text-slate-800 mb-1">Batalkan Pesanan?</h3>
                <p class="text-sm text-slate-500 mb-4">Tindakan ini tidak dapat dibatalkan kembali.</p>

                <form wire:submit.prevent="cancelOrder" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Alasan Pembatalan <span class="text-red-500">*</span></label>
                        <textarea wire:model="cancelReason" rows="3" placeholder="Jelaskan alasan pembatalan..."
                            class="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-orange-500 resize-none"></textarea>
                        @error('cancelReason') <p class="mt-1 text-xs text-red-600">{{ $message }}</p> @enderror
                    </div>

                    <div class="flex gap-3 justify-end pt-2">
                        <button type="button" wire:click="$set('showCancelModal', false)"
                            class="px-4 py-2 text-sm font-medium text-slate-700 bg-white border border-slate-300 rounded-lg hover:bg-slate-50">
                            Batal
                        </button>
                        <button type="submit"
                            class="px-4 py-2 text-sm font-medium text-white bg-red-500 rounded-lg hover:bg-red-600"
                            wire:loading.attr="disabled">
                            <span wire:loading.remove wire:target="cancelOrder">Ya, Batalkan Pesanan</span>
                            <span wire:loading wire:target="cancelOrder">Memproses...</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <x-admin.toast />
</div>
