import WebApp from '@twa-dev/sdk'

export const shareToTelegram = (url, text) => {
  // 构造分享URL
  const shareUrl = `https://t.me/share/url?url=${encodeURIComponent(url)}&text=${encodeURIComponent(text)}`
  WebApp.openTelegramLink(shareUrl)
}
// 外部链接跳转方法
export const openExternalLink = (url: string) => {
  try {
    // 使用 Telegram WebApp.openLink 打开外部链接
    // try_instant_view: 是否尝试使用 Telegram 的即时预览功能（如果支持的话）
    WebApp.openLink(url, { try_instant_view: true })
  } catch (error) {
    console.error('Failed to open link:', error)
  }
}
// 链接生成器类
export class TelegramLinkBuilder {
  botUsername: string
  baseUrl: string

  constructor(botUsername: string) {
    // 移除可能的 @ 前缀
    this.botUsername = botUsername.replace('@', '')
    this.baseUrl = `https://t.me/${this.botUsername}/myapp`
  }

  // 生成分享链接
  generateShareLink(params) {
    // 如果参数是对象，转换为字符串
    let startParam = params
    if (typeof params === 'object') {
      startParam = btoa(JSON.stringify(params))
    }

    return `${this.baseUrl}?startapp=${encodeURIComponent(startParam)}`
  }

  // 解析分享链接
  parseShareLink(url: string) {
    try {
      const urlObj = new URL(url)
      const startapp = urlObj.searchParams.get('startapp')

      if (!startapp) return null

      try {
        // 尝试解析 base64 编码的 JSON
        const decoded = atob(startapp)
        return JSON.parse(decoded)
      } catch {
        // 如果不是 base64 或 JSON，返回原始字符串
        return startapp
      }
    } catch {
      return null
    }
  }
}
export interface TelegramUser {
  id: number
  first_name: string
  last_name?: string
  username?: string
  language_code?: string
  allows_write_to_pm?: boolean
}

export interface ParsedInitData {
  user: TelegramUser
  chat_instance: string
  chat_type: string
  auth_date: number
  hash: string
}
// 解析tg初始化数据
export const parseInitData = (initDataRaw: string): ParsedInitData => {
  try {
    const decodedData = decodeURIComponent(initDataRaw)
    const params = new URLSearchParams(decodedData)
    const result: Record<string, any> = {}

    params.forEach((value, key) => {
      try {
        result[key] = JSON.parse(value)
      } catch {
        if (key === 'auth_date') {
          result[key] = parseInt(value)
        } else {
          result[key] = value
        }
      }
    })

    return result as ParsedInitData
  } catch (error) {
    console.error('Error parsing initDataRaw:', error)
    throw new Error('Failed to parse initDataRaw')
  }
}
export const getAuthTime = (authDate: number) => {
  // auth_date 只是认证时间，不能用它来判断账号年龄
  // 我们可以根据用户 ID 来判断账号大致时间范围

  const ranges = [
    { max: 100000000, label: '2013-2014', age: '11' },
    { max: 200000000, label: '2014-2015', age: '10' },
    { max: 500000000, label: '2015-2016', age: '9' },
    { max: 1000000000, label: '2016-2017', age: '8' },
    { max: 2000000000, label: '2017-2018', age: '7' },
    { max: 3000000000, label: '2018-2019', age: '6' },
    { max: 4000000000, label: '2019-2020', age: '5' },
    { max: 5000000000, label: '2020-2021', age: '4' },
    { max: 6000000000, label: '2021-2022', age: '3' },
    { max: 7000000000, label: '2022-2023', age: '2' },
    { max: Infinity, label: '2023-2024', age: '1' },
  ]

  const getUserAgeRange = (userId: number) => {
    return ranges.find((range) => userId < range.max) || ranges[ranges.length - 1]
  }

  return {
    determineAge: (userId: number) => {
      const range = getUserAgeRange(userId)
      return {
        period: range.label,
        age: range.age,
        isLongTerm: userId < 7000000000, // 假设账号存在超过1年就算长期账号
        isOG: userId < 500000000, // OG用户判断标准
      }
    },
  }
}
