"use client"

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

import { useHotelListingDataStore } from "@/stores/hotel-listing-data"

export default function HotelListingDataProviderContent({
  children,
}: React.PropsWithChildren) {
  const params = useParams()
  const { updateActiveFiltersAndSort, allFilterSlugs } =
    useHotelListingDataStore((state) => ({
      allFilterSlugs: state.allFilterSlugs,
      updateActiveFiltersAndSort: state.actions.updateActiveFiltersAndSort,
    }))

  useEffect(() => {
    const currentUrl = new URL(window.location.href)
    const searchParams = currentUrl.searchParams
    const sort = searchParams.get("sort")
    const filterParam = searchParams.get("filter")
    const activeFilters: string[] = []

    if (filterParam) {
      const filters = filterParam.split(",")
      filters.forEach((filter) => {
        if (allFilterSlugs.includes(filter)) {
          activeFilters.push(filter)
        }
      })
    }

    updateActiveFiltersAndSort(activeFilters, sort)
  }, [params, updateActiveFiltersAndSort, allFilterSlugs])

  return <>{children}</>
}
