<?php $__env->startSection('content'); ?>

<style>
/* =========================
   ANIMATION & BASE
========================= */
.fade-section {
    opacity: 0;
    transform: translateY(20px);
    filter: blur(8px);
    transition: all 0.6s cubic-bezier(0.16, 1, 0.3, 1);
}
.fade-section.show {
    opacity: 1;
    transform: translateY(0);
    filter: blur(0);
}

/* =========================
   CARDS & CONTAINERS
========================= */
.modern-card {
    background: #ffffff;
    border: 1px solid rgba(226, 232, 240, 0.9);
    border-radius: 20px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px -2px rgba(0, 0, 0, 0.02);
    transition: all 0.25s ease;
}

.modern-card:hover {
    box-shadow: 0 10px 25px -5px rgba(15, 23, 42, 0.05);
    border-color: rgba(203, 213, 225, 1);
}

/* =========================
   INPUT & BUTTON
========================= */
.input-modern {
    width: 100%;
    height: 48px;
    border-radius: 14px;
    border: 1px solid #e2e8f0;
    background: #f8fafc;
    padding: 0 16px;
    font-weight: 600;
    color: #0f172a;
    transition: all 0.2s ease;
    outline: none;
}

.input-modern:focus {
    background: #ffffff;
    border-color: #2563eb;
    box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.1);
}

.btn-primary {
    width: 100%;
    height: 48px;
    border-radius: 14px;
    background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
    color: #ffffff;
    font-weight: 700;
    font-size: 0.95rem;
    transition: all 0.25s ease;
    box-shadow: 0 4px 12px rgba(37, 99, 235, 0.25);
}

.btn-primary:hover {
    transform: translateY(-1px);
    box-shadow: 0 8px 20px rgba(37, 99, 235, 0.35);
}

.btn-primary:disabled {
    opacity: 0.7;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
}

/* =========================
   STEP TOGGLE
========================= */
.step-box {
    display: none;
}

.step-box.show {
    display: block;
    animation: fadeDown 0.25s cubic-bezier(0.16, 1, 0.3, 1);
}

@keyframes fadeDown {
    from {
        opacity: 0;
        transform: translateY(-10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* =========================
   TABLE & BADGE
========================= */
.table-modern tbody tr {
    border-bottom: 1px solid #f1f5f9;
    transition: background-color 0.2s ease;
}

.table-modern tbody tr:hover {
    background: #f8fafc;
}

.status-badge {
    padding: 4px 10px;
    border-radius: 999px;
    font-size: 0.75rem;
    font-weight: 700;
    display: inline-block;
}

/* =========================
   PAGINATION
========================= */
.pagination-btn,
.pagination-active,
.pagination-disabled {
    width: 38px;
    height: 38px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    font-size: 0.875rem;
    transition: all 0.2s ease;
}

.pagination-btn {
    background: #ffffff;
    border: 1px solid #e2e8f0;
    color: #334155;
}

.pagination-btn:hover {
    background: #eff6ff;
    border-color: #bfdbfe;
    color: #2563eb;
}

.pagination-active {
    background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
    color: #ffffff;
    box-shadow: 0 4px 12px rgba(37, 99, 235, 0.25);
}

.pagination-disabled {
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    color: #94a3b8;
    cursor: not-allowed;
}

/* =========================
   MODAL
========================= */
@keyframes fadeInSoft {
    0% {
        opacity: 0;
        transform: scale(0.95) translateY(10px);
    }
    100% {
        opacity: 1;
        transform: scale(1) translateY(0);
    }
}

.animate-fade-soft {
    animation: fadeInSoft 0.25s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}
</style>

<main class="space-y-6 font-['Inter',sans-serif]">

    <!-- 💡 SECTION 1: LANGKAH DEPOSIT ACCORDION -->
    <section class="fade-section">
        <div class="modern-card overflow-hidden">
            <button
                onclick="toggleSteps()"
                class="w-full px-5 py-4 flex items-center justify-between hover:bg-slate-50 transition-colors duration-200">
                <div class="flex items-center gap-3.5">
                    <div class="w-10 h-10 rounded-xl bg-blue-50 text-blue-600 border border-blue-100 flex items-center justify-center shrink-0">
                        <span class="material-symbols-outlined text-[22px]">info</span>
                    </div>
                    <div class="text-left">
                        <h2 class="font-bold text-slate-900 text-sm sm:text-base">Panduan & Langkah Deposit</h2>
                        <p class="text-xs text-slate-500 mt-0.5">Klik di sini untuk membaca petunjuk pembayaran QRIS</p>
                    </div>
                </div>

                <span id="stepArrow" class="material-symbols-outlined text-slate-400 transition-transform duration-300 text-[22px]">
                    expand_more
                </span>
            </button>

            <div id="stepContent" class="step-box border-t border-slate-100">
                <div class="p-4 sm:p-5 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 bg-slate-50/50">
                    <div class="bg-white border border-slate-200/80 rounded-xl p-3.5 shadow-sm">
                        <div class="text-blue-600 font-extrabold text-xs mb-1">LANGKAH 1</div>
                        <p class="text-xs text-slate-600 leading-relaxed">
                            Masukkan nominal deposit (Min. Rp 5.000, Maks. Rp 10.000.000).
                        </p>
                    </div>

                    <div class="bg-white border border-slate-200/80 rounded-xl p-3.5 shadow-sm">
                        <div class="text-blue-600 font-extrabold text-xs mb-1">LANGKAH 2</div>
                        <p class="text-xs text-slate-600 leading-relaxed">
                            Sistem secara otomatis akan memilih metode pembayaran QRIS Instan.
                        </p>
                    </div>

                    <div class="bg-white border border-slate-200/80 rounded-xl p-3.5 shadow-sm">
                        <div class="text-blue-600 font-extrabold text-xs mb-1">LANGKAH 3</div>
                        <p class="text-xs text-slate-600 leading-relaxed">
                            Klik tombol "Bayar" lalu scan QRIS dengan E-Wallet atau M-Banking.
                        </p>
                    </div>

                    <div class="bg-white border border-slate-200/80 rounded-xl p-3.5 shadow-sm">
                        <div class="text-blue-600 font-extrabold text-xs mb-1">LANGKAH 4</div>
                        <p class="text-xs text-slate-600 leading-relaxed">
                            Saldo otomatis bertambah segera setelah pembayaran terkonfirmasi.
                        </p>
                    </div>

                    <div class="bg-white border border-slate-200/80 rounded-xl p-3.5 shadow-sm">
                        <div class="text-blue-600 font-extrabold text-xs mb-1">LANGKAH 5</div>
                        <p class="text-xs text-slate-600 leading-relaxed">
                            Selesaikan transaksi sebelum sisa waktu timer QRIS habis.
                        </p>
                    </div>

                    <div onclick="toggleVideoDeposit()" class="bg-white border border-blue-200 hover:border-blue-400 rounded-xl p-3.5 shadow-sm cursor-pointer transition-all duration-200 group">
                        <div class="flex items-center gap-1.5 mb-1 text-slate-900 font-bold text-xs">
                            <span class="material-symbols-outlined text-[16px] text-red-500">play_circle</span>
                            <span>Video Tutorial Deposit</span>
                        </div>
                        <p class="text-xs text-blue-600 font-medium group-hover:underline flex items-center gap-1">
                            Klik untuk menonton panduan
                        </p>

                        <!-- Hidden Video Modal Container -->
                        <div id="videoDeposit" class="hidden mt-3 flex justify-center">
                            <iframe
                                width="100%"
                                height="220"
                                data-src="https://www.youtube.com/embed/ijLz3nZbztU"
                                class="rounded-lg border border-slate-200"
                                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                                referrerpolicy="strict-origin-when-cross-origin"
                                allowfullscreen>
                            </iframe>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- 💳 SECTION 2: FORM & HISTORI DEPOSIT -->
    <section class="grid grid-cols-1 lg:grid-cols-12 gap-5">

        <!-- FORM INPUT DEPOSIT -->
        <div class="lg:col-span-5 xl:col-span-4 fade-section">
            <div class="modern-card p-5 sm:p-6 h-full flex flex-col justify-between">
                <div>
                    <div class="flex items-center gap-3.5 mb-6">
                        <div class="w-12 h-12 rounded-2xl bg-blue-50 text-blue-600 border border-blue-100 flex items-center justify-center shrink-0">
                            <span class="material-symbols-outlined text-[24px]">add_card</span>
                        </div>
                        <div>
                            <h2 class="text-base sm:text-lg font-bold text-slate-900">Form Isi Saldo</h2>
                            <p class="text-xs text-slate-500 mt-0.5">Isi ulang saldo akun secara instan</p>
                        </div>
                    </div>
                    
                    <form id="depositForm" class="space-y-4">
                        <?php echo csrf_field(); ?>
                        <div>
                            <label class="block text-xs font-bold text-slate-700 mb-2 uppercase tracking-wider">
                                Nominal Deposit
                            </label>
                            <div class="relative flex items-center">
                                <span class="absolute left-3.5 top-1/2 -translate-y-1/2 font-bold text-slate-400 text-sm pointer-events-none z-10">
                                    Rp
                                </span>
                                <input
                                    type="number"
                                    name="amount"
                                    id="amount"
                                    min="5000"
                                    required
                                    placeholder="5000"
                                    class="input-modern !pl-12 text-sm"
                                >
                            </div>
                            <p class="text-[11px] text-slate-400 mt-1.5">Minimal deposit sebesar Rp 5.000</p>
                        </div>

                        <!-- HIDDEN METHOD -->
                        <input type="hidden" name="method" id="method" value="qris">

                        <button id="btnDepositSubmit" type="submit" class="btn-primary mt-2 flex items-center justify-center gap-2">
                            <span class="material-symbols-outlined text-[20px]">qr_code_scanner</span>
                            <span>Bayar Sekarang</span>
                        </button>
                    </form>
                </div>

                <div class="mt-6 pt-4 border-t border-slate-100 flex items-center justify-between text-xs text-slate-500">
                    <span class="flex items-center gap-1">
                        <span class="material-symbols-outlined text-[16px] text-emerald-500">verified_user</span>
                        Proses Otomatis 24/7
                    </span>
                    <span class="font-semibold text-slate-700">QRIS All Payment</span>
                </div>
            </div>
        </div>

        <!-- RIWAYAT DEPOSIT TABLE -->
        <div class="lg:col-span-7 xl:col-span-8 fade-section">
            <div class="modern-card overflow-hidden h-full flex flex-col justify-between">
                <div>
                    <div class="px-5 py-4 border-b border-slate-100 flex items-center justify-between">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 rounded-xl bg-indigo-50 text-indigo-600 border border-indigo-100 flex items-center justify-center shrink-0">
                                <span class="material-symbols-outlined text-[20px]">history</span>
                            </div>
                            <div>
                                <h2 class="text-sm sm:text-base font-bold text-slate-900">Riwayat Deposit</h2>
                                <p class="text-xs text-slate-500">Daftar transaksi deposit akun kamu</p>
                            </div>
                        </div>
                    </div>

                    <div class="overflow-x-auto">
                        <table class="w-full min-w-[600px] table-modern text-left">
                            <thead class="bg-slate-50/80 border-b border-slate-100">
                                <tr>
                                    <th class="px-5 py-3 text-xs font-bold text-slate-500 uppercase tracking-wider">Tanggal</th>
                                    <th class="px-5 py-3 text-xs font-bold text-slate-500 uppercase tracking-wider">TRX ID</th>
                                    <th class="px-5 py-3 text-right text-xs font-bold text-slate-500 uppercase tracking-wider">Nominal</th>
                                    <th class="px-5 py-3 text-center text-xs font-bold text-slate-500 uppercase tracking-wider">Status</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 text-xs">
                                <?php $__empty_1 = true; $__currentLoopData = $deposits; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $d): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                <tr>
                                    <td class="px-5 py-3.5 text-slate-600 font-medium whitespace-nowrap">
                                        <?php echo e($d->created_at->format('d/m/Y H:i')); ?>

                                    </td>
                                    <td class="px-5 py-3.5 font-mono font-semibold text-blue-600">
                                        <?php echo e($d->trx_id); ?>

                                    </td>
                                    <td class="px-5 py-3.5 text-right font-bold text-slate-900 whitespace-nowrap">
                                        Rp <?php echo e(number_format($d->amount,0,',','.')); ?>

                                    </td>
                                    <td class="px-5 py-3.5 text-center whitespace-nowrap">
                                        <?php if($d->status == 'PAID'): ?>
                                            <span class="status-badge bg-emerald-50 text-emerald-600 border border-emerald-200/60">
                                                PAID
                                            </span>
                                        <?php elseif($d->status == 'PENDING'): ?>
                                            <span class="status-badge bg-amber-50 text-amber-600 border border-amber-200/60 animate-pulse">
                                                PENDING
                                            </span>
                                        <?php elseif($d->status == 'CANCELED'): ?>
                                            <span class="status-badge bg-slate-100 text-slate-500 border border-slate-200/60">
                                                CANCELED
                                            </span>
                                        <?php else: ?>
                                            <span class="status-badge bg-rose-50 text-rose-600 border border-rose-200/60">
                                                <?php echo e($d->status); ?>

                                            </span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                <tr>
                                    <td colspan="4" class="py-12 text-center">
                                        <div class="flex flex-col items-center justify-center">
                                            <div class="w-14 h-14 rounded-2xl bg-slate-100 text-slate-400 flex items-center justify-center mb-3">
                                                <span class="material-symbols-outlined text-[28px]">receipt_long</span>
                                            </div>
                                            <h3 class="font-bold text-slate-800 text-sm">Belum Ada Transaksi</h3>
                                            <p class="text-xs text-slate-400 mt-1">Riwayat isi saldo kamu akan tampil di sini.</p>
                                        </div>
                                    </td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- 🔹 PAGINASI (SAMA PERSIS DENGAN HALAMAN DAFTAR PEMBELIAN) -->
                <?php if($deposits->hasPages()): ?>
                <div class="px-5 py-4 border-t border-slate-100 bg-slate-50/40">
                    <div class="flex items-center justify-center gap-1.5 flex-wrap">

                        
                        <?php if($deposits->onFirstPage()): ?>
                            <span class="pagination-disabled">‹</span>
                        <?php else: ?>
                            <a href="<?php echo e($deposits->previousPageUrl()); ?>" class="pagination-btn">‹</a>
                        <?php endif; ?>

                        
                        <?php
                            $current = $deposits->currentPage();
                            $last = $deposits->lastPage();
                        ?>

                        <?php if($current > 3): ?>
                            <a href="<?php echo e($deposits->url(1)); ?>" class="pagination-btn">1</a>
                            <?php if($current > 4): ?>
                                <span class="pagination-disabled">...</span>
                            <?php endif; ?>
                        <?php endif; ?>

                        <?php for($i = max(1, $current - 2); $i <= min($last, $current + 2); $i++): ?>
                            <?php if($i == $current): ?>
                                <span class="pagination-active"><?php echo e($i); ?></span>
                            <?php else: ?>
                                <a href="<?php echo e($deposits->url($i)); ?>" class="pagination-btn"><?php echo e($i); ?></a>
                            <?php endif; ?>
                        <?php endfor; ?>

                        <?php if($current < $last - 2): ?>
                            <?php if($current < $last - 3): ?>
                                <span class="pagination-disabled">...</span>
                            <?php endif; ?>
                            <a href="<?php echo e($deposits->url($last)); ?>" class="pagination-btn"><?php echo e($last); ?></a>
                        <?php endif; ?>

                        
                        <?php if($deposits->hasMorePages()): ?>
                            <a href="<?php echo e($deposits->nextPageUrl()); ?>" class="pagination-btn">›</a>
                        <?php else: ?>
                            <span class="pagination-disabled">›</span>
                        <?php endif; ?>

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

            </div>
        </div>

    </section>

    <!-- 🔹 MODAL QRIS -->
    <div id="qrisModal" class="hidden fixed inset-0 bg-slate-900/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
        <div class="bg-white rounded-2xl shadow-2xl p-6 w-full max-w-sm text-center relative border border-slate-100">
            <button onclick="closeModal()" class="absolute top-4 right-4 w-8 h-8 rounded-full bg-slate-100 text-slate-500 hover:text-slate-800 flex items-center justify-center transition">
                ×
            </button>

            <h2 class="text-base font-bold text-slate-900">Pembayaran QRIS</h2>
            <p class="text-slate-500 text-xs mt-0.5 mb-3">Scan menggunakan E-Wallet atau M-Banking pilihanmu</p>

            <div id="qrisTimer" class="inline-flex items-center gap-1 px-3 py-1 rounded-full bg-rose-50 border border-rose-200/60 text-rose-600 text-xs font-semibold mb-4">
                Sisa waktu: 20:00
            </div>

            <div id="qrContent" class="flex flex-col items-center justify-center gap-2 mb-4">
                <div class="w-56 h-56 bg-slate-100 animate-pulse rounded-2xl flex items-center justify-center text-slate-400 text-xs font-medium border border-slate-200">
                    Membuat Kode QRIS...
                </div>
            </div>

            <div id="trxInfo" class="hidden bg-slate-50 border border-slate-200/80 rounded-xl p-3 text-left mb-4">
                <p class="text-[10px] text-slate-400 uppercase font-bold tracking-wider">ID Transaksi</p>
                <p id="trxIdText" class="font-mono font-bold text-sm text-slate-800"></p>
            </div>

            <div class="grid grid-cols-2 gap-2">
                <button
                    id="cancelBtn"
                    onclick="cancelDeposit()"
                    class="w-full bg-rose-50 hover:bg-rose-100 text-rose-600 border border-rose-200/80 font-semibold text-xs py-2.5 rounded-xl transition">
                    Batalkan
                </button>

                <button
                    onclick="closeModal()"
                    class="w-full bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold text-xs py-2.5 rounded-xl transition">
                    Tutup
                </button>
            </div>
        </div>
    </div>

    <!-- 🔔 MODAL NOTIFIKASI -->
    <div id="notifModal" class="hidden fixed inset-0 bg-slate-900/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
        <div class="bg-white rounded-2xl shadow-2xl p-5 w-full max-w-xs text-center animate-fade-soft border border-slate-100">
            <h3 id="notifTitle" class="text-base font-bold text-slate-900 mb-1">Pemberitahuan</h3>
            <p id="notifMessage" class="text-slate-600 text-xs leading-relaxed mb-4">Pesan informasi</p>

            <button
                onclick="closeNotif()"
                class="w-full bg-blue-600 hover:bg-blue-700 text-white font-semibold text-xs py-2.5 rounded-xl transition">
                Tutup
            </button>
        </div>
    </div>

    <!-- FOOTER INCLUSION -->
    <?php echo $__env->make('components.footer', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

</main>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
function toggleSteps() {
    const content = document.getElementById('stepContent');
    const arrow = document.getElementById('stepArrow');

    content.classList.toggle('show');
    if (content.classList.contains('show')) {
        arrow.style.transform = 'rotate(180deg)';
    } else {
        arrow.style.transform = 'rotate(0deg)';
    }
}

function showNotif(title, message, type = "info") {
    const modal = document.getElementById("notifModal");
    const titleEl = document.getElementById("notifTitle");
    const msgEl = document.getElementById("notifMessage");

    titleEl.innerText = title;
    msgEl.innerText = message;

    if (type === "success") titleEl.className = "text-base font-bold text-emerald-600 mb-1";
    else if (type === "error") titleEl.className = "text-base font-bold text-rose-600 mb-1";
    else titleEl.className = "text-base font-bold text-slate-900 mb-1";

    modal.classList.remove("hidden");
}

function closeNotif() {
    document.getElementById("notifModal").classList.add("hidden");
}

let isSubmitting = false;
document.getElementById('depositForm').addEventListener('submit', async function(e) {
    e.preventDefault();

    if (isSubmitting) return;
    isSubmitting = true;

    const amount = document.getElementById('amount').value;
    const method = document.getElementById('method').value;
    const btn = document.getElementById('btnDepositSubmit');

    // 1. Tampilkan animasi loading SVG & nonaktifkan tombol
    btn.disabled = true;
    btn.innerHTML = `
        <svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
        <span>Memproses...</span>
    `;

    try {
        const res = await fetch("<?php echo e(route('deposit.store')); ?>", {
            method: "POST",
            headers: {
                "X-CSRF-TOKEN": document.querySelector('input[name=_token]').value,
                "Content-Type": "application/json",
                "X-Requested-With": "XMLHttpRequest"
            },
            body: JSON.stringify({ amount, method })
        });

        const data = await res.json();

        if (!data || data.error) {
            showNotif("Gagal", data.error || "Gagal membuat QRIS", "error");
            return;
        }

        const qrString = data.qrisData?.string || "";
        const qrImage = data.qrisData?.image || "";

        let qrDisplay = "";

        if (qrImage) {
            qrDisplay = `
                <img
                    src="${qrImage}"
                    class="w-56 h-56 rounded-xl border border-slate-200 shadow-sm"
                    alt="QRIS"
                >
            `;
        } else if (qrString) {
            const qrApi = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(qrString)}`;
            qrDisplay = `
                <img
                    src="${qrApi}"
                    class="w-56 h-56 rounded-xl border border-slate-200 shadow-sm"
                    alt="QRIS"
                >
            `;
        }

        const fee = Math.ceil(Number(amount) * 0.03);
        const total = Number(amount) + fee;

        document.getElementById('qrContent').innerHTML = `
            ${qrDisplay}
            <div class="text-xs text-slate-700 mt-2 font-medium leading-relaxed">
                Nominal: <span class="font-bold text-slate-900">Rp ${Number(amount).toLocaleString('id-ID')}</span><br>
                <span class="text-slate-400 text-[11px]">+ PPN & Admin Rp ${fee.toLocaleString('id-ID')}</span><br>
                <span class="font-bold text-blue-600 text-sm">Total: Rp ${total.toLocaleString('id-ID')}</span>
            </div>
        `;
        document.getElementById('trxIdText').innerText = data.trxId;
        currentTrx = data.trxId;

        document.getElementById('trxInfo').classList.remove('hidden');
        document.getElementById('qrisModal').classList.remove('hidden');
        startQrisCountdown(20);
        startDepositPolling();

    } catch (err) {
        showNotif("Kesalahan", "Terjadi kesalahan. Coba lagi: " + err.message, "error");
    } finally {
        // 2. Kembalikan tombol ke keadaan semula jika proses selesai / gagal
        btn.disabled = false;
        btn.innerHTML = '<span class="material-symbols-outlined text-[20px]">qr_code_scanner</span><span>Bayar Sekarang</span>';
        isSubmitting = false;
    }
});

function closeModal() {
    if (qrisTimerInterval) clearInterval(qrisTimerInterval);
    if (depositPolling) clearInterval(depositPolling);
    currentTrx = null; 
    document.getElementById('qrisModal').classList.add('hidden');
}

function startQrisCountdown(minutes = 20) {
    if (qrisTimerInterval) clearInterval(qrisTimerInterval);

    qrisExpireAt = Date.now() + minutes * 60 * 1000;
    const timerEl = document.getElementById('qrisTimer');

    qrisTimerInterval = setInterval(async () => {
        const now = Date.now();
        const diff = qrisExpireAt - now;

        if (diff <= 0) {
            clearInterval(qrisTimerInterval);
            timerEl.innerText = "Waktu habis";

            if (currentTrx) {
                try {
                    await fetch(`/deposit/cancel/${currentTrx}`, {
                        method: "POST",
                        headers: {
                            "X-CSRF-TOKEN": document.querySelector('input[name=_token]').value,
                            "X-Requested-With": "XMLHttpRequest"
                        }
                    });
                } catch (e) {}

                currentTrx = null;
                closeModal();

                Swal.fire({
                    icon: "warning",
                    title: "Waktu Habis",
                    text: "QRIS telah kadaluarsa dan deposit dibatalkan otomatis.",
                    confirmButtonColor: "#091426",
                    customClass: { popup: 'rounded-2xl' }
                }).then(() => window.location.reload());
            }

            return;
        }

        const min = Math.floor(diff / 60000);
        const sec = Math.floor((diff % 60000) / 1000);

        timerEl.innerText = `Sisa waktu: ${String(min).padStart(2, '0')}:${String(sec).padStart(2, '0')}`;
    }, 1000);
}

async function cancelDeposit() {
    const trxId = document.getElementById('trxIdText').innerText.trim();
    if (!trxId) return showNotif("Gagal", "ID transaksi tidak ditemukan.", "error");

    const result = await Swal.fire({
        title: "Konfirmasi",
        text: "Batalkan deposit ini?",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Ya, Batalkan",
        cancelButtonText: "Tidak",
        reverseButtons: true,
        confirmButtonColor: "#ef4444",
        cancelButtonColor: "#64748b",
        customClass: { popup: 'rounded-2xl' }
    });

    if (!result.isConfirmed) return;

    try {
        const res = await fetch(`/deposit/cancel/${trxId}`, {
            method: "POST",
            headers: {
                "X-CSRF-TOKEN": document.querySelector('input[name=_token]').value,
                "X-Requested-With": "XMLHttpRequest"
            }
        });

        const data = await res.json();

        if (data.success) {
            clearInterval(qrisTimerInterval); 
            currentTrx = null;                
            await Swal.fire({
                icon: "success",
                title: "Berhasil",
                text: "Deposit dibatalkan.",
                confirmButtonColor: "#091426",
                customClass: { popup: 'rounded-2xl' }
            });
            closeModal();
            window.location.reload();
        } else {
            Swal.fire({
                icon: "error",
                title: "Gagal",
                text: data.message || "Gagal membatalkan deposit.",
                customClass: { popup: 'rounded-2xl' }
            });
        }
    } catch (err) {
        Swal.fire({
            icon: "error",
            title: "Kesalahan",
            text: "Terjadi kesalahan: " + err.message,
            customClass: { popup: 'rounded-2xl' }
        });
    }
}

function showPaymentSuccess() {
    Swal.fire({
        title: "Sukses!",
        text: "Saldo berhasil ditambahkan.",
        icon: "success",
        confirmButtonText: "OK",
        confirmButtonColor: "#091426",
        allowOutsideClick: false,
        customClass: { popup: 'rounded-2xl' }
    }).then(() => {
        window.location.reload();
    });
}

let currentTrx = null;
let qrisTimerInterval = null;
let qrisExpireAt = null;
let depositPolling = null;

function startDepositPolling() {
    if (depositPolling) clearInterval(depositPolling);

    depositPolling = setInterval(async () => {
        if (!currentTrx) return;

        if (qrisExpireAt && Date.now() > qrisExpireAt) {
            clearInterval(depositPolling);
            return;
        }

        try {
            const res = await fetch(`/deposit/status/${currentTrx}`, { cache: "no-store" });
            const data = await res.json();

            if (["PAID", "EXPIRED", "CANCELED"].includes(data.status)) {
                clearInterval(depositPolling);
                clearInterval(qrisTimerInterval);

                currentTrx = null;
                closeModal();

                if (data.status === "PAID") {
                    showPaymentSuccess();
                } else {
                    Swal.fire({
                        icon: "warning",
                        title: "Deposit Dibatalkan",
                        text: "Transaksi tidak berhasil atau sudah kadaluarsa.",
                        customClass: { popup: 'rounded-2xl' }
                    });
                }
                return;
            }
        } catch (err) {}
    }, 10000);
}

function toggleVideoDeposit() {
    const videoContainer = document.getElementById('videoDeposit');
    const iframe = videoContainer.querySelector('iframe');

    if (videoContainer.classList.contains('hidden')) {
        videoContainer.classList.remove('hidden');
        if (!iframe.src && iframe.dataset.src) {
            iframe.src = iframe.dataset.src;
        }
    } else {
        videoContainer.classList.add('hidden');
        iframe.src = '';
    }
}

// Fade-in Observer
const observer = new IntersectionObserver(entries => {
    entries.forEach(entry => {
        if (entry.isIntersecting) entry.target.classList.add('show');
    });
}, { threshold: 0.1 });

document.querySelectorAll('.fade-section').forEach(el => observer.observe(el));
</script>

<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/nusaotp/public_html/resources/views/deposit/index.blade.php ENDPATH**/ ?>