<x-app-layout>
<x-slot name="header">
    <div class="flex flex-col sm:flex-row sm:items-center gap-4 w-full">
        <div class="flex items-center gap-3">
            <div class="w-10 h-10 rounded-xl flex items-center justify-center shadow-lg flex-shrink-0"
                style="background: linear-gradient(135deg, #0f172a 0%, #334155 100%);">
                <i class="fas fa-shopping-bag text-white text-sm"></i>
            </div>
            <div>
                <h1 class="text-lg sm:text-xl font-bold text-stone-800">Checkout</h1>
                <p class="text-xs text-stone-500">Periksa pesanan sebelum membayar</p>
            </div>
        </div>
        <a href="{{ route('product.index') }}"
            class="sm:ml-auto inline-flex items-center gap-2 px-4 py-2 bg-white hover:bg-gray-50
                   text-gray-600 text-sm font-medium rounded-xl border border-gray-200 shadow-sm
                   hover:shadow transition-all duration-200">
            <i class="fas fa-arrow-left text-xs"></i>
            <span>Kembali</span>
        </a>
    </div>
</x-slot>

@push('styles')
<style>
.co-page { background: #f5f5f5; min-height: 100vh; }
.addr-row { cursor: pointer; transition: all .15s; }
.addr-row:hover { background: #fff7f0; }
.addr-row.active { background: #fff7f0; }
.addr-radio { width:18px; height:18px; border-radius:50%; border:2px solid #d1d5db; flex-shrink:0;
              display:flex; align-items:center; justify-content:center; transition: all .15s; }
.addr-radio.checked { border-color: #ee4d2d; background:#ee4d2d; }
.addr-radio.checked::after { content:''; width:7px; height:7px; border-radius:50%; background:white; display:block; }

.qty-btn { width:28px; height:28px; border:1px solid #d1d5db; border-radius:4px;
           display:flex; align-items:center; justify-content:center; cursor:pointer;
           font-size:14px; color:#555; transition: all .1s; background:white; }
.qty-btn:hover { border-color:#ee4d2d; color:#ee4d2d; }
.qty-btn:disabled { opacity:.4; cursor:not-allowed; }
.qty-display { min-width:36px; text-align:center; font-size:14px; font-weight:600; color:#222; }

.pay-opt { cursor:pointer; border:1.5px solid #e5e7eb; border-radius:10px; padding:12px 14px;
           display:flex; align-items:center; gap:12px; transition: all .15s; }
.pay-opt:hover { border-color:#ee4d2d; background:#fff7f5; }
.pay-opt.selected { border-color:#ee4d2d; background:#fff7f5; }
.pay-radio { width:18px; height:18px; border-radius:50%; border:2px solid #d1d5db; flex-shrink:0; transition: all .15s; }
.pay-radio.checked { border-color:#ee4d2d; border-width:5px; }

/* Kurir option — mirip pay-opt tapi lebar */
.courier-opt { cursor:pointer; border:1.5px solid #e5e7eb; border-radius:10px; padding:10px 14px;
               display:flex; align-items:center; gap:12px; transition: all .15s; }
.courier-opt:hover { border-color:#3b82f6; background:#eff6ff; }
.courier-opt.selected { border-color:#3b82f6; background:#eff6ff; }
.courier-radio { width:16px; height:16px; border-radius:50%; border:2px solid #d1d5db; flex-shrink:0; transition: all .15s; }
.courier-radio.checked { border-color:#3b82f6; border-width:5px; }

.modal-overlay { position:fixed; inset:0; background:rgba(0,0,0,.5); z-index:9999;
                 display:none; align-items:flex-end; justify-content:center; }
.modal-overlay.open { display:flex; }
.modal-box { background:white; width:100%; max-width:520px; border-radius:20px 20px 0 0;
             max-height:80vh; overflow-y:auto; animation: slideUp .25s ease; }
@media(min-width:640px){ .modal-overlay { align-items:center; }
  .modal-box { border-radius:16px; max-height:85vh; } }
@keyframes slideUp { from { transform: translateY(40px); opacity:0; } to { transform: translateY(0); opacity:1; } }

.summary-sticky { position: sticky; top: 16px; }

.btn-pesan { background: linear-gradient(135deg, #ee4d2d 0%, #d73211 100%); color:white;
             border:none; border-radius:10px; padding:14px; font-weight:700; font-size:15px;
             width:100%; cursor:pointer; transition: all .2s;
             box-shadow: 0 4px 12px rgba(238,77,45,.3); }
.btn-pesan:hover:not(:disabled) { transform:translateY(-1px); box-shadow: 0 6px 18px rgba(238,77,45,.4); }
.btn-pesan:disabled { background: #d1d5db; box-shadow:none; cursor:not-allowed; }

.delete-confirm { display:none; }
.delete-confirm.show { display:flex; }
.notes-input { border:1.5px solid #e5e7eb; border-radius:8px; padding:10px 12px; font-size:13px;
               color:#333; width:100%; resize:none; outline:none; transition: border .15s; }
.notes-input:focus { border-color:#ee4d2d; }
.co-card { background:white; border-radius:12px; overflow:hidden; box-shadow:0 1px 4px rgba(0,0,0,.06); }
.co-card-header { padding:14px 16px; border-bottom:1px solid #f3f4f6; display:flex; align-items:center; gap:8px; }
.co-card-body { padding:16px; }
.badge-primary { background:#fff0ed; color:#ee4d2d; font-size:11px; font-weight:700;
                 padding:2px 8px; border-radius:20px; border:1px solid #ffd0c6; }
/* Free shipping progress bar */
.free-bar { height:6px; background:#fef3c7; border-radius:3px; overflow:hidden; }
.free-bar-fill { height:6px; background:linear-gradient(90deg,#f59e0b,#10b981); border-radius:3px; transition:width .4s; }
</style>
@endpush

    <div class="space-y-6">

        @if($addresses->isEmpty())
        <div class="mb-4 p-4 bg-amber-50 border border-amber-300 text-amber-800 rounded-xl flex items-center gap-3 text-sm">
            <i class="fas fa-exclamation-triangle text-amber-500 flex-shrink-0"></i>
            <div>
                <p class="font-semibold">Belum ada alamat pengiriman</p>
                <p class="text-xs mt-0.5">Tambahkan alamat terlebih dahulu untuk melanjutkan.</p>
            </div>
        </div>
        @endif

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

            {{-- ════════════════ LEFT COLUMN ════════════════ --}}
            <div class="lg:col-span-2 space-y-3">

                {{-- ── CARD: ALAMAT PENGIRIMAN ── --}}
                <div class="co-card">
                    <div class="co-card-header">
                        <i class="fas fa-map-marker-alt text-red-500 text-sm"></i>
                        <span class="font-bold text-gray-800 text-sm">Alamat Pengiriman</span>
                    </div>
                    <div class="co-card-body">
                        @php
                            $selAddr = $addresses->firstWhere('id', $selectedAddressId) ?? $addresses->first();
                        @endphp

                        @if($selAddr)
                        <div class="flex items-start gap-3" id="selected-address-display">
                            <div class="flex-1">
                                <div class="flex items-center gap-2 flex-wrap">
                                    <span class="font-bold text-gray-900 text-sm">{{ auth()->user()->name }}</span>
                                    <span class="text-gray-400 text-xs">|</span>
                                    <span class="text-gray-600 text-sm" id="display-phone">{{ $selAddr->phone }}</span>
                                    <span class="badge-primary" id="display-name-badge">{{ $selAddr->recipient_name }}</span>
                                </div>
                                <p class="text-gray-600 text-sm mt-1 leading-relaxed" id="display-address">{{ $selAddr->full_address }}</p>
                            </div>
                            @if($addresses->count() > 1)
                            <button onclick="openAddressModal()"
                                class="flex-shrink-0 text-xs font-semibold text-red-500 hover:text-red-700 border border-red-300
                                       px-3 py-1.5 rounded-lg hover:bg-red-50 transition whitespace-nowrap">
                                Ganti
                            </button>
                            @endif
                        </div>
                        @else
                        <div class="text-center py-4">
                            <p class="text-gray-400 text-sm mb-3">Belum ada alamat</p>
                            <a href="{{ route('address.create', ['redirect_to' => 'cart.checkout.get']) }}"
                               class="inline-flex items-center gap-1.5 px-4 py-2 bg-red-500 text-white text-sm font-bold rounded-lg hover:bg-red-600 transition">
                                <i class="fas fa-plus text-xs"></i> Tambah Alamat
                            </a>
                        </div>
                        @endif

                        @if($addresses->isNotEmpty())
                        <div class="mt-3 pt-3 border-t border-gray-100">
                            <a href="{{ route('address.create', ['redirect_to' => 'cart.checkout.get']) }}"
                               class="inline-flex items-center gap-1.5 text-xs text-red-500 hover:text-red-700 font-semibold">
                                <i class="fas fa-plus-circle"></i> Tambah Alamat Baru
                            </a>
                        </div>
                        @endif
                    </div>
                </div>

                {{-- ── CARD: PRODUK PESANAN ── --}}
                <div class="co-card">
                    <div class="co-card-header justify-between">
                        <div class="flex items-center gap-2">
                            <i class="fas fa-store text-gray-500 text-sm"></i>
                            <span class="font-bold text-gray-800 text-sm">Produk Pesanan</span>
                        </div>
                        <span class="text-xs text-gray-400">{{ $cartItems->count() }} item</span>
                    </div>

                    <div id="items-container">
                    @foreach($cartItems as $item)
                    @php
                        $product  = $item->product;
                        $imageUrl = null;
                        $img      = $product->image ?? null;
                        if ($img) {
                            if (is_array($img) && count($img) > 0) $imageUrl = asset('storage/'.$img[0]);
                            elseif (is_string($img)) {
                                $dec = json_decode($img, true);
                                $imageUrl = is_array($dec) && count($dec) > 0
                                    ? asset('storage/'.$dec[0])
                                    : asset('storage/'.$img);
                            }
                        }
                        $isFake       = ($item->cart_id === null);
                        $itemWeight   = max((int)($product->weight ?? 1000), 1);
                    @endphp

                    <div class="item-row border-b border-gray-50 last:border-0 px-4 py-4"
                         id="item-row-{{ $item->cart_id ?? 'buynow' }}"
                         data-cart-id="{{ $item->cart_id ?? '' }}"
                         data-product-id="{{ $product->product_id }}"
                         data-price="{{ $product->price }}"
                         data-stock="{{ $product->stock }}"
                         data-weight="{{ $itemWeight }}"
                         data-is-fake="{{ $isFake ? '1' : '0' }}">

                        <div class="flex gap-3">
                            <div class="w-16 h-16 rounded-lg overflow-hidden border border-gray-100 flex-shrink-0 bg-gray-50">
                                @if($imageUrl)
                                <img src="{{ $imageUrl }}" 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-gray-300 text-xl"></i>
                                </div>
                                @endif
                            </div>

                            <div class="flex-1 min-w-0">
                                <p class="text-sm font-semibold text-gray-900 truncate">{{ $product->product_name }}</p>
                                <p class="text-xs text-gray-400 mt-0.5">
                                    {{ $product->category->category_name ?? '' }}
                                    @if($product->weight)
                                    · <i class="fas fa-weight-hanging text-gray-300 mr-0.5"></i>{{ $itemWeight >= 1000 ? round($itemWeight/1000,1).'kg' : $itemWeight.'g' }}
                                    @endif
                                </p>
                                <p class="text-sm font-bold text-red-500 mt-1">Rp {{ number_format($product->price, 0, ',', '.') }}</p>

                                <div class="flex items-center justify-between mt-3">
                                    <div class="flex items-center gap-1">
                                        <button class="qty-btn" onclick="changeQty('{{ $item->cart_id ?? 'buynow' }}', -1)"
                                            {{ $item->quantity <= 1 ? 'disabled' : '' }}>
                                            <i class="fas fa-minus text-xs"></i>
                                        </button>
                                        <span class="qty-display" id="qty-{{ $item->cart_id ?? 'buynow' }}">{{ $item->quantity }}</span>
                                        <button class="qty-btn" onclick="changeQty('{{ $item->cart_id ?? 'buynow' }}', 1)"
                                            {{ $item->quantity >= $product->stock ? 'disabled' : '' }}>
                                            <i class="fas fa-plus text-xs"></i>
                                        </button>
                                        <span class="text-xs text-gray-400 ml-1">
                                            (Stok: <span id="stock-{{ $item->cart_id ?? 'buynow' }}">{{ $product->stock }}</span>)
                                        </span>
                                    </div>

                                    <button onclick="confirmDelete('{{ $item->cart_id ?? 'buynow' }}')"
                                        class="text-xs font-medium text-red-400 hover:text-red-600 transition flex items-center gap-1.5 py-1 px-2 rounded-md hover:bg-red-50 border border-transparent hover:border-red-100">
                                        <i class="fas fa-trash-alt text-[10px]"></i> Hapus
                                    </button>
                                </div>

                                <div class="flex justify-end mt-2">
                                    <span class="text-xs text-gray-500">
                                        Subtotal: <span class="font-bold text-gray-800"
                                            id="subtotal-{{ $item->cart_id ?? 'buynow' }}">
                                            Rp {{ number_format($product->price * $item->quantity, 0, ',', '.') }}
                                        </span>
                                    </span>
                                </div>
                            </div>
                        </div>

                        <div class="delete-confirm mt-3 p-3 bg-red-50 rounded-lg items-center gap-3"
                             id="delete-confirm-{{ $item->cart_id ?? 'buynow' }}">
                            <i class="fas fa-exclamation-circle text-red-400 flex-shrink-0"></i>
                            <span class="text-xs text-red-700 flex-1">Hapus produk ini dari checkout?</span>
                            <button onclick="deleteItem('{{ $item->cart_id ?? 'buynow' }}')"
                                class="text-xs font-bold text-white bg-red-500 px-3 py-1 rounded-lg flex-shrink-0 hover:bg-red-600">
                                Ya
                            </button>
                            <button onclick="cancelDelete('{{ $item->cart_id ?? 'buynow' }}')"
                                class="text-xs font-bold text-gray-500 px-3 py-1 rounded-lg hover:bg-gray-100 flex-shrink-0">
                                Batal
                            </button>
                        </div>
                    </div>
                    @endforeach
                    </div>

                    {{-- Notes --}}
                    <div class="px-4 pb-4 pt-2 border-t border-gray-50">
                        <label class="flex items-center gap-2 text-xs font-semibold text-gray-500 mb-2">
                            <i class="fas fa-sticky-note text-amber-400"></i>
                            Catatan Pesanan <span class="font-normal text-gray-400">(opsional)</span>
                        </label>
                        <textarea id="order-notes" class="notes-input" rows="2" maxlength="255"
                            placeholder="Contoh: Tolong dibungkus rapi, ada hadiah..."></textarea>
                        <p class="text-right text-xs text-gray-300 mt-1">
                            <span id="notes-count">0</span>/255
                        </p>
                    </div>
                </div>

                {{-- ── CARD: KURIR & ONGKOS KIRIM ── --}}
                <div class="co-card" id="shipping-card">
                    <div class="co-card-header">
                        <i class="fas fa-truck text-gray-500 text-sm"></i>
                        <span class="font-bold text-gray-800 text-sm">Kurir & Ongkos Kirim</span>
                        <span id="shipping-zone-badge" class="ml-auto text-xs text-gray-400 hidden">
                            <i class="fas fa-map-marker-alt mr-1 text-red-400"></i>
                            <span id="shipping-zone-name"></span>
                        </span>
                    </div>

                    <div class="co-card-body space-y-3">

                        {{-- Loading state --}}
                        <div id="shipping-loading" class="{{ $selAddr ? '' : 'hidden' }} text-center py-6">
                            <div class="w-10 h-10 border-2 border-blue-200 border-t-blue-500 rounded-full animate-spin mx-auto mb-3"></div>
                            <p class="text-xs text-gray-400">Menghitung ongkos kirim...</p>
                        </div>

                        {{-- No address state --}}
                        <div id="shipping-no-address" class="{{ $selAddr ? 'hidden' : '' }} text-center py-6">
                            <i class="fas fa-map-marker-alt text-gray-200 text-3xl mb-2"></i>
                            <p class="text-xs text-gray-400">Pilih alamat pengiriman terlebih dahulu</p>
                        </div>

                        {{-- No zone --}}
                        <div id="shipping-no-zone" class="hidden p-3 bg-amber-50 rounded-lg border border-amber-200 text-xs text-amber-700 flex items-start gap-2">
                            <i class="fas fa-exclamation-triangle flex-shrink-0 mt-0.5"></i>
                            <span>Layanan pengiriman belum tersedia ke wilayah ini. Silakan pilih alamat lain.</span>
                        </div>

                        {{-- Courier options --}}
                        <div id="shipping-options" class="hidden space-y-3">

                            {{-- Free shipping banner --}}
                            <div id="free-shipping-banner" class="hidden p-3 bg-green-50 rounded-lg border border-green-200 flex items-center gap-2">
                                <i class="fas fa-gift text-green-500 flex-shrink-0"></i>
                                <p class="text-xs text-green-700 font-semibold flex-1">
                                    Selamat! Anda mendapat <strong>GRATIS ONGKIR</strong>
                                    <span id="free-saved-info" class="font-normal text-green-600"></span>
                                </p>
                            </div>

                            {{-- Progress menuju free shipping --}}
                            <div id="free-shipping-progress" class="hidden p-3 bg-amber-50 rounded-lg border border-amber-200">
                                <div class="flex justify-between items-center mb-1.5">
                                    <span class="text-xs text-amber-700 font-medium">
                                        <i class="fas fa-truck mr-1"></i>Gratis ongkir mulai
                                        <span id="free-min-display" class="font-bold"></span>
                                    </span>
                                    <span class="text-xs text-amber-600 font-bold" id="free-shortage-text"></span>
                                </div>
                                <div class="free-bar">
                                    <div id="free-progress-bar" class="free-bar-fill" style="width:0%"></div>
                                </div>
                            </div>

                            {{-- Daftar kurir --}}
                            <div id="courier-list" class="space-y-2"></div>

                            {{-- Berat info --}}
                            <div id="weight-info" class="hidden flex items-center gap-1.5 text-xs text-gray-400 pt-1">
                                <i class="fas fa-weight-hanging text-gray-300"></i>
                                <span>Total berat:
                                    <strong id="total-weight-display" class="text-gray-600"></strong>
                                </span>
                                <span class="ml-auto text-gray-300">
                                    (min. tagih 1 kg, pembulatan 1 kg)
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

            {{-- ════════════════ RIGHT COLUMN ════════════════ --}}
            <div class="lg:col-span-1">
                <div class="summary-sticky space-y-3">

                    {{-- CARD: Metode Pembayaran --}}
                    <div class="co-card">
                        <div class="co-card-header">
                            <i class="fas fa-credit-card text-gray-500 text-sm"></i>
                            <span class="font-bold text-gray-800 text-sm">Metode Pembayaran</span>
                        </div>
                        <div class="co-card-body space-y-2">
                            @php
                            $methods = [
                                ['value'=>'cash',     'label'=>'COD (Bayar di Tempat)', 'icon'=>'fa-money-bill-wave','color'=>'text-green-600',  'bg'=>'bg-green-50'],
                                ['value'=>'transfer', 'label'=>'Transfer Bank (VA)',     'icon'=>'fa-university',     'color'=>'text-blue-600',   'bg'=>'bg-blue-50'],
                                ['value'=>'ewallet',  'label'=>'E-Wallet',              'icon'=>'fa-wallet',         'color'=>'text-purple-600', 'bg'=>'bg-purple-50'],
                                ['value'=>'qris',     'label'=>'QRIS',                  'icon'=>'fa-qrcode',         'color'=>'text-orange-600', 'bg'=>'bg-orange-50'],
                                ['value'=>'card',     'label'=>'Kartu Kredit/Debit',    'icon'=>'fa-credit-card',    'color'=>'text-indigo-600', 'bg'=>'bg-indigo-50'],
                            ];
                            @endphp
                            @foreach($methods as $m)
                            <div class="pay-opt" data-value="{{ $m['value'] }}"
                                 onclick="selectPayment('{{ $m['value'] }}', this)">
                                <div class="w-8 h-8 rounded-lg {{ $m['bg'] }} flex items-center justify-center flex-shrink-0">
                                    <i class="fas {{ $m['icon'] }} {{ $m['color'] }} text-sm"></i>
                                </div>
                                <span class="text-sm font-medium text-gray-700 flex-1">{{ $m['label'] }}</span>
                                <div class="pay-radio" id="pay-radio-{{ $m['value'] }}"></div>
                            </div>
                            @endforeach
                        </div>
                    </div>

                    {{-- CARD: Ringkasan --}}
                    <div class="co-card">
                        <div class="co-card-header">
                            <i class="fas fa-receipt text-gray-500 text-sm"></i>
                            <span class="font-bold text-gray-800 text-sm">Ringkasan Pembayaran</span>
                        </div>
                        <div class="co-card-body space-y-3">
                            {{-- Subtotal produk --}}
                            <div class="flex justify-between text-sm text-gray-600">
                                <span>Total Produk (<span id="summary-count">{{ $cartItems->sum('quantity') }}</span> item)</span>
                                <span class="font-semibold text-gray-800" id="summary-subtotal">
                                    Rp {{ number_format($cartItems->sum(fn($c) => $c->product->price * $c->quantity), 0, ',', '.') }}
                                </span>
                            </div>

                            {{-- Ongkir --}}
                            <div class="flex justify-between text-sm text-gray-600">
                                <span class="flex items-center gap-1">
                                    <i class="fas fa-truck text-gray-400 text-xs"></i>
                                    Ongkos Kirim
                                    <span id="selected-courier-badge"
                                          class="hidden ml-1 text-[10px] font-semibold text-blue-600 bg-blue-50 px-1.5 py-0.5 rounded-full border border-blue-200">
                                    </span>
                                </span>
                                <span id="summary-shipping-cost"
                                      class="text-xs font-bold text-gray-400 italic">
                                    Pilih kurir
                                </span>
                            </div>

                            {{-- ETD --}}
                            <div id="summary-etd-row" class="hidden flex justify-between text-xs text-gray-500">
                                <span class="flex items-center gap-1">
                                    <i class="fas fa-calendar-check text-gray-300" style="font-size:10px"></i>
                                    Estimasi tiba
                                </span>
                                <span id="summary-etd" class="font-medium text-gray-600 text-right"></span>
                            </div>

                            {{-- Total --}}
                            <div class="border-t border-gray-100 pt-3 flex justify-between items-center">
                                <span class="font-bold text-gray-900">Total Bayar</span>
                                <span class="text-xl font-extrabold text-red-500" id="summary-total">
                                    Rp {{ number_format($cartItems->sum(fn($c) => $c->product->price * $c->quantity), 0, ',', '.') }}
                                </span>
                            </div>

                            <button id="btn-pesan" onclick="buatPesanan()"
                                @if($addresses->isEmpty()) disabled @endif
                                class="btn-primary w-full mt-1 py-3.5 rounded-xl font-bold text-[15px] shadow-md hover:shadow-lg transition-all border-0">
                                <span id="btn-text"><i class="fas fa-shopping-bag mr-2"></i>Buat Pesanan</span>
                                <span id="btn-loading" class="hidden"><i class="fas fa-spinner fa-spin mr-2"></i>Memproses...</span>
                            </button>

                            <p class="text-center text-xs text-gray-400">
                                <i class="fas fa-lock mr-1"></i>Transaksi aman & terenkripsi
                            </p>
                        </div>
                    </div>

                </div>
            </div>

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

{{-- ════════════════ MODAL PILIH ALAMAT ════════════════ --}}
<div class="modal-overlay" id="address-modal" onclick="closeAddressModalOutside(event)">
    <div class="modal-box">
        <div class="flex items-center justify-between px-5 pt-5 pb-4 border-b border-gray-100">
            <h3 class="font-bold text-gray-900">Pilih Alamat Pengiriman</h3>
            <button onclick="closeAddressModal()"
                class="w-8 h-8 rounded-full hover:bg-gray-100 flex items-center justify-center">
                <i class="fas fa-times text-gray-500 text-sm"></i>
            </button>
        </div>

        <div class="divide-y divide-gray-100">
            @foreach($addresses as $addr)
            <div class="addr-row px-5 py-4 flex items-start gap-3 {{ ($selAddr && $selAddr->id == $addr->id) ? 'active' : '' }}"
                 id="modal-addr-{{ $addr->id }}"
                 onclick="selectAddress({{ $addr->id }}, this)"
                 data-full="{{ $addr->full_address }}"
                 data-phone="{{ $addr->phone }}"
                 data-name="{{ $addr->recipient_name }}"
                 data-province-code="{{ $addr->province_code }}">

                <div class="addr-radio {{ ($selAddr && $selAddr->id == $addr->id) ? 'checked' : '' }} mt-0.5"
                     id="modal-radio-{{ $addr->id }}"></div>

                <div class="flex-1 min-w-0">
                    <div class="flex items-center gap-2 flex-wrap">
                        <span class="font-bold text-gray-900 text-sm">{{ $addr->recipient_name }}</span>
                        <span class="text-gray-400 text-xs">{{ $addr->phone }}</span>
                    </div>
                    <p class="text-sm text-gray-600 mt-1 leading-relaxed">{{ $addr->full_address }}</p>
                </div>

                <a href="{{ route('address.edit', ['address' => $addr->id, 'redirect_to' => 'cart.checkout.get']) }}"
                   class="flex-shrink-0 text-xs text-blue-500 hover:text-blue-700 hover:underline"
                   onclick="event.stopPropagation()">Edit</a>
            </div>
            @endforeach
        </div>

        <div class="px-5 py-4 border-t border-gray-100">
            <a href="{{ route('address.create', ['redirect_to' => 'cart.checkout.get']) }}"
               class="flex items-center justify-center gap-2 w-full py-3 border-2 border-dashed border-gray-300
                      rounded-xl text-sm font-semibold text-gray-500 hover:border-red-400 hover:text-red-500 transition">
                <i class="fas fa-plus"></i> Tambah Alamat Baru
            </a>
        </div>
    </div>
</div>

{{-- ════════════════ MIDTRANS OVERLAY ════════════════ --}}
<div id="snap-overlay" style="position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:99999;
     display:none;align-items:center;justify-content:center;">
    <div class="bg-white rounded-2xl p-8 text-center shadow-2xl">
        <div class="w-14 h-14 rounded-full bg-red-50 flex items-center justify-center mx-auto mb-4">
            <i class="fas fa-spinner fa-spin text-2xl text-red-500"></i>
        </div>
        <p class="font-bold text-gray-800">Menyiapkan Pembayaran</p>
        <p class="text-sm text-gray-400 mt-1">Mohon tunggu...</p>
    </div>
</div>

{{-- ════════════════ HIDDEN FORM ════════════════ --}}
<form id="checkout-form" action="{{ route('order.checkout') }}" method="POST" class="hidden">
    @csrf
    <input type="hidden" name="selected_items"      id="form-selected-items" value="{{ json_encode($selectedIds) }}">
    <input type="hidden" name="selected_address_id" id="form-address-id"     value="{{ $selAddr->id ?? '' }}">
    <input type="hidden" name="payment_method"      id="form-payment-method" value="">
    <input type="hidden" name="order_note"          id="form-order-note"     value="">
    <input type="hidden" name="quantities"          id="form-quantities"     value="{}">
    <input type="hidden" name="removed_items"       id="form-removed-items"  value="[]">
    <input type="hidden" name="is_buy_now"          id="form-is-buy-now"     value="{{ isset($isBuyNow) && $isBuyNow ? '1' : '0' }}">
    {{-- Shipping fields --}}
    <input type="hidden" name="courier_code"        id="form-courier-code"   value="">
    <input type="hidden" name="shipping_cost"       id="form-shipping-cost"  value="0">
    <input type="hidden" name="shipping_zone"       id="form-shipping-zone"  value="">
</form>

{{-- Midtrans --}}
<script src="{{ config('services.midtrans.is_production')
    ? 'https://app.midtrans.com/snap/snap.js'
    : 'https://app.sandbox.midtrans.com/snap/snap.js' }}"
    data-client-key="{{ config('services.midtrans.client_key') }}"></script>

<script>
// ─────────────────────────────────────────────────
// STATE
// ─────────────────────────────────────────────────
let selectedAddressId    = {{ $selAddr->id ?? 'null' }};
let selectedProvinceCode = '{{ $selAddr->province_code ?? '' }}';
let selectedPaymentMethod = null;
let selectedCourierCode   = null;
let selectedShippingCost  = 0;
let shippingOptions       = [];
let quantities            = {};
let removedItems          = [];

@foreach($cartItems as $item)
quantities['{{ $item->cart_id ?? "buynow" }}'] = {{ $item->quantity }};
@endforeach

// ─────────────────────────────────────────────────
// NOTES
// ─────────────────────────────────────────────────
document.getElementById('order-notes').addEventListener('input', function() {
    document.getElementById('notes-count').textContent = this.value.length;
});

// ─────────────────────────────────────────────────
// ADDRESS MODAL
// ─────────────────────────────────────────────────
function openAddressModal() {
    document.getElementById('address-modal').classList.add('open');
    document.body.style.overflow = 'hidden';
}
function closeAddressModal() {
    document.getElementById('address-modal').classList.remove('open');
    document.body.style.overflow = '';
}
function closeAddressModalOutside(e) {
    if (e.target === document.getElementById('address-modal')) closeAddressModal();
}

function selectAddress(id, el) {
    selectedAddressId    = id;
    selectedProvinceCode = el.dataset.provinceCode || '';
    document.getElementById('form-address-id').value = id;

    document.querySelectorAll('.addr-row').forEach(r => r.classList.remove('active'));
    document.querySelectorAll('[id^="modal-radio-"]').forEach(r => r.classList.remove('checked'));
    el.classList.add('active');
    const radio = document.getElementById('modal-radio-' + id);
    if (radio) radio.classList.add('checked');

    document.getElementById('display-phone').textContent      = el.dataset.phone;
    document.getElementById('display-name-badge').textContent = el.dataset.name;
    document.getElementById('display-address').textContent    = el.dataset.full;

    setTimeout(closeAddressModal, 200);

    // Reset kurir & reload ongkir
    selectedCourierCode  = null;
    selectedShippingCost = 0;
    document.getElementById('form-courier-code').value  = '';
    document.getElementById('form-shipping-cost').value = '0';
    resetCourierUI();

    if (selectedProvinceCode) {
        loadShippingOptions(selectedProvinceCode);
    }
}

// ─────────────────────────────────────────────────
// PAYMENT METHOD
// ─────────────────────────────────────────────────
function selectPayment(value, el) {
    selectedPaymentMethod = value;
    document.getElementById('form-payment-method').value = value;
    document.querySelectorAll('.pay-opt').forEach(o => o.classList.remove('selected'));
    document.querySelectorAll('.pay-radio').forEach(r => r.classList.remove('checked'));
    el.classList.add('selected');
    const radio = document.getElementById('pay-radio-' + value);
    if (radio) radio.classList.add('checked');
}

// ─────────────────────────────────────────────────
// QTY
// ─────────────────────────────────────────────────
function changeQty(cartId, delta) {
    const current = quantities[cartId] || 1;
    const stockEl = document.getElementById('stock-' + cartId);
    const stock   = parseInt(stockEl ? stockEl.textContent : 999);
    const newQty  = Math.min(Math.max(1, current + delta), stock);
    quantities[cartId] = newQty;

    document.getElementById('qty-' + cartId).textContent = newQty;
    const row    = document.getElementById('item-row-' + cartId);
    const minBtn = row.querySelector('.qty-btn:first-child');
    const maxBtn = row.querySelectorAll('.qty-btn')[1];
    if (minBtn) minBtn.disabled = (newQty <= 1);
    if (maxBtn) maxBtn.disabled = (newQty >= stock);

    const price = parseFloat(row.dataset.price);
    const subEl = document.getElementById('subtotal-' + cartId);
    if (subEl) subEl.textContent = 'Rp ' + formatNum(price * newQty);

    document.getElementById('form-quantities').value = JSON.stringify(quantities);
    recalcTotal();

    // Re-load ongkir karena berat & subtotal berubah
    if (selectedProvinceCode) {
        clearTimeout(window._shippingReloadTimer);
        window._shippingReloadTimer = setTimeout(() => loadShippingOptions(selectedProvinceCode), 400);
    }
}

// ─────────────────────────────────────────────────
// DELETE ITEM
// ─────────────────────────────────────────────────
function confirmDelete(cartId) {
    const el = document.getElementById('delete-confirm-' + cartId);
    if (el) el.classList.add('show');
}
function cancelDelete(cartId) {
    const el = document.getElementById('delete-confirm-' + cartId);
    if (el) el.classList.remove('show');
}
async function deleteItem(cartId) {
    if (cartId === 'buynow') {
        showNotif('Checkout dibatalkan...', 'info');
        setTimeout(() => { window.location.href = "{{ route('product.index') }}"; }, 1000);
        return;
    }

    const row = document.getElementById('item-row-' + cartId);
    if (!row) return;

    try {
        // Hapus dari DATABASE via AJAX - Gunakan route Laravel agar alamatnya dinamis & akurat
        const deleteUrl = "{{ route('cart.destroy', ':id') }}".replace(':id', cartId);
        
        const response = await fetch(deleteUrl, {
            method: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept':       'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        });

        if (!response.ok) {
            if (response.status === 404) {
                showNotif('Gagal: Produk sudah tidak ada.', 'error');
            } else {
                showNotif('Ups! Gagal menghapus produk.', 'error');
            }
            return;
        }

        const data = await response.json();
        showNotif(data.message || 'Produk dihapus', 'success');

        // Hapus dari TAMPILAN
        row.style.transition = 'all .2s';
        row.style.opacity    = '0';
        row.style.height     = row.offsetHeight + 'px';
        
        setTimeout(() => {
            row.style.height   = '0';
            row.style.padding  = '0';
            row.style.overflow = 'hidden';
            setTimeout(() => {
                row.remove();
                delete quantities[cartId];
                
                // Update daftar item yang dibuang (untuk backup order)
                removedItems.push(parseInt(cartId));
                document.getElementById('form-removed-items').value = JSON.stringify(removedItems);
                document.getElementById('form-quantities').value    = JSON.stringify(quantities);
                
                recalcTotal();

                // Jika kosong, balik ke keranjang
                if (Object.keys(quantities).length === 0) {
                    showNotif('Kosong. Balik ke keranjang...', 'warning');
                    setTimeout(() => { window.location.href = '{{ route("cart.index") }}'; }, 1000);
                }

                // Update ongkir jika perlu
                if (selectedProvinceCode) {
                    clearTimeout(window._shippingReloadTimer);
                    window._shippingReloadTimer = setTimeout(() => loadShippingOptions(selectedProvinceCode), 400);
                }
            }, 200);
        }, 200);

    } catch (error) {
        console.error('Error delete:', error);
        showNotif('Terjadi kesalahan koneksi.', 'error');
    }
}

// ─────────────────────────────────────────────────
// RECALC TOTAL
// ─────────────────────────────────────────────────
function recalcTotal() {
    let productTotal = 0, totalQty = 0;
    Object.keys(quantities).forEach(cartId => {
        const row = document.getElementById('item-row-' + cartId);
        if (!row) return;
        const price = parseFloat(row.dataset.price);
        const qty   = quantities[cartId];
        productTotal += price * qty;
        totalQty     += qty;
    });
    const grandTotal = productTotal + selectedShippingCost;
    document.getElementById('summary-subtotal').textContent = 'Rp ' + formatNum(productTotal);
    document.getElementById('summary-total').textContent    = 'Rp ' + formatNum(grandTotal);
    document.getElementById('summary-count').textContent    = totalQty;
}

// ─────────────────────────────────────────────────
// SHIPPING CALCULATOR
// ─────────────────────────────────────────────────
async function loadShippingOptions(provinceCode) {
    if (!provinceCode) return;

    document.getElementById('shipping-loading').classList.remove('hidden');
    document.getElementById('shipping-options').classList.add('hidden');
    document.getElementById('shipping-no-address').classList.add('hidden');
    document.getElementById('shipping-no-zone').classList.add('hidden');

    // Hitung subtotal & berat
    let subtotal = 0, totalWeight = 0;
    Object.keys(quantities).forEach(cartId => {
        const row = document.getElementById('item-row-' + cartId);
        if (!row) return;
        const price  = parseFloat(row.dataset.price);
        const weight = parseInt(row.dataset.weight || '1000');
        const qty    = quantities[cartId];
        subtotal     += price * qty;
        totalWeight  += weight * qty;
    });

    try {
        const res = await fetch('{{ route("shipping.calculate") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept':       'application/json',
            },
            body: JSON.stringify({
                province_code:      provinceCode,
                total_weight_gram:  Math.max(totalWeight, 1),
                subtotal:           Math.round(subtotal),
                courier_code:       selectedCourierCode,
            }),
        });

        const json = await res.json();
        document.getElementById('shipping-loading').classList.add('hidden');

        if (!json.success || !json.data) {
            renderShippingError('Gagal memuat layanan pengiriman. Silakan coba lagi.');
            return;
        }

        const data  = json.data;
        shippingOptions = data.options || [];

        if (!data.zone || shippingOptions.length === 0) {
            document.getElementById('shipping-no-zone').classList.remove('hidden');
            return;
        }

        // Badge zona
        document.getElementById('shipping-zone-name').textContent = data.zone.name;
        document.getElementById('shipping-zone-badge').classList.remove('hidden');
        document.getElementById('form-shipping-zone').value = data.zone.code;

        // Berat
        const wKg = (Math.max(totalWeight, 1) / 1000).toFixed(2);
        document.getElementById('total-weight-display').textContent = wKg + ' kg';
        document.getElementById('weight-info').classList.remove('hidden');

        // Free shipping
        renderFreeShippingInfo(data.free_shipping, subtotal);

        // Kurir
        renderCourierOptions(shippingOptions);

        document.getElementById('shipping-options').classList.remove('hidden');

        // Pulihkan kurir yang sudah dipilih
        if (selectedCourierCode) {
            const still = shippingOptions.find(o => o.code === selectedCourierCode);
            if (still) selectCourier(still.code, still.final_price, still.base_price, still);
            else {
                selectedCourierCode  = null;
                selectedShippingCost = 0;
                document.getElementById('form-courier-code').value  = '';
                document.getElementById('form-shipping-cost').value = '0';
                recalcTotal();
            }
        }

    } catch (err) {
        console.error('Shipping error:', err);
        document.getElementById('shipping-loading').classList.add('hidden');
        renderShippingError('Koneksi bermasalah. Coba lagi.');
    }
}

function renderFreeShippingInfo(freeData, subtotal) {
    const banner   = document.getElementById('free-shipping-banner');
    const progress = document.getElementById('free-shipping-progress');
    if (!freeData.enabled) { banner.classList.add('hidden'); progress.classList.add('hidden'); return; }
    const minimum = freeData.minimum;
    if (freeData.qualifies) {
        banner.classList.remove('hidden');
        progress.classList.add('hidden');
        const saved = freeData.saved;
        document.getElementById('free-saved-info').textContent =
            saved > 0 ? ' (hemat Rp ' + formatNum(saved) + ')' : '';
    } else {
        banner.classList.add('hidden');
        progress.classList.remove('hidden');
        const shortage = minimum - subtotal;
        const pct      = Math.min(100, Math.round((subtotal / minimum) * 100));
        document.getElementById('free-min-display').textContent    = 'Rp ' + formatNum(minimum);
        document.getElementById('free-shortage-text').textContent  = 'Tambah Rp ' + formatNum(shortage) + ' lagi';
        document.getElementById('free-progress-bar').style.width   = pct + '%';
    }
}

function renderCourierOptions(options) {
    const container = document.getElementById('courier-list');
    container.innerHTML = '';
    if (!options.length) {
        container.innerHTML = '<p class="text-xs text-center text-gray-400 py-3">Tidak ada layanan tersedia</p>';
        return;
    }
    options.forEach(opt => {
        const isSelected = opt.code === selectedCourierCode;
        const el = document.createElement('div');
        el.className = 'courier-opt' + (isSelected ? ' selected' : '');
        el.id = 'courier-opt-' + opt.code;
        el.onclick = () => selectCourier(opt.code, opt.final_price, opt.base_price, opt);
        el.innerHTML = `
            <div class="w-9 h-9 rounded-lg bg-blue-50 flex items-center justify-center flex-shrink-0 border border-blue-100">
                <i class="fas fa-truck text-blue-500 text-sm"></i>
            </div>
            <div class="flex-1 min-w-0">
                <p class="text-sm font-semibold text-gray-800">${escHtml(opt.short_name)}</p>
                <p class="text-xs text-gray-400 mt-0.5 flex items-center gap-1">
                    <i class="fas fa-clock" style="font-size:9px"></i>${escHtml(opt.etd)}
                </p>
            </div>
            <div class="text-right flex-shrink-0">
                <p class="text-sm font-bold ${opt.is_free ? 'text-green-600' : 'text-gray-800'}">${escHtml(opt.price_display)}</p>
                ${opt.is_free && opt.base_price > 0 ? `<p class="text-xs text-gray-400 line-through">Rp ${formatNum(opt.base_price)}</p>` : ''}
            </div>
            <div class="courier-radio${isSelected ? ' checked' : ''}" id="c-radio-${opt.code}"></div>
        `;
        container.appendChild(el);
    });
}

function selectCourier(code, finalPrice, basePrice, opt) {
    selectedCourierCode  = code;
    selectedShippingCost = finalPrice;
    document.getElementById('form-courier-code').value  = code;
    document.getElementById('form-shipping-cost').value = finalPrice;

    // Update kurir UI
    document.querySelectorAll('[id^="courier-opt-"]').forEach(el => el.classList.remove('selected'));
    document.querySelectorAll('[id^="c-radio-"]').forEach(el => el.classList.remove('checked'));
    const optEl   = document.getElementById('courier-opt-' + code);
    const radioEl = document.getElementById('c-radio-' + code);
    if (optEl)   optEl.classList.add('selected');
    if (radioEl) radioEl.classList.add('checked');

    // Update summary
    const badge   = document.getElementById('selected-courier-badge');
    const costEl  = document.getElementById('summary-shipping-cost');
    const etdRow  = document.getElementById('summary-etd-row');
    const etdEl   = document.getElementById('summary-etd');

    if (opt) {
        if (badge)  { badge.textContent = opt.short_name; badge.classList.remove('hidden'); }
        if (costEl) {
            if (opt.is_free) {
                costEl.textContent = 'GRATIS';
                costEl.className   = 'text-xs font-bold text-green-600 bg-green-50 px-2 py-0.5 rounded-full border border-green-200';
            } else {
                costEl.textContent = 'Rp ' + formatNum(finalPrice);
                costEl.className   = 'text-sm font-semibold text-gray-800';
            }
        }
        if (etdEl)  etdEl.textContent  = opt.etd;
        if (etdRow) etdRow.classList.remove('hidden');
    }

    recalcTotal();
}

function resetCourierUI() {
    document.getElementById('shipping-options').classList.add('hidden');
    document.getElementById('shipping-no-zone').classList.add('hidden');
    document.getElementById('free-shipping-banner').classList.add('hidden');
    document.getElementById('free-shipping-progress').classList.add('hidden');
    document.getElementById('shipping-zone-badge').classList.add('hidden');
    document.getElementById('weight-info').classList.add('hidden');
    document.getElementById('courier-list').innerHTML = '';

    const badge  = document.getElementById('selected-courier-badge');
    const costEl = document.getElementById('summary-shipping-cost');
    const etdRow = document.getElementById('summary-etd-row');
    if (badge)  badge.classList.add('hidden');
    if (costEl) { costEl.textContent = 'Pilih kurir'; costEl.className = 'text-xs font-bold text-gray-400 italic'; }
    if (etdRow) etdRow.classList.add('hidden');
    recalcTotal();
}

function renderShippingError(msg) {
    document.getElementById('courier-list').innerHTML = `
        <div class="p-3 bg-red-50 rounded-lg border border-red-200 text-xs text-red-600 flex items-center gap-2">
            <i class="fas fa-exclamation-circle flex-shrink-0"></i><span>${escHtml(msg)}</span>
        </div>`;
    document.getElementById('shipping-options').classList.remove('hidden');
}

function escHtml(str) {
    const d = document.createElement('div');
    d.textContent = String(str);
    return d.innerHTML;
}

// ─────────────────────────────────────────────────
// FORMAT HELPERS
// ─────────────────────────────────────────────────
function formatNum(n) {
    return Math.round(n).toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
}

// ─────────────────────────────────────────────────
// BUAT PESANAN
// ─────────────────────────────────────────────────
async function buatPesanan() {
    if (!selectedAddressId) {
        showNotif('Pilih alamat pengiriman terlebih dahulu', 'warning'); return;
    }
    if (!selectedCourierCode) {
        showNotif('Pilih layanan kurir terlebih dahulu', 'warning');
        document.getElementById('shipping-card').scrollIntoView({ behavior: 'smooth' });
        return;
    }
    if (!selectedPaymentMethod) {
        showNotif('Pilih metode pembayaran terlebih dahulu', 'warning'); return;
    }
    if (Object.keys(quantities).length === 0) {
        showNotif('Tidak ada produk untuk dipesan', 'warning'); return;
    }

    document.getElementById('form-address-id').value     = selectedAddressId;
    document.getElementById('form-payment-method').value = selectedPaymentMethod;
    document.getElementById('form-order-note').value     = document.getElementById('order-notes').value.trim();
    document.getElementById('form-quantities').value     = JSON.stringify(quantities);
    document.getElementById('form-removed-items').value  = JSON.stringify(removedItems);
    document.getElementById('form-courier-code').value   = selectedCourierCode;
    document.getElementById('form-shipping-cost').value  = selectedShippingCost;

    const activeCartIds = Object.keys(quantities).filter(k => k !== 'buynow').map(Number);
    document.getElementById('form-selected-items').value = JSON.stringify(activeCartIds);

    const btn = document.getElementById('btn-pesan');
    btn.disabled = true;
    document.getElementById('btn-text').classList.add('hidden');
    document.getElementById('btn-loading').classList.remove('hidden');

    if (selectedPaymentMethod === 'cash') {
        document.getElementById('checkout-form').submit();
        return;
    }

    try {
        const formData = new FormData(document.getElementById('checkout-form'));
        const response = await fetch('{{ route("order.checkout") }}', {
            method:  'POST',
            headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' },
            body:    formData,
        });

        if (!response.ok) {
            const errData = await response.json().catch(() => ({}));
            showNotif(errData.message || 'Gagal membuat pesanan.', 'error');
            resetBtn(); return;
        }

        const data = await response.json();
        if (!data.success) {
            showNotif(data.message || 'Gagal membuat pesanan.', 'error');
            resetBtn(); return;
        }

        if (data.snap_token) {
            if (typeof snap === 'undefined') {
                showNotif('Mengarahkan ke halaman pembayaran...', 'info');
                setTimeout(() => { window.location.href = data.payment_url || data.payment_show_url; }, 1200);
                return;
            }
            document.getElementById('snap-overlay').style.display = 'flex';
            snap.pay(data.snap_token, {
                onSuccess: function() {
                    document.getElementById('snap-overlay').style.display = 'none';
                    showNotif('Pembayaran berhasil! Mengkonfirmasi...', 'success');
                    pollPaymentStatus(data.payment_show_url, data.order_show_url);
                },
                onPending: function() {
                    document.getElementById('snap-overlay').style.display = 'none';
                    window.location.href = data.payment_show_url;
                },
                onError: function() {
                    document.getElementById('snap-overlay').style.display = 'none';
                    showNotif('Pembayaran gagal. Pesanan tetap tersimpan.', 'error');
                    setTimeout(() => { window.location.href = data.order_show_url; }, 2000);
                },
                onClose: function() {
                    document.getElementById('snap-overlay').style.display = 'none';
                    window.location.href = data.order_show_url;
                }
            });
        } else if (data.redirect_url) {
            window.location.href = data.redirect_url;
        } else {
            window.location.href = data.order_show_url;
        }
    } catch(err) {
        console.error('Checkout error:', err);
        showNotif('Terjadi kesalahan koneksi.', 'error');
        resetBtn();
        setTimeout(() => { window.location.href = '{{ route("order.index") }}'; }, 2500);
    }
}

function resetBtn() {
    document.getElementById('btn-pesan').disabled = false;
    document.getElementById('btn-text').classList.remove('hidden');
    document.getElementById('btn-loading').classList.add('hidden');
}

// ─────────────────────────────────────────────────
// POLLING STATUS PEMBAYARAN
// ─────────────────────────────────────────────────
async function pollPaymentStatus(paymentShowUrl, orderShowUrl, maxTry = 5) {
    for (let i = 0; i < maxTry; i++) {
        try {
            const paymentId = paymentShowUrl.split('/payment/')[1]?.split('?')[0];
            if (!paymentId) break;
            const res  = await fetch('/payment/' + paymentId + '/check-status', {
                method:  'POST',
                headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' }
            });
            const data = await res.json();
            if (data.success && data.status === 'paid') {
                window.location.href = orderShowUrl + '?payment=success'; return;
            }
            if (data.status === 'failed') {
                window.location.href = orderShowUrl + '?payment=failed'; return;
            }
            await new Promise(r => setTimeout(r, 2000));
        } catch(e) {
            await new Promise(r => setTimeout(r, 2000));
        }
    }
    window.location.href = paymentShowUrl;
}

// ─────────────────────────────────────────────────
// NOTIFIKASI
// ─────────────────────────────────────────────────
function showNotif(msg, type = 'info') {
    const colors = { success:'bg-green-500', error:'bg-red-500', warning:'bg-amber-500', info:'bg-blue-500' };
    const icons  = { success:'fa-check-circle', error:'fa-times-circle', warning:'fa-exclamation-triangle', info:'fa-info-circle' };
    const n = document.createElement('div');
    n.className = `fixed top-4 right-4 z-[99999] px-5 py-3 rounded-xl shadow-xl flex items-center gap-3
                   ${colors[type]} text-white text-sm font-semibold max-w-xs`;
    n.innerHTML = `<i class="fas ${icons[type]} flex-shrink-0"></i><span>${msg}</span>`;
    document.body.appendChild(n);
    setTimeout(() => { n.style.opacity='0'; n.style.transition='opacity .3s'; setTimeout(() => n.remove(), 300); }, 3500);
}

// ─────────────────────────────────────────────────
// INIT
// ─────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
    @if($selAddr && $selAddr->province_code)
    loadShippingOptions('{{ $selAddr->province_code }}');
    @endif
});
</script>
</x-app-layout>