import React from 'react'

function isContentTruncated(element) {
  if (!element) return false
  return (element.scrollHeight - element.clientHeight) > 1 || (element.scrollWidth - element.clientWidth) > 1
}

export default function TruncatedCellContent({
  children,
  tooltipContent = '',
  className = 'table-cell-clamp',
}) {
  const contentRef = React.useRef(null)
  const tooltipText = String(tooltipContent ?? '').trim()

  const syncTooltip = React.useCallback(() => {
    const element = contentRef.current
    if (!element) return
    if (!tooltipText || !isContentTruncated(element)) {
      element.removeAttribute('title')
      return
    }
    element.setAttribute('title', tooltipText)
  }, [tooltipText])

  const clearTooltip = React.useCallback(() => {
    const element = contentRef.current
    if (!element) return
    element.removeAttribute('title')
  }, [])

  React.useEffect(() => {
    const element = contentRef.current
    if (!element) return undefined
    element.removeAttribute('title')
    return () => {
      element.removeAttribute('title')
    }
  }, [tooltipText, children])

  return (
    <div
      ref={contentRef}
      className={className}
      onMouseEnter={syncTooltip}
      onFocus={syncTooltip}
      onMouseLeave={clearTooltip}
      onBlur={clearTooltip}
    >
      {children}
    </div>
  )
}
