type PrintHtmlDocumentParams = {
  title: string;
  html: string;
  widthMm?: number;
  styles?: string;
};

const defaultStyles = `
  * { box-sizing: border-box; }
  html, body {
    margin: 0;
    padding: 0;
    background: #fff;
    color: #111;
    font-family: Tahoma, Arial, sans-serif;
    direction: rtl;
  }
  @page {
    size: 80mm auto;
    margin: 4mm;
  }
  .receipt {
    width: 100%;
  }
`;

export const printHtmlDocument = ({
  title,
  html,
  widthMm = 80,
  styles,
}: PrintHtmlDocumentParams): void => {
  if (typeof window === "undefined") return;

  const printWindow = window.open("", "_blank");
  if (!printWindow) return;

  const safeTitle = title.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  const pageStyles = styles ?? defaultStyles.replace("80mm", `${widthMm}mm`);

  const pageHtml = `
    <!doctype html>
    <html lang="fa" dir="rtl">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>${safeTitle}</title>
        <style>${pageStyles}</style>
      </head>
      <body>
        ${html}
      </body>
    </html>
  `;

  printWindow.document.open();
  printWindow.document.write(pageHtml);
  printWindow.document.close();

  const handlePrint = () => {
    printWindow.focus();
    printWindow.print();
    setTimeout(() => {
      printWindow.close();
    }, 200);
  };

  // Some browsers complete loading too fast for onload assignment.
  if (printWindow.document.readyState === "complete") {
    setTimeout(handlePrint, 50);
    return;
  }

  printWindow.addEventListener("load", () => {
    setTimeout(handlePrint, 50);
  }, { once: true });
};
