pdf-factory 0.4.1 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/parser.cjs +1 -1
- package/dist/parser.cjs.map +1 -1
- package/dist/parser.js +89 -83
- package/dist/parser.js.map +1 -1
- package/dist/pdf-factory.cjs +1 -1
- package/dist/pdf-factory.cjs.map +1 -1
- package/dist/pdf-factory.js +170 -170
- package/dist/pdf-factory.js.map +1 -1
- package/dist/src/generators/report.d.ts.map +1 -1
- package/package.json +10 -10
package/dist/pdf-factory.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pdf-factory.cjs","names":[],"sources":["../src/config/formatPresets.ts","../src/config/compositionCatalog.ts","../src/config/factSheetCatalog.ts","../src/core/drawsDataToDrawData.ts","../src/composition/page.ts","../src/layout/fonts.ts","../src/composition/headerLayouts.ts","../src/composition/tournamentBridge.ts","../src/composition/footerLayouts.ts","../src/composition/seedingsFooter.ts","../src/composition/printDispatcher.ts","../src/composition/editorTypes.ts","../src/composition/printModalTypes.ts","../src/utils/primitives.ts","../src/core/extractDrawData.ts","../src/core/extractScheduleData.ts","../src/core/extractParticipantData.ts","../src/core/extractCourtCardData.ts","../src/core/extractRoundRobinData.ts","../src/renderers/formatEntry.ts","../src/renderers/traditionalDraw.ts","../src/renderers/roundRobinDraw.ts","../src/renderers/luckyDraw.ts","../src/renderers/drawSplitter.ts","../src/renderers/compassDraw.ts","../src/renderers/consolationDraw.ts","../src/renderers/doubleEliminationDraw.ts","../src/core/extractCompassData.ts","../src/layout/headers.ts","../src/layout/tables.ts","../src/layout/brackets.ts","../src/generators/drawSheet.ts","../src/generators/schedule.ts","../src/generators/playerList.ts","../src/generators/courtCard.ts","../src/generators/signInSheet.ts","../src/generators/scheduleV2.ts","../src/generators/sequentialOOP.ts","../src/generators/matchCard.ts","../src/generators/report.ts","../src/generators/factSheet.ts","../src/renderers/mirroredDraw.ts","../src/renderers/backdrawDraw.ts","../src/generators/drawPDF.ts","../src/generators/generateFromEventData.ts"],"sourcesContent":["import type { DrawFormatConfig } from './types';\n\nconst ENGLISH_ROUNDS: Record<string, string> = {\n F: 'Final',\n SF: 'Semi-Finals',\n QF: 'Quarter-Finals',\n R16: 'Round of 16',\n R32: 'Round of 32',\n R64: 'Round of 64',\n R128: 'Round of 128',\n};\n\nconst WIMBLEDON_ROUNDS: Record<string, string> = {\n F: 'Final',\n SF: 'Semi-Finals',\n QF: 'Quarter-Finals',\n R16: 'Fourth Round',\n R32: 'Third Round',\n R64: 'Second Round',\n R128: 'First Round',\n};\n\nconst USOPEN_ROUNDS: Record<string, string> = {\n F: 'Final',\n SF: 'Semifinals',\n QF: 'Quarterfinals',\n R16: 'Round 4',\n R32: 'Round 3',\n R64: 'Round 2',\n R128: 'Round 1',\n};\n\nconst FRENCH_ROUNDS: Record<string, string> = {\n F: 'FINALE',\n SF: '1/2 FINALE',\n QF: '1/4 FINALE',\n R16: '1/8 FINALE',\n R32: '3eme TOUR',\n R64: '2eme TOUR',\n R128: '1er TOUR',\n};\n\nconst DEFAULT_PAGE = {\n pageSize: 'a4' as const,\n orientation: 'auto' as const,\n margins: { top: 15, right: 10, bottom: 15, left: 10 },\n};\n\n// Shared values extracted for sonarjs/no-duplicate-string\nconst LAST_COMMA_FIRST = 'LAST, First' as const;\nconst NAT_BARE = 'bare' as const;\nconst SEED_BEFORE = 'before-position' as const;\nconst SEED_BRACKETS = 'brackets' as const;\nconst GAME_HYPHEN = '-' as const;\nconst TRADITIONAL = 'traditional-lines' as const;\n\nexport const PRESETS: Record<string, DrawFormatConfig> = {\n wimbledon: {\n nameFormat: LAST_COMMA_FIRST,\n nationalityFormat: NAT_BARE,\n seedPosition: SEED_BEFORE,\n seedFormat: SEED_BRACKETS,\n entryFormat: 'parens',\n gameScoreSeparator: GAME_HYPHEN,\n setScoreSeparator: ' ',\n retirementLabel: 'Ret.',\n walkoverLabel: 'w/o',\n roundLabels: WIMBLEDON_ROUNDS,\n renderStyle: TRADITIONAL,\n page: { ...DEFAULT_PAGE },\n },\n\n usOpen: {\n nameFormat: LAST_COMMA_FIRST,\n nationalityFormat: NAT_BARE,\n seedPosition: SEED_BEFORE,\n seedFormat: SEED_BRACKETS,\n entryFormat: 'parens',\n gameScoreSeparator: GAME_HYPHEN,\n setScoreSeparator: ' | ',\n retirementLabel: 'Ret.',\n walkoverLabel: 'w/o',\n roundLabels: USOPEN_ROUNDS,\n renderStyle: TRADITIONAL,\n page: { ...DEFAULT_PAGE },\n },\n\n rolandGarros: {\n nameFormat: 'LAST First',\n nationalityFormat: NAT_BARE,\n seedPosition: 'after-country',\n seedFormat: SEED_BRACKETS,\n entryFormat: 'parens',\n gameScoreSeparator: '/',\n setScoreSeparator: ' ',\n retirementLabel: 'Ab',\n walkoverLabel: 'w/o',\n roundLabels: FRENCH_ROUNDS,\n renderStyle: TRADITIONAL,\n page: { ...DEFAULT_PAGE },\n },\n\n australianOpen: {\n nameFormat: LAST_COMMA_FIRST,\n nationalityFormat: 'parens',\n seedPosition: 'after-name',\n seedFormat: SEED_BRACKETS,\n entryFormat: 'hyphen',\n gameScoreSeparator: '/',\n setScoreSeparator: ' ',\n retirementLabel: 'Ret.',\n walkoverLabel: 'w/o',\n roundLabels: ENGLISH_ROUNDS,\n renderStyle: TRADITIONAL,\n page: { ...DEFAULT_PAGE, pageSize: 'letter' as const, orientation: 'portrait' as const },\n },\n\n itfJunior: {\n nameFormat: LAST_COMMA_FIRST,\n nationalityFormat: NAT_BARE,\n seedPosition: SEED_BEFORE,\n seedFormat: SEED_BRACKETS,\n entryFormat: 'bare',\n gameScoreSeparator: GAME_HYPHEN,\n setScoreSeparator: ' ',\n retirementLabel: 'Ret.',\n walkoverLabel: 'w/o',\n roundLabels: ENGLISH_ROUNDS,\n renderStyle: TRADITIONAL,\n page: { ...DEFAULT_PAGE },\n },\n\n usta: {\n nameFormat: LAST_COMMA_FIRST,\n nationalityFormat: NAT_BARE,\n seedPosition: SEED_BEFORE,\n seedFormat: SEED_BRACKETS,\n entryFormat: 'bare',\n gameScoreSeparator: GAME_HYPHEN,\n setScoreSeparator: ' ',\n retirementLabel: 'Ret.',\n walkoverLabel: 'W/O',\n roundLabels: ENGLISH_ROUNDS,\n renderStyle: TRADITIONAL,\n page: { ...DEFAULT_PAGE },\n },\n};\n\nexport function getPreset(name: string): DrawFormatConfig {\n return PRESETS[name] || PRESETS.itfJunior;\n}\n\nexport function mergePreset(name: string, overrides: Partial<DrawFormatConfig>): DrawFormatConfig {\n return { ...getPreset(name), ...overrides };\n}\n","/**\n * Composition Catalog — named presets for PDF header/footer/layout combinations.\n *\n * Analogous to matchUpFormat catalogs in the factory, these presets bundle\n * header layout, footer layout, draw format, and page config into named units.\n * Tournament directors select a preset and optionally override individual fields.\n *\n * TMX flow: provider defaults → catalog preset → tournament director overrides\n */\n\nimport type { HeaderConfig, FooterConfig, PageConfig } from './types';\n\nconst ITF_JUNIOR_PRESET = 'itfJunior';\nconst COMBINED_TOUR_FOOTER = 'combined-tour' as const;\nconst GRAND_SLAM = 'grand-slam' as const;\nconst OFFICIALS_SIGNOFF = 'officials-signoff' as const;\n\nexport interface CompositionPreset {\n id: string;\n name: string;\n description: string;\n category: 'grand-slam' | 'tour' | 'itf' | 'national' | 'collegiate' | 'club';\n tier: 1 | 2 | 3;\n header: Partial<HeaderConfig>;\n footer: Partial<FooterConfig>;\n page?: Partial<PageConfig>;\n drawFormatPreset?: string;\n}\n\nexport const COMPOSITION_CATALOG: Record<string, CompositionPreset> = {\n [GRAND_SLAM]: {\n id: GRAND_SLAM,\n name: 'Grand Slam',\n description: 'Minimal chrome — large tournament name, timestamp footer',\n category: GRAND_SLAM,\n tier: 1,\n header: { layout: GRAND_SLAM },\n footer: { layout: 'standard', showPageNumbers: true, showTimestamp: true },\n drawFormatPreset: 'wimbledon',\n },\n wimbledon: {\n id: 'wimbledon',\n name: 'Wimbledon',\n description: 'Green/purple Grand Slam style with crest',\n category: GRAND_SLAM,\n tier: 1,\n header: { layout: GRAND_SLAM },\n footer: { layout: 'standard', showPageNumbers: true, showTimestamp: true },\n drawFormatPreset: 'wimbledon',\n },\n 'australian-open': {\n id: 'australian-open',\n name: 'Australian Open',\n description: 'Grand Slam with seedings + prize money footer',\n category: GRAND_SLAM,\n tier: 2,\n header: { layout: GRAND_SLAM },\n footer: { layout: COMBINED_TOUR_FOOTER, showPageNumbers: true, showTimestamp: true },\n drawFormatPreset: 'australianOpen',\n },\n 'wta-500': {\n id: 'wta-500',\n name: 'WTA 500',\n description: 'Tour header with logos, seedings + prize money footer',\n category: 'tour',\n tier: 2,\n header: { layout: 'wta-tour' },\n footer: { layout: COMBINED_TOUR_FOOTER, showPageNumbers: false, showTimestamp: true },\n drawFormatPreset: ITF_JUNIOR_PRESET,\n },\n 'wta-1000': {\n id: 'wta-1000',\n name: 'WTA 1000',\n description: 'Tour header with logos, full footer with officials',\n category: 'tour',\n tier: 2,\n header: { layout: 'wta-tour' },\n footer: { layout: COMBINED_TOUR_FOOTER, showPageNumbers: false, showTimestamp: true },\n drawFormatPreset: ITF_JUNIOR_PRESET,\n },\n 'atp-250': {\n id: 'atp-250',\n name: 'ATP 250',\n description: 'ATP tour header, seedings + prize money footer with sign-off',\n category: 'tour',\n tier: 2,\n header: { layout: 'wta-tour' },\n footer: { layout: COMBINED_TOUR_FOOTER, showPageNumbers: false, showTimestamp: true },\n drawFormatPreset: ITF_JUNIOR_PRESET,\n },\n 'atp-finals': {\n id: 'atp-finals',\n name: 'ATP Finals',\n description: 'Full official sign-off with signature lines',\n category: 'tour',\n tier: 3,\n header: { layout: GRAND_SLAM },\n footer: { layout: OFFICIALS_SIGNOFF, showTimestamp: true },\n drawFormatPreset: ITF_JUNIOR_PRESET,\n },\n 'itf-junior': {\n id: 'itf-junior',\n name: 'ITF Junior',\n description: 'ITF header with metadata row, officials sign-off footer',\n category: 'itf',\n tier: 3,\n header: { layout: 'itf' },\n footer: { layout: OFFICIALS_SIGNOFF, showPageNumbers: true, showTimestamp: true },\n drawFormatPreset: ITF_JUNIOR_PRESET,\n },\n 'itf-pro-circuit': {\n id: 'itf-pro-circuit',\n name: 'ITF Pro Circuit',\n description: 'ITF header, seedings + officials footer',\n category: 'itf',\n tier: 2,\n header: { layout: 'itf' },\n footer: { layout: COMBINED_TOUR_FOOTER, showPageNumbers: true, showTimestamp: true },\n drawFormatPreset: ITF_JUNIOR_PRESET,\n },\n 'national-federation': {\n id: 'national-federation',\n name: 'National Federation',\n description: 'Detailed metadata header, full sign-off footer with ceremony date',\n category: 'national',\n tier: 3,\n header: { layout: 'national-federation' },\n footer: { layout: OFFICIALS_SIGNOFF, showPageNumbers: true, showTimestamp: true },\n drawFormatPreset: 'usta',\n },\n 'collegiate-ncaa': {\n id: 'collegiate-ncaa',\n name: 'NCAA Collegiate',\n description: 'Mirrored bracket layout, team logos, minimal footer',\n category: 'collegiate',\n tier: 1,\n header: { layout: GRAND_SLAM },\n footer: { layout: 'standard', showPageNumbers: true, showTimestamp: true },\n drawFormatPreset: ITF_JUNIOR_PRESET,\n },\n 'club-basic': {\n id: 'club-basic',\n name: 'Club Basic',\n description: 'Minimal header, standard footer — clean and simple',\n category: 'club',\n tier: 1,\n header: { layout: 'minimal' },\n footer: { layout: 'standard', showPageNumbers: true, showTimestamp: true },\n drawFormatPreset: ITF_JUNIOR_PRESET,\n },\n};\n\nexport function getCatalogPreset(id: string): CompositionPreset | undefined {\n return COMPOSITION_CATALOG[id];\n}\n\nexport function listCatalogPresets(category?: string): CompositionPreset[] {\n const entries = Object.values(COMPOSITION_CATALOG);\n return category ? entries.filter((e) => e.category === category) : entries;\n}\n\nexport function mergeCatalogPreset(\n id: string,\n headerOverrides?: Partial<HeaderConfig>,\n footerOverrides?: Partial<FooterConfig>,\n): { header: Partial<HeaderConfig>; footer: Partial<FooterConfig> } {\n const preset = COMPOSITION_CATALOG[id] || COMPOSITION_CATALOG['club-basic'];\n return {\n header: { ...preset.header, ...headerOverrides },\n footer: { ...preset.footer, ...footerOverrides },\n };\n}\n","/**\n * Fact Sheet Catalog — template presets defining which sections to include per governing body.\n *\n * Parallels compositionCatalog.ts (draw sheet presets) but for tournament fact sheets.\n * Each preset declares which sections are enabled, in what order, and which header/footer\n * composition preset to inherit from.\n */\n\nimport type { HeaderLayout } from './types';\n\nexport type FactSheetSectionType =\n | 'tournament-header'\n | 'contacts'\n | 'events'\n | 'entry-info'\n | 'venue-info'\n | 'accommodation'\n | 'transportation'\n | 'hospitality'\n | 'medical'\n | 'regulations'\n | 'prize-money'\n | 'officials'\n | 'sponsors'\n | 'social-events'\n | 'custom-notes';\n\nexport interface FactSheetSection {\n type: FactSheetSectionType;\n title?: string;\n enabled: boolean;\n}\n\nexport interface FactSheetTemplate {\n id: string;\n name: string;\n description: string;\n category: 'itf' | 'national' | 'tour' | 'club' | 'custom';\n headerLayout: HeaderLayout;\n sections: FactSheetSection[];\n}\n\nconst TOURNAMENT_HEADER: FactSheetSectionType = 'tournament-header';\nconst CONTACTS: FactSheetSectionType = 'contacts';\nconst EVENTS: FactSheetSectionType = 'events';\nconst ENTRY_INFO: FactSheetSectionType = 'entry-info';\nconst VENUE_INFO: FactSheetSectionType = 'venue-info';\nconst ACCOMMODATION: FactSheetSectionType = 'accommodation';\nconst TRANSPORTATION: FactSheetSectionType = 'transportation';\nconst HOSPITALITY: FactSheetSectionType = 'hospitality';\nconst MEDICAL: FactSheetSectionType = 'medical';\nconst REGULATIONS: FactSheetSectionType = 'regulations';\nconst PRIZE_MONEY: FactSheetSectionType = 'prize-money';\nconst OFFICIALS: FactSheetSectionType = 'officials';\nconst SPONSORS: FactSheetSectionType = 'sponsors';\nconst SOCIAL_EVENTS: FactSheetSectionType = 'social-events';\nconst CUSTOM_NOTES: FactSheetSectionType = 'custom-notes';\n\nfunction section(type: FactSheetSectionType, enabled = true, title?: string): FactSheetSection {\n return { type, enabled, ...(title && { title }) };\n}\n\nconst FULL_SECTIONS: FactSheetSection[] = [\n section(TOURNAMENT_HEADER),\n section(CONTACTS),\n section(EVENTS),\n section(ENTRY_INFO),\n section(VENUE_INFO),\n section(ACCOMMODATION),\n section(TRANSPORTATION),\n section(HOSPITALITY),\n section(MEDICAL),\n section(REGULATIONS),\n section(PRIZE_MONEY),\n section(OFFICIALS),\n section(SPONSORS),\n section(SOCIAL_EVENTS),\n section(CUSTOM_NOTES),\n];\n\nexport const FACT_SHEET_CATALOG: Record<string, FactSheetTemplate> = {\n 'itf-junior': {\n id: 'itf-junior',\n name: 'ITF Junior',\n description: 'Full fact sheet with all sections — ITF header style',\n category: 'itf',\n headerLayout: 'itf',\n sections: FULL_SECTIONS,\n },\n 'itf-pro-circuit': {\n id: 'itf-pro-circuit',\n name: 'ITF Pro Circuit',\n description: 'Pro circuit fact sheet — contacts, events, entry, venue, prize money, officials',\n category: 'itf',\n headerLayout: 'itf',\n sections: [\n section(TOURNAMENT_HEADER),\n section(CONTACTS),\n section(EVENTS),\n section(ENTRY_INFO),\n section(VENUE_INFO),\n section(PRIZE_MONEY),\n section(OFFICIALS),\n section(REGULATIONS),\n section(CUSTOM_NOTES),\n ],\n },\n 'national-federation': {\n id: 'national-federation',\n name: 'National Federation',\n description: 'Detailed national federation fact sheet with all logistics',\n category: 'national',\n headerLayout: 'national-federation',\n sections: FULL_SECTIONS,\n },\n 'tour-atp-wta': {\n id: 'tour-atp-wta',\n name: 'ATP/WTA Tour',\n description: 'Tour-level fact sheet — contacts, events, prize money, officials, sponsors',\n category: 'tour',\n headerLayout: 'wta-tour',\n sections: [\n section(TOURNAMENT_HEADER),\n section(CONTACTS),\n section(EVENTS),\n section(PRIZE_MONEY),\n section(OFFICIALS),\n section(SPONSORS),\n section(ACCOMMODATION),\n section(TRANSPORTATION),\n section(SOCIAL_EVENTS),\n section(CUSTOM_NOTES),\n ],\n },\n 'club-basic': {\n id: 'club-basic',\n name: 'Club Basic',\n description: 'Simple club-level fact sheet — essentials only',\n category: 'club',\n headerLayout: 'minimal',\n sections: [\n section(TOURNAMENT_HEADER),\n section(CONTACTS),\n section(EVENTS),\n section(ENTRY_INFO),\n section(VENUE_INFO),\n section(CUSTOM_NOTES),\n ],\n },\n};\n\nexport function getFactSheetTemplate(id: string): FactSheetTemplate | undefined {\n return FACT_SHEET_CATALOG[id];\n}\n\nexport function listFactSheetTemplates(category?: string): FactSheetTemplate[] {\n const entries = Object.values(FACT_SHEET_CATALOG);\n return category ? entries.filter((t) => t.category === category) : entries;\n}\n","/**\n * Converts drawsData structures (from tournamentEngine.getEventData())\n * into DrawData for pdf-factory renderers.\n *\n * This is the standard data pipeline for TMX integration:\n * getEventData({ drawId }) → eventData.drawsData → structureToDrawData() → renderer\n */\n\nimport type { DrawData, DrawSlot, DrawMatchUp } from './extractDrawData';\n\n/** Convert a single drawsData structure into DrawData */\nexport function structureToDrawData(struct: any): DrawData {\n const roundMatchUps = struct.roundMatchUps || {};\n const roundProfile = struct.roundProfile || {};\n const roundNumbers = Object.keys(roundMatchUps)\n .map(Number)\n .sort((a, b) => a - b);\n\n // Build slots from all matchUp sides (deduplicate by drawPosition)\n const slotMap = new Map<number, DrawSlot>();\n for (const rn of roundNumbers) {\n for (const mu of roundMatchUps[rn] || []) {\n for (const side of mu.sides || []) {\n if (side?.drawPosition && !slotMap.has(side.drawPosition)) {\n // entryStatus: prefer side-level (future), fall back to participant-level\n const entryStatus = side.entryStatus || side.participant?.entryStatus;\n // Normalize: don't store DIRECT_ACCEPTANCE (the default)\n const displayEntryStatus = entryStatus && entryStatus !== 'DIRECT_ACCEPTANCE' ? entryStatus : undefined;\n\n slotMap.set(side.drawPosition, {\n drawPosition: side.drawPosition,\n participantName: side.participant?.participantName || '',\n nationality: side.participant?.nationalityCode || '',\n seedValue: side.seedValue,\n entryStatus: displayEntryStatus,\n isBye: side.bye === true,\n });\n }\n }\n }\n }\n\n // Build matchUps\n const matchUps: DrawMatchUp[] = [];\n for (const rn of roundNumbers) {\n for (const mu of roundMatchUps[rn] || []) {\n matchUps.push({\n roundNumber: mu.roundNumber,\n roundPosition: mu.roundPosition,\n drawPositions: mu.drawPositions || [],\n score: mu.score?.scoreStringSide1 || '',\n winningSide: mu.winningSide,\n matchUpStatus: mu.matchUpStatus,\n });\n }\n }\n\n // Build roundLabelMap from roundProfile\n const roundLabelMap: Record<number, string> = {};\n for (const rn of roundNumbers) {\n const rp = roundProfile[rn];\n roundLabelMap[rn] = rp?.abbreviatedRoundName || rp?.roundName || `R${rn}`;\n }\n\n const totalRounds = roundNumbers.length > 0 ? Math.max(...roundNumbers) : 0;\n const slots = [...slotMap.values()].sort((a, b) => a.drawPosition - b.drawPosition);\n\n // Qualifying structures don't resolve to a single winner — suppress the winner column\n const isQualifying = struct.stage === 'QUALIFYING';\n // Also detect non-qualifying structures that end with multiple matchUps (no single final)\n const finalRoundMatchUps = roundMatchUps[totalRounds]?.length || 0;\n const noWinnerColumn = isQualifying || finalRoundMatchUps > 1;\n\n return {\n drawName: struct.structureName || '',\n drawSize: slots.length,\n drawType: 'SINGLE_ELIMINATION',\n totalRounds,\n noWinnerColumn,\n slots,\n matchUps,\n seedAssignments: (struct.seedAssignments || [])\n .filter((sa: any) => sa.participantName)\n .map((sa: any) => ({\n seedValue: sa.seedValue,\n participantName: sa.participantName || '',\n nationality: sa.nationalityCode || '',\n })),\n roundLabelMap,\n };\n}\n\n/** Find a structure by stage from drawsData */\nexport function findStructure(drawsData: any[], stage: string): any {\n return drawsData?.[0]?.structures?.find((s: any) => s.stage === stage);\n}\n","import jsPDF from 'jspdf';\nimport type { PageConfig, PageRegions } from '../config/types';\n\nconst PAGE_DIMENSIONS: Record<string, { width: number; height: number }> = {\n a4: { width: 210, height: 297 },\n letter: { width: 216, height: 279 },\n};\n\nexport function createDoc(config: PageConfig, drawSize?: number): jsPDF {\n let orientation = config.orientation;\n if (orientation === 'auto') {\n orientation = drawSize && drawSize >= 32 ? 'landscape' : 'portrait';\n }\n return new jsPDF({ orientation, format: config.pageSize, unit: 'mm' });\n}\n\nexport function getPageRegions(\n doc: jsPDF,\n config: PageConfig,\n headerHeight: number,\n footerHeight: number,\n): PageRegions {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const { margins } = config;\n\n const contentY = margins.top + headerHeight;\n const contentHeight = pageHeight - margins.top - margins.bottom - headerHeight - footerHeight;\n const contentWidth = pageWidth - margins.left - margins.right;\n\n return {\n headerHeight,\n footerHeight,\n contentY,\n contentHeight,\n contentWidth,\n pageWidth,\n pageHeight,\n };\n}\n\nexport function getDefaultPageConfig(): PageConfig {\n return {\n pageSize: 'a4',\n orientation: 'auto',\n margins: { top: 15, right: 10, bottom: 15, left: 10 },\n };\n}\n\nexport { PAGE_DIMENSIONS };\n","import jsPDF from 'jspdf';\n\nexport const FONT = {\n REGULAR: 'helvetica',\n BOLD: 'helvetica',\n} as const;\n\nexport const STYLE = {\n NORMAL: 'normal' as const,\n BOLD: 'bold' as const,\n ITALIC: 'italic' as const,\n};\n\nexport const SIZE = {\n TITLE: 16,\n SUBTITLE: 12,\n HEADING: 10,\n BODY: 8,\n SMALL: 7,\n TINY: 6,\n};\n\nexport function setFont(doc: jsPDF, size: number, style: string = STYLE.NORMAL) {\n doc.setFont(FONT.REGULAR, style);\n doc.setFontSize(size);\n}\n","import jsPDF from 'jspdf';\nimport type { HeaderConfig, PageConfig } from '../config/types';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport function renderHeader(doc: jsPDF, config: HeaderConfig, pageConfig: PageConfig): number {\n switch (config.layout) {\n case 'grand-slam':\n return renderGrandSlamHeader(doc, config, pageConfig);\n case 'itf':\n return renderItfHeader(doc, config, pageConfig);\n case 'minimal':\n return renderMinimalHeader(doc, config, pageConfig);\n case 'wta-tour':\n return renderWtaTourHeader(doc, config, pageConfig);\n case 'national-federation':\n return renderNationalFederationHeader(doc, config, pageConfig);\n case 'none':\n return 0;\n }\n}\n\nfunction renderGrandSlamHeader(doc: jsPDF, config: HeaderConfig, pageConfig: PageConfig): number {\n const { margins } = pageConfig;\n const pageWidth = doc.internal.pageSize.getWidth();\n const rightEdge = pageWidth - margins.right;\n let y = margins.top;\n\n setFont(doc, 18, STYLE.BOLD);\n doc.text(config.tournamentName.toUpperCase(), pageWidth / 2, y, { align: 'center' });\n y += 7;\n\n if (config.subtitle) {\n setFont(doc, 12, STYLE.BOLD);\n doc.text(config.subtitle.toUpperCase(), pageWidth / 2, y, { align: 'center' });\n y += 6;\n }\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n const metaLines: string[] = [];\n if (config.startDate) {\n const dateStr = config.endDate ? `${config.startDate} - ${config.endDate}` : config.startDate;\n metaLines.push(dateStr);\n }\n if (config.location) metaLines.push(config.location);\n metaLines.forEach((line, i) => {\n doc.text(line, rightEdge, margins.top + i * 4, { align: 'right' });\n });\n\n y += 2;\n doc.setDrawColor(0);\n doc.setLineWidth(0.5);\n doc.line(margins.left, y, rightEdge, y);\n y += 3;\n\n return y - margins.top;\n}\n\nfunction renderItfHeader(doc: jsPDF, config: HeaderConfig, pageConfig: PageConfig): number {\n const { margins } = pageConfig;\n const pageWidth = doc.internal.pageSize.getWidth();\n const rightEdge = pageWidth - margins.right;\n let y = margins.top;\n\n setFont(doc, SIZE.TITLE, STYLE.BOLD);\n doc.text(config.tournamentName, margins.left, y);\n y += 6;\n\n if (config.subtitle) {\n setFont(doc, SIZE.SUBTITLE, STYLE.BOLD);\n doc.text(config.subtitle, margins.left, y);\n y += 5;\n }\n\n setFont(doc, SIZE.SMALL, STYLE.NORMAL);\n const rightLines: string[] = [];\n if (config.grade) rightLines.push(`Grade: ${config.grade}`);\n if (config.surface) rightLines.push(`Surface: ${config.surface}`);\n if (config.supervisor) rightLines.push(`Supervisor: ${config.supervisor}`);\n rightLines.forEach((line, i) => {\n doc.text(line, rightEdge, margins.top + i * 3.5, { align: 'right' });\n });\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n const infoLine: string[] = [];\n if (config.startDate) infoLine.push(config.startDate);\n if (config.location) infoLine.push(config.location);\n if (config.organizer) infoLine.push(config.organizer);\n if (infoLine.length) {\n doc.text(infoLine.join(' | '), margins.left, y);\n y += 4;\n }\n\n y += 1;\n doc.setDrawColor(0);\n doc.setLineWidth(0.3);\n doc.line(margins.left, y, rightEdge, y);\n y += 3;\n\n return y - margins.top;\n}\n\nfunction renderMinimalHeader(doc: jsPDF, config: HeaderConfig, pageConfig: PageConfig): number {\n const { margins } = pageConfig;\n let y = margins.top;\n\n setFont(doc, SIZE.SUBTITLE, STYLE.BOLD);\n doc.text(config.tournamentName, margins.left, y);\n const nameWidth = doc.getTextWidth(config.tournamentName);\n\n if (config.subtitle) {\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n doc.text(` - ${config.subtitle}`, margins.left + nameWidth, y);\n }\n\n y += 6;\n return y - margins.top;\n}\n\n/**\n * WTA/ATP Tour header — flanking logos, centered tournament info, section label.\n *\n * Layout:\n * [Left Logo] TOURNAMENT NAME [Right Logo]\n * City, Country\n * Dates | Prize Money | Surface\n * SINGLES MAIN DRAW\n * ─────────────────────────────────────────────────────\n */\nfunction renderWtaTourHeader(doc: jsPDF, config: HeaderConfig, pageConfig: PageConfig): number {\n const { margins } = pageConfig;\n const pageWidth = doc.internal.pageSize.getWidth();\n const rightEdge = pageWidth - margins.right;\n const centerX = pageWidth / 2;\n let y = margins.top;\n\n // Logos (if provided as base64)\n const logoSize = 12;\n if (config.leftLogoBase64) {\n try {\n doc.addImage(config.leftLogoBase64, 'PNG', margins.left, y - 2, logoSize, logoSize);\n } catch {\n /* logo failed to load */\n }\n }\n if (config.rightLogoBase64) {\n try {\n doc.addImage(config.rightLogoBase64, 'PNG', rightEdge - logoSize, y - 2, logoSize, logoSize);\n } catch {\n /* logo failed to load */\n }\n }\n\n // Tournament name — centered, large\n setFont(doc, 14, STYLE.BOLD);\n doc.text(config.tournamentName, centerX, y, { align: 'center' });\n y += 5;\n\n // City, Country\n const cityCountry = [config.city, config.country].filter(Boolean).join(', ');\n if (cityCountry) {\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n doc.setTextColor(80);\n doc.text(cityCountry.toUpperCase(), centerX, y, { align: 'center' });\n doc.setTextColor(0);\n y += 4;\n }\n\n // Dates | Prize Money | Surface\n const detailParts: string[] = [];\n if (config.startDate) {\n const dateStr = config.endDate ? `${config.startDate} - ${config.endDate}` : config.startDate;\n detailParts.push(dateStr);\n }\n if (config.prizeMoney) {\n const money = config.currency ? `${config.currency} ${config.prizeMoney}` : config.prizeMoney;\n detailParts.push(money);\n }\n if (config.surface) detailParts.push(config.surface);\n if (detailParts.length) {\n setFont(doc, SIZE.SMALL, STYLE.NORMAL);\n doc.text(detailParts.join(' | '), centerX, y, { align: 'center' });\n y += 4;\n }\n\n // Section label — right-aligned (e.g., \"SINGLES MAIN DRAW\", \"TOP HALF\")\n if (config.sectionLabel) {\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.text(config.sectionLabel.toUpperCase(), rightEdge, y, { align: 'right' });\n y += 3;\n }\n\n // Separator\n y += 1;\n doc.setDrawColor(0);\n doc.setLineWidth(0.3);\n doc.line(margins.left, y, rightEdge, y);\n y += 3;\n\n return y - margins.top;\n}\n\n/**\n * National Federation header — detailed metadata row.\n *\n * Layout:\n * TOURNAMENT NAME [Federation Logo]\n * Subtitle (event name)\n * Date | Organizer | City | Tournament ID | Grade | Chief Umpire\n * ─────────────────────────────────────────────────────────────\n */\nfunction renderNationalFederationHeader(doc: jsPDF, config: HeaderConfig, pageConfig: PageConfig): number {\n const { margins } = pageConfig;\n const pageWidth = doc.internal.pageSize.getWidth();\n const rightEdge = pageWidth - margins.right;\n let y = margins.top;\n\n // Logo right-aligned\n if (config.rightLogoBase64) {\n try {\n doc.addImage(config.rightLogoBase64, 'PNG', rightEdge - 14, y - 2, 14, 14);\n } catch {\n /* logo failed */\n }\n }\n\n // Tournament name — left, large\n setFont(doc, SIZE.TITLE, STYLE.BOLD);\n doc.text(config.tournamentName, margins.left, y);\n y += 6;\n\n // Subtitle\n if (config.subtitle) {\n setFont(doc, SIZE.HEADING, STYLE.BOLD);\n doc.text(config.subtitle, margins.left, y);\n y += 4;\n }\n\n // Metadata row\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.setTextColor(80);\n const metaParts: string[] = [];\n if (config.startDate) metaParts.push(config.startDate);\n if (config.organizer) metaParts.push(config.organizer);\n if (config.city || config.country) metaParts.push([config.city, config.country].filter(Boolean).join(', '));\n if (config.tournamentId) metaParts.push(`ID: ${config.tournamentId}`);\n if (config.grade) metaParts.push(`Grade: ${config.grade}`);\n if (config.chiefUmpire) metaParts.push(`Umpire: ${config.chiefUmpire}`);\n if (metaParts.length) {\n doc.text(metaParts.join(' | '), margins.left, y);\n y += 3;\n }\n doc.setTextColor(0);\n\n // Separator\n y += 1;\n doc.setDrawColor(0);\n doc.setLineWidth(0.3);\n doc.line(margins.left, y, rightEdge, y);\n y += 3;\n\n return y - margins.top;\n}\n","/**\n * Tournament Bridge — auto-populates HeaderConfig and FooterConfig from tournament record data.\n *\n * This is the bridge between factory's structured data and pdf-factory's rendering configs.\n * Factory provides the data; this module provides the mapping. Factory purity is preserved.\n */\n\nimport type { HeaderConfig, HeaderLayout, FooterConfig, FooterLayout } from '../config/types';\n\ninterface TournamentRecord {\n tournamentId?: string;\n tournamentName?: string;\n formalName?: string;\n startDate?: string;\n endDate?: string;\n hostCountryCode?: string;\n surfaceCategory?: string;\n totalPrizeMoney?: { amount: number; currencyCode: string }[];\n tournamentLevel?: string;\n tournamentTier?: { system?: string; value?: string };\n venues?: Venue[];\n participants?: Participant[];\n registrationProfile?: RegistrationProfile;\n}\n\ninterface Venue {\n venueName?: string;\n addresses?: { city?: string; state?: string; countryCode?: string }[];\n}\n\ninterface Participant {\n participantName?: string;\n participantRole?: string;\n participantRoleResponsibilities?: string[];\n person?: {\n standardGivenName?: string;\n standardFamilyName?: string;\n contacts?: { emailAddress?: string; telephone?: string; mobileTelephone?: string }[];\n };\n}\n\ninterface RegistrationProfile {\n drawCeremonyDate?: string;\n sponsors?: { name: string; tier?: string }[];\n}\n\nfunction formatParticipantName(p: Participant): string {\n const person = p.person;\n if (person?.standardFamilyName) {\n const given = person.standardGivenName || '';\n return given ? person.standardFamilyName + ', ' + given : person.standardFamilyName;\n }\n return p.participantName || '';\n}\n\nfunction findParticipantByRole(participants: Participant[], role: string): Participant | undefined {\n return participants.find((p) => p.participantRole === role);\n}\n\nfunction findOfficialByResponsibility(participants: Participant[], responsibility: string): Participant | undefined {\n return participants.find(\n (p) =>\n p.participantRole === 'OFFICIAL' &&\n p.participantRoleResponsibilities?.some((r) => r.toUpperCase().includes(responsibility.toUpperCase())),\n );\n}\n\nfunction resolveLocation(record: TournamentRecord): string {\n const venue = record.venues?.[0];\n const addr = venue?.addresses?.[0];\n const parts: string[] = [];\n if (addr?.city) parts.push(addr.city);\n if (addr?.state) parts.push(addr.state);\n if (addr?.countryCode || record.hostCountryCode) parts.push(addr?.countryCode || record.hostCountryCode || '');\n return parts.join(', ');\n}\n\nfunction resolveCity(record: TournamentRecord): string | undefined {\n return record.venues?.[0]?.addresses?.[0]?.city;\n}\n\nfunction resolveCountry(record: TournamentRecord): string | undefined {\n return record.venues?.[0]?.addresses?.[0]?.countryCode || record.hostCountryCode;\n}\n\nfunction resolveGrade(record: TournamentRecord): string | undefined {\n if (record.tournamentTier) {\n const tier = record.tournamentTier;\n return tier.system ? tier.system + ' ' + (tier.value || '') : tier.value;\n }\n return record.tournamentLevel;\n}\n\nfunction formatPrizeMoney(record: TournamentRecord): string | undefined {\n const pm = record.totalPrizeMoney?.[0];\n if (!pm) return undefined;\n return String(pm.amount);\n}\n\nfunction formatCurrency(record: TournamentRecord): string | undefined {\n return record.totalPrizeMoney?.[0]?.currencyCode;\n}\n\nexport interface BuildHeaderOptions {\n layout?: HeaderLayout;\n sectionLabel?: string;\n overrides?: Partial<HeaderConfig>;\n}\n\n/**\n * Auto-populate a HeaderConfig from structured tournament data.\n * All fields can be overridden via the overrides parameter.\n */\nexport function buildHeaderFromTournament(record: TournamentRecord, options: BuildHeaderOptions = {}): HeaderConfig {\n const { layout = 'itf', sectionLabel, overrides } = options;\n const participants = record.participants || [];\n\n const director = findParticipantByRole(participants, 'DIRECTOR');\n const referee = findOfficialByResponsibility(participants, 'REFEREE');\n const chiefUmpire =\n findOfficialByResponsibility(participants, 'CHIEF_UMPIRE') || findOfficialByResponsibility(participants, 'UMPIRE');\n const supervisor = findOfficialByResponsibility(participants, 'SUPERVISOR') || referee;\n\n const header: HeaderConfig = {\n layout,\n tournamentName: record.formalName || record.tournamentName || '',\n startDate: record.startDate,\n endDate: record.endDate,\n location: resolveLocation(record),\n city: resolveCity(record),\n country: resolveCountry(record),\n surface: record.surfaceCategory,\n grade: resolveGrade(record),\n tournamentId: record.tournamentId,\n organizer: director ? formatParticipantName(director) : undefined,\n supervisor: supervisor ? formatParticipantName(supervisor) : undefined,\n chiefUmpire: chiefUmpire ? formatParticipantName(chiefUmpire) : undefined,\n prizeMoney: formatPrizeMoney(record),\n currency: formatCurrency(record),\n sectionLabel,\n ...overrides,\n };\n\n return header;\n}\n\nexport interface BuildFooterOptions {\n layout?: FooterLayout;\n seedAssignments?: FooterConfig['seedAssignments'];\n prizeMoney?: FooterConfig['prizeMoney'];\n overrides?: Partial<FooterConfig>;\n}\n\n/**\n * Auto-populate a FooterConfig from structured tournament data.\n * Seed assignments and prize money per round must be passed in since\n * they are draw/event-specific (not on the tournament root).\n */\nexport function buildFooterFromTournament(record: TournamentRecord, options: BuildFooterOptions = {}): FooterConfig {\n const { layout = 'standard', seedAssignments, prizeMoney, overrides } = options;\n const participants = record.participants || [];\n\n const officials = participants.filter((p) => p.participantRole === 'OFFICIAL' || p.participantRole === 'DIRECTOR');\n const signatureLines = officials.map((p) => ({\n role: p.participantRoleResponsibilities?.[0] || p.participantRole || 'Official',\n name: formatParticipantName(p),\n }));\n\n const footer: FooterConfig = {\n layout,\n showPageNumbers: true,\n showTimestamp: true,\n ...(signatureLines.length && { signatureLines }),\n ...(seedAssignments?.length && { seedAssignments }),\n ...(prizeMoney?.length && { prizeMoney }),\n ...(record.registrationProfile?.drawCeremonyDate && {\n drawCeremonyDate: record.registrationProfile.drawCeremonyDate,\n }),\n ...overrides,\n };\n\n return footer;\n}\n","import jsPDF from 'jspdf';\nimport type { FooterConfig, PageConfig } from '../config/types';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport function renderFooter(doc: jsPDF, config: FooterConfig, pageConfig: PageConfig, pageNumber?: number): number {\n switch (config.layout) {\n case 'standard':\n return renderStandardFooter(doc, config, pageConfig, pageNumber);\n case 'seedings':\n case 'seedings-table':\n return renderSeedingsTableFooter(doc, config, pageConfig, pageNumber);\n case 'prize-money':\n return renderPrizeMoneyFooter(doc, config, pageConfig, pageNumber);\n case 'officials':\n case 'officials-signoff':\n return renderOfficialsSignoffFooter(doc, config, pageConfig, pageNumber);\n case 'combined-tour':\n return renderCombinedTourFooter(doc, config, pageConfig, pageNumber);\n case 'none':\n return 0;\n }\n}\n\nexport function measureFooterHeight(config: FooterConfig): number {\n switch (config.layout) {\n case 'standard':\n return 8 + (config.notes?.length || 0) * 3;\n case 'seedings':\n case 'seedings-table': {\n const seedRows = Math.ceil((config.seedAssignments?.length || 0) / 2);\n return 12 + seedRows * 3;\n }\n case 'prize-money':\n return 12 + (config.prizeMoney?.length || 0) * 2.5;\n case 'officials':\n case 'officials-signoff':\n return 12 + (config.signatureLines?.length || config.officials?.length || 0) * 5;\n case 'combined-tour': {\n const seedRows2 = Math.ceil((config.seedAssignments?.length || 0) / 2);\n const prizeRows = config.prizeMoney?.length || 0;\n const mainHeight = Math.max(seedRows2 * 3, prizeRows * 2.5);\n return 16 + mainHeight + (config.withdrawals?.length ? 6 : 0);\n }\n case 'none':\n return 0;\n }\n}\n\n// ---- Standard footer: timestamp + page number + notes ----\n\nfunction renderStandardFooter(doc: jsPDF, config: FooterConfig, pageConfig: PageConfig, pageNumber?: number): number {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const { margins } = pageConfig;\n const rightEdge = pageWidth - margins.right;\n\n let y = pageHeight - margins.bottom;\n\n // Timestamp + page number at the very bottom\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.setTextColor(120);\n if (config.showTimestamp) {\n doc.text(`Generated ${new Date().toLocaleDateString()}`, margins.left, y);\n }\n if (config.showPageNumbers && pageNumber !== undefined) {\n doc.text(`Page ${pageNumber}`, rightEdge, y, { align: 'right' });\n }\n doc.setTextColor(0);\n\n // Separator line above timestamp\n y -= 3;\n doc.setDrawColor(180);\n doc.setLineWidth(0.2);\n doc.line(margins.left, y, rightEdge, y);\n y -= 2;\n\n // Notes above separator\n if (config.notes?.length) {\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(100);\n for (let i = config.notes.length - 1; i >= 0; i--) {\n doc.text(config.notes[i], margins.left, y);\n y -= 3;\n }\n doc.setTextColor(0);\n }\n\n return measureFooterHeight(config);\n}\n\n// ---- Seedings table footer: two-column seed/player list ----\n\nfunction renderSeedingsTableFooter(\n doc: jsPDF,\n config: FooterConfig,\n pageConfig: PageConfig,\n pageNumber?: number,\n): number {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const { margins } = pageConfig;\n const rightEdge = pageWidth - margins.right;\n const footerH = measureFooterHeight(config);\n\n let y = pageHeight - margins.bottom - footerH + 4;\n\n // Separator\n doc.setDrawColor(180);\n doc.setLineWidth(0.2);\n doc.line(margins.left, y, rightEdge, y);\n y += 3;\n\n // Title\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.text('Seeded Players', margins.left, y);\n y += 3;\n\n // Two-column layout\n const seeds = config.seedAssignments || [];\n const halfCol = (rightEdge - margins.left) / 2;\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n\n for (let i = 0; i < seeds.length; i++) {\n const col = i < Math.ceil(seeds.length / 2) ? 0 : 1;\n const row = col === 0 ? i : i - Math.ceil(seeds.length / 2);\n const x = margins.left + col * halfCol;\n const rowY = y + row * 3;\n const s = seeds[i];\n const rankStr = s.ranking ? ` (${s.ranking})` : '';\n doc.text(`${s.seedValue}. ${s.participantName}${rankStr}`, x, rowY);\n }\n\n const seedRows = Math.ceil(seeds.length / 2);\n y += seedRows * 3 + 2;\n\n // Standard footer elements below\n renderFooterBar(doc, config, pageConfig, pageNumber, y);\n\n return footerH;\n}\n\n// ---- Prize money footer: per-round amounts ----\n\nfunction renderPrizeMoneyFooter(doc: jsPDF, config: FooterConfig, pageConfig: PageConfig, pageNumber?: number): number {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const { margins } = pageConfig;\n const rightEdge = pageWidth - margins.right;\n const footerH = measureFooterHeight(config);\n\n let y = pageHeight - margins.bottom - footerH + 4;\n\n doc.setDrawColor(180);\n doc.setLineWidth(0.2);\n doc.line(margins.left, y, rightEdge, y);\n y += 3;\n\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.text('Prize Money', margins.left, y);\n y += 3;\n\n const prizes = config.prizeMoney || [];\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n\n for (const p of prizes) {\n const parts = [p.round];\n if (p.amount) parts.push(p.amount);\n if (p.points) parts.push(`${p.points} pts`);\n doc.text(parts.join(' — '), margins.left, y);\n y += 2.5;\n }\n\n y += 2;\n renderFooterBar(doc, config, pageConfig, pageNumber, y);\n\n return footerH;\n}\n\n// ---- Officials sign-off footer: signature lines + draw ceremony ----\n\nfunction renderOfficialsSignoffFooter(\n doc: jsPDF,\n config: FooterConfig,\n pageConfig: PageConfig,\n pageNumber?: number,\n): number {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const { margins } = pageConfig;\n const rightEdge = pageWidth - margins.right;\n const footerH = measureFooterHeight(config);\n\n let y = pageHeight - margins.bottom - footerH + 4;\n\n doc.setDrawColor(180);\n doc.setLineWidth(0.2);\n doc.line(margins.left, y, rightEdge, y);\n y += 4;\n\n // Draw ceremony date\n if (config.drawCeremonyDate) {\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(80);\n doc.text(`Draw ceremony: ${config.drawCeremonyDate}`, margins.left, y);\n doc.setTextColor(0);\n y += 3;\n }\n\n // Release date\n if (config.releaseDate) {\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(80);\n doc.text(`Released: ${config.releaseDate}`, margins.left, y);\n doc.setTextColor(0);\n y += 3;\n }\n\n // Signature lines\n const lines: { role: string; name?: string }[] =\n config.signatureLines || (config.officials || []).map((name) => ({ role: name }));\n const lineWidth = (rightEdge - margins.left) / Math.min(lines.length, 3);\n\n for (let i = 0; i < lines.length; i++) {\n const col = i % 3;\n const row = Math.floor(i / 3);\n const x = margins.left + col * lineWidth;\n const lineY = y + row * 10;\n\n // Role label\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(100);\n doc.text(lines[i].role, x, lineY);\n doc.setTextColor(0);\n\n // Name (if provided)\n const lineName = lines[i].name;\n if (lineName) {\n setFont(doc, SIZE.TINY, STYLE.BOLD);\n doc.text(lineName, x, lineY + 3);\n }\n\n // Signature line\n doc.setDrawColor(150);\n doc.setLineWidth(0.15);\n doc.line(x, lineY + 5, x + lineWidth - 8, lineY + 5);\n }\n\n const rows = Math.ceil(lines.length / 3);\n y += rows * 10 + 2;\n\n renderFooterBar(doc, config, pageConfig, pageNumber, y);\n\n return footerH;\n}\n\n// ---- Combined tour footer: seedings + prize money + officials (WTA/ATP style) ----\n\nfunction renderCombinedTourFooter(\n doc: jsPDF,\n config: FooterConfig,\n pageConfig: PageConfig,\n pageNumber?: number,\n): number {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const { margins } = pageConfig;\n const rightEdge = pageWidth - margins.right;\n const footerH = measureFooterHeight(config);\n\n let y = pageHeight - margins.bottom - footerH + 4;\n\n doc.setDrawColor(180);\n doc.setLineWidth(0.2);\n doc.line(margins.left, y, rightEdge, y);\n y += 3;\n\n const contentWidth = rightEdge - margins.left;\n const leftColX = margins.left;\n const rightColX = margins.left + contentWidth * 0.55;\n let leftY = y;\n let rightY = y;\n\n // Left column: seeded players\n const seeds = config.seedAssignments || [];\n if (seeds.length) {\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.text('Seeded Players', leftColX, leftY);\n leftY += 3;\n\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n for (const s of seeds) {\n const rankStr = s.ranking ? ` (${s.ranking})` : '';\n doc.text(`${s.seedValue}. ${s.participantName}${rankStr}`, leftColX, leftY);\n leftY += 2.5;\n }\n }\n\n // Right column: prize money\n const prizes = config.prizeMoney || [];\n if (prizes.length) {\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.text('Prize Money', rightColX, rightY);\n rightY += 3;\n\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n for (const p of prizes) {\n const parts = [p.round];\n if (p.amount) parts.push(p.amount);\n if (p.points) parts.push(`${p.points} pts`);\n doc.text(parts.join(' — '), rightColX, rightY);\n rightY += 2.5;\n }\n }\n\n y = Math.max(leftY, rightY) + 2;\n\n // Withdrawals\n if (config.withdrawals?.length) {\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(80);\n const wdText = config.withdrawals.map((w) => (w.reason ? `${w.name} (${w.reason})` : w.name)).join(', ');\n doc.text(`Withdrawals: ${wdText}`, margins.left, y, { maxWidth: contentWidth });\n doc.setTextColor(0);\n y += 3;\n }\n\n // Lucky losers\n if (config.luckyLosers?.length) {\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(80);\n doc.text(`Lucky Losers: ${config.luckyLosers.join(', ')}`, margins.left, y, { maxWidth: contentWidth });\n doc.setTextColor(0);\n y += 3;\n }\n\n // Supervisor + release date\n if (config.officials?.length) {\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.setTextColor(80);\n doc.text(config.officials.join(' | '), margins.left, y);\n doc.setTextColor(0);\n y += 3;\n }\n\n renderFooterBar(doc, config, pageConfig, pageNumber, y);\n\n return footerH;\n}\n\n// ---- Shared footer bar: timestamp + page number at the very bottom ----\n\nfunction renderFooterBar(\n doc: jsPDF,\n config: FooterConfig,\n pageConfig: PageConfig,\n pageNumber?: number,\n _y?: number,\n): void {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const { margins } = pageConfig;\n const rightEdge = pageWidth - margins.right;\n const y = pageHeight - margins.bottom + 2;\n\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.setTextColor(120);\n\n if (config.showTimestamp) {\n doc.text(`Generated ${new Date().toLocaleDateString()}`, margins.left, y);\n }\n if (config.releaseDate) {\n const relX = config.showTimestamp ? margins.left + 50 : margins.left;\n doc.text(`Released: ${config.releaseDate}`, relX, y);\n }\n if (config.showPageNumbers && pageNumber !== undefined) {\n doc.text(`Page ${pageNumber}`, rightEdge, y, { align: 'right' });\n }\n\n doc.setTextColor(0);\n}\n","/**\n * Seeded players table for draw sheet footers.\n *\n * Renders a compact multi-column list of seeded players,\n * similar to what appears at the bottom of WTA/ITF/Grand Slam draw sheets.\n */\n\nimport jsPDF from 'jspdf';\nimport type { DrawFormatConfig } from '../config/types';\nimport type { DrawData } from '../core/extractDrawData';\nimport { setFont, STYLE } from '../layout/fonts';\n\nconst SEED_FONT_SIZE = 5;\nconst SEED_LINE_HEIGHT = 2.5;\n\nexport function renderSeedingsFooter(doc: jsPDF, drawData: DrawData, format: DrawFormatConfig, startY: number): number {\n const seeds = drawData.seedAssignments;\n if (!seeds.length) return startY;\n\n const margins = format.page.margins;\n const pageWidth = doc.internal.pageSize.getWidth();\n const availableWidth = pageWidth - margins.left - margins.right;\n\n // Title\n setFont(doc, SEED_FONT_SIZE + 1, STYLE.BOLD);\n doc.text('Seeded players', margins.left, startY);\n\n // Separator line\n doc.setDrawColor(150);\n doc.setLineWidth(0.15);\n doc.line(margins.left, startY + 1, margins.left + availableWidth * 0.5, startY + 1);\n startY += 3;\n\n // Split seeds into 2 columns\n const half = Math.ceil(seeds.length / 2);\n const col1 = seeds.slice(0, half);\n const col2 = seeds.slice(half);\n const colWidth = availableWidth * 0.25;\n\n let y = startY;\n for (let i = 0; i < Math.max(col1.length, col2.length); i++) {\n if (col1[i]) {\n renderSeedEntry(doc, col1[i], margins.left, y, colWidth);\n }\n if (col2[i]) {\n renderSeedEntry(doc, col2[i], margins.left + colWidth + 4, y, colWidth);\n }\n y += SEED_LINE_HEIGHT;\n }\n\n return y;\n}\n\nfunction renderSeedEntry(\n doc: jsPDF,\n seed: { seedValue: number; participantName: string; nationality: string },\n x: number,\n y: number,\n _maxWidth: number,\n): void {\n setFont(doc, SEED_FONT_SIZE, STYLE.BOLD);\n doc.text(`${seed.seedValue}`, x + 4, y, { align: 'right' });\n\n setFont(doc, SEED_FONT_SIZE, STYLE.NORMAL);\n doc.text(seed.participantName, x + 6, y);\n\n doc.setTextColor(100);\n doc.text(seed.nationality, x + 45, y);\n doc.setTextColor(0);\n}\n\nexport function measureSeedingsHeight(seedCount: number): number {\n if (seedCount === 0) return 0;\n const rows = Math.ceil(seedCount / 2);\n return 4 + rows * SEED_LINE_HEIGHT;\n}\n","/**\n * Print dispatcher — the main entry point for TMX integration.\n *\n * Takes a PrintRequest from a modal and produces a PDF.\n * Uses the CompositionConfig from the request to configure\n * headers, footers, format presets, and content options.\n */\n\nimport jsPDF from 'jspdf';\nimport type { PrintRequest } from './printModalTypes';\n\nexport interface PrintResult {\n success: boolean;\n doc?: jsPDF;\n blob?: Blob;\n filename?: string;\n error?: string;\n}\n\n/**\n * Execute a print request and return the PDF.\n *\n * The caller (TMX) provides tournament data via the factory engine —\n * this function extracts the needed data using the factory queries\n * and generates the appropriate PDF.\n *\n * Usage in TMX:\n * ```typescript\n * import { executePrint } from 'pdf-factory';\n * import { tournamentEngine } from 'tods-competition-factory';\n *\n * const result = executePrint(printRequest, { tournamentEngine });\n * if (result.success && result.blob) {\n * window.open(URL.createObjectURL(result.blob));\n * }\n * ```\n */\nexport function executePrint(request: PrintRequest, _engine: { tournamentEngine: any }): PrintResult {\n // This is a placeholder — each type will be implemented\n // as the TMX integration progresses.\n // For now it validates the request structure.\n\n if (!request.type) return { success: false, error: 'Missing request type' };\n if (!request.composition) return { success: false, error: 'Missing composition config' };\n\n const filename = generateFilename(request);\n\n return {\n success: true,\n filename,\n // doc and blob will be populated by the specific generator\n };\n}\n\nfunction generateFilename(request: PrintRequest): string {\n const timestamp = new Date().toISOString().slice(0, 10);\n switch (request.type) {\n case 'draw':\n return `draw-${timestamp}.pdf`;\n case 'schedule':\n return `order-of-play-${request.scheduledDate || timestamp}.pdf`;\n case 'playerList':\n return `player-list-${timestamp}.pdf`;\n case 'courtCards':\n return `court-cards-${timestamp}.pdf`;\n case 'signInSheet':\n return `sign-in-sheet-${timestamp}.pdf`;\n case 'matchCard':\n return `match-cards-${timestamp}.pdf`;\n }\n}\n","/**\n * Composition Editor types.\n *\n * These types define the interface for a visual editor that allows\n * tournament directors to design PDF layouts — selecting header styles,\n * footer content, page orientation, format presets, and content options.\n *\n * The editor produces a CompositionConfig which drives PDF generation.\n * This config can be saved per-tournament and reused.\n */\n\nimport type {\n HeaderConfig,\n FooterConfig,\n PageConfig,\n DrawFormatConfig,\n HeaderLayout,\n FooterLayout,\n} from '../config/types';\n\n// --- Composition Config (output of the editor) ---\n\nexport interface CompositionConfig {\n id?: string;\n name: string;\n description?: string;\n\n page: PageConfig;\n header: HeaderConfig;\n footer: FooterConfig;\n format: DrawFormatConfig;\n\n // Content options\n content: ContentOptions;\n\n // Metadata\n createdAt?: string;\n updatedAt?: string;\n}\n\nexport interface ContentOptions {\n // Draw sheet options\n draw?: {\n includeSeedings: boolean;\n includeScores: boolean;\n splitStrategy: 'single-page' | 'halves' | 'quarters';\n showDrawPositions: boolean;\n showByes: boolean;\n };\n\n // Schedule/OOP options\n schedule?: {\n cellStyle: 'detailed' | 'compact';\n showMatchNumbers: boolean;\n alertBanner?: string;\n showPotentialParticipants: boolean;\n };\n\n // Player list options\n playerList?: {\n includeRanking: boolean;\n includeEvents: boolean;\n groupByEvent: boolean;\n showSignInStatus: boolean;\n };\n\n // Court card options\n courtCard?: {\n showNextMatch: boolean;\n showVenueName: boolean;\n cardsPerPage: number;\n };\n}\n\n// --- Editor State (for the UI) ---\n\nexport interface EditorState {\n activeTab: 'page' | 'header' | 'footer' | 'content' | 'preview';\n config: CompositionConfig;\n previewData?: PreviewData;\n isDirty: boolean;\n}\n\nexport interface PreviewData {\n type: 'draw' | 'schedule' | 'playerList' | 'courtCard' | 'signInSheet' | 'matchCard';\n pdfBlob?: Blob;\n previewUrl?: string;\n}\n\n// --- Preset Templates ---\n\nexport interface CompositionTemplate {\n id: string;\n name: string;\n description: string;\n category: 'grand-slam' | 'itf' | 'national' | 'club' | 'custom';\n config: CompositionConfig;\n}\n\n// --- Editor Options (available choices) ---\n\nexport const HEADER_LAYOUT_OPTIONS: { value: HeaderLayout; label: string; description: string }[] = [\n { value: 'grand-slam', label: 'Grand Slam', description: 'Centered tournament name, uppercase, date/location right' },\n {\n value: 'itf',\n label: 'ITF/Professional',\n description: 'Left-aligned name, grade/supervisor on right, separator line',\n },\n { value: 'minimal', label: 'Minimal', description: 'Single line with tournament name and subtitle' },\n { value: 'none', label: 'No Header', description: 'Skip header entirely' },\n];\n\nexport const FOOTER_LAYOUT_OPTIONS: { value: FooterLayout; label: string; description: string }[] = [\n { value: 'standard', label: 'Standard', description: 'Timestamp, page number, optional notes' },\n { value: 'seedings', label: 'Seedings Table', description: 'Seeded players list in compact columns' },\n { value: 'officials', label: 'Officials', description: 'Tournament officials with roles' },\n { value: 'none', label: 'No Footer', description: 'Skip footer entirely' },\n];\n\nexport const PAGE_SIZE_OPTIONS = [\n { value: 'a4', label: 'A4 (210 × 297mm)' },\n { value: 'letter', label: 'US Letter (216 × 279mm)' },\n];\n\nexport const ORIENTATION_OPTIONS = [\n { value: 'auto', label: 'Auto (landscape for large draws)' },\n { value: 'landscape', label: 'Landscape' },\n { value: 'portrait', label: 'Portrait' },\n];\n\nexport const SPLIT_STRATEGY_OPTIONS = [\n { value: 'single-page', label: 'Single Page (dense)' },\n { value: 'halves', label: 'Two Halves (64+64)' },\n { value: 'quarters', label: 'Four Quarters (32×4)' },\n];\n","/**\n * Print Modal types — defines the request/response shapes for TMX print integration.\n *\n * A PrintRequest describes what to print and how.\n * PrintModalConfig/Tab/Field describe the modal UI for configuring print options.\n */\n\nimport type { CompositionConfig } from './editorTypes';\n\n// --- Print Requests ---\n\nexport type PrintRequest =\n | PrintDrawRequest\n | PrintScheduleRequest\n | PrintPlayerListRequest\n | PrintCourtCardsRequest\n | PrintSignInSheetRequest\n | PrintMatchCardRequest;\n\nexport interface PrintDrawRequest {\n type: 'draw';\n drawId: string;\n eventId: string;\n composition: CompositionConfig;\n}\n\nexport interface PrintScheduleRequest {\n type: 'schedule';\n scheduledDate: string;\n venueId?: string;\n composition: CompositionConfig;\n}\n\nexport interface PrintPlayerListRequest {\n type: 'playerList';\n eventId?: string;\n composition: CompositionConfig;\n}\n\nexport interface PrintCourtCardsRequest {\n type: 'courtCards';\n venueId?: string;\n scheduledDate?: string;\n composition: CompositionConfig;\n}\n\nexport interface PrintSignInSheetRequest {\n type: 'signInSheet';\n eventId: string;\n composition: CompositionConfig;\n}\n\nexport interface PrintMatchCardRequest {\n type: 'matchCard';\n matchUpIds: string[];\n composition: CompositionConfig;\n}\n\n// --- Print Result ---\n\nexport interface PrintResult {\n success: boolean;\n doc?: any;\n blob?: Blob;\n filename?: string;\n error?: string;\n}\n\n// --- Modal Configuration ---\n\nexport interface PrintModalConfig {\n title: string;\n tabs: PrintModalTab[];\n}\n\nexport interface PrintModalTab {\n id: string;\n label: string;\n icon?: string;\n fields: PrintModalField[];\n}\n\nexport interface PrintModalField {\n id: string;\n label: string;\n type: 'select' | 'checkbox' | 'text' | 'number';\n options?: { value: string; label: string }[];\n defaultValue?: any;\n configPath: string;\n}\n\n// --- Modal Tab Presets ---\n\nexport const DRAW_MODAL_TABS: PrintModalTab[] = [\n {\n id: 'content',\n label: 'Content',\n fields: [\n {\n id: 'includeSeedings',\n label: 'Include seedings',\n type: 'checkbox',\n defaultValue: true,\n configPath: 'content.draw.includeSeedings',\n },\n {\n id: 'includeScores',\n label: 'Include scores',\n type: 'checkbox',\n defaultValue: true,\n configPath: 'content.draw.includeScores',\n },\n {\n id: 'showDrawPositions',\n label: 'Show draw positions',\n type: 'checkbox',\n defaultValue: true,\n configPath: 'content.draw.showDrawPositions',\n },\n { id: 'showByes', label: 'Show byes', type: 'checkbox', defaultValue: true, configPath: 'content.draw.showByes' },\n {\n id: 'splitStrategy',\n label: 'Split strategy',\n type: 'select',\n options: [\n { value: 'single-page', label: 'Single page' },\n { value: 'halves', label: 'Split in halves' },\n { value: 'quarters', label: 'Split in quarters' },\n ],\n defaultValue: 'single-page',\n configPath: 'content.draw.splitStrategy',\n },\n ],\n },\n {\n id: 'layout',\n label: 'Layout',\n fields: [\n {\n id: 'headerLayout',\n label: 'Header style',\n type: 'select',\n options: [\n { value: 'itf', label: 'ITF' },\n { value: 'minimal', label: 'Minimal' },\n { value: 'branded', label: 'Branded' },\n ],\n defaultValue: 'itf',\n configPath: 'header.layout',\n },\n {\n id: 'orientation',\n label: 'Orientation',\n type: 'select',\n options: [\n { value: 'landscape', label: 'Landscape' },\n { value: 'portrait', label: 'Portrait' },\n ],\n defaultValue: 'landscape',\n configPath: 'page.orientation',\n },\n ],\n },\n];\n\nexport const SCHEDULE_MODAL_TABS: PrintModalTab[] = [\n {\n id: 'content',\n label: 'Content',\n fields: [\n {\n id: 'cellStyle',\n label: 'Cell style',\n type: 'select',\n options: [\n { value: 'detailed', label: 'Detailed' },\n { value: 'compact', label: 'Compact' },\n ],\n defaultValue: 'detailed',\n configPath: 'content.schedule.cellStyle',\n },\n {\n id: 'showMatchNumbers',\n label: 'Show match numbers',\n type: 'checkbox',\n defaultValue: false,\n configPath: 'content.schedule.showMatchNumbers',\n },\n { id: 'alertBanner', label: 'Alert banner text', type: 'text', configPath: 'content.schedule.alertBanner' },\n ],\n },\n {\n id: 'layout',\n label: 'Layout',\n fields: [\n {\n id: 'headerLayout',\n label: 'Header style',\n type: 'select',\n options: [\n { value: 'itf', label: 'ITF' },\n { value: 'minimal', label: 'Minimal' },\n { value: 'branded', label: 'Branded' },\n ],\n defaultValue: 'itf',\n configPath: 'header.layout',\n },\n ],\n },\n];\n","export function participantName(participant: any): string {\n if (!participant) return '';\n\n if (participant.person) {\n const { standardFamilyName, standardGivenName } = participant.person;\n if (standardFamilyName) {\n return `${standardFamilyName.toUpperCase()}, ${standardGivenName || ''}`.trim();\n }\n }\n\n return participant.participantName || '';\n}\n\nexport function nationality(participant: any): string {\n if (!participant) return '';\n return participant.person?.nationalityCode || '';\n}\n\nexport function seedDisplay(seedValue: any): string {\n if (!seedValue) return '';\n return `[${seedValue}]`;\n}\n\nexport function entryStatusDisplay(entryStatus: string): string {\n if (!entryStatus) return '';\n const map: Record<string, string> = {\n DIRECT_ACCEPTANCE: 'DA',\n WILDCARD: 'WC',\n LUCKY_LOSER: 'LL',\n QUALIFIER: 'Q',\n ALTERNATE: 'A',\n SPECIAL_EXEMPT: 'SE',\n };\n return map[entryStatus] || entryStatus;\n}\n\nexport function formatScore(score: any): string {\n if (!score) return '';\n if (typeof score === 'string') return score;\n if (score.scoreStringSide1) return score.scoreStringSide1;\n return '';\n}\n\nexport function formatDate(dateStr: string): string {\n if (!dateStr) return '';\n const d = new Date(dateStr + 'T00:00:00');\n return d.toLocaleDateString('en-US', { day: '2-digit', month: 'short', year: 'numeric' });\n}\n\nexport function formatTime(timeStr: string): string {\n if (!timeStr) return '';\n const [h, m] = timeStr.split(':');\n const hour = parseInt(h);\n const ampm = hour >= 12 ? 'PM' : 'AM';\n let hour12 = hour;\n if (hour === 0) hour12 = 12;\n else if (hour > 12) hour12 = hour - 12;\n return `${hour12}:${m} ${ampm}`;\n}\n\nexport function eventAbbreviation(eventName: string): string {\n if (!eventName) return '';\n return eventName\n .split(/\\s+/)\n .map((w) => w[0])\n .join('')\n .toUpperCase();\n}\n\nexport function roundName(roundNumber: number, totalRounds: number): string {\n const remaining = totalRounds - roundNumber + 1;\n if (remaining === 1) return 'F';\n if (remaining === 2) return 'SF';\n if (remaining === 3) return 'QF';\n return `R${Math.pow(2, remaining)}`;\n}\n","import { participantName, nationality, formatScore, roundName } from '../utils/primitives';\n\nexport interface DrawSlot {\n drawPosition: number;\n participantName: string;\n nationality: string;\n seedValue?: number;\n entryStatus?: string;\n isBye?: boolean;\n}\n\nexport interface DrawMatchUp {\n roundNumber: number;\n roundPosition: number;\n drawPositions: number[];\n score?: string;\n winningSide?: number;\n matchUpStatus?: string;\n}\n\nexport interface DrawData {\n drawName: string;\n drawSize: number;\n drawType: string;\n totalRounds: number;\n slots: DrawSlot[];\n matchUps: DrawMatchUp[];\n seedAssignments: { seedValue: number; participantName: string; nationality: string }[];\n roundLabelMap?: Record<number, string>;\n noWinnerColumn?: boolean;\n}\n\nexport function extractDrawData(params: {\n drawDefinition: any;\n participants?: any[];\n structureId?: string;\n processedMatchUps?: any[];\n}): DrawData {\n const { drawDefinition, participants = [] } = params;\n if (!drawDefinition) return emptyDrawData();\n\n const structure = params.structureId\n ? drawDefinition.structures?.find((s: any) => s.structureId === params.structureId)\n : drawDefinition.structures?.[0];\n\n if (!structure) return emptyDrawData();\n\n const participantMap = new Map<string, any>();\n participants.forEach((p: any) => participantMap.set(p.participantId, p));\n\n const positionAssignments = structure.positionAssignments || [];\n const matchUpsRaw = structure.matchUps || [];\n const maxRound = matchUpsRaw.reduce((max: number, mu: any) => Math.max(max, mu.roundNumber || 0), 0);\n\n // For sub-structures (consolation, backdraw), use position count and actual round count\n // rather than the main drawDefinition.drawSize which refers to the overall draw\n const drawSize = params.structureId\n ? positionAssignments.length\n : drawDefinition.drawSize || positionAssignments.length;\n const totalRounds = params.structureId ? maxRound : Math.log2(drawSize);\n\n // seedAssignments live on the structure, not the drawDefinition\n const structureSeedAssignments = structure.seedAssignments || [];\n\n const slots: DrawSlot[] = positionAssignments.map((pa: any) => {\n const participant = pa.participantId ? participantMap.get(pa.participantId) : undefined;\n const seedAssignment = structureSeedAssignments.find((sa: any) => sa.participantId === pa.participantId);\n\n return {\n drawPosition: pa.drawPosition,\n participantName: participant ? participantName(participant) : '',\n nationality: participant ? nationality(participant) : '',\n seedValue: seedAssignment?.seedValue,\n entryStatus: pa.entryStatus,\n isBye: pa.bye === true,\n };\n });\n\n const matchUps: DrawMatchUp[] = (structure.matchUps || []).map((mu: any) => ({\n roundNumber: mu.roundNumber,\n roundPosition: mu.roundPosition,\n drawPositions: mu.drawPositions || [],\n score: formatScore(mu.score),\n winningSide: mu.winningSide,\n matchUpStatus: mu.matchUpStatus,\n }));\n\n const seedAssignments = structureSeedAssignments\n .filter((sa: any) => sa.participantId)\n .map((sa: any) => {\n const participant = participantMap.get(sa.participantId);\n return {\n seedValue: sa.seedValue,\n participantName: participant ? participantName(participant) : '',\n nationality: participant ? nationality(participant) : '',\n };\n })\n .sort((a: any, b: any) => a.seedValue - b.seedValue);\n\n // Build round label map from engine-processed matchUps (preferred) or heuristic\n const roundLabelMap = buildRoundLabelMap(matchUps, totalRounds, params.processedMatchUps);\n\n return {\n drawName: drawDefinition.drawName || '',\n drawSize,\n drawType: drawDefinition.drawType || 'SINGLE_ELIMINATION',\n totalRounds,\n slots,\n matchUps,\n seedAssignments,\n roundLabelMap,\n };\n}\n\nexport function getRoundLabel(roundNumber: number, totalRounds: number): string {\n return roundName(roundNumber, totalRounds);\n}\n\nfunction buildRoundLabelMap(\n matchUps: DrawMatchUp[],\n totalRounds: number,\n processedMatchUps?: any[],\n): Record<number, string> {\n // Use engine-provided roundName/abbreviatedRoundName when available\n if (processedMatchUps?.length) {\n const map: Record<number, string> = {};\n for (const mu of processedMatchUps) {\n if (mu.roundNumber && !map[mu.roundNumber]) {\n map[mu.roundNumber] = mu.abbreviatedRoundName || mu.roundName || `R${mu.roundNumber}`;\n }\n }\n if (Object.keys(map).length > 0) return map;\n }\n\n // Fallback: count matches per round\n const roundCounts = new Map<number, number>();\n for (const mu of matchUps) {\n roundCounts.set(mu.roundNumber, (roundCounts.get(mu.roundNumber) || 0) + 1);\n }\n\n const rounds = [...roundCounts.keys()].sort((a, b) => a - b);\n const isPowerOf2 =\n rounds.length > 0 &&\n rounds.every((r, i) => {\n if (i === 0) return true;\n const prev = roundCounts.get(rounds[i - 1]) || 0;\n const curr = roundCounts.get(r) || 0;\n return curr <= Math.ceil(prev / 2);\n });\n\n // Standard single-elimination: use traditional labels\n if (isPowerOf2) {\n const map: Record<number, string> = {};\n for (const r of rounds) {\n map[r] = roundName(r, totalRounds);\n }\n return map;\n }\n\n // Feed structure: simple round number labels as fallback\n const map: Record<number, string> = {};\n for (const r of rounds) {\n map[r] = `R${r}`;\n }\n return map;\n}\n\nfunction emptyDrawData(): DrawData {\n return {\n drawName: '',\n drawSize: 0,\n drawType: '',\n totalRounds: 0,\n slots: [],\n matchUps: [],\n seedAssignments: [],\n };\n}\n","import { participantName, nationality, formatScore, formatTime, eventAbbreviation } from '../utils/primitives';\n\nexport interface ScheduleMatch {\n courtName: string;\n scheduledTime: string;\n eventName: string;\n eventAbbr: string;\n roundName: string;\n side1: { name: string; nationality: string };\n side2: { name: string; nationality: string };\n score?: string;\n matchUpStatus?: string;\n notBeforeTime?: string;\n}\n\nexport interface ScheduleTimeSlot {\n time: string;\n label: string;\n matches: ScheduleMatch[];\n}\n\nexport interface ScheduleData {\n scheduledDate: string;\n courts: string[];\n timeSlots: ScheduleTimeSlot[];\n}\n\nexport function extractScheduleData(params: {\n matchUps?: any[];\n venues?: any[];\n scheduledDate?: string;\n}): ScheduleData {\n const { matchUps = [], venues = [], scheduledDate = '' } = params;\n\n const courtNames = new Set<string>();\n venues.forEach((v: any) => {\n (v.courts || []).forEach((c: any) => {\n courtNames.add(c.courtName || `Court ${c.courtId}`);\n });\n });\n\n const courtMap = new Map<string, string>();\n venues.forEach((v: any) => {\n (v.courts || []).forEach((c: any) => {\n courtMap.set(c.courtId, c.courtName || `Court ${c.courtId}`);\n });\n });\n\n const scheduled = matchUps.filter((mu: any) => mu.schedule?.scheduledDate === scheduledDate || !scheduledDate);\n\n const timeMap = new Map<string, ScheduleMatch[]>();\n\n for (const mu of scheduled) {\n const schedule = mu.schedule || {};\n const time = schedule.scheduledTime || '00:00';\n const courtId = schedule.venueCourtId || schedule.courtId || '';\n const courtName = courtMap.get(courtId) || courtId;\n\n if (courtName) courtNames.add(courtName);\n\n const sides = mu.sides || [];\n const side1 = extractSide(sides[0]);\n const side2 = extractSide(sides[1]);\n\n const match: ScheduleMatch = {\n courtName,\n scheduledTime: formatTime(time),\n eventName: mu.eventName || mu.event?.eventName || '',\n eventAbbr: eventAbbreviation(mu.eventName || mu.event?.eventName || ''),\n roundName: mu.roundName || '',\n side1,\n side2,\n score: formatScore(mu.score),\n matchUpStatus: mu.matchUpStatus,\n notBeforeTime: schedule.notBeforeTime ? formatTime(schedule.notBeforeTime) : undefined,\n };\n\n const key = schedule.notBeforeTime || time;\n if (!timeMap.has(key)) timeMap.set(key, []);\n timeMap.get(key)!.push(match);\n }\n\n const sortedTimes = [...timeMap.keys()].sort();\n const timeSlots: ScheduleTimeSlot[] = sortedTimes.map((time) => ({\n time,\n label: formatTime(time) || 'TBD',\n matches: timeMap.get(time) || [],\n }));\n\n return {\n scheduledDate,\n courts: [...courtNames].sort(),\n timeSlots,\n };\n}\n\nfunction extractSide(side: any): { name: string; nationality: string } {\n if (!side) return { name: '', nationality: '' };\n const participant = side.participant;\n if (!participant) return { name: '', nationality: '' };\n return {\n name: participantName(participant),\n nationality: nationality(participant),\n };\n}\n","import { participantName, nationality, entryStatusDisplay } from '../utils/primitives';\n\nexport interface ParticipantRow {\n name: string;\n nationality: string;\n ranking?: string;\n seedValue?: number;\n entryStatus: string;\n events: string[];\n signedIn?: boolean;\n}\n\nexport function extractParticipantData(params: {\n participants?: any[];\n eventEntries?: { eventName: string; entries: any[] }[];\n}): ParticipantRow[] {\n const { participants = [], eventEntries = [] } = params;\n\n const entryMap = new Map<string, { events: string[]; entryStatus: string; seedValue?: number }>();\n\n for (const { eventName, entries } of eventEntries) {\n for (const entry of entries) {\n const id = entry.participantId;\n if (!entryMap.has(id)) {\n entryMap.set(id, { events: [], entryStatus: '', seedValue: undefined });\n }\n const record = entryMap.get(id)!;\n record.events.push(eventName);\n if (entry.entryStatus) record.entryStatus = entry.entryStatus;\n }\n }\n\n return participants\n .filter((p: any) => p.participantType === 'INDIVIDUAL')\n .map((p: any) => {\n const entry = entryMap.get(p.participantId);\n return {\n name: participantName(p),\n nationality: nationality(p),\n ranking: p.rankings?.[0]?.ranking?.toString() || '',\n seedValue: entry?.seedValue,\n entryStatus: entryStatusDisplay(entry?.entryStatus || ''),\n events: entry?.events || [],\n signedIn: p.signInStatus === 'SIGNED_IN',\n };\n })\n .sort((a, b) => a.name.localeCompare(b.name));\n}\n","import { participantName, nationality, formatTime } from '../utils/primitives';\n\nexport interface CourtCardData {\n courtName: string;\n venueName?: string;\n currentMatch?: CourtCardMatch;\n nextMatch?: CourtCardMatch;\n}\n\nexport interface CourtCardMatch {\n eventName: string;\n roundName: string;\n scheduledTime?: string;\n side1: { name: string; nationality: string };\n side2: { name: string; nationality: string };\n}\n\nexport function extractCourtCardData(params: {\n matchUps?: any[];\n venues?: any[];\n scheduledDate?: string;\n}): CourtCardData[] {\n const { matchUps = [], venues = [] } = params;\n\n const courtMap = new Map<string, { courtName: string; venueName: string }>();\n venues.forEach((v: any) => {\n (v.courts || []).forEach((c: any) => {\n courtMap.set(c.courtId, {\n courtName: c.courtName || `Court ${c.courtId}`,\n venueName: v.venueName || '',\n });\n });\n });\n\n // Group matchUps by court\n const courtMatchUps = new Map<string, any[]>();\n for (const mu of matchUps) {\n const courtId = mu.schedule?.venueCourtId || mu.schedule?.courtId;\n if (!courtId) continue;\n if (!courtMatchUps.has(courtId)) courtMatchUps.set(courtId, []);\n courtMatchUps.get(courtId)!.push(mu);\n }\n\n const cards: CourtCardData[] = [];\n\n for (const [courtId, matches] of courtMatchUps) {\n const courtInfo = courtMap.get(courtId) || { courtName: courtId, venueName: '' };\n\n // Sort by scheduled time\n matches.sort((a: any, b: any) => {\n const ta = a.schedule?.scheduledTime || '';\n const tb = b.schedule?.scheduledTime || '';\n return ta.localeCompare(tb);\n });\n\n // Find current (IN_PROGRESS or first upcoming) and next\n const completedStatuses = new Set(['COMPLETED', 'RETIRED', 'WALKOVER', 'DEFAULTED', 'ABANDONED']);\n const inProgress = matches.find((m: any) => m.matchUpStatus === 'IN_PROGRESS');\n const upcoming = matches.filter((m: any) => !completedStatuses.has(m.matchUpStatus));\n const completed = matches.filter((m: any) => completedStatuses.has(m.matchUpStatus));\n\n // Prefer in-progress, then first upcoming, then most recent completed\n const currentMu = inProgress || upcoming[0] || completed.at(-1);\n\n let nextMu;\n if (inProgress) {\n nextMu = upcoming[0];\n } else if (upcoming.length > 1) {\n nextMu = upcoming[1];\n }\n\n cards.push({\n courtName: courtInfo.courtName,\n venueName: courtInfo.venueName,\n currentMatch: currentMu ? mapCourtCardMatch(currentMu) : undefined,\n nextMatch: nextMu ? mapCourtCardMatch(nextMu) : undefined,\n });\n }\n\n return cards.sort((a, b) => a.courtName.localeCompare(b.courtName));\n}\n\nfunction mapCourtCardMatch(mu: any): CourtCardMatch {\n const sides = mu.sides || [];\n return {\n eventName: mu.eventName || mu.event?.eventName || '',\n roundName: mu.roundName || '',\n scheduledTime: mu.schedule?.scheduledTime ? formatTime(mu.schedule.scheduledTime) : undefined,\n side1: extractSide(sides[0]),\n side2: extractSide(sides[1]),\n };\n}\n\nfunction extractSide(side: any): { name: string; nationality: string } {\n if (!side?.participant) return { name: 'TBD', nationality: '' };\n return {\n name: participantName(side.participant),\n nationality: nationality(side.participant),\n };\n}\n","import { participantName, nationality, formatScore } from '../utils/primitives';\n\nexport interface RoundRobinParticipant {\n participantName: string;\n nationality: string;\n seedValue?: number;\n groupPosition: number;\n}\n\nexport interface RoundRobinResult {\n rowPosition: number;\n colPosition: number;\n score: string;\n winningSide?: number;\n}\n\nexport interface RoundRobinGroupData {\n groupName: string;\n participants: RoundRobinParticipant[];\n results: RoundRobinResult[];\n standings?: {\n position: number;\n participantName: string;\n wins: number;\n losses: number;\n setsWon: number;\n setsLost: number;\n }[];\n}\n\nexport function extractRoundRobinData(params: { structure: any; participants?: any[] }): RoundRobinGroupData[] {\n const { structure, participants = [] } = params;\n if (!structure) return [];\n\n const participantMap = new Map<string, any>();\n participants.forEach((p: any) => participantMap.set(p.participantId, p));\n\n // Round robin structures have structures (groups) as children\n const groups = structure.structures || [];\n if (!groups.length) return [];\n\n return groups.map((group: any, groupIndex: number) => {\n const positionAssignments = group.positionAssignments || [];\n const seedAssignments = group.seedAssignments || [];\n\n const rrParticipants: RoundRobinParticipant[] = positionAssignments\n .filter((pa: any) => pa.participantId)\n .map((pa: any) => {\n const p = participantMap.get(pa.participantId);\n const seed = seedAssignments.find((sa: any) => sa.participantId === pa.participantId);\n return {\n participantName: p ? participantName(p) : '',\n nationality: p ? nationality(p) : '',\n seedValue: seed?.seedValue,\n groupPosition: pa.drawPosition,\n };\n })\n .sort((a: RoundRobinParticipant, b: RoundRobinParticipant) => a.groupPosition - b.groupPosition);\n\n const results: RoundRobinResult[] = [];\n for (const mu of group.matchUps || []) {\n if (!mu.drawPositions || mu.drawPositions.length < 2) continue;\n const [pos1, pos2] = mu.drawPositions;\n const score = formatScore(mu.score);\n\n if (score) {\n results.push({\n rowPosition: pos1,\n colPosition: pos2,\n score,\n winningSide: mu.winningSide,\n });\n }\n }\n\n return {\n groupName: group.structureName || `Group ${groupIndex + 1}`,\n participants: rrParticipants,\n results,\n };\n });\n}\n","import type { DrawFormatConfig } from '../config/types';\nimport type { DrawSlot } from '../core/extractDrawData';\n\nexport function formatPlayerEntry(slot: DrawSlot, config: DrawFormatConfig): string {\n if (slot.isBye) return 'Bye';\n if (!slot.participantName) return '';\n\n const name = formatName(slot.participantName, config);\n const nat = formatNationality(slot.nationality, config);\n const seed = slot.seedValue ? formatSeed(slot.seedValue, config) : '';\n const entry = slot.entryStatus ? formatEntryStatus(slot.entryStatus, config) : '';\n\n const parts: string[] = [];\n\n if (config.seedPosition === 'before-position' && seed) parts.push(seed);\n parts.push(name);\n if (config.seedPosition === 'after-name' && seed) parts.push(seed);\n if (nat) parts.push(nat);\n if (config.seedPosition === 'after-country' && seed) parts.push(seed);\n if (entry) parts.push(entry);\n\n return parts.join(' ');\n}\n\n/** Returns name (with seed/entry) and nationality as separate strings for split rendering */\nexport function formatPlayerEntrySplit(\n slot: DrawSlot,\n config: DrawFormatConfig,\n): { name: string; nationality: string } {\n if (slot.isBye) return { name: 'Bye', nationality: '' };\n if (!slot.participantName) return { name: '', nationality: '' };\n\n const name = formatName(slot.participantName, config);\n const seed = slot.seedValue ? formatSeed(slot.seedValue, config) : '';\n const entry = slot.entryStatus ? formatEntryStatus(slot.entryStatus, config) : '';\n\n const parts: string[] = [];\n if (config.seedPosition === 'before-position' && seed) parts.push(seed);\n parts.push(name);\n if (config.seedPosition === 'after-name' && seed) parts.push(seed);\n if (config.seedPosition === 'after-country' && seed) parts.push(seed);\n if (entry) parts.push(entry);\n\n return { name: parts.join(' '), nationality: slot.nationality || '' };\n}\n\nfunction formatName(participantName: string, config: DrawFormatConfig): string {\n // participantName comes as \"LASTNAME, GivenName\" from extractDrawData\n if (config.nameFormat === 'LAST First') {\n return participantName.replace(',', '');\n }\n if (config.nameFormat === 'F. LAST') {\n const match = participantName.match(/^([^,]+),\\s*(.+)/);\n if (match) return `${match[2][0]}. ${match[1]}`;\n }\n return participantName;\n}\n\nfunction formatNationality(nat: string, config: DrawFormatConfig): string {\n if (!nat) return '';\n switch (config.nationalityFormat) {\n case 'parens':\n return `(${nat})`;\n case 'hyphen':\n return `-${nat}`;\n default:\n return nat;\n }\n}\n\nfunction formatSeed(seedValue: number, config: DrawFormatConfig): string {\n return config.seedFormat === 'parens' ? `(${seedValue})` : `[${seedValue}]`;\n}\n\nconst ENTRY_ABBREVIATIONS: Record<string, string> = {\n DIRECT_ACCEPTANCE: '',\n WILDCARD: 'WC',\n QUALIFIER: 'Q',\n LUCKY_LOSER: 'LL',\n SPECIAL_EXEMPT: 'SE',\n ALTERNATE: 'ALT',\n PROTECTED_RANKING: 'PR',\n JUNIOR_EXEMPT: 'JE',\n ORGANISER_ACCEPTANCE: 'OA',\n};\n\nfunction formatEntryStatus(entryStatus: string, config: DrawFormatConfig): string {\n if (!entryStatus) return '';\n const abbr = ENTRY_ABBREVIATIONS[entryStatus];\n if (abbr === undefined) return entryStatus;\n if (!abbr) return ''; // DIRECT_ACCEPTANCE → no badge\n switch (config.entryFormat) {\n case 'parens':\n return `(${abbr})`;\n case 'hyphen':\n return `-${abbr}`;\n default:\n return abbr;\n }\n}\n\nexport function formatMatchScore(score: string, config: DrawFormatConfig): string {\n if (!score) return '';\n // The score from the factory comes with hyphens as game separators\n // Convert to the preset's format if needed\n if (config.gameScoreSeparator === '/') {\n return score.replace(/(\\d)-(\\d)/g, `$1/$2`);\n }\n return score;\n}\n","import jsPDF from 'jspdf';\nimport type { DrawFormatConfig, PageRegions } from '../config/types';\nimport type { DrawData, DrawSlot, DrawMatchUp } from '../core/extractDrawData';\nimport { getRoundLabel } from '../core/extractDrawData';\nimport { formatPlayerEntrySplit, formatMatchScore } from './formatEntry';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport interface TraditionalDrawConfig {\n lineHeight: number;\n roundColumnWidth: number;\n firstRoundWidth: number;\n secondRoundWidth: number;\n connectorGap: number;\n fontSize: number;\n scoreFontSize: number;\n}\n\nexport function getDrawConfig(positionCount: number, regions: PageRegions, roundCount?: number): TraditionalDrawConfig {\n const totalRounds = roundCount || Math.log2(positionCount);\n\n // Height: reserve 9mm for round headers + gap. The bracket spans positionCount-1 gaps.\n const headerReserve = 9;\n const availableHeight = regions.contentHeight - headerReserve;\n const lineHeight = availableHeight / positionCount;\n const isDense = lineHeight < 3.5;\n\n // Width: first round + connectorGap + (totalRounds-1) later round columns + connectorGap each + winner column\n // Total columns after R1 = totalRounds (rounds 2..N = totalRounds-1, plus 1 winner column)\n const connectorGap = isDense ? 0.8 : 1.5;\n const laterColumns = totalRounds; // includes winner column\n const totalConnectorWidth = connectorGap * (laterColumns + 1); // gap before each later column + gap after R1\n\n // First round gets enough for position number + name; later rounds share the rest equally\n // Dense draws (64/128) get a narrower R1 to give later rounds more room for name + score\n const isVeryDense = lineHeight < 2;\n const firstRoundPct = isDense ? 0.18 : 0.3;\n const firstRoundWidth = Math.min(isDense ? 38 : 65, regions.contentWidth * firstRoundPct);\n const remainingWidth = regions.contentWidth - firstRoundWidth - totalConnectorWidth;\n\n // For very dense draws (128), give R2 extra width for inline scores\n const r2Bonus = isVeryDense ? 8 : 0;\n const adjustedRemaining = remainingWidth - r2Bonus;\n const roundColumnWidth = Math.min(65, Math.max(8, adjustedRemaining / Math.max(1, laterColumns)));\n const secondRoundWidth = roundColumnWidth + r2Bonus;\n\n // Font sizing adapts to density\n let fontSize = SIZE.SMALL;\n if (lineHeight < 2.5) fontSize = 5;\n else if (lineHeight < 3.5) fontSize = SIZE.TINY;\n\n return {\n lineHeight,\n roundColumnWidth,\n firstRoundWidth,\n secondRoundWidth,\n connectorGap,\n fontSize,\n scoreFontSize: isDense ? 5 : SIZE.TINY,\n };\n}\n\nexport function renderTraditionalDraw(\n doc: jsPDF,\n drawData: DrawData,\n format: DrawFormatConfig,\n regions: PageRegions,\n positionOffset: number = 0,\n positionCount?: number,\n): void {\n // Detect feed structure: any round with match count >= previous round\n const isFeedStructure = detectFeedStructure(drawData.matchUps);\n\n if (isFeedStructure) {\n renderFeedDraw(doc, drawData, format, regions);\n } else {\n renderPowerOf2Draw(doc, drawData, format, regions, positionOffset, positionCount);\n }\n}\n\nfunction detectFeedStructure(matchUps: DrawMatchUp[]): boolean {\n const roundCounts = new Map<number, number>();\n for (const mu of matchUps) {\n roundCounts.set(mu.roundNumber, (roundCounts.get(mu.roundNumber) || 0) + 1);\n }\n const rounds = [...roundCounts.keys()].sort((a, b) => a - b);\n for (let i = 1; i < rounds.length; i++) {\n const prev = roundCounts.get(rounds[i - 1]) || 0;\n const curr = roundCounts.get(rounds[i]) || 0;\n if (curr >= prev) return true;\n }\n return false;\n}\n\n/**\n * Renders feed-in structures.\n *\n * Feed-in draws have alternating elimination and feed rounds:\n * FEED_IN 12: R1(4 matches) → R2(4 feed) → R3(2) → R4(1)\n * FIC 16 consolation: R1(4) → R2(4 feed) → R3(2) → R4(2 feed) → R5(1) → R6(1 feed)\n *\n * The first round renders draw positions as player lines. Feed rounds render\n * the fed-in participant as a new player line entering from the left, while\n * the advancing winner comes via a connector from the previous round.\n * Elimination rounds merge pairs with standard bracket connectors.\n */\nfunction renderFeedDraw(doc: jsPDF, drawData: DrawData, format: DrawFormatConfig, regions: PageRegions): void {\n const margins = format.page.margins;\n const headerReserve = 9;\n const contentTop = regions.contentY + headerReserve;\n const contentHeight = regions.contentHeight - headerReserve;\n\n const roundMap = groupMatchUpsByRound(drawData.matchUps);\n const sortedRounds = [...roundMap.keys()].sort((a, b) => a - b);\n const totalRoundCols = sortedRounds.length;\n const slotMap = new Map(drawData.slots.map((s) => [s.drawPosition, s]));\n\n const feedRoundSet = identifyFeedRounds(sortedRounds, roundMap);\n\n const { feedConfig, connectorGap, firstRoundWidth, roundColumnWidth, fontSize, scoreFontSize } = computeFeedLayout(\n contentHeight,\n roundMap,\n sortedRounds,\n totalRoundCols,\n regions,\n );\n\n const getColX = (ci: number) => {\n if (ci === 0) return margins.left;\n return margins.left + firstRoundWidth + connectorGap + (ci - 1) * (roundColumnWidth + connectorGap);\n };\n\n renderFeedRoundHeaders(\n doc,\n sortedRounds,\n drawData,\n feedConfig,\n format,\n regions,\n getColX,\n totalRoundCols,\n roundColumnWidth,\n );\n\n const roundSlotYs = computeFeedSlotYs(\n sortedRounds,\n totalRoundCols,\n roundMap,\n feedRoundSet,\n contentTop,\n contentHeight,\n feedConfig.lineHeight,\n );\n\n renderFeedRounds(\n doc,\n sortedRounds,\n totalRoundCols,\n roundMap,\n roundSlotYs,\n feedRoundSet,\n slotMap,\n feedConfig,\n format,\n getColX,\n firstRoundWidth,\n roundColumnWidth,\n connectorGap,\n scoreFontSize,\n );\n\n renderFeedWinnerColumn(\n doc,\n drawData,\n sortedRounds,\n totalRoundCols,\n roundMap,\n roundSlotYs,\n slotMap,\n getColX,\n contentTop,\n contentHeight,\n roundColumnWidth,\n fontSize,\n scoreFontSize,\n format,\n );\n}\n\nfunction groupMatchUpsByRound(matchUps: DrawMatchUp[]): Map<number, DrawMatchUp[]> {\n const roundMap = new Map<number, DrawMatchUp[]>();\n for (const mu of matchUps) {\n if (!roundMap.has(mu.roundNumber)) roundMap.set(mu.roundNumber, []);\n roundMap.get(mu.roundNumber)!.push(mu);\n }\n for (const [, mus] of roundMap) mus.sort((a, b) => a.roundPosition - b.roundPosition);\n return roundMap;\n}\n\nfunction identifyFeedRounds(sortedRounds: number[], roundMap: Map<number, DrawMatchUp[]>): Set<number> {\n const feedRoundSet = new Set<number>();\n for (let i = 1; i < sortedRounds.length; i++) {\n const prev = roundMap.get(sortedRounds[i - 1])?.length || 0;\n const curr = roundMap.get(sortedRounds[i])?.length || 0;\n if (curr >= prev) feedRoundSet.add(sortedRounds[i]);\n }\n return feedRoundSet;\n}\n\nfunction computeFeedLayout(\n contentHeight: number,\n roundMap: Map<number, DrawMatchUp[]>,\n sortedRounds: number[],\n totalRoundCols: number,\n regions: PageRegions,\n): {\n feedConfig: TraditionalDrawConfig;\n connectorGap: number;\n firstRoundWidth: number;\n roundColumnWidth: number;\n fontSize: number;\n scoreFontSize: number;\n} {\n const connectorGap = 1.5;\n const r1MatchCount = roundMap.get(sortedRounds[0])?.length || 1;\n const lineHeight = contentHeight / (r1MatchCount * 2);\n const isDense = lineHeight < 3.5;\n const firstRoundWidth = Math.min(isDense ? 50 : 60, regions.contentWidth * 0.25);\n const remainingWidth = regions.contentWidth - firstRoundWidth - connectorGap * (totalRoundCols + 1);\n const roundColumnWidth = Math.max(8, remainingWidth / Math.max(1, totalRoundCols));\n\n let fontSize = SIZE.SMALL;\n if (lineHeight < 2.5) fontSize = 5;\n else if (lineHeight < 3.5) fontSize = SIZE.TINY;\n const scoreFontSize = isDense ? 5 : SIZE.TINY;\n\n const feedConfig: TraditionalDrawConfig = {\n lineHeight,\n roundColumnWidth,\n firstRoundWidth,\n secondRoundWidth: roundColumnWidth,\n connectorGap,\n fontSize,\n scoreFontSize,\n };\n\n return { feedConfig, connectorGap, firstRoundWidth, roundColumnWidth, fontSize, scoreFontSize };\n}\n\nfunction computeFeedSlotYs(\n sortedRounds: number[],\n totalRoundCols: number,\n roundMap: Map<number, DrawMatchUp[]>,\n feedRoundSet: Set<number>,\n contentTop: number,\n contentHeight: number,\n lineHeight: number,\n): Map<number, { topY: number; bottomY: number; midY: number }[]> {\n const roundSlotYs = new Map<number, { topY: number; bottomY: number; midY: number }[]>();\n\n for (let ci = 0; ci < totalRoundCols; ci++) {\n const roundNum = sortedRounds[ci];\n const matchCount = roundMap.get(roundNum)?.length || 0;\n\n if (feedRoundSet.has(roundNum)) {\n const prevRound = sortedRounds[ci - 1];\n const prevSlots = roundSlotYs.get(prevRound) || [];\n const slots = prevSlots.slice(0, matchCount).map((ps) => {\n const armSpan = ps.bottomY - ps.topY;\n const maxArm = lineHeight * 2;\n if (armSpan > maxArm) {\n return { topY: ps.midY - lineHeight, bottomY: ps.midY + lineHeight, midY: ps.midY };\n }\n return { topY: ps.topY, bottomY: ps.bottomY, midY: ps.midY };\n });\n roundSlotYs.set(roundNum, slots);\n } else if (ci === 0) {\n const totalSlots = matchCount * 2;\n const slotSpacing = contentHeight / (totalSlots + 1);\n const slots: { topY: number; bottomY: number; midY: number }[] = [];\n for (let m = 0; m < matchCount; m++) {\n const topY = contentTop + slotSpacing * (m * 2 + 1);\n const bottomY = contentTop + slotSpacing * (m * 2 + 2);\n slots.push({ topY, bottomY, midY: (topY + bottomY) / 2 });\n }\n roundSlotYs.set(roundNum, slots);\n } else {\n const prevRound = sortedRounds[ci - 1];\n const prevSlots = roundSlotYs.get(prevRound) || [];\n const slots: { topY: number; bottomY: number; midY: number }[] = [];\n for (let m = 0; m < matchCount; m++) {\n const topSlot = prevSlots[m * 2];\n const bottomSlot = prevSlots[m * 2 + 1];\n if (topSlot && bottomSlot) {\n const topY = topSlot.midY;\n const bottomY = bottomSlot.midY;\n slots.push({ topY, bottomY, midY: (topY + bottomY) / 2 });\n }\n }\n roundSlotYs.set(roundNum, slots);\n }\n }\n\n return roundSlotYs;\n}\n\nfunction renderFeedRounds(\n doc: jsPDF,\n sortedRounds: number[],\n totalRoundCols: number,\n roundMap: Map<number, DrawMatchUp[]>,\n roundSlotYs: Map<number, { topY: number; bottomY: number; midY: number }[]>,\n feedRoundSet: Set<number>,\n slotMap: Map<number, DrawSlot>,\n feedConfig: TraditionalDrawConfig,\n format: DrawFormatConfig,\n getColX: (ci: number) => number,\n firstRoundWidth: number,\n roundColumnWidth: number,\n connectorGap: number,\n scoreFontSize: number,\n): void {\n for (let ci = 0; ci < totalRoundCols; ci++) {\n const roundNum = sortedRounds[ci];\n const matchUps = roundMap.get(roundNum) || [];\n const slotYs = roundSlotYs.get(roundNum) || [];\n const colX = getColX(ci);\n const colWidth = ci === 0 ? firstRoundWidth : roundColumnWidth;\n const isFeed = feedRoundSet.has(roundNum);\n const rightX = colX + colWidth;\n const nextRoundIsFeed = ci < totalRoundCols - 1 && feedRoundSet.has(sortedRounds[ci + 1]);\n\n for (let mi = 0; mi < matchUps.length; mi++) {\n const mu = matchUps[mi];\n const sy = slotYs[mi];\n if (!sy) continue;\n\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n\n if (ci === 0) {\n renderFeedFirstRound(\n doc,\n mu,\n sy,\n slotMap,\n format,\n feedConfig,\n colX,\n firstRoundWidth,\n rightX,\n connectorGap,\n nextRoundIsFeed,\n );\n } else if (isFeed) {\n renderFeedRound(\n doc,\n mu,\n sy,\n slotMap,\n roundMap,\n sortedRounds,\n ci,\n format,\n feedConfig,\n colX,\n roundColumnWidth,\n rightX,\n connectorGap,\n nextRoundIsFeed,\n );\n } else {\n renderFeedEliminationRound(\n doc,\n mu,\n sy,\n slotMap,\n format,\n feedConfig,\n colX,\n roundColumnWidth,\n rightX,\n connectorGap,\n nextRoundIsFeed,\n );\n }\n\n if (ci < totalRoundCols - 1) {\n const nextColX = getColX(ci + 1);\n if (nextRoundIsFeed) {\n doc.line(rightX, sy.midY, nextColX, sy.midY);\n } else {\n doc.line(rightX + connectorGap, sy.midY, nextColX, sy.midY);\n }\n }\n\n if (mu.score) {\n const scoreStr = formatMatchScore(mu.score, format);\n setFont(doc, scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n const scoreBaselineY = sy.midY + scoreFontSize * 0.12;\n doc.text(scoreStr, rightX - 1, scoreBaselineY, { align: 'right' });\n doc.setTextColor(0);\n }\n }\n }\n}\n\nfunction renderFeedFirstRound(\n doc: jsPDF,\n mu: DrawMatchUp,\n sy: { topY: number; bottomY: number; midY: number },\n slotMap: Map<number, DrawSlot>,\n format: DrawFormatConfig,\n feedConfig: TraditionalDrawConfig,\n colX: number,\n firstRoundWidth: number,\n rightX: number,\n connectorGap: number,\n nextRoundIsFeed: boolean,\n): void {\n if (mu.drawPositions[0])\n drawPlayerLine(\n doc,\n slotMap.get(mu.drawPositions[0]),\n mu.drawPositions[0],\n format,\n feedConfig,\n colX,\n sy.topY,\n firstRoundWidth,\n );\n if (mu.drawPositions[1])\n drawPlayerLine(\n doc,\n slotMap.get(mu.drawPositions[1]),\n mu.drawPositions[1],\n format,\n feedConfig,\n colX,\n sy.bottomY,\n firstRoundWidth,\n );\n\n drawRightBracketConnector(doc, sy, rightX, connectorGap, nextRoundIsFeed);\n}\n\nfunction renderFeedRound(\n doc: jsPDF,\n mu: DrawMatchUp,\n sy: { topY: number; bottomY: number; midY: number },\n slotMap: Map<number, DrawSlot>,\n roundMap: Map<number, DrawMatchUp[]>,\n sortedRounds: number[],\n ci: number,\n format: DrawFormatConfig,\n feedConfig: TraditionalDrawConfig,\n colX: number,\n roundColumnWidth: number,\n rightX: number,\n connectorGap: number,\n nextRoundIsFeed: boolean,\n): void {\n const prevRoundNum = sortedRounds[ci - 1];\n const prevMatchUps = roundMap.get(prevRoundNum) || [];\n const prevWinnerPositions = new Set<number>();\n for (const pmu of prevMatchUps) {\n if (pmu.winningSide) {\n prevWinnerPositions.add(pmu.drawPositions[pmu.winningSide - 1]);\n }\n }\n\n const advDp = mu.drawPositions.find((dp) => dp && prevWinnerPositions.has(dp));\n const fedDp = mu.drawPositions.find((dp) => dp && dp !== advDp);\n\n doc.line(colX, sy.midY, colX, sy.bottomY);\n\n if (fedDp) {\n drawPlayerLine(doc, slotMap.get(fedDp), fedDp, format, feedConfig, colX, sy.topY, roundColumnWidth);\n } else {\n doc.line(colX, sy.topY, colX + roundColumnWidth, sy.topY);\n }\n doc.line(colX, sy.bottomY, colX + roundColumnWidth, sy.bottomY);\n if (advDp) {\n const advSlot = slotMap.get(advDp);\n if (advSlot?.participantName) {\n drawAdvancingName(doc, advSlot, format, feedConfig, colX, sy.bottomY);\n }\n }\n\n drawRightBracketConnector(doc, sy, rightX, connectorGap, nextRoundIsFeed);\n}\n\nfunction renderFeedEliminationRound(\n doc: jsPDF,\n mu: DrawMatchUp,\n sy: { topY: number; bottomY: number; midY: number },\n slotMap: Map<number, DrawSlot>,\n format: DrawFormatConfig,\n feedConfig: TraditionalDrawConfig,\n colX: number,\n roundColumnWidth: number,\n rightX: number,\n connectorGap: number,\n nextRoundIsFeed: boolean,\n): void {\n doc.line(colX, sy.topY, colX + roundColumnWidth, sy.topY);\n doc.line(colX, sy.bottomY, colX + roundColumnWidth, sy.bottomY);\n\n if (mu.drawPositions[0]) {\n const topSlot = slotMap.get(mu.drawPositions[0]);\n if (topSlot?.participantName) {\n drawAdvancingName(doc, topSlot, format, feedConfig, colX, sy.topY);\n }\n }\n if (mu.drawPositions[1]) {\n const bottomSlot = slotMap.get(mu.drawPositions[1]);\n if (bottomSlot?.participantName) {\n drawAdvancingName(doc, bottomSlot, format, feedConfig, colX, sy.bottomY);\n }\n }\n\n drawRightBracketConnector(doc, sy, rightX, connectorGap, nextRoundIsFeed);\n}\n\nfunction drawRightBracketConnector(\n doc: jsPDF,\n sy: { topY: number; bottomY: number },\n rightX: number,\n connectorGap: number,\n nextRoundIsFeed: boolean,\n): void {\n if (nextRoundIsFeed) {\n doc.line(rightX, sy.topY, rightX, sy.bottomY);\n } else {\n doc.line(rightX + connectorGap, sy.topY, rightX + connectorGap, sy.bottomY);\n doc.line(rightX, sy.topY, rightX + connectorGap, sy.topY);\n doc.line(rightX, sy.bottomY, rightX + connectorGap, sy.bottomY);\n }\n}\n\nfunction renderFeedWinnerColumn(\n doc: jsPDF,\n drawData: DrawData,\n sortedRounds: number[],\n totalRoundCols: number,\n roundMap: Map<number, DrawMatchUp[]>,\n roundSlotYs: Map<number, { topY: number; bottomY: number; midY: number }[]>,\n slotMap: Map<number, DrawSlot>,\n getColX: (ci: number) => number,\n contentTop: number,\n contentHeight: number,\n roundColumnWidth: number,\n fontSize: number,\n scoreFontSize: number,\n format: DrawFormatConfig,\n): void {\n if (drawData.noWinnerColumn) return;\n\n const winnerColX = getColX(totalRoundCols);\n const lastRound = sortedRounds.at(-1)!;\n const lastSlots = roundSlotYs.get(lastRound) || [];\n const winnerMidY = lastSlots[0]?.midY || contentTop + contentHeight / 2;\n\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(winnerColX, winnerMidY, winnerColX + Math.min(65, roundColumnWidth), winnerMidY);\n\n const finalMu = (roundMap.get(lastRound) || [])[0];\n if (finalMu?.winningSide) {\n const winnerPos = finalMu.drawPositions[finalMu.winningSide - 1];\n const winnerSlot = slotMap.get(winnerPos);\n if (winnerSlot) {\n setFont(doc, fontSize + 1, STYLE.BOLD);\n const { name: winnerName } = formatPlayerEntrySplit(winnerSlot, format);\n doc.text(winnerName, winnerColX + 1, winnerMidY - 0.5);\n\n if (finalMu.score) {\n const scoreStr = formatMatchScore(finalMu.score, format);\n setFont(doc, scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(scoreStr, winnerColX + 1, winnerMidY + scoreFontSize * 0.4);\n doc.setTextColor(0);\n }\n }\n }\n}\n\nfunction renderFeedRoundHeaders(\n doc: jsPDF,\n sortedRounds: number[],\n drawData: DrawData,\n config: TraditionalDrawConfig,\n format: DrawFormatConfig,\n regions: PageRegions,\n getColX: (ci: number) => number,\n totalRoundCols: number,\n roundColumnWidth: number,\n): void {\n const headerFontSize = config.fontSize <= SIZE.TINY ? 5.5 : SIZE.SMALL;\n setFont(doc, headerFontSize, STYLE.BOLD);\n doc.setTextColor(40);\n\n for (let ci = 0; ci < totalRoundCols; ci++) {\n const roundNum = sortedRounds[ci];\n const defaultLabel = getRoundLabel(roundNum, drawData.totalRounds);\n const label = drawData.roundLabelMap?.[roundNum] || format.roundLabels[defaultLabel] || defaultLabel;\n const x = getColX(ci);\n const width = ci === 0 ? config.firstRoundWidth : roundColumnWidth;\n doc.text(label, x + width / 2, regions.contentY + 2, { align: 'center' });\n doc.setDrawColor(160);\n doc.setLineWidth(0.15);\n doc.line(x + 2, regions.contentY + 3.5, x + width - 2, regions.contentY + 3.5);\n }\n\n const winnerX = getColX(totalRoundCols);\n doc.text('Winner', winnerX + roundColumnWidth / 2, regions.contentY + 2, { align: 'center' });\n doc.setDrawColor(160);\n doc.line(winnerX + 2, regions.contentY + 3.5, winnerX + roundColumnWidth - 2, regions.contentY + 3.5);\n doc.setTextColor(0);\n}\n\nfunction renderPowerOf2Draw(\n doc: jsPDF,\n drawData: DrawData,\n format: DrawFormatConfig,\n regions: PageRegions,\n positionOffset: number = 0,\n positionCount?: number,\n): void {\n const count = positionCount || drawData.drawSize;\n const actualRoundCount = drawData.totalRounds || Math.ceil(Math.log2(count));\n const computedRounds = Math.log2(count);\n // Use actual round count from data when it differs from the computed value\n // (e.g., qualifying structures that don't resolve to a single winner)\n const totalRounds = Number.isInteger(computedRounds) ? Math.min(computedRounds, actualRoundCount) : actualRoundCount;\n const config = getDrawConfig(count, regions, totalRounds);\n const margins = format.page.margins;\n\n const startX = margins.left;\n const startY = regions.contentY + 9;\n\n renderRoundHeaders(\n doc,\n totalRounds,\n drawData.totalRounds,\n config,\n format,\n startX,\n regions.contentY + 2,\n drawData.roundLabelMap,\n drawData.noWinnerColumn,\n );\n\n for (let round = 0; round < totalRounds; round++) {\n renderPowerOf2Round(doc, drawData, format, config, count, round, totalRounds, startX, startY, positionOffset);\n }\n\n if (drawData.noWinnerColumn) return;\n\n renderPowerOf2WinnerColumn(doc, drawData, format, config, totalRounds, startX, startY);\n}\n\nfunction renderPowerOf2Round(\n doc: jsPDF,\n drawData: DrawData,\n format: DrawFormatConfig,\n config: TraditionalDrawConfig,\n count: number,\n round: number,\n totalRounds: number,\n startX: number,\n startY: number,\n positionOffset: number,\n): void {\n const matchesInRound = count / Math.pow(2, round + 1);\n const spacing = config.lineHeight * Math.pow(2, round);\n const roundX = getRoundX(round, config, startX);\n const roundOffset = ((Math.pow(2, round) - 1) * config.lineHeight) / 2;\n const stride = Math.pow(2, round + 1) * config.lineHeight;\n\n for (let match = 0; match < matchesInRound; match++) {\n const topSlotY = startY + roundOffset + match * stride;\n const bottomSlotY = topSlotY + spacing;\n const midY = (topSlotY + bottomSlotY) / 2;\n\n if (round === 0) {\n const topPos = positionOffset + match * 2 + 1;\n const bottomPos = positionOffset + match * 2 + 2;\n drawPlayerLine(doc, findSlot(drawData.slots, topPos), topPos, format, config, roundX, topSlotY);\n drawPlayerLine(doc, findSlot(drawData.slots, bottomPos), bottomPos, format, config, roundX, bottomSlotY);\n } else {\n const colWidth = getRoundWidth(round, config);\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(roundX, topSlotY, roundX + colWidth, topSlotY);\n doc.line(roundX, bottomSlotY, roundX + colWidth, bottomSlotY);\n }\n\n const isFinalRound = round === totalRounds - 1;\n const rightX = roundX + getRoundWidth(round, config);\n\n // Always draw the bracket connector (vertical + horizontals between the two slots)\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(rightX + config.connectorGap, topSlotY, rightX + config.connectorGap, bottomSlotY);\n doc.line(rightX, topSlotY, rightX + config.connectorGap, topSlotY);\n doc.line(rightX, bottomSlotY, rightX + config.connectorGap, bottomSlotY);\n\n // Horizontal line from bracket midpoint to the next round (skip on qualifying final)\n if (!isFinalRound || !drawData.noWinnerColumn) {\n const nextRoundX = getRoundX(round + 1, config, startX);\n doc.line(rightX + config.connectorGap, midY, nextRoundX, midY);\n }\n\n const mu = findMatchUp(drawData.matchUps, round + 1, match + 1);\n\n if (isFinalRound && drawData.noWinnerColumn) {\n // Final qualifying round: draw a short winner line and name to the right\n const advancingSlot = getAdvancingSlot(mu, drawData.slots);\n if (advancingSlot) {\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(rightX + config.connectorGap, midY, rightX + config.connectorGap + config.roundColumnWidth, midY);\n drawAdvancingName(doc, advancingSlot, format, config, rightX + config.connectorGap, midY);\n if (mu?.score) {\n renderMatchScore(doc, mu, format, config, spacing, rightX + config.connectorGap, round, midY);\n }\n }\n } else if (!isFinalRound) {\n const advancingSlot = getAdvancingSlot(mu, drawData.slots);\n if (advancingSlot) {\n const nextRoundX = getRoundX(round + 1, config, startX);\n drawAdvancingName(doc, advancingSlot, format, config, nextRoundX, midY);\n if (mu?.score) {\n renderMatchScore(doc, mu, format, config, spacing, nextRoundX, round, midY);\n }\n }\n }\n }\n}\n\nfunction renderMatchScore(\n doc: jsPDF,\n mu: DrawMatchUp,\n format: DrawFormatConfig,\n config: TraditionalDrawConfig,\n spacing: number,\n nextRoundX: number,\n round: number,\n midY: number,\n): void {\n const scoreStr = formatMatchScore(mu.score!, format);\n setFont(doc, config.scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n const nextRoundSlotHeight = spacing * 2;\n const isDenseRound = nextRoundSlotHeight < config.scoreFontSize * 1.2;\n if (isDenseRound) {\n const nextColWidth = getRoundWidth(round + 1, config);\n const colRight = nextRoundX + nextColWidth - 1;\n doc.text(scoreStr, colRight, midY - 0.5, { align: 'right' });\n } else {\n const scoreOffset = config.scoreFontSize * 0.4;\n doc.text(scoreStr, nextRoundX + 1, midY - 0.5 + scoreOffset);\n }\n doc.setTextColor(0);\n}\n\nfunction renderPowerOf2WinnerColumn(\n doc: jsPDF,\n drawData: DrawData,\n format: DrawFormatConfig,\n config: TraditionalDrawConfig,\n totalRounds: number,\n startX: number,\n startY: number,\n): void {\n const winnerX = getRoundX(totalRounds, config, startX);\n const finalRoundOffset = ((Math.pow(2, totalRounds - 1) - 1) * config.lineHeight) / 2;\n const finalSpacing = config.lineHeight * Math.pow(2, totalRounds - 1);\n const winnerMidY = startY + finalRoundOffset + finalSpacing / 2;\n\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(winnerX, winnerMidY, winnerX + config.roundColumnWidth, winnerMidY);\n\n const finalMu = findMatchUp(drawData.matchUps, totalRounds, 1);\n if (finalMu?.winningSide) {\n const winnerPos = finalMu.drawPositions[finalMu.winningSide - 1];\n const winnerSlot = findSlot(drawData.slots, winnerPos);\n if (winnerSlot) {\n setFont(doc, config.fontSize + 1, STYLE.BOLD);\n const { name: winnerName } = formatPlayerEntrySplit(winnerSlot, format);\n doc.text(winnerName, winnerX + 1, winnerMidY - 0.5);\n\n if (finalMu.score) {\n const scoreStr = formatMatchScore(finalMu.score, format);\n setFont(doc, config.scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(scoreStr, winnerX + 1, winnerMidY + config.scoreFontSize * 0.4);\n doc.setTextColor(0);\n }\n }\n }\n}\n\nfunction renderRoundHeaders(\n doc: jsPDF,\n segmentRounds: number,\n totalRounds: number,\n config: TraditionalDrawConfig,\n format: DrawFormatConfig,\n startX: number,\n y: number,\n roundLabelMap?: Record<number, string>,\n noWinnerColumn?: boolean,\n): void {\n const isDense = config.fontSize <= SIZE.TINY;\n const headerFontSize = isDense ? 5.5 : SIZE.SMALL;\n\n setFont(doc, headerFontSize, STYLE.BOLD);\n doc.setTextColor(40);\n\n // Round headers for R1..Rn\n for (let round = 0; round < segmentRounds; round++) {\n const roundNumber = totalRounds - segmentRounds + round + 1;\n const defaultLabel = getRoundLabel(roundNumber, totalRounds);\n const label = roundLabelMap?.[roundNumber] || format.roundLabels[defaultLabel] || defaultLabel;\n const x = getRoundX(round, config, startX);\n const width = getRoundWidth(round, config);\n const centerX = x + width / 2;\n\n doc.text(label, centerX, y, { align: 'center' });\n\n doc.setDrawColor(160);\n doc.setLineWidth(0.15);\n doc.line(x + 2, y + 1.5, x + width - 2, y + 1.5);\n }\n\n // Winner column header (only on pages that include the final)\n if (!noWinnerColumn) {\n const winnerX = getRoundX(segmentRounds, config, startX);\n doc.text('Winner', winnerX + config.roundColumnWidth / 2, y, { align: 'center' });\n doc.setDrawColor(160);\n doc.setLineWidth(0.15);\n doc.line(winnerX + 2, y + 1.5, winnerX + config.roundColumnWidth - 2, y + 1.5);\n }\n\n doc.setTextColor(0);\n}\n\nfunction getRoundWidth(round: number, config: TraditionalDrawConfig): number {\n if (round === 0) return config.firstRoundWidth;\n if (round === 1) return config.secondRoundWidth;\n return config.roundColumnWidth;\n}\n\nfunction getRoundX(round: number, config: TraditionalDrawConfig, startX: number): number {\n if (round === 0) return startX;\n let x = startX + config.firstRoundWidth + config.connectorGap;\n for (let r = 1; r < round; r++) {\n x += getRoundWidth(r, config) + config.connectorGap;\n }\n return x;\n}\n\nfunction drawPlayerLine(\n doc: jsPDF,\n slot: DrawSlot | undefined,\n drawPosition: number,\n format: DrawFormatConfig,\n config: TraditionalDrawConfig,\n x: number,\n y: number,\n colWidth?: number,\n): void {\n const posNumWidth = config.fontSize <= 5 ? 4 : 5;\n const natGapWidth = config.fontSize <= 5 ? 5 : 6;\n const width = colWidth || config.firstRoundWidth;\n\n // Draw position number (left-aligned)\n const textOffset = config.lineHeight < 2 ? 0.15 : 0.3;\n setFont(doc, config.scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(120);\n doc.text(`${drawPosition}`, x, y - textOffset, { align: 'left' });\n doc.setTextColor(0);\n\n // Nationality / country code in the gap between position number and line\n if (slot?.nationality) {\n setFont(doc, config.scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(100);\n doc.text(slot.nationality, x + posNumWidth + natGapWidth - 1, y - textOffset, { align: 'right' });\n doc.setTextColor(0);\n }\n\n // Horizontal line (starts after the nationality gap)\n const lineStart = x + posNumWidth + natGapWidth;\n const lineEnd = x + width;\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(lineStart, y, lineEnd, y);\n\n if (!slot) return;\n\n const { name } = formatPlayerEntrySplit(slot, format);\n if (!name) return;\n\n setFont(doc, config.fontSize, slot.isBye ? STYLE.ITALIC : STYLE.NORMAL);\n if (slot.isBye) doc.setTextColor(150);\n\n // If name is too wide, use abbreviated form (F. LASTNAME)\n const availableWidth = lineEnd - lineStart - 2;\n let displayName = name;\n if (doc.getTextWidth(name) > availableWidth) {\n displayName = abbreviateName(slot.participantName);\n }\n const nameOffset = config.lineHeight < 2 ? 0.2 : 0.5;\n doc.text(displayName, lineStart + 1, y - nameOffset);\n if (slot.isBye) doc.setTextColor(0);\n}\n\nfunction drawAdvancingName(\n doc: jsPDF,\n slot: DrawSlot,\n format: DrawFormatConfig,\n config: TraditionalDrawConfig,\n x: number,\n y: number,\n): void {\n const shortName = abbreviateName(slot.participantName);\n let seed = '';\n if (slot.seedValue) {\n seed = format.seedFormat === 'parens' ? `(${slot.seedValue})` : `[${slot.seedValue}]`;\n }\n const display = seed ? `${shortName} ${seed}` : shortName;\n\n setFont(doc, config.fontSize, STYLE.BOLD);\n doc.text(display, x + 1, y - 0.5);\n}\n\nfunction abbreviateName(fullName: string): string {\n const commaMatch = fullName.match(/^([^,]+),\\s*(.+)/);\n if (commaMatch) return `${commaMatch[2][0]}. ${commaMatch[1]}`;\n const spaceMatch = fullName.match(/^(\\S+)\\s+(.+)/);\n if (spaceMatch) return `${spaceMatch[1][0]}. ${spaceMatch[2]}`;\n return fullName;\n}\n\nfunction findSlot(slots: DrawSlot[], drawPosition: number): DrawSlot | undefined {\n return slots.find((s) => s.drawPosition === drawPosition);\n}\n\nfunction findMatchUp(matchUps: DrawMatchUp[], roundNumber: number, roundPosition: number): DrawMatchUp | undefined {\n return matchUps.find((mu) => mu.roundNumber === roundNumber && mu.roundPosition === roundPosition);\n}\n\n/** Find the advancing participant slot for a matchUp (handles both completed and BYE matchUps) */\nfunction getAdvancingSlot(mu: DrawMatchUp | undefined, slots: DrawSlot[]): DrawSlot | undefined {\n if (!mu) return undefined;\n\n if (mu.winningSide) {\n const winnerPos = mu.drawPositions[mu.winningSide - 1];\n return findSlot(slots, winnerPos);\n }\n\n // BYE matchUp: the non-BYE participant advances\n if (mu.matchUpStatus === 'BYE') {\n for (const pos of mu.drawPositions) {\n const slot = findSlot(slots, pos);\n if (slot && !slot.isBye && slot.participantName) return slot;\n }\n }\n\n return undefined;\n}\n","import jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport type { PageRegions, DrawFormatConfig } from '../config/types';\nimport type { RoundRobinGroupData } from '../core/extractRoundRobinData';\nimport { formatMatchScore } from './formatEntry';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nconst GRAY_FILL: [number, number, number] = [200, 200, 200];\nconst WIN_COLOR: [number, number, number] = [20, 80, 20];\nconst LOSS_COLOR: [number, number, number] = [160, 40, 40];\nconst HEADER_FILL: [number, number, number] = [50, 50, 50];\n\nexport function renderRoundRobinGroup(\n doc: jsPDF,\n group: RoundRobinGroupData,\n format: DrawFormatConfig,\n _regions: PageRegions,\n startY: number,\n): number {\n const margins = format.page.margins;\n const count = group.participants.length;\n\n // Group title\n setFont(doc, SIZE.HEADING, STYLE.BOLD);\n doc.text(group.groupName, margins.left, startY);\n startY += 5;\n\n // Build the grid: rows = participants, cols = # + Name + Nat + each opponent + W + L\n const headerRow = ['#', 'Player', 'Nat.'];\n for (let i = 0; i < count; i++) {\n headerRow.push(`${i + 1}`);\n }\n headerRow.push('W', 'L');\n\n // Build result matrix\n const resultMatrix = buildResultMatrix(group, format);\n\n // Build table body\n const body: any[][] = group.participants.map((p, rowIdx) => {\n const row: any[] = [\n { content: `${rowIdx + 1}`, styles: { fontStyle: 'bold', halign: 'center' } },\n { content: p.participantName + (p.seedValue ? ` [${p.seedValue}]` : ''), styles: { fontStyle: 'bold' } },\n { content: p.nationality, styles: { halign: 'center' } },\n ];\n\n // Score cells for each opponent\n for (let colIdx = 0; colIdx < count; colIdx++) {\n if (rowIdx === colIdx) {\n // Self-intersection: grayed out\n row.push({ content: '', styles: { fillColor: GRAY_FILL } });\n } else {\n const cell = resultMatrix[rowIdx]?.[colIdx];\n if (cell) {\n const textColor = cell.isWin ? WIN_COLOR : LOSS_COLOR;\n row.push({ content: cell.score, styles: { halign: 'center', textColor } });\n } else {\n row.push({ content: '', styles: { halign: 'center' } });\n }\n }\n }\n\n // Win/Loss counts\n const wins = resultMatrix[rowIdx]?.filter((c) => c?.isWin).length || 0;\n const losses = resultMatrix[rowIdx]?.filter((c) => c && !c.isWin).length || 0;\n row.push({ content: `${wins}`, styles: { halign: 'center', fontStyle: 'bold' } });\n row.push({ content: `${losses}`, styles: { halign: 'center' } });\n\n return row;\n });\n\n autoTable(doc, {\n startY,\n head: [headerRow],\n body,\n styles: {\n fontSize: 7,\n cellPadding: 1.5,\n lineWidth: 0.2,\n lineColor: [150, 150, 150],\n },\n headStyles: {\n fillColor: HEADER_FILL,\n textColor: [255, 255, 255],\n fontStyle: 'bold',\n halign: 'center',\n fontSize: 7,\n },\n columnStyles: {\n 0: { cellWidth: 8 },\n 1: { cellWidth: 'auto' },\n 2: { cellWidth: 12 },\n },\n margin: { left: margins.left, right: margins.right },\n });\n\n return (doc as any).lastAutoTable?.finalY || startY + 40;\n}\n\ninterface CellResult {\n score: string;\n isWin: boolean;\n}\n\nfunction buildResultMatrix(group: RoundRobinGroupData, format: DrawFormatConfig): (CellResult | null)[][] {\n const count = group.participants.length;\n const matrix: (CellResult | null)[][] = Array.from({ length: count }, () => Array(count).fill(null));\n\n // Map group positions to matrix indices\n const posToIdx = new Map<number, number>();\n group.participants.forEach((p, i) => posToIdx.set(p.groupPosition, i));\n\n for (const result of group.results) {\n const rowIdx = posToIdx.get(result.rowPosition);\n const colIdx = posToIdx.get(result.colPosition);\n if (rowIdx === undefined || colIdx === undefined) continue;\n\n const score = formatMatchScore(result.score, format);\n const isRowWinner = result.winningSide === 1;\n\n // Row player's perspective\n matrix[rowIdx][colIdx] = { score, isWin: isRowWinner };\n // Column player's perspective (reversed score)\n matrix[colIdx][rowIdx] = { score: reverseScore(score), isWin: !isRowWinner };\n }\n\n return matrix;\n}\n\nfunction reverseScore(score: string): string {\n // Reverse set scores: \"6-4 3-6\" -> \"4-6 6-3\"\n return score\n .split(/\\s+/)\n .map((set) => {\n const match = set.match(/^(\\d+)([/-])(\\d+)(\\(\\d+\\))?$/);\n if (match) return `${match[3]}${match[2]}${match[1]}${match[4] || ''}`;\n return set;\n })\n .join(' ');\n}\n","import jsPDF from 'jspdf';\nimport type { PageRegions, DrawFormatConfig } from '../config/types';\nimport type { DrawData, DrawMatchUp } from '../core/extractDrawData';\nimport { getRoundLabel } from '../core/extractDrawData';\nimport { formatPlayerEntry, formatMatchScore } from './formatEntry';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nconst BOX_INNER_PAD = 1;\nconst PREFERRED_BOX_HEIGHT = 16;\nconst MIN_BOX_GAP = 1;\n\nexport function renderLuckyDraw(doc: jsPDF, drawData: DrawData, format: DrawFormatConfig, regions: PageRegions): void {\n const margins = format.page.margins;\n\n // Group matchUps by round\n const roundMap = new Map<number, DrawMatchUp[]>();\n for (const mu of drawData.matchUps) {\n if (!roundMap.has(mu.roundNumber)) roundMap.set(mu.roundNumber, []);\n roundMap.get(mu.roundNumber)!.push(mu);\n }\n\n const slotMap = new Map(drawData.slots.map((s) => [s.drawPosition, s]));\n const sortedRounds = [...roundMap.keys()].sort((a, b) => a - b);\n const totalRounds = sortedRounds.length;\n\n // Layout: vertical columns, left to right\n const headerReserve = 7;\n const contentTop = regions.contentY + headerReserve;\n const contentHeight = regions.contentHeight - headerReserve;\n const roundGap = 6;\n const boxWidth = Math.min(55, (regions.contentWidth - (totalRounds - 1) * roundGap) / totalRounds);\n\n // Scale box height to fit the largest round (R1) with minimum gaps\n const maxMatchesInRound = roundMap.get(sortedRounds[0])?.length || 1;\n const boxHeight = Math.min(\n PREFERRED_BOX_HEIGHT,\n (contentHeight - (maxMatchesInRound + 1) * MIN_BOX_GAP) / maxMatchesInRound,\n );\n\n // Round headers\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.setTextColor(30, 60, 120);\n for (let ri = 0; ri < totalRounds; ri++) {\n const roundNum = sortedRounds[ri];\n const label =\n format.roundLabels[getRoundLabel(roundNum, drawData.totalRounds)] ||\n getRoundLabel(roundNum, drawData.totalRounds);\n const colX = margins.left + ri * (boxWidth + roundGap);\n doc.text(label, colX + boxWidth / 2, regions.contentY + 3, { align: 'center' });\n }\n doc.setTextColor(0);\n\n // Render each round column\n for (let ri = 0; ri < totalRounds; ri++) {\n const roundNum = sortedRounds[ri];\n const matchUps = roundMap.get(roundNum) || [];\n const count = matchUps.length;\n const colX = margins.left + ri * (boxWidth + roundGap);\n\n // Space-around: evenly distribute boxes vertically\n const totalBoxHeight = count * boxHeight;\n const gap = count > 1 ? (contentHeight - totalBoxHeight) / (count + 1) : (contentHeight - boxHeight) / 2;\n\n for (let i = 0; i < count; i++) {\n const y = contentTop + gap + i * (boxHeight + gap);\n renderMatchBox(doc, matchUps[i], slotMap, format, colX, y, boxWidth, boxHeight);\n }\n }\n}\n\nfunction renderMatchBox(\n doc: jsPDF,\n mu: DrawMatchUp,\n slotMap: Map<number, any>,\n format: DrawFormatConfig,\n x: number,\n y: number,\n width: number,\n height: number,\n): void {\n const isCompact = height < 10;\n const fontSize = isCompact ? 5 : SIZE.TINY;\n\n // Box outline\n doc.setDrawColor(100);\n doc.setLineWidth(0.3);\n doc.rect(x, y, width, height);\n\n // Divider line in middle\n const midY = y + height / 2;\n doc.setLineWidth(0.15);\n doc.line(x, midY, x + width, midY);\n\n // Side 1 (top half)\n const slot1 = mu.drawPositions[0] ? slotMap.get(mu.drawPositions[0]) : undefined;\n if (slot1) {\n const text = formatPlayerEntry(slot1, format);\n const isWinner = mu.winningSide === 1;\n setFont(doc, fontSize, isWinner ? STYLE.BOLD : STYLE.NORMAL);\n doc.text(text, x + BOX_INNER_PAD, midY - fontSize * 0.15, { maxWidth: width - 2 * BOX_INNER_PAD });\n }\n\n // Side 2 (bottom half)\n const slot2 = mu.drawPositions[1] ? slotMap.get(mu.drawPositions[1]) : undefined;\n if (slot2) {\n const text = formatPlayerEntry(slot2, format);\n const isWinner = mu.winningSide === 2;\n setFont(doc, fontSize, isWinner ? STYLE.BOLD : STYLE.NORMAL);\n doc.text(text, x + BOX_INNER_PAD, midY + fontSize * 0.55, { maxWidth: width - 2 * BOX_INNER_PAD });\n }\n\n // Score (top right corner)\n if (mu.score) {\n const scoreStr = formatMatchScore(mu.score, format);\n setFont(doc, fontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(scoreStr, x + width - BOX_INNER_PAD, y + fontSize * 0.5, { align: 'right' });\n doc.setTextColor(0);\n }\n}\n","import type { DrawSplitConfig } from '../config/types';\nimport type { DrawData, DrawSlot, DrawMatchUp } from '../core/extractDrawData';\n\nexport interface DrawSegment {\n label: string;\n startPosition: number;\n endPosition: number;\n slots: DrawSlot[];\n matchUps: DrawMatchUp[];\n segmentRounds: number;\n /** If true, this segment should NOT render a winner column */\n noWinnerColumn?: boolean;\n /** Remapped round labels for this segment */\n roundLabelMap?: Record<number, string>;\n}\n\nconst DEFAULT_SPLIT: DrawSplitConfig = {\n maxPositionsPerPage: 64,\n includeOverlapRounds: true,\n summaryPage: true,\n};\n\nexport function splitDraw(drawData: DrawData, config: DrawSplitConfig = DEFAULT_SPLIT): DrawSegment[] {\n const { drawSize, slots, matchUps, totalRounds } = drawData;\n\n if (drawSize <= config.maxPositionsPerPage) {\n return [\n {\n label: 'Full Draw',\n startPosition: 1,\n endPosition: drawSize,\n slots,\n matchUps,\n segmentRounds: totalRounds,\n },\n ];\n }\n\n const segmentSize = config.maxPositionsPerPage;\n const segmentCount = Math.ceil(drawSize / segmentSize);\n const segmentRounds = Math.log2(segmentSize);\n const segments: DrawSegment[] = [];\n\n for (let i = 0; i < segmentCount; i++) {\n segments.push(buildPositionSegment(i, segmentSize, segmentCount, segmentRounds, drawSize, slots, matchUps));\n }\n\n if (config.summaryPage && segmentCount > 1) {\n segments.push(buildSummarySegment(drawData));\n }\n\n return segments;\n}\n\nfunction buildPositionSegment(\n index: number,\n segmentSize: number,\n segmentCount: number,\n segmentRounds: number,\n drawSize: number,\n slots: DrawSlot[],\n matchUps: DrawMatchUp[],\n): DrawSegment {\n const startPos = index * segmentSize + 1;\n const endPos = Math.min((index + 1) * segmentSize, drawSize);\n let segmentLabel = `Section ${index + 1}`;\n if (segmentCount === 2) segmentLabel = index === 0 ? 'Top Half' : 'Bottom Half';\n\n const segSlots = slots.filter((s) => s.drawPosition >= startPos && s.drawPosition <= endPos);\n\n const segMatchUpsRaw = matchUps.filter((mu) => {\n if (mu.roundNumber > segmentRounds) return false;\n return mu.drawPositions.every((dp) => dp >= startPos && dp <= endPos);\n });\n\n const segMatchUps = renumberRoundPositions(segMatchUpsRaw);\n\n return {\n label: segmentLabel,\n startPosition: startPos,\n endPosition: endPos,\n slots: segSlots,\n matchUps: segMatchUps,\n segmentRounds,\n noWinnerColumn: true,\n };\n}\n\nfunction buildSummarySegment(drawData: DrawData): DrawSegment {\n const { slots, matchUps, totalRounds, roundLabelMap } = drawData;\n const finalRoundsCount = 5;\n const summaryRoundStart = Math.max(1, totalRounds - finalRoundsCount + 1);\n const summaryRounds = totalRounds - summaryRoundStart + 1;\n const roundOffset = summaryRoundStart - 1;\n\n const firstRoundMatchUps = matchUps\n .filter((mu) => mu.roundNumber === summaryRoundStart)\n .sort((a, b) => a.roundPosition - b.roundPosition);\n const summaryDrawSize = firstRoundMatchUps.length * 2;\n\n const positionMap = buildPositionMap(firstRoundMatchUps);\n\n const summaryMatchUps = matchUps.filter((mu) => mu.roundNumber >= summaryRoundStart);\n const renumbered: DrawMatchUp[] = summaryMatchUps.map((mu) => ({\n ...mu,\n roundNumber: mu.roundNumber - roundOffset,\n roundPosition:\n mu.roundNumber === summaryRoundStart\n ? firstRoundMatchUps.findIndex((m) => m.roundPosition === mu.roundPosition) + 1\n : mu.roundPosition,\n drawPositions: mu.drawPositions.map((dp) => positionMap.get(dp) || dp),\n }));\n\n const finalMatchUps = renumberRoundPositions(renumbered);\n\n const summarySlots: DrawSlot[] = [];\n for (const [origPos, newP] of positionMap) {\n const slot = slots.find((s) => s.drawPosition === origPos);\n if (slot) {\n summarySlots.push({ ...slot, drawPosition: newP });\n }\n }\n summarySlots.sort((a, b) => a.drawPosition - b.drawPosition);\n\n const remappedLabels: Record<number, string> | undefined = roundLabelMap\n ? Object.fromEntries(\n Object.entries(roundLabelMap)\n .filter(([rn]) => Number(rn) >= summaryRoundStart)\n .map(([rn, label]) => [Number(rn) - roundOffset, label]),\n )\n : undefined;\n\n return {\n label: 'Final Rounds',\n startPosition: 1,\n endPosition: summaryDrawSize,\n slots: summarySlots,\n matchUps: finalMatchUps,\n segmentRounds: summaryRounds,\n roundLabelMap: remappedLabels,\n };\n}\n\nfunction renumberRoundPositions(matchUps: DrawMatchUp[]): DrawMatchUp[] {\n const byRound = new Map<number, DrawMatchUp[]>();\n for (const mu of matchUps) {\n if (!byRound.has(mu.roundNumber)) byRound.set(mu.roundNumber, []);\n byRound.get(mu.roundNumber)!.push(mu);\n }\n const result: DrawMatchUp[] = [];\n for (const [, roundMus] of byRound) {\n roundMus.sort((a, b) => a.roundPosition - b.roundPosition);\n roundMus.forEach((mu, idx) => {\n result.push({ ...mu, roundPosition: idx + 1 });\n });\n }\n return result;\n}\n\nfunction buildPositionMap(firstRoundMatchUps: DrawMatchUp[]): Map<number, number> {\n const positionMap = new Map<number, number>();\n let newPos = 1;\n for (const mu of firstRoundMatchUps) {\n for (const dp of mu.drawPositions) {\n if (dp && !positionMap.has(dp)) {\n positionMap.set(dp, newPos++);\n }\n }\n }\n return positionMap;\n}\n","/**\n * Compass draw renderer.\n *\n * Renders a compass draw with the main bracket (East) at the top,\n * followed by consolation brackets for each compass direction.\n * Each sub-bracket is a small single-elimination draw rendered\n * with a section header showing the compass direction name.\n *\n * Layout:\n * - Page 1: East (main bracket) — full width, traditional lines\n * - Below or page 2: West, North, South, NE, NW, SE, SW — smaller brackets\n * arranged in a grid layout\n */\n\nimport jsPDF from 'jspdf';\nimport type { DrawFormatConfig, PageRegions } from '../config/types';\nimport type { CompassDrawData, CompassStructure } from '../core/extractCompassData';\nimport type { DrawData } from '../core/extractDrawData';\nimport { renderTraditionalDraw } from './traditionalDraw';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\n// Rendering order: main bracket first, then consolation directions\nconst DIRECTION_ORDER = ['E', 'W', 'N', 'S', 'NE', 'NW', 'SE', 'SW'];\n\nexport function renderCompassDraw(\n doc: jsPDF,\n compassData: CompassDrawData,\n format: DrawFormatConfig,\n regions: PageRegions,\n): void {\n const margins = format.page.margins;\n const sortedStructures = [...compassData.structures].sort(\n (a, b) => DIRECTION_ORDER.indexOf(a.abbreviation) - DIRECTION_ORDER.indexOf(b.abbreviation),\n );\n\n let y = regions.contentY + 3;\n\n for (const structure of sortedStructures) {\n if (structure.drawSize === 0) continue;\n\n // Check if we need a new page\n const estimatedHeight = estimateStructureHeight(structure, regions);\n if (y + estimatedHeight > regions.contentY + regions.contentHeight) {\n doc.addPage();\n y = regions.contentY;\n }\n\n // Section header with compass direction\n const isMain = structure.abbreviation === 'E';\n setFont(doc, isMain ? SIZE.HEADING : SIZE.BODY, STYLE.BOLD);\n if (!isMain) doc.setTextColor(30, 60, 120);\n const label = isMain ? `Main Draw (${structure.name})` : `${structure.name} Draw`;\n doc.text(label, margins.left, y);\n if (!isMain) doc.setTextColor(0);\n y += isMain ? 5 : 4;\n\n // Render the bracket\n const structureRegions: PageRegions = {\n ...regions,\n contentY: y,\n contentHeight: estimatedHeight - 6,\n };\n\n const drawData = structureToDrawData(structure, compassData.drawName);\n renderTraditionalDraw(doc, drawData, format, structureRegions);\n\n y += estimatedHeight + 3;\n }\n}\n\nfunction estimateStructureHeight(structure: CompassStructure, regions: PageRegions): number {\n const maxHeight = regions.contentHeight * 0.7;\n const minLineHeight = 5;\n const lineHeight = Math.max(minLineHeight, Math.min(8, maxHeight / structure.drawSize));\n return structure.drawSize * lineHeight + 10;\n}\n\nfunction structureToDrawData(structure: CompassStructure, drawName: string): DrawData {\n return {\n drawName: `${drawName} - ${structure.name}`,\n drawSize: structure.drawSize,\n drawType: 'SINGLE_ELIMINATION',\n totalRounds: structure.totalRounds,\n slots: structure.slots,\n matchUps: structure.matchUps,\n seedAssignments: [],\n };\n}\n","/**\n * Consolation draw renderer.\n *\n * Renders a main draw followed by consolation bracket(s).\n * The consolation bracket receives first-round losers from the main draw.\n * Each structure is rendered as a separate section with a labeled header.\n *\n * Factory draw types that use this:\n * - FIRST_MATCH_LOSER_CONSOLATION\n * - FIRST_ROUND_LOSER_CONSOLATION\n * - FEED_IN_CHAMPIONSHIP\n * - CURTIS_CONSOLATION\n */\n\nimport jsPDF from 'jspdf';\nimport type { DrawFormatConfig, PageRegions } from '../config/types';\nimport type { DrawData } from '../core/extractDrawData';\nimport { participantName, nationality } from '../utils/primitives';\nimport { renderTraditionalDraw } from './traditionalDraw';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport interface ConsolationStructure {\n name: string;\n stage: string;\n drawData: DrawData;\n}\n\nexport function extractConsolationStructures(params: {\n drawDefinition: any;\n participants?: any[];\n processedMatchUps?: any[];\n}): ConsolationStructure[] {\n const { drawDefinition, participants = [] } = params;\n if (!drawDefinition?.structures) return [];\n\n const participantMap = new Map<string, any>();\n participants.forEach((p: any) => participantMap.set(p.participantId, p));\n\n return drawDefinition.structures.map((structure: any) => {\n const positionAssignments = structure.positionAssignments || [];\n const seedAssignments = structure.seedAssignments || [];\n const drawSize = positionAssignments.length;\n\n const slots = positionAssignments.map((pa: any) => {\n const participant = pa.participantId ? participantMap.get(pa.participantId) : undefined;\n const seed = seedAssignments.find((sa: any) => sa.participantId === pa.participantId);\n return {\n drawPosition: pa.drawPosition,\n participantName: participant ? participantName(participant) : '',\n nationality: participant ? nationality(participant) : '',\n seedValue: seed?.seedValue,\n isBye: pa.bye === true,\n };\n });\n\n const matchUps = (structure.matchUps || []).map((mu: any) => ({\n roundNumber: mu.roundNumber,\n roundPosition: mu.roundPosition,\n drawPositions: mu.drawPositions || [],\n score: mu.score?.scoreStringSide1 || '',\n winningSide: mu.winningSide,\n matchUpStatus: mu.matchUpStatus,\n }));\n\n const stage = structure.stage || 'MAIN';\n const isMain = stage === 'MAIN';\n const name = structure.structureName || (isMain ? 'Main Draw' : 'Consolation');\n\n const maxRound = matchUps.reduce((max: number, mu: any) => Math.max(max, mu.roundNumber || 0), 0);\n\n // Build roundLabelMap from engine-processed matchUps when available\n const structureProcessed = (params.processedMatchUps || []).filter(\n (m: any) => m.structureId === structure.structureId,\n );\n let roundLabelMap: Record<number, string> | undefined;\n if (structureProcessed.length) {\n roundLabelMap = {};\n for (const mu of structureProcessed) {\n if (mu.roundNumber && !roundLabelMap[mu.roundNumber]) {\n roundLabelMap[mu.roundNumber] = mu.abbreviatedRoundName || mu.roundName || `R${mu.roundNumber}`;\n }\n }\n }\n\n return {\n name,\n stage,\n drawData: {\n drawName: name,\n drawSize,\n drawType: 'SINGLE_ELIMINATION',\n totalRounds: maxRound,\n slots,\n matchUps,\n seedAssignments: seedAssignments\n .filter((sa: any) => sa.participantId)\n .map((sa: any) => {\n const p = participantMap.get(sa.participantId);\n return {\n seedValue: sa.seedValue,\n participantName: p ? participantName(p) : '',\n nationality: p ? nationality(p) : '',\n };\n }),\n roundLabelMap,\n },\n };\n });\n}\n\nexport function renderConsolationDraw(\n doc: jsPDF,\n structures: ConsolationStructure[],\n format: DrawFormatConfig,\n regions: PageRegions,\n): void {\n const margins = format.page.margins;\n let y = regions.contentY;\n\n // Sort: MAIN first, then CONSOLATION, then others\n const stageOrder: Record<string, number> = { MAIN: 0, CONSOLATION: 1, PLAY_OFF: 2 };\n const sorted = [...structures]\n .filter((s) => s.drawData.drawSize > 0)\n .sort((a, b) => (stageOrder[a.stage] ?? 9) - (stageOrder[b.stage] ?? 9));\n\n for (const structure of sorted) {\n const isMain = structure.stage === 'MAIN';\n const estimatedHeight = structure.drawData.drawSize * 3.5 + 8;\n\n // New page if needed\n if (y + estimatedHeight > regions.contentY + regions.contentHeight && y > regions.contentY + 10) {\n doc.addPage();\n y = regions.contentY;\n }\n\n // Section header with top padding\n y += 3;\n setFont(doc, isMain ? SIZE.HEADING : SIZE.BODY, STYLE.BOLD);\n if (!isMain) doc.setTextColor(120, 40, 40);\n doc.text(structure.name, margins.left, y);\n if (!isMain) doc.setTextColor(0);\n y += isMain ? 4 : 3;\n\n // Render bracket\n const structureRegions: PageRegions = {\n ...regions,\n contentY: y,\n contentHeight: Math.min(estimatedHeight, regions.contentY + regions.contentHeight - y),\n };\n\n renderTraditionalDraw(doc, structure.drawData, format, structureRegions);\n y += estimatedHeight + 4;\n }\n}\n","/**\n * Double elimination draw renderer.\n *\n * Layout: Winner's bracket (top ~45%) + Loser's bracket (bottom ~45%).\n * Both brackets flow left-to-right.\n *\n * The factory's DOUBLE_ELIMINATION draw type produces three structures:\n * - Main (MAIN) — winner's bracket, includes the championship match as R4\n * - Backdraw (CONSOLATION) — loser's bracket with feed rounds\n * - Decider (PLAY_OFF) — \"if first loss\" match (not rendered; implied by the final)\n *\n * Main bracket round label overrides:\n * - F-Q (qualifying final) → SF (semifinal of the overall tournament)\n * - F (final in main) → F (the championship match)\n * - Winner of F auto-advances to Winner column\n */\n\nimport jsPDF from 'jspdf';\nimport type { DrawFormatConfig, PageRegions } from '../config/types';\nimport type { DrawData } from '../core/extractDrawData';\nimport { renderTraditionalDraw } from './traditionalDraw';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport interface DoubleEliminationData {\n winnersBracket: DrawData;\n losersBracket: DrawData;\n deciderMatch?: DrawData;\n}\n\nexport function renderDoubleEliminationDraw(\n doc: jsPDF,\n data: DoubleEliminationData,\n format: DrawFormatConfig,\n regions: PageRegions,\n): void {\n const margins = format.page.margins;\n const totalHeight = regions.contentHeight;\n\n const winnersHeight = totalHeight * 0.44;\n const losersHeight = totalHeight * 0.44;\n const deciderWidth = 30;\n const bracketWidth = regions.contentWidth - deciderWidth - 8;\n\n // Override main bracket round labels: F-Q → SF, F → F\n const winnersData = overrideMainRoundLabels(data.winnersBracket);\n\n // Winner's bracket header\n let y = regions.contentY + 3;\n setFont(doc, SIZE.BODY, STYLE.BOLD);\n doc.setTextColor(30, 80, 30);\n doc.text(\"Winner's Bracket\", margins.left, y);\n doc.setTextColor(0);\n y += 3;\n\n const winnersRegions: PageRegions = {\n ...regions,\n contentY: y,\n contentHeight: winnersHeight - 6,\n contentWidth: bracketWidth,\n };\n renderTraditionalDraw(doc, winnersData, format, winnersRegions);\n\n // Loser's bracket header\n y = regions.contentY + winnersHeight + 6;\n setFont(doc, SIZE.BODY, STYLE.BOLD);\n doc.setTextColor(140, 40, 40);\n doc.text(\"Loser's Bracket (Backdraw)\", margins.left, y);\n doc.setTextColor(0);\n y += 3;\n\n const losersRegions: PageRegions = {\n ...regions,\n contentY: y,\n contentHeight: losersHeight - 6,\n contentWidth: bracketWidth,\n };\n renderTraditionalDraw(doc, data.losersBracket, format, losersRegions);\n\n // Decider section — positioned to the right of both brackets, vertically centered\n const deciderX = margins.left + bracketWidth + 8;\n const deciderCenterY = regions.contentY + totalHeight / 2;\n const boxWidth = deciderWidth - 2;\n const boxHeight = 14;\n\n // \"Decider\" label\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.text('Decider', deciderX + boxWidth / 2, deciderCenterY - boxHeight - 4, { align: 'center' });\n\n // Solid match box\n doc.setDrawColor(60);\n doc.setLineWidth(0.5);\n doc.rect(deciderX, deciderCenterY - boxHeight - 1, boxWidth, boxHeight);\n\n // Divider in match box\n doc.setLineWidth(0.2);\n doc.line(deciderX, deciderCenterY - boxHeight / 2 - 1, deciderX + boxWidth, deciderCenterY - boxHeight / 2 - 1);\n\n // Populate decider box with participant names if available\n if (data.deciderMatch?.matchUps?.length) {\n const decMu = data.deciderMatch.matchUps[0];\n const slotMap = new Map(data.deciderMatch.slots.map((s) => [s.drawPosition, s]));\n\n if (decMu.drawPositions[0]) {\n const slot = slotMap.get(decMu.drawPositions[0]);\n if (slot?.participantName) {\n const isWinner = decMu.winningSide === 1;\n setFont(doc, SIZE.TINY, isWinner ? STYLE.BOLD : STYLE.NORMAL);\n doc.text(slot.participantName, deciderX + 1, deciderCenterY - boxHeight / 2 - 3, { maxWidth: boxWidth - 2 });\n }\n }\n if (decMu.drawPositions[1]) {\n const slot = slotMap.get(decMu.drawPositions[1]);\n if (slot?.participantName) {\n const isWinner = decMu.winningSide === 2;\n setFont(doc, SIZE.TINY, isWinner ? STYLE.BOLD : STYLE.NORMAL);\n doc.text(slot.participantName, deciderX + 1, deciderCenterY - 3, { maxWidth: boxWidth - 2 });\n }\n }\n\n // Score in the match box\n if (decMu.score) {\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(decMu.score, deciderX + boxWidth - 1, deciderCenterY - boxHeight + 2, { align: 'right' });\n doc.setTextColor(0);\n }\n }\n}\n\n/** Override round labels in the main bracket for double elimination display */\nfunction overrideMainRoundLabels(drawData: DrawData): DrawData {\n const map = { ...(drawData.roundLabelMap || {}) };\n\n for (const r of Object.keys(map)) {\n if (map[Number(r)] === 'F-Q') map[Number(r)] = 'SF';\n }\n\n return { ...drawData, roundLabelMap: map };\n}\n","/**\n * Extract data for compass draws.\n *\n * A compass draw has up to 8 structures named by compass directions:\n * East (main), West, North, NE, South, SW, NW, SE.\n * Each structure is a small single-elimination bracket.\n */\n\nimport { participantName, nationality } from '../utils/primitives';\nimport type { DrawSlot, DrawMatchUp } from './extractDrawData';\n\nexport interface CompassStructure {\n name: string;\n abbreviation: string;\n drawSize: number;\n slots: DrawSlot[];\n matchUps: DrawMatchUp[];\n totalRounds: number;\n}\n\nexport interface CompassDrawData {\n drawName: string;\n structures: CompassStructure[];\n mainStructure?: CompassStructure;\n}\n\nconst COMPASS_NAMES: Record<string, { name: string; abbreviation: string }> = {\n East: { name: 'East', abbreviation: 'E' },\n West: { name: 'West', abbreviation: 'W' },\n North: { name: 'North', abbreviation: 'N' },\n South: { name: 'South', abbreviation: 'S' },\n Northeast: { name: 'Northeast', abbreviation: 'NE' },\n Northwest: { name: 'Northwest', abbreviation: 'NW' },\n Southeast: { name: 'Southeast', abbreviation: 'SE' },\n Southwest: { name: 'Southwest', abbreviation: 'SW' },\n};\n\nexport function extractCompassData(params: { drawDefinition: any; participants?: any[] }): CompassDrawData {\n const { drawDefinition, participants = [] } = params;\n if (!drawDefinition) return { drawName: '', structures: [] };\n\n const participantMap = new Map<string, any>();\n participants.forEach((p: any) => participantMap.set(p.participantId, p));\n\n const structures: CompassStructure[] = [];\n\n for (const structure of drawDefinition.structures || []) {\n const structureName = structure.structureName || '';\n const compassInfo = COMPASS_NAMES[structureName] || { name: structureName, abbreviation: structureName };\n\n const positionAssignments = structure.positionAssignments || [];\n const seedAssignments = structure.seedAssignments || [];\n const drawSize = positionAssignments.length || 0;\n\n const slots: DrawSlot[] = positionAssignments.map((pa: any) => {\n const participant = pa.participantId ? participantMap.get(pa.participantId) : undefined;\n const seedAssignment = seedAssignments.find((sa: any) => sa.participantId === pa.participantId);\n\n return {\n drawPosition: pa.drawPosition,\n participantName: participant ? participantName(participant) : '',\n nationality: participant ? nationality(participant) : '',\n seedValue: seedAssignment?.seedValue,\n isBye: pa.bye === true,\n };\n });\n\n const matchUps: DrawMatchUp[] = (structure.matchUps || []).map((mu: any) => ({\n roundNumber: mu.roundNumber,\n roundPosition: mu.roundPosition,\n drawPositions: mu.drawPositions || [],\n score: mu.score?.scoreStringSide1 || '',\n winningSide: mu.winningSide,\n matchUpStatus: mu.matchUpStatus,\n }));\n\n structures.push({\n name: compassInfo.name,\n abbreviation: compassInfo.abbreviation,\n drawSize,\n slots,\n matchUps,\n totalRounds: drawSize > 0 ? Math.log2(drawSize) : 0,\n });\n }\n\n // Main structure is \"East\"\n const mainStructure = structures.find((s) => s.abbreviation === 'E');\n\n return {\n drawName: drawDefinition.drawName || '',\n structures,\n mainStructure,\n };\n}\n","import jsPDF from 'jspdf';\nimport { setFont, SIZE, STYLE } from './fonts';\n\nexport interface TournamentHeader {\n tournamentName: string;\n startDate?: string;\n endDate?: string;\n location?: string;\n organizer?: string;\n subtitle?: string;\n}\n\nexport function drawTournamentHeader(doc: jsPDF, header: TournamentHeader, startY: number = 15): number {\n const pageWidth = doc.internal.pageSize.getWidth();\n const margin = 15;\n let y = startY;\n\n // Tournament name\n setFont(doc, SIZE.TITLE, STYLE.BOLD);\n doc.text(header.tournamentName, margin, y);\n y += 7;\n\n // Subtitle (e.g., \"Boys Singles - Main Draw\")\n if (header.subtitle) {\n setFont(doc, SIZE.SUBTITLE, STYLE.BOLD);\n doc.text(header.subtitle, margin, y);\n y += 6;\n }\n\n // Date and location on the right\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n const infoLines: string[] = [];\n\n if (header.startDate) {\n const dateStr = header.endDate ? `${header.startDate} - ${header.endDate}` : header.startDate;\n infoLines.push(dateStr);\n }\n if (header.location) infoLines.push(header.location);\n if (header.organizer) infoLines.push(header.organizer);\n\n infoLines.forEach((line, i) => {\n doc.text(line, pageWidth - margin, startY + i * 4, { align: 'right' });\n });\n\n // Separator line\n y += 2;\n doc.setDrawColor(0);\n doc.setLineWidth(0.5);\n doc.line(margin, y, pageWidth - margin, y);\n y += 5;\n\n return y;\n}\n\nexport function drawPageFooter(doc: jsPDF, text: string, pageNumber?: number) {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const margin = 15;\n\n setFont(doc, SIZE.SMALL, STYLE.ITALIC);\n doc.setTextColor(120);\n doc.text(text, margin, pageHeight - 10);\n\n if (pageNumber !== undefined) {\n doc.text(`Page ${pageNumber}`, pageWidth - margin, pageHeight - 10, { align: 'right' });\n }\n\n doc.setTextColor(0);\n}\n","import type { UserOptions } from 'jspdf-autotable';\n\nexport const TABLE_STYLES: Record<string, Partial<UserOptions>> = {\n compact: {\n styles: {\n fontSize: 7,\n cellPadding: 1.5,\n lineWidth: 0.1,\n lineColor: [200, 200, 200],\n },\n headStyles: {\n fillColor: [50, 50, 50],\n textColor: [255, 255, 255],\n fontStyle: 'bold',\n fontSize: 7,\n },\n alternateRowStyles: {\n fillColor: [245, 245, 245],\n },\n },\n schedule: {\n styles: {\n fontSize: 7,\n cellPadding: 2,\n lineWidth: 0.2,\n lineColor: [180, 180, 180],\n valign: 'top',\n },\n headStyles: {\n fillColor: [30, 60, 120],\n textColor: [255, 255, 255],\n fontStyle: 'bold',\n fontSize: 8,\n halign: 'center',\n },\n alternateRowStyles: {\n fillColor: [240, 244, 250],\n },\n },\n playerList: {\n styles: {\n fontSize: 8,\n cellPadding: 2,\n lineWidth: 0.1,\n lineColor: [200, 200, 200],\n },\n headStyles: {\n fillColor: [40, 80, 40],\n textColor: [255, 255, 255],\n fontStyle: 'bold',\n fontSize: 8,\n },\n alternateRowStyles: {\n fillColor: [242, 248, 242],\n },\n },\n report: {\n styles: {\n fontSize: 8,\n cellPadding: 2,\n lineWidth: 0.1,\n lineColor: [200, 200, 200],\n },\n headStyles: {\n fillColor: [35, 55, 90],\n textColor: [255, 255, 255],\n fontStyle: 'bold',\n fontSize: 8,\n },\n alternateRowStyles: {\n fillColor: [244, 246, 250],\n },\n },\n courtCard: {\n styles: {\n fontSize: 14,\n cellPadding: 6,\n lineWidth: 0.3,\n lineColor: [100, 100, 100],\n halign: 'center',\n },\n headStyles: {\n fillColor: [20, 20, 80],\n textColor: [255, 255, 255],\n fontStyle: 'bold',\n fontSize: 16,\n },\n },\n};\n","import jsPDF from 'jspdf';\nimport { setFont, SIZE, STYLE } from './fonts';\n\nexport interface BracketPosition {\n x: number;\n y: number;\n width: number;\n height: number;\n participantName?: string;\n seed?: number;\n nationality?: string;\n score?: string;\n isBye?: boolean;\n}\n\nexport interface BracketConfig {\n slotWidth: number;\n slotHeight: number;\n roundGap: number;\n verticalGap: number;\n startX: number;\n startY: number;\n}\n\nexport const DEFAULT_BRACKET_CONFIG: BracketConfig = {\n slotWidth: 90,\n slotHeight: 14,\n roundGap: 20,\n verticalGap: 4,\n startX: 15,\n startY: 10,\n};\n\nexport function calculateBracketPositions(\n drawSize: number,\n config: BracketConfig = DEFAULT_BRACKET_CONFIG,\n availableHeight?: number,\n) {\n const rounds = Math.log2(drawSize);\n const positions: BracketPosition[][] = [];\n\n // Calculate spacing to fit all first-round slots within available height\n const firstRoundSlots = drawSize;\n let spacing = config.slotHeight + config.verticalGap;\n\n if (availableHeight) {\n const neededHeight = firstRoundSlots * spacing;\n if (neededHeight > availableHeight) {\n spacing = availableHeight / firstRoundSlots;\n }\n }\n\n const slotHeight = Math.max(spacing * 0.7, 5);\n\n for (let round = 0; round < rounds; round++) {\n const matchesInRound = drawSize / Math.pow(2, round + 1);\n const roundPositions: BracketPosition[] = [];\n\n for (let match = 0; match < matchesInRound; match++) {\n const roundOffset = Math.pow(2, round) * spacing;\n const baseY = config.startY + roundOffset / 2 - spacing / 2;\n\n const topY = baseY + match * roundOffset * 2;\n const bottomY = topY + roundOffset;\n\n const x = config.startX + round * (config.slotWidth + config.roundGap);\n\n roundPositions.push(\n { x, y: topY, width: config.slotWidth, height: slotHeight },\n { x, y: bottomY, width: config.slotWidth, height: slotHeight },\n );\n }\n\n positions.push(roundPositions);\n }\n\n return positions;\n}\n\nexport function drawBracketSlot(doc: jsPDF, pos: BracketPosition) {\n // Draw slot box\n doc.setDrawColor(150);\n doc.setLineWidth(0.3);\n doc.rect(pos.x, pos.y, pos.width, pos.height);\n\n if (pos.isBye) {\n setFont(doc, SIZE.SMALL, STYLE.ITALIC);\n doc.setTextColor(150);\n doc.text('Bye', pos.x + 2, pos.y + pos.height / 2 + 1.5);\n doc.setTextColor(0);\n return;\n }\n\n if (pos.participantName) {\n // Seed number\n if (pos.seed) {\n setFont(doc, SIZE.TINY, STYLE.BOLD);\n doc.text(`[${pos.seed}]`, pos.x + 1, pos.y + pos.height / 2 + 1);\n setFont(doc, SIZE.SMALL, STYLE.NORMAL);\n doc.text(pos.participantName, pos.x + 9, pos.y + pos.height / 2 + 1);\n } else {\n setFont(doc, SIZE.SMALL, STYLE.NORMAL);\n doc.text(pos.participantName, pos.x + 2, pos.y + pos.height / 2 + 1);\n }\n\n // Nationality on right\n if (pos.nationality) {\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.setTextColor(100);\n doc.text(pos.nationality, pos.x + pos.width - 2, pos.y + pos.height / 2 + 1, { align: 'right' });\n doc.setTextColor(0);\n }\n }\n}\n\nexport function drawBracketConnectors(doc: jsPDF, positions: BracketPosition[][], config: BracketConfig) {\n doc.setDrawColor(100);\n doc.setLineWidth(0.3);\n\n for (let round = 0; round < positions.length - 1; round++) {\n const currentRound = positions[round];\n const nextRound = positions[round + 1];\n\n for (let i = 0; i < currentRound.length; i += 2) {\n const top = currentRound[i];\n const bottom = currentRound[i + 1];\n const nextSlot = nextRound[Math.floor(i / 2)];\n\n if (!top || !bottom || !nextSlot) continue;\n\n const rightX = top.x + top.width;\n const midX = rightX + config.roundGap / 2;\n const topMidY = top.y + top.height / 2;\n const bottomMidY = bottom.y + bottom.height / 2;\n const nextMidY = nextSlot.y + nextSlot.height / 2;\n\n // Horizontal from top slot\n doc.line(rightX, topMidY, midX, topMidY);\n // Horizontal from bottom slot\n doc.line(rightX, bottomMidY, midX, bottomMidY);\n // Vertical connector\n doc.line(midX, topMidY, midX, bottomMidY);\n // Horizontal to next round\n doc.line(midX, nextMidY, nextSlot.x, nextMidY);\n }\n }\n}\n\nexport function drawScore(doc: jsPDF, score: string, x: number, y: number) {\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.setTextColor(60, 60, 180);\n doc.text(score, x, y);\n doc.setTextColor(0);\n}\n","import jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport { drawTournamentHeader, drawPageFooter, type TournamentHeader } from '../layout/headers';\nimport { TABLE_STYLES } from '../layout/tables';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\nimport {\n calculateBracketPositions,\n drawBracketSlot,\n drawBracketConnectors,\n drawScore,\n type BracketConfig,\n DEFAULT_BRACKET_CONFIG,\n} from '../layout/brackets';\nimport { getRoundLabel, type DrawData } from '../core/extractDrawData';\n\nexport interface DrawSheetOptions {\n header?: TournamentHeader;\n includeSeedings?: boolean;\n includeScores?: boolean;\n}\n\nexport function generateDrawSheetPDF(drawData: DrawData, options: DrawSheetOptions = {}): jsPDF {\n const { header, includeSeedings = true, includeScores = true } = options;\n\n // Landscape for 32+ draws to fit bracket width\n const landscape = drawData.drawSize >= 32;\n const doc = new jsPDF({ orientation: landscape ? 'landscape' : 'portrait', format: 'a4' });\n\n let startY = 15;\n if (header) {\n const subtitle = `${drawData.drawName} - ${drawData.drawType.replace(/_/g, ' ')} (${drawData.drawSize})`;\n startY = drawTournamentHeader(doc, { ...header, subtitle });\n }\n\n // For small draws (<=16), draw the bracket directly\n if (drawData.drawSize <= 64 && drawData.drawSize > 0) {\n startY = drawBracket(doc, drawData, startY, includeScores);\n } else {\n // For very large draws, fall back to tabular format\n startY = drawTabularDraw(doc, drawData, startY);\n }\n\n // Seeded players table\n if (includeSeedings && drawData.seedAssignments.length > 0) {\n drawSeedingsTable(doc, drawData, startY + 8);\n }\n\n drawPageFooter(doc, `Generated ${new Date().toLocaleDateString()}`);\n\n return doc;\n}\n\nfunction drawBracket(doc: jsPDF, drawData: DrawData, startY: number, includeScores: boolean): number {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n\n // Calculate config based on draw size and available space\n const availableWidth = pageWidth - 30;\n const availableHeight = pageHeight - startY - 30;\n const totalRounds = drawData.totalRounds;\n\n const slotWidth = Math.min(90, (availableWidth - totalRounds * 10) / totalRounds);\n const slotHeight = Math.min(14, availableHeight / drawData.drawSize);\n\n const config: BracketConfig = {\n ...DEFAULT_BRACKET_CONFIG,\n slotWidth,\n slotHeight,\n verticalGap: Math.max(1, slotHeight * 0.3),\n startX: 15,\n startY,\n };\n\n const positions = calculateBracketPositions(drawData.drawSize, config, availableHeight);\n\n // Fill positions with participant data\n const slotMap = new Map(drawData.slots.map((s) => [s.drawPosition, s]));\n\n // Round headers\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n for (let round = 0; round < totalRounds; round++) {\n const x = config.startX + round * (config.slotWidth + config.roundGap);\n const label = getRoundLabel(round + 1, totalRounds);\n doc.text(label, x + config.slotWidth / 2, startY - 2, { align: 'center' });\n }\n\n // Draw first round slots with participant names\n if (positions.length > 0) {\n const firstRound = positions[0];\n for (let i = 0; i < firstRound.length; i++) {\n const drawPosition = i + 1;\n const slot = slotMap.get(drawPosition);\n if (slot) {\n firstRound[i].participantName = slot.participantName;\n firstRound[i].nationality = slot.nationality;\n firstRound[i].seed = slot.seedValue;\n firstRound[i].isBye = slot.isBye;\n }\n }\n\n // Draw slots for each round\n for (const round of positions) {\n for (const pos of round) {\n drawBracketSlot(doc, pos);\n }\n }\n\n // Draw connector lines\n drawBracketConnectors(doc, positions, config);\n\n // Draw scores on connectors\n if (includeScores) {\n for (const mu of drawData.matchUps) {\n if (!mu.score) continue;\n const roundIdx = mu.roundNumber - 1;\n if (roundIdx < positions.length) {\n const matchIdx = (mu.roundPosition - 1) * 2;\n const pos = positions[roundIdx]?.[matchIdx];\n if (pos) {\n drawScore(doc, mu.score, pos.x + pos.width + 2, pos.y + pos.height + 3);\n }\n }\n }\n }\n\n // Return bottom of bracket\n const lastRoundBottom = positions[0][positions[0].length - 1];\n return lastRoundBottom.y + lastRoundBottom.height + 5;\n }\n\n return startY;\n}\n\nfunction drawTabularDraw(doc: jsPDF, drawData: DrawData, startY: number): number {\n const columns = [\n { header: 'Pos', dataKey: 'pos' },\n { header: 'Seed', dataKey: 'seed' },\n { header: 'Player', dataKey: 'name' },\n { header: 'Nat.', dataKey: 'nat' },\n { header: 'Entry', dataKey: 'entry' },\n ];\n\n const body = drawData.slots.map((s) => ({\n pos: s.drawPosition,\n seed: s.seedValue?.toString() || '',\n name: s.isBye ? 'Bye' : s.participantName,\n nat: s.nationality,\n entry: s.entryStatus || '',\n }));\n\n autoTable(doc, {\n ...TABLE_STYLES.compact,\n startY,\n columns,\n body,\n columnStyles: {\n pos: { cellWidth: 12, halign: 'center' },\n seed: { cellWidth: 12, halign: 'center' },\n name: { cellWidth: 'auto' },\n nat: { cellWidth: 15, halign: 'center' },\n entry: { cellWidth: 15, halign: 'center' },\n },\n });\n\n return (doc as any).lastAutoTable?.finalY || startY + 20;\n}\n\nfunction drawSeedingsTable(doc: jsPDF, drawData: DrawData, startY: number): number {\n setFont(doc, SIZE.HEADING, STYLE.BOLD);\n doc.text('Seeded Players', 15, startY);\n startY += 4;\n\n const columns = [\n { header: 'Seed', dataKey: 'seed' },\n { header: 'Player', dataKey: 'name' },\n { header: 'Nat.', dataKey: 'nat' },\n ];\n\n const body = drawData.seedAssignments.map((s) => ({\n seed: s.seedValue,\n name: s.participantName,\n nat: s.nationality,\n }));\n\n autoTable(doc, {\n ...TABLE_STYLES.compact,\n startY,\n columns,\n body,\n tableWidth: 120,\n columnStyles: {\n seed: { cellWidth: 15, halign: 'center', fontStyle: 'bold' },\n name: { cellWidth: 'auto' },\n nat: { cellWidth: 20, halign: 'center' },\n },\n });\n\n return (doc as any).lastAutoTable?.finalY || startY + 20;\n}\n","import jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport { drawTournamentHeader, drawPageFooter, type TournamentHeader } from '../layout/headers';\nimport { TABLE_STYLES } from '../layout/tables';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\nimport type { ScheduleData } from '../core/extractScheduleData';\n\nexport interface ScheduleOptions {\n header?: TournamentHeader;\n landscape?: boolean | 'auto';\n fullCourtNames?: boolean;\n notes?: string[];\n}\n\nexport function generateSchedulePDF(scheduleData: ScheduleData, options: ScheduleOptions = {}): jsPDF {\n const { header, fullCourtNames = true, notes } = options;\n\n const autoLandscape = options.landscape === 'auto' ? scheduleData.courts.length >= 5 : options.landscape;\n const orientation = autoLandscape ? 'landscape' : 'portrait';\n\n const doc = new jsPDF({ orientation, format: 'a4' });\n let startY = 15;\n\n if (header) {\n const subtitle = scheduleData.scheduledDate ? `Order of Play - ${scheduleData.scheduledDate}` : 'Order of Play';\n startY = drawTournamentHeader(doc, { ...header, subtitle });\n }\n\n const courts = scheduleData.courts;\n const courtHeaders = fullCourtNames ? courts : courts.map(abbrevCourt);\n\n for (const timeSlot of scheduleData.timeSlots) {\n // Time slot label\n setFont(doc, SIZE.BODY, STYLE.BOLD);\n doc.setTextColor(30, 60, 120);\n doc.text(timeSlot.label, 15, startY);\n doc.setTextColor(0);\n startY += 4;\n\n // Build table: one column per court\n const columns = courtHeaders.map((name) => ({ header: name, dataKey: name }));\n\n // Group matches by court for this time slot\n const courtMatches = new Map<string, string[]>();\n courts.forEach((c) => courtMatches.set(c, []));\n\n for (const match of timeSlot.matches) {\n const content = formatMatchCell(match);\n const existing = courtMatches.get(match.courtName) || [];\n existing.push(content);\n courtMatches.set(match.courtName, existing);\n }\n\n // Find max rows needed\n const maxRows = Math.max(1, ...Array.from(courtMatches.values()).map((v) => v.length));\n\n const body: Record<string, string>[] = [];\n for (let row = 0; row < maxRows; row++) {\n const rowData: Record<string, string> = {};\n courts.forEach((court, i) => {\n const matches = courtMatches.get(court) || [];\n const key = fullCourtNames ? court : courtHeaders[i];\n rowData[key] = matches[row] || '';\n });\n body.push(rowData);\n }\n\n autoTable(doc, {\n ...TABLE_STYLES.schedule,\n startY,\n columns,\n body,\n tableWidth: 'auto',\n didDrawPage: (data) => {\n drawPageFooter(doc, header?.tournamentName || '', data.pageNumber);\n },\n });\n\n startY = (doc as any).lastAutoTable?.finalY + 6 || startY + 20;\n }\n\n // Notes section\n if (notes?.length) {\n startY += 4;\n setFont(doc, SIZE.SMALL, STYLE.ITALIC);\n doc.setTextColor(80);\n for (const note of notes) {\n doc.text(note, 15, startY);\n startY += 4;\n }\n doc.setTextColor(0);\n }\n\n return doc;\n}\n\nfunction formatMatchCell(match: any): string {\n const lines: string[] = [];\n lines.push(`${match.eventAbbr} ${match.roundName}`);\n lines.push(`${match.side1.name} (${match.side1.nationality})`);\n lines.push(`vs ${match.side2.name} (${match.side2.nationality})`);\n if (match.score) lines.push(match.score);\n return lines.join('\\n');\n}\n\nfunction abbrevCourt(name: string): string {\n return name.replace(/^Court\\s*/i, 'Ct ');\n}\n","import jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport { drawTournamentHeader, drawPageFooter, type TournamentHeader } from '../layout/headers';\nimport { TABLE_STYLES } from '../layout/tables';\nimport type { ParticipantRow } from '../core/extractParticipantData';\n\nexport interface PlayerListOptions {\n header?: TournamentHeader;\n includeRanking?: boolean;\n includeEvents?: boolean;\n groupByEvent?: boolean;\n}\n\nexport function generatePlayerListPDF(players: ParticipantRow[], options: PlayerListOptions = {}): jsPDF {\n const { header, includeRanking = true, includeEvents = true } = options;\n\n const doc = new jsPDF({ orientation: 'portrait', format: 'a4' });\n let startY = 15;\n\n if (header) {\n startY = drawTournamentHeader(doc, { ...header, subtitle: header.subtitle || 'Player List' });\n }\n\n const columns: any[] = [\n { header: '#', dataKey: 'index' },\n { header: 'Name', dataKey: 'name' },\n { header: 'Nat.', dataKey: 'nationality' },\n ];\n\n if (includeRanking) columns.push({ header: 'Rank', dataKey: 'ranking' });\n columns.push({ header: 'Seed', dataKey: 'seed' });\n columns.push({ header: 'Entry', dataKey: 'entryStatus' });\n if (includeEvents) columns.push({ header: 'Events', dataKey: 'events' });\n\n const body = players.map((p, i) => ({\n index: i + 1,\n name: p.name,\n nationality: p.nationality,\n ranking: p.ranking || '',\n seed: p.seedValue?.toString() || '',\n entryStatus: p.entryStatus,\n events: p.events.join(', '),\n }));\n\n autoTable(doc, {\n ...TABLE_STYLES.playerList,\n startY,\n columns,\n body,\n columnStyles: {\n index: { cellWidth: 10, halign: 'center' },\n name: { cellWidth: 'auto', fontStyle: 'bold' },\n nationality: { cellWidth: 15, halign: 'center' },\n ranking: { cellWidth: 15, halign: 'center' },\n seed: { cellWidth: 12, halign: 'center' },\n entryStatus: { cellWidth: 15, halign: 'center' },\n events: { cellWidth: 'auto' },\n },\n didDrawPage: (data) => {\n drawPageFooter(doc, `Generated ${new Date().toLocaleDateString()}`, data.pageNumber);\n },\n });\n\n return doc;\n}\n","import jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\nimport type { CourtCardData } from '../core/extractCourtCardData';\n\nexport interface CourtCardOptions {\n tournamentName?: string;\n pageSize?: 'a4' | 'a5' | 'letter';\n cardsPerPage?: number;\n}\n\nexport function generateCourtCardPDF(cards: CourtCardData[], options: CourtCardOptions = {}): jsPDF {\n const { tournamentName = '', pageSize = 'a5', cardsPerPage = 1 } = options;\n const doc = new jsPDF({ orientation: 'landscape', format: pageSize });\n\n cards.forEach((card, index) => {\n if (index > 0) doc.addPage();\n drawCourtCard(doc, card, tournamentName, cardsPerPage);\n });\n\n return doc;\n}\n\nfunction drawCourtCard(doc: jsPDF, card: CourtCardData, tournamentName: string, _cardsPerPage: number) {\n const pageWidth = doc.internal.pageSize.getWidth();\n const centerX = pageWidth / 2;\n let y = 15;\n\n // Tournament name (small, top)\n if (tournamentName) {\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n doc.setTextColor(100);\n doc.text(tournamentName, centerX, y, { align: 'center' });\n doc.setTextColor(0);\n y += 8;\n }\n\n // Court name (large, prominent)\n setFont(doc, 28, STYLE.BOLD);\n doc.text(card.courtName, centerX, y, { align: 'center' });\n y += 5;\n\n if (card.venueName) {\n setFont(doc, SIZE.HEADING, STYLE.NORMAL);\n doc.setTextColor(100);\n doc.text(card.venueName, centerX, y, { align: 'center' });\n doc.setTextColor(0);\n }\n y += 8;\n\n // Separator\n doc.setDrawColor(0);\n doc.setLineWidth(1);\n doc.line(30, y, pageWidth - 30, y);\n y += 8;\n\n // Current match\n if (card.currentMatch) {\n setFont(doc, SIZE.HEADING, STYLE.BOLD);\n doc.setTextColor(30, 60, 120);\n doc.text('NOW PLAYING', centerX, y, { align: 'center' });\n doc.setTextColor(0);\n y += 6;\n\n setFont(doc, SIZE.BODY, STYLE.ITALIC);\n doc.text(`${card.currentMatch.eventName} - ${card.currentMatch.roundName}`, centerX, y, { align: 'center' });\n y += 8;\n\n // Player names - large\n autoTable(doc, {\n startY: y,\n margin: { left: 25, right: 25 },\n theme: 'plain',\n styles: { halign: 'center', fontSize: 16, cellPadding: 4 },\n body: [\n [\n {\n content: `${card.currentMatch.side1.name} (${card.currentMatch.side1.nationality})`,\n styles: { fontStyle: 'bold' },\n },\n ],\n [{ content: 'vs.', styles: { fontSize: 12, textColor: [120, 120, 120] } }],\n [\n {\n content: `${card.currentMatch.side2.name} (${card.currentMatch.side2.nationality})`,\n styles: { fontStyle: 'bold' },\n },\n ],\n ],\n });\n\n y = (doc as any).lastAutoTable?.finalY || y + 40;\n y += 8;\n }\n\n // Next match\n if (card.nextMatch) {\n doc.setDrawColor(180);\n doc.setLineWidth(0.3);\n doc.line(50, y, pageWidth - 50, y);\n y += 6;\n\n setFont(doc, SIZE.BODY, STYLE.BOLD);\n doc.setTextColor(100);\n const upNextLabel = card.nextMatch.scheduledTime ? `UP NEXT (${card.nextMatch.scheduledTime})` : 'UP NEXT';\n doc.text(upNextLabel, centerX, y, { align: 'center' });\n doc.setTextColor(0);\n y += 5;\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n doc.text(`${card.nextMatch.eventName} - ${card.nextMatch.roundName}`, centerX, y, { align: 'center' });\n y += 5;\n\n setFont(doc, SIZE.HEADING, STYLE.NORMAL);\n doc.text(`${card.nextMatch.side1.name} vs. ${card.nextMatch.side2.name}`, centerX, y, { align: 'center' });\n }\n}\n","import jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport { drawTournamentHeader, type TournamentHeader } from '../layout/headers';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\nimport type { ParticipantRow } from '../core/extractParticipantData';\n\nexport interface SignInSheetOptions {\n header?: TournamentHeader;\n eventName?: string;\n signInDate?: string;\n signInTime?: string;\n}\n\nexport function generateSignInSheetPDF(players: ParticipantRow[], options: SignInSheetOptions = {}): jsPDF {\n const { header, eventName, signInDate, signInTime } = options;\n const doc = new jsPDF({ orientation: 'portrait', format: 'a4' });\n let startY = 15;\n\n if (header) {\n startY = drawTournamentHeader(doc, { ...header, subtitle: header.subtitle || 'Player Sign-In Sheet' });\n }\n\n // Event/date info\n if (eventName || signInDate) {\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n const infoLine: string[] = [];\n if (eventName) infoLine.push(`Event: ${eventName}`);\n if (signInDate) infoLine.push(`Date: ${signInDate}`);\n if (signInTime) infoLine.push(`Time: ${signInTime}`);\n doc.text(infoLine.join(' | '), 15, startY);\n startY += 6;\n }\n\n const columns = [\n { header: '#', dataKey: 'index' },\n { header: 'Player Name', dataKey: 'name' },\n { header: 'Nat.', dataKey: 'nationality' },\n { header: 'Rank', dataKey: 'ranking' },\n { header: 'Seed', dataKey: 'seed' },\n { header: 'Entry', dataKey: 'entry' },\n { header: 'Signature', dataKey: 'signature' },\n { header: 'Time', dataKey: 'time' },\n ];\n\n const body = players.map((p, i) => ({\n index: i + 1,\n name: p.name,\n nationality: p.nationality,\n ranking: p.ranking || '',\n seed: p.seedValue?.toString() || '',\n entry: p.entryStatus,\n signature: '',\n time: '',\n }));\n\n autoTable(doc, {\n startY,\n columns,\n body,\n styles: {\n fontSize: 8,\n cellPadding: 1.5,\n lineWidth: 0.2,\n lineColor: [150, 150, 150],\n },\n headStyles: {\n fillColor: [40, 60, 100],\n textColor: [255, 255, 255],\n fontStyle: 'bold',\n fontSize: 7,\n cellPadding: 2,\n },\n alternateRowStyles: {\n fillColor: [245, 247, 250],\n },\n columnStyles: {\n index: { cellWidth: 10, halign: 'center' },\n name: { cellWidth: 'auto', fontStyle: 'bold' },\n nationality: { cellWidth: 14, halign: 'center' },\n ranking: { cellWidth: 14, halign: 'center' },\n seed: { cellWidth: 14, halign: 'center' },\n entry: { cellWidth: 14, halign: 'center' },\n signature: { cellWidth: 35 },\n time: { cellWidth: 15 },\n },\n });\n\n return doc;\n}\n","/**\n * Professional Order of Play / Schedule PDF generator.\n *\n * Modeled after the ITF J300 reference OOP:\n * - Courts as columns, time slots as numbered rows\n * - 3-zone cell: event/round header, player names with nationalities, score footer\n * - \"Not Before\" and \"Starting at\" time labels\n * - Landscape for 5+ courts, portrait for fewer\n * - Professional header with tournament info and \"ORDER OF PLAY\" title\n * - Footer with notes, officials, timestamp\n */\n\nimport jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport type { ScheduleData, ScheduleMatch } from '../core/extractScheduleData';\nimport type { HeaderConfig, FooterConfig, PageConfig } from '../config/types';\nimport { renderHeader } from '../composition/headerLayouts';\nimport { renderFooter, measureFooterHeight } from '../composition/footerLayouts';\nimport { createDoc } from '../composition/page';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport interface ScheduleV2Options {\n header?: HeaderConfig;\n footer?: FooterConfig;\n page?: Partial<PageConfig>;\n alertBanner?: string;\n notes?: string[];\n officials?: { role: string; name: string }[];\n showMatchNumbers?: boolean;\n cellStyle?: 'detailed' | 'compact';\n}\n\nexport function generateScheduleV2PDF(scheduleData: ScheduleData, options: ScheduleV2Options = {}): jsPDF {\n const courts = scheduleData.courts;\n const autoLandscape = courts.length >= 4;\n const pageConfig: PageConfig = {\n pageSize: options.page?.pageSize || 'a4',\n orientation: options.page?.orientation || (autoLandscape ? 'landscape' : 'portrait'),\n margins: options.page?.margins || { top: 12, right: 8, bottom: 10, left: 8 },\n };\n\n const doc = createDoc(pageConfig);\n const footerConfig: FooterConfig = options.footer || {\n layout: 'standard',\n showTimestamp: true,\n showPageNumbers: true,\n };\n const footerH = measureFooterHeight(footerConfig) + (options.notes?.length ? options.notes.length * 3 : 0);\n\n let startY = pageConfig.margins.top;\n\n // Header\n if (options.header) {\n const headerH = renderHeader(doc, options.header, pageConfig);\n startY = pageConfig.margins.top + headerH;\n }\n\n // Alert banner (red background, white text)\n if (options.alertBanner) {\n startY = renderAlertBanner(doc, options.alertBanner, pageConfig, startY);\n }\n\n // Build the schedule table\n const tableStartY = startY;\n renderScheduleTable(doc, scheduleData, pageConfig, tableStartY, options);\n\n // Notes section above footer\n const pageHeight = doc.internal.pageSize.getHeight();\n if (options.notes?.length) {\n let notesY = pageHeight - pageConfig.margins.bottom - footerH + 2;\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(80);\n for (const note of options.notes) {\n doc.text(note, pageConfig.margins.left, notesY);\n notesY += 3;\n }\n doc.setTextColor(0);\n }\n\n // Officials row\n if (options.officials?.length) {\n const officialsY = pageHeight - pageConfig.margins.bottom - 6;\n renderOfficialsRow(doc, options.officials, pageConfig, officialsY);\n }\n\n // Footer\n renderFooter(doc, footerConfig, pageConfig, 1);\n\n return doc;\n}\n\nfunction renderAlertBanner(doc: jsPDF, text: string, pageConfig: PageConfig, y: number): number {\n const { margins } = pageConfig;\n const pageWidth = doc.internal.pageSize.getWidth();\n const bannerWidth = pageWidth - margins.left - margins.right;\n\n doc.setFillColor(200, 30, 30);\n doc.rect(margins.left, y, bannerWidth, 7, 'F');\n\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.setTextColor(255, 255, 255);\n doc.text(text, pageWidth / 2, y + 4.5, { align: 'center' });\n doc.setTextColor(0);\n\n return y + 9;\n}\n\nfunction renderScheduleTable(\n doc: jsPDF,\n scheduleData: ScheduleData,\n pageConfig: PageConfig,\n startY: number,\n options: ScheduleV2Options,\n): void {\n const { margins } = pageConfig;\n const courts = scheduleData.courts;\n const isCompact = options.cellStyle === 'compact';\n\n // Build column definitions: slot # + one column per court\n const columns: any[] = [{ header: '', dataKey: 'slot' }];\n for (const court of courts) {\n columns.push({ header: court, dataKey: court });\n }\n\n // Build rows: one per time slot\n const body: any[][] = [];\n\n scheduleData.timeSlots.forEach((slot, slotIdx) => {\n const row: any[] = [];\n\n // Slot number + time label\n const timeLabel = buildTimeLabel(slot, slotIdx);\n row.push({ content: timeLabel, styles: { fontStyle: 'bold', valign: 'top', cellWidth: 12 } });\n\n // One cell per court\n for (const court of courts) {\n const courtMatches = slot.matches.filter((m) => m.courtName === court);\n const cellContent =\n courtMatches.length > 0 ? courtMatches.map((m) => formatCellContent(m, isCompact)).join('\\n---\\n') : '';\n row.push(cellContent);\n }\n\n body.push(row);\n });\n\n autoTable(doc, {\n startY,\n head: [columns.map((c) => c.header)],\n body,\n styles: {\n fontSize: isCompact ? 6 : 6.5,\n cellPadding: isCompact ? 1.5 : 2,\n lineWidth: 0.3,\n lineColor: [80, 80, 80],\n valign: 'top',\n overflow: 'linebreak',\n },\n headStyles: {\n fillColor: [255, 255, 255],\n textColor: [0, 0, 0],\n fontStyle: 'bold',\n fontSize: 7,\n halign: 'center',\n lineWidth: 0.5,\n lineColor: [0, 0, 0],\n },\n columnStyles: {\n 0: { cellWidth: 14, fontStyle: 'bold' },\n },\n alternateRowStyles: {\n fillColor: [252, 252, 252],\n },\n margin: { left: margins.left, right: margins.right },\n tableWidth: 'auto',\n didParseCell: (data) => {\n if (data.column.index > 0 && data.section === 'body') {\n // Court columns: equal width, centered text\n const availableWidth = doc.internal.pageSize.getWidth() - margins.left - margins.right - 14;\n data.cell.styles.cellWidth = availableWidth / courts.length;\n data.cell.styles.halign = 'center';\n data.cell.styles.valign = 'middle';\n }\n },\n });\n}\n\nfunction buildTimeLabel(_slot: any, slotIdx: number): string {\n return `${slotIdx + 1}`;\n}\n\nfunction formatCellContent(match: ScheduleMatch, isCompact: boolean): string {\n const lines: string[] = [];\n\n // Scheduling info (per-match time details)\n if (match.notBeforeTime) {\n lines.push(`NB ${match.notBeforeTime}`);\n } else if (match.scheduledTime) {\n lines.push(match.scheduledTime);\n }\n\n // Event + Round (header zone)\n if (match.eventAbbr || match.roundName) {\n lines.push(`${match.eventAbbr} ${match.roundName}`.trim());\n }\n\n // Player 1\n const p1 = formatPlayer(match.side1, isCompact);\n if (p1) lines.push(p1);\n\n // \"vs.\" divider\n lines.push('vs.');\n\n // Player 2\n const p2 = formatPlayer(match.side2, isCompact);\n if (p2) lines.push(p2);\n\n // Score or status (footer zone)\n if (match.score) {\n lines.push(match.score);\n } else if (match.matchUpStatus === 'IN_PROGRESS') {\n lines.push('In progress');\n }\n\n return lines.join('\\n');\n}\n\nfunction formatPlayer(side: { name: string; nationality: string }, isCompact: boolean): string {\n if (!side.name) return 'TBD';\n if (isCompact) return `${side.name} (${side.nationality})`;\n return side.nationality ? `${side.name} (${side.nationality})` : side.name;\n}\n\nfunction renderOfficialsRow(\n doc: jsPDF,\n officials: { role: string; name: string }[],\n pageConfig: PageConfig,\n y: number,\n): void {\n const { margins } = pageConfig;\n const pageWidth = doc.internal.pageSize.getWidth();\n\n doc.setDrawColor(120);\n doc.setLineWidth(0.2);\n doc.line(margins.left, y - 2, pageWidth - margins.right, y - 2);\n\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n const spacing = (pageWidth - margins.left - margins.right) / officials.length;\n\n officials.forEach((official, i) => {\n const x = margins.left + i * spacing;\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(100);\n doc.text(official.role, x, y);\n setFont(doc, SIZE.TINY, STYLE.BOLD);\n doc.setTextColor(0);\n doc.text(official.name, x, y + 3);\n });\n}\n","/**\n * Sequential Order of Play renderer (WTA/ATP/Grand Slam style).\n *\n * Portrait A4, courts stacked vertically with match boxes in sequence.\n * This is the format used by WTA, ATP, and Grand Slam tournaments.\n *\n * Layout per court:\n * COURT NAME (centered, bold, uppercase)\n * [Starting at X:XX PM] (colored bar)\n * ┌─────────────────────┐\n * │ [1] Player One NAT │ Round label\n * │ vs │\n * │ [3] Player Two NAT │\n * └─────────────────────┘\n * [Not before X:XX PM] (colored bar)\n * ┌─────────────────────┐\n * │ Match 2... │\n * └─────────────────────┘\n */\n\nimport jsPDF from 'jspdf';\nimport type { ScheduleData, ScheduleMatch } from '../core/extractScheduleData';\nimport type { HeaderConfig, FooterConfig, PageConfig } from '../config/types';\nimport { renderHeader } from '../composition/headerLayouts';\nimport { renderFooter, measureFooterHeight } from '../composition/footerLayouts';\nimport { createDoc } from '../composition/page';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport interface SequentialOOPOptions {\n header?: HeaderConfig;\n footer?: FooterConfig;\n page?: Partial<PageConfig>;\n accentColor?: [number, number, number];\n disclaimer?: string;\n officials?: { role: string; name: string }[];\n}\n\nconst DEFAULT_ACCENT: [number, number, number] = [120, 50, 140]; // WTA purple\n\nexport function generateSequentialOOP(scheduleData: ScheduleData, options: SequentialOOPOptions = {}): jsPDF {\n const pageConfig: PageConfig = {\n pageSize: options.page?.pageSize || 'a4',\n orientation: options.page?.orientation || 'portrait',\n margins: options.page?.margins || { top: 12, right: 15, bottom: 12, left: 15 },\n };\n\n const doc = createDoc(pageConfig);\n const { margins } = pageConfig;\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const contentWidth = pageWidth - margins.left - margins.right;\n const accent = options.accentColor || DEFAULT_ACCENT;\n const footerConfig: FooterConfig = options.footer || { layout: 'none' };\n const footerH = measureFooterHeight(footerConfig);\n\n let y = margins.top;\n\n // Header\n if (options.header) {\n y = margins.top + renderHeader(doc, options.header, pageConfig) + 3;\n }\n\n // Group matches by court, preserving time slot order\n const courtMatches = groupByCourt(scheduleData);\n\n for (const [courtName, matches] of courtMatches) {\n // Check if court section fits (at least court header + 1 match)\n if (y + 30 > pageHeight - margins.bottom - footerH) {\n renderPageFooter(doc, options, pageConfig, footerConfig);\n doc.addPage();\n y = margins.top;\n }\n\n // Court name header\n y = renderCourtHeader(doc, courtName, margins.left, y, contentWidth);\n\n let lastTime = '';\n for (const match of matches) {\n // Time bar if time changed\n const matchTime = match.scheduledTime || match.notBeforeTime || '';\n if (matchTime && matchTime !== lastTime) {\n if (y + 25 > pageHeight - margins.bottom - footerH) {\n renderPageFooter(doc, options, pageConfig, footerConfig);\n doc.addPage();\n y = margins.top;\n }\n const isNotBefore = !!match.notBeforeTime;\n y = renderTimeBar(doc, matchTime, isNotBefore, margins.left, y, contentWidth, accent);\n lastTime = matchTime;\n }\n\n // Match box\n if (y + 22 > pageHeight - margins.bottom - footerH) {\n renderPageFooter(doc, options, pageConfig, footerConfig);\n doc.addPage();\n y = margins.top;\n }\n y = renderMatchBox(doc, match, margins.left, y, contentWidth);\n }\n\n y += 4;\n }\n\n // Disclaimer\n if (options.disclaimer) {\n y += 2;\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(100);\n doc.text(options.disclaimer, pageWidth / 2, y, { align: 'center' });\n doc.setTextColor(0);\n }\n\n renderPageFooter(doc, options, pageConfig, footerConfig);\n\n return doc;\n}\n\nfunction renderCourtHeader(doc: jsPDF, courtName: string, x: number, y: number, width: number): number {\n setFont(doc, SIZE.HEADING, STYLE.BOLD);\n doc.setTextColor(40);\n doc.text(courtName.toUpperCase(), x + width / 2, y, { align: 'center' });\n doc.setTextColor(0);\n return y + 7;\n}\n\nfunction renderTimeBar(\n doc: jsPDF,\n time: string,\n isNotBefore: boolean,\n x: number,\n y: number,\n width: number,\n accent: [number, number, number],\n): number {\n const label = isNotBefore ? `Not before ${time}` : `Starting at ${time}`;\n\n doc.setFillColor(accent[0], accent[1], accent[2]);\n doc.rect(x + 20, y, width - 40, 5, 'F');\n\n setFont(doc, SIZE.SMALL, STYLE.ITALIC);\n doc.setTextColor(255, 255, 255);\n doc.text(label, x + width / 2, y + 3.5, { align: 'center' });\n doc.setTextColor(0);\n\n return y + 7;\n}\n\nfunction renderMatchBox(doc: jsPDF, match: ScheduleMatch, x: number, y: number, width: number): number {\n const boxX = x + 15;\n const boxWidth = width - 30;\n const startY = y;\n\n // Round label (top-right of box)\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(100);\n const roundLabel = match.eventAbbr ? `${match.eventAbbr} ${match.roundName}` : match.roundName;\n doc.text(roundLabel, boxX + boxWidth - 2, y + 3, { align: 'right' });\n doc.setTextColor(0);\n\n // Score above players (if completed)\n if (match.score) {\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.setTextColor(120, 50, 140);\n doc.text(match.score, boxX + boxWidth / 2, y + 3, { align: 'center' });\n doc.setTextColor(0);\n y += 4;\n }\n\n y += 2;\n\n // Player 1\n y = renderPlayer(doc, match.side1, boxX, y, boxWidth);\n\n // \"vs\" divider\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(120);\n doc.text('vs', boxX + boxWidth / 2, y + 2.5, { align: 'center' });\n doc.setTextColor(0);\n y += 4;\n\n // Player 2\n y = renderPlayer(doc, match.side2, boxX, y, boxWidth);\n\n y += 2;\n\n // Box border\n const boxHeight = y - startY;\n doc.setDrawColor(180);\n doc.setLineWidth(0.3);\n doc.rect(boxX, startY, boxWidth, boxHeight);\n\n return y + 2;\n}\n\nfunction renderPlayer(\n doc: jsPDF,\n side: { name: string; nationality: string },\n x: number,\n y: number,\n _width: number,\n): number {\n if (!side.name || side.name === 'TBD') {\n setFont(doc, SIZE.BODY, STYLE.ITALIC);\n doc.setTextColor(150);\n doc.text('TBD', x + 10, y + 3);\n doc.setTextColor(0);\n return y + 4;\n }\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n\n // Format: player name centered with nationality\n const nameWithNat = side.nationality ? `${side.name} ${side.nationality}` : side.name;\n doc.text(nameWithNat, x + 10, y + 3);\n\n return y + 4;\n}\n\nfunction groupByCourt(scheduleData: ScheduleData): Map<string, ScheduleMatch[]> {\n const courtMap = new Map<string, ScheduleMatch[]>();\n\n // Preserve court order from scheduleData.courts\n for (const court of scheduleData.courts) {\n courtMap.set(court, []);\n }\n\n // Fill matches in time slot order\n for (const slot of scheduleData.timeSlots) {\n for (const match of slot.matches) {\n if (!courtMap.has(match.courtName)) courtMap.set(match.courtName, []);\n courtMap.get(match.courtName)!.push(match);\n }\n }\n\n // Remove empty courts\n for (const [court, matches] of courtMap) {\n if (matches.length === 0) courtMap.delete(court);\n }\n\n return courtMap;\n}\n\nfunction renderPageFooter(\n doc: jsPDF,\n options: SequentialOOPOptions,\n pageConfig: PageConfig,\n footerConfig: FooterConfig,\n): void {\n const { margins } = pageConfig;\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n\n if (options.officials?.length) {\n const y = pageHeight - margins.bottom - 10;\n doc.setDrawColor(120);\n doc.setLineWidth(0.2);\n doc.line(margins.left, y - 2, pageWidth - margins.right, y - 2);\n\n const spacing = (pageWidth - margins.left - margins.right) / options.officials.length;\n\n options.officials.forEach((official, i) => {\n const ox = margins.left + i * spacing;\n setFont(doc, SIZE.TINY, STYLE.BOLD);\n doc.text(official.role, ox, y);\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.text(official.name, ox, y + 3);\n });\n }\n\n renderFooter(doc, footerConfig, pageConfig);\n}\n","import jsPDF from 'jspdf';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport interface MatchCardData {\n tournamentName?: string;\n eventName: string;\n roundName: string;\n matchUpId?: string;\n courtName?: string;\n scheduledTime?: string;\n side1: { name: string; nationality: string; seedValue?: number };\n side2: { name: string; nationality: string; seedValue?: number };\n}\n\nexport interface MatchCardOptions {\n cardsPerPage?: number;\n includeScoreBoxes?: boolean;\n}\n\nexport function generateMatchCardPDF(matches: MatchCardData[], options: MatchCardOptions = {}): jsPDF {\n const { cardsPerPage = 2, includeScoreBoxes = true } = options;\n const doc = new jsPDF({ orientation: 'landscape', format: 'a5' });\n\n matches.forEach((match, index) => {\n if (index > 0) {\n if (cardsPerPage === 1 || index % cardsPerPage === 0) {\n doc.addPage();\n }\n }\n\n const offsetY = cardsPerPage === 2 && index % 2 === 1 ? doc.internal.pageSize.getHeight() / 2 : 5;\n renderMatchCard(doc, match, offsetY, includeScoreBoxes);\n });\n\n return doc;\n}\n\nfunction renderMatchCard(doc: jsPDF, match: MatchCardData, startY: number, includeScoreBoxes: boolean) {\n const pageWidth = doc.internal.pageSize.getWidth();\n const centerX = pageWidth / 2;\n const margin = 10;\n let y = startY;\n\n // Tournament name\n if (match.tournamentName) {\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n doc.setTextColor(100);\n doc.text(match.tournamentName, centerX, y, { align: 'center' });\n doc.setTextColor(0);\n y += 5;\n }\n\n // Event + Round\n setFont(doc, SIZE.HEADING, STYLE.BOLD);\n doc.text(`${match.eventName} - ${match.roundName}`, centerX, y, { align: 'center' });\n y += 5;\n\n // Court + Time\n if (match.courtName || match.scheduledTime) {\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n const info: string[] = [];\n if (match.courtName) info.push(`Court: ${match.courtName}`);\n if (match.scheduledTime) info.push(`Time: ${match.scheduledTime}`);\n doc.text(info.join(' '), centerX, y, { align: 'center' });\n y += 5;\n }\n\n // Separator\n doc.setDrawColor(0);\n doc.setLineWidth(0.5);\n doc.line(margin, y, pageWidth - margin, y);\n y += 6;\n\n // Player 1\n renderPlayerLine(doc, match.side1, margin, y, pageWidth);\n y += 8;\n\n // vs\n setFont(doc, SIZE.BODY, STYLE.ITALIC);\n doc.setTextColor(120);\n doc.text('vs.', centerX, y, { align: 'center' });\n doc.setTextColor(0);\n y += 6;\n\n // Player 2\n renderPlayerLine(doc, match.side2, margin, y, pageWidth);\n y += 8;\n\n // Score boxes\n if (includeScoreBoxes) {\n doc.setDrawColor(0);\n doc.setLineWidth(0.5);\n doc.line(margin, y, pageWidth - margin, y);\n y += 4;\n\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.text('Score:', margin, y);\n\n const boxWidth = 12;\n const boxHeight = 8;\n const boxStartX = margin + 18;\n const boxGap = 3;\n\n // 5 set boxes (3 for best-of-3, 5 for best-of-5)\n for (let i = 0; i < 5; i++) {\n const bx = boxStartX + i * (boxWidth + boxGap);\n doc.rect(bx, y - 4, boxWidth, boxHeight);\n // Set number label above\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.setTextColor(150);\n doc.text(`Set ${i + 1}`, bx + boxWidth / 2, y - 5, { align: 'center' });\n doc.setTextColor(0);\n }\n\n y += boxHeight + 6;\n\n // Umpire signature line\n setFont(doc, SIZE.SMALL, STYLE.NORMAL);\n doc.text('Umpire:', margin, y);\n doc.setDrawColor(150);\n doc.setLineWidth(0.3);\n doc.line(margin + 20, y, margin + 80, y);\n\n doc.text('Signature:', pageWidth - margin - 70, y);\n doc.line(pageWidth - margin - 40, y, pageWidth - margin, y);\n }\n}\n\nfunction renderPlayerLine(\n doc: jsPDF,\n side: { name: string; nationality: string; seedValue?: number },\n margin: number,\n y: number,\n pageWidth: number,\n): void {\n setFont(doc, 14, STYLE.BOLD);\n const seed = side.seedValue ? `[${side.seedValue}] ` : '';\n doc.text(`${seed}${side.name}`, margin, y);\n\n setFont(doc, SIZE.HEADING, STYLE.NORMAL);\n doc.setTextColor(80);\n doc.text(side.nationality, pageWidth - margin, y, { align: 'right' });\n doc.setTextColor(0);\n}\n","import jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport { drawTournamentHeader, drawPageFooter, type TournamentHeader } from '../layout/headers';\nimport { TABLE_STYLES } from '../layout/tables';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport interface ReportColumn {\n key: string;\n title: string;\n type?: 'string' | 'number' | 'boolean' | 'date';\n width?: number;\n}\n\nexport interface ReportPDFOptions {\n header?: TournamentHeader;\n orientation?: 'portrait' | 'landscape';\n title?: string;\n}\n\nexport function generateReportPDF(\n columns: ReportColumn[],\n rows: Record<string, any>[],\n options: ReportPDFOptions = {},\n): jsPDF {\n const orientation = options.orientation || 'portrait';\n const doc = new jsPDF({ orientation, format: 'a4' });\n let startY = 15;\n\n if (options.header) {\n startY = drawTournamentHeader(doc, {\n ...options.header,\n subtitle: options.header.subtitle || options.title,\n });\n } else if (options.title) {\n const margin = 15;\n setFont(doc, SIZE.SUBTITLE, STYLE.BOLD);\n doc.text(options.title, margin, startY);\n startY += 8;\n }\n\n const tableColumns = columns.map((col) => ({\n header: col.title,\n dataKey: col.key,\n }));\n\n const body = rows.map((row) => {\n const mapped: Record<string, any> = {};\n for (const col of columns) {\n const val = row[col.key];\n mapped[col.key] = val != null ? String(val) : '';\n }\n return mapped;\n });\n\n const columnStyles: Record<string, any> = {};\n for (const col of columns) {\n if (col.type === 'number') {\n columnStyles[col.key] = { halign: 'right' };\n }\n if (col.width) {\n columnStyles[col.key] = { ...columnStyles[col.key], cellWidth: col.width };\n }\n }\n\n autoTable(doc, {\n ...TABLE_STYLES.report,\n startY,\n columns: tableColumns,\n body,\n columnStyles,\n didDrawPage: (data) => {\n drawPageFooter(doc, `Generated ${new Date().toLocaleDateString()}`, data.pageNumber);\n },\n });\n\n return doc;\n}\n","/**\n * Fact Sheet Generator — produces structured tournament information PDFs.\n *\n * Pulls from tournament record fields, registration profile, venues, participants,\n * and events. Appends free-form notes HTML as plain text at the bottom.\n */\n\nimport jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport { buildHeaderFromTournament } from '../composition/tournamentBridge';\nimport { renderHeader } from '../composition/headerLayouts';\nimport { getFactSheetTemplate, type FactSheetSectionType } from '../config/factSheetCatalog';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\nimport { drawPageFooter } from '../layout/headers';\n\nconst MARGIN = 15;\n\ninterface FactSheetOptions {\n templateId?: string;\n enabledSections?: FactSheetSectionType[];\n}\n\nfunction stripHtml(html: string): string {\n // Use DOM when available; simple character-walk fallback for Node\n if (typeof document !== 'undefined') {\n const el = document.createElement('div');\n el.innerHTML = html;\n return el.textContent || '';\n }\n let result = '';\n let inTag = false;\n for (const ch of html) {\n if (ch === '<') {\n inTag = true;\n continue;\n }\n if (ch === '>') {\n inTag = false;\n continue;\n }\n if (!inTag) result += ch;\n }\n return result.trim();\n}\n\nfunction sectionHeading(doc: jsPDF, title: string, y: number): number {\n setFont(doc, SIZE.HEADING, STYLE.BOLD);\n doc.setTextColor(40);\n doc.text(title.toUpperCase(), MARGIN, y);\n doc.setTextColor(0);\n y += 1.5;\n doc.setDrawColor(180);\n doc.setLineWidth(0.2);\n doc.line(MARGIN, y, doc.internal.pageSize.getWidth() - MARGIN, y);\n y += 4;\n return y;\n}\n\nfunction bodyText(doc: jsPDF, text: string, y: number, maxWidth?: number): number {\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n const width = maxWidth || doc.internal.pageSize.getWidth() - MARGIN * 2;\n const lines = doc.splitTextToSize(text, width);\n doc.text(lines, MARGIN, y);\n return y + lines.length * 3.2;\n}\n\nfunction checkPageBreak(doc: jsPDF, y: number, needed: number): number {\n const pageHeight = doc.internal.pageSize.getHeight();\n if (y + needed > pageHeight - 20) {\n doc.addPage();\n return 20;\n }\n return y;\n}\n\nfunction renderTournamentHeader(doc: jsPDF, record: any, y: number): number {\n const pageConfig = {\n pageSize: 'a4' as const,\n orientation: 'portrait' as const,\n margins: { top: y, right: MARGIN, bottom: 15, left: MARGIN },\n };\n const headerConfig = buildHeaderFromTournament(record, { layout: 'itf' });\n const headerHeight = renderHeader(doc, headerConfig, pageConfig);\n return y + headerHeight;\n}\n\nfunction renderContacts(doc: jsPDF, record: any, y: number): number {\n const participants = record.participants || [];\n const nonCompetitors = participants.filter((p: any) => p.participantRole && p.participantRole !== 'COMPETITOR');\n if (!nonCompetitors.length) return y;\n\n y = checkPageBreak(doc, y, 20);\n y = sectionHeading(doc, 'Tournament Contacts', y);\n\n const rows = nonCompetitors.map((p: any) => {\n const person = p.person || {};\n const name =\n [person.standardGivenName, person.standardFamilyName].filter(Boolean).join(' ') || p.participantName || '';\n const role = p.participantRoleResponsibilities?.[0] || p.participantRole || '';\n const contact = person.contacts?.[0] || {};\n const details = [contact.emailAddress, contact.telephone || contact.mobileTelephone].filter(Boolean).join(' | ');\n return [name, role, details];\n });\n\n autoTable(doc, {\n startY: y,\n head: [['Name', 'Role', 'Contact']],\n body: rows,\n margin: { left: MARGIN, right: MARGIN },\n styles: { fontSize: 7, cellPadding: 1.5 },\n headStyles: { fillColor: [60, 60, 60], textColor: 255, fontStyle: 'bold' },\n theme: 'grid',\n });\n\n return (doc as any).lastAutoTable.finalY + 6;\n}\n\nfunction renderEvents(doc: jsPDF, record: any, y: number): number {\n const events = record.events || [];\n if (!events.length) return y;\n\n y = checkPageBreak(doc, y, 20);\n y = sectionHeading(doc, 'Events', y);\n\n const rows = events.map((e: any) => {\n const drawSize = e.drawDefinitions?.[0]?.drawSize || '';\n return [e.eventName || '', e.eventType || '', e.matchUpFormat || '', String(drawSize)];\n });\n\n autoTable(doc, {\n startY: y,\n head: [['Event', 'Type', 'Format', 'Draw Size']],\n body: rows,\n margin: { left: MARGIN, right: MARGIN },\n styles: { fontSize: 7, cellPadding: 1.5 },\n headStyles: { fillColor: [60, 60, 60], textColor: 255, fontStyle: 'bold' },\n theme: 'grid',\n });\n\n return (doc as any).lastAutoTable.finalY + 6;\n}\n\nfunction renderEntryInfo(doc: jsPDF, record: any, y: number): number {\n const rp = record.registrationProfile;\n if (!rp) return y;\n\n const lines: string[] = [];\n if (rp.entriesOpen) lines.push('Entries Open: ' + rp.entriesOpen);\n if (rp.entriesClose) lines.push('Entries Close: ' + rp.entriesClose);\n if (rp.withdrawalDeadline) lines.push('Withdrawal Deadline: ' + rp.withdrawalDeadline);\n if (rp.entryMethod) lines.push('Entry Method: ' + rp.entryMethod);\n if (rp.entryUrl) lines.push('Entry URL: ' + rp.entryUrl);\n if (rp.eligibilityNotes) lines.push('Eligibility: ' + rp.eligibilityNotes);\n\n if (rp.entryFees?.length) {\n const feeStr = rp.entryFees\n .map((f: any) => {\n const label = f.eventType ? f.eventType + ': ' : '';\n return label + f.currencyCode + ' ' + f.amount;\n })\n .join(', ');\n lines.push('Entry Fees: ' + feeStr);\n }\n\n if (!lines.length) return y;\n\n y = checkPageBreak(doc, y, 10 + lines.length * 3.5);\n y = sectionHeading(doc, 'Entry Information', y);\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n for (const line of lines) {\n doc.text(line, MARGIN, y);\n y += 3.5;\n }\n return y + 3;\n}\n\nfunction renderVenueInfo(doc: jsPDF, record: any, y: number): number {\n const venues = record.venues || [];\n if (!venues.length) return y;\n\n y = checkPageBreak(doc, y, 15);\n y = sectionHeading(doc, 'Venue', y);\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n for (const venue of venues) {\n setFont(doc, SIZE.BODY, STYLE.BOLD);\n doc.text(venue.venueName || 'Venue', MARGIN, y);\n y += 3.5;\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n\n const addr = venue.addresses?.[0];\n if (addr) {\n const parts = [addr.street, addr.city, addr.state, addr.postalCode, addr.countryCode].filter(Boolean);\n if (parts.length) {\n doc.text(parts.join(', '), MARGIN, y);\n y += 3.5;\n }\n }\n const courts = venue.courts?.length;\n if (courts) {\n doc.text('Courts: ' + courts, MARGIN, y);\n y += 3.5;\n }\n }\n return y + 3;\n}\n\nfunction renderLogisticsSection(doc: jsPDF, title: string, section: any, y: number): number {\n if (!section) return y;\n const hasOptions = section.options?.length;\n const hasNotes = section.notes && stripHtml(section.notes);\n if (!hasOptions && !hasNotes) return y;\n\n y = checkPageBreak(doc, y, 15);\n y = sectionHeading(doc, title, y);\n\n if (hasOptions) {\n const rows = section.options.map((opt: any) => {\n const details = [opt.phone, opt.email, opt.priceRange].filter(Boolean).join(' | ');\n return [opt.name, opt.address || '', details];\n });\n\n autoTable(doc, {\n startY: y,\n head: [['Name', 'Address', 'Details']],\n body: rows,\n margin: { left: MARGIN, right: MARGIN },\n styles: { fontSize: 7, cellPadding: 1.5 },\n headStyles: { fillColor: [60, 60, 60], textColor: 255, fontStyle: 'bold' },\n theme: 'grid',\n });\n\n y = (doc as any).lastAutoTable.finalY + 3;\n }\n\n if (hasNotes) {\n y = bodyText(doc, stripHtml(section.notes), y);\n }\n\n return y + 3;\n}\n\nfunction renderPrizeMoney(doc: jsPDF, record: any, y: number): number {\n const pm = record.totalPrizeMoney;\n if (!pm?.length) return y;\n\n y = checkPageBreak(doc, y, 10);\n y = sectionHeading(doc, 'Prize Money', y);\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n for (const p of pm) {\n doc.text(p.currencyCode + ' ' + p.amount.toLocaleString(), MARGIN, y);\n y += 3.5;\n }\n return y + 3;\n}\n\nfunction renderOfficials(doc: jsPDF, record: any, y: number): number {\n const participants = record.participants || [];\n const officials = participants.filter(\n (p: any) => p.participantRole === 'OFFICIAL' || p.participantRole === 'DIRECTOR',\n );\n if (!officials.length) return y;\n\n y = checkPageBreak(doc, y, 15);\n y = sectionHeading(doc, 'Officials', y);\n\n const rows = officials.map((p: any) => {\n const person = p.person || {};\n const name =\n [person.standardGivenName, person.standardFamilyName].filter(Boolean).join(' ') || p.participantName || '';\n const role = p.participantRoleResponsibilities?.[0] || p.participantRole || '';\n return [name, role];\n });\n\n autoTable(doc, {\n startY: y,\n head: [['Name', 'Role']],\n body: rows,\n margin: { left: MARGIN, right: MARGIN },\n styles: { fontSize: 7, cellPadding: 1.5 },\n headStyles: { fillColor: [60, 60, 60], textColor: 255, fontStyle: 'bold' },\n theme: 'grid',\n });\n\n return (doc as any).lastAutoTable.finalY + 6;\n}\n\nfunction renderRegulations(doc: jsPDF, record: any, y: number): number {\n const rp = record.registrationProfile;\n if (!rp) return y;\n\n const lines: string[] = [];\n if (rp.codeOfConduct) {\n const coc = rp.codeOfConduct;\n lines.push('Code of Conduct: ' + (coc.name || '') + (coc.url ? ' — ' + coc.url : ''));\n }\n if (rp.regulations?.length) {\n for (const reg of rp.regulations) {\n lines.push((reg.name || 'Regulation') + (reg.url ? ' — ' + reg.url : ''));\n }\n }\n if (rp.dressCode) lines.push('Dress Code: ' + rp.dressCode);\n if (rp.contingencyPlan) lines.push('Contingency: ' + rp.contingencyPlan);\n\n if (!lines.length) return y;\n\n y = checkPageBreak(doc, y, 10 + lines.length * 3.5);\n y = sectionHeading(doc, 'Regulations', y);\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n for (const line of lines) {\n doc.text(line, MARGIN, y);\n y += 3.5;\n }\n return y + 3;\n}\n\nfunction renderSponsors(doc: jsPDF, record: any, y: number): number {\n const sponsors = record.registrationProfile?.sponsors;\n if (!sponsors?.length) return y;\n\n y = checkPageBreak(doc, y, 10);\n y = sectionHeading(doc, 'Sponsors', y);\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n for (const s of sponsors) {\n const tierLabel = s.tier ? ' [' + s.tier + ']' : '';\n doc.text(s.name + tierLabel, MARGIN, y);\n y += 3.5;\n }\n return y + 3;\n}\n\nfunction renderSocialEvents(doc: jsPDF, record: any, y: number): number {\n const events = record.registrationProfile?.socialEvents;\n if (!events?.length) return y;\n\n const rp = record.registrationProfile;\n y = checkPageBreak(doc, y, 15);\n y = sectionHeading(doc, 'Social Events & Ceremonies', y);\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n if (rp?.drawCeremonyDate) {\n doc.text('Draw Ceremony: ' + rp.drawCeremonyDate, MARGIN, y);\n y += 3.5;\n }\n if (rp?.awardsCeremonyDate) {\n doc.text('Awards Ceremony: ' + rp.awardsCeremonyDate, MARGIN, y);\n y += 3.5;\n }\n\n for (const e of events) {\n setFont(doc, SIZE.BODY, STYLE.BOLD);\n doc.text(e.name, MARGIN, y);\n y += 3.5;\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n const details = [e.date, e.time, e.location].filter(Boolean).join(' | ');\n if (details) {\n doc.text(details, MARGIN, y);\n y += 3.5;\n }\n if (e.description) {\n doc.text(e.description, MARGIN, y);\n y += 3.5;\n }\n }\n return y + 3;\n}\n\nfunction renderCustomNotes(doc: jsPDF, record: any, y: number): number {\n const notes = record.notes;\n if (!notes) return y;\n\n const plain = stripHtml(notes);\n if (!plain) return y;\n\n y = checkPageBreak(doc, y, 15);\n y = sectionHeading(doc, 'Additional Information', y);\n y = bodyText(doc, plain, y);\n return y + 3;\n}\n\nconst SECTION_RENDERERS: Record<FactSheetSectionType, (doc: jsPDF, record: any, y: number) => number> = {\n 'tournament-header': renderTournamentHeader,\n contacts: renderContacts,\n events: renderEvents,\n 'entry-info': renderEntryInfo,\n 'venue-info': renderVenueInfo,\n accommodation: (doc, rec, y) =>\n renderLogisticsSection(doc, 'Accommodation', rec.registrationProfile?.accommodation, y),\n transportation: (doc, rec, y) =>\n renderLogisticsSection(doc, 'Transportation', rec.registrationProfile?.transportation, y),\n hospitality: (doc, rec, y) => renderLogisticsSection(doc, 'Hospitality', rec.registrationProfile?.hospitality, y),\n medical: (doc, rec, y) => renderLogisticsSection(doc, 'Medical', rec.registrationProfile?.medicalInfo, y),\n regulations: renderRegulations,\n 'prize-money': renderPrizeMoney,\n officials: renderOfficials,\n sponsors: renderSponsors,\n 'social-events': renderSocialEvents,\n 'custom-notes': renderCustomNotes,\n};\n\n/**\n * Generate a structured tournament fact sheet PDF.\n *\n * @param tournamentRecord - Full tournament record from tods-competition-factory\n * @param options - Template selection and section overrides\n * @returns jsPDF document\n */\nexport function generateFactSheet(tournamentRecord: any, options: FactSheetOptions = {}): jsPDF {\n const { templateId = 'itf-junior' } = options;\n const template = getFactSheetTemplate(templateId);\n const sections = template?.sections || getFactSheetTemplate('itf-junior')!.sections;\n\n const enabledSet = options.enabledSections ? new Set(options.enabledSections) : null;\n\n const doc = new jsPDF({ orientation: 'portrait', format: 'a4' });\n let y = MARGIN;\n\n for (const section of sections) {\n if (!section.enabled) continue;\n if (enabledSet && !enabledSet.has(section.type)) continue;\n\n const renderer = SECTION_RENDERERS[section.type];\n if (renderer) {\n y = renderer(doc, tournamentRecord, y);\n }\n }\n\n // Page footers\n const totalPages = doc.getNumberOfPages();\n for (let i = 1; i <= totalPages; i++) {\n doc.setPage(i);\n drawPageFooter(doc, 'Generated ' + new Date().toLocaleDateString(), i);\n }\n\n return doc;\n}\n","/**\n * Mirrored bracket renderer (NCAA-style).\n *\n * Two halves of the draw progress inward — left half flows left-to-right,\n * right half flows right-to-left. The winner column is in the center.\n *\n * Layout:\n * [Left R1] [Left R2] ... [Left SF] |WINNER| [Right SF] ... [Right R2] [Right R1]\n *\n * Used for: NCAA team tennis, collegiate dual matches, club events.\n */\n\nimport jsPDF from 'jspdf';\nimport type { DrawFormatConfig, PageRegions } from '../config/types';\nimport type { DrawData, DrawSlot, DrawMatchUp } from '../core/extractDrawData';\nimport { getRoundLabel } from '../core/extractDrawData';\nimport { formatPlayerEntrySplit, formatMatchScore } from './formatEntry';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\ninterface HalfConfig {\n lineHeight: number;\n roundColumnWidth: number;\n firstRoundWidth: number;\n connectorGap: number;\n fontSize: number;\n scoreFontSize: number;\n}\n\nexport function renderMirroredDraw(\n doc: jsPDF,\n drawData: DrawData,\n format: DrawFormatConfig,\n regions: PageRegions,\n): void {\n const margins = format.page.margins;\n const headerReserve = 9;\n const startY = regions.contentY + headerReserve;\n const contentHeight = regions.contentHeight - headerReserve;\n\n const halfSize = drawData.drawSize / 2;\n const halfRounds = Math.log2(halfSize);\n const totalWidth = regions.contentWidth;\n\n // Center column for winner\n const centerWidth = Math.min(30, totalWidth * 0.08);\n const halfWidth = (totalWidth - centerWidth) / 2;\n const centerX = margins.left + halfWidth;\n\n // Config for each half\n const lineHeight = contentHeight / halfSize;\n const isDense = lineHeight < 3.5;\n const connectorGap = isDense ? 0.8 : 1.5;\n const firstRoundWidth = Math.min(isDense ? 30 : 50, halfWidth * 0.22);\n const laterCols = halfRounds; // includes all rounds after R1\n const remaining = halfWidth - firstRoundWidth - connectorGap * (laterCols + 1);\n const roundColumnWidth = Math.max(8, remaining / Math.max(1, laterCols));\n let fontSize = SIZE.SMALL;\n if (lineHeight < 2.5) fontSize = 5;\n else if (isDense) fontSize = SIZE.TINY;\n const scoreFontSize = isDense ? 5 : SIZE.TINY;\n\n const config: HalfConfig = { lineHeight, roundColumnWidth, firstRoundWidth, connectorGap, fontSize, scoreFontSize };\n\n // Split matchUps and slots into two halves\n const leftSlots = drawData.slots.filter((s) => s.drawPosition <= halfSize);\n const rightSlots = drawData.slots.filter((s) => s.drawPosition > halfSize);\n\n const leftMatchUps = drawData.matchUps.filter((mu) => mu.drawPositions.every((dp) => dp <= halfSize));\n const rightMatchUps = drawData.matchUps.filter((mu) => mu.drawPositions.every((dp) => dp > halfSize));\n\n // Renumber right half: positions to 1..halfSize, roundPosition to 1..N per round\n const rightSlotsRenumbered = rightSlots.map((s) => ({ ...s, drawPosition: s.drawPosition - halfSize }));\n const rightByRound = new Map<number, typeof rightMatchUps>();\n for (const mu of rightMatchUps) {\n if (!rightByRound.has(mu.roundNumber)) rightByRound.set(mu.roundNumber, []);\n rightByRound.get(mu.roundNumber)!.push(mu);\n }\n const rightMatchUpsRenumbered: typeof rightMatchUps = [];\n for (const [, roundMus] of rightByRound) {\n roundMus.sort((a, b) => a.roundPosition - b.roundPosition);\n roundMus.forEach((mu, idx) => {\n rightMatchUpsRenumbered.push({\n ...mu,\n drawPositions: mu.drawPositions.map((dp) => dp - halfSize),\n roundPosition: idx + 1,\n });\n });\n }\n\n // Also renumber left half roundPosition for consistency\n const leftByRound = new Map<number, typeof leftMatchUps>();\n for (const mu of leftMatchUps) {\n if (!leftByRound.has(mu.roundNumber)) leftByRound.set(mu.roundNumber, []);\n leftByRound.get(mu.roundNumber)!.push(mu);\n }\n const leftMatchUpsRenumbered: typeof leftMatchUps = [];\n for (const [, roundMus] of leftByRound) {\n roundMus.sort((a, b) => a.roundPosition - b.roundPosition);\n roundMus.forEach((mu, idx) => {\n leftMatchUpsRenumbered.push({ ...mu, roundPosition: idx + 1 });\n });\n }\n\n // Round headers\n renderMirroredRoundHeaders(\n doc,\n halfRounds,\n drawData.totalRounds,\n config,\n format,\n margins.left,\n margins.left + totalWidth,\n regions.contentY + 2,\n drawData.roundLabelMap,\n );\n\n // Winner column header\n setFont(doc, isDense ? 5.5 : SIZE.SMALL, STYLE.BOLD);\n doc.setTextColor(40);\n doc.text('Winner', centerX + centerWidth / 2, regions.contentY + 2, { align: 'center' });\n doc.setDrawColor(160);\n doc.setLineWidth(0.15);\n doc.line(centerX + 2, regions.contentY + 3.5, centerX + centerWidth - 2, regions.contentY + 3.5);\n doc.setTextColor(0);\n\n // Render left half (left-to-right, normal direction)\n renderLeftHalf(\n doc,\n leftSlots,\n leftMatchUpsRenumbered,\n halfRounds,\n config,\n format,\n margins.left,\n startY,\n drawData.totalRounds,\n );\n\n // Render right half (right-to-left, mirrored)\n renderRightHalf(\n doc,\n rightSlotsRenumbered,\n rightMatchUpsRenumbered,\n halfRounds,\n config,\n format,\n margins.left + totalWidth,\n startY,\n drawData.totalRounds,\n );\n\n // Winner in center\n const finalMu = drawData.matchUps.find((mu) => mu.roundNumber === drawData.totalRounds);\n if (finalMu) {\n const winnerMidY = startY + contentHeight / 2;\n\n // Winner line\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(centerX + 2, winnerMidY, centerX + centerWidth - 2, winnerMidY);\n\n if (finalMu.winningSide) {\n const winnerPos = finalMu.drawPositions[finalMu.winningSide - 1];\n const winnerSlot = drawData.slots.find((s) => s.drawPosition === winnerPos);\n if (winnerSlot) {\n const { name } = formatPlayerEntrySplit(winnerSlot, format);\n setFont(doc, fontSize + 1, STYLE.BOLD);\n doc.text(name, centerX + centerWidth / 2, winnerMidY - 1, { align: 'center' });\n }\n }\n\n if (finalMu.score) {\n setFont(doc, scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(formatMatchScore(finalMu.score, format), centerX + centerWidth / 2, winnerMidY + scoreFontSize * 0.4, {\n align: 'center',\n });\n doc.setTextColor(0);\n }\n }\n}\n\nfunction renderLeftHalf(\n doc: jsPDF,\n slots: DrawSlot[],\n matchUps: DrawMatchUp[],\n totalRounds: number,\n config: HalfConfig,\n format: DrawFormatConfig,\n startX: number,\n startY: number,\n _fullTotalRounds: number,\n): void {\n const slotMap = new Map(slots.map((s) => [s.drawPosition, s]));\n const count = slots.length;\n\n for (let round = 0; round < totalRounds; round++) {\n const matchesInRound = count / Math.pow(2, round + 1);\n const spacing = config.lineHeight * Math.pow(2, round);\n const roundOffset = ((Math.pow(2, round) - 1) * config.lineHeight) / 2;\n const stride = Math.pow(2, round + 1) * config.lineHeight;\n const roundX = leftRoundX(round, config, startX);\n const colWidth = round === 0 ? config.firstRoundWidth : config.roundColumnWidth;\n\n for (let match = 0; match < matchesInRound; match++) {\n const topSlotY = startY + roundOffset + match * stride;\n const bottomSlotY = topSlotY + spacing;\n const midY = (topSlotY + bottomSlotY) / 2;\n\n if (round === 0) {\n const topPos = match * 2 + 1;\n const bottomPos = match * 2 + 2;\n drawPlayerLineCompact(doc, slotMap.get(topPos), config, roundX, topSlotY, colWidth, 'ltr');\n drawPlayerLineCompact(doc, slotMap.get(bottomPos), config, roundX, bottomSlotY, colWidth, 'ltr');\n } else {\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(roundX, topSlotY, roundX + colWidth, topSlotY);\n doc.line(roundX, bottomSlotY, roundX + colWidth, bottomSlotY);\n }\n\n // Right bracket\n const rightX = roundX + colWidth;\n const nextRoundX = leftRoundX(round + 1, config, startX);\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(rightX + config.connectorGap, topSlotY, rightX + config.connectorGap, bottomSlotY);\n doc.line(rightX, topSlotY, rightX + config.connectorGap, topSlotY);\n doc.line(rightX, bottomSlotY, rightX + config.connectorGap, bottomSlotY);\n doc.line(rightX + config.connectorGap, midY, nextRoundX, midY);\n\n // Advancing name\n const mu = findMatchUp(matchUps, round + 1, match + 1);\n if (round < totalRounds - 1 && mu?.winningSide) {\n const winnerPos = mu.drawPositions[mu.winningSide - 1];\n const winnerSlot = slotMap.get(winnerPos);\n if (winnerSlot) {\n setFont(doc, config.fontSize, STYLE.BOLD);\n let name = winnerSlot.participantName;\n if (doc.getTextWidth(name) > config.roundColumnWidth - 2) {\n name = abbreviateName(name);\n }\n doc.text(name, nextRoundX + 1, midY - 0.5);\n }\n }\n\n // Score\n if (mu?.score && round < totalRounds - 1) {\n setFont(doc, config.scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(formatMatchScore(mu.score, format), nextRoundX + 1, midY - 0.5 + config.scoreFontSize * 0.4);\n doc.setTextColor(0);\n }\n }\n }\n}\n\nfunction renderRightHalf(\n doc: jsPDF,\n slots: DrawSlot[],\n matchUps: DrawMatchUp[],\n totalRounds: number,\n config: HalfConfig,\n format: DrawFormatConfig,\n rightEdge: number,\n startY: number,\n _fullTotalRounds: number,\n): void {\n const slotMap = new Map(slots.map((s) => [s.drawPosition, s]));\n const count = slots.length;\n\n for (let round = 0; round < totalRounds; round++) {\n const matchesInRound = count / Math.pow(2, round + 1);\n const spacing = config.lineHeight * Math.pow(2, round);\n const roundOffset = ((Math.pow(2, round) - 1) * config.lineHeight) / 2;\n const stride = Math.pow(2, round + 1) * config.lineHeight;\n const roundX = rightRoundX(round, config, rightEdge);\n const colWidth = round === 0 ? config.firstRoundWidth : config.roundColumnWidth;\n\n for (let match = 0; match < matchesInRound; match++) {\n const topSlotY = startY + roundOffset + match * stride;\n const bottomSlotY = topSlotY + spacing;\n const midY = (topSlotY + bottomSlotY) / 2;\n\n if (round === 0) {\n const topPos = match * 2 + 1;\n const bottomPos = match * 2 + 2;\n drawPlayerLineCompact(doc, slotMap.get(topPos), config, roundX, topSlotY, colWidth, 'rtl');\n drawPlayerLineCompact(doc, slotMap.get(bottomPos), config, roundX, bottomSlotY, colWidth, 'rtl');\n } else {\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(roundX, topSlotY, roundX + colWidth, topSlotY);\n doc.line(roundX, bottomSlotY, roundX + colWidth, bottomSlotY);\n }\n\n // Left bracket (mirrored — vertical + stubs pointing left)\n const leftX = roundX;\n const prevRoundX = rightRoundX(round + 1, config, rightEdge);\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(leftX - config.connectorGap, topSlotY, leftX - config.connectorGap, bottomSlotY);\n doc.line(leftX, topSlotY, leftX - config.connectorGap, topSlotY);\n doc.line(leftX, bottomSlotY, leftX - config.connectorGap, bottomSlotY);\n doc.line(leftX - config.connectorGap, midY, prevRoundX + config.roundColumnWidth, midY);\n\n // Advancing name (right-aligned in the next inward column)\n const mu = findMatchUp(matchUps, round + 1, match + 1);\n if (round < totalRounds - 1 && mu?.winningSide) {\n const winnerPos = mu.drawPositions[mu.winningSide - 1];\n const winnerSlot = slotMap.get(winnerPos);\n if (winnerSlot) {\n setFont(doc, config.fontSize, STYLE.BOLD);\n let name = winnerSlot.participantName;\n if (doc.getTextWidth(name) > config.roundColumnWidth - 2) {\n name = abbreviateName(name);\n }\n const nextColX = prevRoundX;\n doc.text(name, nextColX + config.roundColumnWidth - 1, midY - 0.5, { align: 'right' });\n }\n }\n\n // Score\n if (mu?.score && round < totalRounds - 1) {\n const nextColX = prevRoundX;\n setFont(doc, config.scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(\n formatMatchScore(mu.score, format),\n nextColX + config.roundColumnWidth - 1,\n midY - 0.5 + config.scoreFontSize * 0.4,\n { align: 'right' },\n );\n doc.setTextColor(0);\n }\n }\n }\n}\n\nfunction renderMirroredRoundHeaders(\n doc: jsPDF,\n halfRounds: number,\n totalRounds: number,\n config: HalfConfig,\n format: DrawFormatConfig,\n leftStartX: number,\n rightStartX: number,\n y: number,\n roundLabelMap?: Record<number, string>,\n): void {\n const headerFontSize = config.fontSize <= SIZE.TINY ? 5.5 : SIZE.SMALL;\n setFont(doc, headerFontSize, STYLE.BOLD);\n doc.setTextColor(40);\n\n for (let round = 0; round < halfRounds; round++) {\n const roundNumber = totalRounds - halfRounds + round + 1;\n const defaultLabel = getRoundLabel(roundNumber, totalRounds);\n const label = roundLabelMap?.[roundNumber] || format.roundLabels[defaultLabel] || defaultLabel;\n const width = round === 0 ? config.firstRoundWidth : config.roundColumnWidth;\n\n // Left side\n const leftX = leftRoundX(round, config, leftStartX);\n doc.text(label, leftX + width / 2, y, { align: 'center' });\n doc.setDrawColor(160);\n doc.setLineWidth(0.15);\n doc.line(leftX + 2, y + 1.5, leftX + width - 2, y + 1.5);\n\n // Right side (mirrored)\n const rightX = rightRoundX(round, config, rightStartX);\n doc.text(label, rightX + width / 2, y, { align: 'center' });\n doc.line(rightX + 2, y + 1.5, rightX + width - 2, y + 1.5);\n }\n\n doc.setTextColor(0);\n}\n\nfunction leftRoundX(round: number, config: HalfConfig, startX: number): number {\n if (round === 0) return startX;\n return (\n startX +\n config.firstRoundWidth +\n config.connectorGap +\n (round - 1) * (config.roundColumnWidth + config.connectorGap)\n );\n}\n\nfunction rightRoundX(round: number, config: HalfConfig, rightEdge: number): number {\n if (round === 0) return rightEdge - config.firstRoundWidth;\n return (\n rightEdge -\n config.firstRoundWidth -\n config.connectorGap -\n (round - 1) * (config.roundColumnWidth + config.connectorGap) -\n config.roundColumnWidth\n );\n}\n\nfunction drawPlayerLineCompact(\n doc: jsPDF,\n slot: DrawSlot | undefined,\n config: HalfConfig,\n x: number,\n y: number,\n width: number,\n direction: 'ltr' | 'rtl',\n): void {\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(x, y, x + width, y);\n\n if (!slot || slot.isBye) {\n if (slot?.isBye) {\n setFont(doc, config.fontSize, STYLE.ITALIC);\n doc.setTextColor(150);\n if (direction === 'ltr') {\n doc.text('Bye', x + 1, y - 0.3);\n } else {\n doc.text('Bye', x + width - 1, y - 0.3, { align: 'right' });\n }\n doc.setTextColor(0);\n }\n return;\n }\n\n const seed = slot.seedValue ? `[${slot.seedValue}]` : '';\n setFont(doc, config.fontSize, STYLE.NORMAL);\n\n // Try full name first, abbreviate if too wide\n let name = slot.participantName;\n let display = seed ? `${seed} ${name}` : name;\n if (doc.getTextWidth(display) > width - 2) {\n name = abbreviateName(slot.participantName);\n display = seed ? `${seed} ${name}` : name;\n }\n\n if (direction === 'ltr') {\n doc.text(display, x + 1, y - 0.3);\n } else {\n doc.text(display, x + width - 1, y - 0.3, { align: 'right' });\n }\n}\n\nfunction abbreviateName(fullName: string): string {\n // \"LASTNAME, Firstname\" → \"F. LASTNAME\"\n const commaMatch = fullName.match(/^([^,]+),\\s*(.+)/);\n if (commaMatch) return `${commaMatch[2][0]}. ${commaMatch[1]}`;\n // \"Firstname Lastname\" → \"F. Lastname\"\n const spaceMatch = fullName.match(/^(\\S+)\\s+(.+)/);\n if (spaceMatch) return `${spaceMatch[1][0]}. ${spaceMatch[2]}`;\n return fullName;\n}\n\nfunction findMatchUp(matchUps: DrawMatchUp[], roundNumber: number, roundPosition: number): DrawMatchUp | undefined {\n return matchUps.find((mu) => mu.roundNumber === roundNumber && mu.roundPosition === roundPosition);\n}\n","/**\n * Backdraw (USTA Playback) renderer.\n *\n * First Round in the center, main draw progresses RIGHT,\n * consolation (playback) progresses LEFT. Landscape only.\n * Used for FIRST_ROUND_LOSER_CONSOLATION with drawSize ≤ 32.\n *\n * Layout:\n * [Consol Finals] ... [Consol R1] | [First Round boxes] | [Main R2] ... [Main Finals]\n * ← Playback | First Round | Main Draw →\n */\n\nimport jsPDF from 'jspdf';\nimport type { DrawFormatConfig, PageRegions } from '../config/types';\nimport type { DrawData, DrawSlot, DrawMatchUp } from '../core/extractDrawData';\nimport { formatPlayerEntrySplit, formatMatchScore } from './formatEntry';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport interface BackdrawData {\n mainDraw: DrawData;\n consolation: DrawData;\n}\n\nexport function renderBackdrawDraw(\n doc: jsPDF,\n data: BackdrawData,\n format: DrawFormatConfig,\n regions: PageRegions,\n): void {\n const margins = format.page.margins;\n const headerReserve = 9;\n const contentTop = regions.contentY + headerReserve;\n const contentHeight = regions.contentHeight - headerReserve;\n const totalWidth = regions.contentWidth;\n\n const mainMatchUps = data.mainDraw.matchUps;\n const mainSlots = data.mainDraw.slots;\n const consolMatchUps = data.consolation.matchUps;\n const consolSlots = data.consolation.slots;\n\n const mainSlotMap = new Map(mainSlots.map((s) => [s.drawPosition, s]));\n const consolSlotMap = new Map(consolSlots.map((s) => [s.drawPosition, s]));\n\n // R1 of main has the most matches — determines the center column height\n const r1Matches = mainMatchUps.filter((mu) => mu.roundNumber === 1).sort((a, b) => a.roundPosition - b.roundPosition);\n const r1Count = r1Matches.length;\n const drawSize = r1Count * 2;\n\n // Main has R1..Rn, consolation has R1..Rm\n const mainRounds = Math.max(...mainMatchUps.map((m) => m.roundNumber));\n const mainLaterRounds = mainRounds - 1; // rounds after R1 (progressing right)\n const consolRounds = consolMatchUps.length > 0 ? Math.max(...consolMatchUps.map((m) => m.roundNumber)) : 0;\n\n // Layout widths\n const centerBoxWidth = 28;\n const connectorGap = 1.5;\n const remainingWidth = totalWidth - centerBoxWidth - connectorGap * 4;\n\n // Right: main R2..Rn + winner column = mainLaterRounds + 1 columns\n const rightCols = mainLaterRounds + 1;\n // Left: consolation R1..Rn + winner column = consolRounds + 1 columns\n const leftCols = Math.max(consolRounds + 1, 1);\n\n const rightWidth = remainingWidth * (rightCols / (rightCols + leftCols));\n const leftWidth = remainingWidth - rightWidth;\n const centerX = margins.left + leftWidth + connectorGap;\n\n const rightColWidth = rightCols > 0 ? (rightWidth - connectorGap * rightCols) / rightCols : 0;\n const rightStartX = centerX + centerBoxWidth + connectorGap;\n\n const leftColWidth = leftCols > 0 ? (leftWidth - connectorGap * leftCols) / leftCols : 0;\n const leftEdgeX = margins.left + leftWidth;\n\n // Vertical spacing\n const lineHeight = contentHeight / drawSize;\n const isDense = lineHeight < 3.5;\n let fontSize = SIZE.SMALL;\n if (lineHeight < 2.5) fontSize = 5;\n else if (isDense) fontSize = SIZE.TINY;\n const scoreFontSize = isDense ? 5 : SIZE.TINY;\n\n // Round headers\n renderBackdrawHeaders(\n doc,\n mainRounds,\n consolRounds,\n data,\n format,\n centerX,\n centerBoxWidth,\n rightStartX,\n rightColWidth,\n leftEdgeX,\n leftColWidth,\n connectorGap,\n regions.contentY + 2,\n fontSize,\n );\n\n renderCenterColumn(\n doc,\n r1Matches,\n r1Count,\n mainSlotMap,\n centerX,\n centerBoxWidth,\n connectorGap,\n rightStartX,\n leftEdgeX,\n contentTop,\n lineHeight,\n fontSize,\n consolRounds,\n );\n\n // ---- Right side: Main R2+ (left-to-right) ----\n renderRightBracket(\n doc,\n mainMatchUps,\n mainSlotMap,\n mainRounds,\n r1Count,\n rightStartX,\n rightColWidth,\n connectorGap,\n contentTop,\n lineHeight,\n fontSize,\n scoreFontSize,\n format,\n data.mainDraw.roundLabelMap,\n );\n\n // ---- Left side: Consolation (right-to-left, mirrored) ----\n renderLeftBracket(\n doc,\n consolMatchUps,\n consolSlotMap,\n consolRounds,\n leftEdgeX,\n leftColWidth,\n connectorGap,\n contentTop,\n lineHeight,\n r1Count,\n fontSize,\n scoreFontSize,\n format,\n data.consolation.roundLabelMap,\n );\n}\n\nfunction renderCenterColumn(\n doc: jsPDF,\n r1Matches: DrawMatchUp[],\n r1Count: number,\n mainSlotMap: Map<number, DrawSlot>,\n centerX: number,\n centerBoxWidth: number,\n connectorGap: number,\n rightStartX: number,\n leftEdgeX: number,\n contentTop: number,\n lineHeight: number,\n fontSize: number,\n consolRounds: number,\n): void {\n for (let i = 0; i < r1Count; i++) {\n const mu = r1Matches[i];\n const topY = contentTop + i * lineHeight * 2;\n const bottomY = topY + lineHeight;\n const midY = (topY + bottomY) / 2;\n const dp1 = mu.drawPositions[0];\n const dp2 = mu.drawPositions[1];\n\n const boxH = lineHeight * 0.9;\n doc.setDrawColor(40);\n doc.setLineWidth(0.3);\n doc.rect(centerX, topY, centerBoxWidth, boxH);\n doc.rect(centerX, bottomY, centerBoxWidth, boxH);\n\n const slot1 = dp1 ? mainSlotMap.get(dp1) : undefined;\n const slot2 = dp2 ? mainSlotMap.get(dp2) : undefined;\n\n setFont(doc, fontSize, STYLE.NORMAL);\n if (dp1) {\n renderCenterBoxEntry(doc, dp1, slot1, mu.winningSide === 1, centerX, topY, boxH, centerBoxWidth, fontSize);\n }\n if (dp2) {\n renderCenterBoxEntry(doc, dp2, slot2, mu.winningSide === 2, centerX, bottomY, boxH, centerBoxWidth, fontSize);\n }\n\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(centerX + centerBoxWidth, topY + boxH / 2, centerX + centerBoxWidth + connectorGap, topY + boxH / 2);\n doc.line(centerX + centerBoxWidth, bottomY + boxH / 2, centerX + centerBoxWidth + connectorGap, bottomY + boxH / 2);\n doc.line(\n centerX + centerBoxWidth + connectorGap,\n topY + boxH / 2,\n centerX + centerBoxWidth + connectorGap,\n bottomY + boxH / 2,\n );\n doc.line(centerX + centerBoxWidth + connectorGap, midY, rightStartX, midY);\n\n if (consolRounds > 0) {\n doc.line(centerX, topY + boxH / 2, centerX - connectorGap, topY + boxH / 2);\n doc.line(centerX, bottomY + boxH / 2, centerX - connectorGap, bottomY + boxH / 2);\n doc.line(centerX - connectorGap, topY + boxH / 2, centerX - connectorGap, bottomY + boxH / 2);\n doc.line(centerX - connectorGap, midY, leftEdgeX, midY);\n }\n }\n}\n\nfunction renderCenterBoxEntry(\n doc: jsPDF,\n drawPosition: number,\n slot: DrawSlot | undefined,\n isWinner: boolean,\n centerX: number,\n y: number,\n boxH: number,\n centerBoxWidth: number,\n fontSize: number,\n): void {\n doc.setTextColor(120);\n setFont(doc, fontSize, STYLE.NORMAL);\n doc.text(`${drawPosition}`, centerX + 1, y + boxH / 2 + fontSize * 0.12);\n doc.setTextColor(0);\n if (slot?.participantName) {\n const name = abbreviateName(slot.participantName);\n setFont(doc, fontSize, isWinner ? STYLE.BOLD : STYLE.NORMAL);\n doc.text(name, centerX + 5, y + boxH / 2 + fontSize * 0.12, { maxWidth: centerBoxWidth - 6 });\n }\n}\n\nfunction renderRightBracket(\n doc: jsPDF,\n matchUps: DrawMatchUp[],\n slotMap: Map<number, DrawSlot>,\n totalRounds: number,\n _r1Count: number,\n startX: number,\n colWidth: number,\n connGap: number,\n contentTop: number,\n lineHeight: number,\n fontSize: number,\n scoreFontSize: number,\n format: DrawFormatConfig,\n _roundLabelMap?: Record<number, string>,\n): void {\n // R2..Rn of the main draw, standard left-to-right\n for (let rIdx = 0; rIdx < totalRounds - 1; rIdx++) {\n const roundNum = rIdx + 2;\n const roundMus = matchUps\n .filter((m) => m.roundNumber === roundNum)\n .sort((a, b) => a.roundPosition - b.roundPosition);\n const spacing = lineHeight * Math.pow(2, rIdx + 1);\n const roundOffset = ((Math.pow(2, rIdx + 1) - 1) * lineHeight) / 2;\n const colX = startX + rIdx * (colWidth + connGap);\n\n for (let mi = 0; mi < roundMus.length; mi++) {\n const mu = roundMus[mi];\n const topY = contentTop + roundOffset + mi * spacing * 2;\n const bottomY = topY + spacing;\n const midY = (topY + bottomY) / 2;\n\n // Horizontal slot lines\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(colX, topY, colX + colWidth, topY);\n doc.line(colX, bottomY, colX + colWidth, bottomY);\n\n // Advancing names\n renderAdvancingNames(doc, mu, slotMap, colX, topY, bottomY, colWidth, fontSize, format);\n\n // Bracket connector (if not last round)\n if (rIdx < totalRounds - 2) {\n const rightX = colX + colWidth;\n doc.line(rightX + connGap, topY, rightX + connGap, bottomY);\n doc.line(rightX, topY, rightX + connGap, topY);\n doc.line(rightX, bottomY, rightX + connGap, bottomY);\n doc.line(\n rightX + connGap,\n midY,\n colX + colWidth + connGap + colWidth + connGap > 0\n ? startX + (rIdx + 1) * (colWidth + connGap)\n : rightX + connGap + 5,\n midY,\n );\n }\n\n // Score\n if (mu.score) {\n setFont(doc, scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(formatMatchScore(mu.score, format), colX + colWidth - 1, midY + scoreFontSize * 0.12, {\n align: 'right',\n });\n doc.setTextColor(0);\n }\n }\n }\n\n // Winner line\n const winnerX = startX + (totalRounds - 2) * (colWidth + connGap) + colWidth + connGap;\n const winnerMidY =\n contentTop + ((Math.pow(2, totalRounds - 1) - 1) * lineHeight) / 2 + lineHeight * Math.pow(2, totalRounds - 2);\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(winnerX, winnerMidY, winnerX + colWidth, winnerMidY);\n\n const finalMu = matchUps.find((m) => m.roundNumber === totalRounds);\n if (finalMu?.winningSide) {\n const winnerSlot = slotMap.get(finalMu.drawPositions[finalMu.winningSide - 1]);\n if (winnerSlot) {\n const { name } = formatPlayerEntrySplit(winnerSlot, format);\n setFont(doc, fontSize + 1, STYLE.BOLD);\n doc.text(name, winnerX + 1, winnerMidY - 0.5);\n }\n }\n}\n\nfunction renderLeftBracket(\n doc: jsPDF,\n matchUps: DrawMatchUp[],\n slotMap: Map<number, DrawSlot>,\n totalRounds: number,\n rightEdge: number,\n colWidth: number,\n connGap: number,\n contentTop: number,\n lineHeight: number,\n _r1Count: number,\n fontSize: number,\n scoreFontSize: number,\n format: DrawFormatConfig,\n _roundLabelMap?: Record<number, string>,\n): void {\n for (let rIdx = 0; rIdx < totalRounds; rIdx++) {\n renderLeftRound(\n doc,\n matchUps,\n slotMap,\n rIdx,\n totalRounds,\n rightEdge,\n colWidth,\n connGap,\n contentTop,\n lineHeight,\n fontSize,\n scoreFontSize,\n format,\n );\n }\n\n renderLeftWinnerColumn(\n doc,\n matchUps,\n slotMap,\n totalRounds,\n rightEdge,\n colWidth,\n connGap,\n contentTop,\n lineHeight,\n fontSize,\n format,\n );\n}\n\nfunction renderLeftRound(\n doc: jsPDF,\n matchUps: DrawMatchUp[],\n slotMap: Map<number, DrawSlot>,\n rIdx: number,\n totalRounds: number,\n rightEdge: number,\n colWidth: number,\n connGap: number,\n contentTop: number,\n lineHeight: number,\n fontSize: number,\n scoreFontSize: number,\n format: DrawFormatConfig,\n): void {\n const roundNum = rIdx + 1;\n const roundMus = matchUps.filter((m) => m.roundNumber === roundNum).sort((a, b) => a.roundPosition - b.roundPosition);\n const spacing = lineHeight * Math.pow(2, rIdx + 1);\n const roundOffset = ((Math.pow(2, rIdx + 1) - 1) * lineHeight) / 2;\n const colX = rightEdge - (rIdx + 1) * (colWidth + connGap);\n\n for (let mi = 0; mi < roundMus.length; mi++) {\n const mu = roundMus[mi];\n const topY = contentTop + roundOffset + mi * spacing * 2;\n const bottomY = topY + spacing;\n const midY = (topY + bottomY) / 2;\n\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(colX, topY, colX + colWidth, topY);\n doc.line(colX, bottomY, colX + colWidth, bottomY);\n\n renderMirroredAdvancingName(doc, mu.drawPositions[0], slotMap, fontSize, colX, colWidth, topY);\n renderMirroredAdvancingName(doc, mu.drawPositions[1], slotMap, fontSize, colX, colWidth, bottomY);\n\n if (rIdx < totalRounds - 1) {\n doc.line(colX - connGap, topY, colX - connGap, bottomY);\n doc.line(colX, topY, colX - connGap, topY);\n doc.line(colX, bottomY, colX - connGap, bottomY);\n const nextColX = rightEdge - (rIdx + 2) * (colWidth + connGap);\n doc.line(colX - connGap, midY, nextColX + colWidth, midY);\n }\n\n if (mu.score) {\n setFont(doc, scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(formatMatchScore(mu.score, format), colX + 1, midY + scoreFontSize * 0.12);\n doc.setTextColor(0);\n }\n }\n}\n\nfunction renderMirroredAdvancingName(\n doc: jsPDF,\n drawPosition: number | undefined,\n slotMap: Map<number, DrawSlot>,\n fontSize: number,\n colX: number,\n colWidth: number,\n y: number,\n): void {\n if (!drawPosition) return;\n const slot = slotMap.get(drawPosition);\n if (!slot?.participantName) return;\n setFont(doc, fontSize, STYLE.BOLD);\n let displayName = slot.participantName;\n if (doc.getTextWidth(displayName) > colWidth - 2) displayName = abbreviateName(displayName);\n doc.text(displayName, colX + colWidth - 1, y - 0.3, { align: 'right' });\n}\n\nfunction renderLeftWinnerColumn(\n doc: jsPDF,\n matchUps: DrawMatchUp[],\n slotMap: Map<number, DrawSlot>,\n totalRounds: number,\n rightEdge: number,\n colWidth: number,\n connGap: number,\n contentTop: number,\n lineHeight: number,\n fontSize: number,\n format: DrawFormatConfig,\n): void {\n if (totalRounds <= 0) return;\n\n const winnerX = rightEdge - (totalRounds + 1) * (colWidth + connGap);\n const winnerMidY =\n contentTop + ((Math.pow(2, totalRounds) - 1) * lineHeight) / 2 + lineHeight * Math.pow(2, totalRounds - 1);\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(winnerX, winnerMidY, winnerX + colWidth, winnerMidY);\n\n const finalMu = matchUps.find((m) => m.roundNumber === totalRounds);\n if (finalMu?.winningSide) {\n const winnerSlot = slotMap.get(finalMu.drawPositions[finalMu.winningSide - 1]);\n if (winnerSlot) {\n const { name } = formatPlayerEntrySplit(winnerSlot, format);\n setFont(doc, fontSize + 1, STYLE.BOLD);\n doc.text(name, winnerX + colWidth - 1, winnerMidY - 0.5, { align: 'right' });\n }\n }\n}\n\nfunction renderAdvancingNames(\n doc: jsPDF,\n mu: DrawMatchUp,\n slotMap: Map<number, DrawSlot>,\n colX: number,\n topY: number,\n bottomY: number,\n colWidth: number,\n fontSize: number,\n _format: DrawFormatConfig,\n): void {\n if (mu.drawPositions[0]) {\n const slot = slotMap.get(mu.drawPositions[0]);\n if (slot?.participantName) {\n setFont(doc, fontSize, STYLE.BOLD);\n let name = slot.participantName;\n if (doc.getTextWidth(name) > colWidth - 2) name = abbreviateName(name);\n doc.text(name, colX + 1, topY - 0.3);\n }\n }\n if (mu.drawPositions[1]) {\n const slot = slotMap.get(mu.drawPositions[1]);\n if (slot?.participantName) {\n setFont(doc, fontSize, STYLE.BOLD);\n let name = slot.participantName;\n if (doc.getTextWidth(name) > colWidth - 2) name = abbreviateName(name);\n doc.text(name, colX + 1, bottomY - 0.3);\n }\n }\n}\n\nfunction renderBackdrawHeaders(\n doc: jsPDF,\n mainRounds: number,\n consolRounds: number,\n data: BackdrawData,\n _format: DrawFormatConfig,\n centerX: number,\n centerBoxWidth: number,\n rightStartX: number,\n rightColWidth: number,\n leftEdgeX: number,\n leftColWidth: number,\n connGap: number,\n y: number,\n fontSize: number,\n): void {\n const headerFontSize = fontSize <= SIZE.TINY ? 5.5 : SIZE.SMALL;\n setFont(doc, headerFontSize, STYLE.BOLD);\n doc.setTextColor(40);\n\n // Center: \"First Round\"\n const firstRoundLabel = data.mainDraw.roundLabelMap?.[1] || 'R1';\n doc.text(firstRoundLabel, centerX + centerBoxWidth / 2, y, { align: 'center' });\n\n // Right: Main R2+\n for (let i = 0; i < mainRounds - 1; i++) {\n const roundNum = i + 2;\n const label = data.mainDraw.roundLabelMap?.[roundNum] || `R${roundNum}`;\n const colX = rightStartX + i * (rightColWidth + connGap);\n doc.text(label, colX + rightColWidth / 2, y, { align: 'center' });\n }\n\n // Left: Consolation (mirrored, labels right-to-left)\n for (let i = 0; i < consolRounds; i++) {\n const roundNum = i + 1;\n const label = data.consolation.roundLabelMap?.[roundNum] || `C-R${roundNum}`;\n const colX = leftEdgeX - (i + 1) * (leftColWidth + connGap);\n doc.text(label, colX + leftColWidth / 2, y, { align: 'center' });\n }\n\n doc.setTextColor(0);\n}\n\nfunction abbreviateName(fullName: string): string {\n const commaMatch = fullName.match(/^([^,]+),\\s*(.+)/);\n if (commaMatch) return `${commaMatch[2][0]}. ${commaMatch[1]}`;\n const spaceMatch = fullName.match(/^(\\S+)\\s+(.+)/);\n if (spaceMatch) return `${spaceMatch[1][0]}. ${spaceMatch[2]}`;\n return fullName;\n}\n","/**\n * Composable draw PDF generator.\n *\n * Accepts DrawData + composition options and produces a complete, paginated PDF\n * with headers on every page, footers on every page, and automatic orientation.\n *\n * Supports: traditional single-elimination, feed-in, consolation (multi-structure),\n * compass, double elimination, lucky draw, round robin.\n */\n\nimport jsPDF from 'jspdf';\nimport type { HeaderConfig, FooterConfig, PageConfig } from '../config/types';\nimport type { DrawFormatConfig } from '../config/types';\nimport type { DrawData, DrawMatchUp } from '../core/extractDrawData';\nimport type { CompassDrawData } from '../core/extractCompassData';\nimport type { ConsolationStructure } from '../renderers/consolationDraw';\nimport type { DoubleEliminationData } from '../renderers/doubleEliminationDraw';\nimport { renderTraditionalDraw } from '../renderers/traditionalDraw';\nimport { renderMirroredDraw } from '../renderers/mirroredDraw';\nimport { renderBackdrawDraw, type BackdrawData } from '../renderers/backdrawDraw';\nimport { renderCompassDraw } from '../renderers/compassDraw';\nimport { renderConsolationDraw } from '../renderers/consolationDraw';\nimport { renderDoubleEliminationDraw } from '../renderers/doubleEliminationDraw';\nimport { renderLuckyDraw } from '../renderers/luckyDraw';\nimport { createDoc, getPageRegions } from '../composition/page';\nimport { renderHeader } from '../composition/headerLayouts';\nimport { renderFooter, measureFooterHeight } from '../composition/footerLayouts';\nimport { getPreset } from '../config/formatPresets';\nimport { splitDraw } from '../renderers/drawSplitter';\n\nexport interface DrawPDFOptions {\n header?: HeaderConfig;\n footer?: FooterConfig;\n page?: Partial<PageConfig>;\n preset?: string;\n format?: DrawFormatConfig;\n}\n\n/**\n * Smart entry point for TMX integration.\n *\n * Accepts DrawData and auto-detects the draw type to route to the correct renderer.\n * TMX callers can use getEventData() output directly — the generator inspects\n * matchUp patterns, structure count, and drawType to choose the layout.\n *\n * Header/footer configs come from provider defaults; tournament directors can override.\n */\nexport function generateDrawPDF(drawData: DrawData, options: DrawPDFOptions = {}): jsPDF {\n // Detect feed structure\n if (detectFeedStructure(drawData.matchUps)) {\n return generateFeedInDrawPDF(drawData, options);\n }\n\n // Standard single-elimination\n return generateTraditionalDrawPDF(drawData, options);\n}\n\nfunction detectFeedStructure(matchUps: DrawMatchUp[]): boolean {\n const roundCounts = new Map<number, number>();\n for (const mu of matchUps) {\n roundCounts.set(mu.roundNumber, (roundCounts.get(mu.roundNumber) || 0) + 1);\n }\n const rounds = [...roundCounts.keys()].sort((a, b) => a - b);\n for (let i = 1; i < rounds.length; i++) {\n const prev = roundCounts.get(rounds[i - 1]) || 0;\n const curr = roundCounts.get(rounds[i]) || 0;\n if (curr >= prev) return true;\n }\n return false;\n}\n\ninterface PageChrome {\n doc: jsPDF;\n pageConfig: PageConfig;\n headerConfig: HeaderConfig;\n footerConfig: FooterConfig;\n format: DrawFormatConfig;\n headerH: number;\n footerH: number;\n}\n\n// ---- Public API ----\n\nexport function generateTraditionalDrawPDF(drawData: DrawData, options: DrawPDFOptions = {}): jsPDF {\n // 256+ draws must always be split — too dense for single-page rendering\n if (drawData.drawSize >= 256) {\n return generateSplitDrawPDF(drawData, { ...options, maxPositionsPerPage: 64 });\n }\n\n const chrome = initChrome(drawData.drawSize, options);\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, chrome.headerH, chrome.footerH);\n\n renderTraditionalDraw(chrome.doc, drawData, chrome.format, regions);\n finalizePages(chrome);\n return chrome.doc;\n}\n\nexport function generateSplitDrawPDF(\n drawData: DrawData,\n options: DrawPDFOptions & { maxPositionsPerPage?: number } = {},\n): jsPDF {\n const chrome = initChrome(drawData.drawSize, options);\n const maxPerPage = options.maxPositionsPerPage || 32;\n const segments = splitDraw(drawData, {\n maxPositionsPerPage: maxPerPage,\n includeOverlapRounds: true,\n summaryPage: true,\n });\n\n for (let i = 0; i < segments.length; i++) {\n if (i > 0) chrome.doc.addPage();\n\n const headerH = renderHeader(\n chrome.doc,\n { ...chrome.headerConfig, subtitle: segments[i].label },\n chrome.pageConfig,\n );\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, headerH, chrome.footerH);\n\n if (segments[i].slots.length > 0 || segments[i].matchUps.length > 0) {\n const seg = segments[i];\n const segDrawSize = seg.endPosition - seg.startPosition + 1;\n const segData: DrawData = {\n ...drawData,\n slots: seg.slots,\n matchUps: seg.matchUps,\n noWinnerColumn: seg.noWinnerColumn,\n roundLabelMap: seg.roundLabelMap || drawData.roundLabelMap,\n drawSize: segDrawSize,\n totalRounds: seg.segmentRounds,\n };\n renderTraditionalDraw(chrome.doc, segData, chrome.format, regions, seg.startPosition - 1, segDrawSize);\n }\n }\n\n finalizePages(chrome);\n return chrome.doc;\n}\n\nexport function generateFeedInDrawPDF(drawData: DrawData, options: DrawPDFOptions = {}): jsPDF {\n const needsLandscape = drawData.totalRounds >= 5 || drawData.slots.length >= 12;\n const chrome = initChrome(drawData.drawSize, options, needsLandscape);\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, chrome.headerH, chrome.footerH);\n\n renderTraditionalDraw(chrome.doc, drawData, chrome.format, regions);\n finalizePages(chrome);\n return chrome.doc;\n}\n\nexport function generateConsolationDrawPDF(structures: ConsolationStructure[], options: DrawPDFOptions = {}): jsPDF {\n const maxSize = Math.max(...structures.map((s) => s.drawData.drawSize), 8);\n const chrome = initChrome(maxSize, options);\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, chrome.headerH, chrome.footerH);\n\n renderConsolationDraw(chrome.doc, structures, chrome.format, regions);\n // Consolation renderer may add pages — render header on any new pages\n renderHeadersOnNewPages(chrome, 1);\n finalizePages(chrome);\n return chrome.doc;\n}\n\nexport function generateCompassDrawPDF(compassData: CompassDrawData, options: DrawPDFOptions = {}): jsPDF {\n const mainSize = compassData.mainStructure?.drawSize || 8;\n const chrome = initChrome(mainSize, options);\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, chrome.headerH, chrome.footerH);\n\n renderCompassDraw(chrome.doc, compassData, chrome.format, regions);\n // Compass renderer may add pages — render header on any new pages\n renderHeadersOnNewPages(chrome, 1);\n finalizePages(chrome);\n return chrome.doc;\n}\n\nexport function generateMirroredDrawPDF(drawData: DrawData, options: DrawPDFOptions = {}): jsPDF {\n const chrome = initChrome(drawData.drawSize, options, true);\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, chrome.headerH, chrome.footerH);\n\n renderMirroredDraw(chrome.doc, drawData, chrome.format, regions);\n finalizePages(chrome);\n return chrome.doc;\n}\n\nexport function generateBackdrawPDF(data: BackdrawData, options: DrawPDFOptions = {}): jsPDF {\n const chrome = initChrome(data.mainDraw.drawSize, options, true);\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, chrome.headerH, chrome.footerH);\n\n renderBackdrawDraw(chrome.doc, data, chrome.format, regions);\n finalizePages(chrome);\n return chrome.doc;\n}\n\nexport function generateDoubleEliminationPDF(data: DoubleEliminationData, options: DrawPDFOptions = {}): jsPDF {\n const size = Math.max(data.winnersBracket.drawSize, data.losersBracket.drawSize, 8);\n const chrome = initChrome(size, options, true);\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, chrome.headerH, chrome.footerH);\n\n renderDoubleEliminationDraw(chrome.doc, data, chrome.format, regions);\n finalizePages(chrome);\n return chrome.doc;\n}\n\nexport function generateLuckyDrawPDF(drawData: DrawData, options: DrawPDFOptions = {}): jsPDF {\n const chrome = initChrome(drawData.drawSize, options);\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, chrome.headerH, chrome.footerH);\n\n renderLuckyDraw(chrome.doc, drawData, chrome.format, regions);\n finalizePages(chrome);\n return chrome.doc;\n}\n\n// ---- Internal helpers ----\n\nfunction initChrome(drawSize: number, options: DrawPDFOptions, forceLandscape?: boolean): PageChrome {\n const format = options.format || getPreset(options.preset || 'itfJunior');\n const pageConfig: PageConfig = {\n ...format.page,\n ...options.page,\n orientation: forceLandscape ? 'landscape' : options.page?.orientation || format.page.orientation,\n };\n\n const headerConfig: HeaderConfig = options.header || { layout: 'none', tournamentName: '' };\n const footerConfig: FooterConfig = options.footer || {\n layout: 'standard',\n showPageNumbers: true,\n showTimestamp: true,\n };\n\n const doc = createDoc(pageConfig, drawSize);\n const footerH = measureFooterHeight(footerConfig);\n const headerH = renderHeader(doc, headerConfig, pageConfig);\n\n return { doc, pageConfig, headerConfig, footerConfig, format, headerH, footerH };\n}\n\n/** Render header on any pages added after the initial page (page 1 already has one) */\nfunction renderHeadersOnNewPages(chrome: PageChrome, firstPageCount: number): void {\n const totalPages = chrome.doc.getNumberOfPages();\n for (let p = firstPageCount + 1; p <= totalPages; p++) {\n chrome.doc.setPage(p);\n renderHeader(chrome.doc, chrome.headerConfig, chrome.pageConfig);\n }\n}\n\n/** Render footer on every page with correct page numbers */\nfunction finalizePages(chrome: PageChrome): void {\n const totalPages = chrome.doc.getNumberOfPages();\n for (let p = 1; p <= totalPages; p++) {\n chrome.doc.setPage(p);\n renderFooter(chrome.doc, chrome.footerConfig, chrome.pageConfig, p);\n }\n // Ensure we end on the last page\n chrome.doc.setPage(totalPages);\n}\n","/**\n * High-level TMX API for PDF generation from eventData.\n *\n * TMX calls: generateFromEventData(eventData, options) → jsPDF\n *\n * This resolves a catalog preset, populates header/footer from\n * tournamentInfo/eventInfo, and routes to the appropriate generator.\n */\n\nimport jsPDF from 'jspdf';\nimport type { HeaderConfig, FooterConfig } from '../config/types';\nimport { getCatalogPreset } from '../config/compositionCatalog';\nimport { getPreset } from '../config/formatPresets';\nimport { structureToDrawData, findStructure } from '../core/drawsDataToDrawData';\nimport type { DrawData } from '../core/extractDrawData';\nimport type { ConsolationStructure } from '../renderers/consolationDraw';\nimport type { DoubleEliminationData } from '../renderers/doubleEliminationDraw';\nimport {\n generateTraditionalDrawPDF,\n generateSplitDrawPDF,\n generateConsolationDrawPDF,\n generateDoubleEliminationPDF,\n generateMirroredDrawPDF,\n} from './drawPDF';\nimport { createDoc } from '../composition/page';\n\nexport interface GenerateFromEventDataOptions {\n catalogPreset?: string;\n headerOverrides?: Partial<HeaderConfig>;\n footerOverrides?: Partial<FooterConfig>;\n structureId?: string;\n splitPages?: boolean;\n maxPositionsPerPage?: number;\n mirrored?: boolean;\n}\n\nexport function generateFromEventData(eventData: any, options: GenerateFromEventDataOptions = {}): jsPDF {\n const drawsData = eventData?.drawsData || [];\n const tournamentInfo = eventData?.tournamentInfo || {};\n const eventInfo = eventData?.eventInfo || {};\n\n // Resolve catalog preset\n const preset = getCatalogPreset(options.catalogPreset || 'club-basic');\n const drawFormat = getPreset(preset?.drawFormatPreset || 'itfJunior');\n\n // Build header config from tournament/event info + catalog + overrides\n const header: HeaderConfig = {\n layout: 'itf',\n tournamentName: tournamentInfo.tournamentName || 'Tournament',\n ...preset?.header,\n subtitle: eventInfo.eventName || preset?.header?.subtitle,\n startDate: tournamentInfo.startDate,\n endDate: tournamentInfo.endDate,\n location: tournamentInfo.venues?.[0]?.venueName,\n city: tournamentInfo.venues?.[0]?.city,\n country: tournamentInfo.hostCountryCode,\n surface: eventInfo.surfaceCategory,\n ...options.headerOverrides,\n };\n\n // Build footer config from catalog + overrides\n const footer: FooterConfig = {\n layout: 'standard',\n showPageNumbers: true,\n showTimestamp: true,\n ...preset?.footer,\n ...options.footerOverrides,\n };\n\n // Detect draw type from structures\n const structures = drawsData?.[0]?.structures || [];\n const hasConsolation = structures.some((s: any) => s.stage === 'CONSOLATION');\n const hasPlayOff = structures.some((s: any) => s.stage === 'PLAY_OFF');\n const mainStruct = structures.find((s: any) => s.stage === 'MAIN');\n\n const pdfOpts = { header, footer, format: drawFormat };\n\n // Double elimination: MAIN + CONSOLATION + PLAY_OFF\n if (hasConsolation && hasPlayOff) {\n const data: DoubleEliminationData = {\n winnersBracket: mainStruct ? structureToDrawData(mainStruct) : emptyDrawData(),\n losersBracket: findStructure(drawsData, 'CONSOLATION')\n ? structureToDrawData(findStructure(drawsData, 'CONSOLATION'))\n : emptyDrawData(),\n deciderMatch: findStructure(drawsData, 'PLAY_OFF')\n ? structureToDrawData(findStructure(drawsData, 'PLAY_OFF'))\n : undefined,\n };\n return generateDoubleEliminationPDF(data, pdfOpts);\n }\n\n // Consolation: MAIN + CONSOLATION (no PLAY_OFF)\n if (hasConsolation) {\n const consolStructures: ConsolationStructure[] = structures.map((s: any) => ({\n name: s.structureName,\n stage: s.stage,\n drawData: structureToDrawData(s),\n }));\n return generateConsolationDrawPDF(consolStructures, pdfOpts);\n }\n\n // Single structure — determine which renderer\n const targetStruct = options.structureId\n ? structures.find((s: any) => s.structureId === options.structureId) || mainStruct\n : mainStruct;\n\n if (!targetStruct) {\n return createDoc({\n pageSize: 'a4',\n orientation: 'portrait',\n margins: { top: 12, right: 15, bottom: 12, left: 15 },\n });\n }\n\n const drawData = structureToDrawData(targetStruct);\n\n // Mirrored bracket\n if (options.mirrored) {\n return generateMirroredDrawPDF(drawData, pdfOpts);\n }\n\n // Split pages\n if (options.splitPages || drawData.drawSize >= 256) {\n return generateSplitDrawPDF(drawData, { ...pdfOpts, maxPositionsPerPage: options.maxPositionsPerPage || 32 });\n }\n\n // Feed-in detection (done inside generateTraditionalDrawPDF via detectFeedStructure)\n return generateTraditionalDrawPDF(drawData, pdfOpts);\n}\n\nfunction emptyDrawData(): DrawData {\n return { drawName: '', drawSize: 0, drawType: '', totalRounds: 0, slots: [], matchUps: [], seedAssignments: [] };\n}\n"],"mappings":"yLAEA,IAAM,EAAyC,CAC7C,EAAG,QACH,GAAI,cACJ,GAAI,iBACJ,IAAK,cACL,IAAK,cACL,IAAK,cACL,KAAM,eACP,CAEK,EAA2C,CAC/C,EAAG,QACH,GAAI,cACJ,GAAI,iBACJ,IAAK,eACL,IAAK,cACL,IAAK,eACL,KAAM,cACP,CAEK,EAAwC,CAC5C,EAAG,QACH,GAAI,aACJ,GAAI,gBACJ,IAAK,UACL,IAAK,UACL,IAAK,UACL,KAAM,UACP,CAEK,EAAwC,CAC5C,EAAG,SACH,GAAI,aACJ,GAAI,aACJ,IAAK,aACL,IAAK,YACL,IAAK,YACL,KAAM,WACP,CAEK,EAAe,CACnB,SAAU,KACV,YAAa,OACb,QAAS,CAAE,IAAK,GAAI,MAAO,GAAI,OAAQ,GAAI,KAAM,GAAI,CACtD,CAGK,EAAmB,cACnB,EAAW,OACX,EAAc,kBACd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O,EAAE,CAAE,SAAU,EAAE,CAAE,gBAAiB,EAAE,CAAE"}
|
|
1
|
+
{"version":3,"file":"pdf-factory.cjs","names":[],"sources":["../src/config/formatPresets.ts","../src/config/compositionCatalog.ts","../src/config/factSheetCatalog.ts","../src/core/drawsDataToDrawData.ts","../src/composition/page.ts","../src/layout/fonts.ts","../src/composition/headerLayouts.ts","../src/composition/tournamentBridge.ts","../src/composition/footerLayouts.ts","../src/composition/seedingsFooter.ts","../src/composition/printDispatcher.ts","../src/composition/editorTypes.ts","../src/composition/printModalTypes.ts","../src/utils/primitives.ts","../src/core/extractDrawData.ts","../src/core/extractScheduleData.ts","../src/core/extractParticipantData.ts","../src/core/extractCourtCardData.ts","../src/core/extractRoundRobinData.ts","../src/renderers/formatEntry.ts","../src/renderers/traditionalDraw.ts","../src/renderers/roundRobinDraw.ts","../src/renderers/luckyDraw.ts","../src/renderers/drawSplitter.ts","../src/renderers/compassDraw.ts","../src/renderers/consolationDraw.ts","../src/renderers/doubleEliminationDraw.ts","../src/core/extractCompassData.ts","../src/layout/headers.ts","../src/layout/tables.ts","../src/layout/brackets.ts","../src/generators/drawSheet.ts","../src/generators/schedule.ts","../src/generators/playerList.ts","../src/generators/courtCard.ts","../src/generators/signInSheet.ts","../src/generators/scheduleV2.ts","../src/generators/sequentialOOP.ts","../src/generators/matchCard.ts","../src/generators/report.ts","../src/generators/factSheet.ts","../src/renderers/mirroredDraw.ts","../src/renderers/backdrawDraw.ts","../src/generators/drawPDF.ts","../src/generators/generateFromEventData.ts"],"sourcesContent":["import type { DrawFormatConfig } from './types';\n\nconst ENGLISH_ROUNDS: Record<string, string> = {\n F: 'Final',\n SF: 'Semi-Finals',\n QF: 'Quarter-Finals',\n R16: 'Round of 16',\n R32: 'Round of 32',\n R64: 'Round of 64',\n R128: 'Round of 128',\n};\n\nconst WIMBLEDON_ROUNDS: Record<string, string> = {\n F: 'Final',\n SF: 'Semi-Finals',\n QF: 'Quarter-Finals',\n R16: 'Fourth Round',\n R32: 'Third Round',\n R64: 'Second Round',\n R128: 'First Round',\n};\n\nconst USOPEN_ROUNDS: Record<string, string> = {\n F: 'Final',\n SF: 'Semifinals',\n QF: 'Quarterfinals',\n R16: 'Round 4',\n R32: 'Round 3',\n R64: 'Round 2',\n R128: 'Round 1',\n};\n\nconst FRENCH_ROUNDS: Record<string, string> = {\n F: 'FINALE',\n SF: '1/2 FINALE',\n QF: '1/4 FINALE',\n R16: '1/8 FINALE',\n R32: '3eme TOUR',\n R64: '2eme TOUR',\n R128: '1er TOUR',\n};\n\nconst DEFAULT_PAGE = {\n pageSize: 'a4' as const,\n orientation: 'auto' as const,\n margins: { top: 15, right: 10, bottom: 15, left: 10 },\n};\n\n// Shared values extracted for sonarjs/no-duplicate-string\nconst LAST_COMMA_FIRST = 'LAST, First' as const;\nconst NAT_BARE = 'bare' as const;\nconst SEED_BEFORE = 'before-position' as const;\nconst SEED_BRACKETS = 'brackets' as const;\nconst GAME_HYPHEN = '-' as const;\nconst TRADITIONAL = 'traditional-lines' as const;\n\nexport const PRESETS: Record<string, DrawFormatConfig> = {\n wimbledon: {\n nameFormat: LAST_COMMA_FIRST,\n nationalityFormat: NAT_BARE,\n seedPosition: SEED_BEFORE,\n seedFormat: SEED_BRACKETS,\n entryFormat: 'parens',\n gameScoreSeparator: GAME_HYPHEN,\n setScoreSeparator: ' ',\n retirementLabel: 'Ret.',\n walkoverLabel: 'w/o',\n roundLabels: WIMBLEDON_ROUNDS,\n renderStyle: TRADITIONAL,\n page: { ...DEFAULT_PAGE },\n },\n\n usOpen: {\n nameFormat: LAST_COMMA_FIRST,\n nationalityFormat: NAT_BARE,\n seedPosition: SEED_BEFORE,\n seedFormat: SEED_BRACKETS,\n entryFormat: 'parens',\n gameScoreSeparator: GAME_HYPHEN,\n setScoreSeparator: ' | ',\n retirementLabel: 'Ret.',\n walkoverLabel: 'w/o',\n roundLabels: USOPEN_ROUNDS,\n renderStyle: TRADITIONAL,\n page: { ...DEFAULT_PAGE },\n },\n\n rolandGarros: {\n nameFormat: 'LAST First',\n nationalityFormat: NAT_BARE,\n seedPosition: 'after-country',\n seedFormat: SEED_BRACKETS,\n entryFormat: 'parens',\n gameScoreSeparator: '/',\n setScoreSeparator: ' ',\n retirementLabel: 'Ab',\n walkoverLabel: 'w/o',\n roundLabels: FRENCH_ROUNDS,\n renderStyle: TRADITIONAL,\n page: { ...DEFAULT_PAGE },\n },\n\n australianOpen: {\n nameFormat: LAST_COMMA_FIRST,\n nationalityFormat: 'parens',\n seedPosition: 'after-name',\n seedFormat: SEED_BRACKETS,\n entryFormat: 'hyphen',\n gameScoreSeparator: '/',\n setScoreSeparator: ' ',\n retirementLabel: 'Ret.',\n walkoverLabel: 'w/o',\n roundLabels: ENGLISH_ROUNDS,\n renderStyle: TRADITIONAL,\n page: { ...DEFAULT_PAGE, pageSize: 'letter' as const, orientation: 'portrait' as const },\n },\n\n itfJunior: {\n nameFormat: LAST_COMMA_FIRST,\n nationalityFormat: NAT_BARE,\n seedPosition: SEED_BEFORE,\n seedFormat: SEED_BRACKETS,\n entryFormat: 'bare',\n gameScoreSeparator: GAME_HYPHEN,\n setScoreSeparator: ' ',\n retirementLabel: 'Ret.',\n walkoverLabel: 'w/o',\n roundLabels: ENGLISH_ROUNDS,\n renderStyle: TRADITIONAL,\n page: { ...DEFAULT_PAGE },\n },\n\n usta: {\n nameFormat: LAST_COMMA_FIRST,\n nationalityFormat: NAT_BARE,\n seedPosition: SEED_BEFORE,\n seedFormat: SEED_BRACKETS,\n entryFormat: 'bare',\n gameScoreSeparator: GAME_HYPHEN,\n setScoreSeparator: ' ',\n retirementLabel: 'Ret.',\n walkoverLabel: 'W/O',\n roundLabels: ENGLISH_ROUNDS,\n renderStyle: TRADITIONAL,\n page: { ...DEFAULT_PAGE },\n },\n};\n\nexport function getPreset(name: string): DrawFormatConfig {\n return PRESETS[name] || PRESETS.itfJunior;\n}\n\nexport function mergePreset(name: string, overrides: Partial<DrawFormatConfig>): DrawFormatConfig {\n return { ...getPreset(name), ...overrides };\n}\n","/**\n * Composition Catalog — named presets for PDF header/footer/layout combinations.\n *\n * Analogous to matchUpFormat catalogs in the factory, these presets bundle\n * header layout, footer layout, draw format, and page config into named units.\n * Tournament directors select a preset and optionally override individual fields.\n *\n * TMX flow: provider defaults → catalog preset → tournament director overrides\n */\n\nimport type { HeaderConfig, FooterConfig, PageConfig } from './types';\n\nconst ITF_JUNIOR_PRESET = 'itfJunior';\nconst COMBINED_TOUR_FOOTER = 'combined-tour' as const;\nconst GRAND_SLAM = 'grand-slam' as const;\nconst OFFICIALS_SIGNOFF = 'officials-signoff' as const;\n\nexport interface CompositionPreset {\n id: string;\n name: string;\n description: string;\n category: 'grand-slam' | 'tour' | 'itf' | 'national' | 'collegiate' | 'club';\n tier: 1 | 2 | 3;\n header: Partial<HeaderConfig>;\n footer: Partial<FooterConfig>;\n page?: Partial<PageConfig>;\n drawFormatPreset?: string;\n}\n\nexport const COMPOSITION_CATALOG: Record<string, CompositionPreset> = {\n [GRAND_SLAM]: {\n id: GRAND_SLAM,\n name: 'Grand Slam',\n description: 'Minimal chrome — large tournament name, timestamp footer',\n category: GRAND_SLAM,\n tier: 1,\n header: { layout: GRAND_SLAM },\n footer: { layout: 'standard', showPageNumbers: true, showTimestamp: true },\n drawFormatPreset: 'wimbledon',\n },\n wimbledon: {\n id: 'wimbledon',\n name: 'Wimbledon',\n description: 'Green/purple Grand Slam style with crest',\n category: GRAND_SLAM,\n tier: 1,\n header: { layout: GRAND_SLAM },\n footer: { layout: 'standard', showPageNumbers: true, showTimestamp: true },\n drawFormatPreset: 'wimbledon',\n },\n 'australian-open': {\n id: 'australian-open',\n name: 'Australian Open',\n description: 'Grand Slam with seedings + prize money footer',\n category: GRAND_SLAM,\n tier: 2,\n header: { layout: GRAND_SLAM },\n footer: { layout: COMBINED_TOUR_FOOTER, showPageNumbers: true, showTimestamp: true },\n drawFormatPreset: 'australianOpen',\n },\n 'wta-500': {\n id: 'wta-500',\n name: 'WTA 500',\n description: 'Tour header with logos, seedings + prize money footer',\n category: 'tour',\n tier: 2,\n header: { layout: 'wta-tour' },\n footer: { layout: COMBINED_TOUR_FOOTER, showPageNumbers: false, showTimestamp: true },\n drawFormatPreset: ITF_JUNIOR_PRESET,\n },\n 'wta-1000': {\n id: 'wta-1000',\n name: 'WTA 1000',\n description: 'Tour header with logos, full footer with officials',\n category: 'tour',\n tier: 2,\n header: { layout: 'wta-tour' },\n footer: { layout: COMBINED_TOUR_FOOTER, showPageNumbers: false, showTimestamp: true },\n drawFormatPreset: ITF_JUNIOR_PRESET,\n },\n 'atp-250': {\n id: 'atp-250',\n name: 'ATP 250',\n description: 'ATP tour header, seedings + prize money footer with sign-off',\n category: 'tour',\n tier: 2,\n header: { layout: 'wta-tour' },\n footer: { layout: COMBINED_TOUR_FOOTER, showPageNumbers: false, showTimestamp: true },\n drawFormatPreset: ITF_JUNIOR_PRESET,\n },\n 'atp-finals': {\n id: 'atp-finals',\n name: 'ATP Finals',\n description: 'Full official sign-off with signature lines',\n category: 'tour',\n tier: 3,\n header: { layout: GRAND_SLAM },\n footer: { layout: OFFICIALS_SIGNOFF, showTimestamp: true },\n drawFormatPreset: ITF_JUNIOR_PRESET,\n },\n 'itf-junior': {\n id: 'itf-junior',\n name: 'ITF Junior',\n description: 'ITF header with metadata row, officials sign-off footer',\n category: 'itf',\n tier: 3,\n header: { layout: 'itf' },\n footer: { layout: OFFICIALS_SIGNOFF, showPageNumbers: true, showTimestamp: true },\n drawFormatPreset: ITF_JUNIOR_PRESET,\n },\n 'itf-pro-circuit': {\n id: 'itf-pro-circuit',\n name: 'ITF Pro Circuit',\n description: 'ITF header, seedings + officials footer',\n category: 'itf',\n tier: 2,\n header: { layout: 'itf' },\n footer: { layout: COMBINED_TOUR_FOOTER, showPageNumbers: true, showTimestamp: true },\n drawFormatPreset: ITF_JUNIOR_PRESET,\n },\n 'national-federation': {\n id: 'national-federation',\n name: 'National Federation',\n description: 'Detailed metadata header, full sign-off footer with ceremony date',\n category: 'national',\n tier: 3,\n header: { layout: 'national-federation' },\n footer: { layout: OFFICIALS_SIGNOFF, showPageNumbers: true, showTimestamp: true },\n drawFormatPreset: 'usta',\n },\n 'collegiate-ncaa': {\n id: 'collegiate-ncaa',\n name: 'NCAA Collegiate',\n description: 'Mirrored bracket layout, team logos, minimal footer',\n category: 'collegiate',\n tier: 1,\n header: { layout: GRAND_SLAM },\n footer: { layout: 'standard', showPageNumbers: true, showTimestamp: true },\n drawFormatPreset: ITF_JUNIOR_PRESET,\n },\n 'club-basic': {\n id: 'club-basic',\n name: 'Club Basic',\n description: 'Minimal header, standard footer — clean and simple',\n category: 'club',\n tier: 1,\n header: { layout: 'minimal' },\n footer: { layout: 'standard', showPageNumbers: true, showTimestamp: true },\n drawFormatPreset: ITF_JUNIOR_PRESET,\n },\n};\n\nexport function getCatalogPreset(id: string): CompositionPreset | undefined {\n return COMPOSITION_CATALOG[id];\n}\n\nexport function listCatalogPresets(category?: string): CompositionPreset[] {\n const entries = Object.values(COMPOSITION_CATALOG);\n return category ? entries.filter((e) => e.category === category) : entries;\n}\n\nexport function mergeCatalogPreset(\n id: string,\n headerOverrides?: Partial<HeaderConfig>,\n footerOverrides?: Partial<FooterConfig>,\n): { header: Partial<HeaderConfig>; footer: Partial<FooterConfig> } {\n const preset = COMPOSITION_CATALOG[id] || COMPOSITION_CATALOG['club-basic'];\n return {\n header: { ...preset.header, ...headerOverrides },\n footer: { ...preset.footer, ...footerOverrides },\n };\n}\n","/**\n * Fact Sheet Catalog — template presets defining which sections to include per governing body.\n *\n * Parallels compositionCatalog.ts (draw sheet presets) but for tournament fact sheets.\n * Each preset declares which sections are enabled, in what order, and which header/footer\n * composition preset to inherit from.\n */\n\nimport type { HeaderLayout } from './types';\n\nexport type FactSheetSectionType =\n | 'tournament-header'\n | 'contacts'\n | 'events'\n | 'entry-info'\n | 'venue-info'\n | 'accommodation'\n | 'transportation'\n | 'hospitality'\n | 'medical'\n | 'regulations'\n | 'prize-money'\n | 'officials'\n | 'sponsors'\n | 'social-events'\n | 'custom-notes';\n\nexport interface FactSheetSection {\n type: FactSheetSectionType;\n title?: string;\n enabled: boolean;\n}\n\nexport interface FactSheetTemplate {\n id: string;\n name: string;\n description: string;\n category: 'itf' | 'national' | 'tour' | 'club' | 'custom';\n headerLayout: HeaderLayout;\n sections: FactSheetSection[];\n}\n\nconst TOURNAMENT_HEADER: FactSheetSectionType = 'tournament-header';\nconst CONTACTS: FactSheetSectionType = 'contacts';\nconst EVENTS: FactSheetSectionType = 'events';\nconst ENTRY_INFO: FactSheetSectionType = 'entry-info';\nconst VENUE_INFO: FactSheetSectionType = 'venue-info';\nconst ACCOMMODATION: FactSheetSectionType = 'accommodation';\nconst TRANSPORTATION: FactSheetSectionType = 'transportation';\nconst HOSPITALITY: FactSheetSectionType = 'hospitality';\nconst MEDICAL: FactSheetSectionType = 'medical';\nconst REGULATIONS: FactSheetSectionType = 'regulations';\nconst PRIZE_MONEY: FactSheetSectionType = 'prize-money';\nconst OFFICIALS: FactSheetSectionType = 'officials';\nconst SPONSORS: FactSheetSectionType = 'sponsors';\nconst SOCIAL_EVENTS: FactSheetSectionType = 'social-events';\nconst CUSTOM_NOTES: FactSheetSectionType = 'custom-notes';\n\nfunction section(type: FactSheetSectionType, enabled = true, title?: string): FactSheetSection {\n return { type, enabled, ...(title && { title }) };\n}\n\nconst FULL_SECTIONS: FactSheetSection[] = [\n section(TOURNAMENT_HEADER),\n section(CONTACTS),\n section(EVENTS),\n section(ENTRY_INFO),\n section(VENUE_INFO),\n section(ACCOMMODATION),\n section(TRANSPORTATION),\n section(HOSPITALITY),\n section(MEDICAL),\n section(REGULATIONS),\n section(PRIZE_MONEY),\n section(OFFICIALS),\n section(SPONSORS),\n section(SOCIAL_EVENTS),\n section(CUSTOM_NOTES),\n];\n\nexport const FACT_SHEET_CATALOG: Record<string, FactSheetTemplate> = {\n 'itf-junior': {\n id: 'itf-junior',\n name: 'ITF Junior',\n description: 'Full fact sheet with all sections — ITF header style',\n category: 'itf',\n headerLayout: 'itf',\n sections: FULL_SECTIONS,\n },\n 'itf-pro-circuit': {\n id: 'itf-pro-circuit',\n name: 'ITF Pro Circuit',\n description: 'Pro circuit fact sheet — contacts, events, entry, venue, prize money, officials',\n category: 'itf',\n headerLayout: 'itf',\n sections: [\n section(TOURNAMENT_HEADER),\n section(CONTACTS),\n section(EVENTS),\n section(ENTRY_INFO),\n section(VENUE_INFO),\n section(PRIZE_MONEY),\n section(OFFICIALS),\n section(REGULATIONS),\n section(CUSTOM_NOTES),\n ],\n },\n 'national-federation': {\n id: 'national-federation',\n name: 'National Federation',\n description: 'Detailed national federation fact sheet with all logistics',\n category: 'national',\n headerLayout: 'national-federation',\n sections: FULL_SECTIONS,\n },\n 'tour-atp-wta': {\n id: 'tour-atp-wta',\n name: 'ATP/WTA Tour',\n description: 'Tour-level fact sheet — contacts, events, prize money, officials, sponsors',\n category: 'tour',\n headerLayout: 'wta-tour',\n sections: [\n section(TOURNAMENT_HEADER),\n section(CONTACTS),\n section(EVENTS),\n section(PRIZE_MONEY),\n section(OFFICIALS),\n section(SPONSORS),\n section(ACCOMMODATION),\n section(TRANSPORTATION),\n section(SOCIAL_EVENTS),\n section(CUSTOM_NOTES),\n ],\n },\n 'club-basic': {\n id: 'club-basic',\n name: 'Club Basic',\n description: 'Simple club-level fact sheet — essentials only',\n category: 'club',\n headerLayout: 'minimal',\n sections: [\n section(TOURNAMENT_HEADER),\n section(CONTACTS),\n section(EVENTS),\n section(ENTRY_INFO),\n section(VENUE_INFO),\n section(CUSTOM_NOTES),\n ],\n },\n};\n\nexport function getFactSheetTemplate(id: string): FactSheetTemplate | undefined {\n return FACT_SHEET_CATALOG[id];\n}\n\nexport function listFactSheetTemplates(category?: string): FactSheetTemplate[] {\n const entries = Object.values(FACT_SHEET_CATALOG);\n return category ? entries.filter((t) => t.category === category) : entries;\n}\n","/**\n * Converts drawsData structures (from tournamentEngine.getEventData())\n * into DrawData for pdf-factory renderers.\n *\n * This is the standard data pipeline for TMX integration:\n * getEventData({ drawId }) → eventData.drawsData → structureToDrawData() → renderer\n */\n\nimport type { DrawData, DrawSlot, DrawMatchUp } from './extractDrawData';\n\n/** Convert a single drawsData structure into DrawData */\nexport function structureToDrawData(struct: any): DrawData {\n const roundMatchUps = struct.roundMatchUps || {};\n const roundProfile = struct.roundProfile || {};\n const roundNumbers = Object.keys(roundMatchUps)\n .map(Number)\n .sort((a, b) => a - b);\n\n // Build slots from all matchUp sides (deduplicate by drawPosition)\n const slotMap = new Map<number, DrawSlot>();\n for (const rn of roundNumbers) {\n for (const mu of roundMatchUps[rn] || []) {\n for (const side of mu.sides || []) {\n if (side?.drawPosition && !slotMap.has(side.drawPosition)) {\n // entryStatus: prefer side-level (future), fall back to participant-level\n const entryStatus = side.entryStatus || side.participant?.entryStatus;\n // Normalize: don't store DIRECT_ACCEPTANCE (the default)\n const displayEntryStatus = entryStatus && entryStatus !== 'DIRECT_ACCEPTANCE' ? entryStatus : undefined;\n\n slotMap.set(side.drawPosition, {\n drawPosition: side.drawPosition,\n participantName: side.participant?.participantName || '',\n nationality: side.participant?.nationalityCode || '',\n seedValue: side.seedValue,\n entryStatus: displayEntryStatus,\n isBye: side.bye === true,\n });\n }\n }\n }\n }\n\n // Build matchUps\n const matchUps: DrawMatchUp[] = [];\n for (const rn of roundNumbers) {\n for (const mu of roundMatchUps[rn] || []) {\n matchUps.push({\n roundNumber: mu.roundNumber,\n roundPosition: mu.roundPosition,\n drawPositions: mu.drawPositions || [],\n score: mu.score?.scoreStringSide1 || '',\n winningSide: mu.winningSide,\n matchUpStatus: mu.matchUpStatus,\n });\n }\n }\n\n // Build roundLabelMap from roundProfile\n const roundLabelMap: Record<number, string> = {};\n for (const rn of roundNumbers) {\n const rp = roundProfile[rn];\n roundLabelMap[rn] = rp?.abbreviatedRoundName || rp?.roundName || `R${rn}`;\n }\n\n const totalRounds = roundNumbers.length > 0 ? Math.max(...roundNumbers) : 0;\n const slots = [...slotMap.values()].sort((a, b) => a.drawPosition - b.drawPosition);\n\n // Qualifying structures don't resolve to a single winner — suppress the winner column\n const isQualifying = struct.stage === 'QUALIFYING';\n // Also detect non-qualifying structures that end with multiple matchUps (no single final)\n const finalRoundMatchUps = roundMatchUps[totalRounds]?.length || 0;\n const noWinnerColumn = isQualifying || finalRoundMatchUps > 1;\n\n return {\n drawName: struct.structureName || '',\n drawSize: slots.length,\n drawType: 'SINGLE_ELIMINATION',\n totalRounds,\n noWinnerColumn,\n slots,\n matchUps,\n seedAssignments: (struct.seedAssignments || [])\n .filter((sa: any) => sa.participantName)\n .map((sa: any) => ({\n seedValue: sa.seedValue,\n participantName: sa.participantName || '',\n nationality: sa.nationalityCode || '',\n })),\n roundLabelMap,\n };\n}\n\n/** Find a structure by stage from drawsData */\nexport function findStructure(drawsData: any[], stage: string): any {\n return drawsData?.[0]?.structures?.find((s: any) => s.stage === stage);\n}\n","import jsPDF from 'jspdf';\nimport type { PageConfig, PageRegions } from '../config/types';\n\nconst PAGE_DIMENSIONS: Record<string, { width: number; height: number }> = {\n a4: { width: 210, height: 297 },\n letter: { width: 216, height: 279 },\n};\n\nexport function createDoc(config: PageConfig, drawSize?: number): jsPDF {\n let orientation = config.orientation;\n if (orientation === 'auto') {\n orientation = drawSize && drawSize >= 32 ? 'landscape' : 'portrait';\n }\n return new jsPDF({ orientation, format: config.pageSize, unit: 'mm' });\n}\n\nexport function getPageRegions(\n doc: jsPDF,\n config: PageConfig,\n headerHeight: number,\n footerHeight: number,\n): PageRegions {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const { margins } = config;\n\n const contentY = margins.top + headerHeight;\n const contentHeight = pageHeight - margins.top - margins.bottom - headerHeight - footerHeight;\n const contentWidth = pageWidth - margins.left - margins.right;\n\n return {\n headerHeight,\n footerHeight,\n contentY,\n contentHeight,\n contentWidth,\n pageWidth,\n pageHeight,\n };\n}\n\nexport function getDefaultPageConfig(): PageConfig {\n return {\n pageSize: 'a4',\n orientation: 'auto',\n margins: { top: 15, right: 10, bottom: 15, left: 10 },\n };\n}\n\nexport { PAGE_DIMENSIONS };\n","import jsPDF from 'jspdf';\n\nexport const FONT = {\n REGULAR: 'helvetica',\n BOLD: 'helvetica',\n} as const;\n\nexport const STYLE = {\n NORMAL: 'normal' as const,\n BOLD: 'bold' as const,\n ITALIC: 'italic' as const,\n};\n\nexport const SIZE = {\n TITLE: 16,\n SUBTITLE: 12,\n HEADING: 10,\n BODY: 8,\n SMALL: 7,\n TINY: 6,\n};\n\nexport function setFont(doc: jsPDF, size: number, style: string = STYLE.NORMAL) {\n doc.setFont(FONT.REGULAR, style);\n doc.setFontSize(size);\n}\n","import jsPDF from 'jspdf';\nimport type { HeaderConfig, PageConfig } from '../config/types';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport function renderHeader(doc: jsPDF, config: HeaderConfig, pageConfig: PageConfig): number {\n switch (config.layout) {\n case 'grand-slam':\n return renderGrandSlamHeader(doc, config, pageConfig);\n case 'itf':\n return renderItfHeader(doc, config, pageConfig);\n case 'minimal':\n return renderMinimalHeader(doc, config, pageConfig);\n case 'wta-tour':\n return renderWtaTourHeader(doc, config, pageConfig);\n case 'national-federation':\n return renderNationalFederationHeader(doc, config, pageConfig);\n case 'none':\n return 0;\n }\n}\n\nfunction renderGrandSlamHeader(doc: jsPDF, config: HeaderConfig, pageConfig: PageConfig): number {\n const { margins } = pageConfig;\n const pageWidth = doc.internal.pageSize.getWidth();\n const rightEdge = pageWidth - margins.right;\n let y = margins.top;\n\n setFont(doc, 18, STYLE.BOLD);\n doc.text(config.tournamentName.toUpperCase(), pageWidth / 2, y, { align: 'center' });\n y += 7;\n\n if (config.subtitle) {\n setFont(doc, 12, STYLE.BOLD);\n doc.text(config.subtitle.toUpperCase(), pageWidth / 2, y, { align: 'center' });\n y += 6;\n }\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n const metaLines: string[] = [];\n if (config.startDate) {\n const dateStr = config.endDate ? `${config.startDate} - ${config.endDate}` : config.startDate;\n metaLines.push(dateStr);\n }\n if (config.location) metaLines.push(config.location);\n metaLines.forEach((line, i) => {\n doc.text(line, rightEdge, margins.top + i * 4, { align: 'right' });\n });\n\n y += 2;\n doc.setDrawColor(0);\n doc.setLineWidth(0.5);\n doc.line(margins.left, y, rightEdge, y);\n y += 3;\n\n return y - margins.top;\n}\n\nfunction renderItfHeader(doc: jsPDF, config: HeaderConfig, pageConfig: PageConfig): number {\n const { margins } = pageConfig;\n const pageWidth = doc.internal.pageSize.getWidth();\n const rightEdge = pageWidth - margins.right;\n let y = margins.top;\n\n setFont(doc, SIZE.TITLE, STYLE.BOLD);\n doc.text(config.tournamentName, margins.left, y);\n y += 6;\n\n if (config.subtitle) {\n setFont(doc, SIZE.SUBTITLE, STYLE.BOLD);\n doc.text(config.subtitle, margins.left, y);\n y += 5;\n }\n\n setFont(doc, SIZE.SMALL, STYLE.NORMAL);\n const rightLines: string[] = [];\n if (config.grade) rightLines.push(`Grade: ${config.grade}`);\n if (config.surface) rightLines.push(`Surface: ${config.surface}`);\n if (config.supervisor) rightLines.push(`Supervisor: ${config.supervisor}`);\n rightLines.forEach((line, i) => {\n doc.text(line, rightEdge, margins.top + i * 3.5, { align: 'right' });\n });\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n const infoLine: string[] = [];\n if (config.startDate) infoLine.push(config.startDate);\n if (config.location) infoLine.push(config.location);\n if (config.organizer) infoLine.push(config.organizer);\n if (infoLine.length) {\n doc.text(infoLine.join(' | '), margins.left, y);\n y += 4;\n }\n\n y += 1;\n doc.setDrawColor(0);\n doc.setLineWidth(0.3);\n doc.line(margins.left, y, rightEdge, y);\n y += 3;\n\n return y - margins.top;\n}\n\nfunction renderMinimalHeader(doc: jsPDF, config: HeaderConfig, pageConfig: PageConfig): number {\n const { margins } = pageConfig;\n let y = margins.top;\n\n setFont(doc, SIZE.SUBTITLE, STYLE.BOLD);\n doc.text(config.tournamentName, margins.left, y);\n const nameWidth = doc.getTextWidth(config.tournamentName);\n\n if (config.subtitle) {\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n doc.text(` - ${config.subtitle}`, margins.left + nameWidth, y);\n }\n\n y += 6;\n return y - margins.top;\n}\n\n/**\n * WTA/ATP Tour header — flanking logos, centered tournament info, section label.\n *\n * Layout:\n * [Left Logo] TOURNAMENT NAME [Right Logo]\n * City, Country\n * Dates | Prize Money | Surface\n * SINGLES MAIN DRAW\n * ─────────────────────────────────────────────────────\n */\nfunction renderWtaTourHeader(doc: jsPDF, config: HeaderConfig, pageConfig: PageConfig): number {\n const { margins } = pageConfig;\n const pageWidth = doc.internal.pageSize.getWidth();\n const rightEdge = pageWidth - margins.right;\n const centerX = pageWidth / 2;\n let y = margins.top;\n\n // Logos (if provided as base64)\n const logoSize = 12;\n if (config.leftLogoBase64) {\n try {\n doc.addImage(config.leftLogoBase64, 'PNG', margins.left, y - 2, logoSize, logoSize);\n } catch {\n /* logo failed to load */\n }\n }\n if (config.rightLogoBase64) {\n try {\n doc.addImage(config.rightLogoBase64, 'PNG', rightEdge - logoSize, y - 2, logoSize, logoSize);\n } catch {\n /* logo failed to load */\n }\n }\n\n // Tournament name — centered, large\n setFont(doc, 14, STYLE.BOLD);\n doc.text(config.tournamentName, centerX, y, { align: 'center' });\n y += 5;\n\n // City, Country\n const cityCountry = [config.city, config.country].filter(Boolean).join(', ');\n if (cityCountry) {\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n doc.setTextColor(80);\n doc.text(cityCountry.toUpperCase(), centerX, y, { align: 'center' });\n doc.setTextColor(0);\n y += 4;\n }\n\n // Dates | Prize Money | Surface\n const detailParts: string[] = [];\n if (config.startDate) {\n const dateStr = config.endDate ? `${config.startDate} - ${config.endDate}` : config.startDate;\n detailParts.push(dateStr);\n }\n if (config.prizeMoney) {\n const money = config.currency ? `${config.currency} ${config.prizeMoney}` : config.prizeMoney;\n detailParts.push(money);\n }\n if (config.surface) detailParts.push(config.surface);\n if (detailParts.length) {\n setFont(doc, SIZE.SMALL, STYLE.NORMAL);\n doc.text(detailParts.join(' | '), centerX, y, { align: 'center' });\n y += 4;\n }\n\n // Section label — right-aligned (e.g., \"SINGLES MAIN DRAW\", \"TOP HALF\")\n if (config.sectionLabel) {\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.text(config.sectionLabel.toUpperCase(), rightEdge, y, { align: 'right' });\n y += 3;\n }\n\n // Separator\n y += 1;\n doc.setDrawColor(0);\n doc.setLineWidth(0.3);\n doc.line(margins.left, y, rightEdge, y);\n y += 3;\n\n return y - margins.top;\n}\n\n/**\n * National Federation header — detailed metadata row.\n *\n * Layout:\n * TOURNAMENT NAME [Federation Logo]\n * Subtitle (event name)\n * Date | Organizer | City | Tournament ID | Grade | Chief Umpire\n * ─────────────────────────────────────────────────────────────\n */\nfunction renderNationalFederationHeader(doc: jsPDF, config: HeaderConfig, pageConfig: PageConfig): number {\n const { margins } = pageConfig;\n const pageWidth = doc.internal.pageSize.getWidth();\n const rightEdge = pageWidth - margins.right;\n let y = margins.top;\n\n // Logo right-aligned\n if (config.rightLogoBase64) {\n try {\n doc.addImage(config.rightLogoBase64, 'PNG', rightEdge - 14, y - 2, 14, 14);\n } catch {\n /* logo failed */\n }\n }\n\n // Tournament name — left, large\n setFont(doc, SIZE.TITLE, STYLE.BOLD);\n doc.text(config.tournamentName, margins.left, y);\n y += 6;\n\n // Subtitle\n if (config.subtitle) {\n setFont(doc, SIZE.HEADING, STYLE.BOLD);\n doc.text(config.subtitle, margins.left, y);\n y += 4;\n }\n\n // Metadata row\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.setTextColor(80);\n const metaParts: string[] = [];\n if (config.startDate) metaParts.push(config.startDate);\n if (config.organizer) metaParts.push(config.organizer);\n if (config.city || config.country) metaParts.push([config.city, config.country].filter(Boolean).join(', '));\n if (config.tournamentId) metaParts.push(`ID: ${config.tournamentId}`);\n if (config.grade) metaParts.push(`Grade: ${config.grade}`);\n if (config.chiefUmpire) metaParts.push(`Umpire: ${config.chiefUmpire}`);\n if (metaParts.length) {\n doc.text(metaParts.join(' | '), margins.left, y);\n y += 3;\n }\n doc.setTextColor(0);\n\n // Separator\n y += 1;\n doc.setDrawColor(0);\n doc.setLineWidth(0.3);\n doc.line(margins.left, y, rightEdge, y);\n y += 3;\n\n return y - margins.top;\n}\n","/**\n * Tournament Bridge — auto-populates HeaderConfig and FooterConfig from tournament record data.\n *\n * This is the bridge between factory's structured data and pdf-factory's rendering configs.\n * Factory provides the data; this module provides the mapping. Factory purity is preserved.\n */\n\nimport type { HeaderConfig, HeaderLayout, FooterConfig, FooterLayout } from '../config/types';\n\ninterface TournamentRecord {\n tournamentId?: string;\n tournamentName?: string;\n formalName?: string;\n startDate?: string;\n endDate?: string;\n hostCountryCode?: string;\n surfaceCategory?: string;\n totalPrizeMoney?: { amount: number; currencyCode: string }[];\n tournamentLevel?: string;\n tournamentTier?: { system?: string; value?: string };\n venues?: Venue[];\n participants?: Participant[];\n registrationProfile?: RegistrationProfile;\n}\n\ninterface Venue {\n venueName?: string;\n addresses?: { city?: string; state?: string; countryCode?: string }[];\n}\n\ninterface Participant {\n participantName?: string;\n participantRole?: string;\n participantRoleResponsibilities?: string[];\n person?: {\n standardGivenName?: string;\n standardFamilyName?: string;\n contacts?: { emailAddress?: string; telephone?: string; mobileTelephone?: string }[];\n };\n}\n\ninterface RegistrationProfile {\n drawCeremonyDate?: string;\n sponsors?: { name: string; tier?: string }[];\n}\n\nfunction formatParticipantName(p: Participant): string {\n const person = p.person;\n if (person?.standardFamilyName) {\n const given = person.standardGivenName || '';\n return given ? person.standardFamilyName + ', ' + given : person.standardFamilyName;\n }\n return p.participantName || '';\n}\n\nfunction findParticipantByRole(participants: Participant[], role: string): Participant | undefined {\n return participants.find((p) => p.participantRole === role);\n}\n\nfunction findOfficialByResponsibility(participants: Participant[], responsibility: string): Participant | undefined {\n return participants.find(\n (p) =>\n p.participantRole === 'OFFICIAL' &&\n p.participantRoleResponsibilities?.some((r) => r.toUpperCase().includes(responsibility.toUpperCase())),\n );\n}\n\nfunction resolveLocation(record: TournamentRecord): string {\n const venue = record.venues?.[0];\n const addr = venue?.addresses?.[0];\n const parts: string[] = [];\n if (addr?.city) parts.push(addr.city);\n if (addr?.state) parts.push(addr.state);\n if (addr?.countryCode || record.hostCountryCode) parts.push(addr?.countryCode || record.hostCountryCode || '');\n return parts.join(', ');\n}\n\nfunction resolveCity(record: TournamentRecord): string | undefined {\n return record.venues?.[0]?.addresses?.[0]?.city;\n}\n\nfunction resolveCountry(record: TournamentRecord): string | undefined {\n return record.venues?.[0]?.addresses?.[0]?.countryCode || record.hostCountryCode;\n}\n\nfunction resolveGrade(record: TournamentRecord): string | undefined {\n if (record.tournamentTier) {\n const tier = record.tournamentTier;\n return tier.system ? tier.system + ' ' + (tier.value || '') : tier.value;\n }\n return record.tournamentLevel;\n}\n\nfunction formatPrizeMoney(record: TournamentRecord): string | undefined {\n const pm = record.totalPrizeMoney?.[0];\n if (!pm) return undefined;\n return String(pm.amount);\n}\n\nfunction formatCurrency(record: TournamentRecord): string | undefined {\n return record.totalPrizeMoney?.[0]?.currencyCode;\n}\n\nexport interface BuildHeaderOptions {\n layout?: HeaderLayout;\n sectionLabel?: string;\n overrides?: Partial<HeaderConfig>;\n}\n\n/**\n * Auto-populate a HeaderConfig from structured tournament data.\n * All fields can be overridden via the overrides parameter.\n */\nexport function buildHeaderFromTournament(record: TournamentRecord, options: BuildHeaderOptions = {}): HeaderConfig {\n const { layout = 'itf', sectionLabel, overrides } = options;\n const participants = record.participants || [];\n\n const director = findParticipantByRole(participants, 'DIRECTOR');\n const referee = findOfficialByResponsibility(participants, 'REFEREE');\n const chiefUmpire =\n findOfficialByResponsibility(participants, 'CHIEF_UMPIRE') || findOfficialByResponsibility(participants, 'UMPIRE');\n const supervisor = findOfficialByResponsibility(participants, 'SUPERVISOR') || referee;\n\n const header: HeaderConfig = {\n layout,\n tournamentName: record.formalName || record.tournamentName || '',\n startDate: record.startDate,\n endDate: record.endDate,\n location: resolveLocation(record),\n city: resolveCity(record),\n country: resolveCountry(record),\n surface: record.surfaceCategory,\n grade: resolveGrade(record),\n tournamentId: record.tournamentId,\n organizer: director ? formatParticipantName(director) : undefined,\n supervisor: supervisor ? formatParticipantName(supervisor) : undefined,\n chiefUmpire: chiefUmpire ? formatParticipantName(chiefUmpire) : undefined,\n prizeMoney: formatPrizeMoney(record),\n currency: formatCurrency(record),\n sectionLabel,\n ...overrides,\n };\n\n return header;\n}\n\nexport interface BuildFooterOptions {\n layout?: FooterLayout;\n seedAssignments?: FooterConfig['seedAssignments'];\n prizeMoney?: FooterConfig['prizeMoney'];\n overrides?: Partial<FooterConfig>;\n}\n\n/**\n * Auto-populate a FooterConfig from structured tournament data.\n * Seed assignments and prize money per round must be passed in since\n * they are draw/event-specific (not on the tournament root).\n */\nexport function buildFooterFromTournament(record: TournamentRecord, options: BuildFooterOptions = {}): FooterConfig {\n const { layout = 'standard', seedAssignments, prizeMoney, overrides } = options;\n const participants = record.participants || [];\n\n const officials = participants.filter((p) => p.participantRole === 'OFFICIAL' || p.participantRole === 'DIRECTOR');\n const signatureLines = officials.map((p) => ({\n role: p.participantRoleResponsibilities?.[0] || p.participantRole || 'Official',\n name: formatParticipantName(p),\n }));\n\n const footer: FooterConfig = {\n layout,\n showPageNumbers: true,\n showTimestamp: true,\n ...(signatureLines.length && { signatureLines }),\n ...(seedAssignments?.length && { seedAssignments }),\n ...(prizeMoney?.length && { prizeMoney }),\n ...(record.registrationProfile?.drawCeremonyDate && {\n drawCeremonyDate: record.registrationProfile.drawCeremonyDate,\n }),\n ...overrides,\n };\n\n return footer;\n}\n","import jsPDF from 'jspdf';\nimport type { FooterConfig, PageConfig } from '../config/types';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport function renderFooter(doc: jsPDF, config: FooterConfig, pageConfig: PageConfig, pageNumber?: number): number {\n switch (config.layout) {\n case 'standard':\n return renderStandardFooter(doc, config, pageConfig, pageNumber);\n case 'seedings':\n case 'seedings-table':\n return renderSeedingsTableFooter(doc, config, pageConfig, pageNumber);\n case 'prize-money':\n return renderPrizeMoneyFooter(doc, config, pageConfig, pageNumber);\n case 'officials':\n case 'officials-signoff':\n return renderOfficialsSignoffFooter(doc, config, pageConfig, pageNumber);\n case 'combined-tour':\n return renderCombinedTourFooter(doc, config, pageConfig, pageNumber);\n case 'none':\n return 0;\n }\n}\n\nexport function measureFooterHeight(config: FooterConfig): number {\n switch (config.layout) {\n case 'standard':\n return 8 + (config.notes?.length || 0) * 3;\n case 'seedings':\n case 'seedings-table': {\n const seedRows = Math.ceil((config.seedAssignments?.length || 0) / 2);\n return 12 + seedRows * 3;\n }\n case 'prize-money':\n return 12 + (config.prizeMoney?.length || 0) * 2.5;\n case 'officials':\n case 'officials-signoff':\n return 12 + (config.signatureLines?.length || config.officials?.length || 0) * 5;\n case 'combined-tour': {\n const seedRows2 = Math.ceil((config.seedAssignments?.length || 0) / 2);\n const prizeRows = config.prizeMoney?.length || 0;\n const mainHeight = Math.max(seedRows2 * 3, prizeRows * 2.5);\n return 16 + mainHeight + (config.withdrawals?.length ? 6 : 0);\n }\n case 'none':\n return 0;\n }\n}\n\n// ---- Standard footer: timestamp + page number + notes ----\n\nfunction renderStandardFooter(doc: jsPDF, config: FooterConfig, pageConfig: PageConfig, pageNumber?: number): number {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const { margins } = pageConfig;\n const rightEdge = pageWidth - margins.right;\n\n let y = pageHeight - margins.bottom;\n\n // Timestamp + page number at the very bottom\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.setTextColor(120);\n if (config.showTimestamp) {\n doc.text(`Generated ${new Date().toLocaleDateString()}`, margins.left, y);\n }\n if (config.showPageNumbers && pageNumber !== undefined) {\n doc.text(`Page ${pageNumber}`, rightEdge, y, { align: 'right' });\n }\n doc.setTextColor(0);\n\n // Separator line above timestamp\n y -= 3;\n doc.setDrawColor(180);\n doc.setLineWidth(0.2);\n doc.line(margins.left, y, rightEdge, y);\n y -= 2;\n\n // Notes above separator\n if (config.notes?.length) {\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(100);\n for (let i = config.notes.length - 1; i >= 0; i--) {\n doc.text(config.notes[i], margins.left, y);\n y -= 3;\n }\n doc.setTextColor(0);\n }\n\n return measureFooterHeight(config);\n}\n\n// ---- Seedings table footer: two-column seed/player list ----\n\nfunction renderSeedingsTableFooter(\n doc: jsPDF,\n config: FooterConfig,\n pageConfig: PageConfig,\n pageNumber?: number,\n): number {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const { margins } = pageConfig;\n const rightEdge = pageWidth - margins.right;\n const footerH = measureFooterHeight(config);\n\n let y = pageHeight - margins.bottom - footerH + 4;\n\n // Separator\n doc.setDrawColor(180);\n doc.setLineWidth(0.2);\n doc.line(margins.left, y, rightEdge, y);\n y += 3;\n\n // Title\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.text('Seeded Players', margins.left, y);\n y += 3;\n\n // Two-column layout\n const seeds = config.seedAssignments || [];\n const halfCol = (rightEdge - margins.left) / 2;\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n\n for (let i = 0; i < seeds.length; i++) {\n const col = i < Math.ceil(seeds.length / 2) ? 0 : 1;\n const row = col === 0 ? i : i - Math.ceil(seeds.length / 2);\n const x = margins.left + col * halfCol;\n const rowY = y + row * 3;\n const s = seeds[i];\n const rankStr = s.ranking ? ` (${s.ranking})` : '';\n doc.text(`${s.seedValue}. ${s.participantName}${rankStr}`, x, rowY);\n }\n\n const seedRows = Math.ceil(seeds.length / 2);\n y += seedRows * 3 + 2;\n\n // Standard footer elements below\n renderFooterBar(doc, config, pageConfig, pageNumber, y);\n\n return footerH;\n}\n\n// ---- Prize money footer: per-round amounts ----\n\nfunction renderPrizeMoneyFooter(doc: jsPDF, config: FooterConfig, pageConfig: PageConfig, pageNumber?: number): number {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const { margins } = pageConfig;\n const rightEdge = pageWidth - margins.right;\n const footerH = measureFooterHeight(config);\n\n let y = pageHeight - margins.bottom - footerH + 4;\n\n doc.setDrawColor(180);\n doc.setLineWidth(0.2);\n doc.line(margins.left, y, rightEdge, y);\n y += 3;\n\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.text('Prize Money', margins.left, y);\n y += 3;\n\n const prizes = config.prizeMoney || [];\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n\n for (const p of prizes) {\n const parts = [p.round];\n if (p.amount) parts.push(p.amount);\n if (p.points) parts.push(`${p.points} pts`);\n doc.text(parts.join(' — '), margins.left, y);\n y += 2.5;\n }\n\n y += 2;\n renderFooterBar(doc, config, pageConfig, pageNumber, y);\n\n return footerH;\n}\n\n// ---- Officials sign-off footer: signature lines + draw ceremony ----\n\nfunction renderOfficialsSignoffFooter(\n doc: jsPDF,\n config: FooterConfig,\n pageConfig: PageConfig,\n pageNumber?: number,\n): number {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const { margins } = pageConfig;\n const rightEdge = pageWidth - margins.right;\n const footerH = measureFooterHeight(config);\n\n let y = pageHeight - margins.bottom - footerH + 4;\n\n doc.setDrawColor(180);\n doc.setLineWidth(0.2);\n doc.line(margins.left, y, rightEdge, y);\n y += 4;\n\n // Draw ceremony date\n if (config.drawCeremonyDate) {\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(80);\n doc.text(`Draw ceremony: ${config.drawCeremonyDate}`, margins.left, y);\n doc.setTextColor(0);\n y += 3;\n }\n\n // Release date\n if (config.releaseDate) {\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(80);\n doc.text(`Released: ${config.releaseDate}`, margins.left, y);\n doc.setTextColor(0);\n y += 3;\n }\n\n // Signature lines\n const lines: { role: string; name?: string }[] =\n config.signatureLines || (config.officials || []).map((name) => ({ role: name }));\n const lineWidth = (rightEdge - margins.left) / Math.min(lines.length, 3);\n\n for (let i = 0; i < lines.length; i++) {\n const col = i % 3;\n const row = Math.floor(i / 3);\n const x = margins.left + col * lineWidth;\n const lineY = y + row * 10;\n\n // Role label\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(100);\n doc.text(lines[i].role, x, lineY);\n doc.setTextColor(0);\n\n // Name (if provided)\n const lineName = lines[i].name;\n if (lineName) {\n setFont(doc, SIZE.TINY, STYLE.BOLD);\n doc.text(lineName, x, lineY + 3);\n }\n\n // Signature line\n doc.setDrawColor(150);\n doc.setLineWidth(0.15);\n doc.line(x, lineY + 5, x + lineWidth - 8, lineY + 5);\n }\n\n const rows = Math.ceil(lines.length / 3);\n y += rows * 10 + 2;\n\n renderFooterBar(doc, config, pageConfig, pageNumber, y);\n\n return footerH;\n}\n\n// ---- Combined tour footer: seedings + prize money + officials (WTA/ATP style) ----\n\nfunction renderCombinedTourFooter(\n doc: jsPDF,\n config: FooterConfig,\n pageConfig: PageConfig,\n pageNumber?: number,\n): number {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const { margins } = pageConfig;\n const rightEdge = pageWidth - margins.right;\n const footerH = measureFooterHeight(config);\n\n let y = pageHeight - margins.bottom - footerH + 4;\n\n doc.setDrawColor(180);\n doc.setLineWidth(0.2);\n doc.line(margins.left, y, rightEdge, y);\n y += 3;\n\n const contentWidth = rightEdge - margins.left;\n const leftColX = margins.left;\n const rightColX = margins.left + contentWidth * 0.55;\n let leftY = y;\n let rightY = y;\n\n // Left column: seeded players\n const seeds = config.seedAssignments || [];\n if (seeds.length) {\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.text('Seeded Players', leftColX, leftY);\n leftY += 3;\n\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n for (const s of seeds) {\n const rankStr = s.ranking ? ` (${s.ranking})` : '';\n doc.text(`${s.seedValue}. ${s.participantName}${rankStr}`, leftColX, leftY);\n leftY += 2.5;\n }\n }\n\n // Right column: prize money\n const prizes = config.prizeMoney || [];\n if (prizes.length) {\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.text('Prize Money', rightColX, rightY);\n rightY += 3;\n\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n for (const p of prizes) {\n const parts = [p.round];\n if (p.amount) parts.push(p.amount);\n if (p.points) parts.push(`${p.points} pts`);\n doc.text(parts.join(' — '), rightColX, rightY);\n rightY += 2.5;\n }\n }\n\n y = Math.max(leftY, rightY) + 2;\n\n // Withdrawals\n if (config.withdrawals?.length) {\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(80);\n const wdText = config.withdrawals.map((w) => (w.reason ? `${w.name} (${w.reason})` : w.name)).join(', ');\n doc.text(`Withdrawals: ${wdText}`, margins.left, y, { maxWidth: contentWidth });\n doc.setTextColor(0);\n y += 3;\n }\n\n // Lucky losers\n if (config.luckyLosers?.length) {\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(80);\n doc.text(`Lucky Losers: ${config.luckyLosers.join(', ')}`, margins.left, y, { maxWidth: contentWidth });\n doc.setTextColor(0);\n y += 3;\n }\n\n // Supervisor + release date\n if (config.officials?.length) {\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.setTextColor(80);\n doc.text(config.officials.join(' | '), margins.left, y);\n doc.setTextColor(0);\n y += 3;\n }\n\n renderFooterBar(doc, config, pageConfig, pageNumber, y);\n\n return footerH;\n}\n\n// ---- Shared footer bar: timestamp + page number at the very bottom ----\n\nfunction renderFooterBar(\n doc: jsPDF,\n config: FooterConfig,\n pageConfig: PageConfig,\n pageNumber?: number,\n _y?: number,\n): void {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const { margins } = pageConfig;\n const rightEdge = pageWidth - margins.right;\n const y = pageHeight - margins.bottom + 2;\n\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.setTextColor(120);\n\n if (config.showTimestamp) {\n doc.text(`Generated ${new Date().toLocaleDateString()}`, margins.left, y);\n }\n if (config.releaseDate) {\n const relX = config.showTimestamp ? margins.left + 50 : margins.left;\n doc.text(`Released: ${config.releaseDate}`, relX, y);\n }\n if (config.showPageNumbers && pageNumber !== undefined) {\n doc.text(`Page ${pageNumber}`, rightEdge, y, { align: 'right' });\n }\n\n doc.setTextColor(0);\n}\n","/**\n * Seeded players table for draw sheet footers.\n *\n * Renders a compact multi-column list of seeded players,\n * similar to what appears at the bottom of WTA/ITF/Grand Slam draw sheets.\n */\n\nimport jsPDF from 'jspdf';\nimport type { DrawFormatConfig } from '../config/types';\nimport type { DrawData } from '../core/extractDrawData';\nimport { setFont, STYLE } from '../layout/fonts';\n\nconst SEED_FONT_SIZE = 5;\nconst SEED_LINE_HEIGHT = 2.5;\n\nexport function renderSeedingsFooter(doc: jsPDF, drawData: DrawData, format: DrawFormatConfig, startY: number): number {\n const seeds = drawData.seedAssignments;\n if (!seeds.length) return startY;\n\n const margins = format.page.margins;\n const pageWidth = doc.internal.pageSize.getWidth();\n const availableWidth = pageWidth - margins.left - margins.right;\n\n // Title\n setFont(doc, SEED_FONT_SIZE + 1, STYLE.BOLD);\n doc.text('Seeded players', margins.left, startY);\n\n // Separator line\n doc.setDrawColor(150);\n doc.setLineWidth(0.15);\n doc.line(margins.left, startY + 1, margins.left + availableWidth * 0.5, startY + 1);\n startY += 3;\n\n // Split seeds into 2 columns\n const half = Math.ceil(seeds.length / 2);\n const col1 = seeds.slice(0, half);\n const col2 = seeds.slice(half);\n const colWidth = availableWidth * 0.25;\n\n let y = startY;\n for (let i = 0; i < Math.max(col1.length, col2.length); i++) {\n if (col1[i]) {\n renderSeedEntry(doc, col1[i], margins.left, y, colWidth);\n }\n if (col2[i]) {\n renderSeedEntry(doc, col2[i], margins.left + colWidth + 4, y, colWidth);\n }\n y += SEED_LINE_HEIGHT;\n }\n\n return y;\n}\n\nfunction renderSeedEntry(\n doc: jsPDF,\n seed: { seedValue: number; participantName: string; nationality: string },\n x: number,\n y: number,\n _maxWidth: number,\n): void {\n setFont(doc, SEED_FONT_SIZE, STYLE.BOLD);\n doc.text(`${seed.seedValue}`, x + 4, y, { align: 'right' });\n\n setFont(doc, SEED_FONT_SIZE, STYLE.NORMAL);\n doc.text(seed.participantName, x + 6, y);\n\n doc.setTextColor(100);\n doc.text(seed.nationality, x + 45, y);\n doc.setTextColor(0);\n}\n\nexport function measureSeedingsHeight(seedCount: number): number {\n if (seedCount === 0) return 0;\n const rows = Math.ceil(seedCount / 2);\n return 4 + rows * SEED_LINE_HEIGHT;\n}\n","/**\n * Print dispatcher — the main entry point for TMX integration.\n *\n * Takes a PrintRequest from a modal and produces a PDF.\n * Uses the CompositionConfig from the request to configure\n * headers, footers, format presets, and content options.\n */\n\nimport jsPDF from 'jspdf';\nimport type { PrintRequest } from './printModalTypes';\n\nexport interface PrintResult {\n success: boolean;\n doc?: jsPDF;\n blob?: Blob;\n filename?: string;\n error?: string;\n}\n\n/**\n * Execute a print request and return the PDF.\n *\n * The caller (TMX) provides tournament data via the factory engine —\n * this function extracts the needed data using the factory queries\n * and generates the appropriate PDF.\n *\n * Usage in TMX:\n * ```typescript\n * import { executePrint } from 'pdf-factory';\n * import { tournamentEngine } from 'tods-competition-factory';\n *\n * const result = executePrint(printRequest, { tournamentEngine });\n * if (result.success && result.blob) {\n * window.open(URL.createObjectURL(result.blob));\n * }\n * ```\n */\nexport function executePrint(request: PrintRequest, _engine: { tournamentEngine: any }): PrintResult {\n // This is a placeholder — each type will be implemented\n // as the TMX integration progresses.\n // For now it validates the request structure.\n\n if (!request.type) return { success: false, error: 'Missing request type' };\n if (!request.composition) return { success: false, error: 'Missing composition config' };\n\n const filename = generateFilename(request);\n\n return {\n success: true,\n filename,\n // doc and blob will be populated by the specific generator\n };\n}\n\nfunction generateFilename(request: PrintRequest): string {\n const timestamp = new Date().toISOString().slice(0, 10);\n switch (request.type) {\n case 'draw':\n return `draw-${timestamp}.pdf`;\n case 'schedule':\n return `order-of-play-${request.scheduledDate || timestamp}.pdf`;\n case 'playerList':\n return `player-list-${timestamp}.pdf`;\n case 'courtCards':\n return `court-cards-${timestamp}.pdf`;\n case 'signInSheet':\n return `sign-in-sheet-${timestamp}.pdf`;\n case 'matchCard':\n return `match-cards-${timestamp}.pdf`;\n }\n}\n","/**\n * Composition Editor types.\n *\n * These types define the interface for a visual editor that allows\n * tournament directors to design PDF layouts — selecting header styles,\n * footer content, page orientation, format presets, and content options.\n *\n * The editor produces a CompositionConfig which drives PDF generation.\n * This config can be saved per-tournament and reused.\n */\n\nimport type {\n HeaderConfig,\n FooterConfig,\n PageConfig,\n DrawFormatConfig,\n HeaderLayout,\n FooterLayout,\n} from '../config/types';\n\n// --- Composition Config (output of the editor) ---\n\nexport interface CompositionConfig {\n id?: string;\n name: string;\n description?: string;\n\n page: PageConfig;\n header: HeaderConfig;\n footer: FooterConfig;\n format: DrawFormatConfig;\n\n // Content options\n content: ContentOptions;\n\n // Metadata\n createdAt?: string;\n updatedAt?: string;\n}\n\nexport interface ContentOptions {\n // Draw sheet options\n draw?: {\n includeSeedings: boolean;\n includeScores: boolean;\n splitStrategy: 'single-page' | 'halves' | 'quarters';\n showDrawPositions: boolean;\n showByes: boolean;\n };\n\n // Schedule/OOP options\n schedule?: {\n cellStyle: 'detailed' | 'compact';\n showMatchNumbers: boolean;\n alertBanner?: string;\n showPotentialParticipants: boolean;\n };\n\n // Player list options\n playerList?: {\n includeRanking: boolean;\n includeEvents: boolean;\n groupByEvent: boolean;\n showSignInStatus: boolean;\n };\n\n // Court card options\n courtCard?: {\n showNextMatch: boolean;\n showVenueName: boolean;\n cardsPerPage: number;\n };\n}\n\n// --- Editor State (for the UI) ---\n\nexport interface EditorState {\n activeTab: 'page' | 'header' | 'footer' | 'content' | 'preview';\n config: CompositionConfig;\n previewData?: PreviewData;\n isDirty: boolean;\n}\n\nexport interface PreviewData {\n type: 'draw' | 'schedule' | 'playerList' | 'courtCard' | 'signInSheet' | 'matchCard';\n pdfBlob?: Blob;\n previewUrl?: string;\n}\n\n// --- Preset Templates ---\n\nexport interface CompositionTemplate {\n id: string;\n name: string;\n description: string;\n category: 'grand-slam' | 'itf' | 'national' | 'club' | 'custom';\n config: CompositionConfig;\n}\n\n// --- Editor Options (available choices) ---\n\nexport const HEADER_LAYOUT_OPTIONS: { value: HeaderLayout; label: string; description: string }[] = [\n { value: 'grand-slam', label: 'Grand Slam', description: 'Centered tournament name, uppercase, date/location right' },\n {\n value: 'itf',\n label: 'ITF/Professional',\n description: 'Left-aligned name, grade/supervisor on right, separator line',\n },\n { value: 'minimal', label: 'Minimal', description: 'Single line with tournament name and subtitle' },\n { value: 'none', label: 'No Header', description: 'Skip header entirely' },\n];\n\nexport const FOOTER_LAYOUT_OPTIONS: { value: FooterLayout; label: string; description: string }[] = [\n { value: 'standard', label: 'Standard', description: 'Timestamp, page number, optional notes' },\n { value: 'seedings', label: 'Seedings Table', description: 'Seeded players list in compact columns' },\n { value: 'officials', label: 'Officials', description: 'Tournament officials with roles' },\n { value: 'none', label: 'No Footer', description: 'Skip footer entirely' },\n];\n\nexport const PAGE_SIZE_OPTIONS = [\n { value: 'a4', label: 'A4 (210 × 297mm)' },\n { value: 'letter', label: 'US Letter (216 × 279mm)' },\n];\n\nexport const ORIENTATION_OPTIONS = [\n { value: 'auto', label: 'Auto (landscape for large draws)' },\n { value: 'landscape', label: 'Landscape' },\n { value: 'portrait', label: 'Portrait' },\n];\n\nexport const SPLIT_STRATEGY_OPTIONS = [\n { value: 'single-page', label: 'Single Page (dense)' },\n { value: 'halves', label: 'Two Halves (64+64)' },\n { value: 'quarters', label: 'Four Quarters (32×4)' },\n];\n","/**\n * Print Modal types — defines the request/response shapes for TMX print integration.\n *\n * A PrintRequest describes what to print and how.\n * PrintModalConfig/Tab/Field describe the modal UI for configuring print options.\n */\n\nimport type { CompositionConfig } from './editorTypes';\n\n// --- Print Requests ---\n\nexport type PrintRequest =\n | PrintDrawRequest\n | PrintScheduleRequest\n | PrintPlayerListRequest\n | PrintCourtCardsRequest\n | PrintSignInSheetRequest\n | PrintMatchCardRequest;\n\nexport interface PrintDrawRequest {\n type: 'draw';\n drawId: string;\n eventId: string;\n composition: CompositionConfig;\n}\n\nexport interface PrintScheduleRequest {\n type: 'schedule';\n scheduledDate: string;\n venueId?: string;\n composition: CompositionConfig;\n}\n\nexport interface PrintPlayerListRequest {\n type: 'playerList';\n eventId?: string;\n composition: CompositionConfig;\n}\n\nexport interface PrintCourtCardsRequest {\n type: 'courtCards';\n venueId?: string;\n scheduledDate?: string;\n composition: CompositionConfig;\n}\n\nexport interface PrintSignInSheetRequest {\n type: 'signInSheet';\n eventId: string;\n composition: CompositionConfig;\n}\n\nexport interface PrintMatchCardRequest {\n type: 'matchCard';\n matchUpIds: string[];\n composition: CompositionConfig;\n}\n\n// --- Print Result ---\n\nexport interface PrintResult {\n success: boolean;\n doc?: any;\n blob?: Blob;\n filename?: string;\n error?: string;\n}\n\n// --- Modal Configuration ---\n\nexport interface PrintModalConfig {\n title: string;\n tabs: PrintModalTab[];\n}\n\nexport interface PrintModalTab {\n id: string;\n label: string;\n icon?: string;\n fields: PrintModalField[];\n}\n\nexport interface PrintModalField {\n id: string;\n label: string;\n type: 'select' | 'checkbox' | 'text' | 'number';\n options?: { value: string; label: string }[];\n defaultValue?: any;\n configPath: string;\n}\n\n// --- Modal Tab Presets ---\n\nexport const DRAW_MODAL_TABS: PrintModalTab[] = [\n {\n id: 'content',\n label: 'Content',\n fields: [\n {\n id: 'includeSeedings',\n label: 'Include seedings',\n type: 'checkbox',\n defaultValue: true,\n configPath: 'content.draw.includeSeedings',\n },\n {\n id: 'includeScores',\n label: 'Include scores',\n type: 'checkbox',\n defaultValue: true,\n configPath: 'content.draw.includeScores',\n },\n {\n id: 'showDrawPositions',\n label: 'Show draw positions',\n type: 'checkbox',\n defaultValue: true,\n configPath: 'content.draw.showDrawPositions',\n },\n { id: 'showByes', label: 'Show byes', type: 'checkbox', defaultValue: true, configPath: 'content.draw.showByes' },\n {\n id: 'splitStrategy',\n label: 'Split strategy',\n type: 'select',\n options: [\n { value: 'single-page', label: 'Single page' },\n { value: 'halves', label: 'Split in halves' },\n { value: 'quarters', label: 'Split in quarters' },\n ],\n defaultValue: 'single-page',\n configPath: 'content.draw.splitStrategy',\n },\n ],\n },\n {\n id: 'layout',\n label: 'Layout',\n fields: [\n {\n id: 'headerLayout',\n label: 'Header style',\n type: 'select',\n options: [\n { value: 'itf', label: 'ITF' },\n { value: 'minimal', label: 'Minimal' },\n { value: 'branded', label: 'Branded' },\n ],\n defaultValue: 'itf',\n configPath: 'header.layout',\n },\n {\n id: 'orientation',\n label: 'Orientation',\n type: 'select',\n options: [\n { value: 'landscape', label: 'Landscape' },\n { value: 'portrait', label: 'Portrait' },\n ],\n defaultValue: 'landscape',\n configPath: 'page.orientation',\n },\n ],\n },\n];\n\nexport const SCHEDULE_MODAL_TABS: PrintModalTab[] = [\n {\n id: 'content',\n label: 'Content',\n fields: [\n {\n id: 'cellStyle',\n label: 'Cell style',\n type: 'select',\n options: [\n { value: 'detailed', label: 'Detailed' },\n { value: 'compact', label: 'Compact' },\n ],\n defaultValue: 'detailed',\n configPath: 'content.schedule.cellStyle',\n },\n {\n id: 'showMatchNumbers',\n label: 'Show match numbers',\n type: 'checkbox',\n defaultValue: false,\n configPath: 'content.schedule.showMatchNumbers',\n },\n { id: 'alertBanner', label: 'Alert banner text', type: 'text', configPath: 'content.schedule.alertBanner' },\n ],\n },\n {\n id: 'layout',\n label: 'Layout',\n fields: [\n {\n id: 'headerLayout',\n label: 'Header style',\n type: 'select',\n options: [\n { value: 'itf', label: 'ITF' },\n { value: 'minimal', label: 'Minimal' },\n { value: 'branded', label: 'Branded' },\n ],\n defaultValue: 'itf',\n configPath: 'header.layout',\n },\n ],\n },\n];\n","export function participantName(participant: any): string {\n if (!participant) return '';\n\n if (participant.person) {\n const { standardFamilyName, standardGivenName } = participant.person;\n if (standardFamilyName) {\n return `${standardFamilyName.toUpperCase()}, ${standardGivenName || ''}`.trim();\n }\n }\n\n return participant.participantName || '';\n}\n\nexport function nationality(participant: any): string {\n if (!participant) return '';\n return participant.person?.nationalityCode || '';\n}\n\nexport function seedDisplay(seedValue: any): string {\n if (!seedValue) return '';\n return `[${seedValue}]`;\n}\n\nexport function entryStatusDisplay(entryStatus: string): string {\n if (!entryStatus) return '';\n const map: Record<string, string> = {\n DIRECT_ACCEPTANCE: 'DA',\n WILDCARD: 'WC',\n LUCKY_LOSER: 'LL',\n QUALIFIER: 'Q',\n ALTERNATE: 'A',\n SPECIAL_EXEMPT: 'SE',\n };\n return map[entryStatus] || entryStatus;\n}\n\nexport function formatScore(score: any): string {\n if (!score) return '';\n if (typeof score === 'string') return score;\n if (score.scoreStringSide1) return score.scoreStringSide1;\n return '';\n}\n\nexport function formatDate(dateStr: string): string {\n if (!dateStr) return '';\n const d = new Date(dateStr + 'T00:00:00');\n return d.toLocaleDateString('en-US', { day: '2-digit', month: 'short', year: 'numeric' });\n}\n\nexport function formatTime(timeStr: string): string {\n if (!timeStr) return '';\n const [h, m] = timeStr.split(':');\n const hour = parseInt(h);\n const ampm = hour >= 12 ? 'PM' : 'AM';\n let hour12 = hour;\n if (hour === 0) hour12 = 12;\n else if (hour > 12) hour12 = hour - 12;\n return `${hour12}:${m} ${ampm}`;\n}\n\nexport function eventAbbreviation(eventName: string): string {\n if (!eventName) return '';\n return eventName\n .split(/\\s+/)\n .map((w) => w[0])\n .join('')\n .toUpperCase();\n}\n\nexport function roundName(roundNumber: number, totalRounds: number): string {\n const remaining = totalRounds - roundNumber + 1;\n if (remaining === 1) return 'F';\n if (remaining === 2) return 'SF';\n if (remaining === 3) return 'QF';\n return `R${Math.pow(2, remaining)}`;\n}\n","import { participantName, nationality, formatScore, roundName } from '../utils/primitives';\n\nexport interface DrawSlot {\n drawPosition: number;\n participantName: string;\n nationality: string;\n seedValue?: number;\n entryStatus?: string;\n isBye?: boolean;\n}\n\nexport interface DrawMatchUp {\n roundNumber: number;\n roundPosition: number;\n drawPositions: number[];\n score?: string;\n winningSide?: number;\n matchUpStatus?: string;\n}\n\nexport interface DrawData {\n drawName: string;\n drawSize: number;\n drawType: string;\n totalRounds: number;\n slots: DrawSlot[];\n matchUps: DrawMatchUp[];\n seedAssignments: { seedValue: number; participantName: string; nationality: string }[];\n roundLabelMap?: Record<number, string>;\n noWinnerColumn?: boolean;\n}\n\nexport function extractDrawData(params: {\n drawDefinition: any;\n participants?: any[];\n structureId?: string;\n processedMatchUps?: any[];\n}): DrawData {\n const { drawDefinition, participants = [] } = params;\n if (!drawDefinition) return emptyDrawData();\n\n const structure = params.structureId\n ? drawDefinition.structures?.find((s: any) => s.structureId === params.structureId)\n : drawDefinition.structures?.[0];\n\n if (!structure) return emptyDrawData();\n\n const participantMap = new Map<string, any>();\n participants.forEach((p: any) => participantMap.set(p.participantId, p));\n\n const positionAssignments = structure.positionAssignments || [];\n const matchUpsRaw = structure.matchUps || [];\n const maxRound = matchUpsRaw.reduce((max: number, mu: any) => Math.max(max, mu.roundNumber || 0), 0);\n\n // For sub-structures (consolation, backdraw), use position count and actual round count\n // rather than the main drawDefinition.drawSize which refers to the overall draw\n const drawSize = params.structureId\n ? positionAssignments.length\n : drawDefinition.drawSize || positionAssignments.length;\n const totalRounds = params.structureId ? maxRound : Math.log2(drawSize);\n\n // seedAssignments live on the structure, not the drawDefinition\n const structureSeedAssignments = structure.seedAssignments || [];\n\n const slots: DrawSlot[] = positionAssignments.map((pa: any) => {\n const participant = pa.participantId ? participantMap.get(pa.participantId) : undefined;\n const seedAssignment = structureSeedAssignments.find((sa: any) => sa.participantId === pa.participantId);\n\n return {\n drawPosition: pa.drawPosition,\n participantName: participant ? participantName(participant) : '',\n nationality: participant ? nationality(participant) : '',\n seedValue: seedAssignment?.seedValue,\n entryStatus: pa.entryStatus,\n isBye: pa.bye === true,\n };\n });\n\n const matchUps: DrawMatchUp[] = (structure.matchUps || []).map((mu: any) => ({\n roundNumber: mu.roundNumber,\n roundPosition: mu.roundPosition,\n drawPositions: mu.drawPositions || [],\n score: formatScore(mu.score),\n winningSide: mu.winningSide,\n matchUpStatus: mu.matchUpStatus,\n }));\n\n const seedAssignments = structureSeedAssignments\n .filter((sa: any) => sa.participantId)\n .map((sa: any) => {\n const participant = participantMap.get(sa.participantId);\n return {\n seedValue: sa.seedValue,\n participantName: participant ? participantName(participant) : '',\n nationality: participant ? nationality(participant) : '',\n };\n })\n .sort((a: any, b: any) => a.seedValue - b.seedValue);\n\n // Build round label map from engine-processed matchUps (preferred) or heuristic\n const roundLabelMap = buildRoundLabelMap(matchUps, totalRounds, params.processedMatchUps);\n\n return {\n drawName: drawDefinition.drawName || '',\n drawSize,\n drawType: drawDefinition.drawType || 'SINGLE_ELIMINATION',\n totalRounds,\n slots,\n matchUps,\n seedAssignments,\n roundLabelMap,\n };\n}\n\nexport function getRoundLabel(roundNumber: number, totalRounds: number): string {\n return roundName(roundNumber, totalRounds);\n}\n\nfunction buildRoundLabelMap(\n matchUps: DrawMatchUp[],\n totalRounds: number,\n processedMatchUps?: any[],\n): Record<number, string> {\n // Use engine-provided roundName/abbreviatedRoundName when available\n if (processedMatchUps?.length) {\n const map: Record<number, string> = {};\n for (const mu of processedMatchUps) {\n if (mu.roundNumber && !map[mu.roundNumber]) {\n map[mu.roundNumber] = mu.abbreviatedRoundName || mu.roundName || `R${mu.roundNumber}`;\n }\n }\n if (Object.keys(map).length > 0) return map;\n }\n\n // Fallback: count matches per round\n const roundCounts = new Map<number, number>();\n for (const mu of matchUps) {\n roundCounts.set(mu.roundNumber, (roundCounts.get(mu.roundNumber) || 0) + 1);\n }\n\n const rounds = [...roundCounts.keys()].sort((a, b) => a - b);\n const isPowerOf2 =\n rounds.length > 0 &&\n rounds.every((r, i) => {\n if (i === 0) return true;\n const prev = roundCounts.get(rounds[i - 1]) || 0;\n const curr = roundCounts.get(r) || 0;\n return curr <= Math.ceil(prev / 2);\n });\n\n // Standard single-elimination: use traditional labels\n if (isPowerOf2) {\n const map: Record<number, string> = {};\n for (const r of rounds) {\n map[r] = roundName(r, totalRounds);\n }\n return map;\n }\n\n // Feed structure: simple round number labels as fallback\n const map: Record<number, string> = {};\n for (const r of rounds) {\n map[r] = `R${r}`;\n }\n return map;\n}\n\nfunction emptyDrawData(): DrawData {\n return {\n drawName: '',\n drawSize: 0,\n drawType: '',\n totalRounds: 0,\n slots: [],\n matchUps: [],\n seedAssignments: [],\n };\n}\n","import { participantName, nationality, formatScore, formatTime, eventAbbreviation } from '../utils/primitives';\n\nexport interface ScheduleMatch {\n courtName: string;\n scheduledTime: string;\n eventName: string;\n eventAbbr: string;\n roundName: string;\n side1: { name: string; nationality: string };\n side2: { name: string; nationality: string };\n score?: string;\n matchUpStatus?: string;\n notBeforeTime?: string;\n}\n\nexport interface ScheduleTimeSlot {\n time: string;\n label: string;\n matches: ScheduleMatch[];\n}\n\nexport interface ScheduleData {\n scheduledDate: string;\n courts: string[];\n timeSlots: ScheduleTimeSlot[];\n}\n\nexport function extractScheduleData(params: {\n matchUps?: any[];\n venues?: any[];\n scheduledDate?: string;\n}): ScheduleData {\n const { matchUps = [], venues = [], scheduledDate = '' } = params;\n\n const courtNames = new Set<string>();\n venues.forEach((v: any) => {\n (v.courts || []).forEach((c: any) => {\n courtNames.add(c.courtName || `Court ${c.courtId}`);\n });\n });\n\n const courtMap = new Map<string, string>();\n venues.forEach((v: any) => {\n (v.courts || []).forEach((c: any) => {\n courtMap.set(c.courtId, c.courtName || `Court ${c.courtId}`);\n });\n });\n\n const scheduled = matchUps.filter((mu: any) => mu.schedule?.scheduledDate === scheduledDate || !scheduledDate);\n\n const timeMap = new Map<string, ScheduleMatch[]>();\n\n for (const mu of scheduled) {\n const schedule = mu.schedule || {};\n const time = schedule.scheduledTime || '00:00';\n const courtId = schedule.venueCourtId || schedule.courtId || '';\n const courtName = courtMap.get(courtId) || courtId;\n\n if (courtName) courtNames.add(courtName);\n\n const sides = mu.sides || [];\n const side1 = extractSide(sides[0]);\n const side2 = extractSide(sides[1]);\n\n const match: ScheduleMatch = {\n courtName,\n scheduledTime: formatTime(time),\n eventName: mu.eventName || mu.event?.eventName || '',\n eventAbbr: eventAbbreviation(mu.eventName || mu.event?.eventName || ''),\n roundName: mu.roundName || '',\n side1,\n side2,\n score: formatScore(mu.score),\n matchUpStatus: mu.matchUpStatus,\n notBeforeTime: schedule.notBeforeTime ? formatTime(schedule.notBeforeTime) : undefined,\n };\n\n const key = schedule.notBeforeTime || time;\n if (!timeMap.has(key)) timeMap.set(key, []);\n timeMap.get(key)!.push(match);\n }\n\n const sortedTimes = [...timeMap.keys()].sort();\n const timeSlots: ScheduleTimeSlot[] = sortedTimes.map((time) => ({\n time,\n label: formatTime(time) || 'TBD',\n matches: timeMap.get(time) || [],\n }));\n\n return {\n scheduledDate,\n courts: [...courtNames].sort(),\n timeSlots,\n };\n}\n\nfunction extractSide(side: any): { name: string; nationality: string } {\n if (!side) return { name: '', nationality: '' };\n const participant = side.participant;\n if (!participant) return { name: '', nationality: '' };\n return {\n name: participantName(participant),\n nationality: nationality(participant),\n };\n}\n","import { participantName, nationality, entryStatusDisplay } from '../utils/primitives';\n\nexport interface ParticipantRow {\n name: string;\n nationality: string;\n ranking?: string;\n seedValue?: number;\n entryStatus: string;\n events: string[];\n signedIn?: boolean;\n}\n\nexport function extractParticipantData(params: {\n participants?: any[];\n eventEntries?: { eventName: string; entries: any[] }[];\n}): ParticipantRow[] {\n const { participants = [], eventEntries = [] } = params;\n\n const entryMap = new Map<string, { events: string[]; entryStatus: string; seedValue?: number }>();\n\n for (const { eventName, entries } of eventEntries) {\n for (const entry of entries) {\n const id = entry.participantId;\n if (!entryMap.has(id)) {\n entryMap.set(id, { events: [], entryStatus: '', seedValue: undefined });\n }\n const record = entryMap.get(id)!;\n record.events.push(eventName);\n if (entry.entryStatus) record.entryStatus = entry.entryStatus;\n }\n }\n\n return participants\n .filter((p: any) => p.participantType === 'INDIVIDUAL')\n .map((p: any) => {\n const entry = entryMap.get(p.participantId);\n return {\n name: participantName(p),\n nationality: nationality(p),\n ranking: p.rankings?.[0]?.ranking?.toString() || '',\n seedValue: entry?.seedValue,\n entryStatus: entryStatusDisplay(entry?.entryStatus || ''),\n events: entry?.events || [],\n signedIn: p.signInStatus === 'SIGNED_IN',\n };\n })\n .sort((a, b) => a.name.localeCompare(b.name));\n}\n","import { participantName, nationality, formatTime } from '../utils/primitives';\n\nexport interface CourtCardData {\n courtName: string;\n venueName?: string;\n currentMatch?: CourtCardMatch;\n nextMatch?: CourtCardMatch;\n}\n\nexport interface CourtCardMatch {\n eventName: string;\n roundName: string;\n scheduledTime?: string;\n side1: { name: string; nationality: string };\n side2: { name: string; nationality: string };\n}\n\nexport function extractCourtCardData(params: {\n matchUps?: any[];\n venues?: any[];\n scheduledDate?: string;\n}): CourtCardData[] {\n const { matchUps = [], venues = [] } = params;\n\n const courtMap = new Map<string, { courtName: string; venueName: string }>();\n venues.forEach((v: any) => {\n (v.courts || []).forEach((c: any) => {\n courtMap.set(c.courtId, {\n courtName: c.courtName || `Court ${c.courtId}`,\n venueName: v.venueName || '',\n });\n });\n });\n\n // Group matchUps by court\n const courtMatchUps = new Map<string, any[]>();\n for (const mu of matchUps) {\n const courtId = mu.schedule?.venueCourtId || mu.schedule?.courtId;\n if (!courtId) continue;\n if (!courtMatchUps.has(courtId)) courtMatchUps.set(courtId, []);\n courtMatchUps.get(courtId)!.push(mu);\n }\n\n const cards: CourtCardData[] = [];\n\n for (const [courtId, matches] of courtMatchUps) {\n const courtInfo = courtMap.get(courtId) || { courtName: courtId, venueName: '' };\n\n // Sort by scheduled time\n matches.sort((a: any, b: any) => {\n const ta = a.schedule?.scheduledTime || '';\n const tb = b.schedule?.scheduledTime || '';\n return ta.localeCompare(tb);\n });\n\n // Find current (IN_PROGRESS or first upcoming) and next\n const completedStatuses = new Set(['COMPLETED', 'RETIRED', 'WALKOVER', 'DEFAULTED', 'ABANDONED']);\n const inProgress = matches.find((m: any) => m.matchUpStatus === 'IN_PROGRESS');\n const upcoming = matches.filter((m: any) => !completedStatuses.has(m.matchUpStatus));\n const completed = matches.filter((m: any) => completedStatuses.has(m.matchUpStatus));\n\n // Prefer in-progress, then first upcoming, then most recent completed\n const currentMu = inProgress || upcoming[0] || completed.at(-1);\n\n let nextMu;\n if (inProgress) {\n nextMu = upcoming[0];\n } else if (upcoming.length > 1) {\n nextMu = upcoming[1];\n }\n\n cards.push({\n courtName: courtInfo.courtName,\n venueName: courtInfo.venueName,\n currentMatch: currentMu ? mapCourtCardMatch(currentMu) : undefined,\n nextMatch: nextMu ? mapCourtCardMatch(nextMu) : undefined,\n });\n }\n\n return cards.sort((a, b) => a.courtName.localeCompare(b.courtName));\n}\n\nfunction mapCourtCardMatch(mu: any): CourtCardMatch {\n const sides = mu.sides || [];\n return {\n eventName: mu.eventName || mu.event?.eventName || '',\n roundName: mu.roundName || '',\n scheduledTime: mu.schedule?.scheduledTime ? formatTime(mu.schedule.scheduledTime) : undefined,\n side1: extractSide(sides[0]),\n side2: extractSide(sides[1]),\n };\n}\n\nfunction extractSide(side: any): { name: string; nationality: string } {\n if (!side?.participant) return { name: 'TBD', nationality: '' };\n return {\n name: participantName(side.participant),\n nationality: nationality(side.participant),\n };\n}\n","import { participantName, nationality, formatScore } from '../utils/primitives';\n\nexport interface RoundRobinParticipant {\n participantName: string;\n nationality: string;\n seedValue?: number;\n groupPosition: number;\n}\n\nexport interface RoundRobinResult {\n rowPosition: number;\n colPosition: number;\n score: string;\n winningSide?: number;\n}\n\nexport interface RoundRobinGroupData {\n groupName: string;\n participants: RoundRobinParticipant[];\n results: RoundRobinResult[];\n standings?: {\n position: number;\n participantName: string;\n wins: number;\n losses: number;\n setsWon: number;\n setsLost: number;\n }[];\n}\n\nexport function extractRoundRobinData(params: { structure: any; participants?: any[] }): RoundRobinGroupData[] {\n const { structure, participants = [] } = params;\n if (!structure) return [];\n\n const participantMap = new Map<string, any>();\n participants.forEach((p: any) => participantMap.set(p.participantId, p));\n\n // Round robin structures have structures (groups) as children\n const groups = structure.structures || [];\n if (!groups.length) return [];\n\n return groups.map((group: any, groupIndex: number) => {\n const positionAssignments = group.positionAssignments || [];\n const seedAssignments = group.seedAssignments || [];\n\n const rrParticipants: RoundRobinParticipant[] = positionAssignments\n .filter((pa: any) => pa.participantId)\n .map((pa: any) => {\n const p = participantMap.get(pa.participantId);\n const seed = seedAssignments.find((sa: any) => sa.participantId === pa.participantId);\n return {\n participantName: p ? participantName(p) : '',\n nationality: p ? nationality(p) : '',\n seedValue: seed?.seedValue,\n groupPosition: pa.drawPosition,\n };\n })\n .sort((a: RoundRobinParticipant, b: RoundRobinParticipant) => a.groupPosition - b.groupPosition);\n\n const results: RoundRobinResult[] = [];\n for (const mu of group.matchUps || []) {\n if (!mu.drawPositions || mu.drawPositions.length < 2) continue;\n const [pos1, pos2] = mu.drawPositions;\n const score = formatScore(mu.score);\n\n if (score) {\n results.push({\n rowPosition: pos1,\n colPosition: pos2,\n score,\n winningSide: mu.winningSide,\n });\n }\n }\n\n return {\n groupName: group.structureName || `Group ${groupIndex + 1}`,\n participants: rrParticipants,\n results,\n };\n });\n}\n","import type { DrawFormatConfig } from '../config/types';\nimport type { DrawSlot } from '../core/extractDrawData';\n\nexport function formatPlayerEntry(slot: DrawSlot, config: DrawFormatConfig): string {\n if (slot.isBye) return 'Bye';\n if (!slot.participantName) return '';\n\n const name = formatName(slot.participantName, config);\n const nat = formatNationality(slot.nationality, config);\n const seed = slot.seedValue ? formatSeed(slot.seedValue, config) : '';\n const entry = slot.entryStatus ? formatEntryStatus(slot.entryStatus, config) : '';\n\n const parts: string[] = [];\n\n if (config.seedPosition === 'before-position' && seed) parts.push(seed);\n parts.push(name);\n if (config.seedPosition === 'after-name' && seed) parts.push(seed);\n if (nat) parts.push(nat);\n if (config.seedPosition === 'after-country' && seed) parts.push(seed);\n if (entry) parts.push(entry);\n\n return parts.join(' ');\n}\n\n/** Returns name (with seed/entry) and nationality as separate strings for split rendering */\nexport function formatPlayerEntrySplit(\n slot: DrawSlot,\n config: DrawFormatConfig,\n): { name: string; nationality: string } {\n if (slot.isBye) return { name: 'Bye', nationality: '' };\n if (!slot.participantName) return { name: '', nationality: '' };\n\n const name = formatName(slot.participantName, config);\n const seed = slot.seedValue ? formatSeed(slot.seedValue, config) : '';\n const entry = slot.entryStatus ? formatEntryStatus(slot.entryStatus, config) : '';\n\n const parts: string[] = [];\n if (config.seedPosition === 'before-position' && seed) parts.push(seed);\n parts.push(name);\n if (config.seedPosition === 'after-name' && seed) parts.push(seed);\n if (config.seedPosition === 'after-country' && seed) parts.push(seed);\n if (entry) parts.push(entry);\n\n return { name: parts.join(' '), nationality: slot.nationality || '' };\n}\n\nfunction formatName(participantName: string, config: DrawFormatConfig): string {\n // participantName comes as \"LASTNAME, GivenName\" from extractDrawData\n if (config.nameFormat === 'LAST First') {\n return participantName.replace(',', '');\n }\n if (config.nameFormat === 'F. LAST') {\n const match = participantName.match(/^([^,]+),\\s*(.+)/);\n if (match) return `${match[2][0]}. ${match[1]}`;\n }\n return participantName;\n}\n\nfunction formatNationality(nat: string, config: DrawFormatConfig): string {\n if (!nat) return '';\n switch (config.nationalityFormat) {\n case 'parens':\n return `(${nat})`;\n case 'hyphen':\n return `-${nat}`;\n default:\n return nat;\n }\n}\n\nfunction formatSeed(seedValue: number, config: DrawFormatConfig): string {\n return config.seedFormat === 'parens' ? `(${seedValue})` : `[${seedValue}]`;\n}\n\nconst ENTRY_ABBREVIATIONS: Record<string, string> = {\n DIRECT_ACCEPTANCE: '',\n WILDCARD: 'WC',\n QUALIFIER: 'Q',\n LUCKY_LOSER: 'LL',\n SPECIAL_EXEMPT: 'SE',\n ALTERNATE: 'ALT',\n PROTECTED_RANKING: 'PR',\n JUNIOR_EXEMPT: 'JE',\n ORGANISER_ACCEPTANCE: 'OA',\n};\n\nfunction formatEntryStatus(entryStatus: string, config: DrawFormatConfig): string {\n if (!entryStatus) return '';\n const abbr = ENTRY_ABBREVIATIONS[entryStatus];\n if (abbr === undefined) return entryStatus;\n if (!abbr) return ''; // DIRECT_ACCEPTANCE → no badge\n switch (config.entryFormat) {\n case 'parens':\n return `(${abbr})`;\n case 'hyphen':\n return `-${abbr}`;\n default:\n return abbr;\n }\n}\n\nexport function formatMatchScore(score: string, config: DrawFormatConfig): string {\n if (!score) return '';\n // The score from the factory comes with hyphens as game separators\n // Convert to the preset's format if needed\n if (config.gameScoreSeparator === '/') {\n return score.replace(/(\\d)-(\\d)/g, `$1/$2`);\n }\n return score;\n}\n","import jsPDF from 'jspdf';\nimport type { DrawFormatConfig, PageRegions } from '../config/types';\nimport type { DrawData, DrawSlot, DrawMatchUp } from '../core/extractDrawData';\nimport { getRoundLabel } from '../core/extractDrawData';\nimport { formatPlayerEntrySplit, formatMatchScore } from './formatEntry';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport interface TraditionalDrawConfig {\n lineHeight: number;\n roundColumnWidth: number;\n firstRoundWidth: number;\n secondRoundWidth: number;\n connectorGap: number;\n fontSize: number;\n scoreFontSize: number;\n}\n\nexport function getDrawConfig(positionCount: number, regions: PageRegions, roundCount?: number): TraditionalDrawConfig {\n const totalRounds = roundCount || Math.log2(positionCount);\n\n // Height: reserve 9mm for round headers + gap. The bracket spans positionCount-1 gaps.\n const headerReserve = 9;\n const availableHeight = regions.contentHeight - headerReserve;\n const lineHeight = availableHeight / positionCount;\n const isDense = lineHeight < 3.5;\n\n // Width: first round + connectorGap + (totalRounds-1) later round columns + connectorGap each + winner column\n // Total columns after R1 = totalRounds (rounds 2..N = totalRounds-1, plus 1 winner column)\n const connectorGap = isDense ? 0.8 : 1.5;\n const laterColumns = totalRounds; // includes winner column\n const totalConnectorWidth = connectorGap * (laterColumns + 1); // gap before each later column + gap after R1\n\n // First round gets enough for position number + name; later rounds share the rest equally\n // Dense draws (64/128) get a narrower R1 to give later rounds more room for name + score\n const isVeryDense = lineHeight < 2;\n const firstRoundPct = isDense ? 0.18 : 0.3;\n const firstRoundWidth = Math.min(isDense ? 38 : 65, regions.contentWidth * firstRoundPct);\n const remainingWidth = regions.contentWidth - firstRoundWidth - totalConnectorWidth;\n\n // For very dense draws (128), give R2 extra width for inline scores\n const r2Bonus = isVeryDense ? 8 : 0;\n const adjustedRemaining = remainingWidth - r2Bonus;\n const roundColumnWidth = Math.min(65, Math.max(8, adjustedRemaining / Math.max(1, laterColumns)));\n const secondRoundWidth = roundColumnWidth + r2Bonus;\n\n // Font sizing adapts to density\n let fontSize = SIZE.SMALL;\n if (lineHeight < 2.5) fontSize = 5;\n else if (lineHeight < 3.5) fontSize = SIZE.TINY;\n\n return {\n lineHeight,\n roundColumnWidth,\n firstRoundWidth,\n secondRoundWidth,\n connectorGap,\n fontSize,\n scoreFontSize: isDense ? 5 : SIZE.TINY,\n };\n}\n\nexport function renderTraditionalDraw(\n doc: jsPDF,\n drawData: DrawData,\n format: DrawFormatConfig,\n regions: PageRegions,\n positionOffset: number = 0,\n positionCount?: number,\n): void {\n // Detect feed structure: any round with match count >= previous round\n const isFeedStructure = detectFeedStructure(drawData.matchUps);\n\n if (isFeedStructure) {\n renderFeedDraw(doc, drawData, format, regions);\n } else {\n renderPowerOf2Draw(doc, drawData, format, regions, positionOffset, positionCount);\n }\n}\n\nfunction detectFeedStructure(matchUps: DrawMatchUp[]): boolean {\n const roundCounts = new Map<number, number>();\n for (const mu of matchUps) {\n roundCounts.set(mu.roundNumber, (roundCounts.get(mu.roundNumber) || 0) + 1);\n }\n const rounds = [...roundCounts.keys()].sort((a, b) => a - b);\n for (let i = 1; i < rounds.length; i++) {\n const prev = roundCounts.get(rounds[i - 1]) || 0;\n const curr = roundCounts.get(rounds[i]) || 0;\n if (curr >= prev) return true;\n }\n return false;\n}\n\n/**\n * Renders feed-in structures.\n *\n * Feed-in draws have alternating elimination and feed rounds:\n * FEED_IN 12: R1(4 matches) → R2(4 feed) → R3(2) → R4(1)\n * FIC 16 consolation: R1(4) → R2(4 feed) → R3(2) → R4(2 feed) → R5(1) → R6(1 feed)\n *\n * The first round renders draw positions as player lines. Feed rounds render\n * the fed-in participant as a new player line entering from the left, while\n * the advancing winner comes via a connector from the previous round.\n * Elimination rounds merge pairs with standard bracket connectors.\n */\nfunction renderFeedDraw(doc: jsPDF, drawData: DrawData, format: DrawFormatConfig, regions: PageRegions): void {\n const margins = format.page.margins;\n const headerReserve = 9;\n const contentTop = regions.contentY + headerReserve;\n const contentHeight = regions.contentHeight - headerReserve;\n\n const roundMap = groupMatchUpsByRound(drawData.matchUps);\n const sortedRounds = [...roundMap.keys()].sort((a, b) => a - b);\n const totalRoundCols = sortedRounds.length;\n const slotMap = new Map(drawData.slots.map((s) => [s.drawPosition, s]));\n\n const feedRoundSet = identifyFeedRounds(sortedRounds, roundMap);\n\n const { feedConfig, connectorGap, firstRoundWidth, roundColumnWidth, fontSize, scoreFontSize } = computeFeedLayout(\n contentHeight,\n roundMap,\n sortedRounds,\n totalRoundCols,\n regions,\n );\n\n const getColX = (ci: number) => {\n if (ci === 0) return margins.left;\n return margins.left + firstRoundWidth + connectorGap + (ci - 1) * (roundColumnWidth + connectorGap);\n };\n\n renderFeedRoundHeaders(\n doc,\n sortedRounds,\n drawData,\n feedConfig,\n format,\n regions,\n getColX,\n totalRoundCols,\n roundColumnWidth,\n );\n\n const roundSlotYs = computeFeedSlotYs(\n sortedRounds,\n totalRoundCols,\n roundMap,\n feedRoundSet,\n contentTop,\n contentHeight,\n feedConfig.lineHeight,\n );\n\n renderFeedRounds(\n doc,\n sortedRounds,\n totalRoundCols,\n roundMap,\n roundSlotYs,\n feedRoundSet,\n slotMap,\n feedConfig,\n format,\n getColX,\n firstRoundWidth,\n roundColumnWidth,\n connectorGap,\n scoreFontSize,\n );\n\n renderFeedWinnerColumn(\n doc,\n drawData,\n sortedRounds,\n totalRoundCols,\n roundMap,\n roundSlotYs,\n slotMap,\n getColX,\n contentTop,\n contentHeight,\n roundColumnWidth,\n fontSize,\n scoreFontSize,\n format,\n );\n}\n\nfunction groupMatchUpsByRound(matchUps: DrawMatchUp[]): Map<number, DrawMatchUp[]> {\n const roundMap = new Map<number, DrawMatchUp[]>();\n for (const mu of matchUps) {\n if (!roundMap.has(mu.roundNumber)) roundMap.set(mu.roundNumber, []);\n roundMap.get(mu.roundNumber)!.push(mu);\n }\n for (const [, mus] of roundMap) mus.sort((a, b) => a.roundPosition - b.roundPosition);\n return roundMap;\n}\n\nfunction identifyFeedRounds(sortedRounds: number[], roundMap: Map<number, DrawMatchUp[]>): Set<number> {\n const feedRoundSet = new Set<number>();\n for (let i = 1; i < sortedRounds.length; i++) {\n const prev = roundMap.get(sortedRounds[i - 1])?.length || 0;\n const curr = roundMap.get(sortedRounds[i])?.length || 0;\n if (curr >= prev) feedRoundSet.add(sortedRounds[i]);\n }\n return feedRoundSet;\n}\n\nfunction computeFeedLayout(\n contentHeight: number,\n roundMap: Map<number, DrawMatchUp[]>,\n sortedRounds: number[],\n totalRoundCols: number,\n regions: PageRegions,\n): {\n feedConfig: TraditionalDrawConfig;\n connectorGap: number;\n firstRoundWidth: number;\n roundColumnWidth: number;\n fontSize: number;\n scoreFontSize: number;\n} {\n const connectorGap = 1.5;\n const r1MatchCount = roundMap.get(sortedRounds[0])?.length || 1;\n const lineHeight = contentHeight / (r1MatchCount * 2);\n const isDense = lineHeight < 3.5;\n const firstRoundWidth = Math.min(isDense ? 50 : 60, regions.contentWidth * 0.25);\n const remainingWidth = regions.contentWidth - firstRoundWidth - connectorGap * (totalRoundCols + 1);\n const roundColumnWidth = Math.max(8, remainingWidth / Math.max(1, totalRoundCols));\n\n let fontSize = SIZE.SMALL;\n if (lineHeight < 2.5) fontSize = 5;\n else if (lineHeight < 3.5) fontSize = SIZE.TINY;\n const scoreFontSize = isDense ? 5 : SIZE.TINY;\n\n const feedConfig: TraditionalDrawConfig = {\n lineHeight,\n roundColumnWidth,\n firstRoundWidth,\n secondRoundWidth: roundColumnWidth,\n connectorGap,\n fontSize,\n scoreFontSize,\n };\n\n return { feedConfig, connectorGap, firstRoundWidth, roundColumnWidth, fontSize, scoreFontSize };\n}\n\nfunction computeFeedSlotYs(\n sortedRounds: number[],\n totalRoundCols: number,\n roundMap: Map<number, DrawMatchUp[]>,\n feedRoundSet: Set<number>,\n contentTop: number,\n contentHeight: number,\n lineHeight: number,\n): Map<number, { topY: number; bottomY: number; midY: number }[]> {\n const roundSlotYs = new Map<number, { topY: number; bottomY: number; midY: number }[]>();\n\n for (let ci = 0; ci < totalRoundCols; ci++) {\n const roundNum = sortedRounds[ci];\n const matchCount = roundMap.get(roundNum)?.length || 0;\n\n if (feedRoundSet.has(roundNum)) {\n const prevRound = sortedRounds[ci - 1];\n const prevSlots = roundSlotYs.get(prevRound) || [];\n const slots = prevSlots.slice(0, matchCount).map((ps) => {\n const armSpan = ps.bottomY - ps.topY;\n const maxArm = lineHeight * 2;\n if (armSpan > maxArm) {\n return { topY: ps.midY - lineHeight, bottomY: ps.midY + lineHeight, midY: ps.midY };\n }\n return { topY: ps.topY, bottomY: ps.bottomY, midY: ps.midY };\n });\n roundSlotYs.set(roundNum, slots);\n } else if (ci === 0) {\n const totalSlots = matchCount * 2;\n const slotSpacing = contentHeight / (totalSlots + 1);\n const slots: { topY: number; bottomY: number; midY: number }[] = [];\n for (let m = 0; m < matchCount; m++) {\n const topY = contentTop + slotSpacing * (m * 2 + 1);\n const bottomY = contentTop + slotSpacing * (m * 2 + 2);\n slots.push({ topY, bottomY, midY: (topY + bottomY) / 2 });\n }\n roundSlotYs.set(roundNum, slots);\n } else {\n const prevRound = sortedRounds[ci - 1];\n const prevSlots = roundSlotYs.get(prevRound) || [];\n const slots: { topY: number; bottomY: number; midY: number }[] = [];\n for (let m = 0; m < matchCount; m++) {\n const topSlot = prevSlots[m * 2];\n const bottomSlot = prevSlots[m * 2 + 1];\n if (topSlot && bottomSlot) {\n const topY = topSlot.midY;\n const bottomY = bottomSlot.midY;\n slots.push({ topY, bottomY, midY: (topY + bottomY) / 2 });\n }\n }\n roundSlotYs.set(roundNum, slots);\n }\n }\n\n return roundSlotYs;\n}\n\nfunction renderFeedRounds(\n doc: jsPDF,\n sortedRounds: number[],\n totalRoundCols: number,\n roundMap: Map<number, DrawMatchUp[]>,\n roundSlotYs: Map<number, { topY: number; bottomY: number; midY: number }[]>,\n feedRoundSet: Set<number>,\n slotMap: Map<number, DrawSlot>,\n feedConfig: TraditionalDrawConfig,\n format: DrawFormatConfig,\n getColX: (ci: number) => number,\n firstRoundWidth: number,\n roundColumnWidth: number,\n connectorGap: number,\n scoreFontSize: number,\n): void {\n for (let ci = 0; ci < totalRoundCols; ci++) {\n const roundNum = sortedRounds[ci];\n const matchUps = roundMap.get(roundNum) || [];\n const slotYs = roundSlotYs.get(roundNum) || [];\n const colX = getColX(ci);\n const colWidth = ci === 0 ? firstRoundWidth : roundColumnWidth;\n const isFeed = feedRoundSet.has(roundNum);\n const rightX = colX + colWidth;\n const nextRoundIsFeed = ci < totalRoundCols - 1 && feedRoundSet.has(sortedRounds[ci + 1]);\n\n for (let mi = 0; mi < matchUps.length; mi++) {\n const mu = matchUps[mi];\n const sy = slotYs[mi];\n if (!sy) continue;\n\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n\n if (ci === 0) {\n renderFeedFirstRound(\n doc,\n mu,\n sy,\n slotMap,\n format,\n feedConfig,\n colX,\n firstRoundWidth,\n rightX,\n connectorGap,\n nextRoundIsFeed,\n );\n } else if (isFeed) {\n renderFeedRound(\n doc,\n mu,\n sy,\n slotMap,\n roundMap,\n sortedRounds,\n ci,\n format,\n feedConfig,\n colX,\n roundColumnWidth,\n rightX,\n connectorGap,\n nextRoundIsFeed,\n );\n } else {\n renderFeedEliminationRound(\n doc,\n mu,\n sy,\n slotMap,\n format,\n feedConfig,\n colX,\n roundColumnWidth,\n rightX,\n connectorGap,\n nextRoundIsFeed,\n );\n }\n\n if (ci < totalRoundCols - 1) {\n const nextColX = getColX(ci + 1);\n if (nextRoundIsFeed) {\n doc.line(rightX, sy.midY, nextColX, sy.midY);\n } else {\n doc.line(rightX + connectorGap, sy.midY, nextColX, sy.midY);\n }\n }\n\n if (mu.score) {\n const scoreStr = formatMatchScore(mu.score, format);\n setFont(doc, scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n const scoreBaselineY = sy.midY + scoreFontSize * 0.12;\n doc.text(scoreStr, rightX - 1, scoreBaselineY, { align: 'right' });\n doc.setTextColor(0);\n }\n }\n }\n}\n\nfunction renderFeedFirstRound(\n doc: jsPDF,\n mu: DrawMatchUp,\n sy: { topY: number; bottomY: number; midY: number },\n slotMap: Map<number, DrawSlot>,\n format: DrawFormatConfig,\n feedConfig: TraditionalDrawConfig,\n colX: number,\n firstRoundWidth: number,\n rightX: number,\n connectorGap: number,\n nextRoundIsFeed: boolean,\n): void {\n if (mu.drawPositions[0])\n drawPlayerLine(\n doc,\n slotMap.get(mu.drawPositions[0]),\n mu.drawPositions[0],\n format,\n feedConfig,\n colX,\n sy.topY,\n firstRoundWidth,\n );\n if (mu.drawPositions[1])\n drawPlayerLine(\n doc,\n slotMap.get(mu.drawPositions[1]),\n mu.drawPositions[1],\n format,\n feedConfig,\n colX,\n sy.bottomY,\n firstRoundWidth,\n );\n\n drawRightBracketConnector(doc, sy, rightX, connectorGap, nextRoundIsFeed);\n}\n\nfunction renderFeedRound(\n doc: jsPDF,\n mu: DrawMatchUp,\n sy: { topY: number; bottomY: number; midY: number },\n slotMap: Map<number, DrawSlot>,\n roundMap: Map<number, DrawMatchUp[]>,\n sortedRounds: number[],\n ci: number,\n format: DrawFormatConfig,\n feedConfig: TraditionalDrawConfig,\n colX: number,\n roundColumnWidth: number,\n rightX: number,\n connectorGap: number,\n nextRoundIsFeed: boolean,\n): void {\n const prevRoundNum = sortedRounds[ci - 1];\n const prevMatchUps = roundMap.get(prevRoundNum) || [];\n const prevWinnerPositions = new Set<number>();\n for (const pmu of prevMatchUps) {\n if (pmu.winningSide) {\n prevWinnerPositions.add(pmu.drawPositions[pmu.winningSide - 1]);\n }\n }\n\n const advDp = mu.drawPositions.find((dp) => dp && prevWinnerPositions.has(dp));\n const fedDp = mu.drawPositions.find((dp) => dp && dp !== advDp);\n\n doc.line(colX, sy.midY, colX, sy.bottomY);\n\n if (fedDp) {\n drawPlayerLine(doc, slotMap.get(fedDp), fedDp, format, feedConfig, colX, sy.topY, roundColumnWidth);\n } else {\n doc.line(colX, sy.topY, colX + roundColumnWidth, sy.topY);\n }\n doc.line(colX, sy.bottomY, colX + roundColumnWidth, sy.bottomY);\n if (advDp) {\n const advSlot = slotMap.get(advDp);\n if (advSlot?.participantName) {\n drawAdvancingName(doc, advSlot, format, feedConfig, colX, sy.bottomY);\n }\n }\n\n drawRightBracketConnector(doc, sy, rightX, connectorGap, nextRoundIsFeed);\n}\n\nfunction renderFeedEliminationRound(\n doc: jsPDF,\n mu: DrawMatchUp,\n sy: { topY: number; bottomY: number; midY: number },\n slotMap: Map<number, DrawSlot>,\n format: DrawFormatConfig,\n feedConfig: TraditionalDrawConfig,\n colX: number,\n roundColumnWidth: number,\n rightX: number,\n connectorGap: number,\n nextRoundIsFeed: boolean,\n): void {\n doc.line(colX, sy.topY, colX + roundColumnWidth, sy.topY);\n doc.line(colX, sy.bottomY, colX + roundColumnWidth, sy.bottomY);\n\n if (mu.drawPositions[0]) {\n const topSlot = slotMap.get(mu.drawPositions[0]);\n if (topSlot?.participantName) {\n drawAdvancingName(doc, topSlot, format, feedConfig, colX, sy.topY);\n }\n }\n if (mu.drawPositions[1]) {\n const bottomSlot = slotMap.get(mu.drawPositions[1]);\n if (bottomSlot?.participantName) {\n drawAdvancingName(doc, bottomSlot, format, feedConfig, colX, sy.bottomY);\n }\n }\n\n drawRightBracketConnector(doc, sy, rightX, connectorGap, nextRoundIsFeed);\n}\n\nfunction drawRightBracketConnector(\n doc: jsPDF,\n sy: { topY: number; bottomY: number },\n rightX: number,\n connectorGap: number,\n nextRoundIsFeed: boolean,\n): void {\n if (nextRoundIsFeed) {\n doc.line(rightX, sy.topY, rightX, sy.bottomY);\n } else {\n doc.line(rightX + connectorGap, sy.topY, rightX + connectorGap, sy.bottomY);\n doc.line(rightX, sy.topY, rightX + connectorGap, sy.topY);\n doc.line(rightX, sy.bottomY, rightX + connectorGap, sy.bottomY);\n }\n}\n\nfunction renderFeedWinnerColumn(\n doc: jsPDF,\n drawData: DrawData,\n sortedRounds: number[],\n totalRoundCols: number,\n roundMap: Map<number, DrawMatchUp[]>,\n roundSlotYs: Map<number, { topY: number; bottomY: number; midY: number }[]>,\n slotMap: Map<number, DrawSlot>,\n getColX: (ci: number) => number,\n contentTop: number,\n contentHeight: number,\n roundColumnWidth: number,\n fontSize: number,\n scoreFontSize: number,\n format: DrawFormatConfig,\n): void {\n if (drawData.noWinnerColumn) return;\n\n const winnerColX = getColX(totalRoundCols);\n const lastRound = sortedRounds.at(-1)!;\n const lastSlots = roundSlotYs.get(lastRound) || [];\n const winnerMidY = lastSlots[0]?.midY || contentTop + contentHeight / 2;\n\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(winnerColX, winnerMidY, winnerColX + Math.min(65, roundColumnWidth), winnerMidY);\n\n const finalMu = (roundMap.get(lastRound) || [])[0];\n if (finalMu?.winningSide) {\n const winnerPos = finalMu.drawPositions[finalMu.winningSide - 1];\n const winnerSlot = slotMap.get(winnerPos);\n if (winnerSlot) {\n setFont(doc, fontSize + 1, STYLE.BOLD);\n const { name: winnerName } = formatPlayerEntrySplit(winnerSlot, format);\n doc.text(winnerName, winnerColX + 1, winnerMidY - 0.5);\n\n if (finalMu.score) {\n const scoreStr = formatMatchScore(finalMu.score, format);\n setFont(doc, scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(scoreStr, winnerColX + 1, winnerMidY + scoreFontSize * 0.4);\n doc.setTextColor(0);\n }\n }\n }\n}\n\nfunction renderFeedRoundHeaders(\n doc: jsPDF,\n sortedRounds: number[],\n drawData: DrawData,\n config: TraditionalDrawConfig,\n format: DrawFormatConfig,\n regions: PageRegions,\n getColX: (ci: number) => number,\n totalRoundCols: number,\n roundColumnWidth: number,\n): void {\n const headerFontSize = config.fontSize <= SIZE.TINY ? 5.5 : SIZE.SMALL;\n setFont(doc, headerFontSize, STYLE.BOLD);\n doc.setTextColor(40);\n\n for (let ci = 0; ci < totalRoundCols; ci++) {\n const roundNum = sortedRounds[ci];\n const defaultLabel = getRoundLabel(roundNum, drawData.totalRounds);\n const label = drawData.roundLabelMap?.[roundNum] || format.roundLabels[defaultLabel] || defaultLabel;\n const x = getColX(ci);\n const width = ci === 0 ? config.firstRoundWidth : roundColumnWidth;\n doc.text(label, x + width / 2, regions.contentY + 2, { align: 'center' });\n doc.setDrawColor(160);\n doc.setLineWidth(0.15);\n doc.line(x + 2, regions.contentY + 3.5, x + width - 2, regions.contentY + 3.5);\n }\n\n const winnerX = getColX(totalRoundCols);\n doc.text('Winner', winnerX + roundColumnWidth / 2, regions.contentY + 2, { align: 'center' });\n doc.setDrawColor(160);\n doc.line(winnerX + 2, regions.contentY + 3.5, winnerX + roundColumnWidth - 2, regions.contentY + 3.5);\n doc.setTextColor(0);\n}\n\nfunction renderPowerOf2Draw(\n doc: jsPDF,\n drawData: DrawData,\n format: DrawFormatConfig,\n regions: PageRegions,\n positionOffset: number = 0,\n positionCount?: number,\n): void {\n const count = positionCount || drawData.drawSize;\n const actualRoundCount = drawData.totalRounds || Math.ceil(Math.log2(count));\n const computedRounds = Math.log2(count);\n // Use actual round count from data when it differs from the computed value\n // (e.g., qualifying structures that don't resolve to a single winner)\n const totalRounds = Number.isInteger(computedRounds) ? Math.min(computedRounds, actualRoundCount) : actualRoundCount;\n const config = getDrawConfig(count, regions, totalRounds);\n const margins = format.page.margins;\n\n const startX = margins.left;\n const startY = regions.contentY + 9;\n\n renderRoundHeaders(\n doc,\n totalRounds,\n drawData.totalRounds,\n config,\n format,\n startX,\n regions.contentY + 2,\n drawData.roundLabelMap,\n drawData.noWinnerColumn,\n );\n\n for (let round = 0; round < totalRounds; round++) {\n renderPowerOf2Round(doc, drawData, format, config, count, round, totalRounds, startX, startY, positionOffset);\n }\n\n if (drawData.noWinnerColumn) return;\n\n renderPowerOf2WinnerColumn(doc, drawData, format, config, totalRounds, startX, startY);\n}\n\nfunction renderPowerOf2Round(\n doc: jsPDF,\n drawData: DrawData,\n format: DrawFormatConfig,\n config: TraditionalDrawConfig,\n count: number,\n round: number,\n totalRounds: number,\n startX: number,\n startY: number,\n positionOffset: number,\n): void {\n const matchesInRound = count / Math.pow(2, round + 1);\n const spacing = config.lineHeight * Math.pow(2, round);\n const roundX = getRoundX(round, config, startX);\n const roundOffset = ((Math.pow(2, round) - 1) * config.lineHeight) / 2;\n const stride = Math.pow(2, round + 1) * config.lineHeight;\n\n for (let match = 0; match < matchesInRound; match++) {\n const topSlotY = startY + roundOffset + match * stride;\n const bottomSlotY = topSlotY + spacing;\n const midY = (topSlotY + bottomSlotY) / 2;\n\n if (round === 0) {\n const topPos = positionOffset + match * 2 + 1;\n const bottomPos = positionOffset + match * 2 + 2;\n drawPlayerLine(doc, findSlot(drawData.slots, topPos), topPos, format, config, roundX, topSlotY);\n drawPlayerLine(doc, findSlot(drawData.slots, bottomPos), bottomPos, format, config, roundX, bottomSlotY);\n } else {\n const colWidth = getRoundWidth(round, config);\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(roundX, topSlotY, roundX + colWidth, topSlotY);\n doc.line(roundX, bottomSlotY, roundX + colWidth, bottomSlotY);\n }\n\n const isFinalRound = round === totalRounds - 1;\n const rightX = roundX + getRoundWidth(round, config);\n\n // Always draw the bracket connector (vertical + horizontals between the two slots)\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(rightX + config.connectorGap, topSlotY, rightX + config.connectorGap, bottomSlotY);\n doc.line(rightX, topSlotY, rightX + config.connectorGap, topSlotY);\n doc.line(rightX, bottomSlotY, rightX + config.connectorGap, bottomSlotY);\n\n // Horizontal line from bracket midpoint to the next round (skip on qualifying final)\n if (!isFinalRound || !drawData.noWinnerColumn) {\n const nextRoundX = getRoundX(round + 1, config, startX);\n doc.line(rightX + config.connectorGap, midY, nextRoundX, midY);\n }\n\n const mu = findMatchUp(drawData.matchUps, round + 1, match + 1);\n\n if (isFinalRound && drawData.noWinnerColumn) {\n // Final qualifying round: draw a short winner line and name to the right\n const advancingSlot = getAdvancingSlot(mu, drawData.slots);\n if (advancingSlot) {\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(rightX + config.connectorGap, midY, rightX + config.connectorGap + config.roundColumnWidth, midY);\n drawAdvancingName(doc, advancingSlot, format, config, rightX + config.connectorGap, midY);\n if (mu?.score) {\n renderMatchScore(doc, mu, format, config, spacing, rightX + config.connectorGap, round, midY);\n }\n }\n } else if (!isFinalRound) {\n const advancingSlot = getAdvancingSlot(mu, drawData.slots);\n if (advancingSlot) {\n const nextRoundX = getRoundX(round + 1, config, startX);\n drawAdvancingName(doc, advancingSlot, format, config, nextRoundX, midY);\n if (mu?.score) {\n renderMatchScore(doc, mu, format, config, spacing, nextRoundX, round, midY);\n }\n }\n }\n }\n}\n\nfunction renderMatchScore(\n doc: jsPDF,\n mu: DrawMatchUp,\n format: DrawFormatConfig,\n config: TraditionalDrawConfig,\n spacing: number,\n nextRoundX: number,\n round: number,\n midY: number,\n): void {\n const scoreStr = formatMatchScore(mu.score!, format);\n setFont(doc, config.scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n const nextRoundSlotHeight = spacing * 2;\n const isDenseRound = nextRoundSlotHeight < config.scoreFontSize * 1.2;\n if (isDenseRound) {\n const nextColWidth = getRoundWidth(round + 1, config);\n const colRight = nextRoundX + nextColWidth - 1;\n doc.text(scoreStr, colRight, midY - 0.5, { align: 'right' });\n } else {\n const scoreOffset = config.scoreFontSize * 0.4;\n doc.text(scoreStr, nextRoundX + 1, midY - 0.5 + scoreOffset);\n }\n doc.setTextColor(0);\n}\n\nfunction renderPowerOf2WinnerColumn(\n doc: jsPDF,\n drawData: DrawData,\n format: DrawFormatConfig,\n config: TraditionalDrawConfig,\n totalRounds: number,\n startX: number,\n startY: number,\n): void {\n const winnerX = getRoundX(totalRounds, config, startX);\n const finalRoundOffset = ((Math.pow(2, totalRounds - 1) - 1) * config.lineHeight) / 2;\n const finalSpacing = config.lineHeight * Math.pow(2, totalRounds - 1);\n const winnerMidY = startY + finalRoundOffset + finalSpacing / 2;\n\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(winnerX, winnerMidY, winnerX + config.roundColumnWidth, winnerMidY);\n\n const finalMu = findMatchUp(drawData.matchUps, totalRounds, 1);\n if (finalMu?.winningSide) {\n const winnerPos = finalMu.drawPositions[finalMu.winningSide - 1];\n const winnerSlot = findSlot(drawData.slots, winnerPos);\n if (winnerSlot) {\n setFont(doc, config.fontSize + 1, STYLE.BOLD);\n const { name: winnerName } = formatPlayerEntrySplit(winnerSlot, format);\n doc.text(winnerName, winnerX + 1, winnerMidY - 0.5);\n\n if (finalMu.score) {\n const scoreStr = formatMatchScore(finalMu.score, format);\n setFont(doc, config.scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(scoreStr, winnerX + 1, winnerMidY + config.scoreFontSize * 0.4);\n doc.setTextColor(0);\n }\n }\n }\n}\n\nfunction renderRoundHeaders(\n doc: jsPDF,\n segmentRounds: number,\n totalRounds: number,\n config: TraditionalDrawConfig,\n format: DrawFormatConfig,\n startX: number,\n y: number,\n roundLabelMap?: Record<number, string>,\n noWinnerColumn?: boolean,\n): void {\n const isDense = config.fontSize <= SIZE.TINY;\n const headerFontSize = isDense ? 5.5 : SIZE.SMALL;\n\n setFont(doc, headerFontSize, STYLE.BOLD);\n doc.setTextColor(40);\n\n // Round headers for R1..Rn\n for (let round = 0; round < segmentRounds; round++) {\n const roundNumber = totalRounds - segmentRounds + round + 1;\n const defaultLabel = getRoundLabel(roundNumber, totalRounds);\n const label = roundLabelMap?.[roundNumber] || format.roundLabels[defaultLabel] || defaultLabel;\n const x = getRoundX(round, config, startX);\n const width = getRoundWidth(round, config);\n const centerX = x + width / 2;\n\n doc.text(label, centerX, y, { align: 'center' });\n\n doc.setDrawColor(160);\n doc.setLineWidth(0.15);\n doc.line(x + 2, y + 1.5, x + width - 2, y + 1.5);\n }\n\n // Winner column header (only on pages that include the final)\n if (!noWinnerColumn) {\n const winnerX = getRoundX(segmentRounds, config, startX);\n doc.text('Winner', winnerX + config.roundColumnWidth / 2, y, { align: 'center' });\n doc.setDrawColor(160);\n doc.setLineWidth(0.15);\n doc.line(winnerX + 2, y + 1.5, winnerX + config.roundColumnWidth - 2, y + 1.5);\n }\n\n doc.setTextColor(0);\n}\n\nfunction getRoundWidth(round: number, config: TraditionalDrawConfig): number {\n if (round === 0) return config.firstRoundWidth;\n if (round === 1) return config.secondRoundWidth;\n return config.roundColumnWidth;\n}\n\nfunction getRoundX(round: number, config: TraditionalDrawConfig, startX: number): number {\n if (round === 0) return startX;\n let x = startX + config.firstRoundWidth + config.connectorGap;\n for (let r = 1; r < round; r++) {\n x += getRoundWidth(r, config) + config.connectorGap;\n }\n return x;\n}\n\nfunction drawPlayerLine(\n doc: jsPDF,\n slot: DrawSlot | undefined,\n drawPosition: number,\n format: DrawFormatConfig,\n config: TraditionalDrawConfig,\n x: number,\n y: number,\n colWidth?: number,\n): void {\n const posNumWidth = config.fontSize <= 5 ? 4 : 5;\n const natGapWidth = config.fontSize <= 5 ? 5 : 6;\n const width = colWidth || config.firstRoundWidth;\n\n // Draw position number (left-aligned)\n const textOffset = config.lineHeight < 2 ? 0.15 : 0.3;\n setFont(doc, config.scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(120);\n doc.text(`${drawPosition}`, x, y - textOffset, { align: 'left' });\n doc.setTextColor(0);\n\n // Nationality / country code in the gap between position number and line\n if (slot?.nationality) {\n setFont(doc, config.scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(100);\n doc.text(slot.nationality, x + posNumWidth + natGapWidth - 1, y - textOffset, { align: 'right' });\n doc.setTextColor(0);\n }\n\n // Horizontal line (starts after the nationality gap)\n const lineStart = x + posNumWidth + natGapWidth;\n const lineEnd = x + width;\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(lineStart, y, lineEnd, y);\n\n if (!slot) return;\n\n const { name } = formatPlayerEntrySplit(slot, format);\n if (!name) return;\n\n setFont(doc, config.fontSize, slot.isBye ? STYLE.ITALIC : STYLE.NORMAL);\n if (slot.isBye) doc.setTextColor(150);\n\n // If name is too wide, use abbreviated form (F. LASTNAME)\n const availableWidth = lineEnd - lineStart - 2;\n let displayName = name;\n if (doc.getTextWidth(name) > availableWidth) {\n displayName = abbreviateName(slot.participantName);\n }\n const nameOffset = config.lineHeight < 2 ? 0.2 : 0.5;\n doc.text(displayName, lineStart + 1, y - nameOffset);\n if (slot.isBye) doc.setTextColor(0);\n}\n\nfunction drawAdvancingName(\n doc: jsPDF,\n slot: DrawSlot,\n format: DrawFormatConfig,\n config: TraditionalDrawConfig,\n x: number,\n y: number,\n): void {\n const shortName = abbreviateName(slot.participantName);\n let seed = '';\n if (slot.seedValue) {\n seed = format.seedFormat === 'parens' ? `(${slot.seedValue})` : `[${slot.seedValue}]`;\n }\n const display = seed ? `${shortName} ${seed}` : shortName;\n\n setFont(doc, config.fontSize, STYLE.BOLD);\n doc.text(display, x + 1, y - 0.5);\n}\n\nfunction abbreviateName(fullName: string): string {\n const commaMatch = fullName.match(/^([^,]+),\\s*(.+)/);\n if (commaMatch) return `${commaMatch[2][0]}. ${commaMatch[1]}`;\n const spaceMatch = fullName.match(/^(\\S+)\\s+(.+)/);\n if (spaceMatch) return `${spaceMatch[1][0]}. ${spaceMatch[2]}`;\n return fullName;\n}\n\nfunction findSlot(slots: DrawSlot[], drawPosition: number): DrawSlot | undefined {\n return slots.find((s) => s.drawPosition === drawPosition);\n}\n\nfunction findMatchUp(matchUps: DrawMatchUp[], roundNumber: number, roundPosition: number): DrawMatchUp | undefined {\n return matchUps.find((mu) => mu.roundNumber === roundNumber && mu.roundPosition === roundPosition);\n}\n\n/** Find the advancing participant slot for a matchUp (handles both completed and BYE matchUps) */\nfunction getAdvancingSlot(mu: DrawMatchUp | undefined, slots: DrawSlot[]): DrawSlot | undefined {\n if (!mu) return undefined;\n\n if (mu.winningSide) {\n const winnerPos = mu.drawPositions[mu.winningSide - 1];\n return findSlot(slots, winnerPos);\n }\n\n // BYE matchUp: the non-BYE participant advances\n if (mu.matchUpStatus === 'BYE') {\n for (const pos of mu.drawPositions) {\n const slot = findSlot(slots, pos);\n if (slot && !slot.isBye && slot.participantName) return slot;\n }\n }\n\n return undefined;\n}\n","import jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport type { PageRegions, DrawFormatConfig } from '../config/types';\nimport type { RoundRobinGroupData } from '../core/extractRoundRobinData';\nimport { formatMatchScore } from './formatEntry';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nconst GRAY_FILL: [number, number, number] = [200, 200, 200];\nconst WIN_COLOR: [number, number, number] = [20, 80, 20];\nconst LOSS_COLOR: [number, number, number] = [160, 40, 40];\nconst HEADER_FILL: [number, number, number] = [50, 50, 50];\n\nexport function renderRoundRobinGroup(\n doc: jsPDF,\n group: RoundRobinGroupData,\n format: DrawFormatConfig,\n _regions: PageRegions,\n startY: number,\n): number {\n const margins = format.page.margins;\n const count = group.participants.length;\n\n // Group title\n setFont(doc, SIZE.HEADING, STYLE.BOLD);\n doc.text(group.groupName, margins.left, startY);\n startY += 5;\n\n // Build the grid: rows = participants, cols = # + Name + Nat + each opponent + W + L\n const headerRow = ['#', 'Player', 'Nat.'];\n for (let i = 0; i < count; i++) {\n headerRow.push(`${i + 1}`);\n }\n headerRow.push('W', 'L');\n\n // Build result matrix\n const resultMatrix = buildResultMatrix(group, format);\n\n // Build table body\n const body: any[][] = group.participants.map((p, rowIdx) => {\n const row: any[] = [\n { content: `${rowIdx + 1}`, styles: { fontStyle: 'bold', halign: 'center' } },\n { content: p.participantName + (p.seedValue ? ` [${p.seedValue}]` : ''), styles: { fontStyle: 'bold' } },\n { content: p.nationality, styles: { halign: 'center' } },\n ];\n\n // Score cells for each opponent\n for (let colIdx = 0; colIdx < count; colIdx++) {\n if (rowIdx === colIdx) {\n // Self-intersection: grayed out\n row.push({ content: '', styles: { fillColor: GRAY_FILL } });\n } else {\n const cell = resultMatrix[rowIdx]?.[colIdx];\n if (cell) {\n const textColor = cell.isWin ? WIN_COLOR : LOSS_COLOR;\n row.push({ content: cell.score, styles: { halign: 'center', textColor } });\n } else {\n row.push({ content: '', styles: { halign: 'center' } });\n }\n }\n }\n\n // Win/Loss counts\n const wins = resultMatrix[rowIdx]?.filter((c) => c?.isWin).length || 0;\n const losses = resultMatrix[rowIdx]?.filter((c) => c && !c.isWin).length || 0;\n row.push({ content: `${wins}`, styles: { halign: 'center', fontStyle: 'bold' } });\n row.push({ content: `${losses}`, styles: { halign: 'center' } });\n\n return row;\n });\n\n autoTable(doc, {\n startY,\n head: [headerRow],\n body,\n styles: {\n fontSize: 7,\n cellPadding: 1.5,\n lineWidth: 0.2,\n lineColor: [150, 150, 150],\n },\n headStyles: {\n fillColor: HEADER_FILL,\n textColor: [255, 255, 255],\n fontStyle: 'bold',\n halign: 'center',\n fontSize: 7,\n },\n columnStyles: {\n 0: { cellWidth: 8 },\n 1: { cellWidth: 'auto' },\n 2: { cellWidth: 12 },\n },\n margin: { left: margins.left, right: margins.right },\n });\n\n return (doc as any).lastAutoTable?.finalY || startY + 40;\n}\n\ninterface CellResult {\n score: string;\n isWin: boolean;\n}\n\nfunction buildResultMatrix(group: RoundRobinGroupData, format: DrawFormatConfig): (CellResult | null)[][] {\n const count = group.participants.length;\n const matrix: (CellResult | null)[][] = Array.from({ length: count }, () => Array(count).fill(null));\n\n // Map group positions to matrix indices\n const posToIdx = new Map<number, number>();\n group.participants.forEach((p, i) => posToIdx.set(p.groupPosition, i));\n\n for (const result of group.results) {\n const rowIdx = posToIdx.get(result.rowPosition);\n const colIdx = posToIdx.get(result.colPosition);\n if (rowIdx === undefined || colIdx === undefined) continue;\n\n const score = formatMatchScore(result.score, format);\n const isRowWinner = result.winningSide === 1;\n\n // Row player's perspective\n matrix[rowIdx][colIdx] = { score, isWin: isRowWinner };\n // Column player's perspective (reversed score)\n matrix[colIdx][rowIdx] = { score: reverseScore(score), isWin: !isRowWinner };\n }\n\n return matrix;\n}\n\nfunction reverseScore(score: string): string {\n // Reverse set scores: \"6-4 3-6\" -> \"4-6 6-3\"\n return score\n .split(/\\s+/)\n .map((set) => {\n const match = set.match(/^(\\d+)([/-])(\\d+)(\\(\\d+\\))?$/);\n if (match) return `${match[3]}${match[2]}${match[1]}${match[4] || ''}`;\n return set;\n })\n .join(' ');\n}\n","import jsPDF from 'jspdf';\nimport type { PageRegions, DrawFormatConfig } from '../config/types';\nimport type { DrawData, DrawMatchUp } from '../core/extractDrawData';\nimport { getRoundLabel } from '../core/extractDrawData';\nimport { formatPlayerEntry, formatMatchScore } from './formatEntry';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nconst BOX_INNER_PAD = 1;\nconst PREFERRED_BOX_HEIGHT = 16;\nconst MIN_BOX_GAP = 1;\n\nexport function renderLuckyDraw(doc: jsPDF, drawData: DrawData, format: DrawFormatConfig, regions: PageRegions): void {\n const margins = format.page.margins;\n\n // Group matchUps by round\n const roundMap = new Map<number, DrawMatchUp[]>();\n for (const mu of drawData.matchUps) {\n if (!roundMap.has(mu.roundNumber)) roundMap.set(mu.roundNumber, []);\n roundMap.get(mu.roundNumber)!.push(mu);\n }\n\n const slotMap = new Map(drawData.slots.map((s) => [s.drawPosition, s]));\n const sortedRounds = [...roundMap.keys()].sort((a, b) => a - b);\n const totalRounds = sortedRounds.length;\n\n // Layout: vertical columns, left to right\n const headerReserve = 7;\n const contentTop = regions.contentY + headerReserve;\n const contentHeight = regions.contentHeight - headerReserve;\n const roundGap = 6;\n const boxWidth = Math.min(55, (regions.contentWidth - (totalRounds - 1) * roundGap) / totalRounds);\n\n // Scale box height to fit the largest round (R1) with minimum gaps\n const maxMatchesInRound = roundMap.get(sortedRounds[0])?.length || 1;\n const boxHeight = Math.min(\n PREFERRED_BOX_HEIGHT,\n (contentHeight - (maxMatchesInRound + 1) * MIN_BOX_GAP) / maxMatchesInRound,\n );\n\n // Round headers\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.setTextColor(30, 60, 120);\n for (let ri = 0; ri < totalRounds; ri++) {\n const roundNum = sortedRounds[ri];\n const label =\n format.roundLabels[getRoundLabel(roundNum, drawData.totalRounds)] ||\n getRoundLabel(roundNum, drawData.totalRounds);\n const colX = margins.left + ri * (boxWidth + roundGap);\n doc.text(label, colX + boxWidth / 2, regions.contentY + 3, { align: 'center' });\n }\n doc.setTextColor(0);\n\n // Render each round column\n for (let ri = 0; ri < totalRounds; ri++) {\n const roundNum = sortedRounds[ri];\n const matchUps = roundMap.get(roundNum) || [];\n const count = matchUps.length;\n const colX = margins.left + ri * (boxWidth + roundGap);\n\n // Space-around: evenly distribute boxes vertically\n const totalBoxHeight = count * boxHeight;\n const gap = count > 1 ? (contentHeight - totalBoxHeight) / (count + 1) : (contentHeight - boxHeight) / 2;\n\n for (let i = 0; i < count; i++) {\n const y = contentTop + gap + i * (boxHeight + gap);\n renderMatchBox(doc, matchUps[i], slotMap, format, colX, y, boxWidth, boxHeight);\n }\n }\n}\n\nfunction renderMatchBox(\n doc: jsPDF,\n mu: DrawMatchUp,\n slotMap: Map<number, any>,\n format: DrawFormatConfig,\n x: number,\n y: number,\n width: number,\n height: number,\n): void {\n const isCompact = height < 10;\n const fontSize = isCompact ? 5 : SIZE.TINY;\n\n // Box outline\n doc.setDrawColor(100);\n doc.setLineWidth(0.3);\n doc.rect(x, y, width, height);\n\n // Divider line in middle\n const midY = y + height / 2;\n doc.setLineWidth(0.15);\n doc.line(x, midY, x + width, midY);\n\n // Side 1 (top half)\n const slot1 = mu.drawPositions[0] ? slotMap.get(mu.drawPositions[0]) : undefined;\n if (slot1) {\n const text = formatPlayerEntry(slot1, format);\n const isWinner = mu.winningSide === 1;\n setFont(doc, fontSize, isWinner ? STYLE.BOLD : STYLE.NORMAL);\n doc.text(text, x + BOX_INNER_PAD, midY - fontSize * 0.15, { maxWidth: width - 2 * BOX_INNER_PAD });\n }\n\n // Side 2 (bottom half)\n const slot2 = mu.drawPositions[1] ? slotMap.get(mu.drawPositions[1]) : undefined;\n if (slot2) {\n const text = formatPlayerEntry(slot2, format);\n const isWinner = mu.winningSide === 2;\n setFont(doc, fontSize, isWinner ? STYLE.BOLD : STYLE.NORMAL);\n doc.text(text, x + BOX_INNER_PAD, midY + fontSize * 0.55, { maxWidth: width - 2 * BOX_INNER_PAD });\n }\n\n // Score (top right corner)\n if (mu.score) {\n const scoreStr = formatMatchScore(mu.score, format);\n setFont(doc, fontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(scoreStr, x + width - BOX_INNER_PAD, y + fontSize * 0.5, { align: 'right' });\n doc.setTextColor(0);\n }\n}\n","import type { DrawSplitConfig } from '../config/types';\nimport type { DrawData, DrawSlot, DrawMatchUp } from '../core/extractDrawData';\n\nexport interface DrawSegment {\n label: string;\n startPosition: number;\n endPosition: number;\n slots: DrawSlot[];\n matchUps: DrawMatchUp[];\n segmentRounds: number;\n /** If true, this segment should NOT render a winner column */\n noWinnerColumn?: boolean;\n /** Remapped round labels for this segment */\n roundLabelMap?: Record<number, string>;\n}\n\nconst DEFAULT_SPLIT: DrawSplitConfig = {\n maxPositionsPerPage: 64,\n includeOverlapRounds: true,\n summaryPage: true,\n};\n\nexport function splitDraw(drawData: DrawData, config: DrawSplitConfig = DEFAULT_SPLIT): DrawSegment[] {\n const { drawSize, slots, matchUps, totalRounds } = drawData;\n\n if (drawSize <= config.maxPositionsPerPage) {\n return [\n {\n label: 'Full Draw',\n startPosition: 1,\n endPosition: drawSize,\n slots,\n matchUps,\n segmentRounds: totalRounds,\n },\n ];\n }\n\n const segmentSize = config.maxPositionsPerPage;\n const segmentCount = Math.ceil(drawSize / segmentSize);\n const segmentRounds = Math.log2(segmentSize);\n const segments: DrawSegment[] = [];\n\n for (let i = 0; i < segmentCount; i++) {\n segments.push(buildPositionSegment(i, segmentSize, segmentCount, segmentRounds, drawSize, slots, matchUps));\n }\n\n if (config.summaryPage && segmentCount > 1) {\n segments.push(buildSummarySegment(drawData));\n }\n\n return segments;\n}\n\nfunction buildPositionSegment(\n index: number,\n segmentSize: number,\n segmentCount: number,\n segmentRounds: number,\n drawSize: number,\n slots: DrawSlot[],\n matchUps: DrawMatchUp[],\n): DrawSegment {\n const startPos = index * segmentSize + 1;\n const endPos = Math.min((index + 1) * segmentSize, drawSize);\n let segmentLabel = `Section ${index + 1}`;\n if (segmentCount === 2) segmentLabel = index === 0 ? 'Top Half' : 'Bottom Half';\n\n const segSlots = slots.filter((s) => s.drawPosition >= startPos && s.drawPosition <= endPos);\n\n const segMatchUpsRaw = matchUps.filter((mu) => {\n if (mu.roundNumber > segmentRounds) return false;\n return mu.drawPositions.every((dp) => dp >= startPos && dp <= endPos);\n });\n\n const segMatchUps = renumberRoundPositions(segMatchUpsRaw);\n\n return {\n label: segmentLabel,\n startPosition: startPos,\n endPosition: endPos,\n slots: segSlots,\n matchUps: segMatchUps,\n segmentRounds,\n noWinnerColumn: true,\n };\n}\n\nfunction buildSummarySegment(drawData: DrawData): DrawSegment {\n const { slots, matchUps, totalRounds, roundLabelMap } = drawData;\n const finalRoundsCount = 5;\n const summaryRoundStart = Math.max(1, totalRounds - finalRoundsCount + 1);\n const summaryRounds = totalRounds - summaryRoundStart + 1;\n const roundOffset = summaryRoundStart - 1;\n\n const firstRoundMatchUps = matchUps\n .filter((mu) => mu.roundNumber === summaryRoundStart)\n .sort((a, b) => a.roundPosition - b.roundPosition);\n const summaryDrawSize = firstRoundMatchUps.length * 2;\n\n const positionMap = buildPositionMap(firstRoundMatchUps);\n\n const summaryMatchUps = matchUps.filter((mu) => mu.roundNumber >= summaryRoundStart);\n const renumbered: DrawMatchUp[] = summaryMatchUps.map((mu) => ({\n ...mu,\n roundNumber: mu.roundNumber - roundOffset,\n roundPosition:\n mu.roundNumber === summaryRoundStart\n ? firstRoundMatchUps.findIndex((m) => m.roundPosition === mu.roundPosition) + 1\n : mu.roundPosition,\n drawPositions: mu.drawPositions.map((dp) => positionMap.get(dp) || dp),\n }));\n\n const finalMatchUps = renumberRoundPositions(renumbered);\n\n const summarySlots: DrawSlot[] = [];\n for (const [origPos, newP] of positionMap) {\n const slot = slots.find((s) => s.drawPosition === origPos);\n if (slot) {\n summarySlots.push({ ...slot, drawPosition: newP });\n }\n }\n summarySlots.sort((a, b) => a.drawPosition - b.drawPosition);\n\n const remappedLabels: Record<number, string> | undefined = roundLabelMap\n ? Object.fromEntries(\n Object.entries(roundLabelMap)\n .filter(([rn]) => Number(rn) >= summaryRoundStart)\n .map(([rn, label]) => [Number(rn) - roundOffset, label]),\n )\n : undefined;\n\n return {\n label: 'Final Rounds',\n startPosition: 1,\n endPosition: summaryDrawSize,\n slots: summarySlots,\n matchUps: finalMatchUps,\n segmentRounds: summaryRounds,\n roundLabelMap: remappedLabels,\n };\n}\n\nfunction renumberRoundPositions(matchUps: DrawMatchUp[]): DrawMatchUp[] {\n const byRound = new Map<number, DrawMatchUp[]>();\n for (const mu of matchUps) {\n if (!byRound.has(mu.roundNumber)) byRound.set(mu.roundNumber, []);\n byRound.get(mu.roundNumber)!.push(mu);\n }\n const result: DrawMatchUp[] = [];\n for (const [, roundMus] of byRound) {\n roundMus.sort((a, b) => a.roundPosition - b.roundPosition);\n roundMus.forEach((mu, idx) => {\n result.push({ ...mu, roundPosition: idx + 1 });\n });\n }\n return result;\n}\n\nfunction buildPositionMap(firstRoundMatchUps: DrawMatchUp[]): Map<number, number> {\n const positionMap = new Map<number, number>();\n let newPos = 1;\n for (const mu of firstRoundMatchUps) {\n for (const dp of mu.drawPositions) {\n if (dp && !positionMap.has(dp)) {\n positionMap.set(dp, newPos++);\n }\n }\n }\n return positionMap;\n}\n","/**\n * Compass draw renderer.\n *\n * Renders a compass draw with the main bracket (East) at the top,\n * followed by consolation brackets for each compass direction.\n * Each sub-bracket is a small single-elimination draw rendered\n * with a section header showing the compass direction name.\n *\n * Layout:\n * - Page 1: East (main bracket) — full width, traditional lines\n * - Below or page 2: West, North, South, NE, NW, SE, SW — smaller brackets\n * arranged in a grid layout\n */\n\nimport jsPDF from 'jspdf';\nimport type { DrawFormatConfig, PageRegions } from '../config/types';\nimport type { CompassDrawData, CompassStructure } from '../core/extractCompassData';\nimport type { DrawData } from '../core/extractDrawData';\nimport { renderTraditionalDraw } from './traditionalDraw';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\n// Rendering order: main bracket first, then consolation directions\nconst DIRECTION_ORDER = ['E', 'W', 'N', 'S', 'NE', 'NW', 'SE', 'SW'];\n\nexport function renderCompassDraw(\n doc: jsPDF,\n compassData: CompassDrawData,\n format: DrawFormatConfig,\n regions: PageRegions,\n): void {\n const margins = format.page.margins;\n const sortedStructures = [...compassData.structures].sort(\n (a, b) => DIRECTION_ORDER.indexOf(a.abbreviation) - DIRECTION_ORDER.indexOf(b.abbreviation),\n );\n\n let y = regions.contentY + 3;\n\n for (const structure of sortedStructures) {\n if (structure.drawSize === 0) continue;\n\n // Check if we need a new page\n const estimatedHeight = estimateStructureHeight(structure, regions);\n if (y + estimatedHeight > regions.contentY + regions.contentHeight) {\n doc.addPage();\n y = regions.contentY;\n }\n\n // Section header with compass direction\n const isMain = structure.abbreviation === 'E';\n setFont(doc, isMain ? SIZE.HEADING : SIZE.BODY, STYLE.BOLD);\n if (!isMain) doc.setTextColor(30, 60, 120);\n const label = isMain ? `Main Draw (${structure.name})` : `${structure.name} Draw`;\n doc.text(label, margins.left, y);\n if (!isMain) doc.setTextColor(0);\n y += isMain ? 5 : 4;\n\n // Render the bracket\n const structureRegions: PageRegions = {\n ...regions,\n contentY: y,\n contentHeight: estimatedHeight - 6,\n };\n\n const drawData = structureToDrawData(structure, compassData.drawName);\n renderTraditionalDraw(doc, drawData, format, structureRegions);\n\n y += estimatedHeight + 3;\n }\n}\n\nfunction estimateStructureHeight(structure: CompassStructure, regions: PageRegions): number {\n const maxHeight = regions.contentHeight * 0.7;\n const minLineHeight = 5;\n const lineHeight = Math.max(minLineHeight, Math.min(8, maxHeight / structure.drawSize));\n return structure.drawSize * lineHeight + 10;\n}\n\nfunction structureToDrawData(structure: CompassStructure, drawName: string): DrawData {\n return {\n drawName: `${drawName} - ${structure.name}`,\n drawSize: structure.drawSize,\n drawType: 'SINGLE_ELIMINATION',\n totalRounds: structure.totalRounds,\n slots: structure.slots,\n matchUps: structure.matchUps,\n seedAssignments: [],\n };\n}\n","/**\n * Consolation draw renderer.\n *\n * Renders a main draw followed by consolation bracket(s).\n * The consolation bracket receives first-round losers from the main draw.\n * Each structure is rendered as a separate section with a labeled header.\n *\n * Factory draw types that use this:\n * - FIRST_MATCH_LOSER_CONSOLATION\n * - FIRST_ROUND_LOSER_CONSOLATION\n * - FEED_IN_CHAMPIONSHIP\n * - CURTIS_CONSOLATION\n */\n\nimport jsPDF from 'jspdf';\nimport type { DrawFormatConfig, PageRegions } from '../config/types';\nimport type { DrawData } from '../core/extractDrawData';\nimport { participantName, nationality } from '../utils/primitives';\nimport { renderTraditionalDraw } from './traditionalDraw';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport interface ConsolationStructure {\n name: string;\n stage: string;\n drawData: DrawData;\n}\n\nexport function extractConsolationStructures(params: {\n drawDefinition: any;\n participants?: any[];\n processedMatchUps?: any[];\n}): ConsolationStructure[] {\n const { drawDefinition, participants = [] } = params;\n if (!drawDefinition?.structures) return [];\n\n const participantMap = new Map<string, any>();\n participants.forEach((p: any) => participantMap.set(p.participantId, p));\n\n return drawDefinition.structures.map((structure: any) => {\n const positionAssignments = structure.positionAssignments || [];\n const seedAssignments = structure.seedAssignments || [];\n const drawSize = positionAssignments.length;\n\n const slots = positionAssignments.map((pa: any) => {\n const participant = pa.participantId ? participantMap.get(pa.participantId) : undefined;\n const seed = seedAssignments.find((sa: any) => sa.participantId === pa.participantId);\n return {\n drawPosition: pa.drawPosition,\n participantName: participant ? participantName(participant) : '',\n nationality: participant ? nationality(participant) : '',\n seedValue: seed?.seedValue,\n isBye: pa.bye === true,\n };\n });\n\n const matchUps = (structure.matchUps || []).map((mu: any) => ({\n roundNumber: mu.roundNumber,\n roundPosition: mu.roundPosition,\n drawPositions: mu.drawPositions || [],\n score: mu.score?.scoreStringSide1 || '',\n winningSide: mu.winningSide,\n matchUpStatus: mu.matchUpStatus,\n }));\n\n const stage = structure.stage || 'MAIN';\n const isMain = stage === 'MAIN';\n const name = structure.structureName || (isMain ? 'Main Draw' : 'Consolation');\n\n const maxRound = matchUps.reduce((max: number, mu: any) => Math.max(max, mu.roundNumber || 0), 0);\n\n // Build roundLabelMap from engine-processed matchUps when available\n const structureProcessed = (params.processedMatchUps || []).filter(\n (m: any) => m.structureId === structure.structureId,\n );\n let roundLabelMap: Record<number, string> | undefined;\n if (structureProcessed.length) {\n roundLabelMap = {};\n for (const mu of structureProcessed) {\n if (mu.roundNumber && !roundLabelMap[mu.roundNumber]) {\n roundLabelMap[mu.roundNumber] = mu.abbreviatedRoundName || mu.roundName || `R${mu.roundNumber}`;\n }\n }\n }\n\n return {\n name,\n stage,\n drawData: {\n drawName: name,\n drawSize,\n drawType: 'SINGLE_ELIMINATION',\n totalRounds: maxRound,\n slots,\n matchUps,\n seedAssignments: seedAssignments\n .filter((sa: any) => sa.participantId)\n .map((sa: any) => {\n const p = participantMap.get(sa.participantId);\n return {\n seedValue: sa.seedValue,\n participantName: p ? participantName(p) : '',\n nationality: p ? nationality(p) : '',\n };\n }),\n roundLabelMap,\n },\n };\n });\n}\n\nexport function renderConsolationDraw(\n doc: jsPDF,\n structures: ConsolationStructure[],\n format: DrawFormatConfig,\n regions: PageRegions,\n): void {\n const margins = format.page.margins;\n let y = regions.contentY;\n\n // Sort: MAIN first, then CONSOLATION, then others\n const stageOrder: Record<string, number> = { MAIN: 0, CONSOLATION: 1, PLAY_OFF: 2 };\n const sorted = [...structures]\n .filter((s) => s.drawData.drawSize > 0)\n .sort((a, b) => (stageOrder[a.stage] ?? 9) - (stageOrder[b.stage] ?? 9));\n\n for (const structure of sorted) {\n const isMain = structure.stage === 'MAIN';\n const estimatedHeight = structure.drawData.drawSize * 3.5 + 8;\n\n // New page if needed\n if (y + estimatedHeight > regions.contentY + regions.contentHeight && y > regions.contentY + 10) {\n doc.addPage();\n y = regions.contentY;\n }\n\n // Section header with top padding\n y += 3;\n setFont(doc, isMain ? SIZE.HEADING : SIZE.BODY, STYLE.BOLD);\n if (!isMain) doc.setTextColor(120, 40, 40);\n doc.text(structure.name, margins.left, y);\n if (!isMain) doc.setTextColor(0);\n y += isMain ? 4 : 3;\n\n // Render bracket\n const structureRegions: PageRegions = {\n ...regions,\n contentY: y,\n contentHeight: Math.min(estimatedHeight, regions.contentY + regions.contentHeight - y),\n };\n\n renderTraditionalDraw(doc, structure.drawData, format, structureRegions);\n y += estimatedHeight + 4;\n }\n}\n","/**\n * Double elimination draw renderer.\n *\n * Layout: Winner's bracket (top ~45%) + Loser's bracket (bottom ~45%).\n * Both brackets flow left-to-right.\n *\n * The factory's DOUBLE_ELIMINATION draw type produces three structures:\n * - Main (MAIN) — winner's bracket, includes the championship match as R4\n * - Backdraw (CONSOLATION) — loser's bracket with feed rounds\n * - Decider (PLAY_OFF) — \"if first loss\" match (not rendered; implied by the final)\n *\n * Main bracket round label overrides:\n * - F-Q (qualifying final) → SF (semifinal of the overall tournament)\n * - F (final in main) → F (the championship match)\n * - Winner of F auto-advances to Winner column\n */\n\nimport jsPDF from 'jspdf';\nimport type { DrawFormatConfig, PageRegions } from '../config/types';\nimport type { DrawData } from '../core/extractDrawData';\nimport { renderTraditionalDraw } from './traditionalDraw';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport interface DoubleEliminationData {\n winnersBracket: DrawData;\n losersBracket: DrawData;\n deciderMatch?: DrawData;\n}\n\nexport function renderDoubleEliminationDraw(\n doc: jsPDF,\n data: DoubleEliminationData,\n format: DrawFormatConfig,\n regions: PageRegions,\n): void {\n const margins = format.page.margins;\n const totalHeight = regions.contentHeight;\n\n const winnersHeight = totalHeight * 0.44;\n const losersHeight = totalHeight * 0.44;\n const deciderWidth = 30;\n const bracketWidth = regions.contentWidth - deciderWidth - 8;\n\n // Override main bracket round labels: F-Q → SF, F → F\n const winnersData = overrideMainRoundLabels(data.winnersBracket);\n\n // Winner's bracket header\n let y = regions.contentY + 3;\n setFont(doc, SIZE.BODY, STYLE.BOLD);\n doc.setTextColor(30, 80, 30);\n doc.text(\"Winner's Bracket\", margins.left, y);\n doc.setTextColor(0);\n y += 3;\n\n const winnersRegions: PageRegions = {\n ...regions,\n contentY: y,\n contentHeight: winnersHeight - 6,\n contentWidth: bracketWidth,\n };\n renderTraditionalDraw(doc, winnersData, format, winnersRegions);\n\n // Loser's bracket header\n y = regions.contentY + winnersHeight + 6;\n setFont(doc, SIZE.BODY, STYLE.BOLD);\n doc.setTextColor(140, 40, 40);\n doc.text(\"Loser's Bracket (Backdraw)\", margins.left, y);\n doc.setTextColor(0);\n y += 3;\n\n const losersRegions: PageRegions = {\n ...regions,\n contentY: y,\n contentHeight: losersHeight - 6,\n contentWidth: bracketWidth,\n };\n renderTraditionalDraw(doc, data.losersBracket, format, losersRegions);\n\n // Decider section — positioned to the right of both brackets, vertically centered\n const deciderX = margins.left + bracketWidth + 8;\n const deciderCenterY = regions.contentY + totalHeight / 2;\n const boxWidth = deciderWidth - 2;\n const boxHeight = 14;\n\n // \"Decider\" label\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.text('Decider', deciderX + boxWidth / 2, deciderCenterY - boxHeight - 4, { align: 'center' });\n\n // Solid match box\n doc.setDrawColor(60);\n doc.setLineWidth(0.5);\n doc.rect(deciderX, deciderCenterY - boxHeight - 1, boxWidth, boxHeight);\n\n // Divider in match box\n doc.setLineWidth(0.2);\n doc.line(deciderX, deciderCenterY - boxHeight / 2 - 1, deciderX + boxWidth, deciderCenterY - boxHeight / 2 - 1);\n\n // Populate decider box with participant names if available\n if (data.deciderMatch?.matchUps?.length) {\n const decMu = data.deciderMatch.matchUps[0];\n const slotMap = new Map(data.deciderMatch.slots.map((s) => [s.drawPosition, s]));\n\n if (decMu.drawPositions[0]) {\n const slot = slotMap.get(decMu.drawPositions[0]);\n if (slot?.participantName) {\n const isWinner = decMu.winningSide === 1;\n setFont(doc, SIZE.TINY, isWinner ? STYLE.BOLD : STYLE.NORMAL);\n doc.text(slot.participantName, deciderX + 1, deciderCenterY - boxHeight / 2 - 3, { maxWidth: boxWidth - 2 });\n }\n }\n if (decMu.drawPositions[1]) {\n const slot = slotMap.get(decMu.drawPositions[1]);\n if (slot?.participantName) {\n const isWinner = decMu.winningSide === 2;\n setFont(doc, SIZE.TINY, isWinner ? STYLE.BOLD : STYLE.NORMAL);\n doc.text(slot.participantName, deciderX + 1, deciderCenterY - 3, { maxWidth: boxWidth - 2 });\n }\n }\n\n // Score in the match box\n if (decMu.score) {\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(decMu.score, deciderX + boxWidth - 1, deciderCenterY - boxHeight + 2, { align: 'right' });\n doc.setTextColor(0);\n }\n }\n}\n\n/** Override round labels in the main bracket for double elimination display */\nfunction overrideMainRoundLabels(drawData: DrawData): DrawData {\n const map = { ...(drawData.roundLabelMap || {}) };\n\n for (const r of Object.keys(map)) {\n if (map[Number(r)] === 'F-Q') map[Number(r)] = 'SF';\n }\n\n return { ...drawData, roundLabelMap: map };\n}\n","/**\n * Extract data for compass draws.\n *\n * A compass draw has up to 8 structures named by compass directions:\n * East (main), West, North, NE, South, SW, NW, SE.\n * Each structure is a small single-elimination bracket.\n */\n\nimport { participantName, nationality } from '../utils/primitives';\nimport type { DrawSlot, DrawMatchUp } from './extractDrawData';\n\nexport interface CompassStructure {\n name: string;\n abbreviation: string;\n drawSize: number;\n slots: DrawSlot[];\n matchUps: DrawMatchUp[];\n totalRounds: number;\n}\n\nexport interface CompassDrawData {\n drawName: string;\n structures: CompassStructure[];\n mainStructure?: CompassStructure;\n}\n\nconst COMPASS_NAMES: Record<string, { name: string; abbreviation: string }> = {\n East: { name: 'East', abbreviation: 'E' },\n West: { name: 'West', abbreviation: 'W' },\n North: { name: 'North', abbreviation: 'N' },\n South: { name: 'South', abbreviation: 'S' },\n Northeast: { name: 'Northeast', abbreviation: 'NE' },\n Northwest: { name: 'Northwest', abbreviation: 'NW' },\n Southeast: { name: 'Southeast', abbreviation: 'SE' },\n Southwest: { name: 'Southwest', abbreviation: 'SW' },\n};\n\nexport function extractCompassData(params: { drawDefinition: any; participants?: any[] }): CompassDrawData {\n const { drawDefinition, participants = [] } = params;\n if (!drawDefinition) return { drawName: '', structures: [] };\n\n const participantMap = new Map<string, any>();\n participants.forEach((p: any) => participantMap.set(p.participantId, p));\n\n const structures: CompassStructure[] = [];\n\n for (const structure of drawDefinition.structures || []) {\n const structureName = structure.structureName || '';\n const compassInfo = COMPASS_NAMES[structureName] || { name: structureName, abbreviation: structureName };\n\n const positionAssignments = structure.positionAssignments || [];\n const seedAssignments = structure.seedAssignments || [];\n const drawSize = positionAssignments.length || 0;\n\n const slots: DrawSlot[] = positionAssignments.map((pa: any) => {\n const participant = pa.participantId ? participantMap.get(pa.participantId) : undefined;\n const seedAssignment = seedAssignments.find((sa: any) => sa.participantId === pa.participantId);\n\n return {\n drawPosition: pa.drawPosition,\n participantName: participant ? participantName(participant) : '',\n nationality: participant ? nationality(participant) : '',\n seedValue: seedAssignment?.seedValue,\n isBye: pa.bye === true,\n };\n });\n\n const matchUps: DrawMatchUp[] = (structure.matchUps || []).map((mu: any) => ({\n roundNumber: mu.roundNumber,\n roundPosition: mu.roundPosition,\n drawPositions: mu.drawPositions || [],\n score: mu.score?.scoreStringSide1 || '',\n winningSide: mu.winningSide,\n matchUpStatus: mu.matchUpStatus,\n }));\n\n structures.push({\n name: compassInfo.name,\n abbreviation: compassInfo.abbreviation,\n drawSize,\n slots,\n matchUps,\n totalRounds: drawSize > 0 ? Math.log2(drawSize) : 0,\n });\n }\n\n // Main structure is \"East\"\n const mainStructure = structures.find((s) => s.abbreviation === 'E');\n\n return {\n drawName: drawDefinition.drawName || '',\n structures,\n mainStructure,\n };\n}\n","import jsPDF from 'jspdf';\nimport { setFont, SIZE, STYLE } from './fonts';\n\nexport interface TournamentHeader {\n tournamentName: string;\n startDate?: string;\n endDate?: string;\n location?: string;\n organizer?: string;\n subtitle?: string;\n}\n\nexport function drawTournamentHeader(doc: jsPDF, header: TournamentHeader, startY: number = 15): number {\n const pageWidth = doc.internal.pageSize.getWidth();\n const margin = 15;\n let y = startY;\n\n // Tournament name\n setFont(doc, SIZE.TITLE, STYLE.BOLD);\n doc.text(header.tournamentName, margin, y);\n y += 7;\n\n // Subtitle (e.g., \"Boys Singles - Main Draw\")\n if (header.subtitle) {\n setFont(doc, SIZE.SUBTITLE, STYLE.BOLD);\n doc.text(header.subtitle, margin, y);\n y += 6;\n }\n\n // Date and location on the right\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n const infoLines: string[] = [];\n\n if (header.startDate) {\n const dateStr = header.endDate ? `${header.startDate} - ${header.endDate}` : header.startDate;\n infoLines.push(dateStr);\n }\n if (header.location) infoLines.push(header.location);\n if (header.organizer) infoLines.push(header.organizer);\n\n infoLines.forEach((line, i) => {\n doc.text(line, pageWidth - margin, startY + i * 4, { align: 'right' });\n });\n\n // Separator line\n y += 2;\n doc.setDrawColor(0);\n doc.setLineWidth(0.5);\n doc.line(margin, y, pageWidth - margin, y);\n y += 5;\n\n return y;\n}\n\nexport function drawPageFooter(doc: jsPDF, text: string, pageNumber?: number) {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const margin = 15;\n\n setFont(doc, SIZE.SMALL, STYLE.ITALIC);\n doc.setTextColor(120);\n doc.text(text, margin, pageHeight - 10);\n\n if (pageNumber !== undefined) {\n doc.text(`Page ${pageNumber}`, pageWidth - margin, pageHeight - 10, { align: 'right' });\n }\n\n doc.setTextColor(0);\n}\n","import type { UserOptions } from 'jspdf-autotable';\n\nexport const TABLE_STYLES: Record<string, Partial<UserOptions>> = {\n compact: {\n styles: {\n fontSize: 7,\n cellPadding: 1.5,\n lineWidth: 0.1,\n lineColor: [200, 200, 200],\n },\n headStyles: {\n fillColor: [50, 50, 50],\n textColor: [255, 255, 255],\n fontStyle: 'bold',\n fontSize: 7,\n },\n alternateRowStyles: {\n fillColor: [245, 245, 245],\n },\n },\n schedule: {\n styles: {\n fontSize: 7,\n cellPadding: 2,\n lineWidth: 0.2,\n lineColor: [180, 180, 180],\n valign: 'top',\n },\n headStyles: {\n fillColor: [30, 60, 120],\n textColor: [255, 255, 255],\n fontStyle: 'bold',\n fontSize: 8,\n halign: 'center',\n },\n alternateRowStyles: {\n fillColor: [240, 244, 250],\n },\n },\n playerList: {\n styles: {\n fontSize: 8,\n cellPadding: 2,\n lineWidth: 0.1,\n lineColor: [200, 200, 200],\n },\n headStyles: {\n fillColor: [40, 80, 40],\n textColor: [255, 255, 255],\n fontStyle: 'bold',\n fontSize: 8,\n },\n alternateRowStyles: {\n fillColor: [242, 248, 242],\n },\n },\n report: {\n styles: {\n fontSize: 8,\n cellPadding: 2,\n lineWidth: 0.1,\n lineColor: [200, 200, 200],\n },\n headStyles: {\n fillColor: [35, 55, 90],\n textColor: [255, 255, 255],\n fontStyle: 'bold',\n fontSize: 8,\n },\n alternateRowStyles: {\n fillColor: [244, 246, 250],\n },\n },\n courtCard: {\n styles: {\n fontSize: 14,\n cellPadding: 6,\n lineWidth: 0.3,\n lineColor: [100, 100, 100],\n halign: 'center',\n },\n headStyles: {\n fillColor: [20, 20, 80],\n textColor: [255, 255, 255],\n fontStyle: 'bold',\n fontSize: 16,\n },\n },\n};\n","import jsPDF from 'jspdf';\nimport { setFont, SIZE, STYLE } from './fonts';\n\nexport interface BracketPosition {\n x: number;\n y: number;\n width: number;\n height: number;\n participantName?: string;\n seed?: number;\n nationality?: string;\n score?: string;\n isBye?: boolean;\n}\n\nexport interface BracketConfig {\n slotWidth: number;\n slotHeight: number;\n roundGap: number;\n verticalGap: number;\n startX: number;\n startY: number;\n}\n\nexport const DEFAULT_BRACKET_CONFIG: BracketConfig = {\n slotWidth: 90,\n slotHeight: 14,\n roundGap: 20,\n verticalGap: 4,\n startX: 15,\n startY: 10,\n};\n\nexport function calculateBracketPositions(\n drawSize: number,\n config: BracketConfig = DEFAULT_BRACKET_CONFIG,\n availableHeight?: number,\n) {\n const rounds = Math.log2(drawSize);\n const positions: BracketPosition[][] = [];\n\n // Calculate spacing to fit all first-round slots within available height\n const firstRoundSlots = drawSize;\n let spacing = config.slotHeight + config.verticalGap;\n\n if (availableHeight) {\n const neededHeight = firstRoundSlots * spacing;\n if (neededHeight > availableHeight) {\n spacing = availableHeight / firstRoundSlots;\n }\n }\n\n const slotHeight = Math.max(spacing * 0.7, 5);\n\n for (let round = 0; round < rounds; round++) {\n const matchesInRound = drawSize / Math.pow(2, round + 1);\n const roundPositions: BracketPosition[] = [];\n\n for (let match = 0; match < matchesInRound; match++) {\n const roundOffset = Math.pow(2, round) * spacing;\n const baseY = config.startY + roundOffset / 2 - spacing / 2;\n\n const topY = baseY + match * roundOffset * 2;\n const bottomY = topY + roundOffset;\n\n const x = config.startX + round * (config.slotWidth + config.roundGap);\n\n roundPositions.push(\n { x, y: topY, width: config.slotWidth, height: slotHeight },\n { x, y: bottomY, width: config.slotWidth, height: slotHeight },\n );\n }\n\n positions.push(roundPositions);\n }\n\n return positions;\n}\n\nexport function drawBracketSlot(doc: jsPDF, pos: BracketPosition) {\n // Draw slot box\n doc.setDrawColor(150);\n doc.setLineWidth(0.3);\n doc.rect(pos.x, pos.y, pos.width, pos.height);\n\n if (pos.isBye) {\n setFont(doc, SIZE.SMALL, STYLE.ITALIC);\n doc.setTextColor(150);\n doc.text('Bye', pos.x + 2, pos.y + pos.height / 2 + 1.5);\n doc.setTextColor(0);\n return;\n }\n\n if (pos.participantName) {\n // Seed number\n if (pos.seed) {\n setFont(doc, SIZE.TINY, STYLE.BOLD);\n doc.text(`[${pos.seed}]`, pos.x + 1, pos.y + pos.height / 2 + 1);\n setFont(doc, SIZE.SMALL, STYLE.NORMAL);\n doc.text(pos.participantName, pos.x + 9, pos.y + pos.height / 2 + 1);\n } else {\n setFont(doc, SIZE.SMALL, STYLE.NORMAL);\n doc.text(pos.participantName, pos.x + 2, pos.y + pos.height / 2 + 1);\n }\n\n // Nationality on right\n if (pos.nationality) {\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.setTextColor(100);\n doc.text(pos.nationality, pos.x + pos.width - 2, pos.y + pos.height / 2 + 1, { align: 'right' });\n doc.setTextColor(0);\n }\n }\n}\n\nexport function drawBracketConnectors(doc: jsPDF, positions: BracketPosition[][], config: BracketConfig) {\n doc.setDrawColor(100);\n doc.setLineWidth(0.3);\n\n for (let round = 0; round < positions.length - 1; round++) {\n const currentRound = positions[round];\n const nextRound = positions[round + 1];\n\n for (let i = 0; i < currentRound.length; i += 2) {\n const top = currentRound[i];\n const bottom = currentRound[i + 1];\n const nextSlot = nextRound[Math.floor(i / 2)];\n\n if (!top || !bottom || !nextSlot) continue;\n\n const rightX = top.x + top.width;\n const midX = rightX + config.roundGap / 2;\n const topMidY = top.y + top.height / 2;\n const bottomMidY = bottom.y + bottom.height / 2;\n const nextMidY = nextSlot.y + nextSlot.height / 2;\n\n // Horizontal from top slot\n doc.line(rightX, topMidY, midX, topMidY);\n // Horizontal from bottom slot\n doc.line(rightX, bottomMidY, midX, bottomMidY);\n // Vertical connector\n doc.line(midX, topMidY, midX, bottomMidY);\n // Horizontal to next round\n doc.line(midX, nextMidY, nextSlot.x, nextMidY);\n }\n }\n}\n\nexport function drawScore(doc: jsPDF, score: string, x: number, y: number) {\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.setTextColor(60, 60, 180);\n doc.text(score, x, y);\n doc.setTextColor(0);\n}\n","import jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport { drawTournamentHeader, drawPageFooter, type TournamentHeader } from '../layout/headers';\nimport { TABLE_STYLES } from '../layout/tables';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\nimport {\n calculateBracketPositions,\n drawBracketSlot,\n drawBracketConnectors,\n drawScore,\n type BracketConfig,\n DEFAULT_BRACKET_CONFIG,\n} from '../layout/brackets';\nimport { getRoundLabel, type DrawData } from '../core/extractDrawData';\n\nexport interface DrawSheetOptions {\n header?: TournamentHeader;\n includeSeedings?: boolean;\n includeScores?: boolean;\n}\n\nexport function generateDrawSheetPDF(drawData: DrawData, options: DrawSheetOptions = {}): jsPDF {\n const { header, includeSeedings = true, includeScores = true } = options;\n\n // Landscape for 32+ draws to fit bracket width\n const landscape = drawData.drawSize >= 32;\n const doc = new jsPDF({ orientation: landscape ? 'landscape' : 'portrait', format: 'a4' });\n\n let startY = 15;\n if (header) {\n const subtitle = `${drawData.drawName} - ${drawData.drawType.replace(/_/g, ' ')} (${drawData.drawSize})`;\n startY = drawTournamentHeader(doc, { ...header, subtitle });\n }\n\n // For small draws (<=16), draw the bracket directly\n if (drawData.drawSize <= 64 && drawData.drawSize > 0) {\n startY = drawBracket(doc, drawData, startY, includeScores);\n } else {\n // For very large draws, fall back to tabular format\n startY = drawTabularDraw(doc, drawData, startY);\n }\n\n // Seeded players table\n if (includeSeedings && drawData.seedAssignments.length > 0) {\n drawSeedingsTable(doc, drawData, startY + 8);\n }\n\n drawPageFooter(doc, `Generated ${new Date().toLocaleDateString()}`);\n\n return doc;\n}\n\nfunction drawBracket(doc: jsPDF, drawData: DrawData, startY: number, includeScores: boolean): number {\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n\n // Calculate config based on draw size and available space\n const availableWidth = pageWidth - 30;\n const availableHeight = pageHeight - startY - 30;\n const totalRounds = drawData.totalRounds;\n\n const slotWidth = Math.min(90, (availableWidth - totalRounds * 10) / totalRounds);\n const slotHeight = Math.min(14, availableHeight / drawData.drawSize);\n\n const config: BracketConfig = {\n ...DEFAULT_BRACKET_CONFIG,\n slotWidth,\n slotHeight,\n verticalGap: Math.max(1, slotHeight * 0.3),\n startX: 15,\n startY,\n };\n\n const positions = calculateBracketPositions(drawData.drawSize, config, availableHeight);\n\n // Fill positions with participant data\n const slotMap = new Map(drawData.slots.map((s) => [s.drawPosition, s]));\n\n // Round headers\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n for (let round = 0; round < totalRounds; round++) {\n const x = config.startX + round * (config.slotWidth + config.roundGap);\n const label = getRoundLabel(round + 1, totalRounds);\n doc.text(label, x + config.slotWidth / 2, startY - 2, { align: 'center' });\n }\n\n // Draw first round slots with participant names\n if (positions.length > 0) {\n const firstRound = positions[0];\n for (let i = 0; i < firstRound.length; i++) {\n const drawPosition = i + 1;\n const slot = slotMap.get(drawPosition);\n if (slot) {\n firstRound[i].participantName = slot.participantName;\n firstRound[i].nationality = slot.nationality;\n firstRound[i].seed = slot.seedValue;\n firstRound[i].isBye = slot.isBye;\n }\n }\n\n // Draw slots for each round\n for (const round of positions) {\n for (const pos of round) {\n drawBracketSlot(doc, pos);\n }\n }\n\n // Draw connector lines\n drawBracketConnectors(doc, positions, config);\n\n // Draw scores on connectors\n if (includeScores) {\n for (const mu of drawData.matchUps) {\n if (!mu.score) continue;\n const roundIdx = mu.roundNumber - 1;\n if (roundIdx < positions.length) {\n const matchIdx = (mu.roundPosition - 1) * 2;\n const pos = positions[roundIdx]?.[matchIdx];\n if (pos) {\n drawScore(doc, mu.score, pos.x + pos.width + 2, pos.y + pos.height + 3);\n }\n }\n }\n }\n\n // Return bottom of bracket\n const lastRoundBottom = positions[0][positions[0].length - 1];\n return lastRoundBottom.y + lastRoundBottom.height + 5;\n }\n\n return startY;\n}\n\nfunction drawTabularDraw(doc: jsPDF, drawData: DrawData, startY: number): number {\n const columns = [\n { header: 'Pos', dataKey: 'pos' },\n { header: 'Seed', dataKey: 'seed' },\n { header: 'Player', dataKey: 'name' },\n { header: 'Nat.', dataKey: 'nat' },\n { header: 'Entry', dataKey: 'entry' },\n ];\n\n const body = drawData.slots.map((s) => ({\n pos: s.drawPosition,\n seed: s.seedValue?.toString() || '',\n name: s.isBye ? 'Bye' : s.participantName,\n nat: s.nationality,\n entry: s.entryStatus || '',\n }));\n\n autoTable(doc, {\n ...TABLE_STYLES.compact,\n startY,\n columns,\n body,\n columnStyles: {\n pos: { cellWidth: 12, halign: 'center' },\n seed: { cellWidth: 12, halign: 'center' },\n name: { cellWidth: 'auto' },\n nat: { cellWidth: 15, halign: 'center' },\n entry: { cellWidth: 15, halign: 'center' },\n },\n });\n\n return (doc as any).lastAutoTable?.finalY || startY + 20;\n}\n\nfunction drawSeedingsTable(doc: jsPDF, drawData: DrawData, startY: number): number {\n setFont(doc, SIZE.HEADING, STYLE.BOLD);\n doc.text('Seeded Players', 15, startY);\n startY += 4;\n\n const columns = [\n { header: 'Seed', dataKey: 'seed' },\n { header: 'Player', dataKey: 'name' },\n { header: 'Nat.', dataKey: 'nat' },\n ];\n\n const body = drawData.seedAssignments.map((s) => ({\n seed: s.seedValue,\n name: s.participantName,\n nat: s.nationality,\n }));\n\n autoTable(doc, {\n ...TABLE_STYLES.compact,\n startY,\n columns,\n body,\n tableWidth: 120,\n columnStyles: {\n seed: { cellWidth: 15, halign: 'center', fontStyle: 'bold' },\n name: { cellWidth: 'auto' },\n nat: { cellWidth: 20, halign: 'center' },\n },\n });\n\n return (doc as any).lastAutoTable?.finalY || startY + 20;\n}\n","import jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport { drawTournamentHeader, drawPageFooter, type TournamentHeader } from '../layout/headers';\nimport { TABLE_STYLES } from '../layout/tables';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\nimport type { ScheduleData } from '../core/extractScheduleData';\n\nexport interface ScheduleOptions {\n header?: TournamentHeader;\n landscape?: boolean | 'auto';\n fullCourtNames?: boolean;\n notes?: string[];\n}\n\nexport function generateSchedulePDF(scheduleData: ScheduleData, options: ScheduleOptions = {}): jsPDF {\n const { header, fullCourtNames = true, notes } = options;\n\n const autoLandscape = options.landscape === 'auto' ? scheduleData.courts.length >= 5 : options.landscape;\n const orientation = autoLandscape ? 'landscape' : 'portrait';\n\n const doc = new jsPDF({ orientation, format: 'a4' });\n let startY = 15;\n\n if (header) {\n const subtitle = scheduleData.scheduledDate ? `Order of Play - ${scheduleData.scheduledDate}` : 'Order of Play';\n startY = drawTournamentHeader(doc, { ...header, subtitle });\n }\n\n const courts = scheduleData.courts;\n const courtHeaders = fullCourtNames ? courts : courts.map(abbrevCourt);\n\n for (const timeSlot of scheduleData.timeSlots) {\n // Time slot label\n setFont(doc, SIZE.BODY, STYLE.BOLD);\n doc.setTextColor(30, 60, 120);\n doc.text(timeSlot.label, 15, startY);\n doc.setTextColor(0);\n startY += 4;\n\n // Build table: one column per court\n const columns = courtHeaders.map((name) => ({ header: name, dataKey: name }));\n\n // Group matches by court for this time slot\n const courtMatches = new Map<string, string[]>();\n courts.forEach((c) => courtMatches.set(c, []));\n\n for (const match of timeSlot.matches) {\n const content = formatMatchCell(match);\n const existing = courtMatches.get(match.courtName) || [];\n existing.push(content);\n courtMatches.set(match.courtName, existing);\n }\n\n // Find max rows needed\n const maxRows = Math.max(1, ...Array.from(courtMatches.values()).map((v) => v.length));\n\n const body: Record<string, string>[] = [];\n for (let row = 0; row < maxRows; row++) {\n const rowData: Record<string, string> = {};\n courts.forEach((court, i) => {\n const matches = courtMatches.get(court) || [];\n const key = fullCourtNames ? court : courtHeaders[i];\n rowData[key] = matches[row] || '';\n });\n body.push(rowData);\n }\n\n autoTable(doc, {\n ...TABLE_STYLES.schedule,\n startY,\n columns,\n body,\n tableWidth: 'auto',\n didDrawPage: (data) => {\n drawPageFooter(doc, header?.tournamentName || '', data.pageNumber);\n },\n });\n\n startY = (doc as any).lastAutoTable?.finalY + 6 || startY + 20;\n }\n\n // Notes section\n if (notes?.length) {\n startY += 4;\n setFont(doc, SIZE.SMALL, STYLE.ITALIC);\n doc.setTextColor(80);\n for (const note of notes) {\n doc.text(note, 15, startY);\n startY += 4;\n }\n doc.setTextColor(0);\n }\n\n return doc;\n}\n\nfunction formatMatchCell(match: any): string {\n const lines: string[] = [];\n lines.push(`${match.eventAbbr} ${match.roundName}`);\n lines.push(`${match.side1.name} (${match.side1.nationality})`);\n lines.push(`vs ${match.side2.name} (${match.side2.nationality})`);\n if (match.score) lines.push(match.score);\n return lines.join('\\n');\n}\n\nfunction abbrevCourt(name: string): string {\n return name.replace(/^Court\\s*/i, 'Ct ');\n}\n","import jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport { drawTournamentHeader, drawPageFooter, type TournamentHeader } from '../layout/headers';\nimport { TABLE_STYLES } from '../layout/tables';\nimport type { ParticipantRow } from '../core/extractParticipantData';\n\nexport interface PlayerListOptions {\n header?: TournamentHeader;\n includeRanking?: boolean;\n includeEvents?: boolean;\n groupByEvent?: boolean;\n}\n\nexport function generatePlayerListPDF(players: ParticipantRow[], options: PlayerListOptions = {}): jsPDF {\n const { header, includeRanking = true, includeEvents = true } = options;\n\n const doc = new jsPDF({ orientation: 'portrait', format: 'a4' });\n let startY = 15;\n\n if (header) {\n startY = drawTournamentHeader(doc, { ...header, subtitle: header.subtitle || 'Player List' });\n }\n\n const columns: any[] = [\n { header: '#', dataKey: 'index' },\n { header: 'Name', dataKey: 'name' },\n { header: 'Nat.', dataKey: 'nationality' },\n ];\n\n if (includeRanking) columns.push({ header: 'Rank', dataKey: 'ranking' });\n columns.push({ header: 'Seed', dataKey: 'seed' });\n columns.push({ header: 'Entry', dataKey: 'entryStatus' });\n if (includeEvents) columns.push({ header: 'Events', dataKey: 'events' });\n\n const body = players.map((p, i) => ({\n index: i + 1,\n name: p.name,\n nationality: p.nationality,\n ranking: p.ranking || '',\n seed: p.seedValue?.toString() || '',\n entryStatus: p.entryStatus,\n events: p.events.join(', '),\n }));\n\n autoTable(doc, {\n ...TABLE_STYLES.playerList,\n startY,\n columns,\n body,\n columnStyles: {\n index: { cellWidth: 10, halign: 'center' },\n name: { cellWidth: 'auto', fontStyle: 'bold' },\n nationality: { cellWidth: 15, halign: 'center' },\n ranking: { cellWidth: 15, halign: 'center' },\n seed: { cellWidth: 12, halign: 'center' },\n entryStatus: { cellWidth: 15, halign: 'center' },\n events: { cellWidth: 'auto' },\n },\n didDrawPage: (data) => {\n drawPageFooter(doc, `Generated ${new Date().toLocaleDateString()}`, data.pageNumber);\n },\n });\n\n return doc;\n}\n","import jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\nimport type { CourtCardData } from '../core/extractCourtCardData';\n\nexport interface CourtCardOptions {\n tournamentName?: string;\n pageSize?: 'a4' | 'a5' | 'letter';\n cardsPerPage?: number;\n}\n\nexport function generateCourtCardPDF(cards: CourtCardData[], options: CourtCardOptions = {}): jsPDF {\n const { tournamentName = '', pageSize = 'a5', cardsPerPage = 1 } = options;\n const doc = new jsPDF({ orientation: 'landscape', format: pageSize });\n\n cards.forEach((card, index) => {\n if (index > 0) doc.addPage();\n drawCourtCard(doc, card, tournamentName, cardsPerPage);\n });\n\n return doc;\n}\n\nfunction drawCourtCard(doc: jsPDF, card: CourtCardData, tournamentName: string, _cardsPerPage: number) {\n const pageWidth = doc.internal.pageSize.getWidth();\n const centerX = pageWidth / 2;\n let y = 15;\n\n // Tournament name (small, top)\n if (tournamentName) {\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n doc.setTextColor(100);\n doc.text(tournamentName, centerX, y, { align: 'center' });\n doc.setTextColor(0);\n y += 8;\n }\n\n // Court name (large, prominent)\n setFont(doc, 28, STYLE.BOLD);\n doc.text(card.courtName, centerX, y, { align: 'center' });\n y += 5;\n\n if (card.venueName) {\n setFont(doc, SIZE.HEADING, STYLE.NORMAL);\n doc.setTextColor(100);\n doc.text(card.venueName, centerX, y, { align: 'center' });\n doc.setTextColor(0);\n }\n y += 8;\n\n // Separator\n doc.setDrawColor(0);\n doc.setLineWidth(1);\n doc.line(30, y, pageWidth - 30, y);\n y += 8;\n\n // Current match\n if (card.currentMatch) {\n setFont(doc, SIZE.HEADING, STYLE.BOLD);\n doc.setTextColor(30, 60, 120);\n doc.text('NOW PLAYING', centerX, y, { align: 'center' });\n doc.setTextColor(0);\n y += 6;\n\n setFont(doc, SIZE.BODY, STYLE.ITALIC);\n doc.text(`${card.currentMatch.eventName} - ${card.currentMatch.roundName}`, centerX, y, { align: 'center' });\n y += 8;\n\n // Player names - large\n autoTable(doc, {\n startY: y,\n margin: { left: 25, right: 25 },\n theme: 'plain',\n styles: { halign: 'center', fontSize: 16, cellPadding: 4 },\n body: [\n [\n {\n content: `${card.currentMatch.side1.name} (${card.currentMatch.side1.nationality})`,\n styles: { fontStyle: 'bold' },\n },\n ],\n [{ content: 'vs.', styles: { fontSize: 12, textColor: [120, 120, 120] } }],\n [\n {\n content: `${card.currentMatch.side2.name} (${card.currentMatch.side2.nationality})`,\n styles: { fontStyle: 'bold' },\n },\n ],\n ],\n });\n\n y = (doc as any).lastAutoTable?.finalY || y + 40;\n y += 8;\n }\n\n // Next match\n if (card.nextMatch) {\n doc.setDrawColor(180);\n doc.setLineWidth(0.3);\n doc.line(50, y, pageWidth - 50, y);\n y += 6;\n\n setFont(doc, SIZE.BODY, STYLE.BOLD);\n doc.setTextColor(100);\n const upNextLabel = card.nextMatch.scheduledTime ? `UP NEXT (${card.nextMatch.scheduledTime})` : 'UP NEXT';\n doc.text(upNextLabel, centerX, y, { align: 'center' });\n doc.setTextColor(0);\n y += 5;\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n doc.text(`${card.nextMatch.eventName} - ${card.nextMatch.roundName}`, centerX, y, { align: 'center' });\n y += 5;\n\n setFont(doc, SIZE.HEADING, STYLE.NORMAL);\n doc.text(`${card.nextMatch.side1.name} vs. ${card.nextMatch.side2.name}`, centerX, y, { align: 'center' });\n }\n}\n","import jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport { drawTournamentHeader, type TournamentHeader } from '../layout/headers';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\nimport type { ParticipantRow } from '../core/extractParticipantData';\n\nexport interface SignInSheetOptions {\n header?: TournamentHeader;\n eventName?: string;\n signInDate?: string;\n signInTime?: string;\n}\n\nexport function generateSignInSheetPDF(players: ParticipantRow[], options: SignInSheetOptions = {}): jsPDF {\n const { header, eventName, signInDate, signInTime } = options;\n const doc = new jsPDF({ orientation: 'portrait', format: 'a4' });\n let startY = 15;\n\n if (header) {\n startY = drawTournamentHeader(doc, { ...header, subtitle: header.subtitle || 'Player Sign-In Sheet' });\n }\n\n // Event/date info\n if (eventName || signInDate) {\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n const infoLine: string[] = [];\n if (eventName) infoLine.push(`Event: ${eventName}`);\n if (signInDate) infoLine.push(`Date: ${signInDate}`);\n if (signInTime) infoLine.push(`Time: ${signInTime}`);\n doc.text(infoLine.join(' | '), 15, startY);\n startY += 6;\n }\n\n const columns = [\n { header: '#', dataKey: 'index' },\n { header: 'Player Name', dataKey: 'name' },\n { header: 'Nat.', dataKey: 'nationality' },\n { header: 'Rank', dataKey: 'ranking' },\n { header: 'Seed', dataKey: 'seed' },\n { header: 'Entry', dataKey: 'entry' },\n { header: 'Signature', dataKey: 'signature' },\n { header: 'Time', dataKey: 'time' },\n ];\n\n const body = players.map((p, i) => ({\n index: i + 1,\n name: p.name,\n nationality: p.nationality,\n ranking: p.ranking || '',\n seed: p.seedValue?.toString() || '',\n entry: p.entryStatus,\n signature: '',\n time: '',\n }));\n\n autoTable(doc, {\n startY,\n columns,\n body,\n styles: {\n fontSize: 8,\n cellPadding: 1.5,\n lineWidth: 0.2,\n lineColor: [150, 150, 150],\n },\n headStyles: {\n fillColor: [40, 60, 100],\n textColor: [255, 255, 255],\n fontStyle: 'bold',\n fontSize: 7,\n cellPadding: 2,\n },\n alternateRowStyles: {\n fillColor: [245, 247, 250],\n },\n columnStyles: {\n index: { cellWidth: 10, halign: 'center' },\n name: { cellWidth: 'auto', fontStyle: 'bold' },\n nationality: { cellWidth: 14, halign: 'center' },\n ranking: { cellWidth: 14, halign: 'center' },\n seed: { cellWidth: 14, halign: 'center' },\n entry: { cellWidth: 14, halign: 'center' },\n signature: { cellWidth: 35 },\n time: { cellWidth: 15 },\n },\n });\n\n return doc;\n}\n","/**\n * Professional Order of Play / Schedule PDF generator.\n *\n * Modeled after the ITF J300 reference OOP:\n * - Courts as columns, time slots as numbered rows\n * - 3-zone cell: event/round header, player names with nationalities, score footer\n * - \"Not Before\" and \"Starting at\" time labels\n * - Landscape for 5+ courts, portrait for fewer\n * - Professional header with tournament info and \"ORDER OF PLAY\" title\n * - Footer with notes, officials, timestamp\n */\n\nimport jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport type { ScheduleData, ScheduleMatch } from '../core/extractScheduleData';\nimport type { HeaderConfig, FooterConfig, PageConfig } from '../config/types';\nimport { renderHeader } from '../composition/headerLayouts';\nimport { renderFooter, measureFooterHeight } from '../composition/footerLayouts';\nimport { createDoc } from '../composition/page';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport interface ScheduleV2Options {\n header?: HeaderConfig;\n footer?: FooterConfig;\n page?: Partial<PageConfig>;\n alertBanner?: string;\n notes?: string[];\n officials?: { role: string; name: string }[];\n showMatchNumbers?: boolean;\n cellStyle?: 'detailed' | 'compact';\n}\n\nexport function generateScheduleV2PDF(scheduleData: ScheduleData, options: ScheduleV2Options = {}): jsPDF {\n const courts = scheduleData.courts;\n const autoLandscape = courts.length >= 4;\n const pageConfig: PageConfig = {\n pageSize: options.page?.pageSize || 'a4',\n orientation: options.page?.orientation || (autoLandscape ? 'landscape' : 'portrait'),\n margins: options.page?.margins || { top: 12, right: 8, bottom: 10, left: 8 },\n };\n\n const doc = createDoc(pageConfig);\n const footerConfig: FooterConfig = options.footer || {\n layout: 'standard',\n showTimestamp: true,\n showPageNumbers: true,\n };\n const footerH = measureFooterHeight(footerConfig) + (options.notes?.length ? options.notes.length * 3 : 0);\n\n let startY = pageConfig.margins.top;\n\n // Header\n if (options.header) {\n const headerH = renderHeader(doc, options.header, pageConfig);\n startY = pageConfig.margins.top + headerH;\n }\n\n // Alert banner (red background, white text)\n if (options.alertBanner) {\n startY = renderAlertBanner(doc, options.alertBanner, pageConfig, startY);\n }\n\n // Build the schedule table\n const tableStartY = startY;\n renderScheduleTable(doc, scheduleData, pageConfig, tableStartY, options);\n\n // Notes section above footer\n const pageHeight = doc.internal.pageSize.getHeight();\n if (options.notes?.length) {\n let notesY = pageHeight - pageConfig.margins.bottom - footerH + 2;\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(80);\n for (const note of options.notes) {\n doc.text(note, pageConfig.margins.left, notesY);\n notesY += 3;\n }\n doc.setTextColor(0);\n }\n\n // Officials row\n if (options.officials?.length) {\n const officialsY = pageHeight - pageConfig.margins.bottom - 6;\n renderOfficialsRow(doc, options.officials, pageConfig, officialsY);\n }\n\n // Footer\n renderFooter(doc, footerConfig, pageConfig, 1);\n\n return doc;\n}\n\nfunction renderAlertBanner(doc: jsPDF, text: string, pageConfig: PageConfig, y: number): number {\n const { margins } = pageConfig;\n const pageWidth = doc.internal.pageSize.getWidth();\n const bannerWidth = pageWidth - margins.left - margins.right;\n\n doc.setFillColor(200, 30, 30);\n doc.rect(margins.left, y, bannerWidth, 7, 'F');\n\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.setTextColor(255, 255, 255);\n doc.text(text, pageWidth / 2, y + 4.5, { align: 'center' });\n doc.setTextColor(0);\n\n return y + 9;\n}\n\nfunction renderScheduleTable(\n doc: jsPDF,\n scheduleData: ScheduleData,\n pageConfig: PageConfig,\n startY: number,\n options: ScheduleV2Options,\n): void {\n const { margins } = pageConfig;\n const courts = scheduleData.courts;\n const isCompact = options.cellStyle === 'compact';\n\n // Build column definitions: slot # + one column per court\n const columns: any[] = [{ header: '', dataKey: 'slot' }];\n for (const court of courts) {\n columns.push({ header: court, dataKey: court });\n }\n\n // Build rows: one per time slot\n const body: any[][] = [];\n\n scheduleData.timeSlots.forEach((slot, slotIdx) => {\n const row: any[] = [];\n\n // Slot number + time label\n const timeLabel = buildTimeLabel(slot, slotIdx);\n row.push({ content: timeLabel, styles: { fontStyle: 'bold', valign: 'top', cellWidth: 12 } });\n\n // One cell per court\n for (const court of courts) {\n const courtMatches = slot.matches.filter((m) => m.courtName === court);\n const cellContent =\n courtMatches.length > 0 ? courtMatches.map((m) => formatCellContent(m, isCompact)).join('\\n---\\n') : '';\n row.push(cellContent);\n }\n\n body.push(row);\n });\n\n autoTable(doc, {\n startY,\n head: [columns.map((c) => c.header)],\n body,\n styles: {\n fontSize: isCompact ? 6 : 6.5,\n cellPadding: isCompact ? 1.5 : 2,\n lineWidth: 0.3,\n lineColor: [80, 80, 80],\n valign: 'top',\n overflow: 'linebreak',\n },\n headStyles: {\n fillColor: [255, 255, 255],\n textColor: [0, 0, 0],\n fontStyle: 'bold',\n fontSize: 7,\n halign: 'center',\n lineWidth: 0.5,\n lineColor: [0, 0, 0],\n },\n columnStyles: {\n 0: { cellWidth: 14, fontStyle: 'bold' },\n },\n alternateRowStyles: {\n fillColor: [252, 252, 252],\n },\n margin: { left: margins.left, right: margins.right },\n tableWidth: 'auto',\n didParseCell: (data) => {\n if (data.column.index > 0 && data.section === 'body') {\n // Court columns: equal width, centered text\n const availableWidth = doc.internal.pageSize.getWidth() - margins.left - margins.right - 14;\n data.cell.styles.cellWidth = availableWidth / courts.length;\n data.cell.styles.halign = 'center';\n data.cell.styles.valign = 'middle';\n }\n },\n });\n}\n\nfunction buildTimeLabel(_slot: any, slotIdx: number): string {\n return `${slotIdx + 1}`;\n}\n\nfunction formatCellContent(match: ScheduleMatch, isCompact: boolean): string {\n const lines: string[] = [];\n\n // Scheduling info (per-match time details)\n if (match.notBeforeTime) {\n lines.push(`NB ${match.notBeforeTime}`);\n } else if (match.scheduledTime) {\n lines.push(match.scheduledTime);\n }\n\n // Event + Round (header zone)\n if (match.eventAbbr || match.roundName) {\n lines.push(`${match.eventAbbr} ${match.roundName}`.trim());\n }\n\n // Player 1\n const p1 = formatPlayer(match.side1, isCompact);\n if (p1) lines.push(p1);\n\n // \"vs.\" divider\n lines.push('vs.');\n\n // Player 2\n const p2 = formatPlayer(match.side2, isCompact);\n if (p2) lines.push(p2);\n\n // Score or status (footer zone)\n if (match.score) {\n lines.push(match.score);\n } else if (match.matchUpStatus === 'IN_PROGRESS') {\n lines.push('In progress');\n }\n\n return lines.join('\\n');\n}\n\nfunction formatPlayer(side: { name: string; nationality: string }, isCompact: boolean): string {\n if (!side.name) return 'TBD';\n if (isCompact) return `${side.name} (${side.nationality})`;\n return side.nationality ? `${side.name} (${side.nationality})` : side.name;\n}\n\nfunction renderOfficialsRow(\n doc: jsPDF,\n officials: { role: string; name: string }[],\n pageConfig: PageConfig,\n y: number,\n): void {\n const { margins } = pageConfig;\n const pageWidth = doc.internal.pageSize.getWidth();\n\n doc.setDrawColor(120);\n doc.setLineWidth(0.2);\n doc.line(margins.left, y - 2, pageWidth - margins.right, y - 2);\n\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n const spacing = (pageWidth - margins.left - margins.right) / officials.length;\n\n officials.forEach((official, i) => {\n const x = margins.left + i * spacing;\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(100);\n doc.text(official.role, x, y);\n setFont(doc, SIZE.TINY, STYLE.BOLD);\n doc.setTextColor(0);\n doc.text(official.name, x, y + 3);\n });\n}\n","/**\n * Sequential Order of Play renderer (WTA/ATP/Grand Slam style).\n *\n * Portrait A4, courts stacked vertically with match boxes in sequence.\n * This is the format used by WTA, ATP, and Grand Slam tournaments.\n *\n * Layout per court:\n * COURT NAME (centered, bold, uppercase)\n * [Starting at X:XX PM] (colored bar)\n * ┌─────────────────────┐\n * │ [1] Player One NAT │ Round label\n * │ vs │\n * │ [3] Player Two NAT │\n * └─────────────────────┘\n * [Not before X:XX PM] (colored bar)\n * ┌─────────────────────┐\n * │ Match 2... │\n * └─────────────────────┘\n */\n\nimport jsPDF from 'jspdf';\nimport type { ScheduleData, ScheduleMatch } from '../core/extractScheduleData';\nimport type { HeaderConfig, FooterConfig, PageConfig } from '../config/types';\nimport { renderHeader } from '../composition/headerLayouts';\nimport { renderFooter, measureFooterHeight } from '../composition/footerLayouts';\nimport { createDoc } from '../composition/page';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport interface SequentialOOPOptions {\n header?: HeaderConfig;\n footer?: FooterConfig;\n page?: Partial<PageConfig>;\n accentColor?: [number, number, number];\n disclaimer?: string;\n officials?: { role: string; name: string }[];\n}\n\nconst DEFAULT_ACCENT: [number, number, number] = [120, 50, 140]; // WTA purple\n\nexport function generateSequentialOOP(scheduleData: ScheduleData, options: SequentialOOPOptions = {}): jsPDF {\n const pageConfig: PageConfig = {\n pageSize: options.page?.pageSize || 'a4',\n orientation: options.page?.orientation || 'portrait',\n margins: options.page?.margins || { top: 12, right: 15, bottom: 12, left: 15 },\n };\n\n const doc = createDoc(pageConfig);\n const { margins } = pageConfig;\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n const contentWidth = pageWidth - margins.left - margins.right;\n const accent = options.accentColor || DEFAULT_ACCENT;\n const footerConfig: FooterConfig = options.footer || { layout: 'none' };\n const footerH = measureFooterHeight(footerConfig);\n\n let y = margins.top;\n\n // Header\n if (options.header) {\n y = margins.top + renderHeader(doc, options.header, pageConfig) + 3;\n }\n\n // Group matches by court, preserving time slot order\n const courtMatches = groupByCourt(scheduleData);\n\n for (const [courtName, matches] of courtMatches) {\n // Check if court section fits (at least court header + 1 match)\n if (y + 30 > pageHeight - margins.bottom - footerH) {\n renderPageFooter(doc, options, pageConfig, footerConfig);\n doc.addPage();\n y = margins.top;\n }\n\n // Court name header\n y = renderCourtHeader(doc, courtName, margins.left, y, contentWidth);\n\n let lastTime = '';\n for (const match of matches) {\n // Time bar if time changed\n const matchTime = match.scheduledTime || match.notBeforeTime || '';\n if (matchTime && matchTime !== lastTime) {\n if (y + 25 > pageHeight - margins.bottom - footerH) {\n renderPageFooter(doc, options, pageConfig, footerConfig);\n doc.addPage();\n y = margins.top;\n }\n const isNotBefore = !!match.notBeforeTime;\n y = renderTimeBar(doc, matchTime, isNotBefore, margins.left, y, contentWidth, accent);\n lastTime = matchTime;\n }\n\n // Match box\n if (y + 22 > pageHeight - margins.bottom - footerH) {\n renderPageFooter(doc, options, pageConfig, footerConfig);\n doc.addPage();\n y = margins.top;\n }\n y = renderMatchBox(doc, match, margins.left, y, contentWidth);\n }\n\n y += 4;\n }\n\n // Disclaimer\n if (options.disclaimer) {\n y += 2;\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(100);\n doc.text(options.disclaimer, pageWidth / 2, y, { align: 'center' });\n doc.setTextColor(0);\n }\n\n renderPageFooter(doc, options, pageConfig, footerConfig);\n\n return doc;\n}\n\nfunction renderCourtHeader(doc: jsPDF, courtName: string, x: number, y: number, width: number): number {\n setFont(doc, SIZE.HEADING, STYLE.BOLD);\n doc.setTextColor(40);\n doc.text(courtName.toUpperCase(), x + width / 2, y, { align: 'center' });\n doc.setTextColor(0);\n return y + 7;\n}\n\nfunction renderTimeBar(\n doc: jsPDF,\n time: string,\n isNotBefore: boolean,\n x: number,\n y: number,\n width: number,\n accent: [number, number, number],\n): number {\n const label = isNotBefore ? `Not before ${time}` : `Starting at ${time}`;\n\n doc.setFillColor(accent[0], accent[1], accent[2]);\n doc.rect(x + 20, y, width - 40, 5, 'F');\n\n setFont(doc, SIZE.SMALL, STYLE.ITALIC);\n doc.setTextColor(255, 255, 255);\n doc.text(label, x + width / 2, y + 3.5, { align: 'center' });\n doc.setTextColor(0);\n\n return y + 7;\n}\n\nfunction renderMatchBox(doc: jsPDF, match: ScheduleMatch, x: number, y: number, width: number): number {\n const boxX = x + 15;\n const boxWidth = width - 30;\n const startY = y;\n\n // Round label (top-right of box)\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(100);\n const roundLabel = match.eventAbbr ? `${match.eventAbbr} ${match.roundName}` : match.roundName;\n doc.text(roundLabel, boxX + boxWidth - 2, y + 3, { align: 'right' });\n doc.setTextColor(0);\n\n // Score above players (if completed)\n if (match.score) {\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.setTextColor(120, 50, 140);\n doc.text(match.score, boxX + boxWidth / 2, y + 3, { align: 'center' });\n doc.setTextColor(0);\n y += 4;\n }\n\n y += 2;\n\n // Player 1\n y = renderPlayer(doc, match.side1, boxX, y, boxWidth);\n\n // \"vs\" divider\n setFont(doc, SIZE.TINY, STYLE.ITALIC);\n doc.setTextColor(120);\n doc.text('vs', boxX + boxWidth / 2, y + 2.5, { align: 'center' });\n doc.setTextColor(0);\n y += 4;\n\n // Player 2\n y = renderPlayer(doc, match.side2, boxX, y, boxWidth);\n\n y += 2;\n\n // Box border\n const boxHeight = y - startY;\n doc.setDrawColor(180);\n doc.setLineWidth(0.3);\n doc.rect(boxX, startY, boxWidth, boxHeight);\n\n return y + 2;\n}\n\nfunction renderPlayer(\n doc: jsPDF,\n side: { name: string; nationality: string },\n x: number,\n y: number,\n _width: number,\n): number {\n if (!side.name || side.name === 'TBD') {\n setFont(doc, SIZE.BODY, STYLE.ITALIC);\n doc.setTextColor(150);\n doc.text('TBD', x + 10, y + 3);\n doc.setTextColor(0);\n return y + 4;\n }\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n\n // Format: player name centered with nationality\n const nameWithNat = side.nationality ? `${side.name} ${side.nationality}` : side.name;\n doc.text(nameWithNat, x + 10, y + 3);\n\n return y + 4;\n}\n\nfunction groupByCourt(scheduleData: ScheduleData): Map<string, ScheduleMatch[]> {\n const courtMap = new Map<string, ScheduleMatch[]>();\n\n // Preserve court order from scheduleData.courts\n for (const court of scheduleData.courts) {\n courtMap.set(court, []);\n }\n\n // Fill matches in time slot order\n for (const slot of scheduleData.timeSlots) {\n for (const match of slot.matches) {\n if (!courtMap.has(match.courtName)) courtMap.set(match.courtName, []);\n courtMap.get(match.courtName)!.push(match);\n }\n }\n\n // Remove empty courts\n for (const [court, matches] of courtMap) {\n if (matches.length === 0) courtMap.delete(court);\n }\n\n return courtMap;\n}\n\nfunction renderPageFooter(\n doc: jsPDF,\n options: SequentialOOPOptions,\n pageConfig: PageConfig,\n footerConfig: FooterConfig,\n): void {\n const { margins } = pageConfig;\n const pageWidth = doc.internal.pageSize.getWidth();\n const pageHeight = doc.internal.pageSize.getHeight();\n\n if (options.officials?.length) {\n const y = pageHeight - margins.bottom - 10;\n doc.setDrawColor(120);\n doc.setLineWidth(0.2);\n doc.line(margins.left, y - 2, pageWidth - margins.right, y - 2);\n\n const spacing = (pageWidth - margins.left - margins.right) / options.officials.length;\n\n options.officials.forEach((official, i) => {\n const ox = margins.left + i * spacing;\n setFont(doc, SIZE.TINY, STYLE.BOLD);\n doc.text(official.role, ox, y);\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.text(official.name, ox, y + 3);\n });\n }\n\n renderFooter(doc, footerConfig, pageConfig);\n}\n","import jsPDF from 'jspdf';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport interface MatchCardData {\n tournamentName?: string;\n eventName: string;\n roundName: string;\n matchUpId?: string;\n courtName?: string;\n scheduledTime?: string;\n side1: { name: string; nationality: string; seedValue?: number };\n side2: { name: string; nationality: string; seedValue?: number };\n}\n\nexport interface MatchCardOptions {\n cardsPerPage?: number;\n includeScoreBoxes?: boolean;\n}\n\nexport function generateMatchCardPDF(matches: MatchCardData[], options: MatchCardOptions = {}): jsPDF {\n const { cardsPerPage = 2, includeScoreBoxes = true } = options;\n const doc = new jsPDF({ orientation: 'landscape', format: 'a5' });\n\n matches.forEach((match, index) => {\n if (index > 0) {\n if (cardsPerPage === 1 || index % cardsPerPage === 0) {\n doc.addPage();\n }\n }\n\n const offsetY = cardsPerPage === 2 && index % 2 === 1 ? doc.internal.pageSize.getHeight() / 2 : 5;\n renderMatchCard(doc, match, offsetY, includeScoreBoxes);\n });\n\n return doc;\n}\n\nfunction renderMatchCard(doc: jsPDF, match: MatchCardData, startY: number, includeScoreBoxes: boolean) {\n const pageWidth = doc.internal.pageSize.getWidth();\n const centerX = pageWidth / 2;\n const margin = 10;\n let y = startY;\n\n // Tournament name\n if (match.tournamentName) {\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n doc.setTextColor(100);\n doc.text(match.tournamentName, centerX, y, { align: 'center' });\n doc.setTextColor(0);\n y += 5;\n }\n\n // Event + Round\n setFont(doc, SIZE.HEADING, STYLE.BOLD);\n doc.text(`${match.eventName} - ${match.roundName}`, centerX, y, { align: 'center' });\n y += 5;\n\n // Court + Time\n if (match.courtName || match.scheduledTime) {\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n const info: string[] = [];\n if (match.courtName) info.push(`Court: ${match.courtName}`);\n if (match.scheduledTime) info.push(`Time: ${match.scheduledTime}`);\n doc.text(info.join(' '), centerX, y, { align: 'center' });\n y += 5;\n }\n\n // Separator\n doc.setDrawColor(0);\n doc.setLineWidth(0.5);\n doc.line(margin, y, pageWidth - margin, y);\n y += 6;\n\n // Player 1\n renderPlayerLine(doc, match.side1, margin, y, pageWidth);\n y += 8;\n\n // vs\n setFont(doc, SIZE.BODY, STYLE.ITALIC);\n doc.setTextColor(120);\n doc.text('vs.', centerX, y, { align: 'center' });\n doc.setTextColor(0);\n y += 6;\n\n // Player 2\n renderPlayerLine(doc, match.side2, margin, y, pageWidth);\n y += 8;\n\n // Score boxes\n if (includeScoreBoxes) {\n doc.setDrawColor(0);\n doc.setLineWidth(0.5);\n doc.line(margin, y, pageWidth - margin, y);\n y += 4;\n\n setFont(doc, SIZE.SMALL, STYLE.BOLD);\n doc.text('Score:', margin, y);\n\n const boxWidth = 12;\n const boxHeight = 8;\n const boxStartX = margin + 18;\n const boxGap = 3;\n\n // 5 set boxes (3 for best-of-3, 5 for best-of-5)\n for (let i = 0; i < 5; i++) {\n const bx = boxStartX + i * (boxWidth + boxGap);\n doc.rect(bx, y - 4, boxWidth, boxHeight);\n // Set number label above\n setFont(doc, SIZE.TINY, STYLE.NORMAL);\n doc.setTextColor(150);\n doc.text(`Set ${i + 1}`, bx + boxWidth / 2, y - 5, { align: 'center' });\n doc.setTextColor(0);\n }\n\n y += boxHeight + 6;\n\n // Umpire signature line\n setFont(doc, SIZE.SMALL, STYLE.NORMAL);\n doc.text('Umpire:', margin, y);\n doc.setDrawColor(150);\n doc.setLineWidth(0.3);\n doc.line(margin + 20, y, margin + 80, y);\n\n doc.text('Signature:', pageWidth - margin - 70, y);\n doc.line(pageWidth - margin - 40, y, pageWidth - margin, y);\n }\n}\n\nfunction renderPlayerLine(\n doc: jsPDF,\n side: { name: string; nationality: string; seedValue?: number },\n margin: number,\n y: number,\n pageWidth: number,\n): void {\n setFont(doc, 14, STYLE.BOLD);\n const seed = side.seedValue ? `[${side.seedValue}] ` : '';\n doc.text(`${seed}${side.name}`, margin, y);\n\n setFont(doc, SIZE.HEADING, STYLE.NORMAL);\n doc.setTextColor(80);\n doc.text(side.nationality, pageWidth - margin, y, { align: 'right' });\n doc.setTextColor(0);\n}\n","import jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport { drawTournamentHeader, drawPageFooter, type TournamentHeader } from '../layout/headers';\nimport { TABLE_STYLES } from '../layout/tables';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport interface ReportColumn {\n key: string;\n title: string;\n type?: 'string' | 'number' | 'boolean' | 'date';\n width?: number;\n}\n\nexport interface ReportPDFOptions {\n header?: TournamentHeader;\n orientation?: 'portrait' | 'landscape';\n title?: string;\n}\n\nexport function generateReportPDF(\n columns: ReportColumn[],\n rows: Record<string, any>[],\n options: ReportPDFOptions = {},\n): jsPDF {\n const orientation = options.orientation || 'portrait';\n const doc = new jsPDF({ orientation, format: 'a4' });\n let startY = 15;\n\n if (options.header) {\n startY = drawTournamentHeader(doc, {\n ...options.header,\n subtitle: options.header.subtitle || options.title,\n });\n } else if (options.title) {\n const margin = 15;\n setFont(doc, SIZE.SUBTITLE, STYLE.BOLD);\n doc.text(options.title, margin, startY);\n startY += 8;\n }\n\n if (columns.length === 0) {\n setFont(doc, SIZE.BODY, STYLE.ITALIC);\n doc.text('No columns defined', 15, startY);\n drawPageFooter(doc, `Generated ${new Date().toLocaleDateString()}`, 1);\n return doc;\n }\n\n const tableColumns = columns.map((col) => ({\n header: col.title,\n dataKey: col.key,\n }));\n\n const body = rows.map((row) => {\n const mapped: Record<string, any> = {};\n for (const col of columns) {\n const val = row[col.key];\n mapped[col.key] = val != null ? String(val) : '';\n }\n return mapped;\n });\n\n const columnStyles: Record<string, any> = {};\n for (const col of columns) {\n if (col.type === 'number') {\n columnStyles[col.key] = { halign: 'right' };\n }\n if (col.width) {\n columnStyles[col.key] = { ...columnStyles[col.key], cellWidth: col.width };\n }\n }\n\n autoTable(doc, {\n ...TABLE_STYLES.report,\n startY,\n columns: tableColumns,\n body,\n columnStyles,\n didDrawPage: (data) => {\n drawPageFooter(doc, `Generated ${new Date().toLocaleDateString()}`, data.pageNumber);\n },\n });\n\n return doc;\n}\n","/**\n * Fact Sheet Generator — produces structured tournament information PDFs.\n *\n * Pulls from tournament record fields, registration profile, venues, participants,\n * and events. Appends free-form notes HTML as plain text at the bottom.\n */\n\nimport jsPDF from 'jspdf';\nimport autoTable from 'jspdf-autotable';\nimport { buildHeaderFromTournament } from '../composition/tournamentBridge';\nimport { renderHeader } from '../composition/headerLayouts';\nimport { getFactSheetTemplate, type FactSheetSectionType } from '../config/factSheetCatalog';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\nimport { drawPageFooter } from '../layout/headers';\n\nconst MARGIN = 15;\n\ninterface FactSheetOptions {\n templateId?: string;\n enabledSections?: FactSheetSectionType[];\n}\n\nfunction stripHtml(html: string): string {\n // Use DOM when available; simple character-walk fallback for Node\n if (typeof document !== 'undefined') {\n const el = document.createElement('div');\n el.innerHTML = html;\n return el.textContent || '';\n }\n let result = '';\n let inTag = false;\n for (const ch of html) {\n if (ch === '<') {\n inTag = true;\n continue;\n }\n if (ch === '>') {\n inTag = false;\n continue;\n }\n if (!inTag) result += ch;\n }\n return result.trim();\n}\n\nfunction sectionHeading(doc: jsPDF, title: string, y: number): number {\n setFont(doc, SIZE.HEADING, STYLE.BOLD);\n doc.setTextColor(40);\n doc.text(title.toUpperCase(), MARGIN, y);\n doc.setTextColor(0);\n y += 1.5;\n doc.setDrawColor(180);\n doc.setLineWidth(0.2);\n doc.line(MARGIN, y, doc.internal.pageSize.getWidth() - MARGIN, y);\n y += 4;\n return y;\n}\n\nfunction bodyText(doc: jsPDF, text: string, y: number, maxWidth?: number): number {\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n const width = maxWidth || doc.internal.pageSize.getWidth() - MARGIN * 2;\n const lines = doc.splitTextToSize(text, width);\n doc.text(lines, MARGIN, y);\n return y + lines.length * 3.2;\n}\n\nfunction checkPageBreak(doc: jsPDF, y: number, needed: number): number {\n const pageHeight = doc.internal.pageSize.getHeight();\n if (y + needed > pageHeight - 20) {\n doc.addPage();\n return 20;\n }\n return y;\n}\n\nfunction renderTournamentHeader(doc: jsPDF, record: any, y: number): number {\n const pageConfig = {\n pageSize: 'a4' as const,\n orientation: 'portrait' as const,\n margins: { top: y, right: MARGIN, bottom: 15, left: MARGIN },\n };\n const headerConfig = buildHeaderFromTournament(record, { layout: 'itf' });\n const headerHeight = renderHeader(doc, headerConfig, pageConfig);\n return y + headerHeight;\n}\n\nfunction renderContacts(doc: jsPDF, record: any, y: number): number {\n const participants = record.participants || [];\n const nonCompetitors = participants.filter((p: any) => p.participantRole && p.participantRole !== 'COMPETITOR');\n if (!nonCompetitors.length) return y;\n\n y = checkPageBreak(doc, y, 20);\n y = sectionHeading(doc, 'Tournament Contacts', y);\n\n const rows = nonCompetitors.map((p: any) => {\n const person = p.person || {};\n const name =\n [person.standardGivenName, person.standardFamilyName].filter(Boolean).join(' ') || p.participantName || '';\n const role = p.participantRoleResponsibilities?.[0] || p.participantRole || '';\n const contact = person.contacts?.[0] || {};\n const details = [contact.emailAddress, contact.telephone || contact.mobileTelephone].filter(Boolean).join(' | ');\n return [name, role, details];\n });\n\n autoTable(doc, {\n startY: y,\n head: [['Name', 'Role', 'Contact']],\n body: rows,\n margin: { left: MARGIN, right: MARGIN },\n styles: { fontSize: 7, cellPadding: 1.5 },\n headStyles: { fillColor: [60, 60, 60], textColor: 255, fontStyle: 'bold' },\n theme: 'grid',\n });\n\n return (doc as any).lastAutoTable.finalY + 6;\n}\n\nfunction renderEvents(doc: jsPDF, record: any, y: number): number {\n const events = record.events || [];\n if (!events.length) return y;\n\n y = checkPageBreak(doc, y, 20);\n y = sectionHeading(doc, 'Events', y);\n\n const rows = events.map((e: any) => {\n const drawSize = e.drawDefinitions?.[0]?.drawSize || '';\n return [e.eventName || '', e.eventType || '', e.matchUpFormat || '', String(drawSize)];\n });\n\n autoTable(doc, {\n startY: y,\n head: [['Event', 'Type', 'Format', 'Draw Size']],\n body: rows,\n margin: { left: MARGIN, right: MARGIN },\n styles: { fontSize: 7, cellPadding: 1.5 },\n headStyles: { fillColor: [60, 60, 60], textColor: 255, fontStyle: 'bold' },\n theme: 'grid',\n });\n\n return (doc as any).lastAutoTable.finalY + 6;\n}\n\nfunction renderEntryInfo(doc: jsPDF, record: any, y: number): number {\n const rp = record.registrationProfile;\n if (!rp) return y;\n\n const lines: string[] = [];\n if (rp.entriesOpen) lines.push('Entries Open: ' + rp.entriesOpen);\n if (rp.entriesClose) lines.push('Entries Close: ' + rp.entriesClose);\n if (rp.withdrawalDeadline) lines.push('Withdrawal Deadline: ' + rp.withdrawalDeadline);\n if (rp.entryMethod) lines.push('Entry Method: ' + rp.entryMethod);\n if (rp.entryUrl) lines.push('Entry URL: ' + rp.entryUrl);\n if (rp.eligibilityNotes) lines.push('Eligibility: ' + rp.eligibilityNotes);\n\n if (rp.entryFees?.length) {\n const feeStr = rp.entryFees\n .map((f: any) => {\n const label = f.eventType ? f.eventType + ': ' : '';\n return label + f.currencyCode + ' ' + f.amount;\n })\n .join(', ');\n lines.push('Entry Fees: ' + feeStr);\n }\n\n if (!lines.length) return y;\n\n y = checkPageBreak(doc, y, 10 + lines.length * 3.5);\n y = sectionHeading(doc, 'Entry Information', y);\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n for (const line of lines) {\n doc.text(line, MARGIN, y);\n y += 3.5;\n }\n return y + 3;\n}\n\nfunction renderVenueInfo(doc: jsPDF, record: any, y: number): number {\n const venues = record.venues || [];\n if (!venues.length) return y;\n\n y = checkPageBreak(doc, y, 15);\n y = sectionHeading(doc, 'Venue', y);\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n for (const venue of venues) {\n setFont(doc, SIZE.BODY, STYLE.BOLD);\n doc.text(venue.venueName || 'Venue', MARGIN, y);\n y += 3.5;\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n\n const addr = venue.addresses?.[0];\n if (addr) {\n const parts = [addr.street, addr.city, addr.state, addr.postalCode, addr.countryCode].filter(Boolean);\n if (parts.length) {\n doc.text(parts.join(', '), MARGIN, y);\n y += 3.5;\n }\n }\n const courts = venue.courts?.length;\n if (courts) {\n doc.text('Courts: ' + courts, MARGIN, y);\n y += 3.5;\n }\n }\n return y + 3;\n}\n\nfunction renderLogisticsSection(doc: jsPDF, title: string, section: any, y: number): number {\n if (!section) return y;\n const hasOptions = section.options?.length;\n const hasNotes = section.notes && stripHtml(section.notes);\n if (!hasOptions && !hasNotes) return y;\n\n y = checkPageBreak(doc, y, 15);\n y = sectionHeading(doc, title, y);\n\n if (hasOptions) {\n const rows = section.options.map((opt: any) => {\n const details = [opt.phone, opt.email, opt.priceRange].filter(Boolean).join(' | ');\n return [opt.name, opt.address || '', details];\n });\n\n autoTable(doc, {\n startY: y,\n head: [['Name', 'Address', 'Details']],\n body: rows,\n margin: { left: MARGIN, right: MARGIN },\n styles: { fontSize: 7, cellPadding: 1.5 },\n headStyles: { fillColor: [60, 60, 60], textColor: 255, fontStyle: 'bold' },\n theme: 'grid',\n });\n\n y = (doc as any).lastAutoTable.finalY + 3;\n }\n\n if (hasNotes) {\n y = bodyText(doc, stripHtml(section.notes), y);\n }\n\n return y + 3;\n}\n\nfunction renderPrizeMoney(doc: jsPDF, record: any, y: number): number {\n const pm = record.totalPrizeMoney;\n if (!pm?.length) return y;\n\n y = checkPageBreak(doc, y, 10);\n y = sectionHeading(doc, 'Prize Money', y);\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n for (const p of pm) {\n doc.text(p.currencyCode + ' ' + p.amount.toLocaleString(), MARGIN, y);\n y += 3.5;\n }\n return y + 3;\n}\n\nfunction renderOfficials(doc: jsPDF, record: any, y: number): number {\n const participants = record.participants || [];\n const officials = participants.filter(\n (p: any) => p.participantRole === 'OFFICIAL' || p.participantRole === 'DIRECTOR',\n );\n if (!officials.length) return y;\n\n y = checkPageBreak(doc, y, 15);\n y = sectionHeading(doc, 'Officials', y);\n\n const rows = officials.map((p: any) => {\n const person = p.person || {};\n const name =\n [person.standardGivenName, person.standardFamilyName].filter(Boolean).join(' ') || p.participantName || '';\n const role = p.participantRoleResponsibilities?.[0] || p.participantRole || '';\n return [name, role];\n });\n\n autoTable(doc, {\n startY: y,\n head: [['Name', 'Role']],\n body: rows,\n margin: { left: MARGIN, right: MARGIN },\n styles: { fontSize: 7, cellPadding: 1.5 },\n headStyles: { fillColor: [60, 60, 60], textColor: 255, fontStyle: 'bold' },\n theme: 'grid',\n });\n\n return (doc as any).lastAutoTable.finalY + 6;\n}\n\nfunction renderRegulations(doc: jsPDF, record: any, y: number): number {\n const rp = record.registrationProfile;\n if (!rp) return y;\n\n const lines: string[] = [];\n if (rp.codeOfConduct) {\n const coc = rp.codeOfConduct;\n lines.push('Code of Conduct: ' + (coc.name || '') + (coc.url ? ' — ' + coc.url : ''));\n }\n if (rp.regulations?.length) {\n for (const reg of rp.regulations) {\n lines.push((reg.name || 'Regulation') + (reg.url ? ' — ' + reg.url : ''));\n }\n }\n if (rp.dressCode) lines.push('Dress Code: ' + rp.dressCode);\n if (rp.contingencyPlan) lines.push('Contingency: ' + rp.contingencyPlan);\n\n if (!lines.length) return y;\n\n y = checkPageBreak(doc, y, 10 + lines.length * 3.5);\n y = sectionHeading(doc, 'Regulations', y);\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n for (const line of lines) {\n doc.text(line, MARGIN, y);\n y += 3.5;\n }\n return y + 3;\n}\n\nfunction renderSponsors(doc: jsPDF, record: any, y: number): number {\n const sponsors = record.registrationProfile?.sponsors;\n if (!sponsors?.length) return y;\n\n y = checkPageBreak(doc, y, 10);\n y = sectionHeading(doc, 'Sponsors', y);\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n for (const s of sponsors) {\n const tierLabel = s.tier ? ' [' + s.tier + ']' : '';\n doc.text(s.name + tierLabel, MARGIN, y);\n y += 3.5;\n }\n return y + 3;\n}\n\nfunction renderSocialEvents(doc: jsPDF, record: any, y: number): number {\n const events = record.registrationProfile?.socialEvents;\n if (!events?.length) return y;\n\n const rp = record.registrationProfile;\n y = checkPageBreak(doc, y, 15);\n y = sectionHeading(doc, 'Social Events & Ceremonies', y);\n\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n if (rp?.drawCeremonyDate) {\n doc.text('Draw Ceremony: ' + rp.drawCeremonyDate, MARGIN, y);\n y += 3.5;\n }\n if (rp?.awardsCeremonyDate) {\n doc.text('Awards Ceremony: ' + rp.awardsCeremonyDate, MARGIN, y);\n y += 3.5;\n }\n\n for (const e of events) {\n setFont(doc, SIZE.BODY, STYLE.BOLD);\n doc.text(e.name, MARGIN, y);\n y += 3.5;\n setFont(doc, SIZE.BODY, STYLE.NORMAL);\n const details = [e.date, e.time, e.location].filter(Boolean).join(' | ');\n if (details) {\n doc.text(details, MARGIN, y);\n y += 3.5;\n }\n if (e.description) {\n doc.text(e.description, MARGIN, y);\n y += 3.5;\n }\n }\n return y + 3;\n}\n\nfunction renderCustomNotes(doc: jsPDF, record: any, y: number): number {\n const notes = record.notes;\n if (!notes) return y;\n\n const plain = stripHtml(notes);\n if (!plain) return y;\n\n y = checkPageBreak(doc, y, 15);\n y = sectionHeading(doc, 'Additional Information', y);\n y = bodyText(doc, plain, y);\n return y + 3;\n}\n\nconst SECTION_RENDERERS: Record<FactSheetSectionType, (doc: jsPDF, record: any, y: number) => number> = {\n 'tournament-header': renderTournamentHeader,\n contacts: renderContacts,\n events: renderEvents,\n 'entry-info': renderEntryInfo,\n 'venue-info': renderVenueInfo,\n accommodation: (doc, rec, y) =>\n renderLogisticsSection(doc, 'Accommodation', rec.registrationProfile?.accommodation, y),\n transportation: (doc, rec, y) =>\n renderLogisticsSection(doc, 'Transportation', rec.registrationProfile?.transportation, y),\n hospitality: (doc, rec, y) => renderLogisticsSection(doc, 'Hospitality', rec.registrationProfile?.hospitality, y),\n medical: (doc, rec, y) => renderLogisticsSection(doc, 'Medical', rec.registrationProfile?.medicalInfo, y),\n regulations: renderRegulations,\n 'prize-money': renderPrizeMoney,\n officials: renderOfficials,\n sponsors: renderSponsors,\n 'social-events': renderSocialEvents,\n 'custom-notes': renderCustomNotes,\n};\n\n/**\n * Generate a structured tournament fact sheet PDF.\n *\n * @param tournamentRecord - Full tournament record from tods-competition-factory\n * @param options - Template selection and section overrides\n * @returns jsPDF document\n */\nexport function generateFactSheet(tournamentRecord: any, options: FactSheetOptions = {}): jsPDF {\n const { templateId = 'itf-junior' } = options;\n const template = getFactSheetTemplate(templateId);\n const sections = template?.sections || getFactSheetTemplate('itf-junior')!.sections;\n\n const enabledSet = options.enabledSections ? new Set(options.enabledSections) : null;\n\n const doc = new jsPDF({ orientation: 'portrait', format: 'a4' });\n let y = MARGIN;\n\n for (const section of sections) {\n if (!section.enabled) continue;\n if (enabledSet && !enabledSet.has(section.type)) continue;\n\n const renderer = SECTION_RENDERERS[section.type];\n if (renderer) {\n y = renderer(doc, tournamentRecord, y);\n }\n }\n\n // Page footers\n const totalPages = doc.getNumberOfPages();\n for (let i = 1; i <= totalPages; i++) {\n doc.setPage(i);\n drawPageFooter(doc, 'Generated ' + new Date().toLocaleDateString(), i);\n }\n\n return doc;\n}\n","/**\n * Mirrored bracket renderer (NCAA-style).\n *\n * Two halves of the draw progress inward — left half flows left-to-right,\n * right half flows right-to-left. The winner column is in the center.\n *\n * Layout:\n * [Left R1] [Left R2] ... [Left SF] |WINNER| [Right SF] ... [Right R2] [Right R1]\n *\n * Used for: NCAA team tennis, collegiate dual matches, club events.\n */\n\nimport jsPDF from 'jspdf';\nimport type { DrawFormatConfig, PageRegions } from '../config/types';\nimport type { DrawData, DrawSlot, DrawMatchUp } from '../core/extractDrawData';\nimport { getRoundLabel } from '../core/extractDrawData';\nimport { formatPlayerEntrySplit, formatMatchScore } from './formatEntry';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\ninterface HalfConfig {\n lineHeight: number;\n roundColumnWidth: number;\n firstRoundWidth: number;\n connectorGap: number;\n fontSize: number;\n scoreFontSize: number;\n}\n\nexport function renderMirroredDraw(\n doc: jsPDF,\n drawData: DrawData,\n format: DrawFormatConfig,\n regions: PageRegions,\n): void {\n const margins = format.page.margins;\n const headerReserve = 9;\n const startY = regions.contentY + headerReserve;\n const contentHeight = regions.contentHeight - headerReserve;\n\n const halfSize = drawData.drawSize / 2;\n const halfRounds = Math.log2(halfSize);\n const totalWidth = regions.contentWidth;\n\n // Center column for winner\n const centerWidth = Math.min(30, totalWidth * 0.08);\n const halfWidth = (totalWidth - centerWidth) / 2;\n const centerX = margins.left + halfWidth;\n\n // Config for each half\n const lineHeight = contentHeight / halfSize;\n const isDense = lineHeight < 3.5;\n const connectorGap = isDense ? 0.8 : 1.5;\n const firstRoundWidth = Math.min(isDense ? 30 : 50, halfWidth * 0.22);\n const laterCols = halfRounds; // includes all rounds after R1\n const remaining = halfWidth - firstRoundWidth - connectorGap * (laterCols + 1);\n const roundColumnWidth = Math.max(8, remaining / Math.max(1, laterCols));\n let fontSize = SIZE.SMALL;\n if (lineHeight < 2.5) fontSize = 5;\n else if (isDense) fontSize = SIZE.TINY;\n const scoreFontSize = isDense ? 5 : SIZE.TINY;\n\n const config: HalfConfig = { lineHeight, roundColumnWidth, firstRoundWidth, connectorGap, fontSize, scoreFontSize };\n\n // Split matchUps and slots into two halves\n const leftSlots = drawData.slots.filter((s) => s.drawPosition <= halfSize);\n const rightSlots = drawData.slots.filter((s) => s.drawPosition > halfSize);\n\n const leftMatchUps = drawData.matchUps.filter((mu) => mu.drawPositions.every((dp) => dp <= halfSize));\n const rightMatchUps = drawData.matchUps.filter((mu) => mu.drawPositions.every((dp) => dp > halfSize));\n\n // Renumber right half: positions to 1..halfSize, roundPosition to 1..N per round\n const rightSlotsRenumbered = rightSlots.map((s) => ({ ...s, drawPosition: s.drawPosition - halfSize }));\n const rightByRound = new Map<number, typeof rightMatchUps>();\n for (const mu of rightMatchUps) {\n if (!rightByRound.has(mu.roundNumber)) rightByRound.set(mu.roundNumber, []);\n rightByRound.get(mu.roundNumber)!.push(mu);\n }\n const rightMatchUpsRenumbered: typeof rightMatchUps = [];\n for (const [, roundMus] of rightByRound) {\n roundMus.sort((a, b) => a.roundPosition - b.roundPosition);\n roundMus.forEach((mu, idx) => {\n rightMatchUpsRenumbered.push({\n ...mu,\n drawPositions: mu.drawPositions.map((dp) => dp - halfSize),\n roundPosition: idx + 1,\n });\n });\n }\n\n // Also renumber left half roundPosition for consistency\n const leftByRound = new Map<number, typeof leftMatchUps>();\n for (const mu of leftMatchUps) {\n if (!leftByRound.has(mu.roundNumber)) leftByRound.set(mu.roundNumber, []);\n leftByRound.get(mu.roundNumber)!.push(mu);\n }\n const leftMatchUpsRenumbered: typeof leftMatchUps = [];\n for (const [, roundMus] of leftByRound) {\n roundMus.sort((a, b) => a.roundPosition - b.roundPosition);\n roundMus.forEach((mu, idx) => {\n leftMatchUpsRenumbered.push({ ...mu, roundPosition: idx + 1 });\n });\n }\n\n // Round headers\n renderMirroredRoundHeaders(\n doc,\n halfRounds,\n drawData.totalRounds,\n config,\n format,\n margins.left,\n margins.left + totalWidth,\n regions.contentY + 2,\n drawData.roundLabelMap,\n );\n\n // Winner column header\n setFont(doc, isDense ? 5.5 : SIZE.SMALL, STYLE.BOLD);\n doc.setTextColor(40);\n doc.text('Winner', centerX + centerWidth / 2, regions.contentY + 2, { align: 'center' });\n doc.setDrawColor(160);\n doc.setLineWidth(0.15);\n doc.line(centerX + 2, regions.contentY + 3.5, centerX + centerWidth - 2, regions.contentY + 3.5);\n doc.setTextColor(0);\n\n // Render left half (left-to-right, normal direction)\n renderLeftHalf(\n doc,\n leftSlots,\n leftMatchUpsRenumbered,\n halfRounds,\n config,\n format,\n margins.left,\n startY,\n drawData.totalRounds,\n );\n\n // Render right half (right-to-left, mirrored)\n renderRightHalf(\n doc,\n rightSlotsRenumbered,\n rightMatchUpsRenumbered,\n halfRounds,\n config,\n format,\n margins.left + totalWidth,\n startY,\n drawData.totalRounds,\n );\n\n // Winner in center\n const finalMu = drawData.matchUps.find((mu) => mu.roundNumber === drawData.totalRounds);\n if (finalMu) {\n const winnerMidY = startY + contentHeight / 2;\n\n // Winner line\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(centerX + 2, winnerMidY, centerX + centerWidth - 2, winnerMidY);\n\n if (finalMu.winningSide) {\n const winnerPos = finalMu.drawPositions[finalMu.winningSide - 1];\n const winnerSlot = drawData.slots.find((s) => s.drawPosition === winnerPos);\n if (winnerSlot) {\n const { name } = formatPlayerEntrySplit(winnerSlot, format);\n setFont(doc, fontSize + 1, STYLE.BOLD);\n doc.text(name, centerX + centerWidth / 2, winnerMidY - 1, { align: 'center' });\n }\n }\n\n if (finalMu.score) {\n setFont(doc, scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(formatMatchScore(finalMu.score, format), centerX + centerWidth / 2, winnerMidY + scoreFontSize * 0.4, {\n align: 'center',\n });\n doc.setTextColor(0);\n }\n }\n}\n\nfunction renderLeftHalf(\n doc: jsPDF,\n slots: DrawSlot[],\n matchUps: DrawMatchUp[],\n totalRounds: number,\n config: HalfConfig,\n format: DrawFormatConfig,\n startX: number,\n startY: number,\n _fullTotalRounds: number,\n): void {\n const slotMap = new Map(slots.map((s) => [s.drawPosition, s]));\n const count = slots.length;\n\n for (let round = 0; round < totalRounds; round++) {\n const matchesInRound = count / Math.pow(2, round + 1);\n const spacing = config.lineHeight * Math.pow(2, round);\n const roundOffset = ((Math.pow(2, round) - 1) * config.lineHeight) / 2;\n const stride = Math.pow(2, round + 1) * config.lineHeight;\n const roundX = leftRoundX(round, config, startX);\n const colWidth = round === 0 ? config.firstRoundWidth : config.roundColumnWidth;\n\n for (let match = 0; match < matchesInRound; match++) {\n const topSlotY = startY + roundOffset + match * stride;\n const bottomSlotY = topSlotY + spacing;\n const midY = (topSlotY + bottomSlotY) / 2;\n\n if (round === 0) {\n const topPos = match * 2 + 1;\n const bottomPos = match * 2 + 2;\n drawPlayerLineCompact(doc, slotMap.get(topPos), config, roundX, topSlotY, colWidth, 'ltr');\n drawPlayerLineCompact(doc, slotMap.get(bottomPos), config, roundX, bottomSlotY, colWidth, 'ltr');\n } else {\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(roundX, topSlotY, roundX + colWidth, topSlotY);\n doc.line(roundX, bottomSlotY, roundX + colWidth, bottomSlotY);\n }\n\n // Right bracket\n const rightX = roundX + colWidth;\n const nextRoundX = leftRoundX(round + 1, config, startX);\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(rightX + config.connectorGap, topSlotY, rightX + config.connectorGap, bottomSlotY);\n doc.line(rightX, topSlotY, rightX + config.connectorGap, topSlotY);\n doc.line(rightX, bottomSlotY, rightX + config.connectorGap, bottomSlotY);\n doc.line(rightX + config.connectorGap, midY, nextRoundX, midY);\n\n // Advancing name\n const mu = findMatchUp(matchUps, round + 1, match + 1);\n if (round < totalRounds - 1 && mu?.winningSide) {\n const winnerPos = mu.drawPositions[mu.winningSide - 1];\n const winnerSlot = slotMap.get(winnerPos);\n if (winnerSlot) {\n setFont(doc, config.fontSize, STYLE.BOLD);\n let name = winnerSlot.participantName;\n if (doc.getTextWidth(name) > config.roundColumnWidth - 2) {\n name = abbreviateName(name);\n }\n doc.text(name, nextRoundX + 1, midY - 0.5);\n }\n }\n\n // Score\n if (mu?.score && round < totalRounds - 1) {\n setFont(doc, config.scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(formatMatchScore(mu.score, format), nextRoundX + 1, midY - 0.5 + config.scoreFontSize * 0.4);\n doc.setTextColor(0);\n }\n }\n }\n}\n\nfunction renderRightHalf(\n doc: jsPDF,\n slots: DrawSlot[],\n matchUps: DrawMatchUp[],\n totalRounds: number,\n config: HalfConfig,\n format: DrawFormatConfig,\n rightEdge: number,\n startY: number,\n _fullTotalRounds: number,\n): void {\n const slotMap = new Map(slots.map((s) => [s.drawPosition, s]));\n const count = slots.length;\n\n for (let round = 0; round < totalRounds; round++) {\n const matchesInRound = count / Math.pow(2, round + 1);\n const spacing = config.lineHeight * Math.pow(2, round);\n const roundOffset = ((Math.pow(2, round) - 1) * config.lineHeight) / 2;\n const stride = Math.pow(2, round + 1) * config.lineHeight;\n const roundX = rightRoundX(round, config, rightEdge);\n const colWidth = round === 0 ? config.firstRoundWidth : config.roundColumnWidth;\n\n for (let match = 0; match < matchesInRound; match++) {\n const topSlotY = startY + roundOffset + match * stride;\n const bottomSlotY = topSlotY + spacing;\n const midY = (topSlotY + bottomSlotY) / 2;\n\n if (round === 0) {\n const topPos = match * 2 + 1;\n const bottomPos = match * 2 + 2;\n drawPlayerLineCompact(doc, slotMap.get(topPos), config, roundX, topSlotY, colWidth, 'rtl');\n drawPlayerLineCompact(doc, slotMap.get(bottomPos), config, roundX, bottomSlotY, colWidth, 'rtl');\n } else {\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(roundX, topSlotY, roundX + colWidth, topSlotY);\n doc.line(roundX, bottomSlotY, roundX + colWidth, bottomSlotY);\n }\n\n // Left bracket (mirrored — vertical + stubs pointing left)\n const leftX = roundX;\n const prevRoundX = rightRoundX(round + 1, config, rightEdge);\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(leftX - config.connectorGap, topSlotY, leftX - config.connectorGap, bottomSlotY);\n doc.line(leftX, topSlotY, leftX - config.connectorGap, topSlotY);\n doc.line(leftX, bottomSlotY, leftX - config.connectorGap, bottomSlotY);\n doc.line(leftX - config.connectorGap, midY, prevRoundX + config.roundColumnWidth, midY);\n\n // Advancing name (right-aligned in the next inward column)\n const mu = findMatchUp(matchUps, round + 1, match + 1);\n if (round < totalRounds - 1 && mu?.winningSide) {\n const winnerPos = mu.drawPositions[mu.winningSide - 1];\n const winnerSlot = slotMap.get(winnerPos);\n if (winnerSlot) {\n setFont(doc, config.fontSize, STYLE.BOLD);\n let name = winnerSlot.participantName;\n if (doc.getTextWidth(name) > config.roundColumnWidth - 2) {\n name = abbreviateName(name);\n }\n const nextColX = prevRoundX;\n doc.text(name, nextColX + config.roundColumnWidth - 1, midY - 0.5, { align: 'right' });\n }\n }\n\n // Score\n if (mu?.score && round < totalRounds - 1) {\n const nextColX = prevRoundX;\n setFont(doc, config.scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(\n formatMatchScore(mu.score, format),\n nextColX + config.roundColumnWidth - 1,\n midY - 0.5 + config.scoreFontSize * 0.4,\n { align: 'right' },\n );\n doc.setTextColor(0);\n }\n }\n }\n}\n\nfunction renderMirroredRoundHeaders(\n doc: jsPDF,\n halfRounds: number,\n totalRounds: number,\n config: HalfConfig,\n format: DrawFormatConfig,\n leftStartX: number,\n rightStartX: number,\n y: number,\n roundLabelMap?: Record<number, string>,\n): void {\n const headerFontSize = config.fontSize <= SIZE.TINY ? 5.5 : SIZE.SMALL;\n setFont(doc, headerFontSize, STYLE.BOLD);\n doc.setTextColor(40);\n\n for (let round = 0; round < halfRounds; round++) {\n const roundNumber = totalRounds - halfRounds + round + 1;\n const defaultLabel = getRoundLabel(roundNumber, totalRounds);\n const label = roundLabelMap?.[roundNumber] || format.roundLabels[defaultLabel] || defaultLabel;\n const width = round === 0 ? config.firstRoundWidth : config.roundColumnWidth;\n\n // Left side\n const leftX = leftRoundX(round, config, leftStartX);\n doc.text(label, leftX + width / 2, y, { align: 'center' });\n doc.setDrawColor(160);\n doc.setLineWidth(0.15);\n doc.line(leftX + 2, y + 1.5, leftX + width - 2, y + 1.5);\n\n // Right side (mirrored)\n const rightX = rightRoundX(round, config, rightStartX);\n doc.text(label, rightX + width / 2, y, { align: 'center' });\n doc.line(rightX + 2, y + 1.5, rightX + width - 2, y + 1.5);\n }\n\n doc.setTextColor(0);\n}\n\nfunction leftRoundX(round: number, config: HalfConfig, startX: number): number {\n if (round === 0) return startX;\n return (\n startX +\n config.firstRoundWidth +\n config.connectorGap +\n (round - 1) * (config.roundColumnWidth + config.connectorGap)\n );\n}\n\nfunction rightRoundX(round: number, config: HalfConfig, rightEdge: number): number {\n if (round === 0) return rightEdge - config.firstRoundWidth;\n return (\n rightEdge -\n config.firstRoundWidth -\n config.connectorGap -\n (round - 1) * (config.roundColumnWidth + config.connectorGap) -\n config.roundColumnWidth\n );\n}\n\nfunction drawPlayerLineCompact(\n doc: jsPDF,\n slot: DrawSlot | undefined,\n config: HalfConfig,\n x: number,\n y: number,\n width: number,\n direction: 'ltr' | 'rtl',\n): void {\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(x, y, x + width, y);\n\n if (!slot || slot.isBye) {\n if (slot?.isBye) {\n setFont(doc, config.fontSize, STYLE.ITALIC);\n doc.setTextColor(150);\n if (direction === 'ltr') {\n doc.text('Bye', x + 1, y - 0.3);\n } else {\n doc.text('Bye', x + width - 1, y - 0.3, { align: 'right' });\n }\n doc.setTextColor(0);\n }\n return;\n }\n\n const seed = slot.seedValue ? `[${slot.seedValue}]` : '';\n setFont(doc, config.fontSize, STYLE.NORMAL);\n\n // Try full name first, abbreviate if too wide\n let name = slot.participantName;\n let display = seed ? `${seed} ${name}` : name;\n if (doc.getTextWidth(display) > width - 2) {\n name = abbreviateName(slot.participantName);\n display = seed ? `${seed} ${name}` : name;\n }\n\n if (direction === 'ltr') {\n doc.text(display, x + 1, y - 0.3);\n } else {\n doc.text(display, x + width - 1, y - 0.3, { align: 'right' });\n }\n}\n\nfunction abbreviateName(fullName: string): string {\n // \"LASTNAME, Firstname\" → \"F. LASTNAME\"\n const commaMatch = fullName.match(/^([^,]+),\\s*(.+)/);\n if (commaMatch) return `${commaMatch[2][0]}. ${commaMatch[1]}`;\n // \"Firstname Lastname\" → \"F. Lastname\"\n const spaceMatch = fullName.match(/^(\\S+)\\s+(.+)/);\n if (spaceMatch) return `${spaceMatch[1][0]}. ${spaceMatch[2]}`;\n return fullName;\n}\n\nfunction findMatchUp(matchUps: DrawMatchUp[], roundNumber: number, roundPosition: number): DrawMatchUp | undefined {\n return matchUps.find((mu) => mu.roundNumber === roundNumber && mu.roundPosition === roundPosition);\n}\n","/**\n * Backdraw (USTA Playback) renderer.\n *\n * First Round in the center, main draw progresses RIGHT,\n * consolation (playback) progresses LEFT. Landscape only.\n * Used for FIRST_ROUND_LOSER_CONSOLATION with drawSize ≤ 32.\n *\n * Layout:\n * [Consol Finals] ... [Consol R1] | [First Round boxes] | [Main R2] ... [Main Finals]\n * ← Playback | First Round | Main Draw →\n */\n\nimport jsPDF from 'jspdf';\nimport type { DrawFormatConfig, PageRegions } from '../config/types';\nimport type { DrawData, DrawSlot, DrawMatchUp } from '../core/extractDrawData';\nimport { formatPlayerEntrySplit, formatMatchScore } from './formatEntry';\nimport { setFont, SIZE, STYLE } from '../layout/fonts';\n\nexport interface BackdrawData {\n mainDraw: DrawData;\n consolation: DrawData;\n}\n\nexport function renderBackdrawDraw(\n doc: jsPDF,\n data: BackdrawData,\n format: DrawFormatConfig,\n regions: PageRegions,\n): void {\n const margins = format.page.margins;\n const headerReserve = 9;\n const contentTop = regions.contentY + headerReserve;\n const contentHeight = regions.contentHeight - headerReserve;\n const totalWidth = regions.contentWidth;\n\n const mainMatchUps = data.mainDraw.matchUps;\n const mainSlots = data.mainDraw.slots;\n const consolMatchUps = data.consolation.matchUps;\n const consolSlots = data.consolation.slots;\n\n const mainSlotMap = new Map(mainSlots.map((s) => [s.drawPosition, s]));\n const consolSlotMap = new Map(consolSlots.map((s) => [s.drawPosition, s]));\n\n // R1 of main has the most matches — determines the center column height\n const r1Matches = mainMatchUps.filter((mu) => mu.roundNumber === 1).sort((a, b) => a.roundPosition - b.roundPosition);\n const r1Count = r1Matches.length;\n const drawSize = r1Count * 2;\n\n // Main has R1..Rn, consolation has R1..Rm\n const mainRounds = Math.max(...mainMatchUps.map((m) => m.roundNumber));\n const mainLaterRounds = mainRounds - 1; // rounds after R1 (progressing right)\n const consolRounds = consolMatchUps.length > 0 ? Math.max(...consolMatchUps.map((m) => m.roundNumber)) : 0;\n\n // Layout widths\n const centerBoxWidth = 28;\n const connectorGap = 1.5;\n const remainingWidth = totalWidth - centerBoxWidth - connectorGap * 4;\n\n // Right: main R2..Rn + winner column = mainLaterRounds + 1 columns\n const rightCols = mainLaterRounds + 1;\n // Left: consolation R1..Rn + winner column = consolRounds + 1 columns\n const leftCols = Math.max(consolRounds + 1, 1);\n\n const rightWidth = remainingWidth * (rightCols / (rightCols + leftCols));\n const leftWidth = remainingWidth - rightWidth;\n const centerX = margins.left + leftWidth + connectorGap;\n\n const rightColWidth = rightCols > 0 ? (rightWidth - connectorGap * rightCols) / rightCols : 0;\n const rightStartX = centerX + centerBoxWidth + connectorGap;\n\n const leftColWidth = leftCols > 0 ? (leftWidth - connectorGap * leftCols) / leftCols : 0;\n const leftEdgeX = margins.left + leftWidth;\n\n // Vertical spacing\n const lineHeight = contentHeight / drawSize;\n const isDense = lineHeight < 3.5;\n let fontSize = SIZE.SMALL;\n if (lineHeight < 2.5) fontSize = 5;\n else if (isDense) fontSize = SIZE.TINY;\n const scoreFontSize = isDense ? 5 : SIZE.TINY;\n\n // Round headers\n renderBackdrawHeaders(\n doc,\n mainRounds,\n consolRounds,\n data,\n format,\n centerX,\n centerBoxWidth,\n rightStartX,\n rightColWidth,\n leftEdgeX,\n leftColWidth,\n connectorGap,\n regions.contentY + 2,\n fontSize,\n );\n\n renderCenterColumn(\n doc,\n r1Matches,\n r1Count,\n mainSlotMap,\n centerX,\n centerBoxWidth,\n connectorGap,\n rightStartX,\n leftEdgeX,\n contentTop,\n lineHeight,\n fontSize,\n consolRounds,\n );\n\n // ---- Right side: Main R2+ (left-to-right) ----\n renderRightBracket(\n doc,\n mainMatchUps,\n mainSlotMap,\n mainRounds,\n r1Count,\n rightStartX,\n rightColWidth,\n connectorGap,\n contentTop,\n lineHeight,\n fontSize,\n scoreFontSize,\n format,\n data.mainDraw.roundLabelMap,\n );\n\n // ---- Left side: Consolation (right-to-left, mirrored) ----\n renderLeftBracket(\n doc,\n consolMatchUps,\n consolSlotMap,\n consolRounds,\n leftEdgeX,\n leftColWidth,\n connectorGap,\n contentTop,\n lineHeight,\n r1Count,\n fontSize,\n scoreFontSize,\n format,\n data.consolation.roundLabelMap,\n );\n}\n\nfunction renderCenterColumn(\n doc: jsPDF,\n r1Matches: DrawMatchUp[],\n r1Count: number,\n mainSlotMap: Map<number, DrawSlot>,\n centerX: number,\n centerBoxWidth: number,\n connectorGap: number,\n rightStartX: number,\n leftEdgeX: number,\n contentTop: number,\n lineHeight: number,\n fontSize: number,\n consolRounds: number,\n): void {\n for (let i = 0; i < r1Count; i++) {\n const mu = r1Matches[i];\n const topY = contentTop + i * lineHeight * 2;\n const bottomY = topY + lineHeight;\n const midY = (topY + bottomY) / 2;\n const dp1 = mu.drawPositions[0];\n const dp2 = mu.drawPositions[1];\n\n const boxH = lineHeight * 0.9;\n doc.setDrawColor(40);\n doc.setLineWidth(0.3);\n doc.rect(centerX, topY, centerBoxWidth, boxH);\n doc.rect(centerX, bottomY, centerBoxWidth, boxH);\n\n const slot1 = dp1 ? mainSlotMap.get(dp1) : undefined;\n const slot2 = dp2 ? mainSlotMap.get(dp2) : undefined;\n\n setFont(doc, fontSize, STYLE.NORMAL);\n if (dp1) {\n renderCenterBoxEntry(doc, dp1, slot1, mu.winningSide === 1, centerX, topY, boxH, centerBoxWidth, fontSize);\n }\n if (dp2) {\n renderCenterBoxEntry(doc, dp2, slot2, mu.winningSide === 2, centerX, bottomY, boxH, centerBoxWidth, fontSize);\n }\n\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(centerX + centerBoxWidth, topY + boxH / 2, centerX + centerBoxWidth + connectorGap, topY + boxH / 2);\n doc.line(centerX + centerBoxWidth, bottomY + boxH / 2, centerX + centerBoxWidth + connectorGap, bottomY + boxH / 2);\n doc.line(\n centerX + centerBoxWidth + connectorGap,\n topY + boxH / 2,\n centerX + centerBoxWidth + connectorGap,\n bottomY + boxH / 2,\n );\n doc.line(centerX + centerBoxWidth + connectorGap, midY, rightStartX, midY);\n\n if (consolRounds > 0) {\n doc.line(centerX, topY + boxH / 2, centerX - connectorGap, topY + boxH / 2);\n doc.line(centerX, bottomY + boxH / 2, centerX - connectorGap, bottomY + boxH / 2);\n doc.line(centerX - connectorGap, topY + boxH / 2, centerX - connectorGap, bottomY + boxH / 2);\n doc.line(centerX - connectorGap, midY, leftEdgeX, midY);\n }\n }\n}\n\nfunction renderCenterBoxEntry(\n doc: jsPDF,\n drawPosition: number,\n slot: DrawSlot | undefined,\n isWinner: boolean,\n centerX: number,\n y: number,\n boxH: number,\n centerBoxWidth: number,\n fontSize: number,\n): void {\n doc.setTextColor(120);\n setFont(doc, fontSize, STYLE.NORMAL);\n doc.text(`${drawPosition}`, centerX + 1, y + boxH / 2 + fontSize * 0.12);\n doc.setTextColor(0);\n if (slot?.participantName) {\n const name = abbreviateName(slot.participantName);\n setFont(doc, fontSize, isWinner ? STYLE.BOLD : STYLE.NORMAL);\n doc.text(name, centerX + 5, y + boxH / 2 + fontSize * 0.12, { maxWidth: centerBoxWidth - 6 });\n }\n}\n\nfunction renderRightBracket(\n doc: jsPDF,\n matchUps: DrawMatchUp[],\n slotMap: Map<number, DrawSlot>,\n totalRounds: number,\n _r1Count: number,\n startX: number,\n colWidth: number,\n connGap: number,\n contentTop: number,\n lineHeight: number,\n fontSize: number,\n scoreFontSize: number,\n format: DrawFormatConfig,\n _roundLabelMap?: Record<number, string>,\n): void {\n // R2..Rn of the main draw, standard left-to-right\n for (let rIdx = 0; rIdx < totalRounds - 1; rIdx++) {\n const roundNum = rIdx + 2;\n const roundMus = matchUps\n .filter((m) => m.roundNumber === roundNum)\n .sort((a, b) => a.roundPosition - b.roundPosition);\n const spacing = lineHeight * Math.pow(2, rIdx + 1);\n const roundOffset = ((Math.pow(2, rIdx + 1) - 1) * lineHeight) / 2;\n const colX = startX + rIdx * (colWidth + connGap);\n\n for (let mi = 0; mi < roundMus.length; mi++) {\n const mu = roundMus[mi];\n const topY = contentTop + roundOffset + mi * spacing * 2;\n const bottomY = topY + spacing;\n const midY = (topY + bottomY) / 2;\n\n // Horizontal slot lines\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(colX, topY, colX + colWidth, topY);\n doc.line(colX, bottomY, colX + colWidth, bottomY);\n\n // Advancing names\n renderAdvancingNames(doc, mu, slotMap, colX, topY, bottomY, colWidth, fontSize, format);\n\n // Bracket connector (if not last round)\n if (rIdx < totalRounds - 2) {\n const rightX = colX + colWidth;\n doc.line(rightX + connGap, topY, rightX + connGap, bottomY);\n doc.line(rightX, topY, rightX + connGap, topY);\n doc.line(rightX, bottomY, rightX + connGap, bottomY);\n doc.line(\n rightX + connGap,\n midY,\n colX + colWidth + connGap + colWidth + connGap > 0\n ? startX + (rIdx + 1) * (colWidth + connGap)\n : rightX + connGap + 5,\n midY,\n );\n }\n\n // Score\n if (mu.score) {\n setFont(doc, scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(formatMatchScore(mu.score, format), colX + colWidth - 1, midY + scoreFontSize * 0.12, {\n align: 'right',\n });\n doc.setTextColor(0);\n }\n }\n }\n\n // Winner line\n const winnerX = startX + (totalRounds - 2) * (colWidth + connGap) + colWidth + connGap;\n const winnerMidY =\n contentTop + ((Math.pow(2, totalRounds - 1) - 1) * lineHeight) / 2 + lineHeight * Math.pow(2, totalRounds - 2);\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(winnerX, winnerMidY, winnerX + colWidth, winnerMidY);\n\n const finalMu = matchUps.find((m) => m.roundNumber === totalRounds);\n if (finalMu?.winningSide) {\n const winnerSlot = slotMap.get(finalMu.drawPositions[finalMu.winningSide - 1]);\n if (winnerSlot) {\n const { name } = formatPlayerEntrySplit(winnerSlot, format);\n setFont(doc, fontSize + 1, STYLE.BOLD);\n doc.text(name, winnerX + 1, winnerMidY - 0.5);\n }\n }\n}\n\nfunction renderLeftBracket(\n doc: jsPDF,\n matchUps: DrawMatchUp[],\n slotMap: Map<number, DrawSlot>,\n totalRounds: number,\n rightEdge: number,\n colWidth: number,\n connGap: number,\n contentTop: number,\n lineHeight: number,\n _r1Count: number,\n fontSize: number,\n scoreFontSize: number,\n format: DrawFormatConfig,\n _roundLabelMap?: Record<number, string>,\n): void {\n for (let rIdx = 0; rIdx < totalRounds; rIdx++) {\n renderLeftRound(\n doc,\n matchUps,\n slotMap,\n rIdx,\n totalRounds,\n rightEdge,\n colWidth,\n connGap,\n contentTop,\n lineHeight,\n fontSize,\n scoreFontSize,\n format,\n );\n }\n\n renderLeftWinnerColumn(\n doc,\n matchUps,\n slotMap,\n totalRounds,\n rightEdge,\n colWidth,\n connGap,\n contentTop,\n lineHeight,\n fontSize,\n format,\n );\n}\n\nfunction renderLeftRound(\n doc: jsPDF,\n matchUps: DrawMatchUp[],\n slotMap: Map<number, DrawSlot>,\n rIdx: number,\n totalRounds: number,\n rightEdge: number,\n colWidth: number,\n connGap: number,\n contentTop: number,\n lineHeight: number,\n fontSize: number,\n scoreFontSize: number,\n format: DrawFormatConfig,\n): void {\n const roundNum = rIdx + 1;\n const roundMus = matchUps.filter((m) => m.roundNumber === roundNum).sort((a, b) => a.roundPosition - b.roundPosition);\n const spacing = lineHeight * Math.pow(2, rIdx + 1);\n const roundOffset = ((Math.pow(2, rIdx + 1) - 1) * lineHeight) / 2;\n const colX = rightEdge - (rIdx + 1) * (colWidth + connGap);\n\n for (let mi = 0; mi < roundMus.length; mi++) {\n const mu = roundMus[mi];\n const topY = contentTop + roundOffset + mi * spacing * 2;\n const bottomY = topY + spacing;\n const midY = (topY + bottomY) / 2;\n\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(colX, topY, colX + colWidth, topY);\n doc.line(colX, bottomY, colX + colWidth, bottomY);\n\n renderMirroredAdvancingName(doc, mu.drawPositions[0], slotMap, fontSize, colX, colWidth, topY);\n renderMirroredAdvancingName(doc, mu.drawPositions[1], slotMap, fontSize, colX, colWidth, bottomY);\n\n if (rIdx < totalRounds - 1) {\n doc.line(colX - connGap, topY, colX - connGap, bottomY);\n doc.line(colX, topY, colX - connGap, topY);\n doc.line(colX, bottomY, colX - connGap, bottomY);\n const nextColX = rightEdge - (rIdx + 2) * (colWidth + connGap);\n doc.line(colX - connGap, midY, nextColX + colWidth, midY);\n }\n\n if (mu.score) {\n setFont(doc, scoreFontSize, STYLE.NORMAL);\n doc.setTextColor(60, 60, 160);\n doc.text(formatMatchScore(mu.score, format), colX + 1, midY + scoreFontSize * 0.12);\n doc.setTextColor(0);\n }\n }\n}\n\nfunction renderMirroredAdvancingName(\n doc: jsPDF,\n drawPosition: number | undefined,\n slotMap: Map<number, DrawSlot>,\n fontSize: number,\n colX: number,\n colWidth: number,\n y: number,\n): void {\n if (!drawPosition) return;\n const slot = slotMap.get(drawPosition);\n if (!slot?.participantName) return;\n setFont(doc, fontSize, STYLE.BOLD);\n let displayName = slot.participantName;\n if (doc.getTextWidth(displayName) > colWidth - 2) displayName = abbreviateName(displayName);\n doc.text(displayName, colX + colWidth - 1, y - 0.3, { align: 'right' });\n}\n\nfunction renderLeftWinnerColumn(\n doc: jsPDF,\n matchUps: DrawMatchUp[],\n slotMap: Map<number, DrawSlot>,\n totalRounds: number,\n rightEdge: number,\n colWidth: number,\n connGap: number,\n contentTop: number,\n lineHeight: number,\n fontSize: number,\n format: DrawFormatConfig,\n): void {\n if (totalRounds <= 0) return;\n\n const winnerX = rightEdge - (totalRounds + 1) * (colWidth + connGap);\n const winnerMidY =\n contentTop + ((Math.pow(2, totalRounds) - 1) * lineHeight) / 2 + lineHeight * Math.pow(2, totalRounds - 1);\n doc.setDrawColor(40);\n doc.setLineWidth(0.25);\n doc.line(winnerX, winnerMidY, winnerX + colWidth, winnerMidY);\n\n const finalMu = matchUps.find((m) => m.roundNumber === totalRounds);\n if (finalMu?.winningSide) {\n const winnerSlot = slotMap.get(finalMu.drawPositions[finalMu.winningSide - 1]);\n if (winnerSlot) {\n const { name } = formatPlayerEntrySplit(winnerSlot, format);\n setFont(doc, fontSize + 1, STYLE.BOLD);\n doc.text(name, winnerX + colWidth - 1, winnerMidY - 0.5, { align: 'right' });\n }\n }\n}\n\nfunction renderAdvancingNames(\n doc: jsPDF,\n mu: DrawMatchUp,\n slotMap: Map<number, DrawSlot>,\n colX: number,\n topY: number,\n bottomY: number,\n colWidth: number,\n fontSize: number,\n _format: DrawFormatConfig,\n): void {\n if (mu.drawPositions[0]) {\n const slot = slotMap.get(mu.drawPositions[0]);\n if (slot?.participantName) {\n setFont(doc, fontSize, STYLE.BOLD);\n let name = slot.participantName;\n if (doc.getTextWidth(name) > colWidth - 2) name = abbreviateName(name);\n doc.text(name, colX + 1, topY - 0.3);\n }\n }\n if (mu.drawPositions[1]) {\n const slot = slotMap.get(mu.drawPositions[1]);\n if (slot?.participantName) {\n setFont(doc, fontSize, STYLE.BOLD);\n let name = slot.participantName;\n if (doc.getTextWidth(name) > colWidth - 2) name = abbreviateName(name);\n doc.text(name, colX + 1, bottomY - 0.3);\n }\n }\n}\n\nfunction renderBackdrawHeaders(\n doc: jsPDF,\n mainRounds: number,\n consolRounds: number,\n data: BackdrawData,\n _format: DrawFormatConfig,\n centerX: number,\n centerBoxWidth: number,\n rightStartX: number,\n rightColWidth: number,\n leftEdgeX: number,\n leftColWidth: number,\n connGap: number,\n y: number,\n fontSize: number,\n): void {\n const headerFontSize = fontSize <= SIZE.TINY ? 5.5 : SIZE.SMALL;\n setFont(doc, headerFontSize, STYLE.BOLD);\n doc.setTextColor(40);\n\n // Center: \"First Round\"\n const firstRoundLabel = data.mainDraw.roundLabelMap?.[1] || 'R1';\n doc.text(firstRoundLabel, centerX + centerBoxWidth / 2, y, { align: 'center' });\n\n // Right: Main R2+\n for (let i = 0; i < mainRounds - 1; i++) {\n const roundNum = i + 2;\n const label = data.mainDraw.roundLabelMap?.[roundNum] || `R${roundNum}`;\n const colX = rightStartX + i * (rightColWidth + connGap);\n doc.text(label, colX + rightColWidth / 2, y, { align: 'center' });\n }\n\n // Left: Consolation (mirrored, labels right-to-left)\n for (let i = 0; i < consolRounds; i++) {\n const roundNum = i + 1;\n const label = data.consolation.roundLabelMap?.[roundNum] || `C-R${roundNum}`;\n const colX = leftEdgeX - (i + 1) * (leftColWidth + connGap);\n doc.text(label, colX + leftColWidth / 2, y, { align: 'center' });\n }\n\n doc.setTextColor(0);\n}\n\nfunction abbreviateName(fullName: string): string {\n const commaMatch = fullName.match(/^([^,]+),\\s*(.+)/);\n if (commaMatch) return `${commaMatch[2][0]}. ${commaMatch[1]}`;\n const spaceMatch = fullName.match(/^(\\S+)\\s+(.+)/);\n if (spaceMatch) return `${spaceMatch[1][0]}. ${spaceMatch[2]}`;\n return fullName;\n}\n","/**\n * Composable draw PDF generator.\n *\n * Accepts DrawData + composition options and produces a complete, paginated PDF\n * with headers on every page, footers on every page, and automatic orientation.\n *\n * Supports: traditional single-elimination, feed-in, consolation (multi-structure),\n * compass, double elimination, lucky draw, round robin.\n */\n\nimport jsPDF from 'jspdf';\nimport type { HeaderConfig, FooterConfig, PageConfig } from '../config/types';\nimport type { DrawFormatConfig } from '../config/types';\nimport type { DrawData, DrawMatchUp } from '../core/extractDrawData';\nimport type { CompassDrawData } from '../core/extractCompassData';\nimport type { ConsolationStructure } from '../renderers/consolationDraw';\nimport type { DoubleEliminationData } from '../renderers/doubleEliminationDraw';\nimport { renderTraditionalDraw } from '../renderers/traditionalDraw';\nimport { renderMirroredDraw } from '../renderers/mirroredDraw';\nimport { renderBackdrawDraw, type BackdrawData } from '../renderers/backdrawDraw';\nimport { renderCompassDraw } from '../renderers/compassDraw';\nimport { renderConsolationDraw } from '../renderers/consolationDraw';\nimport { renderDoubleEliminationDraw } from '../renderers/doubleEliminationDraw';\nimport { renderLuckyDraw } from '../renderers/luckyDraw';\nimport { createDoc, getPageRegions } from '../composition/page';\nimport { renderHeader } from '../composition/headerLayouts';\nimport { renderFooter, measureFooterHeight } from '../composition/footerLayouts';\nimport { getPreset } from '../config/formatPresets';\nimport { splitDraw } from '../renderers/drawSplitter';\n\nexport interface DrawPDFOptions {\n header?: HeaderConfig;\n footer?: FooterConfig;\n page?: Partial<PageConfig>;\n preset?: string;\n format?: DrawFormatConfig;\n}\n\n/**\n * Smart entry point for TMX integration.\n *\n * Accepts DrawData and auto-detects the draw type to route to the correct renderer.\n * TMX callers can use getEventData() output directly — the generator inspects\n * matchUp patterns, structure count, and drawType to choose the layout.\n *\n * Header/footer configs come from provider defaults; tournament directors can override.\n */\nexport function generateDrawPDF(drawData: DrawData, options: DrawPDFOptions = {}): jsPDF {\n // Detect feed structure\n if (detectFeedStructure(drawData.matchUps)) {\n return generateFeedInDrawPDF(drawData, options);\n }\n\n // Standard single-elimination\n return generateTraditionalDrawPDF(drawData, options);\n}\n\nfunction detectFeedStructure(matchUps: DrawMatchUp[]): boolean {\n const roundCounts = new Map<number, number>();\n for (const mu of matchUps) {\n roundCounts.set(mu.roundNumber, (roundCounts.get(mu.roundNumber) || 0) + 1);\n }\n const rounds = [...roundCounts.keys()].sort((a, b) => a - b);\n for (let i = 1; i < rounds.length; i++) {\n const prev = roundCounts.get(rounds[i - 1]) || 0;\n const curr = roundCounts.get(rounds[i]) || 0;\n if (curr >= prev) return true;\n }\n return false;\n}\n\ninterface PageChrome {\n doc: jsPDF;\n pageConfig: PageConfig;\n headerConfig: HeaderConfig;\n footerConfig: FooterConfig;\n format: DrawFormatConfig;\n headerH: number;\n footerH: number;\n}\n\n// ---- Public API ----\n\nexport function generateTraditionalDrawPDF(drawData: DrawData, options: DrawPDFOptions = {}): jsPDF {\n // 256+ draws must always be split — too dense for single-page rendering\n if (drawData.drawSize >= 256) {\n return generateSplitDrawPDF(drawData, { ...options, maxPositionsPerPage: 64 });\n }\n\n const chrome = initChrome(drawData.drawSize, options);\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, chrome.headerH, chrome.footerH);\n\n renderTraditionalDraw(chrome.doc, drawData, chrome.format, regions);\n finalizePages(chrome);\n return chrome.doc;\n}\n\nexport function generateSplitDrawPDF(\n drawData: DrawData,\n options: DrawPDFOptions & { maxPositionsPerPage?: number } = {},\n): jsPDF {\n const chrome = initChrome(drawData.drawSize, options);\n const maxPerPage = options.maxPositionsPerPage || 32;\n const segments = splitDraw(drawData, {\n maxPositionsPerPage: maxPerPage,\n includeOverlapRounds: true,\n summaryPage: true,\n });\n\n for (let i = 0; i < segments.length; i++) {\n if (i > 0) chrome.doc.addPage();\n\n const headerH = renderHeader(\n chrome.doc,\n { ...chrome.headerConfig, subtitle: segments[i].label },\n chrome.pageConfig,\n );\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, headerH, chrome.footerH);\n\n if (segments[i].slots.length > 0 || segments[i].matchUps.length > 0) {\n const seg = segments[i];\n const segDrawSize = seg.endPosition - seg.startPosition + 1;\n const segData: DrawData = {\n ...drawData,\n slots: seg.slots,\n matchUps: seg.matchUps,\n noWinnerColumn: seg.noWinnerColumn,\n roundLabelMap: seg.roundLabelMap || drawData.roundLabelMap,\n drawSize: segDrawSize,\n totalRounds: seg.segmentRounds,\n };\n renderTraditionalDraw(chrome.doc, segData, chrome.format, regions, seg.startPosition - 1, segDrawSize);\n }\n }\n\n finalizePages(chrome);\n return chrome.doc;\n}\n\nexport function generateFeedInDrawPDF(drawData: DrawData, options: DrawPDFOptions = {}): jsPDF {\n const needsLandscape = drawData.totalRounds >= 5 || drawData.slots.length >= 12;\n const chrome = initChrome(drawData.drawSize, options, needsLandscape);\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, chrome.headerH, chrome.footerH);\n\n renderTraditionalDraw(chrome.doc, drawData, chrome.format, regions);\n finalizePages(chrome);\n return chrome.doc;\n}\n\nexport function generateConsolationDrawPDF(structures: ConsolationStructure[], options: DrawPDFOptions = {}): jsPDF {\n const maxSize = Math.max(...structures.map((s) => s.drawData.drawSize), 8);\n const chrome = initChrome(maxSize, options);\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, chrome.headerH, chrome.footerH);\n\n renderConsolationDraw(chrome.doc, structures, chrome.format, regions);\n // Consolation renderer may add pages — render header on any new pages\n renderHeadersOnNewPages(chrome, 1);\n finalizePages(chrome);\n return chrome.doc;\n}\n\nexport function generateCompassDrawPDF(compassData: CompassDrawData, options: DrawPDFOptions = {}): jsPDF {\n const mainSize = compassData.mainStructure?.drawSize || 8;\n const chrome = initChrome(mainSize, options);\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, chrome.headerH, chrome.footerH);\n\n renderCompassDraw(chrome.doc, compassData, chrome.format, regions);\n // Compass renderer may add pages — render header on any new pages\n renderHeadersOnNewPages(chrome, 1);\n finalizePages(chrome);\n return chrome.doc;\n}\n\nexport function generateMirroredDrawPDF(drawData: DrawData, options: DrawPDFOptions = {}): jsPDF {\n const chrome = initChrome(drawData.drawSize, options, true);\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, chrome.headerH, chrome.footerH);\n\n renderMirroredDraw(chrome.doc, drawData, chrome.format, regions);\n finalizePages(chrome);\n return chrome.doc;\n}\n\nexport function generateBackdrawPDF(data: BackdrawData, options: DrawPDFOptions = {}): jsPDF {\n const chrome = initChrome(data.mainDraw.drawSize, options, true);\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, chrome.headerH, chrome.footerH);\n\n renderBackdrawDraw(chrome.doc, data, chrome.format, regions);\n finalizePages(chrome);\n return chrome.doc;\n}\n\nexport function generateDoubleEliminationPDF(data: DoubleEliminationData, options: DrawPDFOptions = {}): jsPDF {\n const size = Math.max(data.winnersBracket.drawSize, data.losersBracket.drawSize, 8);\n const chrome = initChrome(size, options, true);\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, chrome.headerH, chrome.footerH);\n\n renderDoubleEliminationDraw(chrome.doc, data, chrome.format, regions);\n finalizePages(chrome);\n return chrome.doc;\n}\n\nexport function generateLuckyDrawPDF(drawData: DrawData, options: DrawPDFOptions = {}): jsPDF {\n const chrome = initChrome(drawData.drawSize, options);\n const regions = getPageRegions(chrome.doc, chrome.pageConfig, chrome.headerH, chrome.footerH);\n\n renderLuckyDraw(chrome.doc, drawData, chrome.format, regions);\n finalizePages(chrome);\n return chrome.doc;\n}\n\n// ---- Internal helpers ----\n\nfunction initChrome(drawSize: number, options: DrawPDFOptions, forceLandscape?: boolean): PageChrome {\n const format = options.format || getPreset(options.preset || 'itfJunior');\n const pageConfig: PageConfig = {\n ...format.page,\n ...options.page,\n orientation: forceLandscape ? 'landscape' : options.page?.orientation || format.page.orientation,\n };\n\n const headerConfig: HeaderConfig = options.header || { layout: 'none', tournamentName: '' };\n const footerConfig: FooterConfig = options.footer || {\n layout: 'standard',\n showPageNumbers: true,\n showTimestamp: true,\n };\n\n const doc = createDoc(pageConfig, drawSize);\n const footerH = measureFooterHeight(footerConfig);\n const headerH = renderHeader(doc, headerConfig, pageConfig);\n\n return { doc, pageConfig, headerConfig, footerConfig, format, headerH, footerH };\n}\n\n/** Render header on any pages added after the initial page (page 1 already has one) */\nfunction renderHeadersOnNewPages(chrome: PageChrome, firstPageCount: number): void {\n const totalPages = chrome.doc.getNumberOfPages();\n for (let p = firstPageCount + 1; p <= totalPages; p++) {\n chrome.doc.setPage(p);\n renderHeader(chrome.doc, chrome.headerConfig, chrome.pageConfig);\n }\n}\n\n/** Render footer on every page with correct page numbers */\nfunction finalizePages(chrome: PageChrome): void {\n const totalPages = chrome.doc.getNumberOfPages();\n for (let p = 1; p <= totalPages; p++) {\n chrome.doc.setPage(p);\n renderFooter(chrome.doc, chrome.footerConfig, chrome.pageConfig, p);\n }\n // Ensure we end on the last page\n chrome.doc.setPage(totalPages);\n}\n","/**\n * High-level TMX API for PDF generation from eventData.\n *\n * TMX calls: generateFromEventData(eventData, options) → jsPDF\n *\n * This resolves a catalog preset, populates header/footer from\n * tournamentInfo/eventInfo, and routes to the appropriate generator.\n */\n\nimport jsPDF from 'jspdf';\nimport type { HeaderConfig, FooterConfig } from '../config/types';\nimport { getCatalogPreset } from '../config/compositionCatalog';\nimport { getPreset } from '../config/formatPresets';\nimport { structureToDrawData, findStructure } from '../core/drawsDataToDrawData';\nimport type { DrawData } from '../core/extractDrawData';\nimport type { ConsolationStructure } from '../renderers/consolationDraw';\nimport type { DoubleEliminationData } from '../renderers/doubleEliminationDraw';\nimport {\n generateTraditionalDrawPDF,\n generateSplitDrawPDF,\n generateConsolationDrawPDF,\n generateDoubleEliminationPDF,\n generateMirroredDrawPDF,\n} from './drawPDF';\nimport { createDoc } from '../composition/page';\n\nexport interface GenerateFromEventDataOptions {\n catalogPreset?: string;\n headerOverrides?: Partial<HeaderConfig>;\n footerOverrides?: Partial<FooterConfig>;\n structureId?: string;\n splitPages?: boolean;\n maxPositionsPerPage?: number;\n mirrored?: boolean;\n}\n\nexport function generateFromEventData(eventData: any, options: GenerateFromEventDataOptions = {}): jsPDF {\n const drawsData = eventData?.drawsData || [];\n const tournamentInfo = eventData?.tournamentInfo || {};\n const eventInfo = eventData?.eventInfo || {};\n\n // Resolve catalog preset\n const preset = getCatalogPreset(options.catalogPreset || 'club-basic');\n const drawFormat = getPreset(preset?.drawFormatPreset || 'itfJunior');\n\n // Build header config from tournament/event info + catalog + overrides\n const header: HeaderConfig = {\n layout: 'itf',\n tournamentName: tournamentInfo.tournamentName || 'Tournament',\n ...preset?.header,\n subtitle: eventInfo.eventName || preset?.header?.subtitle,\n startDate: tournamentInfo.startDate,\n endDate: tournamentInfo.endDate,\n location: tournamentInfo.venues?.[0]?.venueName,\n city: tournamentInfo.venues?.[0]?.city,\n country: tournamentInfo.hostCountryCode,\n surface: eventInfo.surfaceCategory,\n ...options.headerOverrides,\n };\n\n // Build footer config from catalog + overrides\n const footer: FooterConfig = {\n layout: 'standard',\n showPageNumbers: true,\n showTimestamp: true,\n ...preset?.footer,\n ...options.footerOverrides,\n };\n\n // Detect draw type from structures\n const structures = drawsData?.[0]?.structures || [];\n const hasConsolation = structures.some((s: any) => s.stage === 'CONSOLATION');\n const hasPlayOff = structures.some((s: any) => s.stage === 'PLAY_OFF');\n const mainStruct = structures.find((s: any) => s.stage === 'MAIN');\n\n const pdfOpts = { header, footer, format: drawFormat };\n\n // Double elimination: MAIN + CONSOLATION + PLAY_OFF\n if (hasConsolation && hasPlayOff) {\n const data: DoubleEliminationData = {\n winnersBracket: mainStruct ? structureToDrawData(mainStruct) : emptyDrawData(),\n losersBracket: findStructure(drawsData, 'CONSOLATION')\n ? structureToDrawData(findStructure(drawsData, 'CONSOLATION'))\n : emptyDrawData(),\n deciderMatch: findStructure(drawsData, 'PLAY_OFF')\n ? structureToDrawData(findStructure(drawsData, 'PLAY_OFF'))\n : undefined,\n };\n return generateDoubleEliminationPDF(data, pdfOpts);\n }\n\n // Consolation: MAIN + CONSOLATION (no PLAY_OFF)\n if (hasConsolation) {\n const consolStructures: ConsolationStructure[] = structures.map((s: any) => ({\n name: s.structureName,\n stage: s.stage,\n drawData: structureToDrawData(s),\n }));\n return generateConsolationDrawPDF(consolStructures, pdfOpts);\n }\n\n // Single structure — determine which renderer\n const targetStruct = options.structureId\n ? structures.find((s: any) => s.structureId === options.structureId) || mainStruct\n : mainStruct;\n\n if (!targetStruct) {\n return createDoc({\n pageSize: 'a4',\n orientation: 'portrait',\n margins: { top: 12, right: 15, bottom: 12, left: 15 },\n });\n }\n\n const drawData = structureToDrawData(targetStruct);\n\n // Mirrored bracket\n if (options.mirrored) {\n return generateMirroredDrawPDF(drawData, pdfOpts);\n }\n\n // Split pages\n if (options.splitPages || drawData.drawSize >= 256) {\n return generateSplitDrawPDF(drawData, { ...pdfOpts, maxPositionsPerPage: options.maxPositionsPerPage || 32 });\n }\n\n // Feed-in detection (done inside generateTraditionalDrawPDF via detectFeedStructure)\n return generateTraditionalDrawPDF(drawData, pdfOpts);\n}\n\nfunction emptyDrawData(): DrawData {\n return { drawName: '', drawSize: 0, drawType: '', totalRounds: 0, slots: [], matchUps: [], seedAssignments: [] };\n}\n"],"mappings":"yLAEA,IAAM,EAAyC,CAC7C,EAAG,QACH,GAAI,cACJ,GAAI,iBACJ,IAAK,cACL,IAAK,cACL,IAAK,cACL,KAAM,eACP,CAEK,EAA2C,CAC/C,EAAG,QACH,GAAI,cACJ,GAAI,iBACJ,IAAK,eACL,IAAK,cACL,IAAK,eACL,KAAM,cACP,CAEK,EAAwC,CAC5C,EAAG,QACH,GAAI,aACJ,GAAI,gBACJ,IAAK,UACL,IAAK,UACL,IAAK,UACL,KAAM,UACP,CAEK,EAAwC,CAC5C,EAAG,SACH,GAAI,aACJ,GAAI,aACJ,IAAK,aACL,IAAK,YACL,IAAK,YACL,KAAM,WACP,CAEK,EAAe,CACnB,SAAU,KACV,YAAa,OACb,QAAS,CAAE,IAAK,GAAI,MAAO,GAAI,OAAQ,GAAI,KAAM,GAAI,CACtD,CAGK,EAAmB,cACnB,EAAW,OACX,EAAc,kBACd,EAAgB,WAChB,EAAc,IACd,EAAc,oBAEP,EAA4C,CACvD,UAAW,CACT,WAAY,EACZ,kBAAmB,EACnB,aAAc,EACd,WAAY,EACZ,YAAa,SACb,mBAAoB,EACpB,kBAAmB,IACnB,gBAAiB,OACjB,cAAe,MACf,YAAa,EACb,YAAa,EACb,KAAM,C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