"use client"

import {
  createContext, useContext, useEffect, useRef,
  useState, type ReactNode,
} from "react"
import { usePathname } from "next/navigation"

type NavHistoryCtx = {
  /** true si on peut revenir en arrière dans la session */
  canGoBack: boolean
  /** chemin complet de la page précédente */
  previousPath: string | null
}

const Ctx = createContext<NavHistoryCtx>({ canGoBack: false, previousPath: null })

export function NavigationHistoryProvider({ children }: { children: ReactNode }) {
  const pathname = usePathname()
  const stackRef = useRef<string[]>([])
  const [state, setState] = useState<NavHistoryCtx>({ canGoBack: false, previousPath: null })

  useEffect(() => {
    const stack = stackRef.current
    const last = stack[stack.length - 1]
    if (last === pathname) return           // même page, rien à faire
    stack.push(pathname)
    const prev = stack.length >= 2 ? stack[stack.length - 2] : null
    setState({ canGoBack: stack.length > 1, previousPath: prev })
  }, [pathname])

  return <Ctx.Provider value={state}>{children}</Ctx.Provider>
}

export function useNavHistory() {
  return useContext(Ctx)
}
