'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var React = require('react');

var useTabItem = function useTabItem(_ref) {
  var refs = _ref.refs,
    innerRef = _ref.innerRef,
    itemIndex = _ref.itemIndex,
    selected = _ref.selected,
    orientation = _ref.orientation,
    disabled = _ref.disabled,
    onIndexChange = _ref.onIndexChange,
    onClick = _ref.onClick;
  var hasKeyNavigation = itemIndex !== undefined && onIndexChange !== undefined;
  var navigationTabIndex = !disabled && (refs === null || refs === void 0 ? void 0 : refs.current) === itemIndex ? 0 : -1;
  var onItemFocus = React.useCallback(function (event) {
    if (disabled) {
      return;
    }
    if (!hasKeyNavigation && innerRef !== null && innerRef !== void 0 && innerRef.current) {
      if (orientation === ' vertical') {
        innerRef.current.scrollTo({
          top: innerRef.current.offsetTop,
          behavior: 'smooth'
        });
        return;
      }
      innerRef.current.scrollTo({
        top: 0,
        left: innerRef.current.offsetLeft,
        behavior: 'smooth'
      });
      return;
    }
    if (!refs) {
      return;
    }
    var focusIndex = refs.items.findIndex(function (itemRef) {
      return itemRef.current === event.target;
    });
    if (focusIndex === refs.current) {
      return;
    }
    onIndexChange === null || onIndexChange === void 0 || onIndexChange(focusIndex);
    refs.setCurrent(focusIndex);
  }, [refs, innerRef, onIndexChange, disabled]);
  var handleClick = function handleClick(event) {
    if (!onClick) {
      return;
    }
    onClick(event);
  };
  React.useEffect(function () {
    if (!refs) {
      return;
    }
    refs.register(innerRef);
    return function () {
      return refs.unregister(innerRef);
    };
  }, [refs]);
  React.useLayoutEffect(function () {
    var _innerRef$current$par;
    if (!selected || !innerRef.current) {
      return;
    }
    var scrollEl = (_innerRef$current$par = innerRef.current.parentElement) === null || _innerRef$current$par === void 0 ? void 0 : _innerRef$current$par.parentElement;
    if (!scrollEl) {
      return;
    }
    var scrollElStyle = getComputedStyle(scrollEl);
    if (orientation === ' vertical') {
      scrollEl.scrollTo({
        top: innerRef.current.offsetTop - parseInt(scrollElStyle.paddingTop, 10)
      });
      return;
    }
    scrollEl.scrollTo({
      left: innerRef.current.offsetLeft - parseInt(scrollElStyle.paddingLeft, 10)
    });
  }, [selected, orientation]);
  return {
    hasKeyNavigation: hasKeyNavigation,
    navigationTabIndex: navigationTabIndex,
    onItemFocus: onItemFocus,
    handleClick: handleClick
  };
};

exports.useTabItem = useTabItem;
