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

let sequence = 0;
let lastFingerprint = null;
const replayableReasons = new Set([
  "startup",
  "page_load",
  "page_show",
  "visibility_visible",
  "heartbeat"
]);

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;
  }
}

async function publishURL(url, metadata = {}) {
  if (!url) {
    return;
  }

  const fingerprint = `${url.protocol}//${url.hostname}`;
  const reason = metadata.reason ?? "unknown";
  if (fingerprint === lastFingerprint && replayableReasons.has(reason) === false) {
    return;
  }

  lastFingerprint = fingerprint;
  sequence += 1;

  try {
    await extensionAPI.runtime.sendNativeMessage({
      type: "active_page",
      browser: "Safari",
      domain: url.hostname,
      urlScheme: url.protocol.replace(":", ""),
      href: metadata.href ?? url.href,
      title: metadata.title ?? "",
      sequence,
      emittedAtMs: metadata.emittedAtMs ?? Date.now(),
      reason
    });
  } catch (error) {
    console.error("ActualFocus native messaging failed", error);
  }
}

async function publishActivePage(reason) {
  const tabs = await extensionAPI.tabs.query({ active: true, lastFocusedWindow: true });
  const tab = tabs.find(Boolean);
  const url = normalizeURL(tab?.url);

  await publishURL(url, {
    href: tab?.url,
    title: tab?.title ?? "",
    reason
  });
}

extensionAPI.tabs.onActivated.addListener(() => {
  void publishActivePage("tab_activated");
});

extensionAPI.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (!tab.active) {
    return;
  }

  if (typeof changeInfo.url === "string" || changeInfo.status === "complete") {
    void publishActivePage("tab_updated");
  }
});

extensionAPI.windows.onFocusChanged.addListener(() => {
  void publishActivePage("window_focus");
});

extensionAPI.runtime.onInstalled.addListener(() => {
  void publishActivePage("installed");
});

extensionAPI.runtime.onMessage.addListener((message) => {
  if (!message || message.type !== "page_visible") {
    return undefined;
  }

  void publishURL(normalizeURL(message.href), {
    href: message.href,
    title: message.title ?? "",
    emittedAtMs: Date.now(),
    reason: message.reason ?? "content_script"
  });

  return undefined;
});

if (extensionAPI.runtime.onStartup) {
  extensionAPI.runtime.onStartup.addListener(() => {
    void publishActivePage("startup");
  });
}

void publishActivePage("startup");
