export interface ResizeOptions {
  /** 拖拽方向，默认垂直 */
  direction?: 'horizontal' | 'vertical'
  /** 最小百分比，默认 20 */
  minPercent?: number
  /** 最大百分比，默认 80 */
  maxPercent?: number
  /** 最小像素值，默认 150 */
  minPixels?: number
  /** 输出模式：percent（默认）或 pixels。pixels 模式下 onResize/onResizeEnd 接收像素值而非百分比 */
  outputMode?: 'percent' | 'pixels'
  /** 拖拽中回调（值类型由 outputMode 决定） */
  onResize?: (value: number) => void
  /** 拖拽结束回调（用于持久化等） */
  onResizeEnd?: (value: number) => void
}

/**
 * 通用分割拖拽处理器工厂
 *
 * 用法：
 * ```ts
 * const handleResize = createResizeHandler(
 *   () => containerRef.value,   // getter，mousedown 时才读取
 *   () => percent.value,
 *   { direction: 'horizontal', onResize: (p) => { percent.value = p } }
 * )
 * // template: <div class="resizer" @mousedown="handleResize"></div>
 * ```
 */
export function createResizeHandler(
  getContainer: () => HTMLElement | null,
  getInitialPercentage: () => number,
  options: ResizeOptions = {}
): (e: MouseEvent) => void {
  const {
    direction = 'vertical',
    minPercent = 20,
    maxPercent = 80,
    minPixels = 150,
    outputMode = 'percent',
    onResize,
    onResizeEnd,
  } = options

  const isHorizontal = direction === 'horizontal'
  const usePixels = outputMode === 'pixels'

  return (e: MouseEvent) => {
    e.preventDefault()

    const container = getContainer()
    if (!container) return

    // 初始值：pixels 模式下从 getter 获取像素值，percent 模式下获取百分比
    let startValue = getInitialPercentage()
    if (usePixels) {
      // pixels 模式：将初始像素值转换为百分比用于拖拽计算
      const rect = container.getBoundingClientRect()
      const containerSize = isHorizontal ? rect.width : rect.height
      if (containerSize > 0) {
        startValue = (startValue / containerSize) * 100
      }
    }

    const handleMouseMove = (moveEvent: MouseEvent) => {
      const currentRect = container.getBoundingClientRect()
      let rawValue: number

      if (isHorizontal) {
        rawValue = ((moveEvent.clientX - currentRect.left) / currentRect.width) * 100
      } else {
        rawValue = ((moveEvent.clientY - currentRect.top) / currentRect.height) * 100
      }

      const minPercentFromPixels = (minPixels / (isHorizontal ? currentRect.width : currentRect.height)) * 100
      const clamped = Math.max(
        Math.max(minPercent, minPercentFromPixels),
        Math.min(maxPercent, rawValue)
      )

      if (usePixels) {
        // 转回像素值传给回调
        const containerSize = isHorizontal ? currentRect.width : currentRect.height
        onResize?.(Math.round((clamped / 100) * containerSize))
      } else {
        onResize?.(clamped)
      }
    }

    const handleMouseUp = () => {
      document.removeEventListener('mousemove', handleMouseMove)
      document.removeEventListener('mouseup', handleMouseUp)
      document.body.classList.remove('resizing')
      if (usePixels) {
        // pixels 模式：传回当前像素值（onResize 已更新，读 getter 获取最新值）
        onResizeEnd?.(getInitialPercentage())
      } else {
        onResizeEnd?.(getInitialPercentage())
      }
    }

    document.addEventListener('mousemove', handleMouseMove)
    document.addEventListener('mouseup', handleMouseUp)
    document.body.classList.add('resizing')
  }
}
