@extends('layouts.app')

@section('title', 'Checkout')

@section('content')
<div class="max-w-4xl mx-auto px-4 py-10" style="font-family: 'Plus Jakarta Sans', sans-serif;">

    <div class="mb-8">
        <h1 class="text-3xl font-black text-slate-800 italic tracking-tighter">Checkout 🛍️</h1>
        <p class="text-pink-400 font-bold text-sm mt-1">Periksa pesanan sebelum bayar</p>
    </div>

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

        {{-- ── KIRI: Alamat + Metode Bayar ── --}}
        <div class="lg:col-span-2 space-y-6">

            {{-- Pilih Alamat --}}
            <div class="bg-white rounded-[32px] border border-pink-50 shadow-sm p-6">
                <div class="flex items-center justify-between mb-5">
                    <h2 class="font-black text-slate-800 flex items-center gap-2">
                        <i data-lucide="map-pin" class="w-5 h-5 text-pink-400"></i>
                        Alamat Pengiriman
                    </h2>
                    <a href="{{ route('user.address.create') }}"
                       class="text-[10px] font-black uppercase tracking-widest text-pink-400 hover:text-pink-600 transition bg-pink-50 px-3 py-1.5 rounded-xl">
                        + Tambah
                    </a>
                </div>

                @if($addresses->count())
                <div class="space-y-3" id="address-list">
                    @foreach($addresses as $address)
                    <label class="address-card cursor-pointer block">
                        <input type="radio" name="selected_address" value="{{ $address->id }}"
                               data-province="{{ $address->province_code }}"
                               data-city="{{ $address->city_code }}"
                               class="sr-only address-radio"
                               {{ $address->is_default || old('address_id') == $address->id ? 'checked' : '' }}>
                        <div class="address-box p-4 rounded-2xl border-2 transition-all
                            {{ $address->is_default ? 'border-pink-400 bg-pink-50/50' : 'border-slate-100 bg-slate-50/30 hover:border-pink-200' }}">
                            <div class="flex items-start justify-between">
                                <div class="flex-1">
                                    <div class="flex items-center gap-2 mb-1">
                                        <span class="bg-pink-100 text-pink-600 text-[9px] px-2.5 py-0.5 rounded-full font-black uppercase tracking-wider">
                                            {{ $address->label }}
                                        </span>
                                        @if($address->is_default)
                                            <span class="bg-slate-800 text-white text-[9px] px-2 py-0.5 rounded-full font-bold">Utama</span>
                                        @endif
                                    </div>
                                    <p class="text-sm font-black text-slate-800">{{ $address->receiver_name }}</p>
                                    <p class="text-xs font-bold text-slate-500 mt-0.5">{{ $address->phone }}</p>
                                    <p class="text-xs text-slate-400 mt-1 leading-relaxed">{{ $address->full_address }}</p>
                                    {{-- Tombol aksi --}}
                                    <div class="flex items-center gap-2 mt-2">
                                        <a href="{{ route('user.address.edit', $address->id) }}"
                                           class="text-[10px] font-black uppercase tracking-widest text-slate-400 hover:text-pink-500 transition bg-slate-100 hover:bg-pink-50 px-2.5 py-1 rounded-lg">
                                            ✏️ Edit
                                        </a>
                                        <form action="{{ route('user.address.destroy', $address->id) }}" method="POST"
                                              onsubmit="return confirm('Hapus alamat ini?')">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit"
                                                    class="text-[10px] font-black uppercase tracking-widest text-slate-400 hover:text-red-500 transition bg-slate-100 hover:bg-red-50 px-2.5 py-1 rounded-lg">
                                                🗑️ Hapus
                                            </button>
                                        </form>
                                    </div>
                                </div>
                                <div class="w-5 h-5 rounded-full border-2 border-pink-300 flex items-center justify-center shrink-0 mt-1 check-dot transition-all">
                                    <div class="w-2.5 h-2.5 rounded-full bg-pink-500 hidden check-fill"></div>
                                </div>
                            </div>

                            {{-- Zona ongkir untuk alamat ini --}}
                            <div class="mt-3 pt-3 border-t border-slate-100 flex items-center justify-between">
                                <span class="text-[10px] font-bold text-slate-400 zone-label">
                                    @php
                                        $fee = \App\Helpers\ShippingCalculator::calculate($address->province_code, $address->city_code);
                                        $zone = \App\Helpers\ShippingCalculator::getZoneLabel($address->province_code, $address->city_code);
                                    @endphp
                                    📍 {{ $zone }}
                                </span>
                                <span class="text-xs font-black text-pink-500 italic">
                                    {{ \App\Helpers\ShippingCalculator::format($fee) }}
                                </span>
                            </div>
                        </div>
                    </label>
                    @endforeach
                </div>
                @else
                <div class="text-center py-8 bg-slate-50 rounded-2xl border-2 border-dashed border-pink-100">
                    <p class="text-sm text-slate-400 font-bold mb-3">Belum ada alamat tersimpan.</p>
                    <a href="{{ route('user.address.create') }}"
                       class="inline-flex items-center gap-2 bg-pink-500 text-white text-xs font-black uppercase tracking-widest px-4 py-2.5 rounded-xl shadow-lg shadow-pink-200">
                        <i data-lucide="plus" class="w-4 h-4"></i> Tambah Alamat
                    </a>
                </div>
                @endif
            </div>

            {{-- Metode Pembayaran --}}
            <div class="bg-white rounded-[32px] border border-pink-50 shadow-sm p-6">
                <h2 class="font-black text-slate-800 flex items-center gap-2 mb-5">
                    <i data-lucide="credit-card" class="w-5 h-5 text-pink-400"></i>
                    Metode Pembayaran
                </h2>
                <div class="grid grid-cols-1 gap-3">
                    <label class="cursor-pointer">
                        <input type="radio" name="payment_method" value="midtrans" class="sr-only pay-radio" checked>
                        <div class="pay-box p-4 rounded-2xl border-2 border-pink-400 bg-pink-50/50 transition-all">
                            <div class="flex items-center gap-3">
                                <div class="w-9 h-9 bg-blue-500 rounded-xl flex items-center justify-center shadow-sm">
                                    <i data-lucide="smartphone" class="w-4 h-4 text-white"></i>
                                </div>
                                <div>
                                    <p class="text-sm font-black text-slate-800">Midtrans</p>
                                    <p class="text-[10px] text-slate-400 font-bold">Transfer / QRIS / e-Wallet</p>
                                </div>
                            </div>
                        </div>
                    </label>
                </div>
            </div>

            {{-- ── Catatan untuk Admin ── --}}
            <div class="bg-white rounded-[32px] border border-pink-50 shadow-sm p-6">
                <h2 class="font-black text-slate-800 flex items-center gap-2 mb-4">
                    <i data-lucide="message-square" class="w-5 h-5 text-pink-400"></i>
                    Catatan Pesanan
                </h2>
                <textarea id="checkout-note" name="checkout_note" rows="3"
                          placeholder="Contoh: tolong dibungkus rapi, jangan dilipat, ini hadiah ulang tahun..."
                          maxlength="300"
                          class="w-full px-4 py-3 rounded-2xl bg-slate-50 border-2 border-slate-100
                                 focus:border-pink-300 focus:bg-pink-50/30 text-xs font-bold text-slate-700
                                 outline-none transition resize-none placeholder:text-slate-300 leading-relaxed"></textarea>
                <div class="flex items-center justify-between mt-2">
                    <p class="text-[9px] text-slate-400 font-bold">💡 Opsional — dibaca langsung oleh tim packing</p>
                    <p class="text-[9px] text-slate-300 font-bold">
                        <span id="note-counter">0</span>/300
                    </p>
                </div>
            </div>

        </div>

        {{-- ── KANAN: Ringkasan Order ── --}}
        <div class="lg:col-span-1">
            <div class="bg-white rounded-[32px] border border-pink-50 shadow-sm p-6 sticky top-28 space-y-5">
                <h2 class="font-black text-slate-800 flex items-center gap-2">
                    <i data-lucide="shopping-bag" class="w-5 h-5 text-pink-400"></i>
                    Ringkasan
                </h2>

                {{-- Produk --}}
                <div class="space-y-3">
                    @php $subtotal = 0; @endphp
                    @foreach(session('cart', []) as $id => $item)
                    @php $subtotal += $item['price'] * $item['quantity']; @endphp
                    <div class="flex items-center gap-3">
                        <img src="{{ asset('storage/' . $item['image']) }}"
                             class="w-12 h-12 rounded-xl object-cover shadow-sm">
                        <div class="flex-1 min-w-0">
                            <p class="text-xs font-black text-slate-700 truncate">{{ $item['name'] }}</p>
                            <p class="text-[10px] text-slate-400 font-bold">{{ $item['quantity'] }}x</p>
                        </div>
                        <p class="text-xs font-black text-slate-800 italic shrink-0">
                            Rp {{ number_format($item['price'] * $item['quantity'], 0, ',', '.') }}
                        </p>
                    </div>
                    @endforeach
                </div>

                <hr class="border-dashed border-pink-100">

                {{-- Subtotal --}}
                <div class="space-y-2 text-sm">
                    <div class="flex justify-between">
                        <span class="text-slate-500 font-bold">Subtotal</span>
                        <span class="font-black text-slate-800">Rp {{ number_format($subtotal, 0, ',', '.') }}</span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-slate-500 font-bold">Ongkir</span>
                        <div class="text-right">
                            <span id="ongkir-display" class="font-black text-pink-500 italic">
                                Rp {{ number_format($defaultShipping ?? 15000, 0, ',', '.') }}
                            </span>
                            <p id="zone-display" class="text-[9px] text-slate-400 font-bold"></p>
                        </div>
                    </div>
                </div>

                <hr class="border-pink-100">

                <div class="flex justify-between items-center">
                    <span class="text-sm font-black text-slate-700">Total</span>
                    <span id="total-display" class="text-xl font-black text-pink-500 italic">
                        Rp {{ number_format($subtotal + ($defaultShipping ?? 15000), 0, ',', '.') }}
                    </span>
                </div>

                {{-- Nomor HP --}}
                <input type="text" id="checkout-phone" name="checkout_phone"
                       placeholder="Nomor WhatsApp aktif"
                       inputmode="numeric"
                       oninput="this.value=this.value.replace(/[^0-9]/g,'')"
                       class="w-full px-4 py-3 rounded-xl bg-slate-50 text-xs font-bold outline-none focus:ring-2 focus:ring-pink-300 transition">

                <button id="btn-checkout"
                        class="w-full bg-pink-500 hover:bg-pink-600 active:scale-95 text-white font-black text-xs uppercase tracking-widest py-4 rounded-2xl shadow-xl shadow-pink-200 transition-all">
                    Lanjut Bayar
                </button>
                <p class="text-[9px] text-slate-400 text-center font-bold">
                    Dengan menekan tombol, kamu menyetujui syarat & ketentuan Vogue3D.
                </p>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript" src="https://app.sandbox.midtrans.com/snap/snap.js"
        data-client-key="{{ env('MIDTRANS_CLIENT_KEY') }}"></script>

<script>
const subtotal      = {{ $subtotal }};
let   currentOngkir = {{ $defaultShipping ?? 15000 }};
let   selectedAddressId = null;

function formatRp(n) {
    return 'Rp ' + n.toLocaleString('id-ID');
}

function updateSummary(ongkir, zone) {
    currentOngkir = ongkir;
    document.getElementById('ongkir-display').textContent = formatRp(ongkir);
    document.getElementById('zone-display').textContent   = zone || '';
    document.getElementById('total-display').textContent  = formatRp(subtotal + ongkir);
}

function activateAddress(card, addressId, ongkir, zone) {
    document.querySelectorAll('.address-box').forEach(b => {
        b.classList.remove('border-pink-400', 'bg-pink-50/50');
        b.classList.add('border-slate-100', 'bg-slate-50/30');
        b.querySelector('.check-fill').classList.add('hidden');
    });

    card.classList.remove('border-slate-100', 'bg-slate-50/30');
    card.classList.add('border-pink-400', 'bg-pink-50/50');
    card.querySelector('.check-fill').classList.remove('hidden');

    selectedAddressId = addressId;
    updateSummary(ongkir, zone);
}

document.querySelectorAll('.address-radio').forEach(radio => {
    const label     = radio.closest('label');
    const box       = label.querySelector('.address-box');
    const addressId = radio.value;

    const zoneText  = box.querySelector('.zone-label').textContent.trim();
    const priceText = box.querySelector('.zone-label + span').textContent.trim();
    const ongkir    = parseInt(priceText.replace(/[^0-9]/g, ''), 10) || 15000;

    radio.addEventListener('change', function () {
        activateAddress(box, addressId, ongkir, zoneText);
    });

    if (radio.checked) {
        activateAddress(box, addressId, ongkir, zoneText);
    }
});

// Counter karakter catatan
document.getElementById('checkout-note').addEventListener('input', function () {
    document.getElementById('note-counter').textContent = this.value.length;
});

document.getElementById('btn-checkout').addEventListener('click', async function () {
    if (!selectedAddressId) {
        alert('Pilih alamat pengiriman dulu ya!');
        return;
    }

    const phone = document.getElementById('checkout-phone').value.trim();
    if (!phone) {
        alert('Masukkan nomor WhatsApp aktif!');
        return;
    }

    const address     = document.querySelector(`.address-radio[value="${selectedAddressId}"]`)
                            .closest('label').querySelector('.address-box p:nth-child(4)');
    const fullAddress = address ? address.textContent.trim() : '';
    const note        = document.getElementById('checkout-note').value.trim();

    this.disabled    = true;
    this.textContent = 'Memproses...';

    try {
        const resp = await fetch('{{ route('user.payment.process') }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({
                address:        fullAddress,
                phone:          phone,
                payment_method: 'midtrans',
                shipping_fee:   currentOngkir,
                address_id:     selectedAddressId,
                note:           note,
            })
        });

        const data = await resp.json();

        if (data.success) {
            window.snap.pay(data.snap_token, {
                onSuccess: () => window.location.href = '{{ route('user.orders.index') }}',
                onPending: () => window.location.href = '{{ route('user.orders.index') }}',
                onClose:   () => {
                    document.getElementById('btn-checkout').disabled    = false;
                    document.getElementById('btn-checkout').textContent = 'Lanjut Bayar';
                }
            });
        } else {
            alert(data.error || 'Terjadi kesalahan.');
            this.disabled    = false;
            this.textContent = 'Lanjut Bayar';
        }
    } catch (e) {
        alert('Gagal terhubung ke server.');
        this.disabled    = false;
        this.textContent = 'Lanjut Bayar';
    }
});
</script>

<script>lucide.createIcons();</script>
@endsection