function escapeHtml(value) {
  return String(value ?? '')
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#39;');
}

function formatMoney(amount, currency = 'EUR') {
  const safeAmount = Number(amount || 0);
  const locale = currency === 'GBP' ? 'en-GB' : currency === 'USD' || currency === 'CAD' ? 'en-US' : 'en-IE';
  return new Intl.NumberFormat(locale, {
    style: 'currency',
    currency,
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(safeAmount);
}

function buildInvoiceNumber(db) {
  const last = db.prepare('SELECT invoice_number FROM invoices ORDER BY id DESC LIMIT 1').get();
  const numeric = Number(String(last?.invoice_number || '').replace(/\D/g, ''));
  return String(Number.isFinite(numeric) && numeric > 0 ? numeric + 1 : 2100);
}

function renderInvoiceHtml({ profile, invoice, items }) {
  const currency = (invoice.currency || 'EUR').toUpperCase();
  const invoiceDate = invoice.invoice_date || new Date().toISOString().slice(0, 10);
  const dueDate = invoice.due_date || 'Upon Completion';
  const subtotal = Number(invoice.subtotal || 0);
  const depositRequired = Number(invoice.deposit_required || 0);
  const businessBlock = [
    profile.legal_name,
    profile.address_line1,
    profile.address_line2,
    profile.city_postcode_country,
    profile.country,
    profile.utr ? `Tax ID (UTR): ${profile.utr}` : '',
    profile.national_id ? `National Insurance: ${profile.national_id}` : '',
    profile.website ? `Website: ${profile.website}` : '',
    `Invoice Date: ${escapeHtml(invoiceDate)}`
  ].filter(Boolean);
  const clientBlock = [
    invoice.client_name,
    invoice.client_address,
    invoice.client_tax_id ? `UTR/PIVA: ${invoice.client_tax_id}` : '',
    invoice.client_code ? `Codice Univoco: ${invoice.client_code}` : ''
  ].filter(Boolean);

  const lineRows = items.map((item) => `
    <tr>
      <td>${escapeHtml(item.description)}</td>
      <td class="amount">${escapeHtml(formatMoney(item.amount, currency))}</td>
    </tr>
  `).join('');

  const terms = String(invoice.terms || '').trim()
    .split('\n')
    .map((line) => line.trim())
    .filter(Boolean);

  const logoBlock = profile.logo_url
    ? `<img src="${escapeHtml(profile.logo_url)}" alt="${escapeHtml(profile.display_name || 'Logo')}" class="logo">`
    : `<div class="brand-lockup"><div class="brand-name">${escapeHtml(profile.display_name || profile.legal_name || 'INVOICE')}</div><div class="brand-tag">${escapeHtml(profile.tagline || '')}</div></div>`;

  return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Invoice ${escapeHtml(invoice.invoice_number)}</title>
  <style>
    * { box-sizing: border-box; }
    body { margin: 0; font-family: Arial, Helvetica, sans-serif; background: #f3f4f6; color: #111827; }
    .page { width: 210mm; min-height: 297mm; margin: 0 auto 24px; background: white; padding: 18mm 18mm 16mm; box-shadow: 0 12px 40px rgba(15, 23, 42, 0.12); }
    .header { display: flex; justify-content: space-between; align-items: flex-start; gap: 24px; margin-bottom: 24px; }
    .logo { max-width: 180px; max-height: 72px; object-fit: contain; }
    .brand-lockup { display: flex; flex-direction: column; gap: 4px; }
    .brand-name { font-size: 28px; font-weight: 800; letter-spacing: 0.02em; }
    .brand-tag { color: #4b5563; font-size: 13px; }
    .invoice-meta { text-align: right; }
    .invoice-kicker { font-size: 32px; font-weight: 800; letter-spacing: 0.06em; margin: 0 0 12px; }
    .invoice-number { font-size: 16px; font-weight: 700; margin-bottom: 6px; }
    .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 28px; margin-bottom: 24px; }
    .label { font-size: 12px; font-weight: 800; letter-spacing: 0.1em; margin-bottom: 10px; color: #374151; }
    .block p { margin: 0 0 4px; line-height: 1.45; font-size: 14px; }
    .subgrid { display: grid; grid-template-columns: 1fr 210px; gap: 24px; align-items: start; margin-bottom: 20px; }
    .due-box { border: 1px solid #d1d5db; border-radius: 16px; padding: 16px; }
    table { width: 100%; border-collapse: collapse; margin-top: 10px; }
    thead th { text-align: left; padding: 12px 10px; font-size: 13px; border-bottom: 2px solid #111827; }
    tbody td { padding: 12px 10px; font-size: 14px; border-bottom: 1px solid #e5e7eb; vertical-align: top; }
    .amount { text-align: right; white-space: nowrap; font-weight: 700; }
    .summary { margin-top: 18px; display: flex; justify-content: flex-end; }
    .summary-box { width: 320px; }
    .summary-row { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #e5e7eb; font-size: 15px; }
    .summary-row.total { font-weight: 800; font-size: 17px; }
    .bank, .terms { margin-top: 24px; }
    .section-title { font-size: 13px; letter-spacing: 0.08em; font-weight: 800; margin: 0 0 10px; color: #111827; }
    .bank p, .terms li, .terms p { margin: 0 0 6px; font-size: 14px; line-height: 1.5; }
    .terms ul { margin: 0; padding-left: 18px; }
    .footer-note { margin-top: 24px; font-size: 13px; color: #374151; }
    .print-bar { position: sticky; top: 0; background: #111827; color: white; padding: 12px 18px; display: flex; justify-content: space-between; align-items: center; z-index: 10; }
    .print-bar button { background: #4f46e5; border: 0; color: white; padding: 10px 14px; border-radius: 10px; font-weight: 700; cursor: pointer; }
    @media print {
      body { background: white; }
      .print-bar { display: none; }
      .page { box-shadow: none; margin: 0; width: auto; min-height: auto; page-break-after: always; }
      .page:last-child { page-break-after: auto; }
    }
  </style>
</head>
<body>
  <div class="print-bar">
    <div>Invoice ${escapeHtml(invoice.invoice_number)} for ${escapeHtml(invoice.client_name)}</div>
    <button onclick="window.print()">Print / Save PDF</button>
  </div>
  <section class="page">
    <div class="header">
      <div>${logoBlock}</div>
      <div class="invoice-meta">
        <div class="invoice-kicker">INVOICE</div>
        <div class="invoice-number">Invoice #${escapeHtml(invoice.invoice_number)}</div>
      </div>
    </div>

    <div class="grid">
      <div class="block">
        <div class="label">FROM:</div>
        ${businessBlock.map((line) => `<p>${escapeHtml(line)}</p>`).join('')}
      </div>
      <div class="block">
        <div class="label">TO:</div>
        ${clientBlock.map((line) => `<p>${escapeHtml(line)}</p>`).join('')}
      </div>
    </div>

    <div class="subgrid">
      <div>
        <table>
          <thead>
            <tr>
              <th>Description</th>
              <th class="amount">Amount (${escapeHtml(currency)})</th>
            </tr>
          </thead>
          <tbody>
            ${lineRows}
          </tbody>
        </table>
      </div>
      <div class="due-box">
        <div class="label">Due Date</div>
        <p>${escapeHtml(dueDate)}</p>
        ${invoice.payment_reference ? `<div class="label" style="margin-top:16px;">Payment Ref</div><p>${escapeHtml(invoice.payment_reference)}</p>` : ''}
      </div>
    </div>

    <div class="summary">
      <div class="summary-box">
        <div class="summary-row total"><span>SUBTOTAL</span><span>${escapeHtml(formatMoney(subtotal, currency))}</span></div>
        <div class="summary-row"><span>DEPOSIT REQUIRED</span><span>${escapeHtml(formatMoney(depositRequired, currency))}</span></div>
      </div>
    </div>

    <div class="bank">
      <div class="section-title">BANK DETAILS</div>
      ${profile.bank_holder ? `<p><strong>Account Holder:</strong> ${escapeHtml(profile.bank_holder)}</p>` : ''}
      ${profile.bank_account ? `<p><strong>Bank Account:</strong> ${escapeHtml(profile.bank_account)}</p>` : ''}
      ${profile.bank_swift ? `<p><strong>Bank Code (SWIFT):</strong> ${escapeHtml(profile.bank_swift)}</p>` : ''}
      ${profile.bank_bic ? `<p><strong>BIC:</strong> ${escapeHtml(profile.bank_bic)}</p>` : ''}
      ${profile.bank_address ? `<p><strong>Address:</strong> ${escapeHtml(profile.bank_address)}</p>` : ''}
    </div>

    <div class="terms">
      <div class="section-title">INCLUDED SERVICES & TERMS</div>
      ${terms.length ? `<ul>${terms.map((line) => `<li>${escapeHtml(line)}</li>`).join('')}</ul>` : '<p>No terms added.</p>'}
    </div>

    <div class="footer-note">Thank you for choosing ${escapeHtml(profile.display_name || profile.legal_name || 'our company')}. For questions, please contact us via ${escapeHtml(profile.website || 'email')}.</div>
  </section>
  <section class="page">
    <div class="header">
      <div>${logoBlock}</div>
      <div class="invoice-meta">
        <div class="invoice-kicker">FATTURA</div>
        <div class="invoice-number">Fattura #${escapeHtml(invoice.invoice_number)}</div>
      </div>
    </div>

    <div class="grid">
      <div class="block">
        <div class="label">DA:</div>
        ${businessBlock.map((line) => `<p>${escapeHtml(line)}</p>`).join('')}
      </div>
      <div class="block">
        <div class="label">A:</div>
        ${clientBlock.map((line) => `<p>${escapeHtml(line)}</p>`).join('')}
      </div>
    </div>

    <div class="subgrid">
      <div>
        <table>
          <thead>
            <tr>
              <th>Descrizione</th>
              <th class="amount">Valore (${escapeHtml(currency)})</th>
            </tr>
          </thead>
          <tbody>
            ${lineRows}
          </tbody>
        </table>
      </div>
      <div class="due-box">
        <div class="label">Scadenza</div>
        <p>${escapeHtml(dueDate)}</p>
        ${invoice.payment_reference ? `<div class="label" style="margin-top:16px;">Riferimento</div><p>${escapeHtml(invoice.payment_reference)}</p>` : ''}
      </div>
    </div>

    <div class="summary">
      <div class="summary-box">
        <div class="summary-row total"><span>SUBTOTALE</span><span>${escapeHtml(formatMoney(subtotal, currency))}</span></div>
        <div class="summary-row"><span>DEPOSITO RICHIESTO</span><span>${escapeHtml(formatMoney(depositRequired, currency))}</span></div>
      </div>
    </div>

    <div class="bank">
      <div class="section-title">DETTAGLI BANCARI</div>
      ${profile.bank_holder ? `<p><strong>Intestatario:</strong> ${escapeHtml(profile.bank_holder)}</p>` : ''}
      ${profile.bank_account ? `<p><strong>Conto:</strong> ${escapeHtml(profile.bank_account)}</p>` : ''}
      ${profile.bank_swift ? `<p><strong>Codice SWIFT:</strong> ${escapeHtml(profile.bank_swift)}</p>` : ''}
      ${profile.bank_bic ? `<p><strong>BIC:</strong> ${escapeHtml(profile.bank_bic)}</p>` : ''}
      ${profile.bank_address ? `<p><strong>Indirizzo:</strong> ${escapeHtml(profile.bank_address)}</p>` : ''}
    </div>

    <div class="terms">
      <div class="section-title">SERVIZI INCLUSI & TERMINI</div>
      ${terms.length ? `<ul>${terms.map((line) => `<li>${escapeHtml(line)}</li>`).join('')}</ul>` : '<p>Nessun termine aggiunto.</p>'}
    </div>
  </section>
</body>
</html>`;
}

module.exports = { buildInvoiceNumber, renderInvoiceHtml };
