"use client"

import {
	createContext,
	type JSX,
	type ReactNode,
	useContext,
	useEffect,
	useState,
} from "react"

export interface BreadcrumbItem {
	label: string
	href?: string
}

interface BreadcrumbsContextValue {
	items: BreadcrumbItem[]
	setItems: (items: BreadcrumbItem[]) => void
}

const BreadcrumbsContext = createContext<BreadcrumbsContextValue>({
	items: [],
	setItems: () => {},
})

export const BreadcrumbsProvider = ({
	children,
}: {
	children: ReactNode
}): JSX.Element => {
	const [items, setItems] = useState<BreadcrumbItem[]>([])

	return (
		<BreadcrumbsContext.Provider value={{ items, setItems }}>
			{children}
		</BreadcrumbsContext.Provider>
	)
}

export const useBreadcrumbs = (items: BreadcrumbItem[]): void => {
	const { setItems } = useContext(BreadcrumbsContext)

	useEffect(() => {
		setItems(items)
		return () => setItems([])
	}, [JSON.stringify(items)])
}

export const useBreadcrumbItems = (): BreadcrumbItem[] => {
	return useContext(BreadcrumbsContext).items
}
