import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

/* eslint-disable no-console */
import * as React from 'react';

function useAnimation(config) {
  var refs = React.useRef(new Set());
  var parameters = React.useRef(new WeakMap());
  var entryAnimations = React.useRef(new WeakMap());
  var exitAnimations = React.useRef(new WeakMap());
  var isAnimationSupported = React.useRef(true);

  var _React$useState = React.useState('initial'),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      phase = _React$useState2[0],
      setPhase = _React$useState2[1];

  var configRef = React.useRef(config); // We only need the most updated value. Equivalent of using useEffectEvent.

  React.useEffect(function () {
    configRef.current = config;
  }, [config]);
  var register = React.useCallback(function () {
    var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
      index: refs.current.size
    };
    return {
      ref: function ref(el) {
        if (el) {
          parameters.current.set(el, options);
          refs.current.add(el);
        }
      }
    };
  }, []);
  React.useEffect(function () {
    var elements = refs.current; // Check if animation is supported on dom elements in the browser.

    isAnimationSupported.current = Object.hasOwnProperty.call(Element.prototype, 'animate');
    return function () {
      if (isAnimationSupported.current) {
        // Remove all outstanding animations and cleanup refs
        var allSnapshot = _toConsumableArray(elements).flatMap(function (ref) {
          return ref.getAnimations();
        });

        allSnapshot.forEach(function (animation) {
          return animation.cancel();
        });
      }

      elements.clear();
    };
  }, []);
  React.useEffect(function () {
    if (!isAnimationSupported.current) {
      console.warn('Web Animation API is not supported on this browser');
      return;
    } // In debug mode, we override the phase with the one provided.


    if (useAnimation.debug.phase !== null) {
      setPhase(useAnimation.debug.phase);
    }

    switch (phase) {
      case 'entry':
        {
          refs.current.forEach(function (ref) {
            var _entryAnimations$curr, _configRef$current$en;

            var _parameters$current$g = parameters.current.get(ref),
                index = _parameters$current$g.index,
                _parameters$current$g2 = _parameters$current$g.overrides,
                overrides = _parameters$current$g2 === void 0 ? {} : _parameters$current$g2;

            var entry = (_entryAnimations$curr = entryAnimations.current.get(ref)) !== null && _entryAnimations$curr !== void 0 ? _entryAnimations$curr : [];
            ref.getAnimations().forEach(function (animation) {
              return animation.cancel();
            });
            (_configRef$current$en = configRef.current.entry) === null || _configRef$current$en === void 0 ? void 0 : _configRef$current$en.forEach(function (keyframesConfig, i) {
              var id = keyframesConfig.id;
              var keyframes = keyframesConfig.keyframes,
                  _keyframesConfig$opti = keyframesConfig.options,
                  options = _keyframesConfig$opti === void 0 ? {} : _keyframesConfig$opti;
              var override = overrides[id];

              if (override) {
                keyframes = (override === null || override === void 0 ? void 0 : override.keyframes) || keyframes;
                options = _objectSpread(_objectSpread({}, options), override === null || override === void 0 ? void 0 : override.options);
              }

              var animationOptions = _objectSpread(_objectSpread({}, options), {}, {
                delay: typeof options.delay === 'function' ? options.delay(index) : options.delay,
                duration: typeof options.duration === 'function' ? options.duration(index) : options.duration
              });

              var anim = ref.animate(keyframes, animationOptions);
              anim.id = "entry ".concat(i);
              entry.push(anim);
            });
            entryAnimations.current.set(ref, entry);
          });
          break;
        }

      case 'exit':
        {
          refs.current.forEach(function (ref) {
            var _exitAnimations$curre, _configRef$current$ex;

            var _parameters$current$g3 = parameters.current.get(ref),
                index = _parameters$current$g3.index,
                _parameters$current$g4 = _parameters$current$g3.overrides,
                overrides = _parameters$current$g4 === void 0 ? {} : _parameters$current$g4;

            var exit = (_exitAnimations$curre = exitAnimations.current.get(ref)) !== null && _exitAnimations$curre !== void 0 ? _exitAnimations$curre : [];
            (_configRef$current$ex = configRef.current.exit) === null || _configRef$current$ex === void 0 ? void 0 : _configRef$current$ex.forEach(function (keyframesConfig, i) {
              var id = keyframesConfig.id;
              var keyframes = keyframesConfig.keyframes,
                  _keyframesConfig$opti2 = keyframesConfig.options,
                  options = _keyframesConfig$opti2 === void 0 ? {} : _keyframesConfig$opti2;
              var override = overrides[id];

              if (override) {
                keyframes = (override === null || override === void 0 ? void 0 : override.keyframes) || keyframes;
                options = _objectSpread(_objectSpread({}, options), override === null || override === void 0 ? void 0 : override.options);
              }

              var animationOptions = _objectSpread(_objectSpread({}, options), {}, {
                delay: typeof options.delay === 'function' ? options.delay(index) : options.delay,
                duration: typeof options.duration === 'function' ? options.duration(index) : options.duration
              });

              var anim = ref.animate(keyframes, animationOptions);
              anim.id = "exit ".concat(i);
              exit.push(anim);
            });
            exitAnimations.current.set(ref, exit);
          }); // Snapshot all animations  from the whole run that need to be removed.

          var allSnapshot = _toConsumableArray(refs.current).flatMap(function (ref) {
            return ref.getAnimations();
          }); // Detect when all exit animations on all registered elements finish


          var exitSnapshot = _toConsumableArray(refs.current).flatMap(function (ref) {
            return exitAnimations.current.get(ref);
          });

          Promise.allSettled(exitSnapshot.map(function (animation) {
            return animation.finished;
          })).then(function () {
            allSnapshot.forEach(function (animation) {
              return animation.cancel();
            });
            refs.current.forEach(function (ref) {
              entryAnimations.current.set(ref, []);
              exitAnimations.current.set(ref, []);
            });
            setPhase(function (phase) {
              return phase === 'exit' ? 'finished' : phase;
            });
          });
          break;
        }

      default:
        break;
    } // In debug mode, we need to manually pause all animations at the desired time.


    if (useAnimation.debug.phase !== null) {
      var _allSnapshot = _toConsumableArray(refs.current).flatMap(function (ref) {
        return ref.getAnimations();
      });

      _allSnapshot.forEach(function (animation) {
        animation.currentTime = useAnimation.debug.time;
        animation.pause();
      });
    }

    console.log('phase', phase);
  }, [phase]);
  return {
    register: register,
    phase: phase,
    setPhase: setPhase
  };
}

var debug = {
  phase: null,
  time: 0
};
useAnimation.debug = debug;
export { useAnimation };