import React, { createContext, useContext, useState, ReactNode } from 'react';

export type Breadcrumb = {
  title: string;
  path?: string;
  isCurrentPage?: boolean;
};

type BreadcrumbsContextType = {
  breadcrumbs: Breadcrumb[];
  setBreadcrumbs: (breadcrumbs: Breadcrumb[]) => void;
};

const BreadcrumbsContext = createContext<BreadcrumbsContextType | undefined>(undefined);

export const BreadcrumbsProvider: React.FC<{children: ReactNode}> = ({ children }) => {
  const [breadcrumbs, setBreadcrumbs] = useState<Breadcrumb[]>([]);

  return (
    <BreadcrumbsContext.Provider value={{ breadcrumbs, setBreadcrumbs }}>
      {children}
    </BreadcrumbsContext.Provider>
  );
};

export const useBreadcrumbs = () => {
  const context = useContext(BreadcrumbsContext);
  if (context === undefined) {
    throw new Error('useBreadcrumbs must be used within a BreadcrumbsProvider');
  }
  return context;
};

export const useSetBreadcrumbs = (newBreadcrumbs: Breadcrumb[]) => {
  const { setBreadcrumbs } = useBreadcrumbs();
  
  React.useEffect(() => {
    setBreadcrumbs(newBreadcrumbs);
    
    return () => {
      // При размонтировании компонента очищаем хлебные крошки
      setBreadcrumbs([]);
    };
  }, [setBreadcrumbs, JSON.stringify(newBreadcrumbs)]);
}; 