// Shared infrastructure for the PDF export: fonts, colors, the user's export
// settings, text measurement, and data helpers used by the four page types
// (room chart, guest list, cover page, table pages).

type ExportOrientation = "portrait" | "landscape";
type ExportChairStyle = "big" | "small" | "none";
// The guest list can be sorted alphabetically by name, or grouped into a
// small-multiples grid by table — mutually exclusive views of the same list.
type GuestListSortMode = "name" | "table";

// svg2pdf.js can't resolve var(--x) colors (it silently paints nothing), so
// every export color must be resolved to a literal value first.
const resolveExportCssColor = (cssVariableName: string): string =>
  getComputedStyle(document.documentElement).getPropertyValue(cssVariableName).trim();
const resolveExportColor = (colorToken: ColorToken): string =>
  resolveExportCssColor(`--${colorToken}`);

type ExportColorWithOpacity = { color: string; opacity: number };

// svg2pdf.js can't read the alpha of an rgb()/hex color either, so a
// translucent token (--redLight, --exportFill) is split into a solid
// color and a separate fill-opacity. The stylesheet declares those as
// `rgb(from var(--red) r g b / 20%)`, and reading a custom property gives its
// text with the var() already substituted (`rgb(from #fb5666 r g b / 20%)`),
// so the color and the percentage are both in that one string.
const resolveExportColorWithOpacity = (cssVariableName: string): ExportColorWithOpacity => {
  const declared = resolveExportCssColor(cssVariableName);
  const match = declared.match(
    /^rgb\(\s*from\s+(#[0-9a-f]{6})\s+r\s+g\s+b\s*\/\s*([\d.]+)%\s*\)$/i,
  );
  if (!match)
    throw new Error(`${cssVariableName} is not "rgb(from #rrggbb r g b / N%)": ${declared}`);
  return { color: match[1], opacity: parseFloat(match[2]) / 100 };
};
const resolveExportLightColor = (colorToken: ColorToken): ExportColorWithOpacity =>
  resolveExportColorWithOpacity(`--${colorToken}Light`);
const resolveExportSemiColor = (colorToken: ColorToken): ExportColorWithOpacity =>
  resolveExportColorWithOpacity(`--${colorToken}Semi`);
// Resolved again when the theme changes (theme.js fires "themechange"): the
// guests' page draws its chart in the page's colours, dark included
// (css/guestPage.css redefines the paper, ink and fill tokens there). In
// the app these stay what the paper needs, since dark.css leaves them.
let EXPORT_BLACK = resolveExportCssColor("--black");
let EXPORT_WHITE_ALPHA = resolveExportColorWithOpacity("--exportFill");
window.addEventListener("themechange", () => {
  EXPORT_BLACK = resolveExportCssColor("--black");
  EXPORT_WHITE_ALPHA = resolveExportColorWithOpacity("--exportFill");
});

// Vendored TTFs embedded into the PDF — jsPDF only ships the 14 standard PDF
// fonts, so without these svg2pdf.js silently falls back to Helvetica.
//
// Every font gets its own dedicated family name, never a shared family with a
// style or weight switch: this vendored svg2pdf.js can't reliably resolve two
// styles registered under one family, and a numeric font-weight on a custom
// font breaks resolution outright (both confirmed against real exports). So
// "Lato Bold"/"Lato Light" are registered as made-up standalone families, and
// no font-weight attribute is ever set on export text. styles.css has matching
// @font-face rules so the on-screen preview resolves the same names.
//
// centralOffset: how far above the alphabetic baseline the middle of the
// font's em box sits, as a fraction of the font size — (hhea ascender +
// hhea descender) / 2 / unitsPerEm, read from the vendored file. Used by
// centeredTextY to centre text on a point without dominant-baseline.
const EXPORT_FONTS = {
  // Default for the room chart, set on each page's root <svg>.
  body: { family: "Lato", file: "/assets/fonts/Lato-Regular.ttf", centralOffset: 0.387 },
  // Table-page title, matching the site's script-style headings.
  tablePageTitle: {
    family: "MonteCarlo",
    file: "/assets/fonts/MonteCarlo-Regular.ttf",
    centralOffset: 0.35,
  },
  // Table-page guest names, matching the site's heading font (h1-h6).
  tablePageName: {
    family: "Playfair Display",
    file: "/assets/fonts/PlayfairDisplay-Regular.ttf",
    centralOffset: 0.4155,
  },
  // Cover-page title and date.
  coverHeader: { family: "Lato Light", file: "/assets/fonts/Lato-Light.ttf", centralOffset: 0.387 },
  // Cover-page couple-names subtitle.
  coverCoupleNames: {
    family: "Ms Madi",
    file: "/assets/fonts/MsMadi-Regular.ttf",
    centralOffset: 0.24,
  },
  // Cover-grid cell titles ("Bord X").
  coverGridTitle: {
    family: "Lato Bold",
    file: "/assets/fonts/Lato-Bold.ttf",
    centralOffset: 0.387,
  },
  // Cover-grid guest names.
  coverGridName: {
    family: "Klee One",
    file: "/assets/fonts/KleeOne-Regular.ttf",
    centralOffset: 0.436,
  },
};

// Bottom-right watermark stamped on every export page: the site logo + name,
// echoing the header (#logo / #logoTitle in index.php) at print scale. The
// vertical footprint (logoSizeMm + edgeOffsetMm) stays within the minimum
// page margin (10mm) so it never overlaps page content.
const EXPORT_WATERMARK = {
  logoFile: SITE.logo,
  text: SITE.name,
  logoSizeMm: 6,
  fontSizeMm: 3,
  gapMm: 1.3,
  edgeOffsetMm: 4,
  // The header title sits slightly high of center (padding-bottom) — same
  // optical correction here, scaled to the print logo.
  textRaiseMm: 0.4,
};

// The logo PNG inlined as a data URL. svg2pdf.js passes data: hrefs straight
// to jsPDF, while a path href makes it re-fetch the image through an
// Image+canvas round trip mid-export — so the PDF path awaits this promise
// and renders the data URL. The preview can't await (it renders
// synchronously), so it falls back to the raw path until the fetch resolves;
// browsers render either just fine.
let exportLogoDataUrl: string | undefined;
const exportLogoDataUrlPromise: Promise<void> = fetch(EXPORT_WATERMARK.logoFile)
  .then((response) => response.blob())
  .then(
    (blob) =>
      new Promise<void>((resolve) => {
        const reader = new FileReader();
        reader.onload = () => {
          exportLogoDataUrl = reader.result as string;
          resolve();
        };
        reader.readAsDataURL(blob);
      }),
  )
  // A failed fetch just leaves the path fallback in place.
  .catch(() => undefined);

const renderExportWatermarkSvg = (pageWidthMm: number, pageHeightMm: number): string => {
  const { text, logoSizeMm, fontSizeMm, gapMm, edgeOffsetMm, textRaiseMm } = EXPORT_WATERMARK;
  // Same face as the on-screen #logoTitle ('Lato Light'), already embedded
  // in the PDF for the cover header.
  const fontFamily = EXPORT_FONTS.coverHeader.family;
  const textWidthMm = measureSvgTextWidth(text, fontSizeMm, fontFamily);
  const textX = pageWidthMm - edgeOffsetMm;
  const logoX = textX - textWidthMm - gapMm - logoSizeMm;
  const logoY = pageHeightMm - edgeOffsetMm - logoSizeMm;
  const centerY = logoY + logoSizeMm / 2 - textRaiseMm;
  return `
      <image href="${exportLogoDataUrl ?? EXPORT_WATERMARK.logoFile}" x="${logoX}" y="${logoY}" width="${logoSizeMm}" height="${logoSizeMm}" />
      <text x="${textX}" y="${centeredTextY(centerY, fontSizeMm, fontFamily)}" text-anchor="end" font-family="${fontFamily}" font-size="${fontSizeMm}" fill="${EXPORT_BLACK}">${text}</text>
  `;
};

// Diagonal "FÖRHANDSVISNING" across every page while the PDF download is
// locked (see paywall.ts, whose isPdfUnlocked gates it in
// renderExportPageSvg). Deliberately separate from the corner-logo
// watermark above, which is the user's own toggle — this stamp is the
// paywall's, and only paying removes it.
const PREVIEW_STAMP_TEXT = t("export.previewStamp");

// The stamp text is constant, so its width at the probe size is measured
// once, not per page per preview rebuild (measurement forces a layout
// flush). Measured before the Lato webfont finishes loading it reflects
// the fallback font — export.ts invalidates this cache once fonts are
// ready (the subscription lives there, not here: fonts.ready can resolve
// between script files, before export.ts's own globals exist).
let previewStampProbeWidthMm: number | undefined;
const PREVIEW_STAMP_PROBE_SIZE_MM = 10;

const renderPreviewStampSvg = (pageWidthMm: number, pageHeightMm: number): string => {
  const fontFamily = EXPORT_FONTS.body.family;
  if (previewStampProbeWidthMm === undefined || previewStampProbeWidthMm <= 0) {
    previewStampProbeWidthMm = measureSvgTextWidth(
      PREVIEW_STAMP_TEXT,
      PREVIEW_STAMP_PROBE_SIZE_MM,
      fontFamily,
    );
  }
  // A failed measurement (0/NaN) must never blow up the math and hand a
  // locked user a stamp-free page — fall back to a rough average glyph
  // width so the stamp always renders at a sane size.
  const probeWidthMm =
    previewStampProbeWidthMm > 0
      ? previewStampProbeWidthMm
      : PREVIEW_STAMP_TEXT.length * PREVIEW_STAMP_PROBE_SIZE_MM * 0.55;

  // Sized so the text spans most of the page diagonal.
  const diagonalMm = Math.hypot(pageWidthMm, pageHeightMm);
  const fontSizeMm = (PREVIEW_STAMP_PROBE_SIZE_MM * 0.75 * diagonalMm) / probeWidthMm;
  const angleDeg = Math.atan2(pageHeightMm, pageWidthMm) * RAD_TO_DEG;
  const centerX = pageWidthMm / 2;
  const centerY = pageHeightMm / 2;
  // Single rotate transform only — svg2pdf.js mis-flattens longer transform
  // chains (this renders into the PDF too if the locked path is bypassed).
  return `
      <text x="${centerX}" y="${centeredTextY(centerY, fontSizeMm, fontFamily)}" text-anchor="middle"
        font-family="${fontFamily}" font-size="${fontSizeMm}" fill="${EXPORT_BLACK}" fill-opacity="0.12"
        transform="rotate(-${angleDeg} ${centerX} ${centerY})">${PREVIEW_STAMP_TEXT}</text>
  `;
};

const A4_PORTRAIT_MM = { width: 210, height: 297 };

const getExportPageSizeMm = (orientation: ExportOrientation) =>
  orientation === "portrait"
    ? A4_PORTRAIT_MM
    : { width: A4_PORTRAIT_MM.height, height: A4_PORTRAIT_MM.width };

// A rectangular sub-area of a page (mm) — lets page content share the same
// layout code whether it gets a whole page or half of one (combined mode).
type PageRegion = { x: number; y: number; width: number; height: number };

// All user-controlled state from the export panel (see the setters in
// export.ts).
const exportSettings = {
  orientation: "portrait" as ExportOrientation,
  // How far every page's content stays clear of the page edge — used
  // uniformly everywhere a margin is needed (the room chart, both guest-list
  // sort modes, table pages). A user who wants the by-table grid's header to
  // read more like a title page can just turn this up.
  pageMarginMm: 20,
  // The bottom-right logo watermark (see renderExportWatermarkSvg).
  showWatermark: true,
  showRoom: true,
  combineRoomAndList: true,
  showColors: true,
  roomRotation: 0,
  roomScale: 1,
  showTableLabels: true,
  tableLabelFontSizeMm: 16,
  tableBorderRadius: 16,
  chairStyle: "big" as ExportChairStyle,
  showChairNumbers: true,
  globalChairNumbers: false,
  showGuestNames: false,
  // Shared by chair numbers and guest names — whichever is showing at a chair
  // occupies the same visual role, so one size controls both.
  chairTextFontSizeMm: 14,
  wrapGuestNames: false,
  showGuestList: true,
  guestListSortMode: "name" as GuestListSortMode,
  // Optional header (title/date/names) shown above whichever sort mode is
  // active — same fields the old standalone cover page used, in the order
  // they appear on the page. Title matches the input's initial value in
  // index.php; rendered exactly as typed, no casing applied.
  showGuestListHeader: true,
  guestListHeaderTitle: t("export.headerTitleDefault"),
  guestListHeaderDate: "",
  guestListHeaderNames: "",
  // Multiplies every header font size and gap (including the gap below the
  // header, before whatever content follows).
  guestListHeaderScale: 1,
  // Name-mode settings.
  guestListFontSizeMm: 3,
  guestListColumns: 2,
  guestListShowColors: false,
  guestListShowTableLabels: true,
  guestListShowChairNumbers: true,
  // Table-mode setting: prepended as-is to the table label to build each
  // grid cell's title ("BORD " + "A" = "BORD A") — an empty string leaves
  // just the label. Matches the input's initial value in index.php.
  guestListTableTitlePrefix: t("export.tableTitlePrefixUpper"),
  showTablePages: false,
  // Prepended as-is to the table label to build each table page's title
  // ("Bord " + "A" = "Bord A") — an empty string leaves just the label.
  // Matches the input's initial value in index.php.
  tablePageTitlePrefix: t("export.tablePageTitlePrefix"),
};
// The pristine values, for loading a snapshot that lacks a setting
// (persistence.ts) — exportSettings itself changes as the user works.
const EXPORT_SETTING_DEFAULTS: Readonly<typeof exportSettings> = { ...exportSettings };

const getExportPageMarginMm = (): number => exportSettings.pageMarginMm;

// A detached, hidden SVG used to measure text width via real font metrics.
// font-size is a bare number, matching the export SVG's mm-based viewBox, so
// measurements at size N are directly comparable.
let exportTextMeasurementSvg: SVGSVGElement | undefined;
// Measured once per text, size and font: the guests' page lays its labels
// out again on every turn of the map (guestPage.ts) and asks for the same
// names each time, and getComputedTextLength is the slow part. Cleared when
// the webfont arrives (export.ts, guestPage.ts): widths measured in the
// fallback font are wrong.
const exportTextWidthCache = new Map<string, number>();
// fontFamily defaults to the inherited body font (EXPORT_FONTS.body, Lato);
// pass it explicitly to measure text set in another export font.
const measureSvgTextWidth = (text: string, fontSizeMm: number, fontFamily?: string): number => {
  const cacheKey = `${fontFamily ?? ""}|${fontSizeMm}|${text}`;
  const cached = exportTextWidthCache.get(cacheKey);
  if (cached !== undefined) return cached;
  if (!exportTextMeasurementSvg) {
    exportTextMeasurementSvg = document.createElementNS(
      "http://www.w3.org/2000/svg",
      "svg",
    ) as SVGSVGElement;
    exportTextMeasurementSvg.style.position = "fixed";
    exportTextMeasurementSvg.style.top = "0";
    exportTextMeasurementSvg.style.left = "0";
    exportTextMeasurementSvg.style.visibility = "hidden";
    exportTextMeasurementSvg.style.pointerEvents = "none";
    document.body.appendChild(exportTextMeasurementSvg);
  }
  const textEl = document.createElementNS("http://www.w3.org/2000/svg", "text");
  textEl.setAttribute("font-size", String(fontSizeMm));
  if (fontFamily) textEl.setAttribute("font-family", fontFamily);
  textEl.textContent = text;
  exportTextMeasurementSvg.appendChild(textEl);
  const width = textEl.getComputedTextLength();
  exportTextMeasurementSvg.removeChild(textEl);
  exportTextWidthCache.set(cacheKey, width);
  return width;
};

// Text centred on a point, without dominant-baseline: browsers disagree on
// where "central" sits (Safari draws such text visibly higher than Chrome),
// and svg2pdf.js ignores it altogether — while the alphabetic baseline is
// the same point everywhere. So the baseline is placed by the font's own
// metrics (EXPORT_FONTS.centralOffset): exactly where Chrome's "central"
// put it, so the PDF and the preview look as before, and now Safari and
// the guests' page agree with them.
const exportCentralOffset = (fontFamily: string): number =>
  Object.values(EXPORT_FONTS).find((font) => font.family === fontFamily)?.centralOffset ??
  EXPORT_FONTS.body.centralOffset;
const centeredTextY = (
  centerY: number,
  fontSizeMm: number,
  fontFamily: string = EXPORT_FONTS.body.family,
): number => centerY + fontSizeMm * exportCentralOffset(fontFamily);

// User text for an SVG string. Names and labels are stored escaped
// (replaceTags, for the app's own HTML templates); escaping them again
// would print "Tom &amp; Jerry". Unescape first, so the text comes out
// escaped exactly once whatever form it arrives in.
const svgText = (text: string): string => replaceTags(unescapeTags(text));

// A vertical column of names, one per row, centered on centerX — shared by
// the cover-grid cells and the standalone table pages.
const renderCenteredNameColumnSvg = (
  names: string[],
  centerX: number,
  listStartY: number,
  rowHeightMm: number,
  fontSizeMm: number,
  fontFamily: string,
): string =>
  names
    .map(
      (name, i) =>
        `<text x="${centerX}" y="${centeredTextY(listStartY + (i + 0.5) * rowHeightMm, fontSizeMm, fontFamily)}" text-anchor="middle" font-family="${fontFamily}" font-size="${fontSizeMm}" fill="${EXPORT_BLACK}">${svgText(name)}</text>`,
    )
    .join("");

// Alphabetical in the site's language (å/ä/ö sort after z in Swedish).
const compareNames = (a: string, b: string): number => a.localeCompare(b, LANGUAGE);

// Same ordering as the build-mode table list (see compareTablesByLabel).
const getExportTableOrder = (): Table[] =>
  objectKeys(allTables)
    .map((id) => allTables[id])
    .sort(compareTablesByLabel);

// Chair numbers to render: the room's own per-table numbers (1..n, reset at
// every table), or — with the globalChairNumbers setting — those same numbers
// shifted so they keep counting up across tables in table order.
const getExportChairNumbers = (): { [chairId: ChairId]: number } => {
  if (!exportSettings.globalChairNumbers) return chairNumbers;

  let offset = 0;
  const globalChairNumbers: { [chairId: ChairId]: number } = {};
  for (const table of getExportTableOrder()) {
    const tableChairIds = objectKeys(chairNumbers).filter(
      (chairId) => allChairSpots[chairId]?.tableId === table.tableId,
    );
    for (const chairId of tableChairIds) {
      globalChairNumbers[chairId] = offset + chairNumbers[chairId];
    }
    offset += tableChairIds.length;
  }
  return globalChairNumbers;
};

type TableGuests = { table: Table; guestNames: string[] };

// A table's display title, built from a user-configurable prefix (see
// guestListTableTitlePrefix / tablePageTitlePrefix) prepended as-is to its
// label — an empty prefix leaves just the bare label, with no separator to
// strip or re-add.
const getTableTitle = (table: Table, titlePrefix: string): string => `${titlePrefix}${table.label}`;

// One entry per table with at least one seated guest, in table order, guest
// names alphabetical. Tables with nobody seated are omitted entirely. Feeds
// both the guest list's by-table grid and the standalone table pages.
const getTablesWithGuests = (): TableGuests[] => {
  const guestNamesByTableId: { [tableId: TableId]: string[] } = {};
  for (const guestId of objectKeys(placement)) {
    const guest = allGuests[guestId];
    if (!guest) continue;
    const chairId = placement[guestId];
    const tableId = allChairSpots[chairId]?.tableId;
    if (!tableId) continue;
    (guestNamesByTableId[tableId] ??= []).push(guest.name);
  }

  return getExportTableOrder()
    .filter((table) => guestNamesByTableId[table.tableId]?.length)
    .map((table) => ({
      table,
      guestNames: guestNamesByTableId[table.tableId].sort(compareNames),
    }));
};
