import { textCellWidth } from '@simon_he/vue-tui'
import type { LineSegment } from './types'
import { truncateByCells } from './render-utils'

export function truncateWithEllipsis(text: string, maxCells: number): string {
  const limit = Math.max(0, Math.floor(maxCells))
  if (limit <= 0) return ''
  const truncated = truncateByCells(text, limit)
  if (!truncated.truncated) return truncated.text
  if (limit <= 1) return '…'
  return `${truncateByCells(text, limit - 1).text}…`
}

export function padToCells(text: string, targetCells: number): string {
  const w = textCellWidth(text)
  if (w >= targetCells) return text
  return `${text}${' '.repeat(targetCells - w)}`
}

export function clampUtf16Boundary(text: string, index: number): number {
  const next = Math.max(0, Math.min(text.length, Math.floor(index)))
  if (next <= 0 || next >= text.length) return next
  const prevCode = text.charCodeAt(next - 1)
  const nextCode = text.charCodeAt(next)
  const prevIsHigh = prevCode >= 0xD800 && prevCode <= 0xDBFF
  const nextIsLow = nextCode >= 0xDC00 && nextCode <= 0xDFFF
  if (prevIsHigh && nextIsLow) return next - 1
  return next
}

export function clipSegmentsToMaxX(segs: LineSegment[], maxX: number): LineSegment[] {
  if (!segs.length) return segs
  const out: LineSegment[] = []
  for (const seg of segs) {
    if (seg.x >= maxX) continue
    const allowed = Math.max(0, maxX - seg.x)
    const w = Math.min(seg.w, allowed)
    if (w <= 0) continue
    if (seg.w <= allowed) {
      out.push(seg)
      continue
    }
    const clipped = truncateByCells(seg.text, w).text
    const clippedW = textCellWidth(clipped)
    if (clippedW <= 0) continue
    out.push({ ...seg, w: clippedW, text: clipped })
  }
  return out
}
