"use client"

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

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

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

function createSDKPageObject(trackingData: TrackingSDKData) {
  const [lang, ...segments] = trackingData.pathName
    .split("/")
    .filter((seg: string) => seg)

  const joinedSegments = segments.join("|")

  const { host: domain } = window.location
  const page_obj = {
    pageType: trackingData.pageType,
    pageName: joinedSegments,
    pageId: trackingData.pageId,
    channel: trackingData.channel,
    siteSection: joinedSegments,
    domain,
    siteversion: "new-web",
    domainlanguage: trackingData.lang ? trackingData.lang : lang,
    createDate: trackingData.createdDate,
    publishDate: trackingData.publishedDate,
    // sessionid: "<unique identifier of session>", // base on what?
  }
  return page_obj
}

export default function TrackingSDK({ pageData, userData }: TrackingSDKProps) {
  const pathName = usePathname()
  const isWebview = webviews.includes(pathName)
  const [initPerformanceTracking, setInitPerformanceTracking] = useState(true)

  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 (initPerformanceTracking) {
      const perfObserver = new PerformanceObserver((observedEntries) => {
        const entry = observedEntries.getEntriesByType("navigation")[0]

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

          const { loadEventEnd, startTime, duration } =
            entry as PerformanceNavigationTiming

          window.adobeDataLayer.push({
            event: "pageViewEnd",
            pageInfo: pageObject,
            userInfo: userData,
            timing: {
              duration,
              loadEventEnd,
              startTime,
            },
          })
        }
      })

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

      setInitPerformanceTracking(false)

      // Cleanup function to disconnect the observer
      return () => {
        perfObserver.disconnect()
      }
    }
  }, [pathName, pageData, userData, initPerformanceTracking])

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

      window.adobeDataLayer.push({
        event: "pageView",
        pageInfo: pageObject,
        userInfo: userData,
      })
    }
  }, [pathName, pageData, userData])

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

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

  return null
}
