/**
 * 百度：
 * data-tuiguang 带广告的标识
 * c-container 一条搜索结果
 * bing：
 * .b_ad 广告标识
 */

// 是否是百度
let isBaidu = window.location.host === "www.baidu.com"
// 是否是bing
let isBing = window.location.host.includes("bing.com")

// 首次加载隐藏广告
function hiddenAdsFirstLoad() {
  if (isBaidu) {
    const adsList = document.querySelectorAll("[data-tuiguang]")
    adsList.forEach((adsItem) => {
      handleHiddenAdsBaidu(adsItem)
    })
  } else if (isBing) {
    const adsList = document.querySelectorAll(".b_ad")
    adsList.forEach((adsItem) => {
      handleHiddenAdsBing(adsItem)
    })
  }
}

function handleHiddenAds(searchItem) {
  if (searchItem) {
    const isHandled = searchItem.classList.contains("ovo-search-ads-filter") // 是否已经处理过
    const isWhiteList = searchItem.classList.contains(
      "ovo-search-ads-filter-show"
    ) // 是否已经点击过【显示广告】
    if (isHandled || isWhiteList) {
      return
    }
    searchItem.classList.add("ovo-search-ads-filter")
    // 查询searchItem的下一个元素是否有按钮
    const button = searchItem.nextElementSibling
    const notButton = !(
      button && button.classList.contains("ovo-search-ads-filter-button")
    )
    if (notButton) {
      // 创建一个按钮，点击后显示广告
      const button = document.createElement("button")
      button.innerText = "显示广告"
      button.classList.add("ovo-search-ads-filter-button")
      // 按钮插入广告元素的下一个元素
      searchItem.insertAdjacentElement("afterend", button)
    }
  }
}

// 隐藏广告 - 百度
function handleHiddenAdsBaidu(ads) {
  // 找到搜索结果容器
  const searchItem = ads.closest(".c-container")
  handleHiddenAds(searchItem)
}

// 隐藏广告 - bing
function handleHiddenAdsBing(searchItem) {
  handleHiddenAds(searchItem)
}

// 监听 DOM 变化
function setupAdsFilterMutationObserver() {
  const observer = new MutationObserver(adsFilterMutationObserverCallback)

  const config = { childList: true, subtree: true } // 监听子节点变化 和 所有后代节点变化
  observer.observe(document.body, config)
}

// 防抖函数
function debounceAds(func, wait) {
  let timeout
  return function(...args) {
    clearTimeout(timeout)
    timeout = setTimeout(() => func.apply(this, args), wait)
  }
}

// 防抖处理的 handleHiddenAdsBing 调用
const debouncedHandleHiddenAdsBing = debounceAds(() => {
  const adsList = document.querySelectorAll(".b_ad")
  adsList.forEach((adsItem) => {
    handleHiddenAdsBing(adsItem)
  })
}, 300)

// 监听 DOM 变化回调
function adsFilterMutationObserverCallback(mutations) {
  requestAnimationFrame(() => {
    // 是否是百度
    isBaidu = window.location.host === "www.baidu.com"
    // 是否是bing
    isBing = window.location.host.includes("bing.com")
    mutations.forEach((mutation) => {
      if (mutation.type === "childList") {
        mutation.addedNodes.forEach((node) => {
          if (isBaidu) {
            if (node.nodeType === 1 && node.hasAttribute("data-tuiguang")) {
              handleHiddenAdsBaidu(node)
            }
          } else if (isBing) {
            // bing bing无法用mutation观察到广告的变化
            // if (node.nodeType === 1 && node.classList.contains("b_ad")) {
            //   handleHiddenAdsBing(node)
            // }

            if (node.nodeType === 1) {
              debouncedHandleHiddenAdsBing()
            }
          }
        })
      }
    })
  })
}

function bindEvent() {
  document.body.addEventListener("click", (e) => {
    if (e.target.classList.contains("ovo-search-ads-filter-button")) {
      if (isBaidu) {
        const searchItem = e.target.previousElementSibling
        searchItem.classList.add("ovo-search-ads-filter-show")
        searchItem.classList.remove("ovo-search-ads-filter")
        e.target.remove()
      } else if (isBing) {
        let searchItem = e.target.previousElementSibling
        if (!searchItem.classList.contains("b_ad")) {
          searchItem = searchItem.previousElementSibling
        }
        searchItem.classList.add("ovo-search-ads-filter-show")
        searchItem.classList.remove("ovo-search-ads-filter")
        e.target.remove()
      }
    }
  })
}

// 检查是否开启此功能
if (isBaidu || isBing) {
  window.chrome.storage.sync.get(["OVO_SEARCH_ADS_FILTER"], (result) => {
    if (result.OVO_SEARCH_ADS_FILTER) {
      hiddenAdsFirstLoad()
      setupAdsFilterMutationObserver()
      bindEvent()
    }
  })
}
