(function () {
  const COMMON_SELECTORS = [
    'iframe[src*="doubleclick"]',
    'iframe[src*="googlesyndication"]',
    'iframe[src*="adservice"]',
    'script[src*="doubleclick"]',
    'script[src*="googlesyndication"]',
    'script[src*="adservice"]',
    '[id*="ad-"]',
    '[class*="ad-"]',
    '[id^="ad_"]',
    '[class^="ad_"]'
  ];

  const HOST_SELECTORS = {
    'www.youtube.com': [
      'ytd-ad-slot-renderer',
      'ytd-display-ad-renderer',
      'ytd-in-feed-ad-layout-renderer',
      'ytd-promoted-sparkles-web-renderer',
      'ytd-promoted-video-renderer',
      'ytd-search-pyv-renderer',
      '#player-ads',
      '#masthead-ad',
      '.ytp-ad-module',
      '.ytp-ad-overlay-container',
      '.ytp-ad-image-overlay',
      '.ytp-ad-skip-button-container',
      '.video-ads'
    ],
    'm.youtube.com': [
      'ytd-ad-slot-renderer',
      'ytd-display-ad-renderer',
      'ytd-in-feed-ad-layout-renderer',
      'ytd-promoted-sparkles-web-renderer',
      'ytd-promoted-video-renderer',
      'ytd-search-pyv-renderer',
      '#player-ads',
      '#masthead-ad',
      '.ytp-ad-module',
      '.ytp-ad-overlay-container',
      '.ytp-ad-image-overlay',
      '.ytp-ad-skip-button-container',
      '.video-ads'
    ],
    'music.youtube.com': [
      'ytmusic-shorts-lockup-view-model',
      'ytmusic-mealbar-promo-renderer',
      'ytmusic-ads-renderer',
      '[id*="ad"]'
    ],
    'www.tiktok.com': [
      'div[data-e2e*="ad"]',
      'div[class*="ad"]',
      'iframe[src*="ads"]'
    ]
  };

  function removeNodes(selectors) {
    for (const selector of selectors) {
      document.querySelectorAll(selector).forEach((node) => {
        node.remove();
      });
    }
  }

  function cleanPage() {
    removeNodes(COMMON_SELECTORS);

    const hostSelectors = HOST_SELECTORS[window.location.hostname];
    if (hostSelectors) {
      removeNodes(hostSelectors);
    }
  }

  const observer = new MutationObserver(() => {
    cleanPage();
  });

  const start = () => {
    cleanPage();

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

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', start, { once: true });
  } else {
    start();
  }
})();
