(function () {
  'use strict';

  var lastOrganic = [];

  function hostOf(u) {
    try { return new URL(u, location.href).hostname.replace(/^www\./, '').toLowerCase(); }
    catch (e) { return ''; }
  }

  function realHref(a) {
    var href = a.getAttribute('href') || '';
    if (href.indexOf('/url?') === 0 || href.indexOf('https://www.google.com/url?') === 0) {
      try { var u = new URL(href, location.href); var q = u.searchParams.get('q'); if (q) return q; }
      catch (e) {}
    }
    return a.href;
  }

  function organicResults() {
    var seen = Object.create(null);
    var out = [];
    var roots = document.querySelectorAll('#rso h3, #search h3');
    roots.forEach(function (h3) {
      var a = h3.closest('a[href]');
      if (!a) return;
      if (a.closest('[data-text-ad], [aria-label="Ads"], .uEierd, #tads, #bottomads')) return;
      var href = realHref(a);
      var host = hostOf(href);

      if (!host || host === 'google.com' || host === 'googleusercontent.com' || host.endsWith('.googleusercontent.com')) return;
      if (seen[href]) return;
      seen[href] = 1;
      out.push({ url: href, el: a });
    });
    return out;
  }

  function domainMatches(url, target) {
    var h = hostOf(url);
    if (!h || !target) return false;
    return h === target || h.endsWith('.' + target);
  }

  function isCaptcha() {
    if (location.pathname.indexOf('/sorry') === 0) return true;
    if (document.querySelector('form#captcha-form, #recaptcha, iframe[src*="recaptcha"]')) return true;
    var t = (document.body && document.body.innerText || '');
    return /unusual traffic|not a robot|systems have detected/i.test(t);
  }

  function isConsent() {
    if (location.hostname.indexOf('consent.google.') === 0) return true;
    return !!document.querySelector('form[action*="consent"], div[aria-modal="true"][aria-label*="consent" i]');
  }

  function isForbidden() {
    if (/error\s*403|forbidden/i.test(document.title || '')) return true;
    var t = (document.body && document.body.innerText || '');
    return /does not have permission to get url|that.?s an error/i.test(t) && /403/.test(t);
  }

  function highlight(anchor, rank) {
    try {
      var card = anchor.closest('#rso .g, #rso [data-hveid], #search .g') || anchor;

      card.setAttribute('data-bks-hit', '1');
      var oldChip = card.querySelector('.bks-hit-chip');
      if (oldChip) oldChip.remove();
      card.style.outline = '3px solid #22c55e';
      card.style.outlineOffset = '2px';
      card.style.borderRadius = '10px';
      card.style.boxShadow = '0 0 0 6px rgba(34,197,94,.15)';
      var tag = document.createElement('span');
      tag.textContent = '★ Your rank #' + rank + ' — SerpHammer';
      tag.style.cssText = 'display:inline-block;margin:6px 0 2px;padding:2px 10px;border-radius:999px;' +
        'background:#22c55e;color:#08210f;font:700 12px/1.6 -apple-system,Segoe UI,Roboto,sans-serif;';
      card.insertBefore(tag, card.firstChild);
      card.scrollIntoView({ behavior: 'smooth', block: 'center' });
    } catch (e) {}
  }

  function report() {
    chrome.storage.local.get('job', function (data) {
      var job = data.job;
      if (!job || !job.running || job.paused) return;

      if (isCaptcha()) { chrome.runtime.sendMessage({ type: 'serp-page', blocked: 'captcha' }); return; }
      if (isConsent()) { chrome.runtime.sendMessage({ type: 'serp-page', blocked: 'consent' }); return; }
      if (isForbidden()) { chrome.runtime.sendMessage({ type: 'serp-page', blocked: 'forbidden' }); return; }

      var params = new URLSearchParams(location.search);
      var q = params.get('q') || '';

      lastOrganic = organicResults();
      var urls = lastOrganic.map(function (r) { return r.url; });

      var targetIndex = -1;
      for (var i = 0; i < lastOrganic.length; i++) {
        if (domainMatches(lastOrganic[i].url, job.target)) { targetIndex = i; break; }
      }
      chrome.runtime.sendMessage({ type: 'serp-page', q0: q, urls: urls, targetIndex: targetIndex });
    });
  }

  chrome.runtime.onMessage.addListener(function (msg) {
    if (!msg) return;
    if (msg.type === 'highlight' && lastOrganic[msg.index]) {
      highlight(lastOrganic[msg.index].el, msg.rank);
    }

    if (msg.type === 'reread') { setTimeout(report, 500); }
  });

  var SAVED_DOMAINS = null;
  var annotateTimer = null;

  function loadSavedDomains(cb) {
    try {
      chrome.storage.local.get('savedQueries', function (d) {
        var out = [];
        (d.savedQueries || []).forEach(function (q) {
          if (q && q.target) out.push(String(q.target).toLowerCase());
        });
        cb(out);
      });
    } catch (e) { cb([]); }
  }

  function pageOffset() {
    var s = parseInt(new URLSearchParams(location.search).get('start') || '0', 10);
    return (isFinite(s) && s > 0) ? s : 0;
  }

  function cardOf(a) {
    return a.closest('#rso .g, #rso [data-hveid], #search .g') || a;
  }

  function annotate() {
    if (isCaptcha() || isConsent()) return;
    var offset = pageOffset();
    var results = organicResults();
    results.forEach(function (r, i) {
      var pos = offset + i + 1;

      var h3 = r.el.querySelector('h3');
      if (h3) {
        var existing = h3.querySelector('.bks-pos');
        if (!existing) {
          var b = document.createElement('span');
          b.className = 'bks-pos';
          b.textContent = pos;
          b.title = 'Organic position ' + pos + ' — SerpHammer Rank Checker';
          b.style.cssText = 'display:inline-flex;align-items:center;justify-content:center;' +
            'min-width:20px;height:20px;margin-right:8px;padding:0 6px;border-radius:999px;' +
            'background:#3B82F6;color:#fff;font:700 11.5px/1 -apple-system,"Segoe UI",Roboto,sans-serif;' +
            'vertical-align:middle;';
          h3.insertBefore(b, h3.firstChild);
        } else if (existing.textContent !== String(pos)) {
          existing.textContent = pos;
        }
      }

      if (SAVED_DOMAINS && SAVED_DOMAINS.length) {
        for (var d = 0; d < SAVED_DOMAINS.length; d++) {
          if (domainMatches(r.url, SAVED_DOMAINS[d])) {
            var card = cardOf(r.el);
            if (!card.hasAttribute('data-bks-hit')) {
              card.setAttribute('data-bks-hit', '1');
              card.style.outline = '2px solid #3B82F6';
              card.style.outlineOffset = '2px';
              card.style.borderRadius = '10px';
              card.style.boxShadow = '0 0 0 5px rgba(59,130,246,.14)';
              var chip = document.createElement('span');
              chip.className = 'bks-hit-chip';
              chip.textContent = '★ ' + SAVED_DOMAINS[d] + ' · #' + pos + ' — SerpHammer';
              chip.style.cssText = 'display:inline-block;margin:6px 0 2px;padding:2px 10px;border-radius:999px;' +
                'background:#3B82F6;color:#fff;font:700 12px/1.6 -apple-system,"Segoe UI",Roboto,sans-serif;';
              card.insertBefore(chip, card.firstChild);
            }
            break;
          }
        }
      }
    });
  }

  function scheduleAnnotate() {
    clearTimeout(annotateTimer);
    annotateTimer = setTimeout(annotate, 350);
  }

  loadSavedDomains(function (doms) { SAVED_DOMAINS = doms; scheduleAnnotate(); });

  chrome.storage.onChanged.addListener(function (ch, area) {
    if (area === 'local' && ch.savedQueries) {
      loadSavedDomains(function (doms) { SAVED_DOMAINS = doms; scheduleAnnotate(); });
    }
  });

  try {
    new MutationObserver(scheduleAnnotate)
      .observe(document.documentElement, { childList: true, subtree: true });
  } catch (e) {}

  setTimeout(report, 600);
})();
