/**
 * PDF Exporter — client-side storyboard export
 *
 * Converts a storyboard output to a downloadable PDF using browser's print API.
 * No external dependencies required — works in all modern browsers.
 *
 * TODO: For richer PDF output (custom fonts, layout), consider:
 *   - @react-pdf/renderer
 *   - pdfmake
 *   - jsPDF + html2canvas
 */

import type { StoryboardOutput, StoryboardScene } from "@/types/storyboard";

/**
 * Export storyboard output as a PDF by opening a printable HTML page
 * in a new browser window and triggering the print dialog.
 */
export async function exportStoryboardToPdf(output: StoryboardOutput): Promise<void> {
  if (!output || !output.scenes || output.scenes.length === 0) {
    throw new Error("Storyboard tidak memiliki scene untuk di-export.");
  }

  const printHtml = buildPrintHtml(output);
  const printWindow = window.open("", "_blank");

  if (!printWindow) {
    throw new Error(
      "Popup diblokir browser. Izinkan popup untuk site ini agar dapat mendownload PDF."
    );
  }

  printWindow.document.write(printHtml);
  printWindow.document.close();

  // Wait for content to render before printing
  await new Promise<void>((resolve) => {
    printWindow.onload = () => resolve();
    setTimeout(resolve, 1500); // fallback timeout
  });

  printWindow.focus();
  printWindow.print();
}

function buildSceneHtml(scene: StoryboardScene, idx: number): string {
  return `
    <div class="scene">
      <div class="scene-header">
        <span class="scene-number">Scene ${idx + 1}</span>
        <span class="scene-title">${escHtml(scene.title)}</span>
      </div>
      <div class="scene-description">${escHtml(scene.visualDescription)}</div>
      ${scene.narration ? `<div class="scene-note"><strong>Narasi:</strong> ${escHtml(scene.narration)}</div>` : ""}
      ${scene.cameraAngle ? `<div class="scene-note"><strong>Kamera:</strong> ${escHtml(scene.cameraAngle)}</div>` : ""}
      ${scene.emotion ? `<div class="scene-note"><strong>Emosi:</strong> ${escHtml(scene.emotion)}</div>` : ""}
      ${scene.transition ? `<div class="scene-note"><strong>Transisi:</strong> ${escHtml(scene.transition)}</div>` : ""}
      <div class="scene-duration">⏱ ${escHtml(scene.duration)}</div>
    </div>
  `;
}

function buildPrintHtml(output: StoryboardOutput): string {
  const scenesHtml = output.scenes
    .map((scene, idx) => buildSceneHtml(scene, idx))
    .join("\n");

  return `<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8" />
  <title>Storyboard — ${escHtml(output.sourceTitle ?? "Storyboard")}</title>
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body { font-family: sans-serif; font-size: 12px; color: #111; padding: 24px; }
    h1 { font-size: 20px; margin-bottom: 4px; }
    .subtitle { color: #555; font-size: 12px; margin-bottom: 4px; }
    .meta { color: #888; font-size: 11px; margin-bottom: 20px; }
    .scenes { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
    .scene { border: 1px solid #ddd; border-radius: 6px; padding: 12px; page-break-inside: avoid; }
    .scene-header { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
    .scene-number { background: #111; color: #fff; font-size: 10px; font-weight: bold;
      padding: 2px 6px; border-radius: 3px; white-space: nowrap; }
    .scene-title { font-weight: bold; font-size: 13px; }
    .scene-description { font-size: 11px; line-height: 1.5; margin-bottom: 6px; }
    .scene-note { font-size: 10px; color: #444; margin-top: 4px; }
    .scene-duration { font-size: 10px; color: #888; margin-top: 6px; }
    @media print {
      body { padding: 0; }
      .scenes { grid-template-columns: 1fr 1fr; }
    }
  </style>
</head>
<body>
  <h1>${escHtml(output.sourceTitle ?? "Storyboard")}</h1>
  ${output.theme ? `<div class="subtitle">${escHtml(output.theme)}</div>` : ""}
  <div class="meta">
    ${output.sourcePlatform ? `Platform: ${escHtml(output.sourcePlatform)} · ` : ""}
    ${output.metadata.totalScenes} scene · ${escHtml(output.metadata.estimatedDuration)}
  </div>
  ${output.hook ? `<div class="subtitle"><strong>Hook:</strong> ${escHtml(output.hook)}</div>` : ""}
  <br />
  <div class="scenes">${scenesHtml}</div>
  ${output.callToAction ? `<div style="margin-top:16px;padding:12px;border:1px solid #ddd;border-radius:6px;"><strong>Call to Action:</strong> ${escHtml(output.callToAction)}</div>` : ""}
</body>
</html>`;
}

function escHtml(str: string): string {
  return str
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}
