"use client"

import { useParams } from "next/navigation"
import { useEffect } from "react"

import { useDestinationDataStore } from "@/stores/destination-data"

export default function DestinationDataProviderContent({
  children,
}: React.PropsWithChildren) {
  const params = useParams()
  const { basePath, updateActiveFiltersAndSort } = useDestinationDataStore(
    (state) => ({
      basePath: state.basePathnameWithoutFilters,
      updateActiveFiltersAndSort: state.actions.updateActiveFiltersAndSort,
    })
  )

  useEffect(() => {
    const currentUrl = new URL(window.location.href)
    const searchParams = currentUrl.searchParams
    const currentPathname = currentUrl.pathname
    const sort = searchParams.get("sort")
    const filterParam = searchParams.get("filter")
    const filters = []
    const pathParts = currentPathname.split("/")
    const filterFromUrl = pathParts[pathParts.length - 1]

    // Even though the user filter is stored in the query param,
    // we also support having it as the last part of the pathname
    // e.g. /destination/copenhagen/spa
    // In this case we need to add it to the filters array
    if (basePath !== currentPathname) {
      filters.push(filterFromUrl)
    }
    if (filterParam) {
      filters.push(...filterParam.split("&"))
    }

    updateActiveFiltersAndSort(filters, sort, filterFromUrl)
  }, [params, updateActiveFiltersAndSort, basePath])

  return <>{children}</>
}
