"use client";

import type { ReactElement, RefAttributes, ReactNode } from "react";
import { Children, cloneElement } from "react";
import classNames from "classnames/dedupe";
import "./Breadcrumbs.css";

export type BreadcrumbsElementType = HTMLElement;

export interface BreadcrumbsProps extends RefAttributes<BreadcrumbsElementType> {
  /** Custom class name for setting specific CSS */
  className?: string;
  children?: ReactNode;
  "aria-label"?: string;
}

const Breadcrumbs = ({ ref, ...props }: BreadcrumbsProps) => {
  const { "aria-label": ariaLabel = "Breadcrumbs" } = props;
  const { navProps } = { navProps: { "aria-label": ariaLabel } };
  const { children, ...otherProps } = props;
  const childArray = Children.toArray(children);

  // Reshape class name and apply to outer element
  const classes = classNames(
    "mobius",
    "mobius-breadcrumb",
    otherProps.className,
  );

  return (
    <nav ref={ref} {...otherProps} {...navProps} className={classes}>
      <ul>
        {childArray.map((child, i) =>
          cloneElement(child as ReactElement<{ isCurrent?: boolean }>, {
            isCurrent: i === childArray.length - 1,
          }),
        )}
      </ul>
    </nav>
  );
};

Breadcrumbs.displayName = "Breadcrumbs";
export { Breadcrumbs };
