import { useEffect, useRef } from 'react'
import { useBreadcrumbContext, BreadcrumbItem } from '../contexts/BreadcrumbContext'

export function useBreadcrumb(baseCrumbs: BreadcrumbItem[]) {
  const { setBreadcrumbs, appendBreadcrumb, updateLastBreadcrumb, popBreadcrumb } = useBreadcrumbContext()
  const initializedRef = useRef(false)

  // Set base breadcrumbs on mount
  useEffect(() => {
    if (!initializedRef.current) {
      setBreadcrumbs(baseCrumbs)
      initializedRef.current = true
    }

    // Reset on unmount for next page
    return () => {
      initializedRef.current = false
    }
  }, []) // Empty deps - only run on mount/unmount

  return {
    setBreadcrumbs,
    appendBreadcrumb,
    updateLastBreadcrumb,
    popBreadcrumb,
    setContext: (label: string) => updateLastBreadcrumb(label),
    addContext: (label: string, path?: string) => appendBreadcrumb({ label, path }),
    removeContext: () => popBreadcrumb()
  }
}
