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

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

interface BreadcrumbContextValue {
  override: BreadcrumbItem[] | null
  setOverride: (items: BreadcrumbItem[] | null) => void
}

const BreadcrumbContext = createContext<BreadcrumbContextValue>({
  override: null,
  setOverride: () => {},
})

export function BreadcrumbProvider({ children }: { children: ReactNode }) {
  const [override, setOverride] = useState<BreadcrumbItem[] | null>(null)
  return (
    <BreadcrumbContext.Provider value={{ override, setOverride }}>
      {children}
    </BreadcrumbContext.Provider>
  )
}

/**
 * Override the TopBar breadcrumb with page-specific semantic items.
 * Pass `null` to clear (or let unmount handle it).
 * Callers should `useMemo` the items array to avoid unnecessary re-renders.
 */
export function useBreadcrumb(items: BreadcrumbItem[] | null) {
  const { setOverride } = useContext(BreadcrumbContext)
  useEffect(() => {
    setOverride(items)
    return () => setOverride(null)
  }, [items, setOverride])
}

/** Internal — used by TopBar to read the current override. */
export function useBreadcrumbOverride(): BreadcrumbItem[] | null {
  return useContext(BreadcrumbContext).override
}
