// #ifdef H5
import PhotoSwipe from 'photoswipe'
import 'photoswipe/style.css'

type SrcsetInfo = {
  src: string
  width: number
  height: number
  srcset?: string
}

function parseQuery(url: string): Record<string, string> {
  const qIndex = url.indexOf('?')
  if (qIndex === -1) return {}
  const q = url.slice(qIndex + 1)
  const params: Record<string, string> = {}
  q.split('&').forEach((pair) => {
    const [k, v] = pair.split('=')
    if (k) params[decodeURIComponent(k)] = decodeURIComponent(v || '')
  })
  return params
}

function stringifyQuery(base: string, params: Record<string, string | number | undefined>): string {
  const qIndex = base.indexOf('?')
  const basePath = qIndex === -1 ? base : base.slice(0, qIndex)
  const existing = qIndex === -1 ? {} : parseQuery(base)
  const merged: Record<string, string> = { ...existing }
  Object.keys(params).forEach((k) => {
    const v = params[k]
    if (v === undefined || v === null) return
    merged[k] = String(v)
  })
  const query = Object.keys(merged)
    .map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(merged[k])}`)
    .join('&')
  return query ? `${basePath}?${query}` : basePath
}

function parseWH(url: string): { width?: number; height?: number } {
  const q = parseQuery(url)
  const w = q.width ? Number(q.width) : undefined
  const h = q.height ? Number(q.height) : undefined
  return { width: isFinite(w!) ? w : undefined, height: isFinite(h!) ? h : undefined }
}

function buildVariant(url: string, width?: number, height?: number): string {
  const params: Record<string, string | number | undefined> = {}
  if (width && width > 0) params.width = width
  if (height && height > 0) params.height = height
  // 保留其他查询参数，同时替换宽高
  return stringifyQuery(url, params)
}

function buildSrcset(url: string): SrcsetInfo {
  const { width, height } = parseWH(url)
  const ratio = width && height && width > 0 ? height! / width! : undefined
  const candidates = [1080, 1440, 2160, 2880, 3600]
  const entries: { url: string; w: number }[] = []
  for (const w of candidates) {
    const h = ratio ? Math.round(w * ratio) : undefined
    entries.push({ url: buildVariant(url, w, h), w })
  }
  const largest = entries[entries.length - 1]
  const largestH = ratio ? Math.round(largest.w * ratio) : height || 0
  const srcset = entries.map((e) => `${e.url} ${e.w}w`).join(', ')
  return { src: largest.url, width: largest.w, height: largestH || 0, srcset }
}

// 容错：若传入的字符串实际是 srcset（逗号分隔的多 URL），提取第一个 URL
function normalizeUrl(input: string): string {
  const s = input.trim()
  if (s.includes(',') && s.includes('http')) {
    const first = s.split(',')[0].trim()
    // 去掉末尾的宽度描述符 "1080w" 等
    const noDescriptor = first.split(' ')[0]
    return noDescriptor
  }
  return s
}

// 通过加载一张较小宽度的图片探测真实宽高比
function probeRatio(baseUrl: string): Promise<number | undefined> {
  return new Promise((resolve) => {
    try {
      const testUrl = buildVariant(baseUrl, 1080, undefined)
      const img = new Image()
      img.referrerPolicy = 'no-referrer'
      img.onload = () => {
        const w = (img as any).naturalWidth || img.width
        const h = (img as any).naturalHeight || img.height
        resolve(w && h ? h / w : undefined)
      }
      img.onerror = () => resolve(undefined)
      img.src = testUrl
    } catch (e) {
      resolve(undefined)
    }
  })
}

export async function openH5Preview(urls: string[], current?: string) {
  const items = await Promise.all(
    urls.map(async (raw) => {
      const u = normalizeUrl(raw)
      const wh = parseWH(u)
      let ratio = wh.width && wh.height ? wh.height / wh.width : undefined
      if (!ratio) ratio = await probeRatio(u)
      const candidates = [1080, 1440, 2160, 2880, 3600]
      const srcset = candidates
        .map((w) => {
          const h = ratio ? Math.round(w * ratio) : undefined
          return `${buildVariant(u, w, h)} ${w}w`
        })
        .join(', ')
      const largestW = candidates[candidates.length - 1]
      const largestH = ratio ? Math.round(largestW * ratio) : wh.height || 2048
      return {
        src: buildVariant(u, largestW, largestH),
        width: largestW,
        height: largestH,
        srcset,
      }
    })
  )

  const index = current ? Math.max(0, urls.findIndex((u) => u === current)) : 0

  const pswp = new PhotoSwipe({
    dataSource: items,
    index,
    bgOpacity: 0.85,
    wheelToZoom: true,
    zoomAnimationDuration: 300,
    // 限制最大缩放到自然像素，避免超采样导致模糊
    maxZoomPixelRatio: 1,
    // 竖向长图：优先按宽度铺满，允许纵向滚动，避免“被压扁”
    initialZoomLevel: (item: any, pswp: any) => {
      const vpW = pswp?.viewportSize?.x || window.innerWidth
      const vpH = pswp?.viewportSize?.y || window.innerHeight
      const pad = pswp?.options?.padding || { top: 0, bottom: 0, left: 0, right: 0 }
      const padX = (pad.left || 0) + (pad.right || 0)
      const padY = (pad.top || 0) + (pad.bottom || 0)
      const wFit = (vpW - padX) / item.width
      const hFit = (vpH - padY) / item.height
      const isLongPortrait = item.height / item.width >= 1.8
      const isUltraWide = item.width / item.height >= 1.8
      // 长竖图：铺满宽度；超宽横图：铺满高度；其它：contain
      if (isLongPortrait) return wFit
      if (isUltraWide) return hFit
      return Math.min(wFit, hFit)
    },
    allowPanToNext: false,
    closeOnVerticalDrag: false,
    padding: { top: 24, bottom: 24, left: 24, right: 24 },
  } as any)
  pswp.init()
}
// #endif