"use client"

import { usePathname } from "next/navigation"
import { useCallback, useEffect } from "react"

import { webviews } from "@/constants/routes/webviews"

export default function CookieBotConsent() {
  const pathName = usePathname()
  const isWebview = webviews.includes(pathName)
  const CookiebotCallbackOnAccept = useCallback(() => {
    if (window.Cookiebot?.changed && window.adobe) {
      const cookie = window._satellite?.cookie?.get("CookieConsent")
      // For webviews we always set the consent to true since we don't have cookiebot.
      if (isWebview) {
        window.adobe.optIn.approve(window.adobe.OptInCategories.ANALYTICS, true)
      } else if (cookie?.includes("statistics:true")) {
        window.adobe.optIn.approve(window.adobe.OptInCategories.ANALYTICS, true)
      } else {
        window.adobe.optIn.deny(window.adobe.OptInCategories.ANALYTICS, true)
      }
      window.adobe.optIn.complete()
      console.warn("window.load event explicitly dispatched.")
      window.dispatchEvent(new Event("load"))
    }
  }, [isWebview])

  function CookebotCallbackOnDecline() {
    if (window.Cookiebot?.changed && window.adobe) {
      window.adobe.optIn.deny(window.adobe.OptInCategories.ANALYTICS, true)
    }
  }

  useEffect(() => {
    // handle consent
    window.addEventListener("CookiebotOnAccept", CookiebotCallbackOnAccept)
    window.addEventListener("CookiebotOnDecline", CookebotCallbackOnDecline)

    return () => {
      window.removeEventListener("CookiebotOnAccept", CookiebotCallbackOnAccept)
      window.removeEventListener(
        "CookiebotOnDecline",
        CookebotCallbackOnDecline
      )
    }
  }, [CookiebotCallbackOnAccept])

  return null
}
