const url = new URL(window.location.href)

const onload = () => {
  const images = document.body.querySelectorAll('main img')

  if (navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i)) {
    const imagesForMobile = Array.from(images).filter(image => image.clientWidth >= 160)
    fetch(
      `https://ssp.afp.ai/api/sdk_statistic/event_mobile_image_found?publisher_page_url=${window.location.href}&add_info_reserved=${imagesForMobile.length}`,
      {
        method: 'POST',
      }
    )
  } else {
    const imagesForDesktop = Array.from(images).filter(image => image.clientWidth >= 300)
    fetch(
      `https://ssp.afp.ai/api/sdk_statistic/event_desktop_image_found?publisher_page_url=${window.location.href}&add_info_reserved=${imagesForDesktop.length}`,
      {
        method: 'POST',
      }
    )
  }
}

if (url.pathname !== '/' && url.hostname.endsWith('lifehacker.ru')) {
  fetch(
    `https://ssp.afp.ai/api/sdk_statistic/event_sdk_load?publisher_page_url=${window.location.href}`,
    {
      method: 'POST',
    }
  )

  if (document.readyState === 'complete') {
    onload()
  } else {
    window.addEventListener('load', onload)
  }
}
