// Guest list pages: an optional header (title/date/names), then the list
// itself in one of two sort modes — alphabetical by name (this file) or
// grouped by table (exportGuestListByTable.ts) — filling a whole page, or
// the leftover half in combined mode.

const EXPORT_GUEST_LIST_ROW_HEIGHT_FACTOR = 1.9;
// Gap and max column width scale with the list font size — without the width
// cap, a wide/few-column page would stretch columns until name/seat pairs sit
// awkwardly far apart.
const getGuestListColumnGapMm = () => exportSettings.guestListFontSizeMm * 4;
const getGuestListMaxColumnWidthMm = () => exportSettings.guestListFontSizeMm * 20;

type GuestListEntry = { name: string; seat?: string; color: string };

// Every guest, alphabetically, with their seat ("A3" = table A, chair 3) or
// an em dash if unplaced. Seat color matches the table's, so the list
// cross-references the chart.
const getGuestListEntries = (): GuestListEntry[] => {
  const chairNumbersToRender = getExportChairNumbers();
  const entries: GuestListEntry[] = objectKeys(allGuests).map((guestId) => {
    const chairId = placement[guestId];
    const table = chairId ? allTables[allChairSpots[chairId].tableId] : undefined;
    const tableLabel = table && exportSettings.guestListShowTableLabels ? table.label : "";
    const chairNumber =
      chairId && exportSettings.guestListShowChairNumbers
        ? (chairNumbersToRender[chairId] ?? "")
        : "";
    const seat =
      !exportSettings.guestListShowTableLabels && !exportSettings.guestListShowChairNumbers
        ? undefined
        : tableLabel || chairNumber
          ? `${tableLabel} ${chairNumber}`
          : "—";
    return {
      name: allGuests[guestId].name,
      seat,
      color: resolveExportColor(
        table && exportSettings.guestListShowColors ? table.colorToken : "black",
      ),
    };
  });
  entries.sort((a, b) => compareNames(a.name, b.name));
  return entries;
};

type GuestListColumnLayout = {
  rowsPerColumn: number;
  startXMm: number;
  columnWidthMm: number;
  columnGapMm: number;
  rowHeightMm: number;
  fontSizeMm: number;
  entriesPerRegion: number;
};

// The user's column count assumes a full page's width. When the list starts
// in a narrower region (landscape combine mode splits width, not height),
// scale columns down by that width ratio so they don't get cramped.
const getGuestListColumnsForRegion = (region: PageRegion, fullPageWidthMm: number): number =>
  Math.max(1, Math.floor(exportSettings.guestListColumns * (region.width / fullPageWidthMm)));

// How guest-list entries fit into `region`: rows per column, column width
// (capped and centered if that leaves the block narrower than the region),
// and total entries that fit.
const getGuestListColumnLayout = (region: PageRegion, columns: number): GuestListColumnLayout => {
  const fontSizeMm = exportSettings.guestListFontSizeMm;
  const rowHeightMm = fontSizeMm * EXPORT_GUEST_LIST_ROW_HEIGHT_FACTOR;
  const columnGapMm = getGuestListColumnGapMm();

  const availableWidthMm = region.width - 2 * getExportPageMarginMm();
  const gapsWidthMm = (columns + 1) * columnGapMm;
  const naturalColumnWidthMm = (availableWidthMm - gapsWidthMm) / columns;
  const columnWidthMm = Math.min(naturalColumnWidthMm, getGuestListMaxColumnWidthMm());
  // A capped column width can leave the block narrower than the region —
  // center the leftover as equal margins instead of hugging the left edge.
  const contentWidthMm = columns * columnWidthMm + gapsWidthMm;
  const startXMm =
    region.x + getExportPageMarginMm() + columnGapMm + (availableWidthMm - contentWidthMm) / 2;

  const rowsPerColumn = Math.max(
    1,
    Math.floor((region.height - 2 * getExportPageMarginMm()) / rowHeightMm),
  );

  return {
    rowsPerColumn,
    startXMm,
    columnWidthMm,
    columnGapMm,
    rowHeightMm,
    fontSizeMm,
    entriesPerRegion: rowsPerColumn * columns,
  };
};

// `pageEntries` laid out column-major (down column 1, then column 2, ...) so
// each column stays alphabetically contiguous, positioned per `layout`.
const renderGuestListEntriesSvg = (
  pageEntries: GuestListEntry[],
  layout: GuestListColumnLayout,
  region: PageRegion,
): string =>
  pageEntries
    .map((entry, i) => {
      const column = Math.floor(i / layout.rowsPerColumn);
      const rowInColumn = i % layout.rowsPerColumn;
      const colX = layout.startXMm + column * (layout.columnWidthMm + layout.columnGapMm);
      const rowY = region.y + getExportPageMarginMm() + (rowInColumn + 0.5) * layout.rowHeightMm;
      return (
        `<text x="${colX}" y="${centeredTextY(rowY, layout.fontSizeMm)}" font-family="${EXPORT_FONTS.body.family}" font-size="${layout.fontSizeMm}" fill="${EXPORT_BLACK}">${svgText(entry.name)}</text>` +
        (entry.seat
          ? `<text x="${colX + layout.columnWidthMm}" y="${centeredTextY(rowY, layout.fontSizeMm)}" text-anchor="end" font-family="${EXPORT_FONTS.body.family}" font-size="${layout.fontSizeMm}" fill="${entry.color}">${svgText(entry.seat)}</text>`
          : "")
      );
    })
    .join("");

// --- Optional header, shared by both sort modes ---

const EXPORT_GUEST_LIST_HEADER_TITLE_FONT_SIZE_MM = 14;
const EXPORT_GUEST_LIST_HEADER_TITLE_LETTER_SPACING_MM = 2.2;
const EXPORT_GUEST_LIST_HEADER_DATE_FONT_SIZE_MM = 6;
const EXPORT_GUEST_LIST_HEADER_NAMES_FONT_SIZE_MM = 14;
const EXPORT_GUEST_LIST_HEADER_DATE_GAP_MM = 12;
const EXPORT_GUEST_LIST_HEADER_NAMES_GAP_MM = 18;
// Gap after the header's last line, before whatever content follows — shared
// by both sort modes, not tied to the page margin.
const EXPORT_GUEST_LIST_HEADER_GAP_MM = 18;

// Multiplies every header font size, inter-line gap, and the gap below the
// header — one slider scales the header as a unit instead of each piece
// separately.
const getGuestListHeaderScale = (): number => exportSettings.guestListHeaderScale;
const getGuestListHeaderGapMm = (): number =>
  EXPORT_GUEST_LIST_HEADER_GAP_MM * getGuestListHeaderScale();

// Shrinks fontSizeMm down (never up) so text measuring naturalWidthMm at that
// size would fit availableWidthMm — keeps a header line legible in a narrow
// combine-mode column instead of overflowing it.
const shrinkFontSizeToFitWidth = (
  naturalWidthMm: number,
  naturalFontSizeMm: number,
  availableWidthMm: number,
): number => Math.min(naturalFontSizeMm, naturalFontSizeMm * (availableWidthMm / naturalWidthMm));

// Lays out `text` as one <text> with a hand-positioned <tspan> per character,
// each advanced by its own measured width plus `letterSpacingMm` — svg2pdf.js
// has no letter-spacing support at all, so relying on the attribute would
// render fine on screen but collapse to normal spacing in the PDF.
//
// font-family is repeated on every <tspan> — svg2pdf.js doesn't inherit a
// tspan's font from its ancestor <text>, silently falling back to Helvetica.
// No font-weight attribute anywhere, deliberately — see EXPORT_FONTS.
//
// Shrinks font size and letter spacing together (by the same factor) so the
// title still fits within maxWidthMm — matters in a narrow combine-mode
// column, where the full-size letter-spaced title could otherwise overflow.
const renderLetterSpacedCenteredTextSvg = (
  text: string,
  centerX: number,
  y: number,
  naturalFontSizeMm: number,
  naturalLetterSpacingMm: number,
  maxWidthMm: number,
  fontFamily: string,
  color: string,
): string => {
  const chars = Array.from(text);
  const measureAt = (fontSizeMm: number, letterSpacingMm: number) => {
    const charWidths = chars.map((char) => measureSvgTextWidth(char, fontSizeMm, fontFamily));
    const totalWidthMm =
      charWidths.reduce((sum, width) => sum + width, 0) + letterSpacingMm * (chars.length - 1);
    return { charWidths, totalWidthMm };
  };

  const natural = measureAt(naturalFontSizeMm, naturalLetterSpacingMm);
  const shrink = Math.min(1, maxWidthMm / natural.totalWidthMm);
  const fontSizeMm = naturalFontSizeMm * shrink;
  const letterSpacingMm = naturalLetterSpacingMm * shrink;
  const { charWidths, totalWidthMm } =
    shrink < 1 ? measureAt(fontSizeMm, letterSpacingMm) : natural;

  let cursorX = centerX - totalWidthMm / 2;
  const tspans = chars
    .map((char, i) => {
      const tspan = `<tspan x="${cursorX}" y="${y}" font-family="${fontFamily}" font-size="${fontSizeMm}" fill="${color}">${svgText(char)}</tspan>`;
      cursorX += charWidths[i] + letterSpacingMm;
      return tspan;
    })
    .join("");

  return `<text font-family="${fontFamily}" font-size="${fontSizeMm}" fill="${color}">${tspans}</text>`;
};

// One header line (title/date/names): how far its baseline advances from the
// previous line's baseline (for the first line: from the block's own top),
// and how to render it at a given absolute y. Lines for empty fields are left
// out entirely by the caller, so no space is reserved for an unset field.
type GuestListHeaderLine = { baselineAdvanceMm: number; svg: (y: number) => string };

// The optional header's lines (title/date/names) and the block's own height
// — the distance from its top to its last line's baseline, NOT including any
// top margin, since the two sort modes each position that top edge
// differently (see renderGuestListSvg for name mode, top-anchored; and
// renderGuestListByTableSvg for table mode, centered as one block with the
// grid). `marginMm` is only the horizontal shrink-to-fit budget here (each
// caller supplies whatever margin its own mode uses); the block's own top
// margin is entirely up to the caller. Returns no lines / heightMm 0 when the
// header is off or every field is empty, so callers don't need a separate
// on/off check.
const buildGuestListHeaderLines = (
  region: PageRegion,
  marginMm: number,
): { lines: GuestListHeaderLine[]; heightMm: number } => {
  if (!exportSettings.showGuestListHeader) return { lines: [], heightMm: 0 };

  const centerX = region.x + region.width / 2;
  const availableWidthMm = region.width - 2 * marginMm;
  const scale = getGuestListHeaderScale();
  const titleFontSizeMm = EXPORT_GUEST_LIST_HEADER_TITLE_FONT_SIZE_MM * scale;
  const titleLetterSpacingMm = EXPORT_GUEST_LIST_HEADER_TITLE_LETTER_SPACING_MM * scale;
  const dateFontSizeMm = EXPORT_GUEST_LIST_HEADER_DATE_FONT_SIZE_MM * scale;
  const namesFontSizeMm = EXPORT_GUEST_LIST_HEADER_NAMES_FONT_SIZE_MM * scale;
  const dateGapMm = EXPORT_GUEST_LIST_HEADER_DATE_GAP_MM * scale;
  const namesGapMm = EXPORT_GUEST_LIST_HEADER_NAMES_GAP_MM * scale;

  const headerLines: GuestListHeaderLine[] = [];
  const addHeaderLine = (fontSizeMm: number, gapBeforeMm: number, svg: (y: number) => string) =>
    headerLines.push({
      baselineAdvanceMm: headerLines.length === 0 ? fontSizeMm : gapBeforeMm,
      svg,
    });

  if (exportSettings.guestListHeaderTitle) {
    addHeaderLine(titleFontSizeMm, 0, (y) =>
      renderLetterSpacedCenteredTextSvg(
        exportSettings.guestListHeaderTitle,
        centerX,
        y,
        titleFontSizeMm,
        titleLetterSpacingMm,
        availableWidthMm,
        EXPORT_FONTS.coverHeader.family,
        EXPORT_BLACK,
      ),
    );
  }
  if (exportSettings.guestListHeaderDate) {
    const dateText = exportSettings.guestListHeaderDate;
    const fontSizeMm = shrinkFontSizeToFitWidth(
      measureSvgTextWidth(dateText, dateFontSizeMm, EXPORT_FONTS.coverHeader.family),
      dateFontSizeMm,
      availableWidthMm,
    );
    addHeaderLine(
      dateFontSizeMm,
      dateGapMm,
      (y) =>
        `<text x="${centerX}" y="${y}" text-anchor="middle" font-family="${EXPORT_FONTS.coverHeader.family}" font-size="${fontSizeMm}" fill="${EXPORT_BLACK}">${svgText(dateText)}</text>`,
    );
  }
  if (exportSettings.guestListHeaderNames) {
    const namesText = exportSettings.guestListHeaderNames;
    const fontSizeMm = shrinkFontSizeToFitWidth(
      measureSvgTextWidth(namesText, namesFontSizeMm, EXPORT_FONTS.coverCoupleNames.family),
      namesFontSizeMm,
      availableWidthMm,
    );
    addHeaderLine(
      namesFontSizeMm,
      namesGapMm,
      (y) =>
        `<text x="${centerX}" y="${y}" text-anchor="middle" font-family="${EXPORT_FONTS.coverCoupleNames.family}" font-size="${fontSizeMm}" fill="${EXPORT_BLACK}">${svgText(namesText)}</text>`,
    );
  }

  if (headerLines.length === 0) return { lines: [], heightMm: 0 };

  let heightMm = 0;
  for (const line of headerLines) heightMm += line.baselineAdvanceMm;
  return { lines: headerLines, heightMm };
};

// Renders header `lines` (from buildGuestListHeaderLines) with the block's
// own top positioned at `blockTopY`.
const renderGuestListHeaderLinesSvg = (lines: GuestListHeaderLine[], blockTopY: number): string => {
  let cursorMm = 0;
  return lines
    .map((line) => {
      cursorMm += line.baselineAdvanceMm;
      return line.svg(blockTopY + cursorMm);
    })
    .join("");
};

// The guest list's first placement — header (if enabled) plus whichever sort
// mode is active — into `region`: a whole page normally, or the shared half
// in combined mode. In table mode this is the entire list (it never
// paginates — see renderGuestListByTableSvg, which also handles its own
// header since that mode centers the two as one block rather than stacking
// them top-anchored); in name mode, whatever doesn't fit is returned so the
// caller can spill it onto plain continuation pages (see export.ts).
const renderGuestListSvg = (
  region: PageRegion,
  tablesWithGuests: TableGuests[],
  nameEntries: GuestListEntry[],
): { svg: string; remainingNameEntries: GuestListEntry[] } => {
  if (exportSettings.guestListSortMode === "table") {
    return { svg: renderGuestListByTableSvg(region, tablesWithGuests), remainingNameEntries: [] };
  }

  const { lines: headerLines, heightMm: headerBlockHeightMm } = buildGuestListHeaderLines(
    region,
    getExportPageMarginMm(),
  );
  const headerSvg = renderGuestListHeaderLinesSvg(headerLines, region.y + getExportPageMarginMm());
  // Content re-insets itself by the page margin from whatever region it's
  // given, so that term cancels out here — leaving exactly the (scaled)
  // header gap below the header.
  const headerHeightMm =
    headerLines.length > 0 ? headerBlockHeightMm + getGuestListHeaderGapMm() : 0;
  const contentRegion: PageRegion =
    headerHeightMm === 0
      ? region
      : {
          x: region.x,
          y: region.y + headerHeightMm,
          width: region.width,
          height: region.height - headerHeightMm,
        };

  const columns = getGuestListColumnsForRegion(contentRegion, region.width);
  const layout = getGuestListColumnLayout(contentRegion, columns);
  const firstPageEntries = nameEntries.slice(0, layout.entriesPerRegion);
  const remainingNameEntries = nameEntries.slice(layout.entriesPerRegion);
  const contentSvg = renderGuestListEntriesSvg(firstPageEntries, layout, contentRegion);
  return { svg: headerSvg + contentSvg, remainingNameEntries };
};
