import jsPDF from "jspdf";
import html2canvas from "html2canvas-pro";

interface ScaleResult {
  scale_name: string;
  percentile: number;
  risk_level: string;
  raw_score?: number;
}

interface GeneratePDFOptions {
  screeningId: string;
  results: ScaleResult[];
  completedAt: string;
  userName?: string;
  suicideRiskCategory?: string;
  t: (key: string) => string;
}

// Map backend scale names (snake_case) to frontend translation keys (camelCase)
const scaleNameMap: Record<string, string> = {
  somatization: "scales.somatization",
  cognitive_issues: "scales.cognitiveIssues",
  demoralization: "scales.demoralization",
  anhedonia: "scales.anhedonia",
  anxiety: "scales.anxiety",
  suicidal_ideation: "scales.suicidalIdeation",
  activation: "scales.activation",
  disconstraint: "scales.disconstraint",
  substance_use_problems: "scales.substanceUseProblems",
};

// Map backend scale names to interpretation key prefix
const interpretationKeyMap: Record<string, string> = {
  somatization: "somatization",
  cognitive_issues: "cognitiveIssues",
  demoralization: "demoralization",
  anhedonia: "anhedonia",
  anxiety: "anxiety",
  suicidal_ideation: "suicidalIdeation",
  activation: "activation",
  disconstraint: "disconstraint",
  substance_use_problems: "substanceUseProblems",
};

// Scale groups for narrative organization
const SCALE_GROUPS = [
  { key: "somaticCognitive", scales: ["somatization", "cognitive_issues"] },
  { key: "internalizing", scales: ["demoralization", "anhedonia", "anxiety", "suicidal_ideation"] },
  { key: "externalizing", scales: ["activation", "disconstraint", "substance_use_problems"] },
];

// Base64 encoded MBHS logo for PDF generation compatibility
const MBHS_LOGO_BASE64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAYAAADimHc4AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAACxLAAAsSwGlPZapAAAAB3RJTUUH6gEBBRIclOky5gAABktJREFUeNrtnUtsVFUYx3/fuWce7fQhoVIiGCEGpEUQRazF+IzBx0IXPhO3xpU7X2DiSrTExJULNT4WLoyJiajRaDQao4b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Z5ADIwMjYtMDEtMDFUMDU6MTg6MTgrMDA6MDBGiffZAAAAIHRFWHRzb2Z0d2FyZQBodHRwczovL2ltYWdlbWFnaWNrLm9yZ7zPHZ0AAAAYdEVYdFRodW1iOjpEb2N1bWVudDo6UGFnZXMAMaf/uy8AAAAYdEVYdFRodW1iOjpJbWFnZTo6SGVpZ2h0ADE5MkBdcVUAAAAXdEVYdFRodW1iOjpJbWFnZTo6V2lkdGgAMTky06whCAAAABl0RVh0VGh1bWI6Ok1pbWV0eXBlAGltYWdlL3BuZz+yVk4AAAAXdEVYdFRodW1iOjpNVGltZQAxNzY3MjQ0Njk4+gKDfAAAAA90RVh0VGh1bWI6OlNpemUAMEJClKI+7AAAAFZ0RVh0VGh1bWI6OlVSSQBmaWxlOi8vL21udGxvZy9mYXZpY29ucy8yMDI2LTAxLTAxLzE0M2IwMzY1MTUzZWE2ZWFiNjQ0MzMyMzNhMzA4OTU1Lmljby5wbmcxdaLQAAAAAElFTkSuQmCC";

/**
 * Generates a PDF from a screening report HTML element using html2canvas.
 * Uses section-aware page breaking to avoid cutting content between pages.
 */
export async function generatePDFFromElement(
  element: HTMLElement,
  _screeningId: string,
  userName?: string
): Promise<void> {
  if (!element) {
    throw new Error("No element provided to generatePDFFromElement");
  }

  const canvasScale = 2;
  const targetWidth = 1000;

  // Create an off-screen clone at a fixed 800px width.
  // This ensures the canvas capture and the break-point positions
  // are computed from the same element, so page breaks align correctly.
  const wrapper = document.createElement("div");
  wrapper.style.cssText = `position:absolute;left:-9999px;top:0;width:${targetWidth}px;background:#fff;`;
  document.body.appendChild(wrapper);

  const clone = element.cloneNode(true) as HTMLElement;
  clone.style.width = `${targetWidth}px`;
  clone.style.maxWidth = `${targetWidth}px`;
  clone.style.boxSizing = "border-box";
  wrapper.appendChild(clone);

  // Wait for layout to settle (images, fonts)
  await new Promise((resolve) => setTimeout(resolve, 500));

  // Scroll to top so getBoundingClientRect values are viewport-accurate (top=0 means doc top).
  // Must do this BEFORE collecting break points AND before html2canvas capture.
  const savedScrollX = window.scrollX;
  const savedScrollY = window.scrollY;
  window.scrollTo(0, 0);
  await new Promise((resolve) => setTimeout(resolve, 50));

  // Wider page to match 1000px render (maintains same text size as original 800px/A4)
  const pdfWidth = 257;
  const pdfHeight = 297;
  const margin = 10;
  const availableWidth = pdfWidth - margin * 2;
  const availableHeight = pdfHeight - margin * 2;

  // canvas width = targetWidth * canvasScale (known before capture)
  const imgWidthPx = targetWidth * canvasScale;
  const ratio = availableWidth / imgWidthPx; // mm per canvas pixel
  const pageHeightPx = availableHeight / ratio; // available height in canvas pixels

  // Collect section break points WHILE clone is still attached to the DOM so that
  // getBoundingClientRect returns real layout positions (scroll is 0 so top = doc offset).
  // offsetParent traversal was previously used here but is broken when the wrapper is
  // position:absolute — offsetParent skips clone entirely, returning wrong values.
  const sectionElements = clone.querySelectorAll("[data-pdf-section]");
  const rawBreakPoints: number[] = [];
  const cloneRect = clone.getBoundingClientRect();

  sectionElements.forEach((el) => {
    const rect = (el as HTMLElement).getBoundingClientRect();
    const yPx = Math.round((rect.top - cloneRect.top) * canvasScale);
    if (yPx > 0) rawBreakPoints.push(yPx);
  });

  let canvas: HTMLCanvasElement;
  try {
    canvas = await html2canvas(clone, {
      scale: canvasScale,
      useCORS: true,
      allowTaint: true,
      backgroundColor: "#ffffff",
      logging: false,
      scrollX: 0,
      scrollY: 0,
    });
  } finally {
    document.body.removeChild(wrapper);
    window.scrollTo(savedScrollX, savedScrollY);
  }

  const imgHeightPx = canvas.height;

  // Filter to valid range now that we know actual canvas height
  const breakPoints = rawBreakPoints.filter((yPx) => yPx < imgHeightPx);

  // Sort and deduplicate
  const uniqueBreakPoints = [...new Set(breakPoints)].sort((a, b) => a - b);

  // Build page slices by finding the best break point near each page boundary
  const pages: { startY: number; endY: number }[] = [];
  let currentY = 0;

  while (currentY < imgHeightPx) {
    const idealEnd = currentY + pageHeightPx;

    // If remaining content fits on one page, take it all
    if (idealEnd >= imgHeightPx) {
      pages.push({ startY: currentY, endY: imgHeightPx });
      break;
    }

    // Find the last break point that fits within this page
    // Use a 40px safety margin so sections starting very near the page edge
    // are pushed to the next page instead of being clipped.
    const safeEnd = idealEnd - 40;
    let bestBreak = -1;
    for (const bp of uniqueBreakPoints) {
      if (bp <= currentY) continue;
      if (bp <= safeEnd) {
        bestBreak = bp;
      } else {
        break; // sorted, no need to check further
      }
    }

    if (bestBreak > currentY) {
      // Use the section boundary as break point
      pages.push({ startY: currentY, endY: bestBreak });
      currentY = bestBreak;
    } else {
      // No suitable break point found, use fixed height
      pages.push({ startY: currentY, endY: Math.min(idealEnd, imgHeightPx) });
      currentY = Math.min(idealEnd, imgHeightPx);
    }
  }

  // Ensure at least one page
  if (pages.length === 0) {
    pages.push({ startY: 0, endY: imgHeightPx });
  }

  // Create PDF and render each page slice
  const pdf = new jsPDF({
    orientation: "portrait",
    unit: "mm",
    format: [pdfWidth, pdfHeight],
    compress: true,
  });

  for (let i = 0; i < pages.length; i++) {
    if (i > 0) pdf.addPage();

    const { startY, endY } = pages[i];
    const sliceH = endY - startY;
    if (sliceH <= 0) continue;

    const sliceHeightMm = sliceH * ratio;

    // Create canvas for this page slice
    const sliceCanvas = document.createElement("canvas");
    sliceCanvas.width = imgWidthPx;
    sliceCanvas.height = Math.ceil(sliceH);
    const ctx = sliceCanvas.getContext("2d");
    if (!ctx) continue;

    // White background
    ctx.fillStyle = "#ffffff";
    ctx.fillRect(0, 0, sliceCanvas.width, sliceCanvas.height);

    // Draw the slice from captured canvas
    ctx.drawImage(
      canvas,
      0, startY, imgWidthPx, sliceH,
      0, 0, imgWidthPx, Math.ceil(sliceH)
    );

    const sliceData = sliceCanvas.toDataURL("image/png");
    pdf.addImage(
      sliceData,
      "PNG",
      margin,
      margin,
      availableWidth,
      sliceHeightMm,
      undefined,
      "FAST"
    );
  }

  const now = new Date();
  const timestamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}_${String(now.getHours()).padStart(2, "0")}${String(now.getMinutes()).padStart(2, "0")}${String(now.getSeconds()).padStart(2, "0")}${String(now.getMilliseconds()).padStart(3, "0")}`;
  const safeName = userName ? `-${userName.replace(/[^a-zA-Z0-9]/g, "_")}` : "";
  pdf.save(`MBHS-Report${safeName}_${timestamp}.pdf`);
}

/**
 * Creates a report HTML structure and generates PDF
 * Used for generating PDFs without rendering the report page
 */
export async function generateScreeningPDF(
  options: GeneratePDFOptions
): Promise<void> {
  const { screeningId, results, completedAt, userName, suicideRiskCategory, t } = options;

  if (!results || results.length === 0) {
    throw new Error("No results available to generate PDF");
  }

  // Create a temporary container for the report
  const container = document.createElement("div");
  container.style.position = "absolute";
  container.style.left = "-9999px";
  container.style.top = "0";
  container.style.width = "800px";
  container.style.backgroundColor = "#ffffff";
  document.body.appendChild(container);

  try {
    // Format date
    const formatDate = (dateString: string) => {
      const date = new Date(dateString);
      return date.toLocaleDateString("en-GB", {
        day: "numeric",
        month: "short",
        year: "numeric",
      });
    };

    // Use API-provided suicide risk category
    const getRiskLevel = () => {
      const normalized = (suicideRiskCategory || "").toLowerCase();
      if (normalized.includes("high"))
        return { level: t("results.riskHigh"), textColor: "#DC2626", bgColor: "#FEF2F2" };
      if (normalized.includes("moderate"))
        return { level: t("results.riskModerate"), textColor: "#DC2626", bgColor: "#FEF2F2" };
      if (normalized.includes("mild"))
        return { level: t("results.riskMild"), textColor: "#D97706", bgColor: "#FFFBEB" };
      if (normalized.includes("low"))
        return { level: t("results.riskLow"), textColor: "#16A34A", bgColor: "#F0FDF4" };
      return { level: t("results.riskLow"), textColor: "#16A34A", bgColor: "#F0FDF4" };
    };

    const riskInfo = getRiskLevel();

    // Build the HTML structure matching the report page
    container.innerHTML = `
      <div style="background: white; padding: 32px; max-width: 800px; margin: 0 auto; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;">
        <!-- Report Header -->
        <div data-pdf-section="header" style="display: flex; align-items: flex-start; justify-content: space-between; margin-bottom: 24px;">
          <div style="display: flex; align-items: center; gap: 12px;">
            <img src="${MBHS_LOGO_BASE64}" alt="MBHS" style="width: 48px; height: 48px; border-radius: 8px;" />
            <div>
              <h1 style="font-size: 24px; font-weight: 700; color: #111827; margin: 0; line-height: 1.2;">MBHS</h1>
              <p style="font-size: 12px; color: #6B7280; margin: 4px 0 0 0;">Multidimensional Behavioral Health Screen</p>
            </div>
          </div>
          <p style="font-size: 14px; color: #4B5563; margin: 0;">Date: ${formatDate(completedAt)}</p>
        </div>

        ${userName ? `<p style="font-size: 14px; font-weight: 500; color: #374151; margin: 0 0 8px 0;">${userName}</p>` : ""}
        <p style="font-size: 14px; color: #4B5563; margin: 0 0 24px 0;">
          ${t("results.reportTitle")}
        </p>

        <div style="margin-bottom: 32px;"></div>

        <!-- Your Results at a Glance -->
        <div data-pdf-section="results-glance" style="margin-bottom: 32px;">
          <h2 style="font-size: 20px; font-weight: 600; color: #111827; margin: 0 0 12px 0;">
            ${t("results.resultsGlance")}
          </h2>
          <p style="font-size: 14px; color: #4B5563; margin: 0 0 16px 0;">
            ${t("results.resultsDescription")}
          </p>
          <div style="background: #F8FAFC; border-radius: 12px; padding: 16px;">
            <p style="font-size: 14px; color: #4B5563; margin: 0 0 4px 0;">
              <span style="font-weight: 600; color: #334155;">${t("results.percentile50")}</span> = ${t("results.averageRange")}
            </p>
            <p style="font-size: 14px; color: #4B5563; margin: 0;">
              <span style="font-weight: 600; color: #334155;">${t("results.percentile66")}</span> = ${t("results.warrantAttention")}
            </p>
          </div>
        </div>

        <!-- Detailed Results by Scale -->
        <div data-pdf-section="detailed-results">
          <h2 style="font-size: 20px; font-weight: 600; color: #111827; margin: 0 0 16px 0;">
            ${t("results.detailedResults")}
          </h2>
          <div style="background: #F9FAFB; border-radius: 12px; padding: 24px;">
            <!-- Scale Headers -->
            <div style="display: flex; align-items: center; margin-bottom: 16px;">
              <div style="width: 160px;"></div>
              <div style="width: 40px; font-size: 10px; color: #9CA3AF; text-align: center;">RS</div>
              <div style="flex: 1; display: flex; font-size: 12px; color: #6B7280;">
                <div style="flex: 1;"></div>
                <div style="width: 96px; text-align: center; line-height: 1.4;">
                  ${t("results.averageScore")}<br />(${t("results.percentile50")})
                </div>
                <div style="width: 96px; text-align: center; line-height: 1.4;">
                  ${t("results.clinicalThreshold")}<br />(${t("results.percentile66")})
                </div>
              </div>
            </div>

            <!-- Scale Bars -->
            <div style="display: flex; flex-direction: column; gap: 16px;">
              ${results
                .map((result, index) => {
                  // Color based on row position
                  const getBarColor = () => {
                    if (index < 3) return "#00B0F0";
                    if (index < 6) return "#0070C0";
                    return "#7030A0";
                  };

                  const translationKey =
                    scaleNameMap[result.scale_name] || result.scale_name;
                  const scaleName = t(translationKey);

                  return `
                  <div data-pdf-section="scale-${result.scale_name}" style="display: flex; align-items: center; margin-bottom: 8px;">
                    <div style="width: 160px; font-size: 14px; font-weight: 500; color: #374151; padding-right: 16px;">
                      ${scaleName}
                    </div>
                    <div style="width: 40px; font-size: 11px; color: #9CA3AF; text-align: center;">
                      ${result.raw_score != null ? result.raw_score : "-"}
                    </div>
                    <div style="flex: 1; position: relative;">
                      <!-- Background bar -->
                      <div style="height: 28px; background: #E5E7EB; border-radius: 2px; position: relative; overflow: hidden;">
                        <!-- Filled bar -->
                        <div style="position: absolute; left: 0; top: 0; height: 100%; border-radius: 2px; display: flex; align-items: center; justify-content: flex-end; padding-right: 8px; background: ${getBarColor()}; width: ${result.percentile}%;">
                          <span style="font-size: 12px; font-weight: 600; color: white;">
                            ${Math.round(result.percentile)}%
                          </span>
                        </div>
                        <!-- 50th percentile marker -->
                        <div style="position: absolute; top: 0; bottom: 0; width: 1px; background: #6B7280; left: 50%;"></div>
                        <!-- 66th percentile marker -->
                        <div style="position: absolute; top: 0; bottom: 0; width: 1px; background: #374151; left: 66%;"></div>
                      </div>
                      <!-- Scale labels -->
                      <div style="position: relative; display: flex; font-size: 12px; color: #9CA3AF; margin-top: 4px;">
                        <span>0</span>
                        <span style="position: absolute; left: 50%; transform: translateX(-50%);">50</span>
                        <span style="position: absolute; left: 66%; transform: translateX(-50%);">66</span>
                      </div>
                    </div>
                  </div>
                `;
                })
                .join("")}
            </div>
          </div>
        </div>

        <!-- Suicide Risk Classification -->
        <div data-pdf-section="suicide-risk" style="background: ${riskInfo.bgColor}; border-radius: 12px; padding: 24px; margin-top: 32px; margin-bottom: 32px;">
          <h2 style="font-size: 14px; font-weight: 700; color: #111827; text-transform: uppercase; letter-spacing: 0.05em; margin: 0 0 12px 0;">
            ${t("results.suicideRiskTitle")}
          </h2>
          <span style="display: inline-flex; align-items: center; justify-content: center; height: 36px; padding: 0 16px; font-size: 14px; font-weight: 600; color: ${riskInfo.textColor}; background: #F3F4F6; border-radius: 9999px; margin-bottom: 12px;">
            ${t("results.riskCategory")} ${riskInfo.level}
          </span>
          <p style="font-size: 14px; color: #374151; margin: 0;">
            ${t("results.riskDisclaimer")}
          </p>
        </div>

        <!-- Scale Interpretations -->
        <div data-pdf-section="interpretations-header" style="margin-top: 32px;">
          <h2 style="font-size: 20px; font-weight: 600; color: #111827; margin: 0 0 16px 0;">
            ${t("results.interpretationsTitle")}
          </h2>
          ${SCALE_GROUPS.map((group) => {
            const groupResults = group.scales
              .map((scaleName) => results.find((r) => r.scale_name === scaleName))
              .filter(Boolean) as ScaleResult[];
            if (groupResults.length === 0) return "";
            return `
            <div style="margin-bottom: 24px;">
              <h3 style="font-size: 16px; font-weight: 600; color: #1F2937; margin: 0 0 12px 0; padding-bottom: 4px; border-bottom: 1px solid #E5E7EB;">
                ${t(`results.scaleGroups.${group.key}`)}
              </h3>
              <div style="display: flex; flex-direction: column; gap: 20px;">
                ${groupResults.map((result) => {
                  const translationKey = scaleNameMap[result.scale_name] || result.scale_name;
                  const scaleName = t(translationKey);
                  const interpKey = interpretationKeyMap[result.scale_name] || result.scale_name;
                  const isElevated = result.percentile >= 66;
                  return `
                  <div data-pdf-section="interpretation-${result.scale_name}" style="${isElevated ? "border-left: 4px solid #3B9EC9; padding-left: 16px;" : "padding-left: 16px;"}">
                    <h4 style="font-size: 14px; font-weight: 700; color: #111827; margin: 0 0 4px 0;">
                      ${scaleName} - ${isElevated ? t("results.elevated") : t("results.notElevated")}
                    </h4>
                    <p style="font-size: 13px; color: #4B5563; margin: 0 0 4px 0; line-height: 1.6;">
                      ${t(`results.interpretations.${interpKey}Description`)}
                    </p>
                    <p style="font-size: 13px; ${isElevated ? "color: #1F2937; font-weight: 500;" : "color: #4B5563;"} margin: 0; line-height: 1.6;">
                      ${isElevated
                        ? t(`results.interpretations.${interpKey}`)
                        : t(`results.interpretations.${interpKey}NotElevated`)}
                    </p>
                  </div>`;
                }).join("")}
              </div>
            </div>`;
          }).join("")}
        </div>

        <!-- Recommended Next Steps -->
        <div data-pdf-section="next-steps" style="margin-top: 32px; background: #F0F9FF; border: 2px solid #3B9EC9; border-radius: 12px; padding: 24px;">
          <h2 style="font-size: 18px; font-weight: 700; color: #111827; margin: 0 0 12px 0;">
            ${t("results.nextSteps.title")}
          </h2>
          <p style="font-size: 14px; color: #4B5563; margin: 0 0 16px 0;">
            ${t("results.nextSteps.intro")}
          </p>
          <div style="display: flex; flex-direction: column; gap: 8px;">
            <div style="display: flex; align-items: flex-start; gap: 8px; font-size: 14px; color: #374151;">
              <span style="margin-top: 6px; width: 6px; height: 6px; background: #6B7280; border-radius: 50%; flex-shrink: 0;"></span>
              ${t("results.nextSteps.bullet1")}
            </div>
            <div style="display: flex; align-items: flex-start; gap: 8px; font-size: 14px; color: #374151;">
              <span style="margin-top: 6px; width: 6px; height: 6px; background: #6B7280; border-radius: 50%; flex-shrink: 0;"></span>
              ${t("results.nextSteps.bullet2")}
            </div>
            <div style="display: flex; align-items: flex-start; gap: 8px; font-size: 14px; color: #374151;">
              <span style="margin-top: 6px; width: 6px; height: 6px; background: #6B7280; border-radius: 50%; flex-shrink: 0;"></span>
              ${t("results.nextSteps.bullet3")}
            </div>
          </div>
        </div>

        <!-- Single-Session Support Option -->
        <div data-pdf-section="single-session" style="margin-top: 32px; background: #F9FAFB; border-radius: 12px; padding: 24px;">
          <h2 style="font-size: 18px; font-weight: 700; color: #111827; margin: 0 0 12px 0;">
            ${t("results.singleSession.title")}
          </h2>
          <p style="font-size: 14px; color: #4B5563; margin: 0;">
            ${t("results.singleSession.description")}
          </p>
        </div>

        <!-- Important Information -->
        <div data-pdf-section="important-info" style="margin-top: 32px;">
          <h2 style="font-size: 18px; font-weight: 700; color: #111827; margin: 0 0 12px 0;">
            ${t("results.importantInfo.title")}
          </h2>
          <div style="display: flex; flex-direction: column; gap: 8px;">
            <div style="display: flex; align-items: flex-start; gap: 8px; font-size: 14px; color: #4B5563;">
              <span style="margin-top: 6px; width: 6px; height: 6px; background: #9CA3AF; border-radius: 50%; flex-shrink: 0;"></span>
              ${t("results.importantInfo.bullet1")}
            </div>
            <div style="display: flex; align-items: flex-start; gap: 8px; font-size: 14px; color: #4B5563;">
              <span style="margin-top: 6px; width: 6px; height: 6px; background: #9CA3AF; border-radius: 50%; flex-shrink: 0;"></span>
              ${t("results.importantInfo.bullet2")}
            </div>
            <div style="display: flex; align-items: flex-start; gap: 8px; font-size: 14px; color: #4B5563;">
              <span style="margin-top: 6px; width: 6px; height: 6px; background: #9CA3AF; border-radius: 50%; flex-shrink: 0;"></span>
              ${t("results.importantInfo.bullet3")}
            </div>
            <div style="display: flex; align-items: flex-start; gap: 8px; font-size: 14px; color: #4B5563;">
              <span style="margin-top: 6px; width: 6px; height: 6px; background: #9CA3AF; border-radius: 50%; flex-shrink: 0;"></span>
              ${t("results.importantInfo.bullet4")}
            </div>
          </div>
        </div>

        <!-- Footer -->
        <div data-pdf-section="footer" style="margin-top: 40px; padding-top: 24px; border-top: 1px solid #E5E7EB; text-align: center;">
          <p style="font-size: 14px; font-weight: 500; color: #374151; margin: 0;">
            ${t("results.footer.version")}
          </p>
          <p style="font-size: 12px; color: #6B7280; margin: 4px 0 0 0;">
            ${t("results.footer.copyright")}
          </p>
        </div>
      </div>
    `;

    // Wait for DOM to be fully ready
    await new Promise((resolve) => setTimeout(resolve, 300));

    // Generate PDF from the container
    const reportElement = container.firstElementChild as HTMLElement;

    if (!reportElement) {
      throw new Error("Failed to create report element");
    }

    await generatePDFFromElement(reportElement, screeningId, userName);
  } finally {
    // Clean up
    if (container && container.parentNode) {
      document.body.removeChild(container);
    }
  }
}
