import React, { useEffect, useRef } from 'react';
import raf from '../components/rc-util/delayRaf';
import { getPrefixClassName } from '../config-provider/context';
var styleTag;
var animationAttr = "".concat(getPrefixClassName(''), "-ripple-animation");

var Ripple = function Ripple(props) {
  var children = props.children;
  var cnode = null;
  var curNode;
  var newChild = /*#__PURE__*/React.cloneElement(children, {
    className: children.props.className,
    ref: function ref(node) {
      cnode = node;
    }
  });
  var rippleAnimation = useRef({
    isStart: false,
    animationId: null,
    timeoutId: null,
    onAnimationStart: function onAnimationStart(e) {
      if (!e || rippleAnimation.current.isStart) {
        return;
      }

      resetEffect(e.target);
    },
    onAnimationEnd: function onAnimationEnd(e) {
      if (!e || e.animationName !== 'fadeEffect') {
        return;
      }

      resetEffect(e.target);
    }
  });

  var resetEffect = function resetEffect(node) {
    node.setAttribute(animationAttr, 'false');
    node.removeEventListener('animationstart', rippleAnimation.current.onAnimationStart);
    node.removeEventListener('animationend', rippleAnimation.current.onAnimationEnd);
  };

  var createStyle = function createStyle(node) {
    var rippleColor = getComputedStyle(node).getPropertyValue('border-top-color') || getComputedStyle(node).getPropertyValue('border-color') || getComputedStyle(node).getPropertyValue('background-color');
    styleTag = styleTag || document.createElement('style');
    styleTag.innerHTML = "\n      [".concat(animationAttr, "='true']::after {\n        --klein-ripple-shadow-color: ").concat(rippleColor, ";\n      }\n    ");

    if (!document.body.contains(styleTag)) {
      document.body.appendChild(styleTag);
    }
  };

  var init = function init(node) {
    node.addEventListener('click', function () {
      resetEffect(node);
      rippleAnimation.current.timeoutId = window.setTimeout(function () {
        node.setAttribute(animationAttr, 'true');
        createStyle(node);
        node.addEventListener('animationstart', rippleAnimation.current.onAnimationStart);
        node.addEventListener('animationend', rippleAnimation.current.onAnimationEnd);
      }, 0);
      raf.cancel(rippleAnimation.current.animationId);
      rippleAnimation.current.isStart = true;
      rippleAnimation.current.animationId = raf(function () {
        rippleAnimation.current.isStart = false;
      }, 10);
    }, true);
  };

  var clearEffect = function clearEffect() {
    resetEffect(curNode);
    clearTimeout(rippleAnimation.current.timeoutId);

    if (styleTag) {
      styleTag.innerHTML = '';
    }
  };

  useEffect(function () {
    if (!cnode) return;
    init(cnode);
    curNode = cnode;
    return clearEffect;
  }, []);
  return /*#__PURE__*/React.createElement(React.Fragment, null, newChild);
};

export default Ripple;