// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

import { useRef, useState, useEffect, useLayoutEffect } from 'react';
import { Z_INDEX_DROPDOWN, CLS_PREFIX } from '../../constants';
import classNames from 'classnames';
import Popper from '../Popper';
import Menu, { MenuItem, MenuHeader } from '../Menu';
import AutoClosable from '../AutoClosable';
import { safeInvoke, scrollIntoView } from '../utils';
import { jsx as _jsx } from "react/jsx-runtime";
import { createElement as _createElement } from "react";
import { jsxs as _jsxs } from "react/jsx-runtime";
export const findNextSafeIndex = (currIndex, diff, options) => {
  const maxIndex = options.length - 1;
  let attempt = 0;
  for (let i = currIndex + diff; attempt < options.length; i += diff) {
    attempt += 1;
    if (i > maxIndex) {
      i = 0;
    } else if (i < 0) {
      i = maxIndex;
    }
    if (options[i] && options[i].disabled === false) {
      return i;
    }
  }
  return -1;
};
const ComboBoxDropdown = _ref => {
  let {
    baseClassName = `${CLS_PREFIX}combobox-dropdown`,
    className,
    control,
    controlRef,
    opened,
    disabled,
    groups,
    options,
    onHighlightedIndexChange,
    onClose,
    value,
    highlightedIndex,
    onSelect,
    noOptions,
    emitter,
    ...props
  } = _ref;
  const rootRef = useRef(null);
  const menuRef = useRef(null);
  const [minWidth, setMinWidth] = useState(0);
  useLayoutEffect(() => {
    if (opened && rootRef.current) {
      const {
        width
      } = rootRef.current.getBoundingClientRect();
      if (width !== minWidth) {
        setMinWidth(width);
      }
    }
  }, [opened, minWidth]);
  useEffect(() => {
    if (!opened) {
      return undefined;
    }
    const listener = () => {
      safeInvoke(onClose);
    };
    window.addEventListener('resize', listener, {
      once: true
    });
    return () => window.removeEventListener('resize', listener);
  }, [opened, onClose]);
  useEffect(() => {
    if (!emitter) {
      return;
    }
    emitter.on('focus', index => {
      if (menuRef.current) {
        const target = menuRef.current.querySelector(`[data-index="${index}"]`);
        if (target) {
          scrollIntoView(target, {
            behavior: 'instant',
            block: 'nearest',
            boundary: menuRef.current
          });
        }
      }
    });
  }, [emitter]);
  const target = /*#__PURE__*/_jsx(AutoClosable, {
    onClose: () => {
      setTimeout(() => {
        safeInvoke(onClose);
      }, 0);
    },
    ignoreNodes: () => [menuRef.current],
    nodeRef: controlRef,
    children: control
  });
  return /*#__PURE__*/_jsx("div", {
    className: className,
    ...props,
    ref: rootRef,
    children: /*#__PURE__*/_jsx(Popper, {
      target: target,
      targetRef: controlRef,
      show: opened && !disabled,
      className: `${baseClassName}__popper`,
      zIndex: Z_INDEX_DROPDOWN,
      children: /*#__PURE__*/_jsxs(Menu, {
        style: {
          minWidth
        },
        ref: menuRef,
        className: `${baseClassName}__menu`,
        children: [groups.reduce((acc, group) => {
          if (group.label) {
            acc.push( /*#__PURE__*/_createElement(MenuHeader, {
              ...group.props,
              key: `group_${group.label}`
            }, group.label));
          }
          group.options.forEach(option => {
            const optionIndex = options.indexOf(option);
            let onClick;
            let onMouseOver;
            let onMouseDown;
            if (!option.disabled) {
              onClick = e => {
                e.preventDefault();
                safeInvoke(onSelect, option.value);
              };
              onMouseOver = () => {
                // TODO: use throttle
                safeInvoke(onHighlightedIndexChange, optionIndex);
              };
              onMouseDown = e => {
                e.preventDefault();
              };
            }
            const menuItemProps = {
              ...option.props,
              active: value === option.value,
              className: classNames(`${baseClassName}__option`, {
                [`${baseClassName}__option--selected`]: optionIndex === highlightedIndex
              }),
              disabled: option.disabled,
              onClick,
              onMouseOver,
              onMouseDown,
              'data-index': optionIndex
            };
            acc.push( /*#__PURE__*/_jsx(MenuItem, {
              ...menuItemProps,
              children: option.children
            }, `option_${option.value}`));
          });
          return acc;
        }, []), options.length === 0 && noOptions && /*#__PURE__*/_jsx(MenuItem, {
          disabled: true,
          className: `${baseClassName}__no-options`,
          children: noOptions
        })]
      })
    })
  });
};
export default ComboBoxDropdown;