import React, { memo, useRef, useCallback, useEffect } from 'react';
import { classNames } from '../../../../utilities/css.js';
import { useComponentDidMount } from '../../../../utilities/use-component-did-mount.js';
import { useEventListener } from '../../../../utilities/use-event-listener.js';
import styles from '../../AlphaTabs.scss.js';
import { Tab } from '../Tab/Tab.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 - 20 - 28;
      const hiddenTabNodes = containerNode.current.children;
      const hiddenTabNodesArray = Array.from(hiddenTabNodes);
      const hiddenTabWidths = hiddenTabNodesArray.map(node => {
        const buttonWidth = Math.ceil(node.getBoundingClientRect().width);
        return buttonWidth + 4;
      });
      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: `$${tab.id}Hidden`,
      id: `${tab.id}Measurer`,
      siblingTabHasFocus: siblingTabHasFocus,
      focused: index === tabToFocus,
      selected: index === selected,
      url: tab.url,
      content: tab.content,
      onTogglePopover: noop,
      onToggleModal: noop
    });
  });
  const classname = classNames(styles.AlphaTabs, styles.TabsMeasurer);
  useEventListener('resize', handleMeasurement);
  return /*#__PURE__*/React.createElement("div", {
    className: classname,
    ref: containerNode
  }, tabsMarkup, activator);
});

function noop() {}

export { TabMeasurer };
