var UsersPage = (function () {
  "use strict";
  var viewerIsSuper = false;
  var viewerId = null;

  function fetchAdminUsers() {
    fetch("/api/admin/users", { credentials: "same-origin" })
      .then(function (res) {
        if (!res.ok) throw new Error("Unauth");
        return res.json();
      })
      .then(function (users) {
        var tbody = document.getElementById("users-table-body");
        tbody.innerHTML = users
          .map(function (u) {
            var isPrimary = !!u.is_superadmin;
            var canDelete = viewerIsSuper && u.id !== viewerId;
            var delBtn = canDelete
              ? '<button onclick="UsersPage.deleteAdminUser(' +
                u.id +
                ')" class="text-gray-500 hover:text-red-400 hover:bg-red-400/10 p-2 rounded transition-colors"><i class="ph ph-trash text-lg"></i></button>'
              : '<span class="text-gray-600 text-xs">—</span>';
            return (
              '<tr class="hover:bg-white/5 transition-colors">' +
              '<td class="py-4 pl-4 pr-4">#' +
              u.id +
              "</td>" +
              '<td class="py-4 pr-4 text-cyan-400">' +
              u.username +
              (isPrimary
                ? '<span class="ml-2 text-xs uppercase tracking-wider text-violet-400 border border-violet-500/30 rounded px-2 py-0.5">Primary</span>'
                : "") +
              "</td>" +
              '<td class="py-4 pr-4 text-gray-500">' +
              new Date(u.created_at + "Z").toLocaleDateString() +
              "</td>" +
              '<td class="py-4 pr-4 text-right">' +
              delBtn +
              "</td>" +
              "</tr>"
            );
          })
          .join("");
      })
      .catch(function (e) {
        console.error(e);
      });
  }

  function deleteAdminUser(id) {
    if (!confirm("WARNING: Purge operator from system?")) return;
    fetch("/api/admin/delete-user", {
      method: "DELETE",
      headers: { "Content-Type": "application/json" },
      credentials: "same-origin",
      body: JSON.stringify({ id: id }),
    })
      .then(function (res) {
        return res.json().then(function (data) {
          return { res: res, data: data };
        });
      })
      .then(function (o) {
        if (o.res.ok) fetchAdminUsers();
        else alert("ERR: " + (o.data.message || "Delete failed"));
      })
      .catch(function () {
        alert("ERR: Delete failed.");
      });
  }

  function bindAddForm() {
    var form = document.getElementById("add-user-form");
    if (!form || form.dataset.bound === "1") return;
    form.dataset.bound = "1";
    form.addEventListener("submit", function (e) {
      e.preventDefault();
      var u = document.getElementById("new-username").value;
      var p = document.getElementById("new-password").value;
      fetch("/api/admin/add-user", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "same-origin",
        body: JSON.stringify({ username: u, password: p }),
      })
        .then(function (res) {
          return res.json().then(function (data) {
            return { res: res, data: data };
          });
        })
        .then(function (o) {
          if (o.res.ok) {
            document.getElementById("new-username").value = "";
            document.getElementById("new-password").value = "";
            fetchAdminUsers();
          } else alert("ERR: " + (o.data.message || "Failed"));
        })
        .catch(function () {
          alert("ERR: Network failure.");
        });
    });
  }

  function onAuthed(data) {
    viewerIsSuper = !!data.is_superadmin;
    viewerId = data.admin_id != null ? Number(data.admin_id) : null;
    bindAddForm();
    fetchAdminUsers();
  }

  return {
    onAuthed: onAuthed,
    deleteAdminUser: deleteAdminUser,
  };
})();
