import React, { memo, useRef, useCallback, useEffect } from 'react';
import { classNames } from '../../../../utilities/css.js';
import { useComponentDidMount } from '../../../../utilities/use-component-did-mount.js';
import styles from '../../Tabs.scss.js';
import { Tab } from '../Tab/Tab.js';
import { EventListener } from '../../../EventListener/EventListener.js';

const TabMeasurer = /*#__PURE__*/memo(function TabMeasurer({
  selected,
  tabs,
  activator,
  tabToFocus,
  siblingTabHasFocus,
  handleMeasurement: handleMeasurementProp
}) {
  const containerNode = useRef(null);
  const animationFrame = useRef(null);
  const handleMeasurement = useCallback(() => {
    if (animationFrame.current) {
      cancelAnimationFrame(animationFrame.current);
    }

    animationFrame.current = requestAnimationFrame(() => {
      if (!containerNode.current) {
        return;
      }

      const containerWidth = containerNode.current.offsetWidth;
      const hiddenTabNodes = containerNode.current.children;
      const hiddenTabNodesArray = Array.from(hiddenTabNodes);
      const hiddenTabWidths = hiddenTabNodesArray.map(node => {
        return Math.ceil(node.getBoundingClientRect().width);
      });
      const disclosureWidth = hiddenTabWidths.pop() || 0;
      handleMeasurementProp({
        containerWidth,
        disclosureWidth,
        hiddenTabWidths
      });
    });
  }, [handleMeasurementProp]);
  useEffect(() => {
    handleMeasurement();
  }, [handleMeasurement, tabs]);
  useComponentDidMount(() => {
    if (process.env.NODE_ENV === 'development') {
      setTimeout(handleMeasurement, 0);
    }
  });
  const tabsMarkup = tabs.map((tab, index) => {
    return /*#__PURE__*/React.createElement(Tab, {
      measuring: true,
      key: `${index}${tab.id}Hidden`,
      id: `${tab.id}Measurer`,
      siblingTabHasFocus: siblingTabHasFocus,
      focused: index === tabToFocus,
      selected: index === selected,
      onClick: noop,
      url: tab.url
    }, tab.content);
  });
  const classname = classNames(styles.Tabs, styles.TabMeasurer);
  return /*#__PURE__*/React.createElement("div", {
    className: classname,
    ref: containerNode
  }, /*#__PURE__*/React.createElement(EventListener, {
    event: "resize",
    handler: handleMeasurement
  }), tabsMarkup, activator);
});

function noop() {}

export { TabMeasurer };
