/**
 * Statement HTML renderer — customer-statement (wave-16, spec 183).
 *
 * Produces a complete HTML document for the customer statement PDF.
 * RTL/Hebrew-aware: emits `<html dir="rtl">` for locale='he'.
 * Colors use CSS custom properties from packages/ui tokens.
 * All untrusted strings are escaped via esc().
 */
import type { CustomerStatement } from '@zync/types'

const UI_TOKENS_CSS = `:root {
  --bg: oklch(100% 0 0);
  --surface: oklch(95% 0.016 195);
  --ink: oklch(12% 0.04 240);
  --ink-soft: oklch(22% 0.045 240);
  --ink-faint: oklch(43% 0.035 235);
  --line: oklch(90% 0.03 195);
  --danger: oklch(44% 0.19 25);
}`

function esc(s: unknown): string {
  return String(s ?? '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;')
}

function fmtNumber(n: number): string {
  return n.toLocaleString('he-IL', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

function fmtDate(d: string): string {
  // Accepts ISO date string YYYY-MM-DD or full ISO timestamp
  return d.slice(0, 10)
}

export function renderStatementHtml(
  statement: CustomerStatement,
  locale: 'he' | 'en',
): string {
  const isRtl = locale === 'he'
  const dir = isRtl ? 'rtl' : 'ltr'
  const lang = isRtl ? 'he' : 'en'

  const t = {
    title: isRtl ? 'כרטסת לקוח' : 'Statement of Account',
    customer: isRtl ? 'לקוח' : 'Customer',
    period: isRtl ? 'תקופה' : 'Period',
    to: isRtl ? 'עד' : 'to',
    openingBalance: isRtl ? 'יתרת פתיחה' : 'Opening Balance',
    closingBalance: isRtl ? 'יתרת סגירה' : 'Closing Balance',
    date: isRtl ? 'תאריך' : 'Date',
    document: isRtl ? 'מסמך' : 'Document',
    reference: isRtl ? 'אסמכתא' : 'Reference',
    debit: isRtl ? 'חובה' : 'Debit',
    credit: isRtl ? 'זכות' : 'Credit',
    balance: isRtl ? 'יתרה' : 'Balance',
    agingTitle: isRtl ? 'פירוט גיל' : 'Aging Summary',
    d0_30: isRtl ? '0-30 ימים' : '0-30 days',
    d31_60: isRtl ? '31-60 ימים' : '31-60 days',
    d61_90: isRtl ? '61-90 ימים' : '61-90 days',
    d90plus: isRtl ? '90+ ימים' : '90+ days',
    noData: isRtl ? 'אין עסקאות בתקופה זו' : 'No transactions in this period',
  }

  const groupsHtml = statement.groups.map((group) => {
    const rowsHtml = group.rows.length === 0
      ? `<div role="row"><div role="cell" class="empty" aria-colspan="6" style="grid-column: span 6">${t.noData}</div></div>`
      : group.rows.map((row) => `
        <div role="row">
          <div role="cell">${esc(fmtDate(row.date))}</div>
          <div role="cell">${esc(row.documentType)}${row.documentNumber ? ' #' + esc(row.documentNumber) : ''}</div>
          <div role="cell">${row.reference ? esc(row.reference) : ''}</div>
          <div role="cell" class="num">${row.debit > 0 ? fmtNumber(row.debit) : ''}</div>
          <div role="cell" class="num">${row.credit > 0 ? fmtNumber(row.credit) : ''}</div>
          <div role="cell" class="num balance">${fmtNumber(row.runningBalance)}</div>
        </div>
      `).join('')

    return `
      <div class="currency-section">
        <h2 class="currency-header">${esc(group.currency)}</h2>
        <div class="statement-grid" role="table">
          <div role="rowgroup">
            <div role="row">
              <div role="columnheader">${t.date}</div>
              <div role="columnheader">${t.document}</div>
              <div role="columnheader">${t.reference}</div>
              <div role="columnheader" class="num">${t.debit}</div>
              <div role="columnheader" class="num">${t.credit}</div>
              <div role="columnheader" class="num">${t.balance}</div>
            </div>
          </div>
          <div role="rowgroup">
            <div role="row" class="balance-row">
              <div role="cell">${t.openingBalance}</div>
              <div role="cell" aria-colspan="4" style="grid-column: span 4"></div>
              <div role="cell" class="num balance">${fmtNumber(group.openingBalance)}</div>
            </div>
            ${rowsHtml}
            <div role="row" class="balance-row closing">
              <div role="cell">${t.closingBalance}</div>
              <div role="cell" aria-colspan="4" style="grid-column: span 4"></div>
              <div role="cell" class="num balance">${fmtNumber(group.closingBalance)}</div>
            </div>
          </div>
        </div>
      </div>
    `
  }).join('')

  const agingSummary = statement.aging
  const agingHtml = `
    <div class="aging-section">
      <h2 class="aging-header">${t.agingTitle}</h2>
      <div class="aging-table" role="table">
        <div role="rowgroup">
          <div role="row">
            <div role="columnheader" class="num">${t.d0_30}</div>
            <div role="columnheader" class="num">${t.d31_60}</div>
            <div role="columnheader" class="num">${t.d61_90}</div>
            <div role="columnheader" class="num">${t.d90plus}</div>
          </div>
        </div>
        <div role="rowgroup">
          <div role="row">
            <div role="cell" class="num">${fmtNumber(agingSummary.d0_30)}</div>
            <div role="cell" class="num">${fmtNumber(agingSummary.d31_60)}</div>
            <div role="cell" class="num">${fmtNumber(agingSummary.d61_90)}</div>
            <div role="cell" class="num overdue">${fmtNumber(agingSummary.d90plus)}</div>
          </div>
        </div>
      </div>
    </div>
  `

  return `<!DOCTYPE html>
<html dir="${dir}" lang="${lang}">
<head>
<meta charset="UTF-8" />
<title>${t.title} — ${esc(statement.customerName)}</title>
<style>
  ${UI_TOKENS_CSS}
  body {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 12px;
    color: var(--ink);
    margin: 24px;
    direction: ${dir};
  }
  h1 { font-size: 18px; margin-bottom: 4px; }
  h2 { font-size: 14px; margin: 16px 0 8px; }
  .meta { color: var(--ink-soft); font-size: 11px; margin-bottom: 24px; }
  .statement-grid,
  .aging-table { width: 100%; margin-bottom: 16px; }
  .statement-grid [role="row"] {
    display: grid;
    grid-template-columns: 5rem 1fr 1fr 5rem 5rem 5rem;
  }
  .aging-table [role="row"] {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
  }
  [role="columnheader"] {
    background: var(--surface);
    padding: 7px 8px;
    text-align: ${isRtl ? 'right' : 'left'};
    font-weight: 600;
    border-bottom: 2px solid var(--line);
  }
  [role="cell"] { padding: 5px 8px; border-bottom: 1px solid var(--line); }
  .num { text-align: ${isRtl ? 'left' : 'right'}; font-variant-numeric: tabular-nums; }
  .balance { font-weight: 600; }
  .balance-row { background: var(--surface); font-weight: 600; }
  .closing { border-top: 2px solid var(--line); }
  .overdue { color: var(--danger); }
  .empty { text-align: center; color: var(--ink-faint); padding: 16px; }
  .aging-section { margin-top: 24px; page-break-inside: avoid; }
  .currency-header { border-bottom: 1px solid var(--line); padding-bottom: 4px; }
  @media print { body { margin: 0; } }
</style>
</head>
<body>
<h1>${t.title}</h1>
<div class="meta">
  ${t.customer}: <strong>${esc(statement.customerName)}</strong>
  &nbsp;|&nbsp;
  ${t.period}: ${esc(statement.from)} ${t.to} ${esc(statement.to)}
</div>
${groupsHtml}
${agingHtml}
</body>
</html>`
}
