/** 精选菜品列表项展示工具（与首页瀑布流一致） */

export function getFeaturedDishImage(item: Record<string, unknown>): string {
  const raw = item.dishImageUrl ?? item.dishImage
  if (typeof raw !== 'string' || !raw.trim()) return ''
  return raw.split(',')[0].trim()
}

export function isFeaturedDishSoldOut(stockLike: unknown): boolean {
  const n = Number(stockLike)
  return !Number.isNaN(n) && n <= 0
}

export function getFeaturedDishPromoLabel(item: Record<string, unknown>): string {
  const raw = item.marketingLabel ?? item.hotSaleTag ?? item.rankTag ?? item.promotionLabel
  return typeof raw === 'string' && raw.trim() ? raw.trim() : ''
}

/** 解析 featuredDishList 分页响应（兼容 rows 在根或 data 下） */
export function parseFeaturedDishListRes(res: unknown): {
  rows: Record<string, unknown>[]
  total: number
} {
  if (!res || typeof res !== 'object') {
    return { rows: [], total: 0 }
  }
  const r = res as Record<string, unknown>
  const data = r.data
  let rows: unknown[] = []
  if (Array.isArray(r.rows)) {
    rows = r.rows
  } else if (data && typeof data === 'object' && Array.isArray((data as Record<string, unknown>).rows)) {
    rows = (data as Record<string, unknown>).rows as unknown[]
  }
  const totalRaw = r.total ?? (data && typeof data === 'object' ? (data as Record<string, unknown>).total : undefined)
  const total = Number(totalRaw)
  const rowList = rows as Record<string, unknown>[]
  let resolvedTotal = Number.isFinite(total) ? total : rowList.length
  // 部分接口有 rows 但 total 为 0，避免 z-paging 把 total 当成 success 后判失败
  if (resolvedTotal <= 0 && rowList.length > 0) {
    resolvedTotal = rowList.length
  }
  return {
    rows: rowList,
    total: resolvedTotal,
  }
}
