// Hangar Browser Companion — content script
// Runs at document_start on every page, so it fires even when the MV3 service
// worker is cold. Detects the /init/{token} handshake URL and sends a message
// to wake the background script before the page renders the raw JSON.

(function () {
  if (window.__hangarContentLoaded) return;
  window.__hangarContentLoaded = true;

  // ── Init URL detection ────────────────────────────────────────────────────
  // The background webNavigation.onCompleted listener can miss the event when
  // the service worker starts cold. Sending a message from here guarantees the
  // background wakes up to handle the session init.
  try {
    const loc = window.location;
    if (loc.hostname === '127.0.0.1' && loc.pathname.startsWith('/init/')) {
      chrome.runtime.sendMessage({ type: 'INIT_URL', href: loc.href });
    }
  } catch (_) {}

  // ── Track last focused / right-clicked input ──────────────────────────────
  document.addEventListener('focusin', (e) => {
    if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
      window._hangarLastInput = e.target;
    }
  }, true);

  document.addEventListener('contextmenu', (e) => {
    if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
      window._hangarLastInput = e.target;
    }
  }, true);
})();
