import { useEffect, useState } from "react"
import { Outlet, useLocation, useNavigate, useParams } from "react-router-dom"
import { Spinner } from "@heroui/react"
import { fetchCategories, type StoreCategory } from "../api/store"
import SiteHeader from "../components/SiteHeader"

export default function StoreLayout() {
  const { categorySlug } = useParams<{ categorySlug?: string }>()
  const navigate = useNavigate()
  const location = useLocation()
  const [, setCategories] = useState<StoreCategory[]>([])
  const [loading, setLoading] = useState(true)
  const isProductPage = location.pathname.split("/").filter(Boolean).length >= 3

  useEffect(() => {
    fetchCategories()
      .then((res) => {
        const cats = res.data ?? []
        setCategories(cats)
        if (!categorySlug && cats.length > 0) {
		  const query = new URLSearchParams(location.search)
		  const requestedCategory = query.get("category")
		  const requestedGroup = query.get("group")
		  if (requestedCategory && requestedGroup) {
		    query.delete("category")
		    query.delete("group")
		    const suffix = query.toString()
		    navigate(`/store/${encodeURIComponent(requestedCategory)}/${encodeURIComponent(requestedGroup)}${suffix ? `?${suffix}` : ""}`, { replace: true })
		  } else {
		    navigate(`/store/${cats[0].slug}`, { replace: true })
		  }
        }
      })
      .finally(() => setLoading(false))
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  if (isProductPage) {
    return loading ? (
      <div className="flex min-h-screen items-center justify-center bg-white py-24">
        <Spinner size="lg" />
      </div>
    ) : (
      <Outlet />
    )
  }

  return (
    <div className="min-h-screen flex flex-col bg-white">
      <SiteHeader variant="solid" />
      {loading ? (
        <div className="flex flex-1 items-center justify-center py-24">
          <Spinner size="lg" />
        </div>
      ) : (
        <main className="flex-1">
          <Outlet />
        </main>
      )}
    </div>
  )
}
