/* ZA-FARM-KH — License Key Store */
const API_BASE = window.location.hostname === "localhost" ? "http://localhost:3000/zapi" : "/zapi";
let user = JSON.parse(localStorage.getItem("zafarm_user") || "null");
let token = localStorage.getItem("zafarm_token");
let packages = [];
let selectedPackageId = null;

document.addEventListener("DOMContentLoaded", async () => {
  initMobileMenu(); initLiveTime();
  await loadPackages(); bindTabs(); bindBuyModal(); bindRenew(); bindCheck();
  if (!token) {
    const balEl = document.getElementById("userBalance");
    if (balEl) balEl.textContent = "Guest";
    const logoutBtn = document.getElementById("logoutBtn");
    if (logoutBtn) {
      logoutBtn.innerHTML = `<span style="font-size:13px;font-weight:700;color:var(--gold);">🔑 Login</span>`;
      logoutBtn.onclick = () => { window.location.href = "/login"; };
    }
    return;
  }
  renderBalance(); bindLogout(); await loadMyKeys(); loadOnlineCount();
  
  // Auto-switch to renew tab if URL hash is #renew or #tab-renew
  const hash = window.location.hash;
  if (hash === "#renew" || hash === "#tab-renew") {
    const renewBtn = document.querySelector('[data-tab="renew"]');
    if (renewBtn) renewBtn.click();
  }
});

function initMobileMenu() {
  const btn = document.getElementById("menuToggle"), sidebar = document.getElementById("sidebar");
  if (btn && sidebar) { btn.addEventListener("click", () => sidebar.classList.toggle("open")); document.addEventListener("click", (e) => { if (!sidebar.contains(e.target) && !btn.contains(e.target)) sidebar.classList.remove("open"); }); }
}
function initLiveTime() { const el = document.getElementById("liveTime"); if (!el) return; const u = () => { el.textContent = new Date().toLocaleTimeString("en-US", { hour12: false }); }; u(); setInterval(u, 1000); }
function renderBalance() { const b = user ? (user.balance || 0).toFixed(3) : "0.000"; const el = document.getElementById("userBalance"), mob = document.getElementById("mobileBalance"); if (el) el.textContent = "$" + b; if (mob) mob.textContent = "$" + b; }
function escapeHtml(s) { if (typeof s !== "string") return ""; return s.replace(/[&<>"']/g, c => ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;"})[c]); }

function bindTabs() { document.querySelectorAll(".tab-btn").forEach(btn => { btn.addEventListener("click", () => { document.querySelectorAll(".tab-btn").forEach(b => b.classList.remove("active")); document.querySelectorAll(".tab-content").forEach(c => c.classList.remove("active")); btn.classList.add("active"); const t = document.getElementById("tab-" + btn.dataset.tab); if (t) t.classList.add("active"); }); }); }

async function loadPackages() { try { const r = await fetch(API_BASE + "/license/packages"); if (r.ok) packages = await r.json(); } catch {} renderPackages(); populateRenewSelect(); }

function renderPackages() {
  const proG = document.getElementById("proPackages");
  if (!proG) return;
  proG.innerHTML = packages.filter(p => p.type === "PRO").map(packageCard).join("");
  document.querySelectorAll(".pkg-buy-btn").forEach(btn => btn.addEventListener("click", () => openBuyModal(btn.dataset.id)));
}

function packageCard(p) {
  const icon = "💎";
  return '<div class="pkg-card"><div class="pkg-icon">' + icon + '</div><div class="pkg-name">' + escapeHtml(p.name) + '</div><div class="pkg-meta"><span>' + p.days + ' days</span><span>' + p.type + '</span></div><div class="pkg-price">$' + p.price + '</div><button class="pkg-buy-btn" data-id="' + escapeHtml(p.id) + '">Buy Now</button></div>';
}

function populateRenewSelect() { const s = document.getElementById("renewPackageSelect"); if (!s) return; s.innerHTML = packages.map(p => '<option value="' + escapeHtml(p.id) + '">' + escapeHtml(p.name) + ' — $' + p.price + '</option>').join(""); }

function bindBuyModal() {
  const c = document.getElementById("closeLicenseModal"), o = document.getElementById("buyLicenseModal"), b = document.getElementById("confirmLicenseBuy");
  if (c) c.addEventListener("click", closeBuyModal);
  if (o) o.addEventListener("click", (e) => { if (e.target === o) closeBuyModal(); });
  if (b) b.addEventListener("click", confirmBuy);
}
function openBuyModal(id) {
  if (!token) {
    if (typeof showGuestAuthModal === "function") showGuestAuthModal();
    else window.location.href = "/login";
    return;
  }
  const p = packages.find(x => x.id === id); if (!p) return;
  selectedPackageId = id;
  document.getElementById("modalPkgName").textContent = p.name;
  document.getElementById("modalPkgType").textContent = p.type;
  document.getElementById("modalDays").textContent = p.days + " days";
  document.getElementById("modalType").textContent = p.type;
  document.getElementById("modalLicensePrice").textContent = "$" + p.price.toFixed(2);
  document.getElementById("buyLicenseModal").classList.add("show");
}
function closeBuyModal() { document.getElementById("buyLicenseModal").classList.remove("show"); selectedPackageId = null; }

async function confirmBuy() {
  if (!selectedPackageId) return;
  const pkg = packages.find(p => p.id === selectedPackageId);
  if (!pkg) return;
  if (!user || (user.balance || 0) < pkg.price) {
    const needed = parseFloat(pkg.price);
    closeBuyModal();
    if (typeof openDirectKhqrModal === "function") {
      openDirectKhqrModal(needed, `ទិញកញ្ចប់ ${pkg.name} ($${pkg.price.toFixed(2)})`, async () => {
        await executeDirectLicenseBuy(pkg.id);
      });
    } else {
      showToast("Balance not enough — need $" + pkg.price, true);
    }
    return;
  }
  await executeDirectLicenseBuy(pkg.id);
}

async function executeDirectLicenseBuy(pkgId) {
  const btn = document.getElementById("confirmLicenseBuy");
  if (btn) { btn.disabled = true; btn.textContent = "Processing..."; }
  try {
    const r = await fetch(API_BASE + "/license/buy", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer " + token }, body: JSON.stringify({ packageId: pkgId }) });
    const d = await r.json();
    if (!r.ok) throw new Error(d.message);
    user = JSON.parse(localStorage.getItem("zafarm_user") || '{}');
    if (d.newBalance !== undefined) { user.balance = d.newBalance; localStorage.setItem("zafarm_user", JSON.stringify(user)); }
    renderBalance(); closeBuyModal();
    showKeyResult(d.license);
    await loadMyKeys();
    showToast("ទិញ License ជោគជ័យ! ✅");
  } catch (e) { showToast(e.message || "Error", true); }
  finally { if (btn) { btn.disabled = false; btn.textContent = "Confirm Purchase 🔑"; } }
}

function showKeyResult(license) {
  showToast("License Key purchased successfully!");
  const html = '<div class="key-result-card"><h3>Your New License Key</h3><div class="key-display"><code>' + escapeHtml(license.key) + '</code><button class="copy-key-btn" onclick="copyKey(\'' + escapeHtml(license.key) + '\')">Copy</button></div><div class="key-info"><span>Package: ' + escapeHtml(license.package) + '</span><span>Type: ' + license.type + '</span><span>Expiry: ' + license.expiryDate + '</span><span>Days: ' + license.days + '</span></div></div>';
  const tab = document.getElementById("tab-buy");
  const existing = tab.querySelector(".key-result-card");
  if (existing) existing.remove();
  tab.insertAdjacentHTML("afterbegin", html);
}

function copyKey(key) {
  if (navigator.clipboard && window.isSecureContext) {
    navigator.clipboard.writeText(key).then(() => showToast("Copied: " + key)).catch(() => fallbackCopy(key));
  } else {
    fallbackCopy(key);
  }
  function fallbackCopy(k) {
    const t = document.createElement("textarea"); t.value = k; document.body.appendChild(t); t.select();
    try { document.execCommand("copy"); showToast("Copied: " + k); } catch (e) { showToast("Copy failed", true); }
    document.body.removeChild(t);
  }
}

function bindRenew() {
  const btn = document.getElementById("renewBtn");
  if (btn) btn.addEventListener("click", doRenew);
}
async function doRenew() {
  if (!token) {
    if (typeof showGuestAuthModal === "function") showGuestAuthModal();
    else window.location.href = "/login";
    return;
  }
  const key = document.getElementById("renewKeyInput").value.trim();
  const pkgId = document.getElementById("renewPackageSelect").value;
  if (!key) { showToast("Please enter your License Key", true); return; }
  if (!pkgId) { showToast("Please select a package", true); return; }
  const btn = document.getElementById("renewBtn");
  btn.disabled = true; btn.textContent = "Processing...";
  try {
    const r = await fetch(API_BASE + "/license/renew", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer " + token }, body: JSON.stringify({ licenseKey: key, packageId: pkgId }) });
    const d = await r.json();
    if (!r.ok) throw new Error(d.message);
    user.balance = d.newBalance; localStorage.setItem("zafarm_user", JSON.stringify(user));
    renderBalance();
    document.getElementById("renewResult").style.display = "block";
    document.getElementById("renewResult").innerHTML = '<div class="result-success"><h4>Renewal Successful!</h4><p>Key: <code>' + escapeHtml(d.license.key) + '</code></p><p>New Expiry: ' + d.license.expiryDate + '</p><p>Package: ' + escapeHtml(d.license.package) + '</p></div>';
    showToast("Renewed successfully!");
  } catch (e) { showToast(e.message || "Error", true); }
  finally { btn.disabled = false; btn.textContent = "Renew Now"; }
}

function bindCheck() {
  const btn = document.getElementById("checkBtn");
  if (btn) btn.addEventListener("click", doCheck);
}
async function doCheck() {
  const key = document.getElementById("checkKeyInput").value.trim();
  if (!key) { showToast("Please enter a License Key", true); return; }
  const btn = document.getElementById("checkBtn");
  btn.disabled = true;
  try {
    const r = await fetch(API_BASE + "/license/check", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ licenseKey: key }) });
    const d = await r.json();
    if (!r.ok) throw new Error(d.message);
    const statusIcon = d.status === "active" ? "✅" : d.status === "expired" ? "⚠️" : "⛔";
    document.getElementById("checkResult").style.display = "block";
    document.getElementById("checkResult").innerHTML = '<div class="result-info"><h4>' + statusIcon + ' License Info</h4><p>Key: <code>' + escapeHtml(d.key) + '</code></p><p>Package: ' + escapeHtml(d.package) + '</p><p>Expiry: ' + d.expiryDate + '</p><p>Status: <strong>' + d.status.toUpperCase() + '</strong></p></div>';
  } catch (e) { showToast(e.message || "Error", true); }
  finally { btn.disabled = false; }
}

async function loadMyKeys() {
  const list = document.getElementById("myKeysList"); if (!list) return;
  try {
    const r = await fetch(API_BASE + "/license/my-keys", { headers: { Authorization: "Bearer " + token } });
    if (!r.ok) return;
    const keys = await r.json();
    if (keys.length === 0) { list.innerHTML = '<div class="empty-state"><div class="empty-icon">🔑</div><p>No License Keys yet</p></div>'; return; }
    list.innerHTML = keys.map(k => {
      const exp = new Date(k.expiry_date); const now = new Date();
      const st = !k.is_active ? "banned" : exp < now ? "expired" : "active";
      const icon = st === "active" ? "✅" : st === "expired" ? "⚠️" : "⛔";
      return '<div class="my-key-card"><div class="my-key-top"><span class="my-key-status ' + st + '">' + icon + ' ' + st.toUpperCase() + '</span><span class="my-key-date">' + (k.created_at ? new Date(k.created_at).toLocaleDateString() : "") + '</span></div><div class="my-key-value"><code>' + escapeHtml(k.license_key) + '</code><button class="copy-key-btn" onclick="copyKey(\'' + escapeHtml(k.license_key) + '\')">Copy</button></div><div class="my-key-info"><span>' + escapeHtml(k.package_name || "") + '</span><span>Exp: ' + k.expiry_date + '</span></div></div>';
    }).join("");
  } catch {}
}

function bindLogout() { const b = document.getElementById("logoutBtn"); if (b) b.addEventListener("click", () => { localStorage.removeItem("zafarm_token"); localStorage.removeItem("zafarm_user"); window.location.href = "/login"; }); }
function showToast(msg, err) { const t = document.getElementById("toast"); if (!t) return; t.textContent = msg; t.style.borderColor = err ? "var(--red, #ef4444)" : "var(--primary, #f59e0b)"; t.classList.add("show"); setTimeout(() => t.classList.remove("show"), 2500); }

/* ---------- Online Count ---------- */
async function loadOnlineCount() {
  try {
    const res = await fetch(API_BASE + "/online-count");
    if (res.ok) {
      const data = await res.json();
      const el = document.getElementById("onlineCount");
      if (el) el.textContent = data.count;
    }
  } catch {}
  setTimeout(loadOnlineCount, 10000);
}
