"use client"

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

import { webviews } from "@/constants/routes/webviews"
import useTrackingStore from "@/stores/tracking"

import { createSDKPageObject } from "@/utils/tracking"

import { TrackingSDKProps } from "@/types/components/tracking"

export default function TrackingSDK({ pageData, userData }: TrackingSDKProps) {
  const pathName = usePathname()
  const isWebview = webviews.includes(pathName)
  const { hasRun, setHasRun } = useTrackingStore()

  const CookiebotCallbackOnAccept = useCallback(() => {
    const cookie = window._satellite.cookie.get("CookieConsent")

    if (window.Cookiebot?.changed && window.adobe) {
      // 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(() => {
    if (!hasRun) {
      const perfObserver = new PerformanceObserver((observedEntries) => {
        const entry = observedEntries.getEntriesByType("navigation")[0]

        if (entry && window.adobeDataLayer) {
          const trackingData = { ...pageData, pathName }
          const pageObject = createSDKPageObject(trackingData)

          window.adobeDataLayer.push({
            event: "pageView",
            pageInfo: pageObject,
            userInfo: userData,
          })
          perfObserver.disconnect()
        }
      })

      perfObserver.observe({
        type: "navigation",
        buffered: true,
      })

      setHasRun()
    }
  }, [pathName, pageData, userData, hasRun, setHasRun])

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

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

  return null
}
