import { createContext, type JSX, useContext } from 'react'

import { splitFilenameForTruncation } from 'shared-utils/fileupload'

export interface IMiddleTruncate {
  children: string
  /** Trailing chars to preserve when the name is long enough to split. */
  tail?: number
}

type TTruncateContext = { tail: number | undefined }
export const TruncateContext = createContext<TTruncateContext>({ tail: 5 })

/**
 * Middle-truncate a filename. Renders as a React fragment — the parent element
 * (typically a `<p className="…__title">`) is the grid container that drives
 * the layout via CSS in `_fileupload.scss`. The split threshold is shared with
 * the Lit implementation through `splitFilenameForTruncation`.
 *
 * For short filenames the tail span is omitted and the text renders unwrapped.
 */
export const Truncate = ({ children, tail: tailProp }: IMiddleTruncate): JSX.Element => {
  const context = useContext(TruncateContext)
  const tail = tailProp !== undefined ? tailProp : context.tail
  const split = splitFilenameForTruncation(children, tail)

  if (!split) {
    return <span data-pkt-truncate-part="first">{children}</span>
  }

  return (
    <>
      <span className="pkt-fileupload__queue-display__item__title__head" data-pkt-truncate-part="first">
        {split.head}
      </span>
      <span className="pkt-fileupload__queue-display__item__title__tail" data-pkt-truncate-part="tail">
        {split.tail}
      </span>
    </>
  )
}
