<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pembayaran - Glow Beauty</title>

    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    {{-- Midtrans Snap JS --}}
    @if($isProduction)
        <script src="https://app.midtrans.com/snap/snap.js" data-client-key="{{ $clientKey }}"></script>
    @else
        <script src="https://app.sandbox.midtrans.com/snap/snap.js" data-client-key="{{ $clientKey }}"></script>
    @endif

    <style>
        * { font-family: 'Poppins', 'Plus Jakarta Sans', sans-serif; }

        body { background: linear-gradient(135deg, #fdf2f8 0%, #fff1f3 100%); }

        /* Sidebar sticky */
        .sidebar-sticky { position: sticky; top: 24px; }

        /* Cards */
        .section-card {
            background: #fff;
            border-radius: 16px;
            border: 1px solid #fbcfe8;
            overflow: hidden;
        }
        .section-card + .section-card { margin-top: 16px; }

        .section-header {
            padding: 16px 20px;
            border-bottom: 1px solid #fef2f8;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .section-label {
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.08em;
            color: #a09080;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .section-label i { color: #f472b6; font-size: 11px; }

        /* Order header gradient */
        .order-header {
            background: linear-gradient(135deg, #f472b6 0%, #ec489a 100%);
            padding: 24px;
            position: relative;
            overflow: hidden;
        }
        .order-header::before {
            content: '';
            position: absolute;
            top: -30px; right: -30px;
            width: 120px; height: 120px;
            background: rgba(255,255,255,0.08);
            border-radius: 50%;
        }
        .order-header::after {
            content: '';
            position: absolute;
            bottom: -20px; left: 40px;
            width: 80px; height: 80px;
            background: rgba(255,255,255,0.06);
            border-radius: 50%;
        }

        /* Price breakdown rows */
        .price-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 20px;
            font-size: 13.5px;
        }
        .price-row:not(:last-child) { border-bottom: 1px solid #fef2f8; }
        .price-row.total-row {
            background: #fef2f8;
            padding: 14px 20px;
            border-top: 2px solid #fbcfe8;
        }

        /* Item row */
        .item-row {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            padding: 12px 20px;
            font-size: 13.5px;
            gap: 16px;
        }
        .item-row:not(:last-child) { border-bottom: 1px solid #fef2f8; }

        /* Alamat card */
        .alamat-display {
            margin: 0 20px 16px;
            background: #fef2f8;
            border: 1px solid #fbcfe8;
            border-radius: 12px;
            padding: 14px 16px;
        }

        /* Pay button */
        .pay-btn {
            background: linear-gradient(135deg, #f472b6, #ec489a);
            color: white;
            width: 100%;
            padding: 16px;
            border-radius: 14px;
            font-size: 15px;
            font-weight: 700;
            letter-spacing: 0.02em;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            transition: all 0.2s;
            box-shadow: 0 4px 20px rgba(244,114,182,0.35);
        }
        .pay-btn:hover { transform: translateY(-1px); box-shadow: 0 6px 24px rgba(244,114,182,0.45); }
        .pay-btn:active { transform: translateY(0); }
        .pay-btn:disabled { background: #d1d5db; box-shadow: none; cursor: not-allowed; transform: none; }

        /* Payment badge */
        .pay-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 5px 10px;
            background: #fef2f8;
            border-radius: 8px;
            font-size: 12px;
            color: #6b7280;
            font-weight: 500;
            border: 1px solid #fbcfe8;
        }

        /* Modal */
        #addressModal { transition: opacity 0.25s ease; }
        #addressModal.hidden { opacity: 0; pointer-events: none; }
        #modalBox { transition: transform 0.25s ease, opacity 0.25s ease; }
        #addressModal.hidden #modalBox { transform: translateY(20px); opacity: 0; }

        .alamat-card { transition: all 0.2s ease; cursor: pointer; }
        .alamat-card:hover { border-color: #f472b6; box-shadow: 0 0 0 3px rgba(244,114,182,0.12); }
        .alamat-card.selected { border-color: #f472b6; background-color: #fef2f8; box-shadow: 0 0 0 3px rgba(244,114,182,0.18); }
        .alamat-card.selected .check-icon { display: flex; }
        .alamat-card .check-icon { display: none; }

        @keyframes spin { to { transform: rotate(360deg); } }
        .spin { animation: spin 1s linear infinite; }

        @keyframes slideInRight {
            from { opacity: 0; transform: translateX(100px); }
            to   { opacity: 1; transform: translateX(0); }
        }
        @keyframes slideOutRight {
            from { opacity: 1; transform: translateX(0); }
            to   { opacity: 0; transform: translateX(100px); }
        }

        /* Ongkir detail box */
        .ongkir-detail {
            margin: 0 20px 12px;
            background: #fef2f8;
            border: 1px dashed #fbcfe8;
            border-radius: 10px;
            padding: 10px 14px;
            font-size: 12px;
            color: #78350f;
            line-height: 1.6;
        }

        /* Polling */
        #statusPolling {
            background: #eff6ff;
            border-bottom: 1px solid #bfdbfe;
            padding: 12px 20px;
            display: none;
        }

        /* Back link */
        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            color: #9ca3af;
            font-size: 13px;
            font-weight: 600;
            text-decoration: none;
            transition: color 0.15s;
            margin-bottom: 20px;
        }
        .back-link:hover { color: #f472b6; }

        /* Kode pesanan chip */
        .kode-chip {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            background: rgba(255,255,255,0.18);
            border: 1px solid rgba(255,255,255,0.3);
            border-radius: 8px;
            padding: 4px 10px;
            font-size: 12px;
            color: rgba(255,255,255,0.9);
            font-weight: 500;
        }
        
        .border-pink-light { border-color: #fbcfe8; }
    </style>
</head>
<body class="min-h-screen py-8">

<div class="w-full px-4 sm:px-6">

    {{-- Toast --}}
    @if(session('success'))
    <div id="toast-success"
        class="fixed bottom-6 right-6 z-50 flex items-center gap-3 bg-white border border-green-200 shadow-2xl rounded-2xl px-5 py-4 max-w-sm w-full"
        style="animation: slideInRight 0.4s ease;">
        <div class="w-10 h-10 bg-green-500 rounded-xl flex items-center justify-center flex-shrink-0">
            <i class="fas fa-check text-white text-sm"></i>
        </div>
        <div class="flex-1 min-w-0">
            <p class="font-semibold text-gray-800 text-sm">Berhasil!</p>
            <p class="text-gray-500 text-xs mt-0.5">{{ session('success') }}</p>
        </div>
        <button onclick="closeToast()" class="text-gray-400 hover:text-gray-600 flex-shrink-0 ml-1">
            <i class="fas fa-times text-xs"></i>
        </button>
        <div class="absolute bottom-0 left-0 h-1 bg-green-500 rounded-b-2xl" id="toastProgress"
            style="width: 100%; transition: width 5s linear;"></div>
    </div>
    <script>
        setTimeout(() => { const b = document.getElementById('toastProgress'); if(b) b.style.width='0%'; }, 100);
        setTimeout(() => closeToast(), 5100);
        function closeToast() {
            const t = document.getElementById('toast-success');
            if(t) { t.style.animation='slideOutRight 0.3s ease forwards'; setTimeout(()=>t.remove(),300); }
        }
    </script>
    @endif

    @if(session('error'))
    <div class="mb-4 p-4 bg-red-50 border-l-4 border-red-500 rounded-xl flex items-center gap-2">
        <i class="fas fa-exclamation-circle text-red-500"></i>
        <p class="text-red-700 text-sm">{{ session('error') }}</p>
    </div>
    @endif


    {{-- Two-column layout --}}
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

        {{-- ===== LEFT COLUMN (2/3) ===== --}}
        <div class="lg:col-span-2 space-y-4">

            {{-- Header card --}}
            <div class="section-card">
                <div class="order-header">
                    <div class="flex items-center justify-between relative z-10">
                        <div class="flex items-center gap-3">
                            <div class="w-11 h-11 bg-white/20 rounded-xl flex items-center justify-center">
                                <i class="fas fa-credit-card text-white text-lg"></i>
                            </div>
                            <div>
                                <h1 class="text-white font-bold text-xl leading-tight">Pembayaran Pesanan Skincare</h1>
                                <p class="text-pink-100 text-xs mt-0.5">Didukung oleh Midtrans</p>
                            </div>
                        </div>
                        <div class="text-right">
                            <div class="kode-chip mb-1">
                                <i class="fas fa-hashtag text-[10px]"></i>
                                {{ $pesanan->kode_pesanan }}
                            </div>
                        </div>
                    </div>
                </div>

                {{-- Polling indicator --}}
                <div id="statusPolling">
                    <div class="flex items-center gap-3">
                        <i class="fas fa-circle-notch text-pink-500 spin"></i>
                        <div>
                            <p class="text-sm font-semibold text-pink-700">Menunggu konfirmasi pembayaran...</p>
                            <p class="text-xs text-pink-500">Status akan diperbarui otomatis</p>
                        </div>
                    </div>
                </div>
            </div>

            {{-- Alamat Pengiriman --}}
            <div class="section-card">
                <div class="section-header">
                    <span class="section-label">
                        <i class="fas fa-map-marker-alt"></i> Alamat Pengiriman
                    </span>
                    <button onclick="openAddressModal()"
                            class="text-xs text-pink-500 font-semibold hover:text-pink-700 flex items-center gap-1.5 transition-colors">
                        <i class="fas fa-edit text-[11px]"></i> Ganti Alamat
                    </button>
                </div>

                <div id="selectedAddressDisplay" class="p-5">
                    @if($selectedAlamat)
                        @include('components.alamat-display', ['alamat' => $selectedAlamat])
                    @else
                        <div class="bg-amber-50 rounded-xl p-5 border border-amber-200 text-center">
                            <div class="w-12 h-12 bg-amber-100 rounded-full flex items-center justify-center mx-auto mb-3">
                                <i class="fas fa-map-marker-alt text-amber-400 text-lg"></i>
                            </div>
                            <p class="text-sm text-amber-700 font-semibold mb-1">Belum ada alamat pengiriman</p>
                            <p class="text-xs text-amber-500 mb-4">Tambahkan alamat sebelum melanjutkan pembayaran</p>
                            <a href="{{ route('user-alamat.create', ['from' => 'checkout']) }}"
                               class="inline-flex items-center gap-2 bg-pink-500 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-pink-600 transition-colors">
                                <i class="fas fa-plus text-xs"></i> Tambah Alamat
                            </a>
                        </div>
                    @endif
                </div>
            </div>

            {{-- Item Pesanan --}}
            <div class="section-card">
                <div class="section-header">
                    <span class="section-label">
                        <i class="fas fa-box"></i> Item Pesanan Skincare
                    </span>
                    <span class="text-xs text-gray-400 font-medium">{{ $pesanan->detail->count() }} produk</span>
                </div>
                <div>
                    @foreach($pesanan->detail as $d)
                    <div class="item-row">
                        <div class="flex items-start gap-3 flex-1 min-w-0">
                            <div class="w-8 h-8 bg-pink-50 rounded-lg flex items-center justify-center flex-shrink-0 mt-0.5">
                                <i class="fas fa-spa text-pink-400 text-xs"></i>
                            </div>
                            <div class="min-w-0">
                                <p class="text-gray-800 font-medium text-sm leading-snug">{{ $d->nama_produk }}</p>
                                <p class="text-gray-400 text-xs mt-0.5">
                                    @if($d->warna){{ $d->warna }}@endif
                                    @if($d->warna && $d->ukuran) · @endif
                                    @if($d->ukuran){{ $d->ukuran }}@endif
                                    · <span class="font-medium">×{{ $d->qty }}</span>
                                </p>
                            </div>
                        </div>
                        <p class="text-gray-800 font-semibold text-sm flex-shrink-0">
                            Rp {{ number_format($d->subtotal, 0, ',', '.') }}
                        </p>
                    </div>
                    @endforeach
                </div>
            </div>

        </div>

        {{-- ===== RIGHT COLUMN (1/3) ===== --}}
        <div class="lg:col-span-1">
            <div class="sidebar-sticky space-y-4">

                {{-- Ringkasan Pembayaran --}}
                <div class="section-card">
                    <div class="section-header">
                        <span class="section-label">
                            <i class="fas fa-receipt"></i> Ringkasan Pembayaran
                        </span>
                    </div>

                    @php
                        $subtotalProduk        = $pesanan->detail->sum(fn($d) => $d->harga * $d->qty);
                        $diskon                = $diskon ?? 0;
                        $subtotalSetelahDiskon = $subtotalSetelahDiskon ?? $subtotalProduk;
                        $keteranganDiskon      = $keteranganDiskon ?? null;
                        $ongkir                = max(0, $pesanan->total_harga - $subtotalSetelahDiskon);
                    @endphp

                    <div>
                        {{-- Subtotal Produk --}}
                        <div class="price-row">
                            <span class="text-gray-500 flex items-center gap-2">
                                <i class="fas fa-box text-pink-400 text-[11px] w-3"></i> Subtotal Produk
                            </span>
                            <span class="font-semibold text-gray-700" id="subtotalDisplay">
                                Rp {{ number_format($subtotalProduk, 0, ',', '.') }}
                            </span>
                        </div>

                        {{-- Diskon --}}
                        <div id="rowDiskon" class="price-row text-emerald-600 {{ $diskon > 0 ? '' : 'hidden' }}">
                            <span class="flex items-center gap-2">
                                <i class="fas fa-tag text-emerald-500 text-[11px] w-3"></i>
                                Diskon
                                <span class="text-gray-400 text-[11px]" id="diskonKetDisplay">
                                    {{ $keteranganDiskon ? '('.$keteranganDiskon.')' : '' }}
                                </span>
                            </span>
                            <span class="font-semibold" id="diskonDisplay">
                                {{ $diskon > 0 ? '- Rp '.number_format($diskon,0,',','.') : '' }}
                            </span>
                        </div>

                        {{-- Subtotal setelah diskon --}}
                        <div id="rowSubtotalAfterDiskon" class="price-row {{ $diskon > 0 ? '' : 'hidden' }}">
                            <span class="text-gray-500 flex items-center gap-2">
                                <i class="fas fa-calculator text-pink-400 text-[11px] w-3"></i> Setelah diskon
                            </span>
                            <span class="font-semibold text-pink-600" id="subtotalSetelahDiskonDisplay">
                                Rp {{ number_format($subtotalSetelahDiskon, 0, ',', '.') }}
                            </span>
                        </div>

                        {{-- Ongkir --}}
                        <div class="price-row">
                            <span class="text-gray-500 flex items-center gap-2">
                                <i class="fas fa-truck text-emerald-400 text-[11px] w-3"></i> Ongkos Kirim
                            </span>
                            <span id="ongkirDisplay" class="font-semibold {{ $ongkir <= 0 ? 'text-emerald-600' : 'text-gray-700' }}">
                                @if($ongkir <= 0)
                                    <i class="fas fa-check-circle text-[11px]"></i> Gratis
                                @else
                                    Rp {{ number_format($ongkir, 0, ',', '.') }}
                                @endif
                            </span>
                        </div>

                        {{-- Detail ongkir --}}
                        @if(!empty($ongkirRincian) && isset($ongkirRincian['detail']))
                        <div id="ongkirDetailBox" class="ongkir-detail mx-4 mb-3">
                            <p class="font-semibold text-pink-700 mb-1 flex items-center gap-1.5">
                                <i class="fas fa-info-circle text-[11px]"></i> Rincian ongkir
                            </p>
                            <p id="ongkirDetailText" class="text-gray-600">{{ $ongkirRincian['detail'] }}</p>
                        </div>
                        @else
                        <div id="ongkirDetailBox" class="ongkir-detail mx-4 mb-3 hidden">
                            <p class="font-semibold text-pink-700 mb-1">Rincian ongkir</p>
                            <p id="ongkirDetailText"></p>
                        </div>
                        @endif

                        {{-- Total --}}
                        <div class="price-row total-row">
                            <span class="font-bold text-gray-700 flex items-center gap-2">
                                <i class="fas fa-money-bill-wave text-pink-500 text-[11px]"></i> Total
                            </span>
                            <div class="text-right">
                                <p class="text-pink-600 font-extrabold text-lg leading-tight" id="totalDisplay">
                                    Rp {{ number_format($pesanan->total_harga, 0, ',', '.') }}
                                </p>
                                <span id="totalFormatted" class="hidden">Rp {{ number_format($pesanan->total_harga, 0, ',', '.') }}</span>
                            </div>
                        </div>
                    </div>
                </div>

                {{-- CTA --}}
                <div class="section-card p-5 space-y-4">

                    @if(!$selectedAlamat)
                    <div class="bg-red-50 border border-red-100 rounded-xl p-3 text-center">
                        <i class="fas fa-exclamation-triangle text-red-400 text-sm mb-1"></i>
                        <p class="text-xs text-red-600 font-semibold">Tambahkan alamat pengiriman terlebih dahulu</p>
                    </div>
                    @endif

                    <div id="snapOpenInfo" class="hidden text-center py-2">
                        <div class="inline-flex items-center gap-2 text-pink-600 font-semibold text-sm">
                            <i class="fas fa-circle-notch fa-spin"></i>
                            <span>Membuka halaman pembayaran...</span>
                        </div>
                    </div>

                    @if($selectedAlamat)
                        <button id="payBtn" onclick="handlePayClick()" class="pay-btn">
                            <i class="fas fa-lock text-sm"></i> Lanjutkan Pembayaran
                        </button>
                    @else
                        <button disabled class="pay-btn" style="background: #d1d5db; box-shadow: none; cursor: not-allowed;">
                            <i class="fas fa-lock text-sm"></i> Lanjutkan Pembayaran
                        </button>
                    @endif

                    <p class="text-xs text-gray-400 text-center flex items-center justify-center gap-1.5">
                        <i class="fas fa-shield-alt text-gray-300"></i> Transaksi aman & terenkripsi oleh Midtrans
                    </p>

                    <div class="pt-3 border-t border-gray-100">
                        <p class="text-[11px] text-gray-400 text-center mb-2.5 font-medium uppercase tracking-wider">Metode Pembayaran</p>
                        <div class="flex flex-wrap gap-1.5 justify-center">
                            @foreach(['💳 Kartu','🏧 Transfer','📱 GoPay','📱 OVO','📱 ShopeePay','📱 Dana','🏪 Alfamart'] as $m)
                            <span class="pay-badge">{{ $m }}</span>
                            @endforeach
                        </div>
                    </div>
                </div>

            </div>
        </div>

    </div>
</div>

{{-- ======================== MODAL PILIH ALAMAT ======================== --}}
<div id="addressModal" class="hidden fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4">
    <div onclick="closeAddressModal()" class="absolute inset-0 bg-black/50 backdrop-blur-sm"></div>

    <div id="modalBox" class="relative bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[85vh] flex flex-col">

        <div class="flex items-center justify-between p-5 border-b border-pink-100">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 bg-pink-100 rounded-xl flex items-center justify-center">
                    <i class="fas fa-map-marker-alt text-pink-500"></i>
                </div>
                <div>
                    <h3 class="font-bold text-gray-800">Pilih Alamat Pengiriman</h3>
                    <p class="text-xs text-gray-400">{{ count($daftarAlamat) }} alamat tersimpan</p>
                </div>
            </div>
            <button onclick="closeAddressModal()" class="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-100 transition-colors">
                <i class="fas fa-times text-gray-500"></i>
            </button>
        </div>

        <div class="overflow-y-auto flex-1 p-5 space-y-3">
            @forelse($daftarAlamat as $alamat)
                @php
                    $alamatLengkap = $alamat->alamat_lengkap ?? '-';
                    $uniqueIdAlamat = 'alamat_modal_' . ($alamat->ID ?? rand(1, 9999));
                    $batasKarakterAlamat = 80;
                    $isLongAlamat = strlen($alamatLengkap) > $batasKarakterAlamat && $alamatLengkap !== '-';
                @endphp
                
                <div class="alamat-card border-2 border-pink-200 rounded-xl p-4 relative {{ $selectedAlamat && $selectedAlamat->ID == $alamat->ID ? 'selected' : '' }}"
                     data-id="{{ $alamat->ID }}"
                     onclick="selectAddress({{ $alamat->ID }}, this)">

                    <div class="check-icon absolute top-3 right-3 w-6 h-6 bg-pink-500 rounded-full items-center justify-center hidden">
                        <i class="fas fa-check text-white text-xs"></i>
                    </div>

                    <div class="flex items-start gap-3 pr-8">
                        <div class="w-9 h-9 bg-pink-50 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
                            <i class="fas fa-home text-pink-400 text-sm"></i>
                        </div>
                        <div class="flex-1 min-w-0">
                            <div class="flex items-center gap-2 flex-wrap">
                                <p class="font-semibold text-gray-800 text-sm">{{ $alamat->nama_penerima }}</p>
                                <span class="text-gray-400 text-xs">{{ $alamat->no_hp }}</span>
                                @if($alamat->alamat_utama)
                                    <span class="px-2 py-0.5 bg-pink-500 text-white text-xs rounded-full font-medium">Utama</span>
                                @endif
                            </div>
                            
                            {{-- Alamat Lengkap dengan fitur baca selengkapnya --}}
                            <div class="mt-1">
                                @if($alamatLengkap !== '-')
                                    <div>
                                        {{-- Versi pendek --}}
                                        <div id="alamat-pendek-{{ $uniqueIdAlamat }}" class="{{ $isLongAlamat ? '' : 'hidden' }}">
                                            <p class="text-sm text-gray-600 leading-relaxed"
                                               style="overflow:hidden; display:-webkit-box; -webkit-line-clamp:1; -webkit-box-orient:vertical; word-break:break-word;">
                                                {{ $alamatLengkap }}
                                            </p>
                                        </div>
                                        {{-- Versi lengkap --}}
                                        <div id="alamat-lengkap-{{ $uniqueIdAlamat }}" class="{{ $isLongAlamat ? 'hidden' : '' }}">
                                            <p class="text-sm text-gray-600 leading-relaxed"
                                               style="word-break: break-word; overflow-wrap: break-word;">
                                                {{ $alamatLengkap }}
                                            </p>
                                        </div>
                                        @if($isLongAlamat)
                                        <button onclick="event.stopPropagation(); toggleAlamatModalAddress('{{ $uniqueIdAlamat }}', this)"
                                                class="mt-1 text-xs font-semibold text-pink-500 hover:text-pink-600 flex items-center gap-1 transition-colors">
                                            <i id="icon-alamat-{{ $uniqueIdAlamat }}" class="fas fa-chevron-down text-[10px]"></i>
                                            <span id="btn-alamat-{{ $uniqueIdAlamat }}">Baca selengkapnya</span>
                                        </button>
                                        @endif
                                    </div>
                                @else
                                    <p class="text-sm text-gray-400">Alamat lengkap tidak tersedia</p>
                                @endif
                            </div>
                            
                            <p class="text-xs text-gray-400 mt-2">
                                <i class="fas fa-location-dot text-pink-400 text-[10px] mr-1"></i>
                                {{ $alamat->village?->name }}, {{ $alamat->district?->name }},
                                {{ $alamat->city?->name }}, {{ $alamat->province?->name }}
                                @if($alamat->kode_pos) – {{ $alamat->kode_pos }} @endif
                            </p>
                        </div>
                    </div>
                </div>
            @empty
                <div class="text-center py-10">
                    <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-3">
                        <i class="fas fa-map-marker-alt text-gray-300 text-2xl"></i>
                    </div>
                    <p class="text-gray-500 font-medium">Belum ada alamat tersimpan</p>
                    <p class="text-gray-400 text-sm mt-1">Tambahkan alamat pengiriman Anda</p>
                </div>
            @endforelse
        </div>

        <div class="p-5 border-t border-pink-100 flex gap-3">
            <a href="{{ route('user-alamat.create', ['from' => 'checkout', 'pesanan_id' => $pesanan->id]) }}"
               class="flex-1 border-2 border-pink-300 text-pink-500 py-3 rounded-xl font-semibold text-sm hover:bg-pink-50 transition-colors flex items-center justify-center gap-2">
                <i class="fas fa-plus text-xs"></i> Alamat Baru
            </a>
            <button onclick="confirmAddress()" id="confirmAddressBtn"
                    class="flex-1 bg-gradient-to-r from-pink-400 to-pink-500 text-white py-3 rounded-xl font-semibold text-sm hover:from-pink-500 hover:to-pink-600 transition-all flex items-center justify-center gap-2">
                <i class="fas fa-check text-xs"></i> Gunakan Alamat Ini
            </button>
        </div>
    </div>
</div>

<script>
function toggleAlamatModalAddress(id, btn) {
    event.stopPropagation();
    const pendekEl = document.getElementById(`alamat-pendek-${id}`);
    const lengkapEl = document.getElementById(`alamat-lengkap-${id}`);
    const iconEl = document.getElementById(`icon-alamat-${id}`);
    const btnText = document.getElementById(`btn-alamat-${id}`);
    
    if (!pendekEl || !lengkapEl) return;
    
    const isExpanded = pendekEl.classList.contains('hidden');
    
    if (isExpanded) {
        // Sembunyikan - tampilkan 1 baris
        pendekEl.classList.remove('hidden');
        lengkapEl.classList.add('hidden');
        if (iconEl) {
            iconEl.classList.remove('fa-chevron-up');
            iconEl.classList.add('fa-chevron-down');
        }
        if (btnText) btnText.textContent = 'Baca selengkapnya';
    } else {
        // Tampilkan lengkap
        pendekEl.classList.add('hidden');
        lengkapEl.classList.remove('hidden');
        if (iconEl) {
            iconEl.classList.remove('fa-chevron-down');
            iconEl.classList.add('fa-chevron-up');
        }
        if (btnText) btnText.textContent = 'Sembunyikan';
    }
}
</script>

{{-- Hidden inputs --}}
<input type="hidden" id="snapToken"        value="{{ $snapToken }}">
<input type="hidden" id="pesananId"        value="{{ $pesanan->id }}">
<input type="hidden" id="checkUrl"         value="{{ route('pembayaran.check', $pesanan->id) }}">
<input type="hidden" id="showUrl"          value="{{ route('pesanan.show', $pesanan->id) }}">
<input type="hidden" id="saveAlamatUrl"    value="{{ route('pembayaran.saveAlamat', $pesanan->id) }}">
<input type="hidden" id="selectedAlamatId" value="{{ $selectedAlamat?->ID ?? '' }}">
<meta name="csrf-token" content="{{ csrf_token() }}">

<script>
let pollingInterval = null;
let pollingCount    = 0;
const MAX_POLLS     = 120;
let tempSelectedId  = document.getElementById('selectedAlamatId').value || null;

function openAddressModal() {
    document.getElementById('addressModal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
    document.querySelectorAll('.alamat-card').forEach(c => {
        c.classList.toggle('selected', c.dataset.id == tempSelectedId);
    });
}

function closeAddressModal() {
    document.getElementById('addressModal').classList.add('hidden');
    document.body.style.overflow = '';
}

function selectAddress(id, el) {
    document.querySelectorAll('.alamat-card').forEach(c => c.classList.remove('selected'));
    el.classList.add('selected');
    tempSelectedId = id;
}

function confirmAddress() {
    if (!tempSelectedId) { alert('Pilih alamat terlebih dahulu'); return; }

    const btn = document.getElementById('confirmAddressBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> Menyimpan...';

    fetch(document.getElementById('saveAlamatUrl').value, {
        method : 'POST',
        headers: {
            'Content-Type' : 'application/json',
            'X-CSRF-TOKEN'  : document.querySelector('meta[name="csrf-token"]').content,
            'Accept'        : 'application/json',
        },
        body: JSON.stringify({ alamat_id: tempSelectedId }),
    })
    .then(r => r.json())
    .then(data => {
        if (!data.success) { alert('Gagal menyimpan alamat: ' + (data.message || 'Unknown error')); return; }
        if (data.snap_token) document.getElementById('snapToken').value = data.snap_token;
        document.getElementById('selectedAddressDisplay').innerHTML = data.html;
        document.getElementById('selectedAlamatId').value = tempSelectedId;
        setText('totalDisplay',   data.total_formatted);
        setText('totalFormatted', data.total_formatted);
        setText('subtotalDisplay', data.subtotal_produk_formatted);
        updateDiskonDisplay(data);
        updateOngkirDisplay(data);
        closeAddressModal();
    })
    .catch(err => { console.error(err); alert('Terjadi kesalahan. Coba lagi.'); })
    .finally(() => {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-check text-xs"></i> Gunakan Alamat Ini';
    });
}

function updateDiskonDisplay(data) {
    const rowDiskon   = document.getElementById('rowDiskon');
    const rowSubAfter = document.getElementById('rowSubtotalAfterDiskon');
    if (data.diskon && data.diskon > 0) {
        rowDiskon?.classList.remove('hidden');
        const ketEl = document.getElementById('diskonKetDisplay');
        const valEl = document.getElementById('diskonDisplay');
        if (ketEl) ketEl.textContent = data.diskon_keterangan ? `(${data.diskon_keterangan})` : '';
        if (valEl) valEl.textContent = data.diskon_formatted;
        rowSubAfter?.classList.remove('hidden');
        const el = document.getElementById('subtotalSetelahDiskonDisplay');
        if (el) el.textContent = data.total_setelah_diskon_formatted;
    } else {
        rowDiskon?.classList.add('hidden');
        rowSubAfter?.classList.add('hidden');
    }
}

function updateOngkirDisplay(data) {
    const ongkirDisplay    = document.getElementById('ongkirDisplay');
    const ongkirDetailBox  = document.getElementById('ongkirDetailBox');
    const ongkirDetailText = document.getElementById('ongkirDetailText');
    if (ongkirDisplay) {
        if (data.ongkir && data.ongkir > 0) {
            ongkirDisplay.className   = 'font-semibold text-gray-700';
            ongkirDisplay.textContent = data.ongkir_formatted;
        } else {
            ongkirDisplay.className  = 'font-semibold text-emerald-600';
            ongkirDisplay.innerHTML  = '<i class="fas fa-check-circle text-xs"></i> Gratis';
        }
    }
    if (ongkirDetailBox && ongkirDetailText) {
        if (data.ongkir_detail) {
            ongkirDetailText.textContent = data.ongkir_detail;
            ongkirDetailBox.classList.remove('hidden');
        } else {
            ongkirDetailBox.classList.add('hidden');
        }
    }
}

function setText(id, value) {
    const el = document.getElementById(id);
    if (el && value !== undefined && value !== null) el.textContent = value;
}

function handlePayClick() {
    if (!document.getElementById('selectedAlamatId').value) { openAddressModal(); return; }
    openSnap();
}

function openSnap() {
    const token  = document.getElementById('snapToken').value;
    const payBtn = document.getElementById('payBtn');
    const info   = document.getElementById('snapOpenInfo');
    const poll   = document.getElementById('statusPolling');
    payBtn.classList.add('hidden');
    info.classList.remove('hidden');
    snap.pay(token, {
        onSuccess: function () { info.classList.add('hidden'); poll.style.display='block'; startPolling(); setTimeout(checkPaymentStatus, 1000); },
        onPending: function () { info.classList.add('hidden'); poll.style.display='block'; payBtn.classList.remove('hidden'); startPolling(); },
        onError:   function () { info.classList.add('hidden'); payBtn.classList.remove('hidden'); alert('Terjadi kesalahan pada pembayaran. Silakan coba lagi.'); },
        onClose:   function () { info.classList.add('hidden'); payBtn.classList.remove('hidden'); poll.style.display='block'; startPolling(); },
    });
}

function startPolling() {
    if (pollingInterval) return;
    pollingCount    = 0;
    pollingInterval = setInterval(checkPaymentStatus, 3000);
}

function stopPolling() {
    if (pollingInterval) { clearInterval(pollingInterval); pollingInterval = null; }
}

function checkPaymentStatus() {
    if (++pollingCount > MAX_POLLS) { stopPolling(); return; }
    fetch(document.getElementById('checkUrl').value, {
        headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }
    })
    .then(r => r.json())
    .then(data => {
        const showUrl = document.getElementById('showUrl').value;
        if (data.status === 'paid')   { stopPolling(); window.location.href = showUrl + '?payment=success'; }
        if (data.status === 'failed' || data.pesanan === 'dibatalkan') { stopPolling(); window.location.href = showUrl + '?payment=failed'; }
    })
    .catch(err => console.error('Polling error:', err));
}

document.addEventListener('DOMContentLoaded', function () {
    if (!document.getElementById('selectedAlamatId').value) return;
    fetch(document.getElementById('checkUrl').value, {
        headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }
    })
    .then(r => r.json())
    .then(data => {
        const showUrl = document.getElementById('showUrl').value;
        if (data.status === 'paid')   window.location.href = showUrl + '?payment=success';
        if (data.status === 'failed') window.location.href = showUrl + '?payment=failed';
    })
    .catch(err => console.error('Init check error:', err));
});

document.addEventListener('keydown', e => { if (e.key === 'Escape') closeAddressModal(); });
</script>

</body>
</html>