<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Workshop Series — Sellkit Sale Template</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script src="https://sk-api.vibery.app/embed/sdk.js"></script>
  <style>
    :root { --accent: #111827; --accent-hover: #1f2937; }
    @keyframes pulse-dot { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
    .pulse-dot { animation: pulse-dot 2s ease-in-out infinite; }
  </style>
</head>
<body class="bg-gray-50 antialiased">

<!-- ============================================================
  SELLKIT SALE PAGE TEMPLATE

  How to use:
  1. Copy this file to your site
  2. Edit the CONFIG section below (tenant, sale slug, API base)
  3. Customize the hero section, colors, copy
  4. The rest is automatic — product loading, pricing, checkout

  The template uses the Sellkit SDK for all API calls.
  No API key needed. Works on any domain.
============================================================ -->

<script>
// ==================== CONFIG ====================
const CONFIG = {
  apiBase: 'https://sk-api.vibery.app',
  tenantSlug: 'tony',
  saleSlug: 'agent-first-builder-april26',
  checkoutBase: 'https://sellkit.vibery.app',
};

// Workshop metadata keyed by variant ID prefix
const WORKSHOP_META = {
  '38d47e7c': { icon: '🛠', date: 'Thứ 3, 14/04', tagline: 'CLI commerce engine + Telegram flow', topics: ['Tư duy Agent-first', 'CLI design cho AI', 'VietQR payment', 'Auto-fulfillment'] },
  '702cc703': { icon: '🤖', date: 'Thứ 5, 16/04', tagline: 'MCP server + Code Mode pattern', topics: ['MCP trên Cloudflare Workers', 'Code Mode pattern', 'Agent vận hành bằng tiếng Việt', 'Share cho team'] },
  '159ec134': { icon: '🌐', date: 'Thứ 3, 21/04', tagline: 'Astro + EmDash trên Cloudflare', topics: ['Astro + EmDash CMS', 'Blog / Landing / Portfolio', 'Deploy Cloudflare', 'Kết nối commerce'] },
};

function getVariantMeta(vid) {
  for (const [prefix, meta] of Object.entries(WORKSHOP_META)) {
    if (vid.startsWith(prefix)) return meta;
  }
  return null;
}
// ================================================
</script>

<div id="app" class="min-h-screen">
  <!-- Hero -->
  <header class="relative overflow-hidden bg-gray-900 text-white">
    <div class="absolute inset-0" style="background: radial-gradient(ellipse at top, #374151, #111827, #000)"></div>
    <div class="relative max-w-3xl mx-auto px-4 py-12 sm:py-16 text-center">
      <div class="inline-flex items-center gap-2 rounded-full bg-white/10 backdrop-blur-sm px-3 py-1 text-xs font-medium text-gray-300 mb-4">
        <span class="inline-block w-1.5 h-1.5 rounded-full bg-green-400 pulse-dot"></span>
        Đang mở đăng ký
      </div>
      <h1 class="text-2xl sm:text-4xl font-bold tracking-tight mb-3" id="sale-name">Loading...</h1>
      <p class="text-gray-400 max-w-xl mx-auto text-sm sm:text-base leading-relaxed" id="sale-desc"></p>
      <div class="flex flex-wrap justify-center gap-4 mt-6 text-xs sm:text-sm text-gray-400">
        <span class="flex items-center gap-1.5">
          <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5" /></svg>
          3 buổi · 14-21/04
        </span>
        <span class="flex items-center gap-1.5">
          <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
          Mỗi buổi 120 phút · 20h
        </span>
        <span class="flex items-center gap-1.5">
          <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M9 17.25v1.007a3 3 0 01-.879 2.122L7.5 21h9l-.621-.621A3 3 0 0115 18.257V17.25m6-12V15a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 15V5.25m18 0A2.25 2.25 0 0018.75 3H5.25A2.25 2.25 0 003 5.25m18 0H3" /></svg>
          Online · Có recording
        </span>
      </div>
    </div>
  </header>

  <main class="max-w-3xl mx-auto px-4 py-8 sm:py-12">
    <!-- Checkout note -->
    <div id="checkout-note" class="hidden bg-blue-50 border border-blue-100 rounded-xl p-4 mb-8 text-sm text-blue-800"></div>

    <form id="checkout-form" onsubmit="handleSubmit(event)">
      <!-- Workshops -->
      <section class="mb-8">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-lg font-bold text-gray-900">Chọn buổi tham gia</h2>
          <div class="flex gap-2 text-xs">
            <button type="button" onclick="selectAll()" class="text-blue-600 hover:underline">Chọn tất cả</button>
            <span class="text-gray-300">|</span>
            <button type="button" onclick="selectNone()" class="text-gray-400 hover:underline">Bỏ chọn</button>
          </div>
        </div>
        <div id="products" class="space-y-3"></div>
        <p id="bundle-hint" class="hidden text-xs text-gray-400 mt-3 text-center">
          Đăng ký cả 3 buổi để được giá combo tốt hơn
        </p>
      </section>

      <!-- Customer info + Order summary grid -->
      <section class="grid grid-cols-1 lg:grid-cols-5 gap-6">
        <!-- Left: form -->
        <div class="lg:col-span-3 space-y-4">
          <h2 class="text-lg font-bold text-gray-900">Thông tin đăng ký</h2>

          <!-- Membership badge -->
          <div id="membership-badge" class="hidden flex items-center gap-2 rounded-xl p-3 text-sm font-medium"></div>

          <div class="rounded-2xl bg-white shadow-sm border border-gray-100 p-5 space-y-3">
            <input type="text" id="f-name" required placeholder="Họ và tên"
              class="w-full rounded-xl border border-gray-200 bg-gray-50 px-4 py-3 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-900 focus:ring-1 focus:ring-gray-900 focus:bg-white outline-none transition">
            <input type="email" id="f-email" required placeholder="Địa chỉ email"
              class="w-full rounded-xl border border-gray-200 bg-gray-50 px-4 py-3 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-900 focus:ring-1 focus:ring-gray-900 focus:bg-white outline-none transition">
            <p class="text-[10px] text-gray-400 -mt-1 ml-1">Nhập email để kiểm tra giá ưu đãi thành viên</p>
            <input type="tel" id="f-phone" placeholder="Số điện thoại (tùy chọn)"
              class="w-full rounded-xl border border-gray-200 bg-gray-50 px-4 py-3 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-900 focus:ring-1 focus:ring-gray-900 focus:bg-white outline-none transition">
            <div class="flex gap-2">
              <input type="text" id="f-coupon" placeholder="Mã giảm giá"
                class="flex-1 rounded-xl border border-gray-200 bg-gray-50 px-4 py-3 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-900 focus:ring-1 focus:ring-gray-900 focus:bg-white outline-none transition">
              <button type="button" onclick="applyCoupon()" id="coupon-btn"
                class="hidden rounded-xl bg-gray-100 px-4 py-3 text-sm font-medium text-gray-700 hover:bg-gray-200 transition">
                Áp dụng
              </button>
              <button type="button" onclick="removeCoupon()" id="coupon-remove-btn"
                class="hidden rounded-xl bg-red-50 px-4 py-3 text-sm font-medium text-red-600 hover:bg-red-100 transition">&times;</button>
            </div>
            <p id="coupon-msg" class="text-xs hidden"></p>

            <!-- Tax info toggle -->
            <button type="button" onclick="toggleTaxInfo()" id="tax-toggle"
              class="text-xs text-gray-400 hover:text-gray-600 transition">
              ▸ Xuất hóa đơn (tùy chọn)
            </button>
            <div id="tax-fields" class="hidden space-y-2 rounded-xl border border-gray-100 bg-gray-50 p-3">
              <input type="text" id="f-company" placeholder="Tên công ty"
                class="w-full rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-900 focus:ring-1 focus:ring-gray-900 outline-none transition">
              <input type="text" id="f-taxcode" placeholder="Mã số thuế (MST)"
                class="w-full rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-900 focus:ring-1 focus:ring-gray-900 outline-none transition">
              <input type="text" id="f-taxaddr" placeholder="Địa chỉ xuất hóa đơn"
                class="w-full rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-gray-900 focus:ring-1 focus:ring-gray-900 outline-none transition">
            </div>
          </div>
        </div>

        <!-- Right: Order summary -->
        <div class="lg:col-span-2">
          <div class="lg:sticky lg:top-6">
            <h2 class="text-lg font-bold text-gray-900 mb-4">Tóm tắt đơn hàng</h2>
            <div class="rounded-2xl bg-white shadow-sm border border-gray-100 p-5 space-y-4">
              <div id="summary-items" class="space-y-2">
                <p class="text-sm text-gray-400 text-center py-2">Chưa chọn buổi nào</p>
              </div>

              <div id="summary-totals" class="hidden">
                <div class="border-t border-gray-100 pt-3 space-y-2">
                  <div class="flex justify-between text-sm">
                    <span class="text-gray-500">Tạm tính</span>
                    <span class="text-gray-700" id="summary-subtotal"></span>
                  </div>
                  <div id="summary-adjustments" class="space-y-2"></div>
                  <div id="summary-tax" class="hidden flex justify-between text-sm">
                    <span class="text-gray-500" id="summary-tax-label">VAT</span>
                    <span class="text-gray-500" id="summary-tax-amount"></span>
                  </div>
                </div>
                <div class="border-t border-gray-100 pt-3 mt-3">
                  <div class="flex justify-between">
                    <span class="font-bold text-gray-900">Tổng cộng</span>
                    <div class="text-right">
                      <span class="text-xl font-bold text-gray-900" id="summary-total"></span>
                      <p class="text-xs text-gray-400 line-through hidden" id="summary-original"></p>
                    </div>
                  </div>
                  <p class="text-xs text-green-600 mt-1 text-right hidden" id="summary-savings"></p>
                </div>
              </div>

              <p id="loading-price" class="text-xs text-gray-400 text-center hidden animate-pulse">Đang tính giá...</p>
              <p id="error-msg" class="text-sm text-red-600 hidden"></p>

              <button type="submit" id="submit-btn" disabled
                class="w-full rounded-xl bg-gray-900 py-3.5 text-base font-semibold text-white transition hover:bg-gray-800 disabled:opacity-40 disabled:cursor-not-allowed active:scale-[0.98]">
                Chọn ít nhất 1 buổi
              </button>
            </div>
          </div>
        </div>
      </section>

      <!-- Mobile sticky footer -->
      <div id="mobile-footer" class="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4 lg:hidden z-50">
        <div class="flex items-center justify-between max-w-3xl mx-auto">
          <div>
            <p class="text-xs text-gray-500" id="mobile-count">0 buổi</p>
            <p class="text-lg font-bold text-gray-900" id="mobile-total">0₫</p>
          </div>
          <button type="submit" id="mobile-submit-btn" disabled
            class="rounded-xl bg-gray-900 px-6 py-3 text-sm font-semibold text-white transition hover:bg-gray-800 disabled:opacity-40 disabled:cursor-not-allowed active:scale-[0.98]">
            Chọn buổi
          </button>
        </div>
      </div>
      <div class="h-20 lg:hidden"></div>
    </form>

    <!-- Footer -->
    <div class="mt-8 text-center space-y-2 pb-4">
      <p class="text-xs text-gray-400">Host: Tony Bùi · Online · Có recording xem lại</p>
      <p class="text-xs text-gray-300">Powered by Sellkit</p>
    </div>
  </main>
</div>

<script>
const sk = new Sellkit(CONFIG.apiBase);
let saleData = null;
let selected = new Set();
let currentPricing = null;
let couponApplied = false;
let debounceTimer = null;

async function init() {
  try {
    const res = await fetch(`${CONFIG.apiBase}/api/v1/public/${CONFIG.tenantSlug}/sale/${CONFIG.saleSlug}`);
    saleData = await res.json();

    document.getElementById('sale-name').textContent = saleData.sale.name;
    document.getElementById('sale-desc').textContent = saleData.sale.description || '';

    if (saleData.checkout_note) {
      const noteEl = document.getElementById('checkout-note');
      noteEl.textContent = saleData.checkout_note;
      noteEl.classList.remove('hidden');
    }

    renderProducts();
    saleData.products.forEach(p => {
      if (p.variants && p.variants[0]) selected.add(p.variants[0].id);
    });
    updateSelection();
  } catch (e) {
    document.getElementById('sale-name').textContent = 'Không tìm thấy chương trình';
  }
}

function renderProducts() {
  const container = document.getElementById('products');
  container.innerHTML = saleData.products.map((p, i) => {
    const v = p.variants[0];
    if (!v) return '';
    const meta = getVariantMeta(v.id);
    return `
      <label data-vid="${v.id}" onclick="toggleProduct('${v.id}')"
        class="product-card group block cursor-pointer rounded-2xl border-2 border-gray-200 bg-white p-4 sm:p-5 transition-all hover:border-gray-300 hover:shadow-sm">
        <div class="flex items-start gap-3 sm:gap-4">
          <input type="checkbox" class="product-cb mt-1 h-4 w-4 rounded border-gray-300 text-gray-900 focus:ring-gray-900 pointer-events-none" data-vid="${v.id}">
          <div class="flex-1 min-w-0">
            <div class="flex items-center gap-2 flex-wrap">
              <span class="text-lg">${meta?.icon || '📦'}</span>
              <span class="font-semibold text-gray-900">Buổi ${i + 1}</span>
              ${meta?.date ? `<span class="text-xs bg-gray-100 text-gray-500 rounded-full px-2 py-0.5">${meta.date}</span>` : ''}
            </div>
            <p class="text-sm font-medium text-gray-700 mt-1">${p.name}</p>
            ${meta?.tagline ? `<p class="text-xs text-gray-400 mt-0.5">${meta.tagline}</p>` : ''}
            <div class="topic-tags hidden flex-wrap gap-1.5 mt-2">
              ${(meta?.topics || []).map(t => `<span class="text-[10px] bg-gray-50 text-gray-500 rounded-full px-2 py-0.5 border border-gray-100">${t}</span>`).join('')}
            </div>
          </div>
          <div class="text-right shrink-0">
            <span class="product-price font-bold text-sm text-gray-500">${Sellkit.formatPrice(v.price, v.currency)}</span>
          </div>
        </div>
      </label>
    `;
  }).join('');
}

function toggleProduct(vid) {
  if (selected.has(vid)) selected.delete(vid);
  else selected.add(vid);
  updateSelection();
}

function selectAll() {
  saleData.products.forEach(p => { if (p.variants[0]) selected.add(p.variants[0].id); });
  updateSelection();
}

function selectNone() {
  selected.clear();
  updateSelection();
}

function updateSelection() {
  // Update card styles
  document.querySelectorAll('.product-card').forEach(card => {
    const vid = card.dataset.vid;
    const cb = card.querySelector('.product-cb');
    const tags = card.querySelector('.topic-tags');
    const price = card.querySelector('.product-price');
    const isSelected = selected.has(vid);
    cb.checked = isSelected;

    card.className = card.className.replace(/border-\S+/g, '').replace(/shadow-\S+/g, '');
    if (isSelected) {
      card.classList.add('border-gray-900', 'shadow-md');
      price.classList.remove('text-gray-500');
      price.classList.add('text-gray-900');
      if (tags) tags.classList.remove('hidden');
      if (tags) tags.classList.add('flex');
    } else {
      card.classList.add('border-gray-200');
      price.classList.remove('text-gray-900');
      price.classList.add('text-gray-500');
      if (tags) tags.classList.add('hidden');
      if (tags) tags.classList.remove('flex');
    }
  });

  // Bundle hint
  const hint = document.getElementById('bundle-hint');
  if (selected.size > 0 && selected.size < saleData.products.length) {
    hint.classList.remove('hidden');
  } else {
    hint.classList.add('hidden');
  }

  // Calculate raw total
  const rawTotal = saleData.products.reduce((sum, p) => {
    const v = p.variants[0];
    return v && selected.has(v.id) ? sum + v.price : sum;
  }, 0);

  // Update summary
  updateSummary(rawTotal);

  // Update buttons
  const total = currentPricing ? currentPricing.total : rawTotal;
  const isFree = total === 0 && selected.size > 0;
  updateButtons(total, isFree);

  // Debounced pricing preview
  if (debounceTimer) clearTimeout(debounceTimer);
  if (selected.size > 0) {
    debounceTimer = setTimeout(() => fetchPricing(), 400);
  }
}

function updateSummary(rawTotal) {
  const itemsEl = document.getElementById('summary-items');
  const totalsEl = document.getElementById('summary-totals');

  if (selected.size === 0) {
    itemsEl.innerHTML = '<p class="text-sm text-gray-400 text-center py-2">Chưa chọn buổi nào</p>';
    totalsEl.classList.add('hidden');
    return;
  }

  itemsEl.innerHTML = saleData.products.map((p, i) => {
    const v = p.variants[0];
    if (!v || !selected.has(v.id)) return '';
    return `<div class="flex justify-between text-sm"><span class="text-gray-600">Buổi ${i + 1}</span><span class="text-gray-900 font-medium">${Sellkit.formatPrice(v.price, v.currency)}</span></div>`;
  }).join('');

  totalsEl.classList.remove('hidden');
  document.getElementById('summary-subtotal').textContent = Sellkit.formatPrice(rawTotal, 'vnd');

  const total = currentPricing ? currentPricing.total : rawTotal;
  const isFree = total === 0 && selected.size > 0;
  document.getElementById('summary-total').textContent = isFree ? 'Miễn phí' : Sellkit.formatPrice(total, 'vnd');

  // Adjustments
  const adjEl = document.getElementById('summary-adjustments');
  if (currentPricing && currentPricing.adjustments.length > 0) {
    adjEl.innerHTML = currentPricing.adjustments.map(adj =>
      `<div class="flex justify-between text-sm"><span class="text-green-600">${adj.rule_name}</span><span class="text-green-600 font-medium">-${Sellkit.formatPrice(adj.amount, 'vnd')}</span></div>`
    ).join('');
  } else {
    adjEl.innerHTML = '';
  }

  // Tax
  if (currentPricing?.tax_amount > 0) {
    document.getElementById('summary-tax').classList.remove('hidden');
    document.getElementById('summary-tax-label').textContent = currentPricing.tax_inclusive ? 'Đã bao gồm VAT' : 'VAT';
    document.getElementById('summary-tax-amount').textContent = (currentPricing.tax_inclusive ? '' : '+') + Sellkit.formatPrice(currentPricing.tax_amount, 'vnd');
  } else {
    document.getElementById('summary-tax').classList.add('hidden');
  }

  // Savings
  const origEl = document.getElementById('summary-original');
  const saveEl = document.getElementById('summary-savings');
  if (currentPricing && currentPricing.discount > 0) {
    origEl.textContent = Sellkit.formatPrice(rawTotal, 'vnd');
    origEl.classList.remove('hidden');
    saveEl.textContent = `Tiết kiệm ${Sellkit.formatPrice(currentPricing.discount, 'vnd')}`;
    saveEl.classList.remove('hidden');
  } else {
    origEl.classList.add('hidden');
    saveEl.classList.add('hidden');
  }
}

function updateButtons(total, isFree) {
  const btn = document.getElementById('submit-btn');
  const mBtn = document.getElementById('mobile-submit-btn');
  const mCount = document.getElementById('mobile-count');
  const mTotal = document.getElementById('mobile-total');

  mCount.textContent = `${selected.size} buổi`;
  mTotal.textContent = isFree ? 'Miễn phí' : Sellkit.formatPrice(total, 'vnd');

  if (selected.size === 0) {
    btn.textContent = 'Chọn ít nhất 1 buổi';
    btn.disabled = true;
    mBtn.textContent = 'Chọn buổi';
    mBtn.disabled = true;
  } else {
    btn.textContent = isFree ? 'Đăng ký miễn phí' : `Thanh toán ${Sellkit.formatPrice(total, 'vnd')}`;
    btn.disabled = false;
    mBtn.textContent = isFree ? 'Đăng ký' : 'Thanh toán';
    mBtn.disabled = false;
  }
}

async function fetchPricing(couponCode) {
  const variantIds = Array.from(selected);
  if (variantIds.length === 0) return;

  const email = document.getElementById('f-email').value;
  document.getElementById('loading-price').classList.remove('hidden');

  try {
    currentPricing = await sk.previewPricing({
      tenant_slug: CONFIG.tenantSlug,
      variant_ids: variantIds,
      email: email || '',
      quantity: 1,
      coupon_code: couponCode || (couponApplied ? document.getElementById('f-coupon').value : ''),
    });

    if (couponCode) {
      couponApplied = !currentPricing.coupon_error;
      showCouponMsg();
      updateCouponButtons();
    }

    detectMembership();

    const rawTotal = saleData.products.reduce((sum, p) => {
      const v = p.variants[0];
      return v && selected.has(v.id) ? sum + v.price : sum;
    }, 0);
    updateSummary(rawTotal);

    const isFree = currentPricing.total === 0 && selected.size > 0;
    updateButtons(currentPricing.total, isFree);
  } catch (e) { /* ignore */ }
  finally {
    document.getElementById('loading-price').classList.add('hidden');
  }
}

function detectMembership() {
  const badge = document.getElementById('membership-badge');
  if (!currentPricing || currentPricing.discount === 0) {
    badge.classList.add('hidden');
    return;
  }
  let tier = null;
  for (const adj of currentPricing.adjustments) {
    const n = adj.rule_name.toLowerCase();
    if (n.includes('vip')) { tier = 'VIP'; break; }
    if (n.includes('premium')) { tier = 'Premium'; break; }
    if (n.includes('alumni')) { tier = 'Alumni'; break; }
  }
  if (!tier) { badge.classList.add('hidden'); return; }

  const styles = {
    VIP: { bg: 'bg-amber-50 border-amber-200 text-amber-800', icon: '⭐', text: 'Bạn là VIP member! Giá ưu đãi đặc biệt đã được áp dụng.' },
    Premium: { bg: 'bg-purple-50 border-purple-200 text-purple-800', icon: '💎', text: 'Bạn là Premium member! Đã áp dụng giá ưu đãi.' },
    Alumni: { bg: 'bg-blue-50 border-blue-200 text-blue-800', icon: '🎓', text: 'Alumni member! Đã áp dụng giá ưu đãi.' },
  };
  const s = styles[tier];
  badge.className = `flex items-center gap-2 rounded-xl p-3 text-sm font-medium border ${s.bg}`;
  badge.innerHTML = `<span>${s.icon}</span><span>${s.text}</span>`;
  badge.classList.remove('hidden');
}

function showCouponMsg() {
  const msg = document.getElementById('coupon-msg');
  if (currentPricing?.coupon_error) {
    msg.textContent = currentPricing.coupon_error;
    msg.className = 'text-xs text-red-500';
    msg.classList.remove('hidden');
  } else if (currentPricing?.coupon_discount > 0) {
    msg.textContent = `Mã ${currentPricing.coupon_code || document.getElementById('f-coupon').value}: giảm ${Sellkit.formatPrice(currentPricing.coupon_discount, 'vnd')}`;
    msg.className = 'text-xs text-green-600';
    msg.classList.remove('hidden');
  } else {
    msg.classList.add('hidden');
  }
}

function updateCouponButtons() {
  const couponVal = document.getElementById('f-coupon').value.trim();
  document.getElementById('coupon-btn').classList.toggle('hidden', !couponVal || couponApplied);
  document.getElementById('coupon-remove-btn').classList.toggle('hidden', !couponApplied);
}

function applyCoupon() {
  const code = document.getElementById('f-coupon').value.trim();
  if (code) fetchPricing(code);
}

function removeCoupon() {
  document.getElementById('f-coupon').value = '';
  couponApplied = false;
  updateCouponButtons();
  document.getElementById('coupon-msg').classList.add('hidden');
  fetchPricing();
}

function toggleTaxInfo() {
  const fields = document.getElementById('tax-fields');
  const toggle = document.getElementById('tax-toggle');
  const isHidden = fields.classList.contains('hidden');
  fields.classList.toggle('hidden');
  toggle.textContent = isHidden ? '▾ Ẩn thông tin xuất hóa đơn' : '▸ Xuất hóa đơn (tùy chọn)';
}

// Coupon input handler
document.getElementById('f-coupon').addEventListener('input', function() {
  if (couponApplied) { couponApplied = false; }
  updateCouponButtons();
});

// Email blur → fetch pricing (membership detection)
document.getElementById('f-email').addEventListener('blur', function() {
  if (this.value && selected.size > 0) fetchPricing();
});

async function handleSubmit(e) {
  e.preventDefault();
  const btn = document.getElementById('submit-btn');
  const mBtn = document.getElementById('mobile-submit-btn');
  const errEl = document.getElementById('error-msg');
  errEl.classList.add('hidden');

  btn.disabled = true;
  btn.textContent = 'Đang xử lý...';
  mBtn.disabled = true;
  mBtn.textContent = 'Đang xử lý...';

  const taxCode = document.getElementById('f-taxcode').value;

  try {
    const order = await sk.checkout({
      tenant_slug: CONFIG.tenantSlug,
      variant_ids: Array.from(selected),
      name: document.getElementById('f-name').value,
      email: document.getElementById('f-email').value,
      phone: document.getElementById('f-phone').value || undefined,
      coupon_code: couponApplied ? document.getElementById('f-coupon').value : undefined,
      ref: new URLSearchParams(window.location.search).get('ref') || undefined,
      sale_id: saleData?.sale?.id,
      tax_info: taxCode ? {
        company_name: document.getElementById('f-company').value,
        tax_code: taxCode,
        address: document.getElementById('f-taxaddr').value,
      } : undefined,
    });

    // Set order in URL so it survives reload / can be shared to another device
    window.history.replaceState(null, '', '#order=' + order.order_id);

    if (order.is_free) {
      showSuccessScreen(order);
    } else {
      showPaymentScreen(order);
    }
  } catch (err) {
    errEl.textContent = err.message || 'Checkout failed';
    errEl.classList.remove('hidden');
    const total = currentPricing?.total || 0;
    const isFree = total === 0 && selected.size > 0;
    btn.disabled = false;
    btn.textContent = isFree ? 'Đăng ký miễn phí' : `Thanh toán ${Sellkit.formatPrice(total, 'vnd')}`;
    mBtn.disabled = false;
    mBtn.textContent = isFree ? 'Đăng ký' : 'Thanh toán';
  }
}

function showSuccessScreen(order) {
  document.getElementById('app').innerHTML = `
    <div class="flex min-h-screen items-center justify-center p-4 bg-gray-50">
      <div class="w-full max-w-md rounded-2xl bg-white p-8 shadow-lg text-center space-y-4">
        <div class="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-green-100">
          <svg class="h-8 w-8 text-green-600" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />
          </svg>
        </div>
        <h2 class="text-xl font-bold text-gray-900">Thanh toán thành công!</h2>
        <p class="text-gray-500">Đơn hàng #${order.order_number} đã được xác nhận</p>
        <p class="text-sm text-gray-400">Kiểm tra email của bạn để biết chi tiết.</p>
      </div>
    </div>`;
}

function showPaymentScreen(order) {
  const isQR = order.checkout_url && (order.checkout_url.includes('qr') || order.checkout_url.includes('sepay') || order.checkout_url.includes('vietqr'));

  let paymentContent = '';
  if (isQR) {
    paymentContent = `
      <div class="flex justify-center">
        <img src="${order.checkout_url}" alt="Mã QR thanh toán" class="h-64 w-64 rounded-xl" />
      </div>`;
  } else if (order.checkout_url) {
    paymentContent = `
      <a href="${order.checkout_url}" target="_blank" rel="noopener noreferrer"
        class="inline-block rounded-xl bg-blue-600 px-6 py-3 font-semibold text-white hover:bg-blue-700">
        Thanh toán ngay
      </a>`;
  }

  document.getElementById('app').innerHTML = `
    <div class="flex min-h-screen items-center justify-center p-4 bg-gray-50">
      <div class="w-full max-w-md">
        <div class="rounded-2xl bg-white shadow-lg p-6 text-center space-y-4">
          <h2 class="text-lg font-semibold text-gray-900">Hoàn tất thanh toán</h2>
          <p class="text-sm text-gray-500">
            Đơn hàng #${order.order_number} · ${Sellkit.formatPrice(order.total, order.currency)}
          </p>
          ${paymentContent}
          <div id="payment-status" class="flex items-center justify-center gap-2 text-sm text-gray-500">
            <div class="h-4 w-4 animate-spin rounded-full border-2 border-blue-600 border-t-transparent"></div>
            Đang chờ thanh toán...
          </div>
        </div>
        <p class="mt-6 text-center text-xs text-gray-400">Được cung cấp bởi Sellkit</p>
      </div>
    </div>`;

  // Poll for payment status
  sk.pollStatus(order.order_id, function(status) {
    if (status.status === 'paid' || status.status === 'fulfilled') {
      showSuccessScreen({order_number: status.order_number || order.order_number});
    } else if (status._timeout) {
      document.getElementById('payment-status').innerHTML =
        '<span class="text-yellow-600">Phiên thanh toán đã hết hạn. <a href="javascript:location.reload()" class="underline">Thử lại</a></span>';
    }
  });
}

// Check for existing order in URL hash (resume after reload / share to another device)
var hashOrder = window.location.hash.match(/order=([a-f0-9-]+)/);
if (hashOrder) {
  (async function resumeOrder() {
    try {
      var status = await sk.getOrderStatus(hashOrder[1]);
      if (status.status === 'paid' || status.status === 'fulfilled') {
        showSuccessScreen({order_number: status.order_number});
      } else if (status.status === 'pending') {
        // Reconstruct minimal order object for payment screen
        showPaymentScreen({
          order_id: hashOrder[1],
          order_number: status.order_number,
          total: status.total || 0,
          currency: status.currency || 'vnd',
          checkout_url: status.checkout_url || '',
        });
      } else {
        // Canceled/refunded/expired — clear hash, show form
        window.history.replaceState(null, '', window.location.pathname + window.location.search);
        init();
      }
    } catch (e) {
      window.history.replaceState(null, '', window.location.pathname + window.location.search);
      init();
    }
  })();
} else {
  init();
}
</script>

</body>
</html>
