import { t } from '@/locale'
import { toast } from '@/utils/toast'

// 分享数据接口
export interface ShareData {
  url: string
  text: string
  title?: string
}

// 获取 plus runtime
export function getPlusRuntime() {
  const p = (globalThis as any)?.plus
  return p?.runtime
}

// 检测 H5 是否支持原生分享
export function isH5ShareSupported() {
  return typeof navigator !== 'undefined' && typeof (navigator as any).share === 'function'
}

// 检查 APP 是否安装
export function checkAppInstalled(platform: string): boolean {
  const runtime = getPlusRuntime()
  if (!runtime)
    return false

  const appSchemes = {
    facebook: { pname: 'com.facebook.katana', scheme: 'fb://' },
    whatsapp: { pname: 'com.whatsapp', scheme: 'whatsapp://' },
    instagram: { pname: 'com.instagram.android', scheme: 'instagram://' },
    twitter: { pname: 'com.twitter.android', scheme: 'twitter://' },
  }

  const appInfo = appSchemes[platform]
  if (!appInfo)
    return false

  return runtime.isApplicationExist({
    pname: appInfo.pname,
    action: appInfo.scheme,
  })
}

// H5 模式下打开社交平台分享页面
export function openH5ShareTarget(platform: string, shareData: ShareData) {
  const { url, text } = shareData

  const targets: Record<string, string> = {
    facebook: `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}`,
    whatsapp: `https://wa.me/?text=${encodeURIComponent(text)}`,
    twitter: `https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}`,
    instagram: 'https://www.instagram.com/',
  }

  const targetUrl = targets[platform]
  if (!targetUrl)
    return

  if (typeof window !== 'undefined' && typeof window.open === 'function')
    window.open(targetUrl, '_blank')
}

// APP 模式下打开社交 APP
export function openSocialApp(platform: string, shareData: ShareData) {
  const { url, text } = shareData
  const runtime = getPlusRuntime()

  if (!runtime) {
    openH5ShareTarget(platform, shareData)
    return
  }

  // 先复制分享内容到剪贴板
  uni.setClipboardData({
    data: text,
    success: () => {
      console.log('分享内容已复制到剪贴板')
    },
  })

  const shareUrls = {
    facebook: `fb://facewebmodal/f?href=${encodeURIComponent(url)}`,
    whatsapp: `whatsapp://send?text=${encodeURIComponent(text)}`,
    instagram: 'instagram://camera',
    twitter: `twitter://post?message=${encodeURIComponent(text)}`,
  }

  const shareUrl = shareUrls[platform]
  if (shareUrl) {
    runtime.openURL(shareUrl, (error: any) => {
      console.error('打开APP失败:', error)
      toast.info(t('share.appNotInstalled'))
    })
  }
}

// 统一分享处理方法（H5 直接跳转，APP 检查安装后跳转）
export function handleSocialShare(platform: string, shareData: ShareData) {
  // H5 模式下直接跳转到对应平台网页
  if (!getPlusRuntime()) {
    openH5ShareTarget(platform, shareData)
    return
  }

  // APP 模式：检查 APP 是否安装
  if (!checkAppInstalled(platform)) {
    toast.info(t('share.appNotInstalled'))
    return
  }

  // 打开对应的社交媒体 APP
  openSocialApp(platform, shareData)
}

// H5 模式下打开 WhatsApp
export function openH5WhatsApp(type: 'live_chat' | 'activity_group', value: string = '') {
  const phone = (value || '').replace(/\s+/g, '')
  const url = type === 'activity_group'
    ? `https://chat.whatsapp.com/${encodeURIComponent(value || '')}`
    : `https://wa.me/message/${encodeURIComponent(phone)}`

  if (typeof window !== 'undefined' && typeof window.open === 'function')
    window.open(url, '_blank')
}

// 统一 WhatsApp 跳转处理
export function handleWhatsApp(type: 'live_chat' | 'activity_group', value: string = '') {
  const runtime = getPlusRuntime()
  // H5 模式下直接跳转网页
  if (!runtime) {
    openH5WhatsApp(type, value)
    return
  }

  // APP 模式：检查 WhatsApp 是否安装
  if (!checkAppInstalled('whatsapp')) {
    toast.info(t('share.appNotInstalled'))
    return
  }

  // 打开 WhatsApp
  if (type === 'live_chat') {
    runtime.openURL(`whatsapp://send?phone=${value}`)
  }
  else if (type === 'activity_group') {
    runtime.openURL(`https://chat.whatsapp.com/${value}`)
  }
}
