import { ReactNode, useEffect, useState } from 'react' import { useLocation, useNavigate, useNavigationType } from 'react-router-dom' import { HistoryContext } from './HistoryContext' export type IHistoryContext = ReturnType const useInitialState = () => { const navigate = useNavigate() const location = useLocation() const navType = useNavigationType() const currentLocation = location.pathname + location.search const [canGoBackCount, setCanGoBackCount] = useState(0) const [previousPaths, setPreviousPaths] = useState([]) useEffect(() => { if (navType === 'PUSH') { setCanGoBackCount(prev => prev + 1) setPreviousPaths(prev => [...prev, currentLocation]) } else if (navType === 'POP') { setCanGoBackCount(prev => Math.max(prev - 1, 0)) setPreviousPaths(prev => prev.slice(0, -1)) } }, [currentLocation, navType]) const goBack = () => { // Always try to go back first if there's browser history if (canGoBackCount > 0) { navigate(-1) } else if (previousPaths.length > 1) { // If we have a previous path, navigate to it const previousPath = previousPaths[previousPaths.length - 2] navigate(previousPath, { replace: true }) } else { // Only navigate to home as absolute last resort // Check current path to avoid redirecting home from home if (location.pathname !== '/' && location.pathname !== '/home') { navigate('/', { replace: true }) } } } return { goBack, canGoBack: canGoBackCount > 0 || previousPaths.length > 1 } } export const HistoryContextProvider = ({ children }: { children: ReactNode }) => { const initialState = useInitialState() return {children} }