import React, { useState, useRef, useEffect, useLayoutEffect } from 'react';
import { flushSync } from 'react-dom';
import classNames from 'classnames';
import { useDebounce } from '../hooks/use-debounce';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
export const ELLIPSIS_PLACE_TYPES = {
  MIDDLE: 'middle',
  END: 'end'
};
const ellipsisPlace = {
  middle: 50,
  end: 100
};
const sizeTolerance = {
  max: 4,
  // 4px,
  tolerance: 0.02 // 2%
};
const getSizeTolerance = value => {
  const currentTolerance = value * sizeTolerance.tolerance;
  return currentTolerance <= sizeTolerance.max ? Math.round(currentTolerance) : sizeTolerance.max;
};
const truncateString = (text, ellipsisString, truncateAt, parent = 0, children = 0) => {
  const textLength = text.length;
  const percentage = ellipsisPlace[truncateAt];
  if (textLength === 0) {
    return '';
  }
  if (children <= parent) {
    return text;
  }
  // Recheck for tolerance
  if (children - getSizeTolerance(children) <= parent) {
    return text;
  }

  // get number of chars that related truncatedAt coefficient which will fit in the container
  const charIndex = size => Math.floor((textLength - ellipsisString.length) * size / children);

  // slice from first char till portioned text. We always need leaving the first char in a small container
  const left = text.slice(0, Math.max(1, charIndex(parent * (percentage / 100))));
  const right = text.slice(textLength - charIndex(parent * ((100 - percentage) / 100)), textLength);
  return `${left}${ellipsisString}${right}`;
};
/**
 * Component that truncates long text in the middle or end.
 * 🚨 NOTE ➡️: max-width & min-width for a parent element is required for proper work. 🚨
 * */
const TruncateString = ({
  text = '',
  ellipsisString = '...',
  truncateAt = ELLIPSIS_PLACE_TYPES.MIDDLE,
  className = null,
  testId = ''
}) => {
  const [truncatedString, setTruncatedString] = useState(null);
  const [isTruncating, setTruncating] = useState(false);
  const parentRef = useRef(null);
  const textRef = useRef(null);
  let timer;
  const handleResize = useDebounce(() => {
    flushSync(() => {
      setTruncating(true);
    });
    const truncated = truncateString(text, ellipsisString, truncateAt, parentRef.current?.offsetWidth, textRef.current?.offsetWidth);
    flushSync(() => {
      setTruncatedString(truncated);
      setTruncating(false);
    });
  }, 100);
  useEffect(() => {
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
      clearTimeout(timer);
    };
  }, [text]);
  useLayoutEffect(() => {
    setTruncating(true);
    // use native timeout because we do not change scope and don't want to trigger digest
    timer = setTimeout(() => {
      const truncated = truncateString(text, ellipsisString, truncateAt, parentRef.current?.offsetWidth, textRef.current?.offsetWidth);
      setTruncatedString(truncated);
      flushSync(() => {
        setTruncatedString(truncated);
        setTruncating(false);
      });
    }, 0);
  }, [text]);
  return /*#__PURE__*/_jsxs("div", {
    ref: parentRef,
    className: classNames('truncate-string', className),
    "test-id": testId,
    children: [isTruncating && /*#__PURE__*/_jsx("span", {
      className: "original-text",
      ref: textRef,
      children: text
    }), !isTruncating && /*#__PURE__*/_jsx("span", {
      ref: textRef,
      children: truncatedString
    })]
  });
};
export default TruncateString;