/**
 * Receipt HTML renderer — invoice-receipt-document (wave-12, spec 179).
 *
 * Produces print-ready Hebrew RTL HTML for:
 *   - קבלה (receipt, doc_type='receipt')
 *   - חשבונית מס/קבלה (invoice_receipt, doc_type='invoice_receipt')
 *
 * No puppeteer — caller converts to PDF via browser print.
 * Hebrew amount-in-words via amountInWordsHe().
 *
 * TODO(ird-024): reuse tenant_invoice_pdf_config branding (logo, colors) like invoice render.
 */

import type { ReceiptObject } from '@zync/types'

// ── Amount in words (Hebrew) ──────────────────────────────────────────────────

const ONES_HE = [
  '', 'אחד', 'שניים', 'שלושה', 'ארבעה', 'חמישה',
  'שישה', 'שבעה', 'שמונה', 'תשעה', 'עשרה', 'אחד עשר',
  'שנים עשר', 'שלושה עשר', 'ארבעה עשר', 'חמישה עשר',
  'שישה עשר', 'שבעה עשר', 'שמונה עשר', 'תשעה עשר',
]
const TENS_HE = ['', '', 'עשרים', 'שלושים', 'ארבעים', 'חמישים', 'שישים', 'שבעים', 'שמונים', 'תשעים']

function integerToWordsHe(n: number): string {
  if (n === 0) return 'אפס'
  if (n < 0) return `מינוס ${integerToWordsHe(-n)}`
  if (n < 20) return ONES_HE[n] ?? ''
  if (n < 100) {
    const t = Math.floor(n / 10)
    const o = n % 10
    return o === 0 ? (TENS_HE[t] ?? '') : `${TENS_HE[t] ?? ''} ו${ONES_HE[o] ?? ''}`
  }
  if (n < 1000) {
    const h = Math.floor(n / 100)
    const rest = n % 100
    const hWord = h === 1 ? 'מאה' : h === 2 ? 'מאתיים' : `${ONES_HE[h] ?? ''} מאות`
    return rest === 0 ? hWord : `${hWord} ו${integerToWordsHe(rest)}`
  }
  if (n < 1_000_000) {
    const k = Math.floor(n / 1000)
    const rest = n % 1000
    const kWord = k === 1 ? 'אלף' : k === 2 ? 'אלפיים' : `${integerToWordsHe(k)} אלף`
    return rest === 0 ? kWord : `${kWord} ו${integerToWordsHe(rest)}`
  }
  const m = Math.floor(n / 1_000_000)
  const rest = n % 1_000_000
  const mWord = `${integerToWordsHe(m)} מיליון`
  return rest === 0 ? mWord : `${mWord} ו${integerToWordsHe(rest)}`
}

const CURRENCY_NAMES_HE: Record<string, { integer: string; fraction: string }> = {
  ILS: { integer: 'שקל', fraction: 'אגורה' },
  USD: { integer: 'דולר', fraction: 'סנט' },
  EUR: { integer: 'יורו', fraction: 'סנט' },
  GBP: { integer: 'פאונד', fraction: 'פני' },
}

export function amountInWordsHe(amount: number, currency: string): string {
  const names = CURRENCY_NAMES_HE[currency] ?? { integer: currency, fraction: '' }
  const intPart = Math.floor(amount)
  const fracPart = Math.round((amount - intPart) * 100)
  let result = `${integerToWordsHe(intPart)} ${names.integer}`
  if (fracPart > 0 && names.fraction) {
    result += ` ו${integerToWordsHe(fracPart)} ${names.fraction}`
  }
  return result
}

// ── HTML escape ───────────────────────────────────────────────────────────────

function esc(s: string | null | undefined): string {
  if (!s) return ''
  return s
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
}

// ── Render ────────────────────────────────────────────────────────────────────

const METHOD_LABELS_HE: Record<string, string> = {
  cash: 'מזומן',
  bank_transfer: 'העברה בנקאית',
  cheque: "צ'ק",
  credit_card: 'כרטיס אשראי',
  other: 'אחר',
}

export interface ReceiptRenderContext {
  tenantName: string
  tenantAddress?: string
  tenantTaxId?: string
  customerName?: string
  customerTaxId?: string
  customerAddress?: string
  /** Originating tax-invoice number (never a UUID). */
  invoiceNumber?: string
  r2PublicUrl?: string
}

export function renderReceiptHtml(
  receipt: ReceiptObject,
  ctx: ReceiptRenderContext,
): string {
  const isInvoiceReceipt = receipt.docType === 'invoice_receipt'
  const docTitleHe = isInvoiceReceipt ? 'חשבונית מס/קבלה' : 'קבלה'
  const docTitleEn = isInvoiceReceipt ? 'Invoice-Receipt' : 'Receipt'

  const fontUrl = ctx.r2PublicUrl
    ? `${ctx.r2PublicUrl}/_static/fonts/heebo-variable.woff2`
    : null

  const formatCurrency = (val: string | number | null) => {
    if (val === null || val === undefined) return '—'
    const n = typeof val === 'string' ? parseFloat(val) : val
    return new Intl.NumberFormat('he-IL', {
      style: 'currency',
      currency: receipt.currency,
    }).format(n)
  }

  const formatDate = (d: string | null) => {
    if (!d) return '—'
    return new Intl.DateTimeFormat('he-IL', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    }).format(new Date(d))
  }

  const amountNum = parseFloat(receipt.amount)
  const amountWords = amountInWordsHe(amountNum, receipt.currency)

  const linesHtml = (receipt.lines ?? []).map((line) => {
    const methodLabel = METHOD_LABELS_HE[line.method] ?? line.method
    let detail = ''
    if (line.method === 'cheque' && line.chequeNumber) {
      detail = ` — מס׳ ${esc(line.chequeNumber)}`
      if (line.chequeBank) detail += ` בנק ${esc(line.chequeBank)}`
      if (line.chequeDueDate) detail += ` תאריך פירעון ${esc(line.chequeDueDate)}`
    }
    if (line.method === 'credit_card' && line.cardLastFour) {
      detail = ` — *${esc(line.cardLastFour)}`
      if (line.cardBrand) detail += ` (${esc(line.cardBrand)})`
    }
    if (line.reference) {
      detail += ` אסמכתא: ${esc(line.reference)}`
    }
    return `<div role="row">
      <div role="cell">${esc(methodLabel)}${detail}</div>
      <div role="cell" style="text-align:left">${formatCurrency(line.amount)}</div>
    </div>`
  }).join('')

  const voidBanner = receipt.status === 'VOIDED'
    ? `<div class="void-banner">מבוטל — ${esc(receipt.voidReason)}</div>`
    : ''

  const fontFaceBlock = fontUrl
    ? `@font-face {
      font-family: 'Heebo';
      src: url('${fontUrl}') format('woff2');
      font-weight: 100 900;
    }`
    : ''

  return `<!DOCTYPE html>
<html lang="he" dir="rtl">
<head>
  <meta charset="utf-8">
  <title>${docTitleHe} ${esc(receipt.receiptNumber ?? '')}</title>
  <style>
    ${fontFaceBlock}
    body {
      font-family: 'Heebo', sans-serif;
      direction: rtl;
      padding: 32px;
      color: oklch(20% 0 0);
      font-size: 14px;
      line-height: 1.6;
    }
    .header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 24px; }
    .doc-title { font-size: 1.5rem; font-weight: 700; }
    .doc-number { font-size: 1rem; color: oklch(50% 0 0); }
    .parties { display: flex; gap: 32px; margin-bottom: 24px; }
    .party { flex: 1; }
    .party-label { font-weight: 600; border-bottom: 1px solid oklch(85% 0 0); margin-bottom: 8px; padding-bottom: 4px; }
    .payment-table { width: 100%; margin-bottom: 16px; }
    .payment-table [role="row"] {
      display: grid;
      grid-template-columns: 1fr auto;
    }
    [role="columnheader"], [role="cell"] {
      border: 1px solid oklch(85% 0 0);
      padding: 8px;
      text-align: right;
    }
    [role="columnheader"] { background: oklch(95% 0 0); font-weight: 600; }
    .total-row { font-weight: 700; font-size: 1.1rem; }
    .amount-words { font-style: italic; color: oklch(40% 0 0); margin-bottom: 24px; }
    .void-banner {
      background: oklch(75% 0.15 25);
      color: oklch(100% 0 0);
      text-align: center;
      padding: 8px 16px;
      font-weight: 700;
      font-size: 1.1rem;
      margin-bottom: 16px;
    }
    .meta-row { display: flex; gap: 32px; margin-bottom: 16px; }
    .meta-item { display: flex; gap: 8px; }
    .meta-label { font-weight: 500; color: oklch(40% 0 0); }
    @media print { body { padding: 0; } }
  </style>
</head>
<body>
  ${voidBanner}
  <div class="header">
    <div>
      <div class="doc-title">${docTitleHe}</div>
      <div class="doc-number">${esc(receipt.receiptNumber ? `מס׳ ${receipt.receiptNumber}` : 'טיוטה')}</div>
    </div>
    <div style="text-align:left">
      <div style="font-weight:600">${esc(ctx.tenantName)}</div>
      ${ctx.tenantAddress ? `<div>${esc(ctx.tenantAddress)}</div>` : ''}
      ${ctx.tenantTaxId ? `<div>ח.פ. ${esc(ctx.tenantTaxId)}</div>` : ''}
    </div>
  </div>

  <div class="parties">
    <div class="party">
      <div class="party-label">לכבוד</div>
      <div>${esc(ctx.customerName ?? '')}</div>
      ${ctx.customerAddress ? `<div>${esc(ctx.customerAddress)}</div>` : ''}
    </div>
    <div class="party">
      <div class="meta-row">
        <div class="meta-item">
          <span class="meta-label">תאריך הנפקה:</span>
          <span>${formatDate(receipt.issuedAt)}</span>
        </div>
      </div>
      ${ctx.invoiceNumber ? `<div class="meta-item"><span class="meta-label">מס׳ חשבונית:</span> <span>${esc(ctx.invoiceNumber)}</span></div>` : ''}
    </div>
  </div>

  <div class="payment-table" role="table">
    <div role="rowgroup">
      <div role="row">
        <div role="columnheader">אמצעי תשלום</div>
        <div role="columnheader">סכום</div>
      </div>
    </div>
    <div role="rowgroup">
      ${linesHtml || `<div role="row"><div role="cell" aria-colspan="2" style="grid-column: span 2">—</div></div>`}
    </div>
    <div role="rowgroup">
      <div role="row" class="total-row">
        <div role="cell">סה"כ</div>
        <div role="cell" style="text-align:left">${formatCurrency(receipt.amount)}</div>
      </div>
    </div>
  </div>

  <div class="amount-words">סכום במילים: ${esc(amountWords)}</div>

  <div style="margin-top:48px; color:oklch(60% 0 0); font-size:12px; text-align:center">
    ${docTitleEn} — ${docTitleHe} | ${esc(ctx.tenantName)}
  </div>
</body>
</html>`
}
