/**
 * Breadcrumbs component matching the Angular `page-breadcrumbs` component.
 *
 * Renders a simple breadcrumb trail. First item always links to the
 * main Aeroflot site. Additional items come from props.
 *
 * @module
 */

import type { FC } from "react";
import { useTranslation } from "@/i18n/provider.js";
import "./Breadcrumbs.scss";

export interface BreadcrumbItem {
  label: string;
  url?: string;
}

export interface BreadcrumbsProps {
  items?: BreadcrumbItem[];
}

export const Breadcrumbs: FC<BreadcrumbsProps> = ({ items = [] }) => {
  const { t } = useTranslation();

  const allItems: BreadcrumbItem[] = [
    { label: t("SHARED.MAIN"), url: "https://www.aeroflot.ru" },
    ...items,
  ];

  return (
    <nav className="breadcrumbs" aria-label={t("SHARED.A11Y-BREADCRUMB")} data-testid="breadcrumbs">
      <ol className="breadcrumbs__list">
        {allItems.map((item, index) => {
          const isLast = index === allItems.length - 1;
          // All items with a url render as links. This includes the last item
          // (leaf crumb) when it represents a navigatable back-link, per TZ
          // Table 7 row 6 note: the last breadcrumb on details pages must
          // navigate back to the search results page with filter state preserved.
          // Previously this was `index === 0 || !isLast`, which suppressed links
          // on the last crumb — that was incorrect for details pages.
          const showAsLink = Boolean(item.url);
          return (
            <li
              key={`${item.label}-${index}`}
              className={`breadcrumbs__item${isLast ? " breadcrumbs__item--active" : ""}`}
            >
              {showAsLink ? (
                <a
                  href={item.url}
                  className="breadcrumbs__link"
                  {...(isLast ? { "aria-current": "page" } : {})}
                >
                  {item.label}
                </a>
              ) : (
                <span
                  className="breadcrumbs__text"
                  {...(isLast ? { "aria-current": "page" } : {})}
                >
                  {item.label}
                </span>
              )}
              {!isLast && (
                <span className="breadcrumbs__separator" aria-hidden="true">/</span>
              )}
            </li>
          );
        })}
      </ol>
    </nav>
  );
};
