let clientsCache = [];

const $ = (id) => document.getElementById(id);

async function apiPost(path, payload = {}) {
  const res = await fetch(`./api/${path}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    credentials: "include",
    body: JSON.stringify(payload)
  });
  const rawText = await res.text();
  let data = {};
  try {
    if (rawText) data = JSON.parse(rawText);
  } catch {
    /* non-JSON body (e.g. PHP/HTML error page) */
  }
  if (!data || typeof data !== "object") data = {};

  const failed = !res.ok || data.status === "error";
  if (!failed) return data;

  const http = `HTTP ${res.status}`;
  const msg = typeof data.message === "string" ? data.message.trim() : "";
  if (msg) throw new Error(`${msg} (${http})`);

  const snippet = rawText.replace(/\s+/g, " ").trim().slice(0, 200);
  const detail = snippet ? `: ${snippet}` : "";
  throw new Error(`${http} ${path}${detail}`);
}

function setMsg(id, text, danger = false) {
  const el = $(id);
  if (!el) return;
  el.textContent = text || "";
  el.classList.toggle("danger", !!danger);
}

function escapeHtml(s) {
  return String(s ?? "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

function statusPill(status) {
  const safe = String(status || "active");
  const esc = escapeHtml(safe);
  const cls = safe === "suspended" ? "status-suspended" : "status-active";
  return `<span class="status-pill ${cls}">${esc}</span>`;
}

function renderClients() {
  const q = ($("search-q").value || "").toLowerCase();
  const f = $("filter-status").value;
  const tbody = $("clients-tbody");
  const rows = clientsCache.filter((c) => {
    const okQ = !q || c.clientId.toLowerCase().includes(q) || (c.siteName || "").toLowerCase().includes(q);
    const okF = f === "all" || c.status === f;
    return okQ && okF;
  });
  tbody.innerHTML = rows.map((c) => {
    const cid = escapeHtml(c.clientId);
    const site = escapeHtml(c.siteName || "-");
    const bal = escapeHtml(Number(c.balance || 0).toFixed(2));
    const fillAttr = escapeHtml(c.clientId);
    return `
    <tr>
      <td>${cid}</td>
      <td>${site}</td>
      <td>${statusPill(c.status)}</td>
      <td>${bal}</td>
      <td>
        <button type="button" class="secondary" data-fill="${fillAttr}">Use</button>
      </td>
    </tr>
  `;
  }).join("");
  tbody.querySelectorAll("button[data-fill]").forEach((btn) => {
    btn.addEventListener("click", () => {
      const cid = btn.getAttribute("data-fill");
      $("action-client-id").value = cid;
      $("wallet-client-id").value = cid;
      $("imp-client-id").value = cid;
    });
  });
}

async function refreshClients() {
  setMsg("action-msg", "Loading clients...");
  const data = await apiPost("super-admin-list-clients.php", {});
  clientsCache = Array.isArray(data.clients) ? data.clients : [];
  renderClients();
  setMsg("action-msg", `Loaded ${clientsCache.length} clients.`);
}

async function tryAuthSession() {
  try {
    const data = await apiPost("super-admin-auth-check.php", {});
    if (data && data.status === "success" && data.allowed) return data;
  } catch {
    return null;
  }
  return null;
}

function showLoginView() {
  $("login-view").classList.remove("hidden");
  $("app-view").classList.add("hidden");
}

function showAppView(email, uid) {
  $("login-view").classList.add("hidden");
  $("app-view").classList.remove("hidden");
  const u = uid ? String(uid) : "session";
  $("whoami").textContent = `${email} (${u})`;
}

function clearLegacyClientAuthKeys() {
  localStorage.removeItem("sa_logged_in");
  localStorage.removeItem("sa_email");
}

async function login() {
  const email = $("login-email").value.trim();
  const password = $("login-password").value;
  try {
    setMsg("login-msg", "");
    await apiPost("super-admin-login.php", { email, password });
    const me = await tryAuthSession();
    if (!me) throw new Error("Session not established");
    showAppView(me.email || email, me.uid);
    await refreshClients().catch((err) => setMsg("action-msg", err.message || "Client API unavailable", true));
  } catch (err) {
    setMsg("login-msg", err.message || "Login failed", true);
  }
}

async function logout() {
  try {
    await apiPost("super-admin-logout.php", {});
  } catch {
    /* still leave UI; server session may already be gone */
  }
  clientsCache = [];
  const tbody = $("clients-tbody");
  if (tbody) tbody.innerHTML = "";
  $("login-password").value = "";
  setMsg("login-msg", "");
  setMsg("action-msg", "");
  showLoginView();
}

async function setStatus() {
  try {
    const clientId = $("action-client-id").value.trim();
    const status = $("action-status").value;
    const data = await apiPost("super-admin-update-client.php", { clientId, status });
    setMsg("action-msg", data.message || "Client status updated.");
    await refreshClients();
  } catch (err) {
    setMsg("action-msg", err.message, true);
  }
}

async function adjustWallet() {
  try {
    const clientId = $("wallet-client-id").value.trim();
    const amount = Number($("wallet-amount").value || 0);
    const note = $("wallet-note").value.trim();
    const data = await apiPost("super-admin-wallet-adjust.php", { clientId, amount, note });
    setMsg("action-msg", data.message || "Wallet updated.");
    await refreshClients();
  } catch (err) {
    setMsg("action-msg", err.message, true);
  }
}

async function createImpersonation() {
  try {
    const clientId = $("imp-client-id").value.trim();
    const data = await apiPost("super-admin-impersonate.php", { clientId });
    setMsg("action-msg", `Impersonation token: ${data.token}`);
  } catch (err) {
    setMsg("action-msg", err.message, true);
  }
}

const SA_WIZ_TOTAL = 4;
const SA_DEMO_LOGO = "https://i.postimg.cc/90dcxxJP/logo.avif";
const SA_DEMO_BANNER = "https://i.ibb.co/DPRk1nSj/gb-banner.webp";

let saWizStep = 1;
let saWizCheckTimer = 0;

function normalizeSubdomain(raw) {
  return String(raw || "")
    .trim()
    .toLowerCase()
    .replace(/\s+/g, "-")
    .replace(/[^a-z0-9-]/g, "")
    .replace(/-+/g, "-")
    .replace(/^-+|-+$/g, "");
}

function getEffectiveSubdomain() {
  const override = $("sa-wiz-subdomain-override").value.trim();
  const site = $("sa-wiz-site-name").value.trim();
  return normalizeSubdomain(override !== "" ? override : site);
}

function saWizClearErrors(step) {
  const panel = document.getElementById(`sa-wiz-step-${step}`);
  if (!panel) return;
  panel.querySelectorAll(".sa-wiz-error").forEach((el) => {
    el.textContent = "";
  });
  panel.querySelectorAll(".sa-wiz-input").forEach((el) => el.classList.remove("sa-wiz-invalid"));
}

function saWizUpdatePreview(url, containerId) {
  const box = $(containerId);
  if (!box) return;
  const u = String(url || "").trim();
  box.replaceChildren();
  if (!u) return;
  const img = document.createElement("img");
  img.alt = "";
  img.src = u;
  box.appendChild(img);
}

async function saWizRunSubdomainCheck() {
  const statusEl = $("sa-wiz-map-status");
  const siteInput = $("sa-wiz-site-name");
  if (!statusEl || !siteInput) return;

  const sub = getEffectiveSubdomain();
  if (!sub || sub.length < 2) {
    statusEl.innerHTML = "";
    siteInput.dataset.available = "unknown";
    return;
  }

  statusEl.innerHTML = '<span class="sa-wiz-spinner"></span>';
  try {
    const d = await apiPost("super-admin-check-subdomain.php", { subdomain: sub });
    const ok = d.available === true;
    siteInput.dataset.available = ok ? "true" : "false";
    statusEl.textContent = ok ? "\u2713" : "\u2717";
    if (!ok) statusEl.style.color = "#dc2626";
    else statusEl.style.color = "#16a34a";
  } catch {
    siteInput.dataset.available = "unknown";
    statusEl.textContent = "";
  }
}

function saWizScheduleSubdomainCheck() {
  clearTimeout(saWizCheckTimer);
  $("sa-wiz-site-name").dataset.available = "unknown";
  saWizCheckTimer = setTimeout(() => {
    saWizRunSubdomainCheck();
  }, 450);
}

function saWizShowStep(n) {
  saWizStep = Math.min(Math.max(1, n), SA_WIZ_TOTAL);
  for (let i = 1; i <= SA_WIZ_TOTAL; i++) {
    const p = document.getElementById(`sa-wiz-step-${i}`);
    if (p) p.classList.toggle("active", i === saWizStep);
  }
  const pct = (saWizStep / SA_WIZ_TOTAL) * 100;
  const fill = $("sa-wiz-progress-fill");
  if (fill) fill.style.width = `${pct}%`;
  const ind = $("sa-wiz-step-indicator");
  if (ind) ind.textContent = `Step ${saWizStep} / ${SA_WIZ_TOTAL}`;

  const prev = $("sa-wiz-prev");
  const next = $("sa-wiz-next");
  const subm = $("sa-wiz-submit");
  if (prev) prev.classList.toggle("hidden", saWizStep === 1);
  if (next) next.classList.toggle("hidden", saWizStep === SA_WIZ_TOTAL);
  if (subm) subm.classList.toggle("hidden", saWizStep !== SA_WIZ_TOTAL);
}

function saWizValidateStep(step) {
  if (step === 1 || step === 3) return true;
  saWizClearErrors(step);
  let ok = true;

  if (step === 2) {
    const site = $("sa-wiz-site-name").value.trim();
    const phone = $("sa-wiz-contact-phone").value.trim();
    const sub = getEffectiveSubdomain();
    if (!site) {
      $("sa-wiz-site-name-err").textContent = "Business name is required.";
      $("sa-wiz-site-name").classList.add("sa-wiz-invalid");
      ok = false;
    }
    if (!phone) {
      $("sa-wiz-contact-phone-err").textContent = "Business phone is required.";
      $("sa-wiz-contact-phone").classList.add("sa-wiz-invalid");
      ok = false;
    }
    if (!sub || sub.length < 2) {
      $("sa-wiz-site-name-err").textContent =
        "Business name (or subdomain) must include at least one letter or number so the URL key is valid.";
      $("sa-wiz-site-name").classList.add("sa-wiz-invalid");
      ok = false;
    }
    if (ok && $("sa-wiz-site-name").dataset.available !== "true") {
      $("sa-wiz-site-name-err").textContent = "This subdomain is taken or not checked yet. Wait for the check or pick another name.";
      $("sa-wiz-site-name").classList.add("sa-wiz-invalid");
      ok = false;
    }
  }

  if (step === 4) {
    const email = $("sa-wiz-admin-email").value.trim();
    const pass = $("sa-wiz-admin-password").value;
    if (!/^\S+@\S+\.\S+$/.test(email)) {
      $("sa-wiz-admin-email-err").textContent = "Please enter a valid email.";
      $("sa-wiz-admin-email").classList.add("sa-wiz-invalid");
      ok = false;
    }
    if (pass.length < 8 || !/[a-zA-Z]/.test(pass) || !/\d/.test(pass)) {
      $("sa-wiz-admin-password-err").textContent =
        "Password must be at least 8 characters and include both letters and numbers.";
      $("sa-wiz-admin-password").classList.add("sa-wiz-invalid");
      ok = false;
    }
  }

  return ok;
}

function saWizReset() {
  saWizStep = 1;
  [
    "sa-wiz-site-name",
    "sa-wiz-subdomain-override",
    "sa-wiz-contact-phone",
    "sa-wiz-logo-url",
    "sa-wiz-banner-url",
    "sa-wiz-admin-email",
    "sa-wiz-admin-password"
  ].forEach((id) => {
    const el = $(id);
    if (el) el.value = "";
  });
  const siteInput = $("sa-wiz-site-name");
  if (siteInput) siteInput.dataset.available = "unknown";
  const st = $("sa-wiz-map-status");
  if (st) {
    st.textContent = "";
    st.style.color = "";
  }
  saWizUpdatePreview("", "sa-wiz-logo-preview");
  saWizUpdatePreview("", "sa-wiz-banner-preview");
  saWizShowStep(1);
}

async function saWizSubmitCreate() {
  const siteName = $("sa-wiz-site-name").value.trim();
  const override = $("sa-wiz-subdomain-override").value.trim();
  const adminEmail = $("sa-wiz-admin-email").value.trim();
  const adminPassword = $("sa-wiz-admin-password").value;
  const phone = $("sa-wiz-contact-phone").value.trim();
  const activeDesign = ($("sa-wiz-active-design") && $("sa-wiz-active-design").value.trim()) || "ghorerbazar";
  const logoUrl = $("sa-wiz-logo-url").value.trim();
  const bannerUrl = $("sa-wiz-banner-url").value.trim();
  const dashWrap = $("create-site-dashboard-wrap");
  const dashLink = $("open-dashboard-link");
  if (dashWrap) dashWrap.classList.add("hidden");
  if (dashLink) dashLink.removeAttribute("href");

  try {
    setMsg("create-site-msg", "Creating\u2026");
    const payload = { siteName, adminEmail, adminPassword, phone, activeDesign };
    if (override) payload.subdomain = normalizeSubdomain(override);
    if (logoUrl) payload.logoUrl = logoUrl;
    if (bannerUrl) payload.bannerUrl = bannerUrl;
    const data = await apiPost("super-admin-create-client.php", payload);
    const cid = data.clientId ? String(data.clientId) : "";
    const sub = data.subdomain ? String(data.subdomain) : "";
    setMsg("create-site-msg", data.message || `Created ${cid}${sub ? ` (${sub})` : ""}.`);
    $("action-client-id").value = cid;
    $("wallet-client-id").value = cid;
    $("imp-client-id").value = cid;
    if (data.dashboardUrl && dashWrap && dashLink) {
      dashLink.href = String(data.dashboardUrl);
      dashWrap.classList.remove("hidden");
    }
    await refreshClients();
    saWizReset();
  } catch (err) {
    setMsg("create-site-msg", err.message, true);
  }
}

function initCreateSiteWizard() {
  if (!$("sa-wiz-next")) return;

  $("sa-wiz-prev").addEventListener("click", () => {
    if (saWizStep > 1) {
      saWizShowStep(saWizStep - 1);
    }
  });

  $("sa-wiz-next").addEventListener("click", async () => {
    if (saWizStep === 2) {
      await saWizRunSubdomainCheck();
    }
    if (!saWizValidateStep(saWizStep)) return;
    if (saWizStep < SA_WIZ_TOTAL) {
      saWizShowStep(saWizStep + 1);
    }
  });

  $("sa-wiz-submit").addEventListener("click", async () => {
    if (!saWizValidateStep(4)) return;
    await saWizSubmitCreate();
  });

  ["sa-wiz-site-name", "sa-wiz-subdomain-override"].forEach((id) => {
    const el = $(id);
    if (!el) return;
    el.addEventListener("input", () => {
      saWizScheduleSubdomainCheck();
    });
  });

  $("sa-wiz-demo-logo").addEventListener("click", () => {
    $("sa-wiz-logo-url").value = SA_DEMO_LOGO;
    saWizUpdatePreview(SA_DEMO_LOGO, "sa-wiz-logo-preview");
  });
  $("sa-wiz-demo-banner").addEventListener("click", () => {
    $("sa-wiz-banner-url").value = SA_DEMO_BANNER;
    saWizUpdatePreview(SA_DEMO_BANNER, "sa-wiz-banner-preview");
  });

  $("sa-wiz-logo-url").addEventListener("input", () => {
    saWizUpdatePreview($("sa-wiz-logo-url").value, "sa-wiz-logo-preview");
  });
  $("sa-wiz-banner-url").addEventListener("input", () => {
    saWizUpdatePreview($("sa-wiz-banner-url").value, "sa-wiz-banner-preview");
  });

  saWizShowStep(1);
}

$("login-btn").addEventListener("click", login);
$("logout-btn").addEventListener("click", logout);
const appLogout = $("app-logout-btn");
if (appLogout) appLogout.addEventListener("click", logout);
$("refresh-btn").addEventListener("click", () => refreshClients().catch((e) => setMsg("action-msg", e.message, true)));
$("set-status-btn").addEventListener("click", setStatus);
$("wallet-adjust-btn").addEventListener("click", adjustWallet);
$("impersonate-btn").addEventListener("click", createImpersonation);
$("search-q").addEventListener("input", renderClients);
$("filter-status").addEventListener("change", renderClients);

clearLegacyClientAuthKeys();
initCreateSiteWizard();

(async function init() {
  const me = await tryAuthSession();
  if (me) {
    showAppView(me.email || "", me.uid);
    await refreshClients().catch((err) => setMsg("action-msg", err.message || "Client API unavailable", true));
  } else {
    showLoginView();
  }
})();
