// adeater.js — Core orchestration: observer, storage listener, init, entry point.
// Runs last in the content-script "js" array, so all prior files are already
// in scope: adeater-selectors.js → adeater-utils.js → adeater-sweepers.js → adeater-security.js

// ---------------------------------------------------------------------------
// Consolidated MutationObserver — single debounced observer that drives the
// DOM ad/tracker sweeps (scheduleSweep + napPatrol).
// ---------------------------------------------------------------------------
let observerTimeout = null;

function observerCallback() {
  if (observerTimeout) return;
  observerTimeout = setTimeout(() => {
    observerTimeout = null;
    if (!enabled) return;
    scheduleSweep();
    if (EAT_POPUPS) napPatrol();
  }, 2000);
}

// ---------------------------------------------------------------------------
// Enabled state
// ---------------------------------------------------------------------------
let enabled = true;

async function loadEnabled() {
  try {
    const data = await chrome.storage.local.get("tabby");
    const tabby = data.tabby || {};
    enabled = tabby.adEaterEnabled !== false;
    trustedDomains = new Set((tabby.adeaterTrustedDomains || []).map(d => d.toLowerCase()));
  } catch {
    enabled = true;
  }
}

function onStorageChanged(changes, area) {
  if (area !== "local") return;
  if (changes.tabby) {
    const newVal = changes.tabby.newValue || {};
    enabled = newVal.adEaterEnabled !== false;
    trustedDomains = new Set((newVal.adeaterTrustedDomains || []).map(d => d.toLowerCase()));
    if (enabled) {
      setTimeout(eatAll, 500);
    }
  }
}

// ---------------------------------------------------------------------------
// Init
// ---------------------------------------------------------------------------
async function init() {
  try {
    if (!chrome.runtime || !chrome.runtime.id) return;
  } catch { return; }

  if (window.top !== window) return;

  if (isWhitelisted()) {
    return;
  }

  if (window.__tabbyAdeater) return;
  window.__tabbyAdeater = true;

  await loadEnabled();
  if (!enabled) return;

  // Relay stats/threats dispatched by adeater-hooks.js (main world).
  window.addEventListener("tabby-hook-stat", (e) => {
    const { stat, count } = e.detail || {};
    if (stat && stat in stats) {
      stats[stat] += (count || 1);
      scheduleReport();
    }
  });
  window.addEventListener("tabby-hook-threat", (e) => {
    const { type, detail } = e.detail || {};
    if (type && !isTrustedDomain()) reportThreat(type, detail || "");
  });

  eatAll();
  if (EAT_POPUPS) napPatrol();

  if (document.readyState === "complete") {
    setTimeout(reportPerformanceMetrics, 500);
  } else {
    window.addEventListener("load", () => setTimeout(reportPerformanceMetrics, 500), { once: true });
  }

  const domObserver = new MutationObserver(() => {
    if (!enabled) return;
    observerCallback();
  });

  domObserver.observe(document.documentElement || document.body, {
    childList: true,
    subtree: true,
  });

  let scrollTimer = null;
  window.addEventListener("scroll", () => {
    if (!enabled) return;
    if (scrollTimer) return;
    scrollTimer = setTimeout(() => {
      scrollTimer = null;
      scheduleSweep();
    }, 2000);
  }, { passive: true });

  try {
    chrome.storage.onChanged.addListener(onStorageChanged);
  } catch {}
}

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------
if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", init, { once: true });
} else {
  init();
}
