// Export orchestration: assembles the three page types (room chart, guest
// list — sortable by name or by table — and table pages; see the export*.ts
// files) into the preview and the downloadable PDF, plus the export panel's
// setters and its mode switch (PDF, or sharing with guests — share.ts).

const renderExportPageSvg = (
  pageWidthMm: number,
  pageHeightMm: number,
  content: string,
): string => `
    <svg
      width="${pageWidthMm}mm"
      height="${pageHeightMm}mm"
      viewBox="0 0 ${pageWidthMm} ${pageHeightMm}"
      font-family="${EXPORT_FONTS.body.family}"
      xmlns="http://www.w3.org/2000/svg">
      <rect x="0" y="0" width="${pageWidthMm}" height="${pageHeightMm}" fill="white" />
      ${content}
      ${exportSettings.showWatermark ? renderExportWatermarkSvg(pageWidthMm, pageHeightMm) : ""}
      ${isPdfUnlocked() ? "" : renderPreviewStampSvg(pageWidthMm, pageHeightMm)}
    </svg>
  `;

// All export pages in order: the room chart, the guest list (its first
// placement, then any name-mode continuation pages), and one page per table.
// When combining, the chart takes half of page 1 and the guest list fills
// the other half — in name mode, spilling overflow onto full pages after;
// in table mode, the whole list always fits that one placement (see
// renderGuestListByTableSvg).
const getExportPageSvgs = (): string[] => {
  const { width: pageWidthMm, height: pageHeightMm } = getExportPageSizeMm(
    exportSettings.orientation,
  );
  const fullPage: PageRegion = { x: 0, y: 0, width: pageWidthMm, height: pageHeightMm };
  const pages: string[] = [];

  const showGuestList = exportSettings.showGuestList;
  let remainingNameEntries =
    showGuestList && exportSettings.guestListSortMode === "name" ? getGuestListEntries() : [];
  const tablesWithGuests =
    (showGuestList && exportSettings.guestListSortMode === "table") || exportSettings.showTablePages
      ? getTablesWithGuests()
      : [];

  if (exportSettings.showRoom) {
    if (exportSettings.combineRoomAndList) {
      const isPortrait = exportSettings.orientation === "portrait";
      const roomRegion: PageRegion = isPortrait
        ? { x: 0, y: 0, width: pageWidthMm, height: pageHeightMm / 2 }
        : { x: 0, y: 0, width: pageWidthMm / 2, height: pageHeightMm };
      const listRegion: PageRegion = isPortrait
        ? {
            x: 0,
            y: pageHeightMm / 2 - getExportPageMarginMm(),
            width: pageWidthMm,
            height: pageHeightMm / 2 + getExportPageMarginMm(),
          }
        : {
            x: pageWidthMm / 2 - getExportPageMarginMm(),
            y: 0,
            width: pageWidthMm / 2 + getExportPageMarginMm(),
            height: pageHeightMm,
          };

      let listSvg = "";
      if (showGuestList) {
        const result = renderGuestListSvg(listRegion, tablesWithGuests, remainingNameEntries);
        listSvg = result.svg;
        remainingNameEntries = result.remainingNameEntries;
      }
      const combinedContent = renderRoomChartSvg(roomRegion) + listSvg;
      pages.push(renderExportPageSvg(pageWidthMm, pageHeightMm, combinedContent));
    } else {
      pages.push(renderExportPageSvg(pageWidthMm, pageHeightMm, renderRoomChartSvg(fullPage)));
    }
  }

  // The list gets exactly one "first placement": combined with the room
  // above, or (if that didn't happen) its own full page here.
  const listAlreadyPlaced = exportSettings.showRoom && exportSettings.combineRoomAndList;
  if (showGuestList && !listAlreadyPlaced) {
    const result = renderGuestListSvg(fullPage, tablesWithGuests, remainingNameEntries);
    remainingNameEntries = result.remainingNameEntries;
    pages.push(renderExportPageSvg(pageWidthMm, pageHeightMm, result.svg));
  }

  // Continuation pages: name mode only — table mode never paginates, it
  // always fit entirely into its one placement above.
  if (showGuestList && exportSettings.guestListSortMode === "name") {
    const layout = getGuestListColumnLayout(fullPage, exportSettings.guestListColumns);
    for (let i = 0; i < remainingNameEntries.length; i += layout.entriesPerRegion) {
      const pageEntries = remainingNameEntries.slice(i, i + layout.entriesPerRegion);
      const content = renderGuestListEntriesSvg(pageEntries, layout, fullPage);
      pages.push(renderExportPageSvg(pageWidthMm, pageHeightMm, content));
    }
  }

  if (exportSettings.showTablePages) {
    for (const entry of tablesWithGuests) {
      const content = renderTablePageSvg(entry, pageWidthMm, pageHeightMm);
      pages.push(renderExportPageSvg(pageWidthMm, pageHeightMm, content));
    }
  }

  return pages;
};

// The stamp probe width (exportShared.ts) reflects whatever font was live
// when it was measured; once webfonts finish loading, invalidate it and
// refresh a visible preview. Subscribed HERE because the callback needs
// this file's exportPreviewVisible/updateExportPreview: fonts.ready can
// resolve in the gap between script files (fonts already cached), and a
// subscription made in an earlier file would then fire before they exist.
// exportPreviewVisible stays false until the overlay opens, so the guarded
// call can't touch later files' globals early either.
document.fonts?.ready.then(() => {
  previewStampProbeWidthMm = undefined;
  exportTextWidthCache.clear();
  if (exportPreviewVisible) updateExportPreview();
});

// Suspended while syncExportPanelFromSettings replays every setter, so a
// restore triggers one preview rebuild instead of ~30.
let exportPreviewUpdatesSuspended = false;

// Redraws whichever preview is on screen: the PDF pages, or in share mode
// the guests' page (share.ts), which the chart and header options also
// change. The pages are rendered again when the mode switches back.
const updateExportPreview = () => {
  if (exportPreviewUpdatesSuspended) return;
  if (exportPanelMode !== "pdf") {
    updateGuestPagePreview();
    return;
  }
  const landscapeClass = exportSettings.orientation === "landscape" ? " landscape" : "";
  const pagesHtml = getExportPageSvgs()
    .map((svg) => `<div class="exportPage${landscapeClass}">${svg}</div>`)
    .join("");
  $("#exportPages").html(pagesHtml);
};

// Reflects the current exportSettings into the export panel's controls —
// the counterpart of the setters below, for when settings arrive from data
// (the persistence restore) instead of from the user. Inputs get their
// value/checked state here; each setter then reapplies its own dependent UI
// (selected-tool classes, value labels, slider fills, hidden sections).
const syncExportPanelFromSettings = () => {
  const setInput = (inputId: string, value: string | number) => $(`#${inputId}`).val(String(value));
  const setCheckbox = (inputId: string, checked: boolean) =>
    $(`#${inputId}`).prop("checked", checked);
  const s = exportSettings;

  exportPreviewUpdatesSuspended = true;
  try {
    setExportOrientation(s.orientation);
    setInput("exportPageMarginSlider", s.pageMarginMm);
    setExportPageMarginMm(s.pageMarginMm);
    setCheckbox("exportShowWatermarkCheckbox", s.showWatermark);
    setCheckbox("exportShowRoomCheckbox", s.showRoom);
    setExportShowRoom(s.showRoom);
    setCheckbox("exportCombineRoomAndListCheckbox", s.combineRoomAndList);
    setCheckbox("exportShowColorsCheckbox", s.showColors);
    setCheckbox("exportShowTableLabelsCheckbox", s.showTableLabels);
    setCheckbox("exportShowChairNumbersCheckbox", s.showChairNumbers);
    setCheckbox("exportGlobalChairNumbersCheckbox", s.globalChairNumbers);
    setCheckbox("exportShowGuestNamesCheckbox", s.showGuestNames);
    setExportShowGuestNames(s.showGuestNames);
    setCheckbox("exportWrapGuestNamesCheckbox", s.wrapGuestNames);
    setExportTableBorderRadius(s.tableBorderRadius);
    setExportChairStyle(s.chairStyle);
    setInput("exportTableLabelFontSizeSlider", s.tableLabelFontSizeMm);
    setExportTableLabelFontSizeMm(s.tableLabelFontSizeMm);
    setInput("exportChairTextFontSizeSlider", s.chairTextFontSizeMm);
    setExportChairTextFontSizeMm(s.chairTextFontSizeMm);
    setInput("exportRoomRotationSlider", s.roomRotation);
    setExportRoomRotation(s.roomRotation);
    setInput("exportRoomScaleSlider", s.roomScale);
    setExportRoomScale(s.roomScale);
    setCheckbox("exportShowGuestListCheckbox", s.showGuestList);
    setExportShowGuestList(s.showGuestList);
    setCheckbox("exportShowGuestListHeaderCheckbox", s.showGuestListHeader);
    setExportShowGuestListHeader(s.showGuestListHeader);
    setInput("exportGuestListHeaderTitleInput", s.guestListHeaderTitle);
    setInput("exportGuestListHeaderDateInput", s.guestListHeaderDate);
    setInput("exportGuestListHeaderNamesInput", s.guestListHeaderNames);
    setInput("exportGuestListHeaderScaleSlider", s.guestListHeaderScale);
    setExportGuestListHeaderScale(s.guestListHeaderScale);
    setExportGuestListSortMode(s.guestListSortMode);
    setCheckbox("exportGuestListColors", s.guestListShowColors);
    setCheckbox("exportListShowTableLabelsCheckbox", s.guestListShowTableLabels);
    setCheckbox("exportListShowChairNumbersCheckbox", s.guestListShowChairNumbers);
    setInput("exportGuestListFontSizeSlider", s.guestListFontSizeMm);
    setExportGuestListFontSizeMm(s.guestListFontSizeMm);
    setInput("exportGuestListColumns", s.guestListColumns);
    setInput("exportGuestListTableTitlePrefixInput", s.guestListTableTitlePrefix);
    setCheckbox("exportShowTablePagesCheckbox", s.showTablePages);
    setExportShowTablePages(s.showTablePages);
    setInput("exportTablePageTitlePrefixInput", s.tablePageTitlePrefix);
    setInput("exportShareTablePrefixInput", s.tablePageTitlePrefix);
  } finally {
    exportPreviewUpdatesSuspended = false;
  }
  updateExportPreview();
};

// --- Export panel setters (called from inline handlers in index.php) ---

// One segment of a segmented control (.segmented, styles.css).
const setExportToolSelected = (elementId: string, selected: boolean) => {
  const element = document.getElementById(elementId);
  if (element) setToolSelected(element, selected);
};

// Chrome/Safari/Edge fake the slider's filled portion with a gradient (see
// styles.css) that can't compute value/max itself, so it's set here.
const setExportSliderProgress = (sliderId: string, fraction: number) => {
  $(`#${sliderId}`).css("--range-progress", `${fraction * 100}%`);
};

const setExportOrientation = (orientation: ExportOrientation) => {
  exportSettings.orientation = orientation;
  setExportToolSelected("exportOrientationPortrait", orientation === "portrait");
  setExportToolSelected("exportOrientationLandscape", orientation === "landscape");
  updateExportPreview();
};

const setExportPageMarginMm = (value: string | number) => {
  exportSettings.pageMarginMm = Math.min(50, Math.max(10, Number(value)));
  $("#exportPageMarginValue").text(`${exportSettings.pageMarginMm.toFixed(1)}mm`);
  setExportSliderProgress("exportPageMarginSlider", (exportSettings.pageMarginMm - 10) / 40);
  updateExportPreview();
};

const setExportShowWatermark = (value: boolean) => {
  exportSettings.showWatermark = value;
  updateExportPreview();
};

const setExportShowRoom = (value: boolean) => {
  exportSettings.showRoom = value;
  updateExportSectionVisibility();
  updateExportPreview();
};

const setExportCombineRoomAndList = (value: boolean) => {
  exportSettings.combineRoomAndList = value;
  updateExportPreview();
};

const setExportShowColors = (value: boolean) => {
  exportSettings.showColors = value;
  updateExportPreview();
};

const setExportRoomRotation = (value: string | number) => {
  exportSettings.roomRotation = Number(value);
  $("#exportRoomRotationValue").text(`${exportSettings.roomRotation}°`);
  setExportSliderProgress("exportRoomRotationSlider", exportSettings.roomRotation / 360);
  updateExportPreview();
};

const setExportRoomScale = (value: string | number) => {
  exportSettings.roomScale = Math.min(2, Math.max(0, Number(value)));
  $("#exportRoomScaleValue").text(`${exportSettings.roomScale.toFixed(2)}x`);
  setExportSliderProgress("exportRoomScaleSlider", exportSettings.roomScale / 2);
  updateExportPreview();
};

const setExportShowTableLabels = (value: boolean) => {
  exportSettings.showTableLabels = value;
  updateExportPreview();
};

const setExportTableLabelFontSizeMm = (value: string | number) => {
  exportSettings.tableLabelFontSizeMm = Math.min(48, Math.max(8, Number(value)));
  $("#exportTableLabelFontSizeValue").text(`${exportSettings.tableLabelFontSizeMm.toFixed(1)}mm`);
  setExportSliderProgress(
    "exportTableLabelFontSizeSlider",
    (exportSettings.tableLabelFontSizeMm - 8) / 40,
  );
  updateExportPreview();
};

const setExportTableBorderRadius = (value: number) => {
  exportSettings.tableBorderRadius = value;
  setExportToolSelected("exportTableBorderRadius", value !== 0);
  setExportToolSelected("exportTableBorderRadiusNone", value === 0);
  updateExportPreview();
};

const setExportChairStyle = (value: ExportChairStyle) => {
  exportSettings.chairStyle = value;
  setExportToolSelected("exportChairStyleBig", value === "big");
  setExportToolSelected("exportChairStyleSmall", value === "small");
  setExportToolSelected("exportChairStyleNone", value === "none");
  updateExportPreview();
};

const setExportShowChairNumbers = (value: boolean) => {
  exportSettings.showChairNumbers = value;
  updateExportPreview();
};

const setExportGlobalChairNumbers = (value: boolean) => {
  exportSettings.globalChairNumbers = value;
  updateExportPreview();
};

const setExportShowGuestNames = (value: boolean) => {
  exportSettings.showGuestNames = value;
  // Wrapping only means something when names are drawn.
  $("#exportWrapGuestNamesRow").prop("hidden", !value);
  updateExportPreview();
};

const setExportChairTextFontSizeMm = (value: string | number) => {
  exportSettings.chairTextFontSizeMm = Math.min(32, Math.max(8, Number(value)));
  $("#exportChairTextFontSizeValue").text(`${exportSettings.chairTextFontSizeMm.toFixed(1)}mm`);
  setExportSliderProgress(
    "exportChairTextFontSizeSlider",
    (exportSettings.chairTextFontSizeMm - 8) / 24,
  );
  updateExportPreview();
};

const setExportWrapGuestNames = (value: boolean) => {
  exportSettings.wrapGuestNames = value;
  updateExportPreview();
};

const setExportShowGuestList = (value: boolean) => {
  exportSettings.showGuestList = value;
  updateExportSectionVisibility();
  updateExportPreview();
};

const setExportGuestListSortMode = (mode: GuestListSortMode) => {
  exportSettings.guestListSortMode = mode;
  setExportToolSelected("exportGuestListSortName", mode === "name");
  setExportToolSelected("exportGuestListSortTable", mode === "table");
  $("#exportGuestListNameModeSettings").prop("hidden", mode !== "name");
  $("#exportGuestListTableModeSettings").prop("hidden", mode !== "table");
  updateExportPreview();
};

const setExportShowGuestListHeader = (value: boolean) => {
  exportSettings.showGuestListHeader = value;
  updateExportSectionVisibility();
  updateExportPreview();
};

const setExportGuestListHeaderTitle = (value: string) => {
  exportSettings.guestListHeaderTitle = value;
  updateExportPreview();
};

const setExportGuestListHeaderDate = (value: string) => {
  exportSettings.guestListHeaderDate = value;
  updateExportPreview();
};

const setExportGuestListHeaderNames = (value: string) => {
  exportSettings.guestListHeaderNames = value;
  updateExportPreview();
};

const setExportGuestListHeaderScale = (value: string | number) => {
  exportSettings.guestListHeaderScale = Math.min(2, Math.max(0.5, Number(value)));
  $("#exportGuestListHeaderScaleValue").text(`${exportSettings.guestListHeaderScale.toFixed(2)}x`);
  setExportSliderProgress(
    "exportGuestListHeaderScaleSlider",
    (exportSettings.guestListHeaderScale - 0.5) / 1.5,
  );
  updateExportPreview();
};

const setExportGuestListFontSizeMm = (value: string | number) => {
  exportSettings.guestListFontSizeMm = Math.min(5, Math.max(1, Number(value)));
  $("#exportGuestListFontSizeValue").text(`${exportSettings.guestListFontSizeMm.toFixed(1)}mm`);
  setExportSliderProgress(
    "exportGuestListFontSizeSlider",
    (exportSettings.guestListFontSizeMm - 1) / 4,
  );
  updateExportPreview();
};

const setExportGuestListColumns = (value: string | number) => {
  exportSettings.guestListColumns = Math.max(1, Math.min(6, Math.round(Number(value)) || 1));
  updateExportPreview();
};

const setExportGuestListShowColors = (value: boolean) => {
  exportSettings.guestListShowColors = value;
  updateExportPreview();
};

const setExportGuestListShowTableLabels = (value: boolean) => {
  exportSettings.guestListShowTableLabels = value;
  updateExportPreview();
};

const setExportGuestListShowChairNumbers = (value: boolean) => {
  exportSettings.guestListShowChairNumbers = value;
  updateExportPreview();
};

const setExportGuestListTableTitlePrefix = (value: string) => {
  exportSettings.guestListTableTitlePrefix = value;
  updateExportPreview();
};

const setExportShowTablePages = (value: boolean) => {
  exportSettings.showTablePages = value;
  $("#exportTablePagesSettings").prop("hidden", !value);
  updateExportPreview();
};

// Two inputs set this one: under the table pages in PDF mode, under the
// title fields in share mode (the guests' page names tables with it).
// Whichever was typed in, the other follows; the typed one is left alone so
// its caret stays put.
const setExportTablePageTitlePrefix = (value: string) => {
  exportSettings.tablePageTitlePrefix = value;
  for (const id of ["exportTablePageTitlePrefixInput", "exportShareTablePrefixInput"]) {
    const input = document.getElementById(id) as HTMLInputElement | null;
    if (input && input.value !== value) input.value = value;
  }
  updateExportPreview();
};

let exportPreviewVisible = false;

// The panel does two things with the arrangement: the PDF, or the guests'
// page (share.ts). One at a time: the mode picks which settings, footer and
// preview are on screen. Kept for the session, not saved — it is about
// what the person is doing now, not about the arrangement.
type ExportPanelMode = "pdf" | "share";
let exportPanelMode: ExportPanelMode = "pdf";

const setExportPanelMode = (mode: ExportPanelMode) => {
  exportPanelMode = mode;
  // The two tabs (.exportTab, export.css) style themselves from this.
  $("#exportModePdf").attr("aria-selected", String(mode === "pdf"));
  $("#exportModeShare").attr("aria-selected", String(mode === "share"));
  // The chart and header options (#exportOptions) serve both modes; the
  // class hides what only paper has (.pdfOnly, export.css).
  $("#exportPanel").toggleClass("shareMode", mode === "share");
  $("#exportPdfFooter, #exportPages").prop("hidden", mode !== "pdf");
  $("#shareSection, #guestPagePreview").prop("hidden", mode !== "share");
  // The share tab's pay footer is renderShareSection's to show.
  if (mode !== "share") $("#sharePayFooter").prop("hidden", true);
  updateExportSectionVisibility();
  renderExportRoomSwitcher();
  if (mode === "pdf") updateExportPreview();
  else renderShareSection();
};

// With more than one room, a row of them at the top of the panel: the one
// that is open is what the PDF prints and what the guests' page preview
// opens on. Switching here is switching in the app (switchRoom).
const renderExportRoomSwitcher = () => {
  const container = document.getElementById("exportRoomSwitcher");
  const buttons = document.getElementById("exportRoomButtons");
  if (!container || !buttons) return;
  container.hidden = roomOrder.length <= 1;
  if (container.hidden) return;
  buttons.replaceChildren();
  for (const roomId of roomOrder) {
    const room = allRooms[roomId];
    if (!room) continue;
    const button = document.createElement("button");
    button.type = "button";
    button.className = "toolButton";
    setToolSelected(button, roomId === currentRoomId);
    button.style.transition = "none";
    button.textContent = unescapeTags(room.roomName);
    button.addEventListener("click", () => selectExportRoom(roomId));
    buttons.appendChild(button);
  }
};

const selectExportRoom = (roomId: RoomId) => {
  if (roomId === currentRoomId) return;
  switchRoom(roomId);
  renderExportRoomSwitcher();
  updateExportPreview();
  renderShareSection();
};

// The option sections the PDF's on/off switches fold away (the room, the
// guest list, its header). The guests' page always has the chart and the
// header, so in share mode those stay open whatever the switches say.
const updateExportSectionVisibility = () => {
  const share = exportPanelMode === "share";
  $("#exportRoomSettings").prop("hidden", !share && !exportSettings.showRoom);
  $("#exportGuestListSettings").prop("hidden", !share && !exportSettings.showGuestList);
  $("#exportGuestListHeaderSettings").prop("hidden", !share && !exportSettings.showGuestListHeader);
};

const openExportOverlay = () => {
  $("#exportOverlay").removeAttr("hidden");
  exportPreviewVisible = true;
  setExportPanelMode(exportPanelMode);
};

// Hides the overlay; navigateTo (navigation.ts) calls this on the way to
// steps 1–3. The overlay's own close (the cross, the backdrop) is
// closeExportOverlay: step 4 ends and step 3 is back.
const hideExportOverlay = () => {
  $("#exportOverlay").attr("hidden", "hidden");
  exportPreviewVisible = false;
};

const closeExportOverlay = () => {
  hideExportOverlay();
  leaveShareStep();
};

// --- PDF generation ---

const EXPORT_PDF_FILENAME = t("export.pdfFilename");

// Minimal shape of the vendored jsPDF global — no @types package.
// svg2pdf.js patches .svg() onto it at load time.
type JsPdfDocument = {
  addPage: (format: [number, number], orientation: ExportOrientation) => JsPdfDocument;
  svg: (
    element: SVGElement,
    options: { x: number; y: number; width: number; height: number },
  ) => Promise<JsPdfDocument>;
  save: (filename: string) => void;
  addFileToVFS: (filename: string, base64Content: string) => JsPdfDocument;
  addFont: (filename: string, fontFamily: string, fontStyle: string) => JsPdfDocument;
};
declare const jspdf: {
  jsPDF: new (options: {
    orientation: ExportOrientation;
    unit: "mm";
    format: [number, number];
  }) => JsPdfDocument;
};

const exportFontBase64Promises: { [filename: string]: Promise<string> } = {};

// Base64-encodes a vendored TTF for jsPDF's addFileToVFS. Byte-by-byte loop —
// spreading ~400k bytes as String.fromCharCode arguments can exceed the
// engine's call-argument limit.
const loadFontBase64 = (filename: string): Promise<string> => {
  if (!exportFontBase64Promises[filename]) {
    exportFontBase64Promises[filename] = fetch(filename)
      .then((response) => response.arrayBuffer())
      .then((buffer) => {
        const bytes = new Uint8Array(buffer);
        let binary = "";
        for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
        return btoa(binary);
      });
  }
  return exportFontBase64Promises[filename];
};

// Converts the pages currently shown in the preview into one downloadable
// PDF. Each page's SVG is briefly appended to the document (off-screen) —
// svg2pdf.js needs it attached, not just parsed, to measure text/layout.
const exportToPdf = async () => {
  // The paywall gate lives on the operation itself, not on the button, so
  // every present and future caller pays the same toll.
  if (!isPdfUnlocked()) {
    // The button is disabled until the consent box is ticked; this guards
    // any other caller the same way.
    if (isPurchaseConsentGiven()) startPdfCheckout();
    return;
  }

  const button = document.getElementById("exportPdfButton") as HTMLButtonElement | null;
  const originalLabel = $("#exportPdfButtonText").text();
  if (button) {
    button.disabled = true;
    $("#exportPdfButtonText").text(t("export.exporting"));
  }

  try {
    const { width: pageWidthMm, height: pageHeightMm } = getExportPageSizeMm(
      exportSettings.orientation,
    );
    // The watermark logo must be inlined as a data URL before the page SVGs
    // are built (see exportLogoDataUrlPromise).
    await exportLogoDataUrlPromise;
    const pageSvgStrings = getExportPageSvgs();
    const parser = new DOMParser();

    const pdf = new jspdf.jsPDF({
      orientation: exportSettings.orientation,
      unit: "mm",
      format: [pageWidthMm, pageHeightMm],
    });

    const fonts = Object.values(EXPORT_FONTS);
    const fontBase64s = await Promise.all(fonts.map((font) => loadFontBase64(font.file)));
    fonts.forEach((font, i) => {
      pdf.addFileToVFS(font.file, fontBase64s[i]);
      pdf.addFont(font.file, font.family, "normal");
    });

    for (let i = 0; i < pageSvgStrings.length; i++) {
      if (i > 0) pdf.addPage([pageWidthMm, pageHeightMm], exportSettings.orientation);

      // Off-screen via position, not visibility:hidden — svg2pdf.js honors
      // CSS visibility as real SVG semantics, so a hidden element paints
      // nothing into the PDF.
      const svgElement = parser.parseFromString(pageSvgStrings[i], "image/svg+xml")
        .documentElement as unknown as SVGSVGElement;
      svgElement.style.position = "absolute";
      svgElement.style.left = "-99999px";
      document.body.appendChild(svgElement);
      try {
        // Every text sits on its alphabetic baseline (centeredTextY in
        // exportShared.ts), a point svg2pdf.js and the browser agree on.
        await pdf.svg(svgElement, { x: 0, y: 0, width: pageWidthMm, height: pageHeightMm });
      } finally {
        document.body.removeChild(svgElement);
      }
    }

    pdf.save(EXPORT_PDF_FILENAME);
    // Only a successful export costs a download credit (fire-and-forget;
    // the paywall UI updates with the remaining count when it answers).
    consumePdfDownload();
    reportAnalyticsEvent("pdfDownloaded");
  } catch (error) {
    console.error("PDF export failed:", error);
    showAlertDialog({
      title: t("export.failedTitle"),
      description: t("export.failedDescription"),
    });
  } finally {
    if (button) {
      button.disabled = false;
      $("#exportPdfButtonText").text(originalLabel);
    }
  }
};
