"use client"
import "client-only" // NEEDED?

import { TrackingData, TrackingProps } from "@/types/components/tracking"
import { usePathname, useSearchParams } from "next/navigation"
import { useEffect } from "react"

type WindowWithDataLayer = Window & {
  datalayer: { [key: string]: any }
}

declare const window: WindowWithDataLayer

function createPageObject(trackingData: TrackingData) {
  const [lang, ...segments] = trackingData.pathName
    .split("/")
    .filter((v: string) => v)

  // Better to get lang from useParams() instead?? ⬆️

  function getSiteSections(segments: string[]) {
    const sitesections: { [key: string]: string } = {}
    // Adobe expects the properties sitesection1 - sitessection6, hence the for-loop below
    for (let i = 0; i < 6; i++) {
      const key = "value" + (i + 1)
      sitesections[key] = segments.slice(0, i + 1).join("|")
      if (i > 0 && !segments[i]) {
        sitesections[key] = sitesections[key].concat(
          "|".repeat(i + 1 - segments.length)
        )
      }
    }
    return sitesections
  }
  const sitesections = getSiteSections(segments)
  const { host: domain, href: pageurl } = window.location

  const page_obj = {
    pagename: trackingData.pageName,
    pagetype: trackingData.pageType,
    pageurl, // is window.location.href viable?
    ...sitesections,
    createDate: trackingData.createdDate,
    publishDate: trackingData.publishedDate,
    domain, // is window.location.host viable?
    errorcode: null, // handle
    querystring: trackingData.queryString || "",
    pageid: trackingData.pageId,
    sessionid: "<unique identifier of session>", // base on what?
    domainlanguage: lang,
    hotelbrand: "scandic", // "<scandic or scandicgo)>", what is this based on?
    siteversion: "new-web", // good enough?
  }
  return page_obj
}

export default function Tracking({ pageData }: TrackingProps) {
  const pathName = usePathname()
  const queryString = useSearchParams().toString()
  useEffect(() => {
    if (!window.datalayer) {
      console.log("creating datalayer 🧑‍🔧")
      window.datalayer = {}
    } else {
      const trackingData = { ...pageData, pathName, queryString }
      const pageObject = createPageObject(trackingData)

      window.datalayer.page = pageObject

      // NOTE: Is this irrelevant för drop 1?
      // var user_obj = {
      //   loginstatus: "<if the user is logged in or not>",
      //   memberid: "<unique meeting package membership id for the user>",
      //   memberlevel: "<member level of user>",
      // }

      // datalayer.user = user_obj;
      console.log("🤖 datalayer: ", window.datalayer)
    }
  }, [pathName, queryString, pageData])

  return null
}
