import _extends from "@babel/runtime/helpers/esm/extends";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
var _excluded = ["active", "delay", "fillMode", "onTransitionEnd"];
import * as React from 'react';
import cx from 'classnames';
import useReducedMotion from '../utils/useReducedMotion';
import { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect';
import { createClassNamesRegistry } from './classNamesRegistry';
import { createCSSTransitionAnimator } from './CSSTransitionAnimator'; // This is to satisfy api extractor requirement. See https://github.com/brainly/style-guide/issues/2650

import * as predefinedEffects from './predefinedEffects';
import { getDebugOptions } from './debug';
Transition.createEffect = predefinedEffects.createEffect;

var isFillModeBackwards = function isFillModeBackwards(mode) {
  return mode === 'backwards' || mode === 'both';
};

var isFillModeForwards = function isFillModeForwards(mode) {
  return mode === 'forwards' || mode === 'both';
}; // https://github.com/jsdom/jsdom/issues/1781


var supportsTransitions = function supportsTransitions() {
  return typeof window !== 'undefined' && typeof window.TransitionEvent !== 'undefined';
};

function BaseTransition(_ref) {
  var active = _ref.active,
      effect = _ref.effect,
      _ref$delay = _ref.delay,
      delay = _ref$delay === void 0 ? 0 : _ref$delay,
      _ref$fillMode = _ref.fillMode,
      fillMode = _ref$fillMode === void 0 ? 'none' : _ref$fillMode,
      inline = _ref.inline,
      className = _ref.className,
      children = _ref.children,
      onTransitionStart = _ref.onTransitionStart,
      onTransitionEnd = _ref.onTransitionEnd;
  var containerRef = React.useRef(null);
  var prefersReducedMotion = useReducedMotion();
  var currentEffect = React.useMemo(function () {
    if (typeof effect === 'function') {
      return effect(prefersReducedMotion);
    }

    return effect;
  }, [effect, prefersReducedMotion]);
  var classNamesRegistry = React.useMemo(createClassNamesRegistry, []);
  var animator = React.useMemo(function () {
    return createCSSTransitionAnimator(classNamesRegistry);
  }, [classNamesRegistry]);

  var _getDebugOptions = getDebugOptions(),
      outlines = _getDebugOptions.outlines;

  var baseClassName = cx('sg-transition', className, {
    'sg-transition--inline': inline,
    'sg-transition--outlines': outlines
  });
  useIsomorphicLayoutEffect(function () {
    /**
     * Since the transition imperatively applies the style
     * and className to the container element, other props
     * changes that affect these element attributes should
     * also be imperative. The registry synchronizes them
     * without affecting the animation.
     */
    classNamesRegistry.register('base', baseClassName || '');
    var container = containerRef.current;

    if (container) {
      container.className = classNamesRegistry.toString();
    }
  }, [classNamesRegistry, baseClassName]);
  /**
   * Changing callbacks should not trigger transition.
   */

  var onTransitionStartRef = React.useRef();
  var onTransitionEndRef = React.useRef();
  useIsomorphicLayoutEffect(function () {
    onTransitionStartRef.current = onTransitionStart;
    onTransitionEndRef.current = onTransitionEnd;
    animator.onFinish(function () {
      var container = containerRef.current;

      if (container && !isFillModeForwards(fillMode)) {
        animator.cleanup(container);
      }

      if (onTransitionEnd && currentEffect) {
        onTransitionEnd(currentEffect);
      }
    });
  });
  /**
   * The transition can be triggered by props that have been
   * applied to the actual DOM, and subsequent renders of the
   * virtual DOM should not produce any visual result.
   */

  var previouslyAppliedProps = React.useRef({
    active: false,
    effect: null
  });
  /**
   * The useLayoutEffect because of possible flicking
   * issues while using a regular useEffect hook.
   */

  useIsomorphicLayoutEffect(function () {
    var _getDebugOptions2 = getDebugOptions(),
        speed = _getDebugOptions2.speed;

    var currentProps = {
      active: active,
      effect: currentEffect
    };
    var container = containerRef.current;
    var rules = getTransitionRules({
      previousProps: previouslyAppliedProps.current,
      currentProps: currentProps
    }); // no rules that trigger the transition found

    if (!container || typeof rules === 'undefined') {
      return;
    }

    if (currentEffect === null || rules === null) {
      animator.cleanup(container);
      return;
    }

    if (supportsTransitions() && isFillModeBackwards(fillMode)) {
      animator.apply(container, rules.from);
    }

    var performTransitionEffect = function performTransitionEffect() {
      if (onTransitionStartRef.current) {
        onTransitionStartRef.current(currentEffect);
      }

      if (!supportsTransitions()) {
        if (onTransitionEndRef.current) {
          onTransitionEndRef.current(currentEffect);
        }
      } else {
        animator.animate(container, rules.from, rules.to, speed);
      }
      /**
       * These props should be memoized just
       * after applying them to the actual DOM.
       */


      previouslyAppliedProps.current = currentProps;
    };
    /**
     * The parent Transition component can delay mounting
     * a child BaseTransition component when the active prop
     * changes and the child should not wait again.
     */


    var actualDelay = rules.canSkipDelay && !isFillModeBackwards(fillMode) ? 0 : delay;

    if (actualDelay > 0) {
      var timeoutId = setTimeout(performTransitionEffect, actualDelay / speed);
      return function () {
        return clearTimeout(timeoutId);
      };
    }

    performTransitionEffect();
  }, [animator, active, currentEffect, delay, fillMode]);
  var handleTransitionEnd = React.useCallback(function (event) {
    // ignores bubbling events of its own descendants
    if (event.target === event.currentTarget) {
      animator.propertyTransitionEnd();
    }
  }, [animator]);
  return /*#__PURE__*/React.createElement("div", {
    ref: containerRef,
    onTransitionEnd: supportsTransitions() ? handleTransitionEnd : undefined
  }, children);
}

function Transition(_ref2) {
  var active = _ref2.active,
      _ref2$delay = _ref2.delay,
      delay = _ref2$delay === void 0 ? 0 : _ref2$delay,
      _ref2$fillMode = _ref2.fillMode,
      fillMode = _ref2$fillMode === void 0 ? 'none' : _ref2$fillMode,
      onTransitionEnd = _ref2.onTransitionEnd,
      otherProps = _objectWithoutProperties(_ref2, _excluded);

  var canMountBaseComponent = delay === 0 || isFillModeBackwards(fillMode);

  var _React$useState = React.useState(canMountBaseComponent ? active : false),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      mounted = _React$useState2[0],
      setMounted = _React$useState2[1];

  useIsomorphicLayoutEffect(function () {
    if (active) {
      var mountBaseComponent = function mountBaseComponent() {
        return setMounted(true);
      };

      if (canMountBaseComponent) {
        mountBaseComponent();
      } else {
        var _getDebugOptions3 = getDebugOptions(),
            speed = _getDebugOptions3.speed;

        var timeoutId = setTimeout(mountBaseComponent, delay / speed);
        return function () {
          return clearTimeout(timeoutId);
        };
      }
    }
  }, [active, delay, canMountBaseComponent]);
  var handleTransitionEnd = React.useCallback(function (effect) {
    if (!active) {
      setMounted(false);
    } // proxy the actual event


    if (onTransitionEnd) {
      onTransitionEnd(effect);
    }
  }, [active, onTransitionEnd]);
  return mounted ? /*#__PURE__*/React.createElement(BaseTransition, _extends({}, otherProps, {
    active: active,
    delay: delay,
    fillMode: fillMode,
    onTransitionEnd: handleTransitionEnd
  })) : null;
}

function getTransitionRules(_ref3) {
  var previousProps = _ref3.previousProps,
      currentProps = _ref3.currentProps;

  if (currentProps.effect === null) {
    return null;
  }

  if (previousProps.active === false && currentProps.active === true) {
    return {
      from: currentProps.effect.initial,
      to: currentProps.effect.animate,
      canSkipDelay: true
    };
  }

  if (previousProps.active === true && currentProps.active === false) {
    return {
      from: currentProps.effect.animate,
      to: currentProps.effect.exit,
      canSkipDelay: false
    };
  }

  if (previousProps.effect === null && currentProps.effect !== null) {
    return {
      from: currentProps.effect.initial,
      to: currentProps.effect.animate,
      canSkipDelay: false
    };
  }

  if (previousProps.effect !== currentProps.effect) {
    return {
      from: currentProps.effect.initial,
      to: currentProps.effect.animate,
      canSkipDelay: false
    };
  }
} // Export default when there is an assignement to the static property results in the followig bug:
// https://github.com/storybookjs/storybook/discussions/13935
// Separating function declaration from export statement solves the issue until it's fixed


export default Transition;