/**
 * Shared auth, login overlay, role-based nav.
 */
var AdminCore = (function () {
  "use strict";

  function showLogin() {
    var overlay = document.getElementById("login-overlay");
    if (!overlay) return;
    overlay.classList.remove("hidden");
    window.SCII_ADMIN_SUPER = false;
    setTimeout(function () {
      overlay.classList.remove("opacity-0", "pointer-events-none");
    }, 10);
  }

  function hideLogin() {
    var overlay = document.getElementById("login-overlay");
    if (!overlay) return;
    overlay.classList.add("opacity-0", "pointer-events-none");
    setTimeout(function () {
      overlay.classList.add("hidden");
    }, 300);
  }

  function applyRole(data) {
    window.SCII_ADMIN_SUPER = !!data.is_superadmin;
    var uname = document.getElementById("admin-username-display");
    if (uname) uname.textContent = data.username || "";
    var role = document.getElementById("admin-role-display");
    if (role) role.textContent = data.is_superadmin ? "Primary Admin" : "Operator";
    var navLi = document.getElementById("nav-settings-li");
    if (navLi && !data.is_superadmin) navLi.remove();
    var navMobile = document.getElementById("nav-settings-mobile");
    if (navMobile && !data.is_superadmin) navMobile.remove();
    var navMobile = document.getElementById("nav-settings-mobile");
    if (navMobile && !data.is_superadmin) navMobile.remove();
  }

  function bindLoginForm(globalOpts) {
    globalOpts = globalOpts || {};
    var form = document.getElementById("login-form");
    if (!form || form.dataset.bound === "1") return;
    form.dataset.bound = "1";
    form.addEventListener("submit", function (e) {
      e.preventDefault();
      if (typeof AlertSound !== "undefined") AlertSound.unlock();
      var u = document.getElementById("login-username").value;
      var p = document.getElementById("login-password").value;
      var err = document.getElementById("login-error");
      fetch("/api/admin/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "same-origin",
        body: JSON.stringify({ username: u, password: p }),
      })
        .then(function (res) {
          if (res.ok) {
            err.classList.add("hidden");
            document.getElementById("login-password").value = "";
            return checkAuth({
              requireSuperadmin: !!globalOpts.requireSuperadmin,
              onAuthed: globalOpts.onAuthed,
            });
          }
          err.classList.remove("hidden");
        })
        .catch(function () {
          err.classList.remove("hidden");
        });
    });
  }

  function checkAuth(options) {
    options = options || {};
    return fetch("/api/admin/check-auth", { credentials: "same-origin" })
      .then(function (res) {
        if (!res.ok) throw new Error("unauthorized");
        return res.json();
      })
      .then(function (data) {
        if (options.requireSuperadmin && !data.is_superadmin) {
          window.location.href =
            document.querySelector("aside nav a")?.getAttribute("href") || "/";
          return null;
        }
        applyRole(data);
        hideLogin();
        if (typeof options.onAuthed === "function") options.onAuthed(data);
        return data;
      })
      .catch(function () {
        showLogin();
        return null;
      });
  }

  function adminLogout() {
    fetch("/api/admin/logout", { method: "POST", credentials: "same-origin" }).finally(
      function () {
        showLogin();
      }
    );
  }

  function init(options) {
    options = options || {};
    bindLoginForm(options);
    var themeReady =
      typeof PanelModeUI !== "undefined" ? PanelModeUI.load() : Promise.resolve();
    themeReady.finally(function () {
      checkAuth({
        requireSuperadmin: !!options.requireSuperadmin,
        onAuthed: options.onAuthed,
      });
      if (typeof PanelModeUI !== "undefined" && !window._panelModePoll) {
        window._panelModePoll = setInterval(PanelModeUI.load, 4000);
      }
    });
  }

  return {
    init: init,
    checkAuth: checkAuth,
    adminLogout: adminLogout,
    showLogin: showLogin,
    hideLogin: hideLogin,
  };
})();
