/**
 * DataTable export utilities
 * @countermeasure/web-components/components/data-table
 */

import { type ColumnDef } from './types'

/** Escape a CSV field value, wrapping in quotes if necessary */
function escapeCsvField(value: unknown): string {
  const str =
    value === null || value === undefined
      ? ''
      : typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'
        ? String(value)
        : JSON.stringify(value)

  if (str.includes(',') || str.includes('"') || str.includes('\n') || str.includes('\r')) {
    return `"${str.replace(/"/g, '""')}"`
  }
  return str
}

/** Export table data as a CSV string */
export function exportCsv(columns: ColumnDef[], rows: unknown[][]): string {
  const header = columns.map(col => escapeCsvField(col.label)).join(',')
  const lines: string[] = [header]

  for (const row of rows) {
    const fields: string[] = []
    for (let i = 0; i < columns.length; i++) {
      const cell = row[i]
      fields.push(escapeCsvField(cell))
    }
    lines.push(fields.join(','))
  }

  return lines.join('\n')
}

/** Export table data as a JSON string (array of objects keyed by column key) */
export function exportJson(columns: ColumnDef[], rows: unknown[][]): string {
  const objects: Record<string, unknown>[] = []

  for (const row of rows) {
    const obj: Record<string, unknown> = {}
    for (let i = 0; i < columns.length; i++) {
      const col = columns[i]
      if (col !== undefined) {
        obj[col.key] = row[i] ?? null
      }
    }
    objects.push(obj)
  }

  return JSON.stringify(objects, null, 2)
}

/** Copy text to the clipboard using the Clipboard API */
export async function copyToClipboard(text: string): Promise<void> {
  await navigator.clipboard.writeText(text)
}
