import type { CompanyProfile } from '../engine/types';
import { renderMarkdown } from './render';

/** Maskiert HTML-Sonderzeichen für den Briefkopf. */
function esc(text: string): string {
  return text
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;');
}

/** Baut den Briefkopf (Logo, Firmenname, Kontaktdaten) als HTML. */
function letterhead(profile: CompanyProfile): string {
  const addressLines = [profile.street, profile.zipCity].filter((l) => l.trim() !== '');
  const contactLines = [
    profile.contactPerson,
    profile.email,
    profile.phone,
    profile.website,
  ].filter((l) => l.trim() !== '');

  if (profile.name.trim() === '' && profile.logoDataUrl === '' && contactLines.length === 0) {
    return '';
  }

  const logo = profile.logoDataUrl
    ? `<img class="lh-logo" src="${profile.logoDataUrl}" alt="Logo">`
    : '';

  return `
  <header class="letterhead">
    <div class="lh-company">
      <div class="lh-name">${esc(profile.name)}</div>
      <div class="lh-lines">${addressLines.map(esc).join('<br>')}</div>
      <div class="lh-lines">${contactLines.map(esc).join(' · ')}</div>
    </div>
    ${logo}
  </header>`;
}

/** Fußzeile mit Kontaktdaten für jede gedruckte Seite. */
function footer(profile: CompanyProfile): string {
  const parts = [profile.name, profile.street, profile.zipCity, profile.email, profile.phone]
    .filter((p) => p.trim() !== '')
    .map(esc);
  return parts.length > 0 ? `<footer class="pagefoot">${parts.join(' · ')}</footer>` : '';
}

const PRINT_CSS = `
  @page { size: A4; margin: 22mm 20mm; }
  * { box-sizing: border-box; }
  body {
    font-family: 'Iowan Old Style', 'Palatino Linotype', Palatino, Georgia, 'Times New Roman', serif;
    color: #14120e; margin: 0; font-size: 11.5pt; line-height: 1.55; background: #fff;
  }
  .letterhead { display: flex; justify-content: space-between; align-items: flex-start;
    border-bottom: 2.5pt solid #14120e; padding-bottom: 10pt; margin-bottom: 18pt; }
  .lh-name { font-size: 15pt; font-weight: 700; letter-spacing: 0.02em; }
  .lh-lines { font-size: 9pt; color: #444; margin-top: 3pt;
    font-family: ui-monospace, 'Courier New', monospace; }
  .lh-logo { max-height: 52pt; max-width: 160pt; object-fit: contain; }
  h1 { font-size: 17pt; margin: 0 0 12pt; line-height: 1.25;
    border-bottom: 1pt solid #14120e; padding-bottom: 6pt; }
  h2 { font-size: 13pt; margin: 16pt 0 6pt; }
  h3 { font-size: 11.5pt; margin: 12pt 0 4pt; }
  p { margin: 0 0 8pt; }
  ul { margin: 0 0 8pt; padding-left: 16pt; }
  li { margin-bottom: 3pt; }
  blockquote { margin: 10pt 0; padding: 6pt 10pt; border-left: 2.5pt solid #a3271e;
    font-size: 9.5pt; color: #444; }
  table { width: 100%; border-collapse: collapse; margin: 6pt 0 12pt; font-size: 9.5pt; }
  th { text-align: left; border-bottom: 1.5pt solid #14120e; padding: 4pt 6pt;
    font-family: ui-monospace, 'Courier New', monospace; font-size: 8pt;
    text-transform: uppercase; letter-spacing: 0.06em; }
  td { border-bottom: 0.5pt solid #999; padding: 4pt 6pt; vertical-align: top; }
  em { color: #a3271e; font-style: italic; }
  .pagefoot { margin-top: 24pt; padding-top: 6pt; border-top: 0.75pt solid #14120e;
    font-size: 7.5pt; color: #555; font-family: ui-monospace, 'Courier New', monospace; }
`;

/**
 * Öffnet ein Dokument als druckfertige Ansicht mit Firmen-Briefkopf und
 * startet den Druckdialog (PDF via "Als PDF speichern" des Browsers).
 * Alles läuft lokal — keine Server-Roundtrips.
 *
 * @param title - Fenstertitel (wird auch Standard-PDF-Dateiname)
 * @param markdown - Vom Dokumenten-Generator erzeugtes Markdown
 * @param profile - Firmenprofil für Briefkopf und Fußzeile
 */
export function printDocument(title: string, markdown: string, profile: CompanyProfile): void {
  const win = window.open('', '_blank', 'width=900,height=1000');
  if (!win) {
    window.alert('Popup blockiert — bitte Popups für diese Seite erlauben, um drucken zu können.');
    return;
  }
  win.document.write(`<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<title>${esc(title)}</title>
<style>${PRINT_CSS}</style>
</head>
<body>
${letterhead(profile)}
${renderMarkdown(markdown)}
${footer(profile)}
<script>window.addEventListener('load', function () { window.print(); });</script>
</body>
</html>`);
  win.document.close();
}
