(function () {
  "use strict";

  const PRESETS_URL = "/ui/platform-overlay/presets.json";
  const DEFAULT_PRESETS = {
    mount: "netkingdom",
    role: "platform-admin",
    title: "Sign in with KeyCape",
    signInLabel: "Sign in with KeyCape",
    banner:
      "Platform operators authenticate through KeyCape at kc.coulomb.social.",
  };

  async function loadPresets() {
    try {
      const response = await fetch(PRESETS_URL, { cache: "no-store" });
      if (!response.ok) return { ...DEFAULT_PRESETS };
      return { ...DEFAULT_PRESETS, ...(await response.json()) };
    } catch (_error) {
      return { ...DEFAULT_PRESETS };
    }
  }

  async function redirectToKeyCape(presets) {
    const mount = presets.mount || "netkingdom";
    const role = presets.role || "platform-admin";
    const redirectUri = `${window.location.origin}/ui/vault/auth/${mount}/oidc/callback`;

    const response = await fetch(`/v1/auth/${mount}/oidc/auth_url`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        role,
        redirect_uri: redirectUri,
      }),
    });

    if (!response.ok) {
      throw new Error(`OIDC auth_url request failed (${response.status})`);
    }

    const payload = await response.json();
    const authUrl = payload?.data?.auth_url;
    if (!authUrl) {
      throw new Error("OIDC auth_url missing from OpenBao response");
    }

    window.location.assign(authUrl);
  }

  function showError(message) {
    const error = document.getElementById("login-error");
    if (!error) return;
    error.textContent = message;
    error.classList.add("is-visible");
  }

  async function init() {
    const presets = await loadPresets();
    const title = document.getElementById("login-title");
    const banner = document.getElementById("login-banner");
    const button = document.getElementById("login-submit");

    if (title) title.textContent = presets.title;
    if (banner) banner.textContent = presets.banner;
    if (button) button.textContent = presets.signInLabel;

    if (!button) return;

    button.addEventListener("click", async () => {
      button.disabled = true;
      try {
        await redirectToKeyCape(presets);
      } catch (error) {
        button.disabled = false;
        showError(
          error instanceof Error
            ? error.message
            : "Sign-in failed. Contact your administrator."
        );
      }
    });
  }

  init();
})();