function splitPreviewRow(line) {
  return String(line || '')
    .split('|')
    .map((cell) => cell.trim())
}

export function buildPreviewMetaLine(document) {
  if (!document) {
    return []
  }

  return [document.summary, document.time].filter(Boolean)
}

export function buildPreviewSecondaryMetaLine(document, page = null) {
  if (!document) {
    return []
  }

  const activePage = page || (Array.isArray(document.previewPages) ? document.previewPages[0] : null)
  if (!activePage) {
    return []
  }

  const parts = []

  if (activePage.subtitle) {
    parts.push(activePage.subtitle)
  }

  if (document.previewKind === 'table') {
    for (const item of activePage.stats || []) {
      if (!item?.label || !item?.value || item.label === '文件大小') {
        continue
      }
      parts.push(`${item.label} ${item.value}`)
    }
  }

  return parts
}

export function buildExcelPreviewTable(page) {
  const rawRows = (page?.blocks || [])
    .flatMap((block) => block.lines || [])
    .map(splitPreviewRow)
    .filter((row) => row.length > 0 && row.some((cell) => cell !== ''))

  if (!rawRows.length) {
    return { headers: [], rows: [] }
  }

  const columnCount = rawRows.reduce((max, row) => Math.max(max, row.length), 0)
  const normalizedRows = rawRows.map((row) =>
    Array.from({ length: columnCount }, (_, index) => row[index] ?? '')
  )

  const [headerRow, ...bodyRows] = normalizedRows
  const headers = headerRow.map((cell, index) => cell || `列 ${index + 1}`)

  return {
    headers,
    rows: bodyRows
  }
}
