// Auto-injected (via manifest content_scripts, not on-demand like
// content-script.js) on cortaly.com/surf/* and cortaly.com/index.php*
// pages — lets a user just navigate to their own surf link or a PTC
// campaign and have the extension take over immediately, no popup/username
// typing needed. Runs at document_start, before the page has parsed/rendered
// anything of its own — halts the rest of THIS page's own load right away
// (window.stop(), only affects this real page load, never the extension's
// own background script) so its own surf.js/click.js never gets a chance to
// race the extension for the same hit, and hands off to background.js,
// which takes over THIS SAME TAB rather than opening a separate one.
(() => {
  const surfMatch = location.pathname.match(/^\/surf\/([A-Za-z0-9_]{3,32})/);
  if (surfMatch) {
    window.stop();
    api.runtime.sendMessage({ type: 'AUTO_START', username: surfMatch[1] }).catch(() => {});
    return;
  }

  // PTC campaign pages are query-string routed
  // (index.php?content=click-view&campaign_id=N), not path-based like
  // /surf/ — content_scripts URL matching can't express that precisely, so
  // manifest.json/manifest.firefox.json match the whole of index.php* and
  // this does the real check itself. Every OTHER index.php page (dashboard,
  // profile, sites, ...) hits this branch too and no-ops immediately —
  // negligible cost, same pattern as any other early-exit content script.
  const params = new URLSearchParams(location.search);
  if (params.get('content') === 'click-view') {
    const campaignId = parseInt(params.get('campaign_id'), 10);
    if (campaignId > 0) {
      window.stop();
      api.runtime.sendMessage({ type: 'AUTO_START_CLICK', campaignId }).catch(() => {});
    }
  }
})();
