"use client"
import { useRouter } from "next/navigation"
import { createContext, useEffect, useState } from "react"

import useHash from "@/hooks/useHash"

interface ISidePeekContext {
  handleClose: (isOpen: boolean) => void
  activeSidePeek: string | null
}

export const SidePeekContext = createContext<ISidePeekContext | null>(null)

export default function SidePeekProvider({
  children,
}: React.PropsWithChildren) {
  const router = useRouter()
  const hash = useHash()
  const [activeSidePeek, setActiveSidePeek] = useState<string | null>(null)

  useEffect(() => {
    if (hash?.startsWith("s-")) {
      setActiveSidePeek(hash.slice(2))
    } else {
      setActiveSidePeek(null)
    }
  }, [hash, setActiveSidePeek])

  function handleClose(isOpen: boolean) {
    if (!isOpen) {
      router.push(window.location.pathname, { scroll: false })
      setActiveSidePeek(null)
    }
  }

  return (
    <SidePeekContext.Provider value={{ handleClose, activeSidePeek }}>
      {children}
    </SidePeekContext.Provider>
  )
}
