All files / src/components TournamentBracket.vue

93.15% Statements 408/438
73.58% Branches 78/106
66.66% Functions 10/15
93.15% Lines 408/438

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 7691x 1x 1x 1x   4x   1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x   1x 1x   1x 1x 1x 1x 1x   1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x   1x         1x       1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 95x 95x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 95x 95x 95x 95x 48x 48x 33x 33x 33x 15x 15x 95x 95x   1x 95x 95x 95x 95x 27x 27x 27x 27x 95x 95x   1x 1x 19x 19x 19x 19x 19x 1x   1x   1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   76x 76x 76x 570x 570x 570x 570x 541x 76x 76x 76x   76x 76x   76x 76x 76x 76x 76x   76x 76x 76x 76x 14x 14x 14x 14x 14x   14x 8x 8x 8x 6x 6x 6x 14x 14x 14x       6x 6x   76x 76x 76x   1x 19x 1x 1x 19x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 19x 19x 19x 19x 19x 1x   1x 1x 1x 19x 1x   1x   1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 7x 7x 7x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 7x 4x 4x 1x   1x 4x 4x 4x 4x 4x 4x 1x   1x 1x 1x 1x 1x 1x 1x 1x 351x 351x 351x 48x 48x 48x 48x 48x 351x   351x 351x 303x 303x 303x 303x 303x 303x 303x 303x 303x 303x 303x 48x 48x 48x 48x 48x 48x 48x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 48x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 48x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x 351x                         351x 351x 351x 351x 351x 351x 1x 1x   1x   96x 96x     96x               96x 96x   96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x               48x 48x 48x 48x 48x 48x 48x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
<template>
  <div>
    <!-- No matches in this bracket -->
    <div v-if="!hasAnyBracket" class="text-center py-10 text-fg-muted">
      No matches in this bracket yet.
    </div>
 
    <!-- Compact path: bracket starts deeper than R32 (e.g. SF + Final only).
         Self-scales to the populated rounds so small brackets render. -->
    <div v-else-if="!isFullBracket" class="overflow-x-auto pb-4">
      <div class="bracket-grid-compact" :style="compactGridStyle">
        <div
          v-for="(label, i) in compactLayout.headers"
          :key="`chdr-${i}`"
          class="bracket-header"
          :style="{ gridColumn: i + 1, gridRow: 1 }"
        >
          {{ label }}
        </div>
        <div
          v-for="it in compactLayout.items"
          :key="it.key"
          class="bracket-cell-compact"
          :class="{ 'is-last': it.isLastCol }"
          :style="{
            gridColumn: it.col,
            gridRow: `${it.rowStart} / span ${it.rowSpan}`,
          }"
        >
          <div v-if="it.showBridge" class="bracket-bridge"></div>
          <div class="bracket-cell-inner">
            <BracketCell
              :match="it.match"
              :is-final="it.isFinal"
              @click="$emit('match-click', it.match)"
            />
          </div>
        </div>
      </div>
    </div>
 
    <div v-else class="overflow-x-auto pb-4">
      <div class="bracket-grid min-w-[1080px]">
        <!-- Column headers -->
        <div
          v-for="(round, i) in ROUNDS"
          :key="`hdr-${round.key}`"
          :class="['bracket-header', `col-${i + 1}`]"
        >
          {{ round.label }}
        </div>
 
        <!-- R32 cells (16) -->
        <div
          v-for="(m, idx) in r32Matches"
          :key="`r32-${idx}`"
          :class="['bracket-cell', `col-1`, `r32-${idx}`]"
        >
          <BracketCell :match="m" @click="$emit('match-click', m)" />
        </div>
 
        <!-- Later rounds: real matches where loaded, placeholder otherwise -->
        <div
          v-for="(m, idx) in r16Cells"
          :key="`r16-${idx}`"
          :class="['bracket-cell', `col-2`, `r16-${idx}`]"
        >
          <BracketCell :match="m" @click="$emit('match-click', m)" />
        </div>
        <div
          v-for="(m, idx) in qfCells"
          :key="`qf-${idx}`"
          :class="['bracket-cell', `col-3`, `qf-${idx}`]"
        >
          <BracketCell :match="m" @click="$emit('match-click', m)" />
        </div>
        <div
          v-for="(m, idx) in sfCells"
          :key="`sf-${idx}`"
          :class="['bracket-cell', `col-4`, `sf-${idx}`]"
        >
          <BracketCell :match="m" @click="$emit('match-click', m)" />
        </div>
        <div :class="['bracket-cell', `col-5`, `final-0`]">
          <BracketCell
            :match="finalCell"
            :is-final="true"
            @click="$emit('match-click', finalCell)"
          />
        </div>
      </div>
    </div>
  </div>
</template>
 
<script setup>
import { computed, h } from 'vue';
import { BRACKET_ROUND_ORDER } from '../utils/tournamentRounds';
 
const props = defineProps({
  matches: { type: Array, required: true },
  // Match ids that are a tournament Match of the Day (SB-1560): ringed in
  // amber so the pick is findable in the bracket, not only in the banner.
  motdMatchIds: { type: Array, default: () => [] },
});
 
defineEmits(['match-click']);
 
// Column headings are plural where a round has several matches, so they are
// kept here rather than taken from the shared (singular) round labels.
const COLUMN_HEADINGS = {
  round_of_32: 'Round of 32',
  round_of_16: 'Round of 16',
  quarterfinal: 'Quarterfinals',
  semifinal: 'Semifinals',
  final: 'Final',
};
 
const ROUNDS = BRACKET_ROUND_ORDER.map(key => ({
  key,
  label: COLUMN_HEADINGS[key],
}));
 
// `tournament_round_order` is the explicit bracket-position field (0-based,
// top of bracket = 0). When present, the match goes at that slot directly.
// When absent, the match is placed via the per-round fallback chain below:
//   R32: id-order
//   R16 / QF / SF / Final: feeder-derived (pair (2k, 2k+1) → slot k), then id-order
//
// The mlssoccer.com canonical layout doesn't always match the order matches
// were inserted into the DB, so id-order alone produces misaligned
// brackets — tournament_round_order is the proper fix.
 
// Place matches into a fixed-size slot array. Explicit tournament_round_order
// wins; collisions and unordered matches drop into `unresolved` for the
// caller's secondary placement strategy (feeder-derived or id-order).
function placeWithExplicitOrder(matches, slotCount) {
  const placed = Array.from({ length: slotCount }, () => null);
  const unresolved = [];
  for (const m of matches) {
    const slot = m.tournament_round_order;
    if (slot == null || slot < 0 || slot >= slotCount || placed[slot] != null) {
      unresolved.push(m);
      continue;
    }
    placed[slot] = m;
  }
  return { placed, unresolved };
}
 
// Drop unresolved matches into remaining empty slots in id order.
function fillRemainingByIdOrder(placed, unresolved, slotCount) {
  const remaining = [...unresolved].sort((a, b) => a.id - b.id);
  let cursor = 0;
  for (const m of remaining) {
    while (cursor < slotCount && placed[cursor] != null) cursor++;
    if (cursor >= slotCount) break;
    placed[cursor] = m;
  }
  return placed;
}
 
// R32 has no feeder round — only explicit-order and id-order placement.
const r32Matches = computed(() => {
  const matches = props.matches.filter(
    m => m.tournament_round === 'round_of_32'
  );
  const { placed, unresolved } = placeWithExplicitOrder(matches, 16);
  return fillRemainingByIdOrder(placed, unresolved, 16);
});
 
const hasAnyR32 = computed(() => r32Matches.value.some(m => m != null));
 
// When R32 is present we render the canonical full 32-team layout below.
// A full bracket is exactly "R32 has matches".
const isFullBracket = computed(() => hasAnyR32.value);
 
// ── Feeder-derived placement ──────────────────────────────────────────────
// For R16 / QF / SF / Final, we don't just sort by id — we place each match
// directly under its two feeder matches.
//
// In a single-elimination bracket, the pair (2k, 2k+1) of feeder slots feeds
// into slot k of the next round. So if team A advanced from R32 slot 4 and
// team B from R32 slot 5, the R16 match they meet in goes at R16 slot 2.
//
// We detect the feeder slot by looking up each team's id in the feeder
// round's placement. Matches whose teams aren't in the feeder round (e.g.
// placeholders before the feeder round is loaded, or off-bracket teams)
// fall back to id-order placement in whatever slots remain.
 
function buildFeederSlotByTeam(feederCells) {
  const map = new Map();
  feederCells.forEach((m, slot) => {
    if (!m) return;
    const homeId = m.home_team?.id;
    const awayId = m.away_team?.id;
    if (homeId != null) map.set(homeId, slot);
    if (awayId != null) map.set(awayId, slot);
  });
  return map;
}
 
function placeByFeeder(roundKey, feederCells, slotCount) {
  const matches = props.matches.filter(m => m.tournament_round === roundKey);
 
  // Pass 1: respect explicit tournament_round_order.
  const { placed, unresolved: needFeederOrId } = placeWithExplicitOrder(
    matches,
    slotCount
  );
 
  // Pass 2: for the remainder, derive slot from the two teams' feeder slots.
  const feederSlotByTeam = buildFeederSlotByTeam(feederCells);
  const stillUnresolved = [];
  for (const m of needFeederOrId) {
    const feederSlots = [];
    const homeSlot = feederSlotByTeam.get(m.home_team?.id);
    const awaySlot = feederSlotByTeam.get(m.away_team?.id);
    if (homeSlot != null) feederSlots.push(homeSlot);
    if (awaySlot != null) feederSlots.push(awaySlot);
 
    if (feederSlots.length === 0) {
      stillUnresolved.push(m);
      continue;
    }
    const targetSlot = Math.floor(Math.min(...feederSlots) / 2);
    if (
      targetSlot < 0 ||
      targetSlot >= slotCount ||
      placed[targetSlot] != null
    ) {
      stillUnresolved.push(m);
      continue;
    }
    placed[targetSlot] = m;
  }
 
  // Pass 3: id-order fallback for anything that didn't fit.
  return fillRemainingByIdOrder(placed, stillUnresolved, slotCount);
}
 
const r16Cells = computed(() =>
  placeByFeeder('round_of_16', r32Matches.value, 8)
);
const qfCells = computed(() =>
  placeByFeeder('quarterfinal', r16Cells.value, 4)
);
const sfCells = computed(() => placeByFeeder('semifinal', qfCells.value, 2));
const finalCell = computed(() => placeByFeeder('final', sfCells.value, 1)[0]);
 
// ── Small-bracket (compact) layout ─────────────────────────────────────────
// The full layout above hard-seeds a 16-slot Round of 32. Tournaments whose
// playoffs are smaller than 32 teams (e.g. a 4-team Semifinal + Final) have no
// R32 matches, so the canonical grid collapses to the empty state. The compact
// path renders only the populated rounds, starting from the deepest one that
// actually has matches, and self-scales the row count to that entry round.
 
const roundCells = computed(() => [
  { key: 'round_of_32', label: 'Round of 32', cells: r32Matches.value },
  { key: 'round_of_16', label: 'Round of 16', cells: r16Cells.value },
  { key: 'quarterfinal', label: 'Quarterfinals', cells: qfCells.value },
  { key: 'semifinal', label: 'Semifinals', cells: sfCells.value },
  { key: 'final', label: 'Final', cells: [finalCell.value] },
]);
 
// Index of the shallowest round that has at least one real match. -1 when the
// bracket is entirely empty.
const firstRoundIdx = computed(() =>
  roundCells.value.findIndex(r => r.cells.some(m => m != null))
);
 
const hasAnyBracket = computed(() => firstRoundIdx.value !== -1);
 
// Positioned cells for the compact grid. Null unless we're on the compact path
// (some bracket match exists, but no R32). Geometry mirrors the full layout:
// the entry round gets 2 rows per cell, each later round doubles its span so
// every match centers between its two feeders.
const compactLayout = computed(() => {
  if (firstRoundIdx.value <= 0) return null;
  const rounds = roundCells.value.slice(firstRoundIdx.value);
  const firstSlots = rounds[0].cells.length;
  const totalRows = firstSlots * 2;
  const nCols = rounds.length;
  const items = [];
  rounds.forEach((round, d) => {
    const slotCount = round.cells.length;
    const rowsPerCell = totalRows / slotCount;
    round.cells.forEach((m, i) => {
      items.push({
        key: `${round.key}-${i}`,
        col: d + 1,
        rowStart: 2 + i * rowsPerCell, // row 1 is the header track
        rowSpan: rowsPerCell,
        match: m,
        isFinal: round.key === 'final',
        isLastCol: d === nCols - 1,
        // Vertical bridge joins each sibling pair (2k, 2k+1); draw it on the
        // top cell of the pair. Never on the last column (the final).
        showBridge: d < nCols - 1 && i % 2 === 0,
      });
    });
  });
  return { items, totalRows, nCols, headers: rounds.map(r => r.label) };
});
 
const compactGridStyle = computed(() => {
  const l = compactLayout.value;
  if (!l) return '';
  return (
    `grid-template-columns: repeat(${l.nCols}, minmax(170px, 1fr));` +
    `grid-template-rows: auto repeat(${l.totalRows}, minmax(28px, 1fr));`
  );
});
 
// ── Inline child component for match cells ──
const BracketCell = {
  props: {
    match: { type: Object, default: null },
    isFinal: { type: Boolean, default: false },
  },
  emits: ['click'],
  setup(p, { emit }) {
    const homeWinner = computed(() => isWinner(p.match, 'home'));
    const awayWinner = computed(() => isWinner(p.match, 'away'));
    const statusLabel = computed(() => {
      if (!p.match) return null;
      if (p.match.match_status === 'completed') return 'Final';
      if (['live', 'in_progress'].includes(p.match.match_status)) return 'Live';
      if (p.match.match_status === 'cancelled') return 'Cancelled';
      return null;
    });
 
    return () => {
      if (!p.match) {
        return h(
          'div',
          {
            class: [
              'h-full rounded-md border border-dashed border-line bg-surface-alt/50 flex items-center justify-center text-fg-muted text-xs',
              p.isFinal ? 'px-3 py-2' : 'px-2 py-1.5',
            ],
          },
          '—'
        );
      }
      const live = p.match.match_status === 'in_progress';
      const motd = props.motdMatchIds.includes(p.match.id);
      return h(
        'button',
        {
          type: 'button',
          onClick: () => emit('click', p.match),
          'data-motd': motd ? 'true' : 'false',
          title: motd ? 'Match of the Day' : undefined,
          class: [
            'w-full text-left rounded-md border bg-card px-2 py-1.5 shadow-sm hover:border-brand-400 transition-colors',
            live ? 'border-brand-400 animate-pulse' : 'border-line',
            motd ? 'ring-2 ring-amber-400 dark:ring-amber-500' : '',
          ],
        },
        [
          // Row 1: home team
          h(
            'div',
            {
              class: [
                'flex items-center justify-between gap-2 text-xs',
                homeWinner.value
                  ? 'font-bold text-fg'
                  : p.match.match_status === 'completed'
                    ? 'text-fg-muted'
                    : 'text-fg',
              ],
            },
            [
              h(
                'span',
                { class: 'truncate min-w-0' },
                p.match.home_team?.name || 'TBD'
              ),
              h(
                'span',
                { class: 'font-mono tabular-nums shrink-0' },
                scoreCell(p.match, 'home')
              ),
            ]
          ),
          // Row 2: away team
          h(
            'div',
            {
              class: [
                'flex items-center justify-between gap-2 text-xs mt-0.5',
                awayWinner.value
                  ? 'font-bold text-fg'
                  : p.match.match_status === 'completed'
                    ? 'text-fg-muted'
                    : 'text-fg',
              ],
            },
            [
              h(
                'span',
                { class: 'truncate min-w-0' },
                p.match.away_team?.name || 'TBD'
              ),
              h(
                'span',
                { class: 'font-mono tabular-nums shrink-0' },
                scoreCell(p.match, 'away')
              ),
            ]
          ),
          // Row 3: meta (date + status)
          h(
            'div',
            {
              class:
                'mt-1 flex items-center justify-between text-[10px] text-fg-muted',
            },
            [
              h('span', null, formatMatchDate(p.match.match_date)),
              statusLabel.value
                ? h(
                    'span',
                    {
                      class: live
                        ? 'text-brand-600 font-semibold'
                        : statusLabel.value === 'Final'
                          ? 'text-green-600 font-semibold'
                          : statusLabel.value === 'Cancelled'
                            ? 'text-red-500'
                            : '',
                    },
                    statusLabel.value
                  )
                : null,
            ]
          ),
        ]
      );
    };
  },
};
 
// ── helpers ──
 
function isWinner(match, side) {
  if (!match || match.match_status !== 'completed') return false;
  const h = match.home_score;
  const a = match.away_score;
  if (h == null || a == null) return false;
  // PK shootout wins handled via penalty scores when regulation is tied.
  if (h === a) {
    const hp = match.home_penalty_score;
    const ap = match.away_penalty_score;
    if (hp == null || ap == null) return false;
    return side === 'home' ? hp > ap : ap > hp;
  }
  return side === 'home' ? h > a : a > h;
}
 
function scoreCell(match, side) {
  // A not-yet-played match can carry a stored 0:0 (create defaults scores to 0,
  // and there is no write path to null them again). Only surface a score once the
  // match is actually under way or has a result — otherwise it reads as a played
  // 0:0 draw. A forfeit carries a real result (e.g. 3:0), so it counts too; this
  // mirrors the backend, which treats ('completed', 'forfeit') as result-bearing.
  if (
    match.match_status !== 'completed' &&
    match.match_status !== 'in_progress' &&
    match.match_status !== 'forfeit'
  )
    return 'TBD';
  if (match.home_score == null || match.away_score == null) return 'TBD';
  const base = side === 'home' ? match.home_score : match.away_score;
  if (match.home_penalty_score != null && match.away_penalty_score != null) {
    const pk =
      side === 'home' ? match.home_penalty_score : match.away_penalty_score;
    return `${base} (${pk})`;
  }
  return String(base);
}
 
function formatMatchDate(d) {
  if (!d) return '';
  return new Date(d + 'T00:00:00').toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
  });
}
</script>
 
<style scoped>
/*
 * Single-elimination 32-team bracket on a CSS grid.
 *
 * 32 row tracks let each round-cell span the right number of rows to
 * center it vertically against its parent: R32 spans 2, R16 spans 4,
 * QF spans 8, SF spans 16, Final spans 32. The connector lines are
 * drawn with ::before/::after pseudo-elements on each cell.
 */
.bracket-grid {
  display: grid;
  grid-template-columns:
    minmax(170px, 1fr) minmax(170px, 1fr) minmax(170px, 1fr)
    minmax(170px, 1fr) minmax(170px, 1fr);
  grid-template-rows: auto repeat(32, minmax(28px, 1fr));
  gap: 0;
  position: relative;
}
 
.bracket-header {
  grid-row: 1;
  font-size: 0.7rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  color: rgb(var(--color-fg-muted));
  text-align: center;
  padding-bottom: 0.5rem;
}
.col-1 {
  grid-column: 1;
}
.col-2 {
  grid-column: 2;
}
.col-3 {
  grid-column: 3;
}
.col-4 {
  grid-column: 4;
}
.col-5 {
  grid-column: 5;
}
 
.bracket-cell {
  position: relative;
  padding: 4px 12px 4px 4px;
  display: flex;
  align-items: center;
}
.col-2.bracket-cell,
.col-3.bracket-cell,
.col-4.bracket-cell,
.col-5.bracket-cell {
  padding-left: 12px;
}
 
.bracket-cell > * {
  width: 100%;
}
 
/* R32: rows 2..33 in pairs of 2 */
.r32-0 {
  grid-row: 2 / span 2;
}
.r32-1 {
  grid-row: 4 / span 2;
}
.r32-2 {
  grid-row: 6 / span 2;
}
.r32-3 {
  grid-row: 8 / span 2;
}
.r32-4 {
  grid-row: 10 / span 2;
}
.r32-5 {
  grid-row: 12 / span 2;
}
.r32-6 {
  grid-row: 14 / span 2;
}
.r32-7 {
  grid-row: 16 / span 2;
}
.r32-8 {
  grid-row: 18 / span 2;
}
.r32-9 {
  grid-row: 20 / span 2;
}
.r32-10 {
  grid-row: 22 / span 2;
}
.r32-11 {
  grid-row: 24 / span 2;
}
.r32-12 {
  grid-row: 26 / span 2;
}
.r32-13 {
  grid-row: 28 / span 2;
}
.r32-14 {
  grid-row: 30 / span 2;
}
.r32-15 {
  grid-row: 32 / span 2;
}
 
/* R16: each spans 4 rows, centered between its two R32 parents */
.r16-0 {
  grid-row: 2 / span 4;
}
.r16-1 {
  grid-row: 6 / span 4;
}
.r16-2 {
  grid-row: 10 / span 4;
}
.r16-3 {
  grid-row: 14 / span 4;
}
.r16-4 {
  grid-row: 18 / span 4;
}
.r16-5 {
  grid-row: 22 / span 4;
}
.r16-6 {
  grid-row: 26 / span 4;
}
.r16-7 {
  grid-row: 30 / span 4;
}
 
/* QF: each spans 8 rows */
.qf-0 {
  grid-row: 2 / span 8;
}
.qf-1 {
  grid-row: 10 / span 8;
}
.qf-2 {
  grid-row: 18 / span 8;
}
.qf-3 {
  grid-row: 26 / span 8;
}
 
/* SF: each spans 16 rows */
.sf-0 {
  grid-row: 2 / span 16;
}
.sf-1 {
  grid-row: 18 / span 16;
}
 
/* Final spans all 32 */
.final-0 {
  grid-row: 2 / span 32;
}
 
/* Connector lines.
 * For each cell, draw a short horizontal line going right toward the
 * next round, and a vertical line joining sibling pairs.
 *
 * Layout reference:
 *   cell ─┐
 *         │ vertical
 *   cell ─┘
 *         ── horizontal (drawn from the next column's left edge)
 */
.bracket-cell::after {
  /* Short horizontal line going right from this cell's right edge.
   * This is the "lead-out" line common to every cell except Final. */
  content: '';
  position: absolute;
  right: 0;
  top: 50%;
  width: 12px;
  height: 1px;
  background: rgb(var(--color-line));
}
.col-5.bracket-cell::after {
  display: none;
}
 
/*
 * Vertical "bridge" that joins two sibling cells: drawn on the top
 * cell of each pair, extending downward to the bottom cell's midpoint.
 *   For R32→R16: pair = (2k, 2k+1). Top cells: r32-0,2,4,...,14.
 *   For R16→QF: top cells: r16-0,2,4,6.
 *   For QF→SF: top cells: qf-0, qf-2.
 *   For SF→Final: top cell: sf-0.
 * Height of the bridge = vertical distance between paired-cell midpoints
 * = (rows-per-cell) × row-height. Since each pair sits in 2 × span rows,
 * the bridge spans exactly `span` rows downward (= 100% of cell height).
 */
.r32-0::before,
.r32-2::before,
.r32-4::before,
.r32-6::before,
.r32-8::before,
.r32-10::before,
.r32-12::before,
.r32-14::before,
.r16-0::before,
.r16-2::before,
.r16-4::before,
.r16-6::before,
.qf-0::before,
.qf-2::before,
.sf-0::before {
  content: '';
  position: absolute;
  right: 0;
  top: 50%;
  width: 1px;
  height: 100%;
  background: rgb(var(--color-line));
}
 
/* Mobile: keep the bracket usable; rely on the outer overflow-x scroll. */
@media (max-width: 768px) {
  .bracket-grid {
    grid-template-rows: auto repeat(32, minmax(34px, auto));
  }
}
 
/* ── Compact bracket (smaller than 32 teams) ──
 * Same visual language as the full grid, but column/row geometry is driven by
 * inline styles computed in `compactLayout` so it self-scales to the rounds
 * that are actually populated. */
.bracket-grid-compact {
  display: grid;
  gap: 0;
  position: relative;
  min-width: min-content;
}
.bracket-cell-compact {
  position: relative;
  padding: 4px 12px 4px 4px;
  display: flex;
  align-items: center;
}
.bracket-cell-compact:not(:first-child) {
  padding-left: 12px;
}
.bracket-cell-inner {
  width: 100%;
}
/* Horizontal lead-out toward the next round (every cell except the final). */
.bracket-cell-compact:not(.is-last)::after {
  content: '';
  position: absolute;
  right: 0;
  top: 50%;
  width: 12px;
  height: 1px;
  background: rgb(var(--color-line));
}
/* Vertical bridge joining a sibling pair: 100% of the (top) cell's height
 * reaches from this cell's midpoint down to its sibling's midpoint. */
.bracket-bridge {
  position: absolute;
  right: 0;
  top: 50%;
  width: 1px;
  height: 100%;
  background: rgb(var(--color-line));
}
</style>