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

.info-card {
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 16px;
    padding: 16px;
    transition: all 0.2s ease;
    min-height: 72px;
    display: flex;
    align-items: center;
}

.info-card:hover {
    border-color: #cbd5e1;
    box-shadow: 0 4px 12px -2px rgba(15, 23, 42, 0.04);
}

/* =========================
   OTP HIGHLIGHT CARD
========================= */
.otp-card {
    border-radius: 18px;
    background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
    position: relative;
    overflow: hidden;
    min-height: 80px;
    box-shadow: 0 8px 20px -4px rgba(37, 99, 235, 0.3);
}

/* =========================
   BUTTONS
========================= */
.btn-action {
    height: 44px;
    padding: 0 20px;
    border-radius: 12px;
    font-weight: 600;
    font-size: 0.875rem;
    transition: all 0.2s ease;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.btn-action:hover {
    transform: translateY(-1px);
}
</style>

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

    <!-- MAIN CARD -->
    <section class="fade-section">
        <div class="modern-card max-w-5xl mx-auto p-5 sm:p-7">

            <!-- HEADER -->
            <div class="flex items-center gap-3.5 pb-5 mb-6 border-b border-slate-100">
                <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]">phonelink_setup</span>
                </div>
                <div>
                    <h2 class="text-base sm:text-lg font-bold text-slate-900">Informasi Pesanan</h2>
                    <p class="text-xs text-slate-500 mt-0.5">Detail transaksi dan status penerimaan kode OTP</p>
                </div>
            </div>

            <!-- GRID INFO DETAILS -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-3.5 items-stretch">
                <?php
                    $items = [
                        ['label' => 'Order ID', 'icon' => 'tag', 'color' => 'blue', 'value' => $order->id],
                        ['label' => 'Nomor', 'icon' => 'sim_card', 'color' => 'indigo', 'value' => $order->number ?? '-'],
                        ['label' => 'Layanan', 'icon' => 'apps', 'color' => 'emerald', 'value' => strtoupper($order->layanan_nama ?? $order->layanan)],
                        ['label' => 'Harga', 'icon' => 'payments', 'color' => 'amber', 'value' => 'Rp ' . number_format($order->harga, 0, ',', '.')],
                    ];
                ?>

                <?php $__currentLoopData = $items; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <div class="info-card flex items-center gap-3.5">
                        <div class="w-10 h-10 rounded-xl bg-slate-100 text-slate-600 border border-slate-200/80 flex items-center justify-center shrink-0">
                            <span class="material-symbols-outlined text-[20px]"><?php echo e($item['icon']); ?></span>
                        </div>

                        <div class="flex-1 min-w-0">
                            <div class="text-[11px] font-bold text-slate-400 uppercase tracking-wider mb-0.5">
                                <?php echo e($item['label']); ?>

                            </div>

                            <div class="font-bold text-sm text-slate-900 break-all flex items-center justify-between gap-2">
                                <?php if($item['label'] === 'Order ID'): ?>
                                    <span id="orderIdValue" class="font-mono text-blue-600">#<?php echo e($item['value']); ?></span>
                                <?php elseif($item['label'] === 'Nomor'): ?>
                                    <span id="numberValue" class="font-mono"><?php echo e($item['value']); ?></span>
                                <?php else: ?>
                                    <span><?php echo e($item['value']); ?></span>
                                <?php endif; ?>

                                <?php if($item['label'] === 'Nomor' && !empty($order->number)): ?>
                                    <button id="btnCopyNumber"
                                        class="w-8 h-8 rounded-lg bg-slate-100 text-slate-600 hover:bg-blue-50 hover:text-blue-600 flex items-center justify-center transition shrink-0 border border-slate-200/60"
                                        title="Salin nomor">
                                        <span class="material-symbols-outlined text-[18px]">content_copy</span>
                                    </button>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </div>

            <!-- OTP + STATUS CONTAINER -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-3.5 mt-3.5 items-stretch">
                
                <!-- OTP DISPLAY CARD -->
                <div id="otpCard" class="otp-card p-4 sm:p-5 text-white flex items-center justify-between gap-3">
                    <div class="flex items-center gap-3.5 min-w-0 flex-1">
                        <div class="w-10 h-10 rounded-xl bg-white/15 backdrop-blur border border-white/20 flex items-center justify-center shrink-0 text-white">
                            <span class="material-symbols-outlined text-[22px]">sms</span>
                        </div>
                        <div class="min-w-0 flex-1">
                            <div class="text-[11px] font-bold uppercase tracking-wider text-blue-100">
                                Kode OTP
                            </div>
                            <div id="otpValue" class="font-mono text-base sm:text-lg font-black tracking-widest break-all text-white mt-0.5">
                                <?php echo e($order->otp ?? 'Menunggu..'); ?>

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

                    <button id="btnCopyOtp"
                        class="w-9 h-9 rounded-xl bg-white/15 hover:bg-white/25 backdrop-blur border border-white/20 flex items-center justify-center transition shrink-0 text-white"
                        title="Salin OTP">
                        <span class="material-symbols-outlined text-[18px]">content_copy</span>
                    </button>
                </div>

                <!-- STATUS DISPLAY CARD -->
                <div class="info-card flex items-center gap-3.5">
                    <div class="w-10 h-10 rounded-xl bg-slate-100 text-slate-600 border border-slate-200/80 flex items-center justify-center shrink-0">
                        <span class="material-symbols-outlined text-[20px]">sync</span>
                    </div>

                    <div class="flex-1 min-w-0">
                        <div class="text-[11px] font-bold text-slate-400 uppercase tracking-wider mb-0.5">
                            Status Pesanan
                        </div>

                        <div id="statusLabel"
                            class="font-bold text-sm tracking-wide <?php echo e($order->status === 'SUCCESS' ? 'text-emerald-600' : ($order->status === 'PENDING' ? 'text-amber-600' : 'text-rose-600')); ?>">
                            <?php echo e($order->status); ?>

                        </div>

                        <div id="countdownText" class="text-xs text-slate-500 font-medium mt-0.5">
                            Menghitung waktu...
                        </div>
                    </div>
                </div>

            </div>

            <!-- ACTIONS -->
            <div class="mt-6 pt-5 border-t border-slate-100 flex flex-wrap items-center gap-2.5">
                <a href="<?php echo e(route('riwayat')); ?>"
                    class="btn-action bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200/80">
                    <span class="material-symbols-outlined text-[18px]">arrow_back</span>
                    <span>Kembali ke Riwayat</span>
                </a>

                <?php if($order->status === 'PENDING'): ?>
                    <button id="btnCancel" class="btn-action bg-rose-600 hover:bg-rose-700 text-white shadow-sm">
                        <span class="material-symbols-outlined text-[18px]">cancel</span>
                        <span>Batalkan Pesanan</span>
                    </button>
                <?php endif; ?>
            </div>

        </div>
    </section>

    <!-- 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>
    const orderId = <?php echo e($order->id); ?>;

    let poller = null;
    let delay = 5000;

    const otpEl = document.getElementById('otpValue');
    const numberEl = document.getElementById('numberValue');
    const btnCancel = document.getElementById('btnCancel');
    const statusEl = document.getElementById('statusLabel');
    const otpCard = document.getElementById('otpCard');

    const createdAt = new Date("<?php echo e($order->created_at); ?>");
    const expiredAt = new Date(createdAt.getTime() + (20 * 60 * 1000));
    const countdownEl = document.getElementById('countdownText');

    // ===== UI UPDATE =====
    function updateUI(data) {

      if (data.number && numberEl) {
        numberEl.innerText = data.number;
      }

      // OTP
      if (data.otp && otpEl) {
        otpEl.innerText = data.otp;
      } else if (otpEl) {
        otpEl.innerText = 'Menunggu..';
      }

      // STATUS
      if (data.status && statusEl) {

        statusEl.innerText = data.status;

        statusEl.className = 'font-bold text-sm tracking-wide ' + (
          data.status === 'SUCCESS' ? 'text-emerald-600' :
            data.status === 'PENDING' ? 'text-amber-600' :
              'text-rose-600'
        );

        if (['FAILED', 'CANCELED', 'COMPLETED'].includes(data.status)) {

          // sembunyikan OTP
          if (otpCard) {
            otpCard.style.display = 'none';
          }

        } else {

          // tampilkan OTP
          if (otpCard) {
            otpCard.style.display = 'flex';
          }

        }

        // countdown hanya hilang saat SUCCESS dll
        if (['SUCCESS', 'FAILED', 'CANCELED', 'COMPLETED'].includes(data.status)) {

          if (countdownEl) {
            countdownEl.style.display = 'none';
          }

        } else {

          if (countdownEl) {
            countdownEl.style.display = 'block';
          }

        }
      }
    }

    // ===== STOP ALL =====
    function stopAll() {
      if (poller) {
        clearTimeout(poller);
        poller = null;
      }

      if (btnCancel) {
        btnCancel.disabled = true;
        btnCancel.classList.add('opacity-50');
      }
    }

    // ===== SMART POLLING =====
    async function smartPoll() {

      try {

        const res = await fetch(`/orderv2/check/${orderId}`, {

          cache: 'no-store'

        });

        if (!res.ok) {
          throw new Error('Network response error');
        }

        const data = await res.json();

        updateUI(data);

        if (!data.otp && otpEl) {
          otpEl.innerText = 'Menunggu..';
        }

        if (['SUCCESS', 'FAILED', 'CANCELED', 'COMPLETED'].includes(data.status)) {

          stopAll();

          return;

        }

        if (!data.otp) {

          delay = Math.min(delay + 2000, 15000);

        } else {

          delay = 5000;

        }

      } catch (e) {

        console.log('Polling retry...', e);

        if (otpEl && (

          otpEl.innerText === '' ||

          otpEl.innerText === 'Error ambil OTP'

        )) {

          otpEl.innerText = 'Menunggu..';

        }

        delay = 3000;

      }

      poller = setTimeout(smartPoll, delay);

    }

    // ===== VISIBILITY =====
    document.addEventListener("visibilitychange", () => {
      if (document.hidden) {
        stopAll();
      } else {
        if (!poller) smartPoll();
      }
    });

    // ===== COPY NUMBER =====
    const btnCopyNumber = document.getElementById('btnCopyNumber');

    if (btnCopyNumber) {

      btnCopyNumber.onclick = async () => {

        await navigator.clipboard.writeText(numberEl.innerText);

        Swal.fire({
          icon: 'success',
          title: 'Disalin',
          timer: 1500,
          showConfirmButton: false,
          confirmButtonColor: '#091426',
          customClass: { popup: 'rounded-2xl' }
        });

      }

    }

    // ===== CANCEL =====
    if (btnCancel) {

      btnCancel.onclick = async () => {

        if (btnCancel.disabled) return;

        const confirm = await Swal.fire({
          title: 'Batalkan order?',
          text: 'Saldo akan dikembalikan secara otomatis.',
          icon: 'warning',
          showCancelButton: true,
          confirmButtonText: 'Ya, Batalkan',
          cancelButtonText: 'Tidak',
          reverseButtons: true,
          confirmButtonColor: '#ef4444',
          cancelButtonColor: '#64748b',
          customClass: { popup: 'rounded-2xl' }
        });

        if (!confirm.isConfirmed) return;

        Swal.fire({
          title: 'Memproses...',
          allowOutsideClick: false,
          didOpen: () => Swal.showLoading(),
          customClass: { popup: 'rounded-2xl' }
        });

        const res = await fetch(`/orderv2/cancel/${orderId}`, {
          method: 'POST',
          headers: {
            'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
          }
        });

        Swal.close();

        const data = await res.json();

        if (data.ok) {

          stopAll();

          Swal.fire({
            icon: 'success',
            title: 'Dibatalkan',
            timer: 1500,
            showConfirmButton: false,
            customClass: { popup: 'rounded-2xl' }
          });

          setTimeout(() => location.reload(), 1200);

        } else {

          Swal.fire({
            icon: 'error',
            title: 'Gagal',
            text: data.message || 'Gagal membatalkan pesanan',
            customClass: { popup: 'rounded-2xl' }
          });

        }

      }

    }

    // ===== COPY OTP =====
    const btnCopyOtp = document.getElementById('btnCopyOtp');

    if (btnCopyOtp) {

      btnCopyOtp.onclick = async () => {

        const otp = otpEl.innerText.trim();

        if (
          otp === '' ||
          otp === 'Menunggu..' ||
          otp === 'Menunggu'
        ) {

          Swal.fire({
            icon: 'info',
            title: 'OTP Belum Tersedia',
            text: 'Tunggu beberapa saat sampai kode OTP diterima.',
            timer: 1800,
            showConfirmButton: false,
            customClass: { popup: 'rounded-2xl' }
          });

          return;
        }

        await navigator.clipboard.writeText(otp);

        Swal.fire({
          icon: 'success',
          title: 'OTP Berhasil Disalin',
          timer: 1500,
          showConfirmButton: false,
          customClass: { popup: 'rounded-2xl' }
        });

      }

    }

    // ===== CANCEL DELAY =====
    let cancelTimer = null;

    function startCancelDelay() {

      if (!btnCancel) return;

      const now = new Date();
      const diff = (now - createdAt) / 1000;
      let remaining = Math.max(0, 180 - diff);

      if (remaining > 0) {

        btnCancel.disabled = true;
        btnCancel.classList.add('opacity-50', 'cursor-not-allowed');

        const span = document.createElement('span');

        span.id = 'cancelCountdown';
        span.className = 'ml-1.5 text-xs text-white/80 font-mono';

        btnCancel.appendChild(span);

        cancelTimer = setInterval(() => {

          remaining--;

          if (remaining <= 0) {

            clearInterval(cancelTimer);

            btnCancel.disabled = false;

            btnCancel.classList.remove('opacity-50', 'cursor-not-allowed');

            span.remove();

          } else {

            span.textContent = `(${Math.ceil(remaining)}s)`;

          }

        }, 1000);

      }

    }

    // ===== COUNTDOWN =====
    function startCountdown() {

      if (!countdownEl) return;

      const currentStatus = document.getElementById('statusLabel')?.innerText;

      if (['CANCELED', 'SUCCESS', 'FAILED', 'COMPLETED'].includes(currentStatus)) {
        countdownEl.style.display = 'none';
        return;
      }

      const timer = setInterval(() => {

        const now = new Date();

        const distance = expiredAt - now;

        if (distance <= 0) {

          clearInterval(timer);

          countdownEl.innerHTML = `
                <span class="text-rose-600 font-semibold">
                  Waktu pending habis & saldo kamu telah dikembalikan, Silahkan Lakukan Pembelian Ulang.
                </span>
              `;

          return;
        }

        const minutes = Math.floor(distance / 1000 / 60);
        const seconds = Math.floor((distance / 1000) % 60);

        countdownEl.innerHTML = `
            <span>Sisa waktu: </span>
            <span class="font-bold text-rose-600 font-mono">
              ${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}
            </span>
          `;

      }, 1000);

    }

    // ===== FADE OBSERVER =====
    document.addEventListener("DOMContentLoaded", () => {

      const els = document.querySelectorAll('.fade-section');

      els.forEach((el, i) => {

        setTimeout(() => {
          el.classList.add('show');
        }, i * 120);

      });

    });

    // ===== INIT =====
    startCancelDelay();
    startCountdown();
    smartPoll();
</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/orderv2/detail.blade.php ENDPATH**/ ?>