// Room chart page: the seating chart itself — tables, chairs, chair numbers,
// and guest names, rotated and scaled to fit its page region.

const EXPORT_ROOM_CHAIR_RADIUS = 18;
const EXPORT_ROOM_CHAIR_DOT_RADIUS = 5;
const EXPORT_ROOM_STROKE_WIDTH = 2.5;
const EXPORT_ROOM_GUEST_NAME_LINE_HEIGHT_FACTOR = 1.15;
// Wrap width for guest names when the "Radbryt namn" setting is on.
const EXPORT_ROOM_GUEST_NAME_MAX_WIDTH = 40;
// How close (vertically, after room rotation) two neighbouring chairs' labels
// may get before they count as colliding — see isRoomChairCloseToNeighbour.
const EXPORT_ROOM_NEIGHBOUR_COLLISION_DISTANCE = 36;

type RoomChartBounds = { minX: number; minY: number; maxX: number; maxY: number };

const getRoomTableColor = (table: Table): string =>
  resolveExportColor(exportSettings.showColors ? table.colorToken : "black");

// Greedy word-wrap (SVG has no native wrapping). A single word wider than
// maxWidthMm is left as-is, not split.
const wrapTextToWidth = (text: string, maxWidthMm: number, fontSizeMm: number): string[] => {
  const words = text.split(" ");
  const lines: string[] = [];
  let currentLine = "";
  for (const word of words) {
    const candidate = currentLine ? `${currentLine} ${word}` : word;
    if (currentLine && measureSvgTextWidth(candidate, fontSizeMm) > maxWidthMm) {
      lines.push(currentLine);
      currentLine = word;
    } else {
      currentLine = candidate;
    }
  }
  if (currentLine) lines.push(currentLine);
  return lines;
};

// Widest rendered width among placed guests' names, capped at the wrap width
// when wrapping is on. Lets getRoomChartBounds pad by a real measurement
// instead of a guessed constant.
const getRoomWidestGuestNameWidth = (): number => {
  let maxWidth = 0;
  for (const guestId of objectKeys(placement)) {
    const guest = allGuests[guestId];
    if (!guest) continue;
    const width = measureSvgTextWidth(guest.name, exportSettings.chairTextFontSizeMm);
    const cappedWidth = exportSettings.wrapGuestNames
      ? Math.min(width, EXPORT_ROOM_GUEST_NAME_MAX_WIDTH)
      : width;
    maxWidth = Math.max(maxWidth, cappedWidth);
  }
  return maxWidth;
};

// Room-space bounding box of everything built, so the chart can scale/center
// around only the used part of the (much larger) room canvas. Folds room
// rotation into each shape's own extent rather than rotating an unrotated
// box's corners — the latter overestimates non-rectangular shapes (a rotated
// circle's footprint never changes, but its bounding square's corners sweep
// wider at 45°), which made the fitted scale pulse as the slider moved.
const getRoomChartBounds = (
  roomRotation: number,
  pivot: { x: number; y: number },
): RoomChartBounds => {
  let minX = Infinity;
  let minY = Infinity;
  let maxX = -Infinity;
  let maxY = -Infinity;
  const expand = (x: number, y: number) => {
    minX = Math.min(minX, x);
    minY = Math.min(minY, y);
    maxX = Math.max(maxX, x);
    maxY = Math.max(maxY, y);
  };

  const rotateAroundPivot = (x: number, y: number) => {
    const rotated = rotateXY(x - pivot.x, y - pivot.y, roomRotation * DEG_TO_RAD);
    return { x: pivot.x + rotated.x, y: pivot.y + rotated.y };
  };

  for (const tableId of objectKeys(allTables)) {
    const table = allTables[tableId];
    // The center moves only via room rotation; the shape's orientation is the
    // sum of table.rotate and room rotation.
    const center = rotateAroundPivot(table.centerX, table.centerY);
    const a = table.width / 2;
    const b = table.height / 2;
    const angle = (table.rotate + roomRotation) * DEG_TO_RAD;

    let halfWidth: number;
    let halfHeight: number;
    if (table.type === "round") {
      // Tight AABB of an ellipse rotated by `angle`; reduces to exactly `a`
      // for a circle (a === b), so its footprint doesn't pulse as it spins.
      halfWidth = Math.sqrt((a * Math.cos(angle)) ** 2 + (b * Math.sin(angle)) ** 2);
      halfHeight = Math.sqrt((a * Math.sin(angle)) ** 2 + (b * Math.cos(angle)) ** 2);
    } else {
      // Tight AABB of a rectangle rotated by `angle` (closed form of checking
      // all 4 corners).
      halfWidth = Math.abs(a * Math.cos(angle)) + Math.abs(b * Math.sin(angle));
      halfHeight = Math.abs(a * Math.sin(angle)) + Math.abs(b * Math.cos(angle));
    }
    expand(center.x - halfWidth, center.y - halfHeight);
    expand(center.x + halfWidth, center.y + halfHeight);
  }

  // Guest-name labels extend past a bare chair circle — pad by the widest
  // name actually shown so labels don't clip at the page edge. Chairs are
  // circles, so a fixed margin around the rotated center is exact.
  const chairMargin =
    EXPORT_ROOM_CHAIR_RADIUS + (exportSettings.showGuestNames ? getRoomWidestGuestNameWidth() : 0);
  for (const chairId of objectKeys(allChairSpots)) {
    const chairSpot = allChairSpots[chairId];
    if (!chairSpot.isChair || chairSpot.isHidden) continue;
    const { x, y } = getChairRoomPosition(chairSpot);
    const rotated = rotateAroundPivot(x, y);
    expand(rotated.x - chairMargin, rotated.y - chairMargin);
    expand(rotated.x + chairMargin, rotated.y + chairMargin);
  }

  if (!isFinite(minX)) return { minX: 0, minY: 0, maxX: BASE_ROOM_SIZE, maxY: BASE_ROOM_SIZE };
  return { minX, minY, maxX, maxY };
};

const renderRoomTableSvg = (table: Table): string => {
  const cx = table.centerX;
  const cy = table.centerY;
  const color = getRoomTableColor(table);
  const strokeWidth = EXPORT_ROOM_STROKE_WIDTH;
  // Benches render only their top edge (matches .benchTable's border-top-only
  // styling) — a full rect would look like a table.
  const shape =
    table.type === "round"
      ? `<ellipse cx="${cx}" cy="${cy}" rx="${table.width / 2}" ry="${table.height / 2}" fill="${EXPORT_WHITE_ALPHA.color}" fill-opacity="${EXPORT_WHITE_ALPHA.opacity}" stroke="${color}" stroke-width="${strokeWidth}" />`
      : table.type === "bench"
        ? `<line x1="${cx - table.width / 2}" y1="${cy - table.height / 2}" x2="${cx + table.width / 2}" y2="${cy - table.height / 2}" stroke="${color}" stroke-width="${strokeWidth}" stroke-linecap="round" />`
        : `<rect x="${cx - table.width / 2}" y="${cy - table.height / 2}" width="${table.width}" height="${table.height}" rx="${exportSettings.tableBorderRadius}" fill="${EXPORT_WHITE_ALPHA.color}" fill-opacity="${EXPORT_WHITE_ALPHA.opacity}" stroke="${color}" stroke-width="${strokeWidth}" />`;

  // The label counter-rotates against the room-rotation slider so it stays
  // upright however the room is rotated.
  const adjust =
    table.type === "bench" ? rotateXY(0, 4, table.rotate * DEG_TO_RAD) : { x: 0, y: 0 };
  const label = exportSettings.showTableLabels
    ? `<text x="${cx + adjust.x}" y="${centeredTextY(cy + adjust.y, exportSettings.tableLabelFontSizeMm)}" transform="rotate(${-exportSettings.roomRotation} ${cx + adjust.x} ${cy + adjust.y})" text-anchor="middle" font-size="${exportSettings.tableLabelFontSizeMm}" fill="${color}">${svgText(table.label)}</text>`
    : "";

  return `
    <g transform="rotate(${table.rotate} ${cx} ${cy})">${shape}</g>
    ${label}
  `;
};

// showGuestNames only drops the chair border's stroke (so the ring doesn't
// visually compete with the name) — chair numbers are independent.
const renderRoomChairSvg = (
  chairSpot: ChairSpot,
  chairNumbersToRender: { [chairId: ChairId]: number },
): string => {
  const table = allTables[chairSpot.tableId];
  const color = getRoomTableColor(table);
  const { x, y } = getChairRoomPosition(chairSpot);
  const strokeWidth = EXPORT_ROOM_STROKE_WIDTH;

  // A white underlay below the translucent colored fill, so overlapping
  // content doesn't show through the chair.
  let circles = "";
  if (exportSettings.chairStyle === "big") {
    const colorLight = resolveExportLightColor(
      exportSettings.showColors ? table.colorToken : "black",
    );
    circles =
      `<circle cx="${x}" cy="${y}" r="${EXPORT_ROOM_CHAIR_RADIUS}" fill="${EXPORT_WHITE_ALPHA.color}" fill-opacity="${EXPORT_WHITE_ALPHA.opacity}" stroke="none" />` +
      `<circle cx="${x}" cy="${y}" r="${EXPORT_ROOM_CHAIR_RADIUS}" fill="${colorLight.color}" fill-opacity="${colorLight.opacity}" stroke="${exportSettings.showGuestNames && !exportSettings.showChairNumbers ? "none" : color}" stroke-width="${strokeWidth}" />`;
  }
  const number = exportSettings.showChairNumbers
    ? `<text x="${x}" y="${centeredTextY(y, exportSettings.chairTextFontSizeMm)}" transform="rotate(${-exportSettings.roomRotation} ${x} ${y})" text-anchor="middle" font-size="${exportSettings.chairTextFontSizeMm}" fill="${color}">${chairNumbersToRender[chairSpot.chairId] ?? ""}</text>`
    : "";
  return `${circles}${number}`;
};

const renderRoomChairDotSvg = (chairSpot: ChairSpot): string => {
  if (exportSettings.chairStyle !== "small") return "";
  const table = allTables[chairSpot.tableId];
  const color = getRoomTableColor(table);
  const { x, y } = getChairRoomPosition(chairSpot, 0);
  const strokeWidth = EXPORT_ROOM_STROKE_WIDTH;

  return `<circle cx="${x}" cy="${y}" r="${EXPORT_ROOM_CHAIR_DOT_RADIUS}" fill="${color}" stroke="${color}" stroke-width="${strokeWidth}" />`;
};

type RoomChairAngleInfo = { angle: number; left: number; top: number };

// The chair's true final angle on the page (table.rotate + room rotation,
// clockwise-from-top like rotateXY elsewhere), bundled with its local
// pre-rotation position since round tables need an arc-length walk
// (getChairPosition) to get that, and every caller needs both.
const getRoomChairAngleInfo = (table: Table, chairSpot: ChairSpot): RoomChairAngleInfo => {
  const { left, top } = getChairPosition(
    table.width,
    table.height,
    chairSpot.chairType,
    chairSpot.chairNr,
  );

  let localAngle: number;
  if (chairSpot.chairType === "round") {
    // Round chairs are spaced by arc length, so the angle must come from the
    // local position. Same ellipse-normal trick as cursor.ts's roundResize:
    // the gradient of x²/a²+y²/b²=1 gives (x/a², y/b²), the outward normal.
    const a = table.width / 2;
    const b = table.height / 2;
    const dx = left - a;
    const dy = top - b;
    localAngle = (Math.atan2(dy / (b * b), dx / (a * a)) * RAD_TO_DEG + 90 + 360) % 360;
  } else {
    localAngle = { top: 0, right: 90, bottom: 180, left: 270 }[chairSpot.chairType];
  }

  const angle = (localAngle + table.rotate + exportSettings.roomRotation) % 360;
  return { angle, left, top };
};

// The two chairs immediately before/after `chairSpot` around a round table's
// ring, wrapping past chair 1 / the last chair.
const getRoomRoundTableNeighbours = (table: Table, chairSpot: ChairSpot): ChairSpot[] => {
  const nrOfChairs = Math.round(
    ellipseCircumference(table.width / 2, table.height / 2) / arcLenghtBetween2Chairs,
  );
  const previousNr = chairSpot.chairNr - 1 < 1 ? nrOfChairs : chairSpot.chairNr - 1;
  const nextNr = chairSpot.chairNr + 1 > nrOfChairs ? 1 : chairSpot.chairNr + 1;
  return [
    allChairSpots[getChairId(table.tableId, "round", previousNr)],
    allChairSpots[getChairId(table.tableId, "round", nextNr)],
  ];
};

// True when `chair` and `neighbour` would land close enough vertically (after
// room rotation), on the same half of the table, to visually collide — the
// label then needs to tilt away from horizontal.
const isRoomChairCloseToNeighbour = (
  chair: RoomChairAngleInfo,
  neighbourGuestId: GuestId | undefined,
  neighbour: RoomChairAngleInfo,
): boolean => {
  if (!neighbourGuestId) return false;

  const sameHalf = chair.angle >= 180 === neighbour.angle >= 180;
  if (!sameHalf) return false;

  const { y: verticalGap } = rotateXY(
    chair.left - neighbour.left,
    chair.top - neighbour.top,
    exportSettings.roomRotation * DEG_TO_RAD,
  );
  return Math.abs(verticalGap) < EXPORT_ROOM_NEIGHBOUR_COLLISION_DISTANCE;
};

const renderRoomGuestNameSvg = (
  chairSpot: ChairSpot,
  chairIdToGuestId: { [chairId: ChairId]: GuestId },
): string => {
  if (!exportSettings.showGuestNames) return "";

  const table = allTables[chairSpot.tableId];
  const color = getRoomTableColor(table);
  const { x, y } = getChairRoomPosition(
    chairSpot,
    exportSettings.chairStyle === "big" || exportSettings.showChairNumbers ? GAP_CHAIR_TABLE : 15,
  );

  const guestId = chairIdToGuestId[chairSpot.chairId];
  const guestName = guestId ? allGuests[guestId]?.name : undefined;
  if (!guestName) return "";

  const chair = getRoomChairAngleInfo(table, chairSpot);

  // Square/bench chairs have one guest per side (no neighbour to dodge) —
  // always tilt those for a consistent look. Round chairs tilt only to dodge
  // an actual collision.
  const needsTilt =
    chairSpot.chairType !== "round" ||
    getRoomRoundTableNeighbours(table, chairSpot).some((neighbourChairSpot) =>
      isRoomChairCloseToNeighbour(
        chair,
        chairIdToGuestId[neighbourChairSpot.chairId],
        getRoomChairAngleInfo(table, neighbourChairSpot),
      ),
    );

  const textAnchor = chair.angle < 180 ? "start" : "end";
  const numberShift = !exportSettings.showChairNumbers ? 0 : chair.angle < 180 ? 24 : -24;

  const TILT_DEGREES = 40;
  let rotate = 0;
  if (needsTilt) {
    if (chair.angle < TILT_DEGREES) rotate = chair.angle - TILT_DEGREES;
    if (180 - TILT_DEGREES <= chair.angle && chair.angle < 180)
      rotate = chair.angle - (180 - TILT_DEGREES);
    if (180 <= chair.angle && chair.angle < 180 + TILT_DEGREES)
      rotate = chair.angle - (180 + TILT_DEGREES);
    if (360 - TILT_DEGREES <= chair.angle) rotate = chair.angle - (360 - TILT_DEGREES);
  }

  const lines = exportSettings.wrapGuestNames
    ? wrapTextToWidth(
        guestName,
        EXPORT_ROOM_GUEST_NAME_MAX_WIDTH,
        exportSettings.chairTextFontSizeMm,
      )
    : [guestName];
  const lineHeightMm =
    exportSettings.chairTextFontSizeMm * EXPORT_ROOM_GUEST_NAME_LINE_HEIGHT_FACTOR;
  const tspans = lines
    .map((line, i) => {
      const lineY = centeredTextY(
        y + (i - (lines.length - 1) / 2) * lineHeightMm,
        exportSettings.chairTextFontSizeMm,
      );
      return `<tspan x="${x + numberShift}" y="${lineY}">${svgText(line)}</tspan>`;
    })
    .join("");

  return `<text transform="rotate(${rotate - exportSettings.roomRotation} ${x} ${y})" text-anchor="${textAnchor}" font-size="${exportSettings.chairTextFontSizeMm}" fill="${color}">${tspans}</text>`;
};

// The guests' page marks the chair a guest searched for: a dashed ring
// around it in the table colour's semi shade, drawn last so nothing paints over it,
// and set spinning by the page's stylesheet (guestPage.css). Never part of
// a PDF.
const EXPORT_ROOM_HIGHLIGHT_RADIUS = EXPORT_ROOM_CHAIR_RADIUS + 9;
const renderRoomChairHighlightSvg = (chairId: ChairId): string => {
  const chairSpot = allChairSpots[chairId];
  if (!chairSpot) return "";
  // Around the chair circle and its number (renderRoomChairSvg), whatever
  // the chair style: that is what the guest reads — unless the chair is
  // only a dot (renderRoomChairDotSvg) with no number beside it; then the
  // dot, at the table's edge, is what the ring goes around.
  const aroundDot = exportSettings.chairStyle === "small" && !exportSettings.showChairNumbers;
  const { x, y } = aroundDot ? getChairRoomPosition(chairSpot, 0) : getChairRoomPosition(chairSpot);
  // The table colour's semi shade: softer than the table's own line, but
  // not as faint as the chairs' fill.
  const table = allTables[chairSpot.tableId];
  const semi = resolveExportSemiColor(exportSettings.showColors ? table.colorToken : "black");
  return `<circle class="roomChairHighlight" cx="${x}" cy="${y}" r="${EXPORT_ROOM_HIGHLIGHT_RADIUS}" fill="none" stroke="${semi.color}" stroke-opacity="${semi.opacity}" stroke-width="${EXPORT_ROOM_STROKE_WIDTH * 2}" stroke-dasharray="9 12" stroke-linecap="round" />`;
};

// The whole room chart as a <g>, scaled/centered to fit inside `region` — a
// whole page normally, or half of one in combined mode.
const renderRoomChartSvg = (region: PageRegion, highlightChairId?: ChairId): string => {
  const unrotatedBounds = getRoomChartBounds(0, { x: 0, y: 0 });
  const roomPivotX = (unrotatedBounds.minX + unrotatedBounds.maxX) / 2;
  const roomPivotY = (unrotatedBounds.minY + unrotatedBounds.maxY) / 2;
  const bounds = getRoomChartBounds(exportSettings.roomRotation, {
    x: roomPivotX,
    y: roomPivotY,
  });
  const contentWidth = bounds.maxX - bounds.minX;
  const contentHeight = bounds.maxY - bounds.minY;

  const availWidth =
    region.width -
    (exportSettings.combineRoomAndList && exportSettings.orientation === "landscape"
      ? getExportPageMarginMm() + 15
      : 2 * getExportPageMarginMm());
  const availHeight =
    region.height -
    (exportSettings.combineRoomAndList && exportSettings.orientation === "portrait"
      ? getExportPageMarginMm() + 15
      : 2 * getExportPageMarginMm());
  // roomScale is a user-controlled multiplier on top of the auto-fit scale —
  // intentionally allowed to push content past the page's margins (even off
  // the page) rather than being clamped back to fit.
  const scale =
    Math.min(availWidth / contentWidth, availHeight / contentHeight) * exportSettings.roomScale;

  const offsetX = region.x + getExportPageMarginMm() + (availWidth - contentWidth * scale) / 2;
  const offsetY = region.y + getExportPageMarginMm() + (availHeight - contentHeight * scale) / 2;

  const chairIdToGuestId: { [chairId: ChairId]: GuestId } = {};
  for (const guestId of objectKeys(placement)) {
    chairIdToGuestId[placement[guestId]] = guestId;
  }

  const chairNumbersToRender = getExportChairNumbers();

  const chairSpotsByTableId: { [tableId: TableId]: ChairSpot[] } = {};
  for (const chairId of objectKeys(allChairSpots)) {
    const chairSpot = allChairSpots[chairId];
    if (!chairSpot.isChair || chairSpot.isHidden) continue;
    (chairSpotsByTableId[chairSpot.tableId] ??= []).push(chairSpot);
  }

  // In the room, a table and its chairs are one DOM stack sharing the table's
  // z-index. SVG paint order follows document order, so flat passes (all
  // tables, then all chairs, ...) would let a lower table's chairs paint over
  // a higher table. Grouping each table's shape+chairs+dots+names together,
  // in z-index order, restores the room's stacking.
  const tablesSvg = objectKeys(allTables)
    .sort((a, b) => allTables[a].zIndex - allTables[b].zIndex)
    .map((tableId) => {
      const table = allTables[tableId];
      const tableChairSpots = chairSpotsByTableId[tableId] ?? [];
      return `
        ${renderRoomTableSvg(table)}
        ${tableChairSpots.map((chairSpot) => renderRoomChairSvg(chairSpot, chairNumbersToRender)).join("")}
        ${tableChairSpots.map((chairSpot) => renderRoomChairDotSvg(chairSpot)).join("")}
        ${tableChairSpots.map((chairSpot) => renderRoomGuestNameSvg(chairSpot, chairIdToGuestId)).join("")}
      `;
    })
    .join("");

  // Pre-flattened into a single matrix() — svg2pdf.js 2.3.0 silently
  // mis-multiplies transform lists this long, pushing the whole chart off the
  // page with no error.
  const roomContentMatrix = new DOMMatrix()
    .translate(offsetX, offsetY)
    .scale(scale)
    .translate(-bounds.minX, -bounds.minY)
    .translate(roomPivotX, roomPivotY)
    .rotate(exportSettings.roomRotation)
    .translate(-roomPivotX, -roomPivotY);
  const { a, b, c, d, e, f } = roomContentMatrix;

  return `
    <g transform="matrix(${a} ${b} ${c} ${d} ${e} ${f})">
      ${tablesSvg}
      ${highlightChairId ? renderRoomChairHighlightSvg(highlightChairId) : ""}
    </g>
  `;
};
