import { BreadcrumbItem } from "@/types/shared";
import Link from "next/link";

interface BreadcrumbProps {
  items: BreadcrumbItem[];
}

const Breadcrumb = ({ items }: BreadcrumbProps) => {
  const currentPage = items[items.length - 1];
  const toDataCySegment = (value: string) =>
    value.toLowerCase().replace(/[^a-z0-9]+/g, "-");

  return (
    <div
      className="mb-3 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between"
      data-cy="breadcrumb"
    >
      <h2 className="text-[16px] font-bold leading-[30px] text-dark dark:text-white">
        {currentPage.name}
      </h2>

      <nav data-cy="breadcrumb-nav">
        <ol className="flex items-center gap-2">
          {items.map((item, index) => {
            const isLast = index === items.length - 1;
            const dataCySegment = toDataCySegment(item.name);

            return isLast ? (
              <li
                key={index}
                className="font-medium text-sm text-primary"
                data-cy={`breadcrumb-current-${dataCySegment}`}
              >
                {item.name}
              </li>
            ) : (
              <li key={index} className="flex items-center gap-2">
                <Link
                  href={item.href}
                  data-cy={`breadcrumb-link-${dataCySegment}`}
                  className="font-medium text-sm hover:text-primary"
                >
                  {item.name}
                </Link>
                <span className="text-dark dark:text-white">/</span>
              </li>
            );
          })}
        </ol>
      </nav>
    </div>
  );
};

export default Breadcrumb;
