import ApiConfig from "./api"
export function throttle<T extends (...args: any[]) => any>(
  func: T,
  delay: number
): (...args: Parameters<T>) => void {
  let lastCall = 0
  let timer: ReturnType<typeof setTimeout> | null = null
  return function (this: any, ...args: Parameters<T>) {
    const now = Date.now()
    if (now - lastCall < delay) {
      clearTimeout(timer!)
      timer = setTimeout(() => {
        func.apply(this, args)
        lastCall = now
      }, delay)
    } else {
      func.apply(this, args)
      lastCall = now
    }
  }
}

/**
 * remove px unit and convert to number
 * @param value example: "16px", "16.5px", "-16px", "16", 16
 * @returns example: 16, 16.5, -16, 16, 16
 * @throws Error if value is invalid
 */
export const removePx = (value: string | number): number => {
  // 如果已经是数字，直接返回
  if (typeof value === "number") return value

  // 如果是空字符串，抛出错误
  if (!value) {
    throw new Error("Invalid value: empty string")
  }

  // 移除所有空格
  const trimmed = value.trim()

  // 检查是否以 px 结尾（不区分大小写）
  const hasPx = /px$/i.test(trimmed)

  // 提取数字部分
  const num = hasPx ? trimmed.slice(0, -2) : trimmed

  // 转换为数字
  const result = Number.parseFloat(num)

  // 验证结果是否为有效数字
  if (Number.isNaN(result)) {
    throw new Error(`Invalid value: ${value}`)
  }

  return result
}

export function isMobile() {
  const userAgent = navigator.userAgent
  return /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i.test(
    userAgent
  )
}

export const getParams = () => {
  const params = new URLSearchParams(window.location.search)
  const result: Record<string, string> = {}
  for (const [key, value] of params.entries()) {
    result[key] = value
  }
  return result
}

export const getAuth = () => {
  const { token } = getParams()
  return token || ""
}

export const setWindowHeight = () => {
  const windowHeight = window.innerHeight
  document
    .getElementsByTagName("body")[0]
    .style.setProperty("--height-primary", `${windowHeight}px`)
}

export function getApiUrl() {
  const { apiUrl } = getParams()
  if (apiUrl) {
    return apiUrl
  }
  if (process.env.NODE_ENV === "development") {
    return ApiConfig.test_api
  }
  return ApiConfig.prod_api
}

export const isElectron =
  typeof window !== "undefined" &&
  window.navigator.userAgent.includes("Electron")

export const isApp =
  typeof window !== "undefined" &&
  window.navigator.userAgent.includes("MyAppWebView")
