import { type ClassValue, clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

/**
 * Strip markdown formatting from text for clean clipboard copy
 */
export function stripMarkdown(text: string): string {
  return text
    // Remove headers
    .replace(/^#{1,6}\s+/gm, '')
    // Bold+italic
    .replace(/\*\*\*(.+?)\*\*\*/g, '$1')
    // Bold
    .replace(/\*\*(.+?)\*\*/g, '$1')
    // Italic
    .replace(/\*(.+?)\*/g, '$1')
    // Strikethrough
    .replace(/~~(.+?)~~/g, '$1')
    // Inline code
    .replace(/`(.+?)`/g, '$1')
    // Links [text](url)
    .replace(/\[(.+?)\]\(.+?\)/g, '$1')
    // Images
    .replace(/!\[.*?\]\(.+?\)/g, '')
    // Blockquotes
    .replace(/^>\s*/gm, '')
    // Horizontal rules
    .replace(/^[-*_]{3,}\s*$/gm, '—')
    // Bullet lists - preserve text
    .replace(/^[\s]*[-*+]\s+/gm, '• ')
    // Numbered lists - keep as-is
    .trim()
}

/**
 * Download content as a Word document via the export API
 */
export async function downloadAsWord(title: string, content: string) {
  const res = await fetch('/api/export/docx', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ title, content }),
  })

  if (!res.ok) {
    throw new Error('Erro ao gerar documento Word')
  }

  const blob = await res.blob()
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${title}.docx`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}
