const ALLOWED_HOSTS = [
  "html5.gamemonetize.com",
  "html5.gamemonetize.co",
  "gamemonetize.com",
  "gamemonetize.co",
  "wgplayground.com",
  "www.wgplayground.com",
  "gamedistribution.com",
  "html5.gamedistribution.com",
];

export function isAllowedEmbedUrl(url: string): boolean {
  try {
    const u = new URL(url);
    if (u.protocol !== "https:") return false;
    return ALLOWED_HOSTS.some((h) => u.hostname === h || u.hostname.endsWith(`.${h}`));
  } catch {
    return false;
  }
}

export function playShellUrl(embedUrl: string): string {
  if (!isAllowedEmbedUrl(embedUrl)) return embedUrl;
  return `/play?u=${encodeURIComponent(embedUrl)}`;
}

// Fullscreen is enabled via iframe `allow="fullscreen"`, not sandbox.
export const IFRAME_SANDBOX =
  "allow-scripts allow-same-origin allow-pointer-lock allow-forms allow-modals allow-popups";

/** Strict allowlist — avoids false positives like "loadstart" matching "adstart". */
const AD_EVENT_NAMES = new Set([
  "ad_started",
  "ad_start",
  "adstart",
  "ad-show",
  "ad_show",
  "adshow",
  "preroll",
  "sdk_game_pause",
  "show_banner",
  "showbanner",
  "ima:started",
  "ima:start",
]);

export function isAdMessage(data: unknown): boolean {
  if (data == null) return false;

  if (typeof data === "string") {
    const s = data.toLowerCase().trim();
    if (AD_EVENT_NAMES.has(s)) return true;
    if (s.startsWith("ima:") && (s.includes("start") || s.includes("show"))) return true;
    if (s === "googima" || s.startsWith("googima:")) return true;
    return false;
  }

  if (typeof data === "object") {
    const o = data as Record<string, unknown>;
    const name = String(o.name ?? o.event ?? o.type ?? o.action ?? "")
      .toLowerCase()
      .trim();
    if (AD_EVENT_NAMES.has(name)) return true;
    if (name.startsWith("ima:") && (name.includes("start") || name.includes("show"))) return true;
    if (o.ad === true || o.isAd === true || o.adStarted === true) return true;
  }

  return false;
}

export function stopIframe(iframe: HTMLIFrameElement | null) {
  if (!iframe) return;
  try {
    iframe.src = "about:blank";
  } catch {
    /* ignore */
  }
}
