export function toAbsoluteH5Url(path: string) {
  // #ifdef H5
  const base = new URL(window.location.href)
  base.searchParams.delete('code')
  base.searchParams.delete('state')
  base.hash = path.startsWith('#') ? path : `#${path.startsWith('/') ? path : `/${path}`}`
  return base.toString()
  // #endif
  // #ifndef H5
  return path
  // #endif
}

export async function shareH5Link(path: string, title = '访客码分享') {
  const url = toAbsoluteH5Url(path)
  // #ifdef H5
  const navigatorWithShare = navigator as Navigator & {
    share?: (data: { title?: string, url?: string }) => Promise<void>
  }
  if (typeof navigatorWithShare.share === 'function') {
    await navigatorWithShare.share({ title, url })
    return
  }
  // #endif
  await new Promise<void>((resolve, reject) => {
    uni.setClipboardData({
      data: url,
      success: () => resolve(),
      fail: () => reject(new Error('复制分享链接失败')),
    })
  })
  uni.showToast({ title: '分享链接已复制', icon: 'none' })
}
