const extensionAPI = globalThis.browser ?? globalThis.chrome;

let lastFingerprint = null;

function normalizeURL(rawURL) {
  if (!rawURL) {
    return null;
  }

  try {
    const url = new URL(rawURL);
    if (url.protocol !== "http:" && url.protocol !== "https:") {
      return null;
    }

    return url;
  } catch {
    return null;
  }
}

function emitVisiblePage(reason) {
  const url = normalizeURL(globalThis.location?.href);
  if (!url) {
    return;
  }

  const fingerprint = `${url.protocol}//${url.hostname}`;
  if (fingerprint === lastFingerprint && reason !== "heartbeat") {
    return;
  }

  lastFingerprint = fingerprint;
  extensionAPI.runtime.sendMessage({
    type: "page_visible",
    href: url.href,
    title: globalThis.document?.title ?? "",
    reason
  }).catch(() => {});
}

emitVisiblePage("page_load");

globalThis.addEventListener("focus", () => {
  emitVisiblePage("window_focus");
});

globalThis.addEventListener("pageshow", () => {
  emitVisiblePage("page_show");
});

globalThis.document?.addEventListener("visibilitychange", () => {
  if (globalThis.document?.hidden !== false) {
    return;
  }

  emitVisiblePage("visibility_visible");
});

globalThis.setInterval(() => {
  if (globalThis.document?.hidden) {
    return;
  }

  emitVisiblePage("heartbeat");
}, 10000);
