import React, { useCallback, useRef, useState } from 'react';

type Props = {
  text: string;
  className?: string;
};

/** Однострочный текст с ellipsis; полный title при обрезке. */
export function EllipsisText({ text, className }: Props) {
  const ref = useRef<HTMLDivElement | null>(null);
  const [title, setTitle] = useState<string | undefined>(undefined);

  const syncTitle = useCallback(() => {
    const el = ref.current;
    if (!el) {
      setTitle(undefined);
      return;
    }
    setTitle(el.scrollWidth > el.clientWidth + 1 ? text : undefined);
  }, [text]);

  return (
    <div
      ref={ref}
      className={className}
      title={title}
      onMouseEnter={syncTitle}
      onMouseLeave={() => setTitle(undefined)}
    >
      {text}
    </div>
  );
}
