<x-app-layout>
    {{-- Scripts --}}
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script type="text/javascript" src="{{ config('midtrans.snap_url') }}" data-client-key="{{ config('midtrans.client_key') }}"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />

    <div class="bg-[#FAF7F2] min-h-screen py-8 sm:py-12">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            
            {{-- Header --}}
            <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-8 sm:mb-10">
                <div>
                    <div class="flex items-center gap-2 text-sm text-[#8c6a4a] mb-1">
                        <i class="fas fa-receipt"></i>
                        <span>Konfirmasi Pesanan</span>
                    </div>
                    <h1 class="text-2xl sm:text-3xl font-extrabold text-[#2c1a0e] tracking-tight">Konfirmasi Pesanan</h1>
                    <p class="text-sm text-[#8c6a4a] mt-1">Selesaikan pembayaran untuk memproses pesanan Anda.</p>
                </div>
                <a href="{{ route('cart.index') }}" class="inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-white border border-[#e0d3c2] text-[#8c6a4a] hover:border-[#f59e0b] hover:text-[#f59e0b] transition-all text-sm font-bold">
                    <i class="fas fa-arrow-left text-xs"></i> Kembali ke Keranjang
                </a>
            </div>

            <div class="flex flex-col lg:flex-row gap-6 lg:gap-10">
                
                {{-- KIRI: DAFTAR ITEM & ALAMAT --}}
                <div class="flex-1 space-y-6">
                    
                    {{-- Section Alamat --}}
                    <div class="bg-white p-6 sm:p-8 rounded-2xl shadow-sm border border-[#e0d3c2]">
                        <div class="flex items-center gap-3 mb-6">
                            <div class="w-10 h-10 bg-[#fef3c7] rounded-xl flex items-center justify-center text-[#d97706]">
                                <i class="fas fa-map-marker-alt"></i>
                            </div>
                            <h2 class="text-lg font-bold text-[#2c1a0e]">Alamat Pengiriman</h2>
                        </div>

                        <select id="address-selector" class="w-full border-[#e0d3c2] rounded-xl focus:ring-2 focus:ring-[#f59e0b]/50 focus:border-[#f59e0b] p-4 text-[#2c1a0e] font-medium bg-[#fef9f0] transition-all">
                            <option value="">-- Pilih Alamat --</option>
                            @foreach($addresses as $address)
                                <option value="{{ $address->id }}" 
                                    data-city="{{ $address->city_rel->name ?? $address->city }}" 
                                    data-name="{{ $address->recipient_name }}"
                                    data-phone="{{ $address->phone }}"
                                    data-complete="{{ $address->address }}, {{ $address->city_rel->name ?? '' }}"
                                    {{ $address->is_default ? 'selected' : '' }}>
                                    [{{ $address->label }}] {{ $address->recipient_name }} - {{ $address->city_rel->name ?? $address->city }}
                                </option>
                            @endforeach
                        </select>

                        {{-- Ganti bagian link edit di dalam Section Alamat --}}
                        <div id="address-detail-box" class="mt-4 p-5 bg-[#fef9f0] rounded-xl border border-dashed border-[#e0d3c2] hidden">
                            <p class="font-bold text-[#2c1a0e]" id="detail-name"></p>
                            <p class="text-sm text-[#8c6a4a] mt-1" id="detail-phone"></p>
                            <p class="text-sm text-[#2c1a0e]/80 mt-2 italic" id="detail-complete"></p>
                            
                            {{-- Link Edit yang Dinamis --}}
                            <a id="edit-address-link" href="#" class="text-xs font-bold text-blue-600 mt-3 inline-block hover:underline">
                                <i class="fas fa-edit mr-1"></i> Ubah detail alamat ini
                            </a>
                        </div>
                        <a href="{{ route('addresses.create', ['redirect' => 'checkout']) }}" class="text-xs font-bold text-[#d97706] mt-3 inline-block hover:text-[#f59e0b] transition">+ Tambah/Atur Alamat</a>
                    </div>

                    {{-- Section Produk --}}
                    <div class="bg-white rounded-2xl shadow-sm border border-[#e0d3c2] overflow-hidden">
                        <div class="p-6 sm:p-8 border-b border-[#f0e7dc]">
                            <h2 class="text-lg font-bold text-[#2c1a0e]">Rincian Produk</h2>
                        </div>
                        <div class="divide-y divide-[#f0e7dc]">
                            @foreach($cartItems as $item)
                                <div class="p-5 sm:p-6 flex flex-col sm:flex-row items-center gap-4 sm:gap-6">
                                    <div class="w-20 h-20 bg-[#fef9f0] rounded-xl border border-[#e0d3c2] overflow-hidden flex-shrink-0">
                                        @php 
                                            $variantImage = $item->variant->images->first() ?? null;
                                            $productImage = $item->product->images->first() ?? null;
                                            $displayPath = $variantImage ? $variantImage->image : ($productImage ? $productImage->image : null);
                                        @endphp
                                        <img src="{{ asset('storage/' . str_replace('public/', '', $displayPath)) }}" 
                                             class="w-full h-full object-cover"
                                             onerror="this.src='https://placehold.co/200x200?text=No+Photo'">
                                    </div>
                                    <div class="flex-1 text-center sm:text-left">
                                        <h3 class="font-bold text-[#2c1a0e]">{{ $item->product->name }}</h3>
                                        <p class="text-xs font-bold text-[#d97706] uppercase tracking-wider mt-1">
                                            Varian: {{ $item->variant->color ?? 'Standar' }}
                                        </p>
                                        <p class="text-sm text-[#8c6a4a] mt-1">{{ $item->quantity }} x Rp {{ number_format($item->price_at_add, 0, ',', '.') }}</p>
                                    </div>
                                    <div class="text-right">
                                        <p class="font-black text-[#2c1a0e]">Rp {{ number_format($item->quantity * $item->price_at_add, 0, ',', '.') }}</p>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    </div>

                    {{-- Section Catatan --}}
                    <div class="bg-white p-6 sm:p-8 rounded-2xl shadow-sm border border-[#e0d3c2]">
                        <div class="flex items-center gap-3 mb-4">
                            <div class="w-10 h-10 bg-[#fef3c7] rounded-xl flex items-center justify-center text-[#d97706]">
                                <i class="fas fa-sticky-note"></i>
                            </div>
                            <h2 class="text-lg font-bold text-[#2c1a0e]">Catatan untuk Penjual</h2>
                        </div>
                        <textarea 
                            name="notes" 
                            id="order-notes" 
                            rows="3" 
                            class="w-full border-[#e0d3c2] rounded-xl focus:ring-2 focus:ring-[#f59e0b]/50 focus:border-[#f59e0b] p-4 text-[#2c1a0e] placeholder:text-[#c9b59b] bg-[#fef9f0] transition-all"
                            placeholder="Contoh: Tolong bungkus kado, atau kirim sebelum jam 5 sore ya..."></textarea>
                    </div>
                </div>

                {{-- KANAN: RINGKASAN & KURIR --}}
                <div class="w-full lg:w-[400px]">
                    <div class="bg-[#2c1a0e] rounded-2xl p-6 sm:p-8 text-white shadow-xl sticky top-10">
                        <form id="checkout-form">
                            @csrf
                            <input type="hidden" name="address_id" id="hidden-address-id">

                            <h2 class="text-xl font-black mb-6 flex items-center gap-3">
                                <i class="fas fa-truck text-[#fbbf24]"></i> Pengiriman
                            </h2>

                            <div class="mb-8">
                                <select name="shipping_rate_id" id="shipping-selector" class="w-full bg-[#3d2a1a] border-[#5c3d24] rounded-xl p-4 text-sm text-white focus:ring-2 focus:ring-[#f59e0b]/50 transition-all" required>
                                    <option value="" data-cost="0" data-estimation="">-- Pilih Kurir --</option>
                                    @foreach($shippingRates as $rate)
                                        @php
                                            $rateName = strtolower($rate->name);
                                            $isIntercity = str_contains($rateName, 'luar');
                                        @endphp
                                        <option value="{{ $rate->id }}" class="shipping-option" 
                                            data-type="{{ $isIntercity ? 'intercity' : 'local' }}"
                                            data-cost="{{ $rate->cost }}"
                                            data-estimation="{{ $rate->estimation }}">
                                            {{ $rate->name }} (+Rp {{ number_format($rate->cost, 0, ',', '.') }}) — {{ $rate->estimation }}
                                        </option>
                                    @endforeach
                                </select>
                                <div class="mt-2 px-2">
                                    <p id="courier-notice" class="text-[10px] italic"></p>
                                    <p id="estimation-notice" class="text-[10px] text-[#fbbf24] font-bold mt-1 hidden">
                                        <i class="fas fa-clock mr-1"></i> Estimasi Tiba: <span id="est-text"></span>
                                    </p>
                                </div>
                            </div>

                            @if(isset($order) && $order->delivery_proof)
                            <div class="mb-8 p-4 bg-[#3d2a1a] rounded-xl border border-[#5c3d24]">
                                <h3 class="text-xs font-bold uppercase tracking-wider text-[#c9b59b] mb-3">Bukti Foto Kurir</h3>
                                <div class="relative group cursor-pointer" onclick="viewProof('{{ asset('storage/' . $order->delivery_proof) }}')">
                                    <img src="{{ asset('storage/' . $order->delivery_proof) }}" class="w-full h-32 object-cover rounded-lg opacity-80 group-hover:opacity-100 transition-all">
                                    <div class="absolute inset-0 flex items-center justify-center">
                                        <span class="bg-[#f59e0b] text-[#2c1a0e] px-3 py-1 rounded-full text-[10px] font-black uppercase tracking-tighter">Klik Perbesar</span>
                                    </div>
                                </div>
                            </div>
                            @endif

                            <h2 class="text-xl font-black mb-4 flex items-center gap-3">
                                <i class="fas fa-credit-card text-[#fbbf24]"></i> Pembayaran
                            </h2>
                            <div class="space-y-3 mb-8">
                                <label class="flex items-center p-4 bg-[#3d2a1a] rounded-xl cursor-pointer border border-transparent hover:border-[#f59e0b] transition-all">
                                    <input type="radio" name="payment_method" value="midtrans" checked class="payment-radio text-[#f59e0b] focus:ring-[#f59e0b]">
                                    <span class="ml-3 text-sm font-bold">Transfer / QRIS / E-Wallet</span>
                                </label>
                            </div>

                            <div class="space-y-3 pt-6 border-t border-white/10 mb-8">
                                <div class="flex justify-between text-[#c9b59b] text-sm">
                                    <span>Subtotal Produk</span>
                                    <span>Rp {{ number_format($total, 0, ',', '.') }}</span>
                                </div>
                                <div class="flex justify-between text-[#c9b59b] text-sm">
                                    <span>Ongkos Kirim</span>
                                    <span id="display-shipping-cost">Rp 0</span>
                                </div>
                                <div class="flex justify-between items-center pt-4">
                                    <span class="font-bold text-lg">Total</span>
                                    <span class="font-black text-2xl text-[#fbbf24]" id="display-grand-total">Rp {{ number_format($total, 0, ',', '.') }}</span>
                                </div>
                            </div>

                            <button type="button" id="pay-button" class="w-full bg-gradient-to-r from-[#f59e0b] to-[#d97706] hover:from-[#d97706] hover:to-[#b45309] text-white py-5 rounded-xl font-black text-sm uppercase tracking-wider transition-all shadow-md active:scale-[0.98]">
                                Bayar Sekarang
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        function viewProof(url) {
            Swal.fire({
                imageUrl: url,
                imageAlt: 'Bukti Pengiriman Kurir',
                showConfirmButton: false,
                background: 'transparent',
                customClass: { popup: 'p-0 bg-transparent' }
            });
        }

        document.addEventListener('DOMContentLoaded', function() {
            const addressSelector = document.getElementById('address-selector');
            const shippingSelector = document.getElementById('shipping-selector');
            const hiddenAddressId = document.getElementById('hidden-address-id');
            const courierNotice = document.getElementById('courier-notice');
            const estimationNotice = document.getElementById('estimation-notice');
            const estText = document.getElementById('est-text');
            const payButton = document.getElementById('pay-button');
            const subtotal = {{ $total }};

           function filterCourier() {
                const selected = addressSelector.options[addressSelector.selectedIndex];
                const editAddressLink = document.getElementById('edit-address-link'); // Ambil elemen link edit
                
                if(!selected || selected.value === "") {
                    hiddenAddressId.value = ""; 
                    document.getElementById('address-detail-box').classList.add('hidden');
                    document.querySelectorAll('.shipping-option').forEach(opt => opt.style.display = 'none');
                    shippingSelector.value = "";
                    courierNotice.innerText = "";
                    updateTotal();
                    return;
                }

                hiddenAddressId.value = selected.value;
                document.getElementById('address-detail-box').classList.remove('hidden');
                document.getElementById('detail-name').innerText = selected.dataset.name;
                document.getElementById('detail-phone').innerText = selected.dataset.phone;
                document.getElementById('detail-complete').innerText = selected.dataset.complete;

                // UPDATE LINK EDIT: Mengarahkan ke route edit dengan parameter redirect checkout
                editAddressLink.href = `/addresses/${selected.value}/edit?redirect=checkout`;

                const cityName = (selected.dataset.city || "").toLowerCase().trim();
                const jabodetabek = ['jakarta', 'bogor', 'depok', 'tangerang', 'bekasi'];
                const isJabodetabek = jabodetabek.some(area => cityName.includes(area));
                const targetType = isJabodetabek ? 'local' : 'intercity';

                let foundCount = 0;
                document.querySelectorAll('.shipping-option').forEach(opt => {
                    if (opt.dataset.type === targetType) {
                        opt.style.display = 'block';
                        opt.disabled = false;
                        foundCount++;
                    } else {
                        opt.style.display = 'none';
                        opt.disabled = true;
                    }
                });

                shippingSelector.value = "";
                
                if (isJabodetabek) {
                    courierNotice.innerHTML = "<span class='text-[#fbbf24]'>✨ Wilayah: Dalam Kota (Jabodetabek)</span>";
                } else {
                    courierNotice.innerHTML = "<span class='text-[#f59e0b]'>🚚 Wilayah: Luar Kota (" + cityName.toUpperCase() + ")</span>";
                }

                if(foundCount === 0) courierNotice.innerHTML = "<span class='text-red-400'>❌ Kurir tidak tersedia untuk wilayah ini.</span>";

                updateTotal();
            }

            function updateTotal() {
                const opt = shippingSelector.options[shippingSelector.selectedIndex];
                const cost = parseInt(opt ? opt.dataset.cost : 0) || 0;
                const estimation = opt ? opt.dataset.estimation : "";

                document.getElementById('display-shipping-cost').innerText = 'Rp ' + cost.toLocaleString('id-ID');
                document.getElementById('display-grand-total').innerText = 'Rp ' + (subtotal + cost).toLocaleString('id-ID');

                if (estimation && estimation !== "") {
                    estimationNotice.classList.remove('hidden');
                    estText.innerText = estimation;
                } else {
                    estimationNotice.classList.add('hidden');
                }
            }

            addressSelector.addEventListener('change', filterCourier);
            shippingSelector.addEventListener('change', updateTotal);
            
            filterCourier();

            payButton.addEventListener('click', async function() {
                if (!addressSelector.value || !shippingSelector.value) {
                    Swal.fire({ icon: 'warning', title: 'Belum Lengkap', text: 'Pilih alamat dan kurir dulu!', customClass: {popup: 'rounded-xl'} });
                    return;
                }

                this.innerText = "Menghubungkan...";
                this.disabled = true;

                const orderNotes = document.getElementById('order-notes').value;

                try {
                    const response = await fetch("{{ route('checkout.snap') }}", {
                        method: "POST",
                        headers: { 
                            "Content-Type": "application/json", 
                            "X-CSRF-TOKEN": "{{ csrf_token() }}" 
                        },
                        body: JSON.stringify({ 
                            shipping_rate_id: shippingSelector.value, 
                            address_id: addressSelector.value,
                            notes: orderNotes 
                        })
                    });
                    
                    const data = await response.json();
                    
                    if (data.snap_token) {
                        window.snap.pay(data.snap_token, {
                            onSuccess: (res) => { window.location.href = "{{ route('orders.index') }}"; },
                            onPending: (res) => { window.location.href = "{{ route('orders.index') }}"; },
                            onClose: () => {
                                this.disabled = false;
                                this.innerText = "Bayar Sekarang";
                                Swal.fire({
                                    icon: 'info',
                                    title: 'Pembayaran Ditunda',
                                    text: 'Anda menutup jendela pembayaran.',
                                    customClass: { popup: 'rounded-xl' }
                                });
                            }
                        });
                    } else {
                        throw new Error(data.error || 'Gagal mengambil token');
                    }
                } catch (e) {
                    this.disabled = false;
                    this.innerText = "Bayar Sekarang";
                    Swal.fire({ icon: 'error', title: 'Kesalahan', text: e.message, customClass: {popup: 'rounded-xl'} });
                }
            });
        });
    </script>

    <style>
        @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap');
        body { font-family: 'Plus Jakarta Sans', sans-serif; }
        input, select, textarea { transition: all 0.2s ease; }
        .swal2-popup { border-radius: 1rem !important; }
    </style>
</x-app-layout>