<x-app-layout>
    @push('styles')
    <style>
        .address-card {
            transition: all 0.2s ease;
            border: 1px solid #e5e7eb;
            background: white;
        }

        .address-card.selected {
            border-color: #f59e0b;
            background-color: #fffbeb;
            box-shadow: 0 4px 12px rgba(245, 158, 11, 0.1);
        }



        .btn-outline {
            border: 1px solid #e5e7eb;
            background: white;
            padding: 8px 16px;
            border-radius: 10px;
            font-weight: 500;
            transition: all 0.2s;
        }

        .btn-outline:hover {
            background: #f3f4f6;
        }
    </style>
    @endpush

    @php
    // Ambil redirect_to dari query string (default ke address.index)
    $redirectTo = request()->query('redirect_to', 'address.index');

    // Validasi whitelist (sama dengan di controller)
    $allowedRedirects = ['address.index', 'cart.checkout.get', 'cart.index', 'order.index'];
    if (!in_array($redirectTo, $allowedRedirects)) {
    $redirectTo = 'address.index';
    }

    $selectedAddressId = session('selected_address_id');
    $isFromCheckout = ($redirectTo === 'cart.checkout.get' || $redirectTo === 'order.index');
    @endphp

    <x-slot name="header">
        <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 gradient-primary rounded-xl flex items-center justify-center shadow-lg">
                    <i class="fas fa-map-marker-alt text-sm"></i>
                </div>
                <div>
                    <h1 class="text-xl font-bold text-stone-800">
                        {{ $isFromCheckout ? 'Pilih Alamat Pengiriman' : 'Daftar Alamat Saya' }}
                    </h1>
                    <p class="text-xs text-stone-500">
                        {{ $isFromCheckout ? 'Pilih alamat untuk pengiriman pesanan Anda' : 'Kelola alamat pengiriman Anda' }}
                    </p>
                </div>
            </div>

            @if($isFromCheckout)
            <a href="{{ route($redirectTo === 'order.index' ? 'order.checkout.page' : 'cart.checkout.get') }}"
                class="inline-flex items-center gap-2 px-4 py-2 bg-stone-100 hover:bg-stone-200 text-stone-700 text-sm font-medium rounded-xl transition border border-stone-300">
                <i class="fas fa-arrow-left text-xs"></i>
                <span>Kembali ke Checkout</span>
            </a>
            @endif
        </div>
    </x-slot>

    <div class="py-6">

        @if($isFromCheckout)
        {{-- ================= LAYOUT CHECKOUT ================= --}}
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

            {{-- LEFT COLUMN: Alamat + Produk --}}
            <div class="lg:col-span-2 space-y-6">

                {{-- CARD: ALAMAT --}}
                <div class="bg-white rounded-xl shadow-sm border border-stone-200 overflow-hidden">
                    <div class="px-5 py-4 border-b border-stone-100 bg-gradient-to-r from-stone-50 to-white">
                        <div class="flex items-center gap-2">
                            <i class="fas fa-map-marker-alt text-amber-500"></i>
                            <h2 class="font-semibold text-stone-800">Alamat Pengiriman</h2>
                        </div>
                    </div>

                    <div class="p-5">
                        @forelse ($addresses as $address)
                        <div class="address-card rounded-xl p-4 mb-3 cursor-pointer transition-all 
                                    {{ $selectedAddressId == $address->id ? 'selected border-amber-400 bg-amber-50' : 'border-stone-200 hover:border-amber-200' }}"
                            onclick="selectAddress({{ $address->id }})">

                            <div class="flex items-start justify-between">
                                <div class="flex-1">
                                    <div class="flex items-center gap-2 flex-wrap">
                                        <p class="font-semibold text-stone-800">{{ $address->recipient_name }}</p>
                                        <span class="text-xs text-stone-400">|</span>
                                        <span class="text-sm text-stone-600">{{ $address->phone }}</span>
                                        @if($selectedAddressId == $address->id)
                                        <span class="ml-2 text-xs bg-amber-100 text-amber-700 px-2 py-0.5 rounded-full">
                                            <i class="fas fa-check-circle text-xs mr-1"></i>Dipilih
                                        </span>
                                        @endif
                                    </div>
                                    <p class="text-sm text-stone-600 mt-2 leading-relaxed">
                                        {{ $address->full_address }}
                                    </p>
                                </div>

                                <div class="flex gap-2 ml-3">
                                    <a href="{{ route('address.edit', $address) }}?redirect_to={{ $redirectTo }}"
                                        class="text-xs text-amber-600 hover:text-amber-700 font-medium px-2 py-1 rounded-lg hover:bg-amber-50 transition"
                                        onclick="event.stopPropagation()">
                                        <i class="fas fa-edit mr-1"></i>Edit
                                    </a>
                                </div>
                            </div>
                        </div>
                        @empty
                        <div class="text-center py-8">
                            <div class="w-16 h-16 bg-amber-50 rounded-full flex items-center justify-center mx-auto mb-3">
                                <i class="fas fa-map-marker-alt text-amber-500 text-xl"></i>
                            </div>
                            <p class="text-stone-500 mb-3">Belum ada alamat tersimpan</p>
                            <a href="{{ route('address.create', ['redirect_to' => $redirectTo]) }}"
                                class="inline-flex items-center gap-2 px-4 py-2 btn-primary text-sm font-medium rounded-lg transition">
                                <i class="fas fa-plus"></i>
                                Tambah Alamat Baru
                            </a>
                        </div>
                        @endforelse

                        @if($addresses->isNotEmpty())
                        <div class="mt-4 pt-3 border-t border-stone-100">
                            <a href="{{ route('address.create', ['redirect_to' => $redirectTo]) }}"
                                class="inline-flex items-center gap-2 text-sm text-amber-600 hover:text-amber-700 font-medium">
                                <i class="fas fa-plus-circle"></i>
                                Tambah Alamat Baru
                            </a>
                        </div>
                        @endif
                    </div>
                </div>

                {{-- CARD: PRODUK --}}
                <div class="bg-white rounded-xl shadow-sm border border-stone-200 overflow-hidden">
                    <div class="px-5 py-4 border-b border-stone-100 bg-gradient-to-r from-stone-50 to-white">
                        <div class="flex items-center gap-2">
                            <i class="fas fa-box text-amber-500"></i>
                            <h2 class="font-semibold text-stone-800">Ringkasan Pesanan</h2>
                        </div>
                    </div>
                    <div class="p-5">
                        @if(session('buynow_product_id'))
                        @php
                        $product = \App\Models\Product::find(session('buynow_product_id'));
                        @endphp
                        @if($product)
                        <div class="flex gap-4">
                            <div class="w-20 h-20 bg-stone-100 rounded-lg overflow-hidden flex-shrink-0">
                                @php
                                $img = $product->image;
                                $imgUrl = null;
                                if ($img) {
                                if (is_array($img) && count($img) > 0) $imgUrl = asset('storage/'.$img[0]);
                                elseif (is_string($img)) {
                                $dec = json_decode($img, true);
                                $imgUrl = is_array($dec) && count($dec) > 0 ? asset('storage/'.$dec[0]) : asset('storage/'.$img);
                                }
                                }
                                @endphp
                                @if($imgUrl)
                                <img src="{{ $imgUrl }}" class="w-full h-full object-cover">
                                @else
                                <div class="w-full h-full flex items-center justify-center">
                                    <i class="fas fa-image text-stone-300 text-2xl"></i>
                                </div>
                                @endif
                            </div>
                            <div class="flex-1">
                                <p class="font-semibold text-stone-800">{{ $product->product_name }}</p>
                                <p class="text-amber-600 font-bold mt-1">Rp {{ number_format($product->price, 0, ',', '.') }}</p>
                                <p class="text-xs text-stone-500 mt-1">Jumlah: 1</p>
                            </div>
                        </div>
                        @endif
                        @else
                        <p class="text-stone-500 text-sm">Informasi pesanan akan muncul setelah pilih alamat</p>
                        @endif
                    </div>
                </div>
            </div>

            {{-- RIGHT COLUMN: Ringkasan Pembayaran --}}
            <div class="lg:col-span-1">
                <div class="bg-white rounded-xl shadow-sm border border-stone-200 overflow-hidden sticky top-24">
                    <div class="px-5 py-4 border-b border-stone-100 bg-gradient-to-r from-stone-50 to-white">
                        <div class="flex items-center gap-2">
                            <i class="fas fa-receipt text-amber-500"></i>
                            <h2 class="font-semibold text-stone-800">Ringkasan Pembayaran</h2>
                        </div>
                    </div>

                    <div class="p-5 space-y-3">
                        @if(session('buynow_product_id'))
                        @php
                        $product = \App\Models\Product::find(session('buynow_product_id'));
                        $subtotal = $product ? $product->price : 0;
                        @endphp
                        <div class="flex justify-between text-sm">
                            <span class="text-stone-600">Total Produk</span>
                            <span class="font-semibold text-stone-800">Rp {{ number_format($subtotal, 0, ',', '.') }}</span>
                        </div>
                        <div class="flex justify-between text-sm">
                            <span class="text-stone-600">Ongkos Kirim</span>
                            <span class="font-semibold text-stone-800" id="shipping-cost-display">-</span>
                        </div>
                        <div class="border-t border-stone-100 pt-3 mt-2">
                            <div class="flex justify-between">
                                <span class="font-bold text-stone-800">Total</span>
                                <span class="font-bold text-amber-600 text-lg" id="total-display">Rp {{ number_format($subtotal, 0, ',', '.') }}</span>
                            </div>
                        </div>
                        @else
                        <p class="text-stone-500 text-sm text-center py-4">Pilih alamat untuk menghitung ongkir</p>
                        @endif
                    </div>

                    @if($addresses->isNotEmpty() && session('buynow_product_id'))
                    <div class="px-5 pb-5">
                        <form id="select-address-form" action="{{ route('address.select-for-checkout', ['address' => '__ADDRESS_ID__']) }}" method="POST" style="display: none;">
                            @csrf
                        </form>
                        <button id="btn-continue"
                            onclick="continueToCheckout()"
                            class="w-full py-3 btn-primary font-semibold rounded-xl shadow-md hover:shadow-lg transition-all duration-200"
                            {{ !$selectedAddressId ? 'disabled' : '' }}>
                            <i class="fas fa-arrow-right mr-2"></i>
                            Lanjutkan ke Pembayaran
                        </button>
                        @if(!$selectedAddressId)
                        <p class="text-xs text-amber-600 mt-2 text-center">Silakan pilih alamat terlebih dahulu</p>
                        @endif
                    </div>
                    @endif
                </div>
            </div>

        </div>

        @else

        {{-- ================= LAYOUT NON CHECKOUT (MANAJEMEN ALAMAT BIASA) ================= --}}
        <div class="bg-white rounded-xl shadow-sm border border-stone-200 overflow-hidden">
            <div class="px-5 py-4 border-b border-stone-100 bg-gradient-to-r from-stone-50 to-white flex justify-between items-center">
                <div class="flex items-center gap-2">
                    <i class="fas fa-address-book text-amber-500"></i>
                    <h2 class="font-semibold text-stone-800">Daftar Alamat Saya</h2>
                    <span class="text-xs text-stone-500 bg-stone-100 px-2 py-0.5 rounded-full">{{ $addresses->count() }} alamat</span>
                </div>
                <a href="{{ route('address.create', ['redirect_to' => 'address.index']) }}"
                    class="inline-flex items-center gap-2 px-4 py-2 btn-primary text-sm font-medium rounded-lg transition shadow-md">
                    <i class="fas fa-plus"></i>
                    Tambah Alamat
                </a>
            </div>

            <div class="p-5">
                @forelse ($addresses as $address)
                <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3 p-4 mb-3 bg-stone-50 rounded-xl border border-stone-200 hover:border-amber-200 transition">
                    <div class="flex-1">
                        <div class="flex items-center gap-2 flex-wrap">
                            <p class="font-semibold text-stone-800">{{ $address->recipient_name }}</p>
                            <span class="text-xs text-stone-400">|</span>
                            <span class="text-sm text-stone-600">{{ $address->phone }}</span>
                            @if($address->is_default)
                            <span class="text-xs bg-amber-100 text-amber-700 px-2 py-0.5 rounded-full">Utama</span>
                            @endif
                        </div>
                        <p class="text-sm text-stone-600 mt-1">{{ $address->full_address }}</p>
                    </div>
                    <div class="flex gap-2">
                        <a href="{{ route('address.edit', $address) }}?redirect_to=address.index"
                            class="px-3 py-1.5 text-sm text-amber-600 hover:bg-amber-50 rounded-lg transition">
                            <i class="fas fa-edit mr-1"></i>Edit
                        </a>
                        <form action="{{ route('address.destroy', $address) }}" method="POST" class="inline"
                            onsubmit="return confirm('Yakin ingin menghapus alamat ini?')">
                            @csrf
                            @method('DELETE')
                            <button type="submit" class="px-3 py-1.5 text-sm text-red-500 hover:bg-red-50 rounded-lg transition">
                                <i class="fas fa-trash mr-1"></i>Hapus
                            </button>
                        </form>
                    </div>
                </div>
                @empty
                <div class="text-center py-12">
                    <div class="w-20 h-20 bg-amber-50 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-map-marker-alt text-amber-500 text-2xl"></i>
                    </div>
                    <p class="text-stone-500 mb-4">Belum ada alamat yang tersimpan</p>
                    <a href="{{ route('address.create', ['redirect_to' => 'address.index']) }}"
                        class="inline-flex items-center gap-2 px-5 py-2.5 btn-primary font-medium rounded-xl transition">
                        <i class="fas fa-plus"></i>
                        Tambah Alamat Pertama
                    </a>
                </div>
                @endforelse
            </div>
        </div>

        @endif

    </div>

    <script>
        function selectAddress(addressId) {
            // Submit form untuk memilih alamat
            const form = document.getElementById('select-address-form');
            if (form) {
                form.action = form.action.replace('__ADDRESS_ID__', addressId);
                form.submit();
            } else {
                // Fallback: redirect langsung
                fetch(`/address/${addressId}/select-for-checkout`, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Content-Type': 'application/json'
                    }
                }).then(() => {
                    window.location.reload();
                });
            }
        }

        function continueToCheckout() {
            const redirectTo = '{{ $redirectTo }}';
            if (redirectTo === 'order.index') {
                window.location.href = '{{ route("order.checkout.page") }}';
            } else {
                window.location.href = '{{ route("cart.checkout.get") }}';
            }
        }
    </script>
</x-app-layout>