(function () {
  async function loadSkills() {
    var grid = document.getElementById("skill-grid");
    if (!grid) return;

    var res = await fetch("/api/skills", { credentials: "include" });
    if (!res.ok) {
      grid.innerHTML = '<p class="hint">Sign in first to browse skills.</p>';
      return;
    }

    var data = await res.json();
    grid.innerHTML = "";

    data.skills.forEach(function (s) {
      var card = document.createElement("article");
      card.className = "card";
      card.innerHTML =
        "<h3>" + escapeHtml(s.title) + "</h3>" +
        "<p>" + escapeHtml(s.description) + "</p>" +
        "<p class='hint'>Seller: " + escapeHtml(s.owner_email || "unknown") + "</p>" +
        "<p><strong>$" + (s.price_cents / 100).toFixed(2) + "</strong></p>" +
        "<button class='btn buy' data-skill-id='" + s.id + "'>Buy Skill</button>";
      grid.appendChild(card);
    });

    grid.querySelectorAll("[data-skill-id]").forEach(function (btn) {
      btn.addEventListener("click", onBuy);
    });
  }

  async function onBuy(event) {
    var skillId = event.currentTarget.getAttribute("data-skill-id");
    var body = new URLSearchParams();
    body.set("skill_id", skillId);

    var res = await fetch("/api/purchase", {
      method: "POST",
      credentials: "include",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: body.toString()
    });

    if (!res.ok) {
      alert("Purchase failed.");
      return;
    }
    window.location.href = "/purchase";
  }

  async function loadMySkills() {
    var grid = document.getElementById("my-skill-grid");
    if (!grid) return;

    var res = await fetch("/api/my-skills", { credentials: "include" });
    if (!res.ok) {
      grid.innerHTML = '<p class="hint">Sign in first to view your purchased skills.</p>';
      return;
    }

    var data = await res.json();
    grid.innerHTML = "";

    data.skills.forEach(function (s) {
      var card = document.createElement("article");
      card.className = "card";
      card.innerHTML =
        "<h3>" + escapeHtml(s.title) + "</h3>" +
        "<p>" + escapeHtml(s.description) + "</p>" +
        "<p class='hint'>Purchased from: " + escapeHtml(s.owner_email || "unknown") + "</p>" +
        "<div class='actions'>" +
        "<a class='btn' href='/uploads/" + s.skill_id + "'>Download</a>" +
        "<button class='btn' data-copy-id='" + s.skill_id + "'>Copy Link</button>" +
        "</div>";
      grid.appendChild(card);
    });

    grid.querySelectorAll("[data-copy-id]").forEach(function (btn) {
      btn.addEventListener("click", function (event) {
        var id = event.currentTarget.getAttribute("data-copy-id");
        var link = window.location.origin + "/uploads/" + id;
        navigator.clipboard.writeText(link);
        event.currentTarget.textContent = "Copied";
      });
    });
  }

  function uploadInit() {
    var form = document.getElementById("upload-form");
    if (!form) return;
    var status = document.getElementById("upload-status");

    form.addEventListener("submit", async function (event) {
      event.preventDefault();
      var data = new FormData(form);
      var res = await fetch("/api/upload", {
        method: "POST",
        credentials: "include",
        body: data
      });
      if (!res.ok) {
        status.textContent = "Upload failed. Check token and required fields.";
        return;
      }
      status.textContent = "Upload complete. Your skill is live in the marketplace.";
      form.reset();
    });
  }

  function escapeHtml(value) {
    return String(value || "")
      .replaceAll("&", "&amp;")
      .replaceAll("<", "&lt;")
      .replaceAll(">", "&gt;")
      .replaceAll('"', "&quot;")
      .replaceAll("'", "&#039;");
  }

  uploadInit();
  loadSkills();
  loadMySkills();
})();
