import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import ResizeObserver from 'resize-observer-polyfill';
import { faEllipsisVertical } from '@fortawesome/free-solid-svg-icons/faEllipsisVertical';
import { DropdownMenu } from '../dropdown-menu';
import { sortOptions } from './adaptive-list-utils';
import { useTranslation } from '../hooks/use-translation';
import { FontAwesomeIcon } from '../font-awesome-icon';
import { useFontSizeObserver } from '../hooks';
import { DRAW_STATE } from './adaptive-list-constants';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/** Adaptive List
    @midnight-gray-supported
    @alpine-light-supported
 */
export default function AdaptiveList({
  options,
  Component,
  selected,
  onSelect = () => {},
  target = 'offsetWidth',
  triggerOffset = 44,
  dropdownMenuProps = {},
  truncatedView,
  triggerAriaLabelText,
  isSubNavItem = false,
  componentProps = {}
}) {
  const {
    t
  } = useTranslation();
  const fontSize = useFontSizeObserver();
  const [parentWidth, setParentWidth] = useState(Infinity);
  const elements = useRef({});
  const elementsWidth = useRef({});
  const container = useRef(null);
  const selectedArr = Array.isArray(selected) ? selected : [selected].filter(val => typeof val !== 'undefined');
  const [state, setState] = useState(DRAW_STATE.CALCULATING);
  useLayoutEffect(() => {
    if (fontSize?.previousSize !== fontSize?.currentSize) {
      setState(DRAW_STATE.CALCULATING);
    }
  }, [fontSize]);
  useLayoutEffect(() => {
    setState(DRAW_STATE.CALCULATING);
  }, [options]);
  useEffect(() => {
    const outputWidth = () => {
      setParentWidth(container?.current?.[target] || 0);
    };
    if (container.current) {
      const observer = new ResizeObserver(() => window.requestAnimationFrame(outputWidth));
      observer.observe(container.current);
      return () => observer.disconnect();
    }
  }, []);
  const {
    active,
    inActive
  } = useMemo(() => sortOptions({
    options,
    maxWidth: parentWidth,
    selected: selectedArr,
    optionsWidth: elementsWidth.current,
    startWidth: triggerOffset,
    state
  }), [options, parentWidth, selected, triggerOffset, state]);
  useLayoutEffect(() => {
    if (state === DRAW_STATE.CALCULATING) {
      elementsWidth.current = Object.keys(elements.current).reduce((acc, current) => ({
        ...acc,
        [current]: elements.current[current]?.[target] || 0
      }), {});
      setState(DRAW_STATE.PAINTING);
    }
  }, [state]);
  useLayoutEffect(() => {
    setParentWidth(container?.current?.[target] || 0);
  }, []);
  const isLimited = !!inActive.length;
  return /*#__PURE__*/_jsxs("div", {
    ref: container,
    "test-id": "adaptive-list",
    className: "adaptive-list-container",
    children: [/*#__PURE__*/_jsx("div", {
      className: "adaptive-list",
      role: isSubNavItem ? 'tablist' : undefined,
      children: active.map(option => /*#__PURE__*/_jsx("div", {
        ref: ref => {
          elements.current[option.key] = ref;
        },
        className: "adaptive-list-element",
        "test-id": "adaptive-list-element",
        role: isSubNavItem ? 'presentation' : undefined,
        children: Component({
          ...option,
          option,
          selected,
          onSelect,
          isLimited,
          ...componentProps
        })
      }, option.key))
    }), !!inActive.length && !truncatedView && !Array.isArray(selected) && /*#__PURE__*/_jsx(DropdownMenu, {
      options: inActive,
      selectedKey: selected,
      onSelect: onSelect,
      triggerTestId: "adaptive-list-trigger",
      contentTestId: "adaptive-list-dropdown-content",
      triggerDynamicContent: () => /*#__PURE__*/_jsx(FontAwesomeIcon, {
        icon: faEllipsisVertical
      }),
      triggerAriaLabelText: triggerAriaLabelText ?? t('Trigger another item'),
      triggerIsIcon: true,
      triggerHideChevron: true,
      ...dropdownMenuProps
    }), !!inActive.length && truncatedView && truncatedView({
      options: inActive,
      selected,
      onSelect,
      isLimited,
      ...componentProps
    })]
  });
}