import { onBeforeMount, ref, shallowRef, watch } from 'vue';
import '../interface';
import raf from '../../../_util/raf';
import { toPx } from '../../../_util/util';
export const useIndicator = (props, activeTabOffset, horizontal) => {
  const inkStyle = ref();
  const inkBarRafRef = shallowRef();
  const cleanInkBarRaf = () => {
    raf.cancel(inkBarRafRef.value);
  };
  const getLength = (origin, indicator) => {
    if (typeof indicator.size === 'function') {
      return indicator.size(origin);
    }
    if (typeof indicator.size === 'number') {
      return indicator.size;
    }
    return origin;
  };
  watch([activeTabOffset, horizontal, () => props.rtl, () => props.indicator], () => {
    const newInkStyle = {};
    const {
      indicator,
      rtl
    } = props;
    const align = (indicator === null || indicator === void 0 ? void 0 : indicator.align) || 'center';
    const _activeTabOffset = activeTabOffset.value;
    if (_activeTabOffset) {
      if (horizontal.value) {
        newInkStyle.width = toPx(getLength(_activeTabOffset.width, indicator || {}));
        const key = rtl ? 'right' : 'left';
        if (align === 'start') {
          newInkStyle[key] = toPx(_activeTabOffset[key]);
        } else if (align === 'center') {
          newInkStyle[key] = toPx(_activeTabOffset[key] + _activeTabOffset.width / 2);
          newInkStyle.transform = rtl ? 'translateX(50%)' : 'translateX(-50%)';
        } else {
          newInkStyle[key] = toPx(_activeTabOffset[key] + _activeTabOffset.width);
          newInkStyle.transform = 'translateX(-100%)';
        }
      } else {
        newInkStyle.height = toPx(getLength(_activeTabOffset.height, indicator || {}));
        if (align === 'start') {
          newInkStyle.top = toPx(_activeTabOffset.top);
        } else if (align === 'center') {
          newInkStyle.top = toPx(_activeTabOffset.top + _activeTabOffset.height / 2);
          newInkStyle.transform = 'translateY(-50%)';
        } else {
          newInkStyle.top = toPx(_activeTabOffset.top + _activeTabOffset.height);
          newInkStyle.transform = 'translateY(-100%)';
        }
      }
    }
    cleanInkBarRaf();
    inkBarRafRef.value = raf(() => {
      // Avoid jitter caused by tiny numerical differences
      // fix https://github.com/ant-design/ant-design/issues/53378
      const isEqual = inkStyle.value && newInkStyle && Object.keys(newInkStyle).every(key => {
        const newValue = newInkStyle[key];
        const oldValue = inkStyle[key];
        return typeof newValue === 'number' && typeof oldValue === 'number' ? Math.round(newValue) === Math.round(oldValue) : newValue === oldValue;
      });
      if (!isEqual) {
        inkStyle.value = newInkStyle;
      }
    });
  });
  onBeforeMount(() => {
    cleanInkBarRaf();
  });
  return {
    style: inkStyle
  };
};