/**
 * AR Aging PDF renderer — ar-aging-report (wave-12).
 *
 * Renders the report as HTML then converts via the HTML-to-PDF Worker pattern.
 * RTL/Hebrew-aware: uses `dir="rtl"` when locale is 'he'.
 * window.print() fallback documented below.
 *
 * NOTE: Cloudflare Browser Rendering is explicitly rejected per spec.
 * The HTML-to-PDF Worker pattern encodes the HTML as base64, posts to a
 * dedicated PDF-render Worker, and returns the PDF bytes. If the PDF Worker
 * is unavailable, the route falls back to returning the raw HTML with
 * Content-Type text/html and a `X-Print-Fallback: true` header so the
 * client can trigger window.print().
 */
import type { ArAgingReport } 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-faint: oklch(43% 0.035 235);
  --line: oklch(90% 0.03 195);
  --line-subtle: oklch(96% 0.014 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 fmtAmount(amount: string): string {
  const n = parseFloat(amount)
  return n.toLocaleString('he-IL', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

export function buildArAgingHtml(report: ArAgingReport, locale: 'he' | 'en' = 'he'): string {
  const isRtl = locale === 'he'
  const dir = isRtl ? 'rtl' : 'ltr'
  const fontFamily = isRtl
    ? "Arial, 'Noto Sans Hebrew', Helvetica, sans-serif"
    : "Arial, Helvetica, sans-serif"

  const s = report.summary

  const customerRows = report.customers.map((c) => `
    <div role="row">
      <div role="cell">${esc(c.customerName)}</div>
      <div role="cell" class="num">${fmtAmount(c.current.amount)}</div>
      <div role="cell" class="num">${fmtAmount(c.d1_30.amount)}</div>
      <div role="cell" class="num">${fmtAmount(c.d31_60.amount)}</div>
      <div role="cell" class="num">${fmtAmount(c.d61_90.amount)}</div>
      <div role="cell" class="num overdue-severe">${fmtAmount(c.d90plus.amount)}</div>
      <div role="cell" class="num total">${fmtAmount(c.total)}</div>
    </div>
  `).join('')

  return `<!DOCTYPE html>
<html dir="${dir}" lang="${locale === 'he' ? 'he' : 'en'}">
<head>
<meta charset="UTF-8" />
<title>AR Aging Report — ${esc(report.asOf)}</title>
<style>
  ${UI_TOKENS_CSS}
  body { font-family: ${fontFamily}; font-size: 12px; color: var(--ink); margin: 24px; direction: ${dir}; }
  h1 { font-size: 18px; margin-bottom: 4px; }
  .meta { color: var(--ink-faint); font-size: 11px; margin-bottom: 24px; }
  .aging-table { width: 100%; margin-top: 16px; }
  .aging-table [role="row"] {
    display: grid;
    grid-template-columns: 1.5fr repeat(6, minmax(4rem, 1fr));
  }
  [role="columnheader"] {
    background: var(--surface);
    padding: 8px;
    text-align: ${isRtl ? 'right' : 'left'};
    font-weight: 600;
    border-bottom: 2px solid var(--line);
  }
  [role="cell"] { padding: 6px 8px; border-bottom: 1px solid var(--line-subtle); }
  .num { text-align: ${isRtl ? 'left' : 'right'}; font-variant-numeric: tabular-nums; }
  .total { font-weight: 600; }
  .overdue-severe { color: var(--danger); }
  .summary-row { background: var(--surface); font-weight: 700; }
  @media print { body { margin: 0; } }
</style>
</head>
<body>
<h1>${isRtl ? 'דוח גיל חובות (AR Aging)' : 'Accounts Receivable Aging Report'}</h1>
<div class="meta">
  ${isRtl ? 'נכון לתאריך' : 'As of'}: ${esc(report.asOf)} &nbsp;|&nbsp;
  ${isRtl ? 'מטבע' : 'Currency'}: ${esc(report.currency)}
</div>
<div class="aging-table" role="table">
  <div role="rowgroup">
    <div role="row">
      <div role="columnheader">${isRtl ? 'לקוח' : 'Customer'}</div>
      <div role="columnheader" class="num">${isRtl ? 'שוטף' : 'Current'}</div>
      <div role="columnheader" class="num">${isRtl ? '1–30 ימים' : '1–30 Days'}</div>
      <div role="columnheader" class="num">${isRtl ? '31–60 ימים' : '31–60 Days'}</div>
      <div role="columnheader" class="num">${isRtl ? '61–90 ימים' : '61–90 Days'}</div>
      <div role="columnheader" class="num">${isRtl ? '90+ ימים' : '90+ Days'}</div>
      <div role="columnheader" class="num">${isRtl ? 'סה"כ' : 'Total'}</div>
    </div>
  </div>
  <div role="rowgroup">
    <div role="row" class="summary-row">
      <div role="cell">${isRtl ? 'סה"כ' : 'TOTAL'}</div>
      <div role="cell" class="num">${fmtAmount(s.current.amount)}</div>
      <div role="cell" class="num">${fmtAmount(s.d1_30.amount)}</div>
      <div role="cell" class="num">${fmtAmount(s.d31_60.amount)}</div>
      <div role="cell" class="num">${fmtAmount(s.d61_90.amount)}</div>
      <div role="cell" class="num overdue-severe">${fmtAmount(s.d90plus.amount)}</div>
      <div role="cell" class="num total">${fmtAmount(s.total)}</div>
    </div>
    ${customerRows}
  </div>
</div>
</body>
</html>`
}
