// StellarCaptions — Transcript export (TXT / Word / PDF)
// Modern, professional output: a branded title block with metadata, a divider,
// and readable flowing paragraphs. Timestamps are intentionally omitted.

const DOC_TITLE = 'StellarCaptions Transcript'
const ACCENT = '#6366f1' // indigo brand accent
const INK = '#18181b'
const MUTED = '#71717a'

function chosenText(s) {
  // Prefer the translated text when present; otherwise the original.
  const tr = (s.translatedText || '').trim()
  if (tr) return tr
  return (s.text || '').trim()
}

function headerDate(segments) {
  const ts = segments && segments.length ? segments[0].timestamp : Date.now()
  return new Date(ts).toLocaleDateString([], {
    weekday: 'long', year: 'numeric', month: 'long', day: 'numeric',
  })
}

// Merge segments into flowing paragraphs (groups of sentences) so the export
// reads like a document instead of a list of fragments.
function buildParagraphs(segments) {
  const full = (segments || [])
    .map(chosenText)
    .filter(Boolean)
    .join(' ')
    .replace(/\s+/g, ' ')
    .trim()
  if (!full) return []

  const sentences = full.match(/[^.!?]+[.!?]+|\S[^.!?]*$/g) || [full]
  const paras = []
  let cur = []
  sentences.forEach((sn) => {
    cur.push(sn.trim())
    if (cur.length >= 3) {
      paras.push(cur.join(' '))
      cur = []
    }
  })
  if (cur.length) paras.push(cur.join(' '))
  return paras
}

function wordCount(paras) {
  return paras.join(' ').split(/\s+/).filter(Boolean).length
}

function download(blob, filename) {
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  setTimeout(() => URL.revokeObjectURL(url), 1000)
}

// ---------- TXT ----------
function toTxt(segments, filename) {
  const paras = buildParagraphs(segments)
  const date = headerDate(segments)
  const words = wordCount(paras)

  // Soft-wrap each paragraph to ~80 columns for readable plain text.
  const wrap = (text, width = 80) => {
    const out = []
    let line = ''
    text.split(/\s+/).forEach((w) => {
      if ((line + ' ' + w).trim().length > width) { out.push(line.trim()); line = w }
      else line += ' ' + w
    })
    if (line.trim()) out.push(line.trim())
    return out.join('\n')
  }

  const rule = '─'.repeat(64)
  let out = ''
  out += `${rule}\n`
  out += `  ${DOC_TITLE.toUpperCase()}\n`
  out += `${rule}\n`
  out += `  ${date}\n`
  out += `  ${paras.length} paragraph${paras.length === 1 ? '' : 's'} · ${words} word${words === 1 ? '' : 's'}\n`
  out += `${rule}\n\n`
  out += paras.map((p) => wrap(p)).join('\n\n')
  out += '\n'
  download(new Blob([out], { type: 'text/plain;charset=utf-8' }), `${filename}.txt`)
}

// ---------- Word (.doc via HTML) ----------
function toDoc(segments, filename) {
  const paras = buildParagraphs(segments)
  const date = headerDate(segments)
  const words = wordCount(paras)

  const body = paras
    .map((p) => `<p style="margin:0 0 14px 0;line-height:1.7;text-align:justify;">${escapeHtml(p)}</p>`)
    .join('')

  const html = `<!DOCTYPE html><html><head><meta charset="utf-8">
    <title>${escapeHtml(DOC_TITLE)}</title></head>
    <body style="font-family:Calibri,'Segoe UI',Arial,sans-serif;font-size:11.5pt;color:${INK};margin:0;">
      <div style="border-left:6px solid ${ACCENT};padding:2px 0 2px 16px;margin:0 0 6px 0;">
        <div style="font-size:9pt;letter-spacing:2px;color:${ACCENT};font-weight:700;text-transform:uppercase;">StellarCaptions</div>
        <h1 style="font-size:24pt;margin:2px 0 0 0;font-weight:700;letter-spacing:-0.3px;">Transcript</h1>
      </div>
      <p style="color:${MUTED};font-size:10pt;margin:0 0 4px 0;">${escapeHtml(date)}</p>
      <p style="color:${MUTED};font-size:9pt;margin:0 0 18px 0;">${paras.length} paragraph${paras.length === 1 ? '' : 's'} &middot; ${words} word${words === 1 ? '' : 's'}</p>
      <hr style="border:none;border-top:1px solid #e4e4e7;margin:0 0 22px 0;">
      ${body}
    </body></html>`

  download(new Blob([html], { type: 'application/msword' }), `${filename}.doc`)
}

// ---------- PDF (jsPDF) ----------
function hex(c) {
  const n = parseInt(c.replace('#', ''), 16)
  return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
}

function toPdf(segments, filename) {
  const jsPDFCtor = (window.jspdf && window.jspdf.jsPDF) || window.jsPDF
  if (!jsPDFCtor) {
    console.error('[export] jsPDF not loaded')
    return
  }
  const doc = new jsPDFCtor({ unit: 'pt', format: 'letter' })
  const margin = 64
  const pageHeight = doc.internal.pageSize.getHeight()
  const pageWidth = doc.internal.pageSize.getWidth()
  const maxWidth = pageWidth - margin * 2
  const [ar, ag, ab] = hex(ACCENT)
  const [ir, ig, ib] = hex(INK)
  const [mr, mg, mb] = hex(MUTED)

  const paras = buildParagraphs(segments)
  const date = headerDate(segments)
  const words = wordCount(paras)

  // --- Header block ---
  let y = margin
  // Accent rule on the left of the title.
  doc.setFillColor(ar, ag, ab)
  doc.rect(margin, y - 2, 4, 46, 'F')

  doc.setFont('helvetica', 'bold')
  doc.setFontSize(8.5)
  doc.setTextColor(ar, ag, ab)
  doc.text('STELLARCAPTIONS', margin + 14, y + 8)

  doc.setFontSize(26)
  doc.setTextColor(ir, ig, ib)
  doc.text('Transcript', margin + 14, y + 36)
  y += 64

  doc.setFont('helvetica', 'normal')
  doc.setFontSize(10)
  doc.setTextColor(mr, mg, mb)
  doc.text(date, margin, y)
  y += 14
  doc.setFontSize(9)
  doc.text(`${paras.length} paragraph${paras.length === 1 ? '' : 's'}  ·  ${words} word${words === 1 ? '' : 's'}`, margin, y)
  y += 16

  // Divider.
  doc.setDrawColor(228, 228, 231)
  doc.setLineWidth(0.8)
  doc.line(margin, y, pageWidth - margin, y)
  y += 24

  // --- Body ---
  doc.setFont('times', 'normal')
  doc.setFontSize(12)
  doc.setTextColor(ir, ig, ib)
  const lineH = 18

  const footer = () => {
    const page = doc.internal.getCurrentPageInfo().pageNumber
    doc.setFont('helvetica', 'normal')
    doc.setFontSize(8)
    doc.setTextColor(mr, mg, mb)
    doc.text('StellarCaptions', margin, pageHeight - 32)
    doc.text(String(page), pageWidth - margin, pageHeight - 32, { align: 'right' })
    doc.setFont('times', 'normal')
    doc.setFontSize(12)
    doc.setTextColor(ir, ig, ib)
  }
  footer()

  paras.forEach((p) => {
    const wrapped = doc.splitTextToSize(p, maxWidth)
    wrapped.forEach((w) => {
      if (y > pageHeight - margin - 24) {
        doc.addPage()
        y = margin
        footer()
      }
      doc.text(w, margin, y)
      y += lineH
    })
    y += 12 // paragraph spacing
  })

  doc.save(`${filename}.pdf`)
}

function escapeHtml(s) {
  return (s || '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
}

if (typeof window !== 'undefined') {
  window.Exporter = { toTxt, toDoc, toPdf }
}
