<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pembayaran - Raja Futsal</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&display=swap" rel="stylesheet">

    
    <?php if($isProduction): ?>
        <script src="https://app.midtrans.com/snap/snap.js" data-client-key="<?php echo e($clientKey); ?>"></script>
    <?php else: ?>
        <script src="https://app.sandbox.midtrans.com/snap/snap.js" data-client-key="<?php echo e($clientKey); ?>"></script>
    <?php endif; ?>

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

        body { background: #f8f7f4; }

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

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

        .section-header {
            padding: 16px 20px;
            border-bottom: 1px solid #f5f2ee;
            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: #f97316; font-size: 11px; }

        /* Order header gradient */
        .order-header {
            background: linear-gradient(135deg, #f97316 0%, #ea580c 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 #f8f5f0; }
        .price-row.total-row {
            background: #fff9f5;
            padding: 14px 20px;
            border-top: 2px solid #fed7aa;
        }

        /* 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 #f8f5f0; }

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

        /* Pay button */
        .pay-btn {
            background: linear-gradient(135deg, #f97316, #ea580c);
            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(249,115,22,0.35);
        }
        .pay-btn:hover { transform: translateY(-1px); box-shadow: 0 6px 24px rgba(249,115,22,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: #f3f4f6;
            border-radius: 8px;
            font-size: 12px;
            color: #6b7280;
            font-weight: 500;
        }

        /* 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: #f97316; box-shadow: 0 0 0 3px rgba(249,115,22,0.12); }
        .alamat-card.selected { border-color: #f97316; background-color: #fff7ed; box-shadow: 0 0 0 3px rgba(249,115,22,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: #fff9f0;
            border: 1px dashed #fed7aa;
            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: #f97316; }

        /* 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;
        }
    </style>
</head>
<body class="min-h-screen py-8" data-no-image="<?php echo e(asset('images/no-image.png')); ?>">

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

    <!-- TOAST NOTIFICATION -->
    <?php if(session('success') || session('error')): ?>
    <div id="toast-notification"
        class="fixed bottom-6 right-6 z-50 flex items-center gap-3 bg-white border <?php echo e(session('success') ? 'border-green-200' : 'border-red-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 <?php echo e(session('success') ? 'bg-green-500' : 'bg-red-500'); ?> rounded-xl flex items-center justify-center flex-shrink-0">
            <i class="fas <?php echo e(session('success') ? 'fa-check' : 'fa-exclamation'); ?> text-white text-sm"></i>
        </div>
        <div class="flex-1 min-w-0">
            <p class="toast-title font-semibold text-gray-800 text-sm"><?php echo e(session('success') ? 'Berhasil!' : 'Gagal!'); ?></p>
            <p class="toast-message text-gray-500 text-xs mt-0.5 truncate"><?php echo e(session('success') ?? session('error')); ?></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 <?php echo e(session('success') ? 'bg-green-500' : 'bg-red-500'); ?> rounded-b-2xl" id="toastProgress"
            style="width: 100%; transition: width 5s linear;"></div>
    </div>

    <style>
    @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); }
    }
    </style>

    <script>
        setTimeout(() => {
            const bar = document.getElementById('toastProgress');
            if (bar) bar.style.width = '0%';
        }, 100);
        setTimeout(() => closeToast(), 5100);
        function closeToast() {
            const toast = document.getElementById('toast-notification');
            if (toast) {
                toast.style.animation = 'slideOutRight 0.3s ease forwards';
                setTimeout(() => toast.remove(), 300);
            }
        }
    </script>
    <?php endif; ?>


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

        
        <div class="lg:col-span-2 space-y-4">

            
            <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</h1>
                                <p class="text-orange-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>
                                <?php echo e($pesanan->kode_pesanan); ?>

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

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

            
            <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-orange-500 font-semibold hover:text-orange-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">
                    <?php if($selectedAlamat): ?>
                        <?php echo $__env->make('components.alamat-display', ['alamat' => $selectedAlamat], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                    <?php 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="<?php echo e(route('user-alamat.create', ['from' => 'checkout'])); ?>"
                               class="inline-flex items-center gap-2 bg-orange-500 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-orange-600 transition-colors">
                                <i class="fas fa-plus text-xs"></i> Tambah Alamat
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            
            <div class="section-card">
                <div class="section-header">
                    <span class="section-label">
                        <i class="fas fa-box"></i> Item Pesanan
                    </span>
                    <span class="text-xs text-gray-400 font-medium"><?php echo e($pesanan->detail->count()); ?> produk</span>
                </div>
                <div>
                    <?php $__currentLoopData = $pesanan->detail; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $d): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <div class="item-row">
                        <div class="flex items-start gap-3 flex-1 min-w-0">
                    <?php
                        $fotoProduk = null;
                        $warnaItem  = strtolower(trim($d->warna ?? ''));

                        if ($d->produk && $d->produk->foto) {
                            foreach (explode('|', $d->produk->foto) as $fotoItem) {
                                $fotoItem = trim($fotoItem);
                                if (str_contains($fotoItem, ':')) {
                                    [$warnaFoto, $pathFoto] = explode(':', $fotoItem, 2);
                                    if (strtolower(trim($warnaFoto)) === $warnaItem && trim($pathFoto)) {
                                        $fotoProduk = trim($pathFoto);
                                        break;
                                    }
                                }
                            }
                            // Jika tidak ada foto yang cocok dengan warna, pakai foto pertama
                            if (!$fotoProduk) {
                                $firstItem = trim(explode('|', $d->produk->foto)[0]);
                                $fotoProduk = str_contains($firstItem, ':')
                                    ? trim(explode(':', $firstItem, 2)[1])
                                    : $firstItem;
                            }
                        }
                    ?>

                    <div class="w-12 h-12 rounded-lg overflow-hidden flex-shrink-0 mt-0.5 border border-gray-100 bg-gray-50">
                        <?php if($fotoProduk): ?>
                            <img src="<?php echo e(asset('storage/' . $fotoProduk)); ?>"
                                alt="<?php echo e($d->nama_produk); ?>"
                                class="w-full h-full object-contain p-0.5"
                                onerror="this.onerror=null; this.src=document.body.dataset.noImage">
                        <?php else: ?>
                            <div class="w-full h-full flex items-center justify-center">
                                <i class="fas fa-tshirt text-orange-300 text-sm"></i>
                            </div>
                        <?php endif; ?>
                    </div>
                            <div class="min-w-0">
                                <p class="text-gray-800 font-medium text-sm leading-snug"><?php echo e($d->nama_produk); ?></p>
                                <p class="text-gray-400 text-xs mt-0.5">
                                    <?php if($d->warna): ?><?php echo e($d->warna); ?><?php endif; ?>
                                    <?php if($d->warna && $d->ukuran): ?> · <?php endif; ?>
                                    <?php if($d->ukuran): ?><?php echo e($d->ukuran); ?><?php endif; ?>
                                    · <span class="font-medium">×<?php echo e($d->qty); ?></span>
                                </p>
                            </div>
                        </div>
                        <p class="text-gray-800 font-semibold text-sm flex-shrink-0">
                            Rp <?php echo e(number_format($d->subtotal, 0, ',', '.')); ?>

                        </p>
                    </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </div>
            </div>

        </div>

        
        <div class="lg:col-span-1">
            <div class="sidebar-sticky space-y-4">

                
                <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);
                    ?>

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

                            </span>
                        </div>

                        
                        <div id="rowDiskon" class="price-row text-emerald-600 <?php echo e($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">
                                    <?php echo e($keteranganDiskon ? '('.$keteranganDiskon.')' : ''); ?>

                                </span>
                            </span>
                            <span class="font-semibold" id="diskonDisplay">
                                <?php echo e($diskon > 0 ? '- Rp '.number_format($diskon,0,',','.') : ''); ?>

                            </span>
                        </div>

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

                            </span>
                        </div>

                        
                        <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 <?php echo e($ongkir <= 0 ? 'text-emerald-600' : 'text-gray-700'); ?>">
                                <?php if($ongkir <= 0): ?>
                                    <i class="fas fa-check-circle text-[11px]"></i> Gratis
                                <?php else: ?>
                                    Rp <?php echo e(number_format($ongkir, 0, ',', '.')); ?>

                                <?php endif; ?>
                            </span>
                        </div>

                        
                        <?php if(!empty($ongkirRincian) && isset($ongkirRincian['detail'])): ?>
                        <div id="ongkirDetailBox" class="ongkir-detail mx-4 mb-3">
                            <p class="font-semibold text-orange-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"><?php echo e($ongkirRincian['detail']); ?></p>
                        </div>
                        <?php else: ?>
                        <div id="ongkirDetailBox" class="ongkir-detail mx-4 mb-3 hidden">
                            <p class="font-semibold text-orange-700 mb-1">Rincian ongkir</p>
                            <p id="ongkirDetailText"></p>
                        </div>
                        <?php endif; ?>

                        
                        <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-orange-500 text-[11px]"></i> Total
                            </span>
                            <div class="text-right">
                                <p class="text-orange-600 font-extrabold text-lg leading-tight" id="totalDisplay">
                                    Rp <?php echo e(number_format($pesanan->total_harga, 0, ',', '.')); ?>

                                </p>
                                <span id="totalFormatted" class="hidden">Rp <?php echo e(number_format($pesanan->total_harga, 0, ',', '.')); ?></span>
                            </div>
                        </div>
                    </div>
                </div>

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

                    <?php 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>
                    <?php endif; ?>

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

                    <?php if($selectedAlamat): ?>
                        <button id="payBtn" onclick="handlePayClick()" class="pay-btn">
                            <i class="fas fa-lock text-sm"></i> Lanjutkan Pembayaran
                        </button>
                    <?php 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>
                    <?php 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">
                            <?php $__currentLoopData = ['💳 Kartu','🏧 Transfer','📱 GoPay','📱 OVO','📱 ShopeePay','📱 Dana','🏪 Alfamart']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $m): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <span class="pay-badge"><?php echo e($m); ?></span>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>
                    </div>
                </div>

            </div>
        </div>

    </div>
</div>


<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-gray-100">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 bg-orange-100 rounded-xl flex items-center justify-center">
                    <i class="fas fa-map-marker-alt text-orange-500"></i>
                </div>
                <div>
                    <h3 class="font-bold text-gray-800">Pilih Alamat Pengiriman</h3>
                    <p class="text-xs text-gray-400"><?php echo e(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">
            <?php $__empty_1 = true; $__currentLoopData = $daftarAlamat; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $alamat): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                <?php
                    $alamatLengkap = $alamat->alamat_lengkap ?? '-';
                    $uniqueIdAlamat = 'alamat_modal_' . ($alamat->ID ?? rand(1, 9999));
                    $batasKarakterAlamat = 80;
                    $isLongAlamat = strlen($alamatLengkap) > $batasKarakterAlamat && $alamatLengkap !== '-';
                ?>
                
                <div class="alamat-card border-2 border-gray-200 rounded-xl p-4 relative <?php echo e($selectedAlamat && $selectedAlamat->ID == $alamat->ID ? 'selected' : ''); ?>"
                     data-id="<?php echo e($alamat->ID); ?>"
                     onclick="selectAddress(this.dataset.id, this)">

                    <div class="check-icon absolute top-3 right-3 w-6 h-6 bg-orange-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-orange-50 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
                            <i class="fas fa-home text-orange-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"><?php echo e($alamat->nama_penerima); ?></p>
                                <span class="text-gray-400 text-xs"><?php echo e($alamat->no_hp); ?></span>
                                <?php if($alamat->alamat_utama): ?>
                                    <span class="px-2 py-0.5 bg-orange-500 text-white text-xs rounded-full font-medium">Utama</span>
                                <?php endif; ?>
                            </div>
                            
                            
                            <div class="mt-1">
                                <?php if($alamatLengkap !== '-'): ?>
                                    <div>
                                        
                                        <div id="alamat-pendek-<?php echo e($uniqueIdAlamat); ?>" class="<?php echo e($isLongAlamat ? '' : 'hidden'); ?>">
                                            <p class="text-sm text-gray-600 leading-relaxed"
                                               style="overflow:hidden; display:-webkit-box; -webkit-line-clamp:1; line-clamp:1; -webkit-box-orient:vertical; word-break:break-word;">
                                                <?php echo e($alamatLengkap); ?>

                                            </p>
                                        </div>
                                        
                                        <div id="alamat-lengkap-<?php echo e($uniqueIdAlamat); ?>" class="<?php echo e($isLongAlamat ? 'hidden' : ''); ?>">
                                            <p class="text-sm text-gray-600 leading-relaxed"
                                               style="word-break: break-word; overflow-wrap: break-word;">
                                                <?php echo e($alamatLengkap); ?>

                                            </p>
                                        </div>
                                        <?php if($isLongAlamat): ?>
                                        <button data-unique-id="<?php echo e($uniqueIdAlamat); ?>"
                                                onclick="event.stopPropagation(); toggleAlamatModalAddress(this.dataset.uniqueId, this)"
                                                class="mt-1 text-xs font-semibold text-orange-500 hover:text-orange-600 flex items-center gap-1 transition-colors">
                                            <i id="icon-alamat-<?php echo e($uniqueIdAlamat); ?>" class="fas fa-chevron-down text-[10px]"></i>
                                            <span id="btn-alamat-<?php echo e($uniqueIdAlamat); ?>">Baca selengkapnya</span>
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                <?php else: ?>
                                    <p class="text-sm text-gray-400">Alamat lengkap tidak tersedia</p>
                                <?php endif; ?>
                            </div>
                            
                            <p class="text-xs text-gray-400 mt-2">
                                <i class="fas fa-location-dot text-orange-400 text-[10px] mr-1"></i>
                                <?php echo e($alamat->village?->name); ?>, <?php echo e($alamat->district?->name); ?>,
                                <?php echo e($alamat->city?->name); ?>, <?php echo e($alamat->province?->name); ?>

                                <?php if($alamat->kode_pos): ?> – <?php echo e($alamat->kode_pos); ?> <?php endif; ?>
                            </p>
                        </div>
                    </div>
                </div>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                <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>
            <?php endif; ?>
        </div>

        <div class="p-5 border-t border-gray-100 flex gap-3">
            <a href="<?php echo e(route('user-alamat.create', ['from' => 'checkout', 'pesanan_id' => $pesanan->id])); ?>"
               class="flex-1 border-2 border-orange-300 text-orange-500 py-3 rounded-xl font-semibold text-sm hover:bg-orange-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-orange-500 to-orange-600 text-white py-3 rounded-xl font-semibold text-sm hover:from-orange-600 hover:to-orange-700 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>


<input type="hidden" id="snapToken"        value="<?php echo e($snapToken); ?>">
<input type="hidden" id="pesananId"        value="<?php echo e($pesanan->id); ?>">
<input type="hidden" id="checkUrl"         value="<?php echo e(route('pembayaran.check', $pesanan->id)); ?>">
<input type="hidden" id="showUrl"          value="<?php echo e(route('pesanan.show', $pesanan->id)); ?>">
<input type="hidden" id="saveAlamatUrl"    value="<?php echo e(route('pembayaran.saveAlamat', $pesanan->id)); ?>">
<input type="hidden" id="selectedAlamatId" value="<?php echo e($selectedAlamat?->ID ?? ''); ?>">
<meta name="csrf-token" content="<?php echo e(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';
    fetch(document.getElementById('checkUrl').value, {
        headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }
    })
    .then(r => r.json())
    .then(() => {
        window.location.href = document.getElementById('showUrl').value + '?payment=success';
    })
    .catch(() => {
        window.location.href = document.getElementById('showUrl').value + '?payment=success';
    });
},        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><?php /**PATH C:\laragon\www\ecommerce\resources\views/pembayaran/create.blade.php ENDPATH**/ ?>