export function normalizeSourceProject(project = {}) {
  return {
    projectId: project.projectId,
    id: project.slug || String(project.projectId || ''),
    name: project.projectName || project.name || '',
    category: project.category || '',
    coverText: project.coverText || '',
    summary: project.summary || '',
    descriptionMd: project.descriptionMd || '',
    price: project.priceLabel || formatPrice(project.price),
    priceValue: Number(project.price || 0),
    views: Number(project.viewCount || project.views || 0),
    updateTime: normalizeDate(project.updateTime),
    tags: normalizeList(project.tags),
    modules: normalizeList(project.modules),
    scenes: normalizeList(project.scenes),
    purchased: Boolean(project.purchased),
    resourceReady: Boolean(project.resourceReady)
  }
}

export function normalizeSourceProjects(projects = []) {
  return Array.isArray(projects) ? projects.map(normalizeSourceProject) : []
}

export function normalizeSourceCategories(categories = []) {
  if (!Array.isArray(categories)) return []
  return categories
    .map((category) => ({
      value: category.value || category.dictValue || '',
      label: category.label || category.dictLabel || category.value || category.dictValue || ''
    }))
    .filter((category) => category.value)
}

export function buildSourceCategories(projects = [], sourceCategories = []) {
  const seen = new Set()
  const categories = [{ value: 'all', label: '全部源码' }]
  normalizeSourceCategories(sourceCategories).forEach((category) => {
    if (seen.has(category.value)) return
    seen.add(category.value)
    categories.push(category)
  })
  projects.forEach((project) => {
    const value = project.category
    if (!value || seen.has(value)) return
    seen.add(value)
    categories.push({
      value,
      label: value
    })
  })
  return categories
}

function normalizeList(value) {
  if (Array.isArray(value)) return value
  if (!value) return []
  if (typeof value !== 'string') return []
  try {
    const parsed = JSON.parse(value)
    return Array.isArray(parsed) ? parsed : []
  } catch (error) {
    return value
      .split(/[,，\n]/)
      .map((item) => item.trim())
      .filter(Boolean)
  }
}

function normalizeDate(value) {
  if (!value) return ''
  if (typeof value === 'string') return value.slice(0, 10)
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return ''
  return date.toISOString().slice(0, 10)
}

function formatPrice(cents) {
  const value = Number(cents || 0) / 100
  return `¥${Number.isInteger(value) ? value : value.toFixed(2)}`
}
