let adBlockEnabled = true;
let observer = null;

function removeAds() {
  if (!adBlockEnabled) return;

  const selectors = [
    '[id*="ad"]',
    '[class*="ad"]',
    '[class*="ads"]',
    '[id*="ads"]',
    'iframe[src*="ads"]',
    'iframe[src*="doubleclick"]',
    'iframe[src*="googlesyndication"]'
  ];

  selectors.forEach(selector => {
    document.querySelectorAll(selector).forEach(el => {
      el.remove();
    });
  });
}

function startObserver() {
  if (observer) return;

  observer = new MutationObserver(() => {
    removeAds();
  });

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

function stopObserver() {
  if (!observer) return;

  observer.disconnect();
  observer = null;
}

chrome.storage.local.get(["enabled"], data => {
  adBlockEnabled = data.enabled !== false;

  if (adBlockEnabled) {
    removeAds();
    startObserver();
  }
});

chrome.storage.onChanged.addListener((changes, area) => {
  if (area !== "local" || !changes.enabled) return;

  adBlockEnabled = changes.enabled.newValue !== false;

  if (adBlockEnabled) {
    removeAds();
    startObserver();
  } else {
    stopObserver();
  }
});

function killYouTubeAds() {
  const video = document.querySelector("video");
  if (!video) return;

  const skipBtn = document.querySelector(".ytp-ad-skip-button");
  if (skipBtn) {
    skipBtn.click();
  }

  const isAd = document.querySelector(".ad-showing");

  if (isAd && video) {
    video.muted = true;
    video.currentTime = video.duration || 9999;
  }
}

setInterval(killYouTubeAds, 1000);