{% extends "base.html" %}
{% set active = "topup" %}

{% block title %}Top Up Token{% endblock %}
{% block page_title %}Top Up Token{% endblock %}

{% block extra_head %}
<script src="https://app.sandbox.midtrans.com/snap/snap.js"
        data-client-key="{{ midtrans_client_key }}"
        id="snap-script"></script>

<style>
  .topup-layout {
    display: grid;
    grid-template-columns: 1fr 320px;
    gap: 20px;
    align-items: start;
  }
  @media (max-width: 860px) { .topup-layout { grid-template-columns: 1fr; } }

  .balance-card {
    background: linear-gradient(135deg, #1a2a3f 0%, #0e1a2d 100%);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 28px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
  }
  .balance-label {
    font-size: .78rem;
    font-weight: 600;
    color: var(--muted);
    text-transform: uppercase;
    letter-spacing: .8px;
    margin-bottom: 6px;
  }
  .balance-amount {
    font-family: 'Sora', sans-serif;
    font-size: 2rem;
    font-weight: 800;
    color: var(--text);
    letter-spacing: -1px;
    transition: color .3s;
  }
  .balance-amount.updated {
    color: var(--success);
  }
  .balance-icon {
    width: 56px; height: 56px;
    background: rgba(88,166,255,.12);
    border-radius: 14px;
    display: flex; align-items: center; justify-content: center;
    font-size: 24px;
    flex-shrink: 0;
  }

  .amount-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
    margin-bottom: 20px;
  }
  @media (max-width: 500px) { .amount-grid { grid-template-columns: repeat(2, 1fr); } }

  .amount-card {
    background: var(--surface);
    border: 2px solid var(--border);
    border-radius: var(--radius-sm);
    padding: 16px 12px;
    text-align: center;
    cursor: pointer;
    transition: all .2s;
    position: relative;
    overflow: hidden;
  }
  .amount-card:hover {
    border-color: var(--accent);
    background: rgba(88,166,255,.05);
  }
  .amount-card.selected {
    border-color: var(--accent);
    background: rgba(88,166,255,.08);
    box-shadow: 0 0 0 3px rgba(88,166,255,.15);
  }
  .amount-card.selected::before {
    content: '✓';
    position: absolute;
    top: 6px; right: 8px;
    font-size: .7rem;
    color: var(--accent);
    font-weight: 700;
  }
  .amount-label {
    font-size: .68rem;
    color: var(--muted);
    margin-bottom: 2px;
  }
  .amount-value {
    font-family: 'Sora', sans-serif;
    font-size: 1rem;
    font-weight: 700;
    color: var(--text);
  }

  .btn-pay {
    width: 100%;
    padding: 13px;
    background: linear-gradient(135deg, var(--accent), #2d7de0);
    color: #fff;
    border: none;
    border-radius: var(--radius-sm);
    font-family: 'DM Sans', sans-serif;
    font-size: .95rem; font-weight: 700;
    cursor: pointer;
    display: flex; align-items: center; justify-content: center; gap: 8px;
    transition: all .2s;
    margin-top: 4px;
  }
  .btn-pay:hover:not(:disabled) {
    transform: translateY(-1px);
    box-shadow: 0 8px 24px rgba(88,166,255,.3);
  }
  .btn-pay:disabled { opacity: .45; cursor: not-allowed; transform: none; }

  .pay-status {
    display: none;
    margin-top: 14px;
    padding: 13px 16px;
    border-radius: var(--radius-sm);
    font-size: .875rem;
    align-items: center;
    gap: 10px;
  }
  .pay-status.show { display: flex; }
  .pay-status.success {
    background: rgba(63,185,80,.08);
    border: 1px solid rgba(63,185,80,.25);
    color: var(--success);
  }
  .pay-status.error {
    background: rgba(248,81,73,.08);
    border: 1px solid rgba(248,81,73,.25);
    color: var(--danger);
  }
  .pay-status.pending {
    background: rgba(88,166,255,.08);
    border: 1px solid rgba(88,166,255,.25);
    color: var(--accent);
  }

  .info-panel {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 20px;
  }
  .info-title {
    font-family: 'Sora', sans-serif;
    font-size: .88rem; font-weight: 700;
    margin-bottom: 14px;
    padding-bottom: 12px;
    border-bottom: 1px solid var(--border2);
  }
  .info-item {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    margin-bottom: 12px;
    font-size: .82rem;
    color: var(--muted);
    line-height: 1.5;
  }
  .info-item-icon { flex-shrink: 0; margin-top: 1px; }

  .webhook-warning {
    background: rgba(212,160,23,.07);
    border: 1px solid rgba(212,160,23,.3);
    border-radius: var(--radius-sm);
    padding: 12px 14px;
    font-size: .8rem;
    color: #c9a227;
    margin-bottom: 14px;
    display: none;
  }

  .order-list { margin-top: 0; }
  .order-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid var(--border2);
    font-size: .82rem;
    gap: 8px;
  }
  .order-item:last-child { border-bottom: none; }
  .order-amount { font-weight: 700; font-size: .88rem; }
  .order-meta { color: var(--muted); }
  .badge-paid    { background: rgba(63,185,80,.15);  color: var(--success); }
  .badge-pending { background: rgba(88,166,255,.15); color: var(--accent); }
  .badge-failed  { background: rgba(248,81,73,.15);  color: var(--danger); }
  .badge-expired { background: rgba(107,127,150,.15); color: var(--muted); }
</style>
{% endblock %}

{% block content %}
<div class="topup-layout">

  <div>
    <div class="balance-card">
      <div>
        <div class="balance-label">Token Anda</div>
        <div class="balance-amount" id="balance-display">
          {{ "{:,}".format(user.balance) }} Token
        </div>
      </div>
      <div class="balance-icon">🪙</div>
    </div>

    <div class="card">
      <div class="card-header">
        <span class="card-title">💳 Pilih Nominal Top Up</span>
      </div>

      <div class="amount-grid" id="amount-grid"></div>

      <button class="btn-pay" id="btn-pay" disabled onclick="startPayment()">
        <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
          <rect x="1" y="4" width="22" height="16" rx="2"/>
          <line x1="1" y1="10" x2="23" y2="10"/>
        </svg>
        <span id="btn-pay-text">Pilih nominal terlebih dahulu</span>
      </button>

      <div class="pay-status" id="pay-status"></div>
    </div>

    <div class="card" style="margin-top:16px">
      <div class="card-header">
        <span class="card-title">📋 Riwayat Top Up</span>
      </div>
      <div class="order-list" id="order-list">
        <div style="color:var(--muted);font-size:.85rem;padding:8px 0">Memuat...</div>
      </div>
    </div>
  </div>

  <div>
    <div class="info-panel">
      <div class="info-title">ℹ️ Cara Top Up</div>

      <div class="info-item">
        <span class="info-item-icon">①</span>
        <span>Pilih nominal top up yang diinginkan dari daftar di atas.</span>
      </div>
      <div class="info-item">
        <span class="info-item-icon">②</span>
        <span>Klik tombol <strong>Bayar Sekarang</strong> — popup pembayaran Midtrans akan muncul.</span>
      </div>
      <div class="info-item">
        <span class="info-item-icon">③</span>
        <span>Pilih metode pembayaran (transfer bank, GoPay, QRIS, dll.) dan selesaikan pembayaran.</span>
      </div>
      <div class="info-item">
        <span class="info-item-icon">④</span>
        <span>Token akan otomatis bertambah setelah pembayaran dikonfirmasi (biasanya instan).</span>
      </div>
    </div>

    <div class="info-panel" style="margin-top:14px">
      <div class="info-title">💡 Tarif Layanan</div>
      <div class="info-item">
        <span class="info-item-icon">🎙️</span>
        <span><strong>Transkripsi</strong> — 5.000 Token/menit audio (dibulatkan ke atas).</span>
      </div>
      <div class="info-item">
        <span class="info-item-icon">📄</span>
        <span><strong>Berita Acara</strong> — 20.000 Token per dokumen.</span>
      </div>
    </div>
  </div>

</div>
{% endblock %}

{% block scripts %}
<script>
  let selectedAmount = null;

  async function loadAmounts() {
    try {
      const res  = await fetch('/api/topup/amounts');
      const data = await res.json();
      renderAmounts(data.amounts);
    } catch (e) {
      console.error('Gagal memuat nominal:', e);
    }
  }

  function formatNumber(n) {
    if (n >= 1_000_000) return `${(n/1_000_000).toLocaleString('id-ID')}jt`;
    if (n >= 1_000)     return `${(n/1_000).toLocaleString('id-ID')}k`;
    return n.toLocaleString('id-ID');
  }

  function renderAmounts(amounts) {
    const grid = document.getElementById('amount-grid');
    grid.innerHTML = amounts.map(a => `
      <div class="amount-card" onclick="selectAmount(${a})" data-amount="${a}">
        <div class="amount-label">Token</div>
        <div class="amount-value">${formatNumber(a)}</div>
      </div>
    `).join('');
  }

  function selectAmount(amount) {
    selectedAmount = amount;
    document.querySelectorAll('.amount-card').forEach(c => {
      c.classList.toggle('selected', parseInt(c.dataset.amount) === amount);
    });
    const btn  = document.getElementById('btn-pay');
    const text = document.getElementById('btn-pay-text');
    btn.disabled = false;
    text.textContent = `Bayar ${amount.toLocaleString('id-ID')} Token`;
    document.getElementById('pay-status').classList.remove('show');
  }

  async function startPayment() {
    if (!selectedAmount) return;

    const btn = document.getElementById('btn-pay');
    setStatus('pending', '⏳ Menghubungi Midtrans...');
    btn.disabled = true;

    try {
      const res = await fetch('/api/topup/create', {
        method:  'POST',
        headers: { 'Content-Type': 'application/json' },
        body:    JSON.stringify({ amount: selectedAmount }),
      });
      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.detail || 'Gagal membuat order.');
      }

      const orderId = data.order_id;

      clearStatus();
      window.snap.pay(data.snap_token, {
        onSuccess: function(result) {
          setStatus('pending', '⏳ Memverifikasi pembayaran ke server...');
          btn.disabled = true;
          pollOrderStatus(orderId);
        },
        onPending: function(result) {
          setStatus('pending', '⏳ Menunggu pembayaran dikonfirmasi...');
          btn.disabled = false;
          loadOrders();
        },
        onError: function(result) {
          setStatus('error', '❌ Pembayaran gagal. Silakan coba lagi.');
          btn.disabled = false;
        },
        onClose: function() {
          clearStatus();
          btn.disabled = false;
          loadOrders();
        },
      });

    } catch (e) {
      setStatus('error', `❌ ${e.message}`);
      btn.disabled = false;
    }
  }

  async function pollOrderStatus(orderId, attempt = 0) {
    const MAX_ATTEMPTS = 15;

    if (attempt >= MAX_ATTEMPTS) {
      setStatus('pending',
        '⏳ Pembayaran diterima Midtrans. Token akan diperbarui otomatis ' +
        'setelah server menerima konfirmasi. Coba refresh halaman dalam beberapa saat.'
      );
      document.getElementById('btn-pay').disabled = false;
      loadOrders();
      return;
    }

    try {
      const res  = await fetch(`/api/topup/check-order/${orderId}`);
      const data = await res.json();

      if (data.status === 'paid') {
        setStatus('success', '✅ Pembayaran berhasil! Token Anda telah diperbarui.');
        await refreshBalance();
        loadOrders();
        document.getElementById('btn-pay').disabled = false;
        return;
      }

      if (data.status === 'failed' || data.status === 'expired') {
        setStatus('error', `❌ Pembayaran ${data.status === 'failed' ? 'gagal' : 'kedaluwarsa'}.`);
        document.getElementById('btn-pay').disabled = false;
        loadOrders();
        return;
      }
    } catch (e) {
      console.warn('[Polling] Gagal cek status, coba lagi...', e);
    }

    setTimeout(() => pollOrderStatus(orderId, attempt + 1), 2000);
  }

  async function refreshBalance() {
    try {
      const res  = await fetch('/api/auth/me');
      const data = await res.json();
      if (data.balance !== undefined) {
        const el = document.getElementById('balance-display');
        el.textContent = data.balance.toLocaleString('id-ID') + ' Token';
        el.classList.add('updated');
        setTimeout(() => el.classList.remove('updated'), 2000);
      }
    } catch (e) { /* silent */ }
  }

  async function loadOrders() {
    const container = document.getElementById('order-list');
    try {
      const res  = await fetch('/api/topup/orders');
      const data = await res.json();

      if (data.orders.length === 0) {
        container.innerHTML = '<div style="color:var(--muted);font-size:.82rem;padding:8px 0">Belum ada riwayat top up.</div>';
        return;
      }

      container.innerHTML = data.orders.map(o => {
        const badgeClass = {
          paid: 'badge-paid', pending: 'badge-pending',
          failed: 'badge-failed', expired: 'badge-expired',
        }[o.status] || 'badge-expired';
        const statusText = {
          paid: 'Berhasil', pending: 'Menunggu',
          failed: 'Gagal', expired: 'Kedaluwarsa',
        }[o.status] || o.status;
        const date = o.created_at
          ? new Date(o.created_at).toLocaleString('id-ID', { dateStyle:'short', timeStyle:'short' })
          : '-';
        return `
          <div class="order-item">
            <div>
              <div class="order-amount">+ ${o.amount.toLocaleString('id-ID')} Token</div>
              <div class="order-meta">${date} · ${o.payment_type || 'Belum dibayar'}</div>
            </div>
            <span class="badge ${badgeClass}">${statusText}</span>
          </div>
        `;
      }).join('');

    } catch (e) {
      container.innerHTML = '<div style="color:var(--muted);font-size:.82rem;padding:8px 0">Gagal memuat riwayat.</div>';
    }
  }

  function setStatus(type, msg) {
    const el = document.getElementById('pay-status');
    el.className = `pay-status show ${type}`;
    el.textContent = msg;
  }
  function clearStatus() {
    document.getElementById('pay-status').classList.remove('show');
  }

  loadAmounts();
  loadOrders();
</script>
{% endblock %}