export type SourcePreviewItem = {
  title?: string
  url?: string
  snippet?: string
  query?: string
}

export function sourceDomain(url: string) {
  try {
    return new URL(url).hostname.replace(/^www\./, '')
  } catch {
    return url
  }
}

export function sourceDisplayTitle(item: SourcePreviewItem, fallback = '參考連結') {
  return item.title?.trim() || item.query?.trim() || fallback
}

export function domainAvatarLabel(domain: string) {
  const label = domain.split('.')[0]?.trim() || domain
  if (!label) return '?'
  return label.slice(0, 1).toUpperCase()
}

export function domainAvatarHue(domain: string) {
  let hash = 0
  for (let i = 0; i < domain.length; i += 1) {
    hash = (hash * 31 + domain.charCodeAt(i)) % 360
  }
  return hash
}

export function buildSourceIndex(items: SourcePreviewItem[]) {
  const byURL = new Map<string, SourcePreviewItem>()
  for (const item of items) {
    const url = item.url?.trim()
    if (!url || byURL.has(url)) continue
    byURL.set(url, item)
  }
  return byURL
}

export function enrichSourceItem(
  item: SourcePreviewItem,
  index: Map<string, SourcePreviewItem>,
): SourcePreviewItem {
  const url = item.url?.trim()
  if (!url) return item
  const found = index.get(url)
  if (!found) return item
  return {
    title: item.title?.trim() || found.title,
    url,
    snippet: item.snippet?.trim() || found.snippet,
    query: item.query?.trim() || found.query,
  }
}