import { t } from "../config/site.js";

const BANNER_ID = "site-auth-gate-banner";
const BODY_ATTR = "data-auth-gate";

let gateActive = false;
let gateMode = null;

const WRAPPED_GLOBALS = [
  "__siteOpenLogin",
  "__siteOpenRegister",
  "__siteOpenPromoModal",
  "__siteOpenChat",
  "__siteOpenSearchPalette",
  "__siteOpenSidebar",
];

const wrappedKey = "__alpingoAuthGateWrapped";

export function normalizeAuthGateInput(needs) {
  if (typeof needs === "object" && needs !== null) {
    return {
      profileCompletion: !!needs.profileCompletion,
      passwordChange: !!needs.passwordChange,
    };
  }
  const legacy = !!needs;
  return {
    profileCompletion: legacy,
    passwordChange: false,
  };
}

export function authGateFlagsFromUser(user) {
  if (!user) {
    return { profileCompletion: false, passwordChange: false };
  }
  return {
    profileCompletion: !!user.needsProfileCompletion,
    passwordChange: !!user.needsPasswordChange,
  };
}

export function isAuthGateActive(flags) {
  const f = normalizeAuthGateInput(flags);
  return f.profileCompletion || f.passwordChange;
}

export function isAuthGateActiveForUser(user) {
  return isAuthGateActive(authGateFlagsFromUser(user));
}

export function isAuthGateActiveNow() {
  return gateActive;
}

function ensureBanner() {
  let el = document.getElementById(BANNER_ID);
  if (el) return el;
  el = document.createElement("div");
  el.id = BANNER_ID;
  el.setAttribute("role", "alert");
  el.setAttribute("aria-live", "assertive");
  el.className = "site-auth-gate-banner";
  el.innerHTML = `
    <div class="site-auth-gate-banner__inner">
      <span class="site-auth-gate-banner__icon" aria-hidden="true">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="18" height="18"><path d="M12 9v4"/><path d="M12 17h.01"/><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/></svg>
      </span>
      <div class="site-auth-gate-banner__text">
        <strong class="site-auth-gate-banner__title"></strong>
        <span class="site-auth-gate-banner__hint"></span>
      </div>
      <button type="button" class="site-auth-gate-banner__cta" data-auth-gate-cta>
      </button>
    </div>
  `;
  document.body.appendChild(el);

  el.querySelector("[data-auth-gate-cta]")?.addEventListener("click", () => {
    if (typeof globalThis.__siteNavigateTo === "function") {
      globalThis.__siteNavigateTo("/profil");
    } else {
      window.location.hash = "#/profil";
    }
  });
  return el;
}

function refreshBannerCopy() {
  const el = document.getElementById(BANNER_ID);
  if (!el) return;
  const titleEl = el.querySelector(".site-auth-gate-banner__title");
  const hintEl = el.querySelector(".site-auth-gate-banner__hint");
  const ctaEl = el.querySelector(".site-auth-gate-banner__cta");
  if (gateMode === "password") {
    if (titleEl) titleEl.textContent = t("profilePasswordChangeBannerTitle");
    if (hintEl) hintEl.textContent = t("profilePasswordChangeBannerHint");
    if (ctaEl) ctaEl.textContent = t("profilePasswordChangeSubmit");
  } else {
    if (titleEl) titleEl.textContent = t("profileCompleteBannerTitle");
    if (hintEl) hintEl.textContent = t("profileCompleteBannerHint");
    if (ctaEl) ctaEl.textContent = t("profileCompleteSubmit");
  }
}

function closeOpenModals() {
  try {
    globalThis.__siteCloseAuthModals?.();
  } catch {}
  try {
    globalThis.__siteClosePromoModal?.();
  } catch {}
  try {
    globalThis.__siteCloseNewsModal?.();
  } catch {}
  try {
    globalThis.__siteCloseGameSelectorModal?.();
  } catch {}
  try {
    globalThis.__siteCloseSearchPalette?.();
  } catch {}
  try {
    globalThis.__siteCloseChat?.();
  } catch {}
}

function wrapModalGlobals() {
  if (globalThis[wrappedKey]) return;
  globalThis[wrappedKey] = true;

  for (const name of WRAPPED_GLOBALS) {
    let current = globalThis[name];
    Object.defineProperty(globalThis, name, {
      configurable: true,
      get() {
        if (typeof current !== "function") return current;
        if (!gateActive) return current;
        return function gatedNoop() {
          if (typeof globalThis.__siteNavigateTo === "function") {
            globalThis.__siteNavigateTo("/profil");
          } else {
            window.location.hash = "#/profil";
          }
        };
      },
      set(value) {
        current = value;
      },
    });
  }
}

export function setAuthGate(needs) {
  const flags = normalizeAuthGateInput(needs);
  const next = flags.profileCompletion || flags.passwordChange;
  gateActive = next;
  gateMode = flags.passwordChange ? "password" : flags.profileCompletion ? "profile" : null;
  if (typeof globalThis !== "undefined") {
    globalThis.__siteAuthGate = next;
    globalThis.__siteAuthGateMode = gateMode;
  }
  if (typeof document === "undefined") return;
  wrapModalGlobals();

  const body = document.body;
  if (!body) return;

  if (next) {
    body.setAttribute(BODY_ATTR, gateMode || "true");
    ensureBanner();
    refreshBannerCopy();
    closeOpenModals();
    if (typeof window !== "undefined") {
      const path = (window.location.hash || "").replace(/^#/, "").trim() || "/";
      const normalized = path.startsWith("/") ? path : `/${path}`;
      const trimmed = normalized.replace(/\/+$/, "") || "/";
      if (trimmed !== "/profil") {
        if (typeof globalThis.__siteNavigateTo === "function") {
          globalThis.__siteNavigateTo("/profil");
        } else {
          window.location.hash = "#/profil";
        }
      }
    }
  } else {
    body.removeAttribute(BODY_ATTR);
    const el = document.getElementById(BANNER_ID);
    if (el && el.parentNode) el.parentNode.removeChild(el);
  }
}

if (typeof window !== "undefined") {
  window.addEventListener("mocker:locale", () => {
    if (gateActive) refreshBannerCopy();
  });
}
