/* eslint-disable no-param-reassign */
import { useState, useEffect } from 'react';
import { inBrowser } from '../utils';
import { getTargetElement } from '../utils/dom/getTargetElement';
var overflowScrollReg = /scroll|auto/i;
var defaultRoot = inBrowser ? window : undefined;

function isElement(node) {
  var ELEMENT_NODE_TYPE = 1;
  return node.tagName !== 'HTML' && node.tagName !== 'BODY' && node.nodeType === ELEMENT_NODE_TYPE;
}

export function getScrollParent(el, root) {
  if (root === void 0) {
    root = defaultRoot;
  }

  if (root === undefined) {
    root = window;
  }

  var node = el;

  while (node && node !== root && isElement(node)) {
    var _window$getComputedSt = window.getComputedStyle(node),
        overflowY = _window$getComputedSt.overflowY;

    if (overflowScrollReg.test(overflowY)) {
      if (node.tagName !== 'BODY') {
        return node;
      }

      var htmlOverflowY = window.getComputedStyle(node.parentNode).overflowY;

      if (overflowScrollReg.test(htmlOverflowY)) {
        return node;
      }
    }

    node = node.parentNode;
  }

  return root;
}

function useScrollParent(el) {
  var _useState = useState(),
      scrollParent = _useState[0],
      setScrollParent = _useState[1];

  useEffect(function () {
    if (el) {
      var element = getTargetElement(el);
      setScrollParent(getScrollParent(element));
    }
  }, []);
  return scrollParent;
}

export default useScrollParent;