// Single-purpose: the popup IS the button handler (the popup rail is the one extension surface
// proven reliable under --load-extension here; action.onClicked worker events are not). Fire
// annotate on the active tab via pup's loopback, then close.
(async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  for (const port of [64230, 8851]) {
    try {
      const r = await fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(1200) });
      const j = await r.json();
      if (!j || j.bridge !== 'puppeteer') continue;
      await fetch(`http://127.0.0.1:${port}/command`, {
        method: 'POST',
        headers: { 'content-type': 'application/json', 'x-adom-caller-thread': 'user-toolbar', 'x-adom-caller-reason': 'Adom Annotate button' },
        body: JSON.stringify({ command: 'pup_annotate', args: { _tabUrl: tab && tab.url, tool: 'pen', caller: { aiThread: 'user-toolbar' } } }),
      });
      break;
    } catch (e) {}
  }
  window.close();
})();
