import { forwardRef, useLayoutEffect, useRef, useState } from "react";
import { pxToRem } from "../../../utils";

import { CrumbListItem, RadixNavigationMenuLink } from "../breadcrumbs.styled";
import { BaseCrumb } from "./base-crumb";

import type { CrumbProps } from "./crumb-props";

const CRUMB_MAX_MIN_WIDTH = 64;

const CrumbComponent = forwardRef<
  HTMLAnchorElement,
  CrumbProps & { crumbItemProps?: React.ComponentProps<typeof CrumbListItem>; isFirst?: boolean }
>((props, ref) => {
  const { divider, crumbItemProps, isFirst, ...rest } = props;
  const [minWidth, setMinWidth] = useState("0");
  const listElemRef = useRef<HTMLLIElement>(null);

  useLayoutEffect(() => {
    const listElem = listElemRef.current;
    if (!listElem || (!isFirst && !rest.isLast)) {
      return;
    }

    const originalFlexBasis = listElem.style.flexBasis;
    listElem.style.flexBasis = "fit-content";

    const crumbWidth = listElem.offsetWidth;

    setMinWidth(pxToRem(Math.min(CRUMB_MAX_MIN_WIDTH, crumbWidth)));
    listElem.style.flexBasis = originalFlexBasis;
  }, [isFirst, rest.isLast]);

  return (
    <>
      <CrumbListItem
        {...crumbItemProps}
        ref={listElemRef}
        {...((isFirst || rest.isLast) && { css: { minWidth } })}
      >
        <RadixNavigationMenuLink asChild>
          <BaseCrumb ref={ref} {...rest} />
        </RadixNavigationMenuLink>
      </CrumbListItem>

      {!rest.isLast && <li aria-hidden="true">{divider}</li>}
    </>
  );
});

CrumbComponent.displayName = "Crumb";

export const Crumb = CrumbComponent;
