"use client"

import { useCallback, useEffect } from "react"

import { logger } from "@scandic-hotels/common/logger"

export default function CookieBotConsent() {
  const CookiebotCallbackOnAccept = useCallback(() => {
    if (window.Cookiebot?.changed && window.adobe) {
      const cookie = window._satellite?.cookie?.get("CookieConsent")

      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()
      logger.warn("window.load event explicitly dispatched.")
      window.dispatchEvent(new Event("load"))
    }
  }, [])

  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
}
