<x-app-layout>
    <x-slot name="header">
        <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
            <div class="flex items-center gap-2 min-w-0">
                <div class="w-8 h-8 sm:w-9 sm:h-9 md:w-10 md:h-10 rounded-lg sm:rounded-xl flex items-center justify-center shadow-lg flex-shrink-0 gradient-primary">
                    <i class="fas fa-receipt text-xs sm:text-sm"></i>
                </div>
                <div class="min-w-0">
                    <h1 class="text-base sm:text-lg md:text-xl font-bold text-stone-800 truncate">Detail Pesanan</h1>
                    <p class="text-[10px] sm:text-xs text-stone-500 truncate">#{{ $order->order_id }}</p>
                </div>
            </div>
            <a href="{{ route('order.index') }}"
                class="flex-shrink-0 inline-flex items-center gap-1.5 px-3 py-1.5 sm:px-4 sm:py-2 bg-stone-100
                       hover:bg-stone-200 border border-stone-300 text-stone-700 text-xs sm:text-sm rounded-lg sm:rounded-xl transition">
                <i class="fas fa-arrow-left text-[10px] sm:text-xs"></i>
                <span>Kembali</span>
            </a>
        </div>
    </x-slot>

    @php
        $trackingSteps = [
            ['key'=>'processing','icon'=>'fa-box',        'title'=>'Sedang Dikemas',     'description'=>'Pesanan kamu sedang disiapkan dan dikemas oleh tim kami.',       'color'=>'from-amber-500 to-amber-600',  'text'=>'text-amber-600',  'bg'=>'bg-amber-50',  'border'=>'border-amber-200'],
            ['key'=>'shipped',   'icon'=>'fa-truck',      'title'=>'Dalam Perjalanan',   'description'=>'Paket telah diserahkan ke kurir dan sedang dalam perjalanan.',   'color'=>'from-blue-500 to-blue-600',    'text'=>'text-blue-600',   'bg'=>'bg-blue-50',   'border'=>'border-blue-200'],
            ['key'=>'delivered', 'icon'=>'fa-warehouse',  'title'=>'Hampir Tiba',        'description'=>'Paket tiba di kota tujuan dan sedang diantar ke alamat kamu.',   'color'=>'from-purple-500 to-purple-600','text'=>'text-purple-600', 'bg'=>'bg-purple-50', 'border'=>'border-purple-200'],
            ['key'=>'completed', 'icon'=>'fa-check-double','title'=>'Pesanan Diterima',  'description'=>'Pesanan telah diterima. Terima kasih sudah berbelanja!',         'color'=>'from-emerald-500 to-emerald-600','text'=>'text-emerald-600','bg'=>'bg-emerald-50','border'=>'border-emerald-200'],
        ];
        $statusOrder  = ['processing','shipped','delivered','completed'];
        $currentIndex = array_search($order->status, $statusOrder);
        $isCancelled  = ($order->status === 'cancelled');
        $isDone = fn(string $key) => array_search($key, $statusOrder) !== false && $currentIndex !== false && array_search($key, $statusOrder) <= $currentIndex;
        $isCurrent = fn(string $key) => $currentIndex !== false && array_search($key, $statusOrder) === $currentIndex;
        $totalSteps   = count($trackingSteps);
        $doneCount    = $currentIndex !== false ? $currentIndex + 1 : 0;
        $progressPct  = $totalSteps > 1 ? round(($doneCount / $totalSteps) * 100) : 0;
        $statusColors = ['processing'=>'bg-amber-50 text-amber-700 border-amber-200','shipped'=>'bg-blue-50 text-blue-700 border-blue-200','delivered'=>'bg-purple-50 text-purple-700 border-purple-200','completed'=>'bg-emerald-50 text-emerald-700 border-emerald-200','cancelled'=>'bg-rose-50 text-rose-700 border-rose-200'];
        $statusLabels = ['processing'=>'Sedang Dikemas','shipped'=>'Dikirim','delivered'=>'Hampir Tiba','completed'=>'Selesai','cancelled'=>'Dibatalkan'];
        $statusClass  = $statusColors[$order->status] ?? 'bg-stone-50 text-stone-700 border-stone-200';
        $statusLabel  = $statusLabels[$order->status] ?? ucfirst($order->status);
    @endphp

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

            {{-- ═══ KOLOM KIRI ═══ --}}
            <div class="lg:col-span-2 space-y-4 sm:space-y-6">

                {{-- Status + Tracking --}}
                <div class="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-stone-200 overflow-hidden">
                    <div class="p-4 sm:p-5 md:p-6">
                        <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4 mb-6">
                            <div class="flex items-center gap-2 sm:gap-3">
                                <div class="w-10 h-10 sm:w-11 sm:h-11 bg-gradient-to-br from-amber-100 to-stone-100
                                            rounded-lg sm:rounded-xl flex items-center justify-center shadow-sm border border-stone-200 flex-shrink-0">
                                    @if($isCancelled) <i class="fas fa-times-circle text-rose-600 text-lg sm:text-xl"></i>
                                    @elseif($order->isCompleted()) <i class="fas fa-check-double text-emerald-600 text-lg sm:text-xl"></i>
                                    @else <i class="fas fa-shipping-fast text-amber-600 text-lg sm:text-xl"></i>
                                    @endif
                                </div>
                                <div>
                                    <h3 class="text-sm sm:text-base md:text-lg font-bold text-stone-800">Tracking Pesanan</h3>
                                    <p class="text-[10px] sm:text-xs text-stone-500">
                                        <i class="fas fa-calendar-alt mr-1"></i>{{ $order->created_at->format('d M Y, H:i') }}
                                    </p>
                                </div>
                            </div>
                            <span class="px-3 sm:px-4 py-1.5 sm:py-2 text-xs sm:text-sm font-bold rounded-full {{ $statusClass }} border inline-flex items-center whitespace-nowrap">
                                <i class="fas fa-circle mr-1.5 text-[8px] sm:text-[10px]"></i>{{ $statusLabel }}
                            </span>
                        </div>

                        @if(!$isCancelled)
                        <div class="mb-5">
                            <div class="flex justify-between text-[10px] text-stone-400 mb-1">
                                <span>Mulai</span>
                                <span>{{ $progressPct }}% selesai</span>
                            </div>
                            <div class="w-full h-2 bg-stone-200 rounded-full overflow-hidden">
                                <div class="h-2 rounded-full gradient-primary transition-all duration-700"
                                     style="width: {{ $progressPct }}%"></div>
                            </div>
                        </div>

                        <div class="relative">
                            <div class="absolute left-[18px] sm:left-[22px] top-0 bottom-0 w-0.5 bg-stone-200 z-0"></div>
                            <div class="space-y-4 sm:space-y-5 relative z-10">
                                @foreach($trackingSteps as $i => $step)
                                @php $done = $isDone($step['key']); $current = $isCurrent($step['key']); @endphp
                                <div class="flex items-start gap-3 sm:gap-4">
                                    <div class="flex-shrink-0 w-9 h-9 sm:w-11 sm:h-11 rounded-full flex items-center justify-center border-2 z-10
                                        @if($done) bg-gradient-to-br {{ $step['color'] }} border-white shadow-md
                                        @elseif($current) bg-white {{ $step['border'] }} shadow
                                        @else bg-stone-100 border-stone-200 @endif">
                                        <i class="fas {{ $step['icon'] }} text-xs sm:text-sm
                                            @if($done) text-white
                                            @elseif($current) {{ $step['text'] }}
                                            @else text-stone-400 @endif"></i>
                                    </div>
                                    <div class="flex-1 min-w-0 pb-4 sm:pb-5">
                                        <div class="rounded-lg sm:rounded-xl p-3 sm:p-4 border
                                            @if($done) {{ $step['bg'] }} {{ $step['border'] }}
                                            @elseif($current) {{ $step['bg'] }} {{ $step['border'] }} ring-1 ring-offset-1 ring-amber-300
                                            @else bg-stone-50 border-stone-200 opacity-50 @endif">
                                            <div class="flex items-center justify-between flex-wrap gap-2">
                                                <h5 class="text-xs sm:text-sm font-bold
                                                    {{ ($done || $current) ? $step['text'] : 'text-stone-400' }}">
                                                    @if($done && !$current) <i class="fas fa-check-circle mr-1.5 text-[10px]"></i>
                                                    @elseif($current) <i class="fas fa-circle-notch fa-spin mr-1.5 text-[10px]"></i>
                                                    @else <i class="fas fa-circle mr-1.5 text-[10px] opacity-40"></i>
                                                    @endif
                                                    {{ $step['title'] }}
                                                </h5>
                                                @if($done || $current)
                                                <span class="text-[10px] text-stone-500">
                                                    {{ $step['key'] === 'processing' ? $order->created_at->format('d M Y, H:i') : $order->updated_at->format('d M Y, H:i') }}
                                                </span>
                                                @endif
                                            </div>
                                            <p class="text-[10px] sm:text-xs mt-1 {{ ($done || $current) ? 'text-stone-600' : 'text-stone-400' }}">
                                                {{ $step['description'] }}
                                            </p>

                                            @if($step['key'] === 'shipped' && ($done || $current) && $order->hasTrackingNumber())
                                            <div class="mt-2 pt-2 border-t {{ $step['border'] }}">
                                                <div class="flex items-center gap-2">
                                                    <i class="fas fa-barcode {{ $step['text'] }} text-sm flex-shrink-0"></i>
                                                    <span class="font-mono text-xs font-bold text-stone-800 tracking-wider flex-1">
                                                        {{ $order->tracking_number }}
                                                    </span>
                                                    <button onclick="copyResi('{{ $order->tracking_number }}')"
                                                        class="text-[10px] {{ $step['text'] }} font-semibold flex items-center gap-1 hover:opacity-75 transition">
                                                        <i class="fas fa-copy"></i>Salin
                                                    </button>
                                                </div>
                                            </div>
                                            @endif
                                        </div>
                                    </div>
                                </div>
                                @endforeach
                            </div>
                        </div>

                        @else
                        <div class="relative pl-8 sm:pl-10">
                            <div class="bg-rose-50 rounded-lg sm:rounded-xl p-3 sm:p-4 border border-rose-200">
                                <h5 class="text-xs sm:text-sm font-bold text-rose-700">
                                    <i class="fas fa-times-circle mr-1.5"></i>Pesanan Dibatalkan
                                </h5>
                                <p class="text-[10px] sm:text-xs text-rose-600 mt-0.5">{{ $order->updated_at->format('d M Y, H:i') }}</p>
                                <p class="text-[10px] sm:text-xs text-rose-500 mt-1">Pesanan ini telah dibatalkan.</p>
                            </div>
                        </div>
                        @endif
                    </div>
                </div>

                {{-- Produk --}}
                <div class="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-stone-200 overflow-hidden">
                    <div class="p-4 sm:p-5 md:p-6">
                        <h3 class="text-sm sm:text-base md:text-lg font-bold text-stone-800 mb-3 sm:mb-4 flex items-center">
                            <i class="fas fa-boxes mr-2 text-amber-600"></i>
                            Produk yang Dibeli
                            <span class="ml-auto text-[10px] sm:text-xs font-normal text-stone-500">
                                {{ $order->items->count() }} item
                            </span>
                        </h3>
                        <div class="space-y-3 sm:space-y-4">
                            @foreach($order->items as $item)
                            <div class="flex flex-col xs:flex-row gap-3 p-3 sm:p-4 {{ !$loop->last ? 'border-b border-stone-200' : '' }}">
                                @php
                                    $productImage = $item->product->image ?? null;
                                    $imageUrl = null;
                                    if ($productImage) {
                                        if (is_array($productImage) && count($productImage) > 0) {
                                            $imageUrl = asset('storage/'.$productImage[0]);
                                        } elseif (is_string($productImage)) {
                                            $decoded = json_decode($productImage, true);
                                            $imageUrl = is_array($decoded) && count($decoded) > 0
                                                ? asset('storage/'.$decoded[0])
                                                : asset('storage/'.$productImage);
                                        }
                                    }
                                @endphp
                                <div class="flex-shrink-0 w-full xs:w-16 sm:w-20 h-16 sm:h-20 bg-gradient-to-br from-amber-100 to-stone-100
                                            rounded-lg sm:rounded-xl overflow-hidden border border-stone-200 shadow-sm">
                                    @if($imageUrl) <img src="{{ $imageUrl }}" alt="{{ $item->product->product_name }}" class="w-full h-full object-cover">
                                    @else <div class="w-full h-full flex items-center justify-center"><i class="fas fa-box text-lg sm:text-xl text-amber-400"></i></div>
                                    @endif
                                </div>
                                <div class="flex-1 min-w-0">
                                    <div class="flex flex-col xs:flex-row xs:items-start justify-between gap-2">
                                        <div>
                                            <h4 class="text-xs sm:text-sm md:text-base font-semibold text-stone-800">{{ $item->product->product_name }}</h4>
                                            <span class="inline-flex items-center px-2 py-0.5 bg-amber-50 text-amber-700 rounded-full text-[8px] sm:text-[10px] font-medium border border-amber-200 mt-1">
                                                <i class="fas fa-tag mr-1"></i>{{ $item->product->category->category_name ?? '-' }}
                                            </span>
                                        </div>
                                        <div class="text-right">
                                            <p class="text-[8px] sm:text-[10px] text-stone-500">Harga Satuan</p>
                                            <p class="text-xs sm:text-sm font-semibold text-stone-800">
                                                Rp {{ number_format($item->subtotal / $item->quantity, 0, ',', '.') }}
                                            </p>
                                        </div>
                                    </div>
                                    <div class="flex flex-col xs:flex-row xs:items-center justify-between mt-2 gap-2">
                                        <div class="flex items-center gap-2">
                                            <span class="text-[8px] sm:text-[10px] text-stone-500">Jumlah:</span>
                                            <span class="px-2 py-0.5 bg-amber-50 rounded-lg text-xs font-bold text-amber-700 border border-amber-200">
                                                {{ $item->quantity }}
                                            </span>
                                        </div>
                                        <div class="text-right">
                                            <p class="text-[8px] sm:text-[10px] text-stone-500">Subtotal</p>
                                            <p class="text-sm sm:text-base font-extrabold text-amber-600">
                                                Rp {{ number_format($item->subtotal, 0, ',', '.') }}
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            @endforeach
                        </div>
                    </div>
                </div>

                {{-- Alamat pengiriman --}}
                @if($order->address)
                <div class="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-stone-200 overflow-hidden">
                    <div class="p-4 sm:p-5">
                        <h3 class="text-sm font-bold text-stone-800 mb-3 flex items-center">
                            <i class="fas fa-map-marker-alt mr-2 text-amber-600"></i>
                            Alamat Pengiriman
                        </h3>
                        <div class="bg-stone-50 rounded-xl p-3 border border-stone-200">
                            <div class="flex items-center gap-2 mb-1">
                                <span class="font-bold text-stone-800 text-sm">{{ $order->address->recipient_name }}</span>
                                <span class="text-stone-400 text-xs">·</span>
                                <span class="text-stone-600 text-xs">{{ $order->address->phone }}</span>
                            </div>
                            <p class="text-xs text-stone-600 leading-relaxed">{{ $order->address->full_address }}</p>
                        </div>
                    </div>
                </div>
                @endif

                {{-- ═══ SECTION ULASAN (hanya jika order completed) ═══ --}}
                @if($order->isCompleted())
                <div class="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-stone-200 overflow-hidden">
                    <div class="p-4 sm:p-5 md:p-6">
                        <h3 class="text-sm sm:text-base md:text-lg font-bold text-stone-800 mb-1 flex items-center gap-2">
                            <i class="fas fa-star text-amber-500"></i>
                            Beri Ulasan Produk
                        </h3>
                        <p class="text-xs text-stone-400 mb-4">Bagikan pengalaman belanjamu untuk membantu pembeli lain.</p>

                        <div class="space-y-3">
                            @foreach($order->items as $item)
                            @php
                                $product = $item->product;
                                $isReviewed = in_array($product->product_id, $reviewedProductIds);
                                $productImage = $product->image ?? null;
                                $imgUrl = null;
                                if ($productImage) {
                                    if (is_array($productImage) && count($productImage) > 0) {
                                        $imgUrl = asset('storage/'.$productImage[0]);
                                    } elseif (is_string($productImage)) {
                                        $decoded = json_decode($productImage, true);
                                        $imgUrl = is_array($decoded) && count($decoded) > 0
                                            ? asset('storage/'.$decoded[0])
                                            : asset('storage/'.$productImage);
                                    }
                                }
                            @endphp
                            <div class="flex items-center gap-3 p-3 rounded-xl border {{ $isReviewed ? 'bg-stone-50 border-stone-200' : 'bg-amber-50 border-amber-200' }}">
                                {{-- Foto produk --}}
                                <div class="flex-shrink-0 w-12 h-12 rounded-lg overflow-hidden border border-stone-200 bg-amber-100">
                                    @if($imgUrl)
                                        <img src="{{ $imgUrl }}" alt="{{ $product->product_name }}" class="w-full h-full object-cover">
                                    @else
                                        <div class="w-full h-full flex items-center justify-center">
                                            <i class="fas fa-box text-amber-400"></i>
                                        </div>
                                    @endif
                                </div>
                                {{-- Info produk --}}
                                <div class="flex-1 min-w-0">
                                    <p class="text-xs sm:text-sm font-semibold text-stone-800 truncate">{{ $product->product_name }}</p>
                                    <p class="text-[10px] text-stone-500">{{ $item->quantity }}x · Rp {{ number_format($item->subtotal / $item->quantity, 0, ',', '.') }}</p>
                                </div>
                                {{-- Tombol --}}
                                @if($isReviewed)
                                    <span class="flex-shrink-0 inline-flex items-center gap-1.5 px-3 py-1.5 bg-emerald-50 text-emerald-700 border border-emerald-200 rounded-lg text-xs font-semibold">
                                        <i class="fas fa-check-circle"></i> Sudah Diulas
                                    </span>
                                @else
                                    <button type="button"
                                        onclick="openReviewModal('{{ $product->product_id }}', '{{ addslashes($product->product_name) }}', '{{ $imgUrl ?? '' }}')"
                                        class="flex-shrink-0 inline-flex items-center gap-1.5 px-3 py-1.5 bg-gradient-to-r from-amber-400 to-amber-500 hover:from-amber-500 hover:to-amber-600 text-white rounded-lg text-xs font-bold shadow-sm transition-all duration-200">
                                        <i class="fas fa-pen"></i> Tulis Ulasan
                                    </button>
                                @endif
                            </div>
                            @endforeach
                        </div>
                    </div>
                </div>
                @endif

            </div>

            {{-- ═══ KOLOM KANAN ═══ --}}
            <div class="lg:col-span-1">
                <div class="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-stone-200 overflow-hidden sticky top-4 sm:top-6">
                    <div class="p-4 sm:p-5 md:p-6 space-y-4">

                        {{-- Ringkasan Pembayaran --}}
                        <div>
                            <h3 class="text-sm sm:text-base font-bold text-stone-800 mb-3 flex items-center">
                                <i class="fas fa-receipt mr-2 text-amber-600"></i>Ringkasan Pembayaran
                            </h3>
                            <div class="space-y-2 text-xs sm:text-sm bg-stone-50 rounded-xl p-3 sm:p-4 mb-3">
                                <div class="flex justify-between">
                                    <span class="text-stone-600">Subtotal Produk</span>
                                    <span class="font-semibold text-stone-800">
                                        Rp {{ number_format($order->product_subtotal, 0, ',', '.') }}
                                    </span>
                                </div>
                                <div class="flex justify-between items-center">
                                    <span class="text-stone-600 flex items-center gap-1">
                                        <i class="fas fa-truck text-stone-400 text-xs"></i>
                                        Ongkos Kirim
                                        @if($order->courier_name)
                                        <span class="text-[10px] text-stone-400">({{ $order->courier_name }})</span>
                                        @endif
                                    </span>
                                    @if((int)$order->shipping_cost === 0)
                                    <span class="inline-flex items-center px-2 py-0.5 bg-emerald-50 text-emerald-700 rounded-full text-[10px] sm:text-xs font-semibold border border-emerald-200">
                                        <i class="fas fa-check-circle mr-1"></i>GRATIS
                                    </span>
                                    @else
                                    <span class="font-semibold text-stone-800">
                                        Rp {{ number_format($order->shipping_cost, 0, ',', '.') }}
                                    </span>
                                    @endif
                                </div>
                            </div>
                            <div class="flex justify-between items-center p-3 sm:p-4 bg-gradient-to-r from-amber-50 to-stone-50 rounded-xl border border-amber-100 mb-4">
                                <span class="font-bold text-stone-800 text-xs sm:text-sm">Total Pembayaran</span>
                                <span class="text-lg sm:text-xl md:text-2xl font-extrabold text-amber-600">
                                    Rp {{ number_format($order->total_price, 0, ',', '.') }}
                                </span>
                            </div>
                        </div>

                        {{-- Metode Pembayaran --}}
                        @if($order->payment)
                        <div class="border-t border-stone-200 pt-4">
                            <h4 class="text-xs sm:text-sm font-bold text-stone-800 mb-2 sm:mb-3 flex items-center">
                                <i class="fas fa-credit-card mr-2 text-amber-600"></i>Metode Pembayaran
                            </h4>
                            <div class="bg-stone-50 rounded-xl p-3 sm:p-4 space-y-2">
                                <div class="flex justify-between">
                                    <span class="text-[8px] sm:text-xs text-stone-500">Metode</span>
                                    <span class="text-xs sm:text-sm font-semibold text-stone-800">{{ strtoupper($order->payment->payment_method) }}</span>
                                </div>
                                @if($order->payment->isPaid())
                                <div class="mt-2 p-2 bg-emerald-50 rounded-lg border border-emerald-200">
                                    <p class="text-[8px] sm:text-xs text-emerald-700 flex items-center">
                                        <i class="fas fa-check-circle mr-1"></i>
                                        Dibayar {{ $order->payment->payment_date->format('d M Y, H:i') }}
                                    </p>
                                </div>
                                @elseif($order->payment->isUnpaid())
                                <a href="{{ route('payment.show', $order->payment->id) }}"
                                    class="mt-2 w-full inline-flex justify-center items-center px-3 sm:px-4 py-2 sm:py-2.5 btn-primary text-xs sm:text-sm font-bold rounded-xl shadow-md hover:shadow-lg transition-all duration-200">
                                    <i class="fas fa-credit-card mr-2"></i>Lihat Pembayaran
                                </a>
                                @endif
                            </div>
                        </div>
                        @endif

                        {{-- Resi & Info Pengiriman --}}
                        @include('orders._tracking_resi', ['order' => $order])

                        
@php
    $payment        = $order->payment;
    $invoiceReady   = $payment && $payment->isPaid();
    $isCashUnpaid   = $payment
                      && $payment->payment_method === 'cash'
                      && !$payment->isPaid();
@endphp
 
{{-- Tombol Invoice --}}
<div class="border-t border-stone-200 pt-3 sm:pt-4 mt-3 sm:mt-4">
    <h4 class="text-xs sm:text-sm font-bold text-stone-800 mb-2 sm:mb-3 flex items-center">
        <i class="fas fa-file-invoice mr-2 text-amber-600"></i>
        Invoice
    </h4>
 
    @if($invoiceReady)
        {{-- Payment sudah lunas → tampilkan invoice --}}
        <div class="space-y-2">
            <a href="{{ route('invoice.show', $order->order_id) }}"
               class="btn-primary w-full inline-flex items-center justify-center gap-2 px-4 py-2.5 text-xs font-bold rounded-xl transition shadow-sm">
                <i class="fas fa-file-invoice"></i>
                Lihat Invoice
            </a>
            <a href="{{ route('invoice.download', $order->order_id) }}" 
               onclick="window.open('{{ route('invoice.stream', $order->order_id) }}', '_blank');"
               class="w-full inline-flex items-center justify-center gap-2 px-4 py-2.5
                      bg-stone-100 hover:bg-stone-200 text-stone-700 text-xs font-semibold
                      rounded-xl border border-stone-300 transition">
                <i class="fas fa-file-pdf text-amber-600"></i>
                Download PDF
            </a>
        </div>
 
    @elseif($isCashUnpaid)
        {{-- COD & belum dibayar → invoice belum tersedia --}}
        <div class="flex items-start gap-2 p-3 bg-amber-50 rounded-xl border border-amber-200">
            <i class="fas fa-info-circle text-amber-500 flex-shrink-0 mt-0.5"></i>
            <p class="text-xs text-amber-700">
                Invoice akan tersedia setelah pembayaran COD dikonfirmasi oleh admin.
            </p>
        </div>
 
    @elseif($payment && !$payment->isPaid())
        {{-- Online payment, masih pending --}}
        <div class="flex items-start gap-2 p-3 bg-stone-50 rounded-xl border border-stone-200">
            <i class="fas fa-clock text-stone-400 flex-shrink-0 mt-0.5"></i>
            <p class="text-xs text-stone-500">
                Invoice akan tersedia setelah pembayaran dikonfirmasi.
            </p>
        </div>
 
    @endif
</div>

                        {{-- Tombol Batal --}}
                        @if($order->isProcessing())
                        <div class="mt-2">
                            <button onclick="openCancelModal()"
                                class="w-full inline-flex justify-center items-center px-3 sm:px-4 py-2 sm:py-3
                                    text-white text-xs sm:text-sm font-bold rounded-lg sm:rounded-xl shadow-md hover:shadow-lg transition-all duration-200"
                                style="background: linear-gradient(135deg, #e11d48, #be123c);">
                                <i class="fas fa-times-circle mr-2"></i>Batalkan Pesanan
                            </button>
                        </div>

                        {{-- Hidden form untuk cancel --}}
                        <form id="cancel-order-form" action="{{ route('order.cancel', $order->order_id) }}" method="POST" style="display: none;">
                            @csrf
                        </form>
                        @endif

                        @if($order->isCompleted())
                        <div class="mt-2 p-3 bg-emerald-50 rounded-xl border border-emerald-200">
                            <p class="text-[8px] sm:text-xs text-emerald-700 text-center flex items-center justify-center">
                                <i class="fas fa-check-circle mr-1"></i>Terima kasih telah berbelanja!
                            </p>
                        </div>
                        @endif

                    </div>
                </div>
            </div>

        </div>
    </div>

    {{-- Modal Batalkan Pesanan --}}
    <div id="cancelOrderModal" class="fixed inset-0 z-[9999] hidden items-center justify-center bg-black/50 backdrop-blur-sm transition-all duration-300">
        <div class="bg-white rounded-2xl max-w-md w-full mx-4 transform transition-all duration-300 scale-95 opacity-0 shadow-2xl" id="cancelOrderModalContent">
            <div class="p-6">
                <!-- Icon & Title -->
                <div class="text-center mb-4">
                    <div class="mx-auto w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mb-3">
                        <svg class="w-8 h-8 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
                        </svg>
                    </div>
                    <h3 class="text-xl font-bold text-slate-800">Batalkan Pesanan</h3>
                </div>

                <p class="text-slate-500 text-center text-sm mb-2">Apakah Anda yakin ingin membatalkan pesanan</p>
                <p class="text-center font-semibold text-slate-800 mb-6">#{{ $order->order_id }}?</p>

                <div class="flex gap-3">
                    <button onclick="closeCancelModal()"
                        class="flex-1 px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 text-sm font-semibold rounded-xl transition-all duration-200">
                        Tidak
                    </button>
                    <button id="confirmCancelBtn"
                        class="flex-1 px-4 py-2.5 text-white text-sm font-semibold rounded-xl transition-all duration-200"
                        style="background: linear-gradient(135deg, #e11d48, #be123c);">
                        <i class="fas fa-times-circle mr-1"></i> Ya, Batalkan
                    </button>
                </div>
            </div>
        </div>
    </div>

    <style>
        @media (max-width: 480px) {
            .xs\:flex-row { flex-direction: row; }
            .xs\:items-start { align-items: flex-start; }
            .xs\:w-16 { width: 4rem; }
        }
        button, a, [role="button"] { touch-action: manipulation; min-height: 40px; }
        input, select, textarea { font-size: 16px !important; }

        /* Star rating */
        .star-btn { cursor: pointer; transition: transform 0.1s; color: #d1d5db; font-size: 1.75rem; }
        .star-btn:hover, .star-btn.active { color: #f59e0b; transform: scale(1.15); }
        .star-btn.active { filter: drop-shadow(0 0 4px rgba(245,158,11,0.5)); }
    </style>

    {{-- ════ MODAL REVIEW ════ --}}
    <div id="reviewModal" class="fixed inset-0 z-[9999] hidden items-center justify-center bg-black/50 backdrop-blur-sm p-4">
        <div id="reviewModalContent"
             class="bg-white rounded-2xl w-full max-w-lg shadow-2xl transform transition-all duration-300 scale-95 opacity-0 overflow-hidden">

            {{-- Header --}}
            <div class="bg-gradient-to-r from-amber-400 to-amber-500 p-4 sm:p-5 flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <div id="reviewProductImg"
                         class="w-12 h-12 rounded-xl overflow-hidden border-2 border-white/50 bg-amber-200 flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-box text-white text-lg"></i>
                    </div>
                    <div>
                        <p class="text-xs text-amber-100 font-medium">Ulasan untuk</p>
                        <h3 id="reviewProductName" class="text-sm sm:text-base font-bold text-white leading-tight line-clamp-2"></h3>
                    </div>
                </div>
                <button onclick="closeReviewModal()" class="text-white/80 hover:text-white transition ml-2 flex-shrink-0">
                    <i class="fas fa-times text-lg"></i>
                </button>
            </div>

            {{-- Body --}}
            <form id="reviewForm" method="POST" enctype="multipart/form-data" class="p-4 sm:p-5 space-y-4">
                @csrf

                {{-- Hidden product_id --}}
                <input type="hidden" id="reviewProductId" name="_product_id_placeholder">

                {{-- Rating --}}
                <div>
                    <label class="block text-sm font-semibold text-stone-700 mb-2">Rating <span class="text-rose-500">*</span></label>
                    <div class="flex gap-1 justify-center" id="starContainer">
                        @for($s = 1; $s <= 5; $s++)
                        <button type="button" class="star-btn" data-value="{{ $s }}" onclick="setRating({{ $s }})">
                            <i class="fas fa-star"></i>
                        </button>
                        @endfor
                    </div>
                    <input type="hidden" name="rating" id="ratingInput" value="">
                    <p id="ratingLabel" class="text-center text-xs text-stone-400 mt-1">Ketuk bintang untuk memberi rating</p>
                </div>

                {{-- Komentar --}}
                <div>
                    <label class="block text-sm font-semibold text-stone-700 mb-1" for="reviewComment">Komentar <span class="text-stone-400 font-normal">(opsional)</span></label>
                    <textarea id="reviewComment" name="comment" rows="3"
                        placeholder="Ceritakan pengalamanmu dengan produk ini..."
                        class="w-full rounded-xl border border-stone-200 bg-stone-50 px-3 py-2.5 text-sm text-stone-800 focus:outline-none focus:ring-2 focus:ring-amber-400 focus:border-transparent resize-none transition"></textarea>
                </div>

                {{-- Upload foto --}}
                <div>
                    <label class="block text-sm font-semibold text-stone-700 mb-1">Foto/Video <span class="text-stone-400 font-normal">(opsional)</span></label>
                    <label for="reviewMedia"
                           class="flex items-center gap-2 w-full cursor-pointer border-2 border-dashed border-stone-200 hover:border-amber-400 rounded-xl p-3 transition-colors duration-200 bg-stone-50 hover:bg-amber-50">
                        <i class="fas fa-camera text-amber-400 text-lg"></i>
                        <span class="text-xs text-stone-500">Tambah foto atau video produk</span>
                    </label>
                    <input type="file" id="reviewMedia" name="media[]" multiple accept="image/*,video/*"
                           class="hidden" onchange="previewMedia(this)">
                    <div id="mediaPreview" class="flex gap-2 flex-wrap mt-2"></div>
                </div>

                {{-- Actions --}}
                <div class="flex gap-3 pt-1">
                    <button type="submit" id="reviewSubmitBtn"
                            class="flex-1 px-4 py-2.5 bg-gradient-to-r from-amber-400 to-amber-500 hover:from-amber-500 hover:to-amber-600 text-white text-sm font-bold rounded-xl shadow-md transition disabled:opacity-50 disabled:cursor-not-allowed">
                        <i class="fas fa-paper-plane mr-1"></i> Kirim Ulasan
                    </button>
                </div>
            </form>
        </div>
    </div>

    @push('scripts')
    <script>
        /* ─── Cancel Modal ─────────────────────────────────────── */
        function openCancelModal() {
            const modal = document.getElementById('cancelOrderModal');
            const modalContent = document.getElementById('cancelOrderModalContent');
            modal.classList.remove('hidden');
            modal.classList.add('flex');
            void modal.offsetHeight;
            setTimeout(() => {
                modalContent.classList.remove('scale-95', 'opacity-0');
                modalContent.classList.add('scale-100', 'opacity-100');
            }, 10);
            document.body.style.overflow = 'hidden';
        }

        function closeCancelModal() {
            const modal = document.getElementById('cancelOrderModal');
            const modalContent = document.getElementById('cancelOrderModalContent');
            modalContent.classList.remove('scale-100', 'opacity-100');
            modalContent.classList.add('scale-95', 'opacity-0');
            setTimeout(() => {
                modal.classList.remove('flex');
                modal.classList.add('hidden');
                document.body.style.overflow = '';
            }, 300);
        }

        document.getElementById('confirmCancelBtn')?.addEventListener('click', function() {
            document.getElementById('cancel-order-form').submit();
        });

        document.getElementById('cancelOrderModal')?.addEventListener('click', function(e) {
            if (e.target === this) closeCancelModal();
        });

        /* ─── Review Modal ─────────────────────────────────────── */
        const ratingLabels = ['', 'Tidak Memuaskan 😞', 'Kurang Memuaskan 😐', 'Cukup Bagus 🙂', 'Bagus! 😊', 'Luar Biasa! 🤩'];

        function openReviewModal(productId, productName, imgUrl) {
            // Set form action
            const baseUrl = '{{ url("/orders/" . $order->order_id . "/review") }}';
            document.getElementById('reviewForm').action = baseUrl + '/' + productId;

            // Set product name
            document.getElementById('reviewProductName').textContent = productName;

            // Set product image
            const imgContainer = document.getElementById('reviewProductImg');
            if (imgUrl) {
                imgContainer.innerHTML = `<img src="${imgUrl}" alt="${productName}" class="w-full h-full object-cover">`;
            } else {
                imgContainer.innerHTML = `<i class="fas fa-box text-white text-lg"></i>`;
            }

            // Reset form
            document.getElementById('ratingInput').value = '';
            document.getElementById('reviewComment').value = '';
            document.getElementById('mediaPreview').innerHTML = '';
            document.getElementById('reviewMedia').value = '';
            document.getElementById('ratingLabel').textContent = 'Ketuk bintang untuk memberi rating';
            document.querySelectorAll('.star-btn').forEach(s => s.classList.remove('active'));

            // Show modal
            const modal = document.getElementById('reviewModal');
            const content = document.getElementById('reviewModalContent');
            modal.classList.remove('hidden');
            modal.classList.add('flex');
            void modal.offsetHeight;
            setTimeout(() => {
                content.classList.remove('scale-95', 'opacity-0');
                content.classList.add('scale-100', 'opacity-100');
            }, 10);
            document.body.style.overflow = 'hidden';
        }

        function closeReviewModal() {
            const modal = document.getElementById('reviewModal');
            const content = document.getElementById('reviewModalContent');
            content.classList.remove('scale-100', 'opacity-100');
            content.classList.add('scale-95', 'opacity-0');
            setTimeout(() => {
                modal.classList.remove('flex');
                modal.classList.add('hidden');
                document.body.style.overflow = '';
            }, 300);
        }

        function setRating(value) {
            document.getElementById('ratingInput').value = value;
            document.getElementById('ratingLabel').textContent = ratingLabels[value] || '';
            document.querySelectorAll('.star-btn').forEach(btn => {
                if (parseInt(btn.dataset.value) <= value) {
                    btn.classList.add('active');
                } else {
                    btn.classList.remove('active');
                }
            });
        }

        // Hover effect on stars
        document.querySelectorAll('.star-btn').forEach(btn => {
            btn.addEventListener('mouseenter', function() {
                const val = parseInt(this.dataset.value);
                document.querySelectorAll('.star-btn').forEach(b => {
                    b.style.color = parseInt(b.dataset.value) <= val ? '#f59e0b' : '#d1d5db';
                });
            });
            btn.addEventListener('mouseleave', function() {
                const current = parseInt(document.getElementById('ratingInput').value) || 0;
                document.querySelectorAll('.star-btn').forEach(b => {
                    b.style.color = parseInt(b.dataset.value) <= current ? '#f59e0b' : '#d1d5db';
                });
            });
        });

        function previewMedia(input) {
            const preview = document.getElementById('mediaPreview');
            preview.innerHTML = '';
            Array.from(input.files).slice(0, 5).forEach(file => {
                const reader = new FileReader();
                const wrapper = document.createElement('div');
                wrapper.className = 'w-16 h-16 rounded-lg overflow-hidden border border-stone-200 bg-stone-100 relative flex-shrink-0';
                if (file.type.startsWith('video/')) {
                    wrapper.innerHTML = `<div class="w-full h-full flex items-center justify-center bg-stone-200"><i class="fas fa-film text-stone-500"></i></div>`;
                    preview.appendChild(wrapper);
                } else {
                    reader.onload = e => {
                        wrapper.innerHTML = `<img src="${e.target.result}" class="w-full h-full object-cover">`;
                    };
                    reader.readAsDataURL(file);
                    preview.appendChild(wrapper);
                }
            });
        }

        // Validate form before submit
        document.getElementById('reviewForm').addEventListener('submit', function(e) {
            if (!document.getElementById('ratingInput').value) {
                e.preventDefault();
                document.getElementById('ratingLabel').textContent = '⚠️ Pilih rating terlebih dahulu!';
                document.getElementById('ratingLabel').classList.add('text-rose-500');
                return;
            }
            document.getElementById('reviewSubmitBtn').disabled = true;
            document.getElementById('reviewSubmitBtn').innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> Mengirim...';
        });

        // Close modal on backdrop click / Escape
        document.getElementById('reviewModal')?.addEventListener('click', function(e) {
            if (e.target === this) closeReviewModal();
        });

        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                const cancelModal = document.getElementById('cancelOrderModal');
                const reviewModal = document.getElementById('reviewModal');
                if (cancelModal && cancelModal.classList.contains('flex')) closeCancelModal();
                if (reviewModal && reviewModal.classList.contains('flex')) closeReviewModal();
            }
        });
    </script>
    @endpush

</x-app-layout>
