import _extends from "@babel/runtime/helpers/extends";
// Copyright 1999-2020. Plesk International GmbH. All rights reserved.
import React, { useEffect, useRef, useState } from 'react';
import classNames from 'classnames';
import Icon from '../Icon';
import { CLS_PREFIX } from '../../constants';
const DEFAULT_ICONS = ['clock', 'emoticon-smile', 'rocket', 'sand-clock', 'sleep', 'web', 'star'];

const useIcon = (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 {
    name: icons[cursor],
    targetRef
  };
};

const IconsLoader = ({
  baseClassName = `${CLS_PREFIX}icons-loader`,
  className,
  icons,
  ...props
}) => {
  const syncRef = useRef(0);
  icons = icons && icons.length > 0 ? icons : DEFAULT_ICONS;
  const icon1 = useIcon(icons, 0, () => {
    if (syncRef.current === 0) {
      syncRef.current += 1;
      return true;
    }

    return false;
  });
  const icon2 = useIcon(icons, 1, () => {
    if (syncRef.current === 1) {
      syncRef.current -= 1;
      return true;
    }

    return false;
  });
  return /*#__PURE__*/React.createElement("div", _extends({
    className: classNames(baseClassName, className)
  }, props), /*#__PURE__*/React.createElement("div", {
    className: classNames(`${baseClassName}__icon`, `${baseClassName}__icon--1`),
    ref: icon1.targetRef
  }, /*#__PURE__*/React.createElement(Icon, {
    name: icon1.name,
    size: "64"
  })), /*#__PURE__*/React.createElement("div", {
    className: classNames(`${baseClassName}__icon`, `${baseClassName}__icon--2`),
    ref: icon2.targetRef
  }, /*#__PURE__*/React.createElement(Icon, {
    name: icon2.name,
    size: "64"
  })));
};

export default IconsLoader;