/**
 * Wraps a text or element in a div, which shows a tooltip when the text is truncated
 * due to not enough horizontal space. Thanks to LavaSquid#9980 for this.
 * @component
 */

import React, { memo, useRef } from 'react';
import { joinClassNames } from '@vizality/util/dom';

import { AsyncComponent } from '.';

const Tooltip = AsyncComponent.fromDisplayName('Tooltip');

export default memo(props => {
  const overflowDiv = useRef(null);
  return (
    <Tooltip {...props}>
      {propz => {
        const ogMouseEnter = propz.onMouseEnter;
        propz.onMouseEnter = () => {
          const ref = overflowDiv.current;
          ref?.scrollWidth > ref?.offsetWidth && ogMouseEnter?.();
        };
        return (
          <div ref={overflowDiv} className={joinClassNames('vz-overflow-tooltip', props.className)} {...propz}>
            {props.children}
          </div>
        );
      }}
    </Tooltip>
  );
});
