import { ref, computed, onMounted, onUnmounted, unref } from 'vue'

/** 与全局响应式断点一致：≤768px 视为移动端 */
export const TABLE_MOBILE_BREAKPOINT = 768

/** 移除列配置中的 fixed，用于移动端 */
export function stripTableFixed(columns) {
  if (!Array.isArray(columns)) return columns
  return columns.map((col) => {
    if (!col?.fixed) return col
    const { fixed, ...rest } = col
    return rest
  })
}

/**
 * 表格响应式：桌面端保留固定列，移动端取消固定列
 */
export function useResponsiveTable(breakpoint = TABLE_MOBILE_BREAKPOINT) {
  const isMobile = ref(false)
  let resizeHandler = null

  const syncMobile = () => {
    isMobile.value = window.innerWidth <= breakpoint
  }

  onMounted(() => {
    resizeHandler = syncMobile
    syncMobile()
    window.addEventListener('resize', resizeHandler)
  })

  onUnmounted(() => {
    if (resizeHandler) {
      window.removeEventListener('resize', resizeHandler)
    }
  })

  /** 供 a-table-column 的 :fixed 绑定 */
  const tableFixed = (side = 'right') => (isMobile.value ? undefined : side)

  /** 供 :columns 绑定，根据 isMobile 自动去掉 fixed */
  const useTableColumns = (columnsSource) =>
    computed(() => {
      const cols =
        typeof columnsSource === 'function' ? columnsSource() : unref(columnsSource)
      return isMobile.value ? stripTableFixed(cols) : cols
    })

  return { isMobile, tableFixed, useTableColumns, stripTableFixed }
}
