import React, { useMemo } from "react";
import { Breadcrumb } from "antd";
import { useTranslation } from "react-i18next";
import styles from "../CategoryPage.module.scss";

const CategoryBreadcrumbs = ({ categoriesData, categoryId, onCategoryClick }) => {
  const { t } = useTranslation();

  const breadcrumbs = useMemo(() => {
    if (!categoriesData?.data || !categoryId) return [];

    const buildPath = (categories, targetId, path = []) => {
      for (const category of categories) {
        if (category.id === parseInt(targetId)) {
          return [...path, category];
        }
        if (category.children) {
          const found = buildPath(category.children, targetId, [...path, category]);
          if (found) return found;
        }
      }
      return null;
    };

    return buildPath(categoriesData.data, categoryId) || [];
  }, [categoriesData, categoryId]);

  if (breadcrumbs.length === 0) return null;

  return (
    <Breadcrumb className={styles.breadcrumb}>
      
      
      {breadcrumbs.map((crumb, index) => {
        const isLast = index === breadcrumbs.length - 1;
        
        return (
          <Breadcrumb.Item key={crumb.id}>
            {isLast ? (
              <span>{crumb.name}</span>
            ) : (
              <a 
                onClick={(e) => {
                  e.preventDefault();
                  onCategoryClick?.(crumb.id);
                }}
                style={{ cursor: 'pointer' }}
              >
                {crumb.name}
              </a>
            )}
          </Breadcrumb.Item>
        );
      })}
    </Breadcrumb>
  );
};

export default CategoryBreadcrumbs;