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

import { useEffect, useRef, useState } from 'react';
import classNames from 'classnames';
import Icon from '../Icon';
import { CLS_PREFIX } from '../../constants';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
const DEFAULT_ICONS = ['clock', 'emoticon-smile', 'rocket', 'sand-clock', 'sleep', 'web', 'star'];
const useIconCursor = (icons, initialCursor, isSync) => {
  const targetRef = useRef(null);
  const [cursor, setCursor] = useState(initialCursor);
  useEffect(() => {
    const target = targetRef.current;
    const listener = () => {
      if (isSync()) {
        setCursor(c => (c + 2) % icons.length);
      }
    };
    if (target) {
      target.addEventListener('animationiteration', listener);
    }
    return () => {
      if (target) {
        target.removeEventListener('animationiteration', listener);
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [icons]);
  return [icons[cursor], targetRef];
};
const IconsLoader = _ref => {
  let {
    baseClassName = `${CLS_PREFIX}icons-loader`,
    className,
    icons,
    size,
    style,
    ...props
  } = _ref;
  const syncRef = useRef('icon1');
  if (!icons?.length) {
    icons = DEFAULT_ICONS;
  } else if (icons.length === 1) {
    icons = [icons[0], icons[0]];
  }
  const [icon1, icon1Ref] = useIconCursor(icons, 0, () => {
    if (syncRef.current === 'icon1') {
      syncRef.current = 'icon2';
      return true;
    }
    return false;
  });
  const [icon2, icon2Ref] = useIconCursor(icons, 1, () => {
    if (syncRef.current === 'icon2') {
      syncRef.current = 'icon1';
      return true;
    }
    return false;
  });
  return /*#__PURE__*/_jsxs("div", {
    className: classNames(baseClassName, className),
    style: {
      ...style,
      ['--icons-loader-size']: size ? size : undefined
    },
    ...props,
    children: [/*#__PURE__*/_jsx("div", {
      className: classNames(`${baseClassName}__icon`, `${baseClassName}__icon--1`),
      ref: icon1Ref,
      children: Icon.create(icon1, {
        size: size ? size : '64'
      })
    }), /*#__PURE__*/_jsx("div", {
      className: classNames(`${baseClassName}__icon`, `${baseClassName}__icon--2`),
      ref: icon2Ref,
      children: Icon.create(icon2, {
        size: size ? size : '64'
      })
    })]
  });
};
export default IconsLoader;