All files / src/components LeagueTable.vue

0% Statements 0/604
0% Branches 0/1
0% Functions 0/1
0% Lines 0/604

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
<template>
  <div>
    <!-- Filters Section -->
    <div class="mb-6 space-y-4">
      <!-- Age Group Links -->
      <div data-testid="age-group-filter">
        <h3 class="text-sm font-medium text-gray-700 mb-3">Age Groups</h3>
        <div class="flex flex-wrap gap-2">
          <button
            v-for="ageGroup in ageGroups"
            :key="ageGroup.id"
            @click="selectedAgeGroupId = ageGroup.id"
            :class="[
              'px-4 py-2 text-sm rounded-lg font-medium transition-colors',
              selectedAgeGroupId === ageGroup.id
                ? 'bg-brand-500 text-white shadow-sm'
                : 'bg-slate-100 text-slate-600 hover:bg-slate-200',
            ]"
            :data-testid="`age-group-${ageGroup.name}`"
          >
            {{ ageGroup.name }}
          </button>
        </div>
      </div>
 
      <!-- League Selector -->
      <div>
        <h3 class="text-sm font-medium text-gray-700 mb-3">League</h3>
        <div class="flex flex-wrap gap-2">
          <button
            v-for="league in leagues"
            :key="league.id"
            @click="selectedLeagueId = league.id"
            :class="[
              'px-4 py-2 text-sm rounded-lg font-medium transition-colors',
              selectedLeagueId === league.id
                ? 'bg-brand-500 text-white shadow-sm'
                : 'bg-slate-100 text-slate-600 hover:bg-slate-200',
            ]"
          >
            {{ league.name }}
          </button>
        </div>
      </div>
 
      <!-- Season and Division Row -->
      <div
        class="flex flex-col sm:flex-row sm:space-x-6 space-y-4 sm:space-y-0"
      >
        <!-- Season Dropdown -->
        <div class="flex-1">
          <h3 class="text-sm font-medium text-gray-700 mb-3">Season</h3>
          <select
            v-model="selectedSeasonId"
            class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-brand-500 focus:border-brand-500 sm:text-sm"
            data-testid="season-filter"
          >
            <option
              v-for="season in seasons"
              :key="season.id"
              :value="season.id"
            >
              {{ season.name }} ({{ formatSeasonDates(season) }})
            </option>
          </select>
        </div>
 
        <!-- Division Dropdown -->
        <div class="flex-1">
          <h3 class="text-sm font-medium text-gray-700 mb-3">Division</h3>
          <select
            v-model="selectedDivisionId"
            class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-brand-500 focus:border-brand-500 sm:text-sm"
            data-testid="division-filter"
          >
            <option
              v-for="division in divisions"
              :key="division.id"
              :value="division.id"
            >
              {{ division.name }}
            </option>
          </select>
        </div>
      </div>
    </div>
 
    <!-- Playoff bracket toggle -->
    <div v-if="bracketExists" class="mb-4 flex justify-end">
      <button
        @click="showBracket = !showBracket"
        class="px-4 py-2 text-sm font-medium rounded-md transition-colors"
        :class="
          showBracket
            ? 'bg-gray-200 text-gray-700 hover:bg-gray-300'
            : 'bg-yellow-500 text-white hover:bg-yellow-600'
        "
      >
        {{ showBracket ? 'Show Standings' : 'Show Playoff Bracket' }}
      </button>
    </div>
 
    <!-- Playoff Bracket View -->
    <PlayoffBracket
      v-if="
        showBracket &&
        selectedLeagueId &&
        selectedSeasonId &&
        selectedAgeGroupId
      "
      :leagueId="selectedLeagueId"
      :seasonId="selectedSeasonId"
      :ageGroupId="selectedAgeGroupId"
    />
 
    <div v-if="!showBracket" class="overflow-x-auto">
      <!-- Loading State -->
      <div
        v-if="loading"
        class="text-center py-4"
        data-testid="loading-indicator"
      >
        Loading table data...
      </div>
 
      <!-- Error State -->
      <div
        v-else-if="error"
        class="text-center py-4 text-red-600"
        data-testid="error-message"
      >
        Error: {{ error }}
      </div>
 
      <!-- Table -->
      <table
        v-else
        class="min-w-full divide-y divide-slate-200"
        data-testid="standings-table"
      >
        <thead class="bg-brand-500">
          <tr>
            <th
              class="px-1 sm:px-2 md:px-6 py-3 text-left text-xs font-semibold text-slate-300 uppercase tracking-wider"
              title="Rank"
            >
              #
            </th>
            <th
              class="hidden md:table-cell px-1 sm:px-2 md:px-3 py-3 text-center text-xs font-semibold text-slate-300 uppercase tracking-wider"
              title="Position change since last week"
            >
              +/-
            </th>
            <th
              class="px-2 sm:px-4 md:px-6 py-3 text-left text-xs font-semibold text-slate-300 uppercase tracking-wider max-w-[100px] sm:max-w-[140px] md:max-w-none"
            >
              Team
            </th>
            <th
              class="px-2 sm:px-4 md:px-6 py-3 text-center text-xs font-semibold text-slate-300 uppercase tracking-wider"
              title="Games Played"
            >
              GP
            </th>
            <th
              class="px-2 sm:px-4 md:px-6 py-3 text-center text-xs font-semibold text-slate-300 uppercase tracking-wider"
              title="Wins"
            >
              W
            </th>
            <th
              class="px-2 sm:px-4 md:px-6 py-3 text-center text-xs font-semibold text-slate-300 uppercase tracking-wider"
              title="Draws"
            >
              D
            </th>
            <th
              class="px-2 sm:px-4 md:px-6 py-3 text-center text-xs font-semibold text-slate-300 uppercase tracking-wider"
              title="Losses"
            >
              L
            </th>
            <th
              class="hidden md:table-cell px-2 sm:px-4 md:px-6 py-3 text-center text-xs font-semibold text-slate-300 uppercase tracking-wider"
              title="Goals For"
            >
              GF
            </th>
            <th
              class="hidden md:table-cell px-2 sm:px-4 md:px-6 py-3 text-center text-xs font-semibold text-slate-300 uppercase tracking-wider"
              title="Goals Against"
            >
              GA
            </th>
            <th
              class="hidden md:table-cell px-2 sm:px-4 md:px-6 py-3 text-center text-xs font-semibold text-slate-300 uppercase tracking-wider"
              title="Goal Difference"
            >
              GD
            </th>
            <th
              class="px-2 sm:px-4 md:px-6 py-3 text-center text-xs font-semibold text-brand-200 uppercase tracking-wider"
              title="Points"
            >
              Pts
            </th>
            <th
              class="hidden md:table-cell px-2 sm:px-4 md:px-6 py-3 text-center text-xs font-semibold text-slate-300 uppercase tracking-wider"
              title="Last 5 results"
            >
              Form
            </th>
          </tr>
        </thead>
        <tbody
          class="bg-white divide-y divide-slate-100"
          data-testid="standings-body"
        >
          <tr
            v-for="(team, index) in tableData"
            :key="team.team"
            class="hover:bg-slate-50 transition-colors"
            data-testid="standings-row"
          >
            <td
              class="px-1 sm:px-2 md:px-6 py-3 md:py-4 whitespace-nowrap text-sm text-gray-500"
            >
              {{ index + 1 }}
            </td>
            <td
              class="hidden md:table-cell px-1 sm:px-2 md:px-3 py-3 md:py-4 whitespace-nowrap text-xs text-center"
            >
              <span
                v-if="team.position_change > 0"
                class="text-green-600 font-medium"
                :title="`Up ${team.position_change}`"
              >
                ▲ {{ team.position_change }}
              </span>
              <span
                v-else-if="team.position_change < 0"
                class="text-red-600 font-medium"
                :title="`Down ${Math.abs(team.position_change)}`"
              >
                ▼ {{ Math.abs(team.position_change) }}
              </span>
              <span v-else class="text-gray-400">—</span>
            </td>
            <td
              class="px-2 sm:px-4 md:px-6 py-3 md:py-4 text-xs sm:text-sm font-medium text-gray-900 max-w-[100px] sm:max-w-[140px] md:max-w-none md:whitespace-nowrap"
            >
              <div class="flex items-center gap-1.5">
                <ClubLogo
                  :logo-url="team.logo_url"
                  :name="team.team"
                  size="xs"
                />
                <span>{{ getTeamDisplayName(team.team) }}</span>
              </div>
            </td>
            <td
              class="px-2 sm:px-4 md:px-6 py-3 md:py-4 whitespace-nowrap text-sm text-center text-gray-500"
            >
              {{ team.played }}
            </td>
            <td
              class="px-2 sm:px-4 md:px-6 py-3 md:py-4 whitespace-nowrap text-sm text-center text-gray-500"
            >
              {{ team.wins }}
            </td>
            <td
              class="px-2 sm:px-4 md:px-6 py-3 md:py-4 whitespace-nowrap text-sm text-center text-gray-500"
            >
              {{ team.draws }}
            </td>
            <td
              class="px-2 sm:px-4 md:px-6 py-3 md:py-4 whitespace-nowrap text-sm text-center text-gray-500"
            >
              {{ team.losses }}
            </td>
            <td
              class="hidden md:table-cell px-2 sm:px-4 md:px-6 py-3 md:py-4 whitespace-nowrap text-sm text-center text-gray-500"
            >
              {{ team.goals_for }}
            </td>
            <td
              class="hidden md:table-cell px-2 sm:px-4 md:px-6 py-3 md:py-4 whitespace-nowrap text-sm text-center text-gray-500"
            >
              {{ team.goals_against }}
            </td>
            <td
              class="hidden md:table-cell px-2 sm:px-4 md:px-6 py-3 md:py-4 whitespace-nowrap text-sm text-center text-gray-500"
            >
              {{ team.goal_difference }}
            </td>
            <td
              class="px-2 sm:px-4 md:px-6 py-3 md:py-4 whitespace-nowrap text-sm text-center font-bold text-brand-600"
            >
              {{ team.points }}
            </td>
            <td
              class="hidden md:table-cell px-2 sm:px-4 md:px-6 py-3 md:py-4 whitespace-nowrap text-center"
            >
              <div class="flex items-center justify-center gap-1">
                <span
                  v-for="(result, rIdx) in team.form || []"
                  :key="rIdx"
                  class="inline-block w-5 h-5 rounded-full text-[10px] font-bold leading-5 text-white text-center"
                  :class="{
                    'bg-green-500': result === 'W',
                    'bg-red-500': result === 'L',
                    'bg-gray-400': result === 'D',
                  }"
                  :title="
                    result === 'W' ? 'Win' : result === 'L' ? 'Loss' : 'Draw'
                  "
                >
                  {{ result }}
                </span>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
 
<script>
import { ref, onMounted, watch, computed } from 'vue';
import { useAuthStore } from '../stores/auth';
import { getApiBaseUrl } from '../config/api';
import PlayoffBracket from './PlayoffBracket.vue';
import ClubLogo from './shared/ClubLogo.vue';
 
export default {
  name: 'LeagueTable',
  components: { PlayoffBracket, ClubLogo },
  props: {
    initialAgeGroupId: {
      type: Number,
      default: null,
    },
    initialLeagueId: {
      type: Number,
      default: null,
    },
    initialDivisionId: {
      type: Number,
      default: null,
    },
    filterKey: {
      type: Number,
      default: 0,
    },
  },
  setup(props) {
    const authStore = useAuthStore();
    const tableData = ref([]);
    const teams = ref([]); // Store all teams for name→id mapping
    const ageGroups = ref([]);
    const leagues = ref([]);
    const divisions = ref([]);
    const allDivisions = ref([]); // Store all divisions for filtering
    const seasons = ref([]);
    const selectedAgeGroupId = ref(2); // Default to U14
    const selectedLeagueId = ref(null); // Default to first league
    const selectedDivisionId = ref(1); // Default to Northeast
    const selectedSeasonId = ref(2); // Default to 2024-2025
    const error = ref(null);
    const loading = ref(true);
 
    // Playoff bracket state
    const bracketExists = ref(false);
    const showBracket = ref(false);
 
    // Computed property for selected league name
    const selectedLeagueName = computed(() => {
      const league = leagues.value.find(l => l.id === selectedLeagueId.value);
      return league ? league.name : '';
    });
 
    const fetchAgeGroups = async () => {
      try {
        const data = await authStore.apiRequest(
          `${getApiBaseUrl()}/api/age-groups`
        );
        ageGroups.value = data.sort((a, b) => a.name.localeCompare(b.name));
 
        // Set U14 as default if available
        const u14 = data.find(ag => ag.name === 'U14');
        if (u14) {
          selectedAgeGroupId.value = u14.id;
        }
      } catch (err) {
        console.error('Error fetching age groups:', err);
      }
    };
 
    const fetchTeams = async () => {
      try {
        const data = await authStore.apiRequest(`${getApiBaseUrl()}/api/teams`);
        teams.value = data;
      } catch (err) {
        console.error('Error fetching teams:', err);
      }
    };
 
    const fetchLeagues = async () => {
      try {
        const data = await authStore.apiRequest(
          `${getApiBaseUrl()}/api/leagues`
        );
        leagues.value = data.sort((a, b) => a.name.localeCompare(b.name));
 
        // Set Homegrown as default if available
        const homegrown = data.find(l => l.name === 'Homegrown');
        if (homegrown) {
          selectedLeagueId.value = homegrown.id;
        } else if (data.length > 0) {
          selectedLeagueId.value = data[0].id;
        }
      } catch (err) {
        console.error('Error fetching leagues:', err);
      }
    };
 
    // Filter leagues to only those where the user's club has teams
    const filterLeaguesByClub = () => {
      const clubId = authStore.userClubId.value;
      if (authStore.isAdmin.value || !clubId) return;
 
      const clubLeagueIds = new Set(
        teams.value
          .filter(t => t.club_id === clubId && t.league_id)
          .map(t => t.league_id)
      );
 
      if (clubLeagueIds.size > 0) {
        leagues.value = leagues.value.filter(l => clubLeagueIds.has(l.id));
        // Re-select default if current selection was filtered out
        if (!leagues.value.find(l => l.id === selectedLeagueId.value)) {
          const homegrown = leagues.value.find(l => l.name === 'Homegrown');
          selectedLeagueId.value = homegrown
            ? homegrown.id
            : leagues.value[0]?.id || null;
        }
      }
    };
 
    const filterDivisionsByLeague = () => {
      console.log('Filtering divisions by league:', {
        selectedLeagueId: selectedLeagueId.value,
        allDivisionsCount: allDivisions.value.length,
      });
 
      if (selectedLeagueId.value) {
        divisions.value = allDivisions.value.filter(
          d => Number(d.league_id) === Number(selectedLeagueId.value)
        );
 
        console.log('Filtered divisions:', {
          filteredCount: divisions.value.length,
          divisions: divisions.value.map(d => ({
            id: d.id,
            name: d.name,
            league_id: d.league_id,
          })),
        });
 
        // Reset division selection if current division is not in filtered list
        if (!divisions.value.find(d => d.id === selectedDivisionId.value)) {
          if (divisions.value.length > 0) {
            selectedDivisionId.value = divisions.value[0].id;
            console.log('Auto-selected division:', selectedDivisionId.value);
          }
        }
      } else {
        divisions.value = allDivisions.value;
      }
    };
 
    const fetchDivisions = async () => {
      try {
        const data = await authStore.apiRequest(
          `${getApiBaseUrl()}/api/divisions`
        );
        allDivisions.value = data.sort((a, b) => a.name.localeCompare(b.name));
 
        // Filter divisions by selected league
        filterDivisionsByLeague();
 
        // Set Northeast as default if available in filtered divisions
        const northeast = divisions.value.find(d => d.name === 'Northeast');
        if (northeast) {
          selectedDivisionId.value = northeast.id;
        } else if (divisions.value.length > 0) {
          selectedDivisionId.value = divisions.value[0].id;
        }
      } catch (err) {
        console.error('Error fetching divisions:', err);
      }
    };
 
    const fetchSeasons = async () => {
      try {
        const data = await authStore.apiRequest(
          `${getApiBaseUrl()}/api/seasons`
        );
        // Sort seasons by start date (most recent first)
        seasons.value = data.sort(
          (a, b) => new Date(b.start_date) - new Date(a.start_date)
        );
 
        // Set 2025-2026 as default if available
        const currentSeason = data.find(s => s.name === '2025-2026');
        if (currentSeason) {
          selectedSeasonId.value = currentSeason.id;
        }
      } catch (err) {
        console.error('Error fetching seasons:', err);
      }
    };
 
    const formatSeasonDates = season => {
      const startYear = new Date(season.start_date).getFullYear();
      const endYear = new Date(season.end_date).getFullYear();
      return `${startYear}-${endYear}`;
    };
 
    // Get team display name - now just returns the team name directly
    // Teams are scoped by league in the new clubs architecture
    const getTeamDisplayName = teamName => {
      return teamName;
    };
 
    const fetchTableData = async () => {
      loading.value = true;
      console.log('Fetching table data...', {
        seasonId: selectedSeasonId.value,
        ageGroupId: selectedAgeGroupId.value,
        divisionId: selectedDivisionId.value,
      });
      try {
        const url = `${getApiBaseUrl()}/api/table?season_id=${selectedSeasonId.value}&age_group_id=${selectedAgeGroupId.value}&division_id=${selectedDivisionId.value}`;
 
        const data = await authStore.apiRequest(url);
        console.log('Table data received:', data);
 
        tableData.value = data;
        console.log('Table data set:', tableData.value);
      } catch (err) {
        console.error('Error fetching table data:', err);
        error.value = err.message;
      } finally {
        loading.value = false;
      }
    };
 
    const checkBracketExists = async () => {
      bracketExists.value = false;
      showBracket.value = false;
      if (
        !selectedLeagueId.value ||
        !selectedSeasonId.value ||
        !selectedAgeGroupId.value
      )
        return;
      try {
        const params = new URLSearchParams({
          league_id: selectedLeagueId.value,
          season_id: selectedSeasonId.value,
          age_group_id: selectedAgeGroupId.value,
        });
        const data = await authStore.apiRequest(
          `${getApiBaseUrl()}/api/playoffs/bracket?${params}`,
          { method: 'GET' }
        );
        bracketExists.value = Array.isArray(data) && data.length > 0;
      } catch {
        // Bracket check is non-critical — ignore errors
      }
    };
 
    // Watch for league changes to filter divisions and check bracket
    watch(selectedLeagueId, () => {
      filterDivisionsByLeague();
      checkBracketExists();
    });
 
    // Watch for changes in filters and refetch data
    watch([selectedSeasonId, selectedAgeGroupId, selectedDivisionId], () => {
      fetchTableData();
    });
 
    // Re-check bracket when season or age group changes
    watch([selectedSeasonId, selectedAgeGroupId], () => {
      checkBracketExists();
    });
 
    // Watch for filterKey changes to apply external filters (from team card clicks)
    watch(
      () => props.filterKey,
      async newKey => {
        if (newKey > 0 && props.initialLeagueId) {
          console.log('Applying external filters:', {
            ageGroupId: props.initialAgeGroupId,
            leagueId: props.initialLeagueId,
            divisionId: props.initialDivisionId,
          });
 
          // Apply age group filter
          if (props.initialAgeGroupId) {
            selectedAgeGroupId.value = props.initialAgeGroupId;
          }
 
          // Apply league filter and re-filter divisions
          if (props.initialLeagueId) {
            selectedLeagueId.value = props.initialLeagueId;
            filterDivisionsByLeague();
          }
 
          // Apply division filter
          if (props.initialDivisionId) {
            selectedDivisionId.value = props.initialDivisionId;
          }
 
          // Fetch updated table data
          await fetchTableData();
        }
      }
    );
 
    onMounted(async () => {
      console.log('LeagueTable component mounted');
      console.log('Initial props:', {
        initialAgeGroupId: props.initialAgeGroupId,
        initialLeagueId: props.initialLeagueId,
        initialDivisionId: props.initialDivisionId,
        filterKey: props.filterKey,
      });
 
      await Promise.all([
        fetchAgeGroups(),
        fetchLeagues(),
        fetchSeasons(),
        fetchTeams(),
      ]);
 
      // Filter leagues to user's club before selecting defaults
      filterLeaguesByClub();
 
      // Fetch divisions after leagues are loaded so we can filter by default league
      await fetchDivisions();
 
      // Apply initial filters from props if provided (e.g., from team card click)
      if (props.filterKey > 0 && props.initialLeagueId) {
        console.log('Applying initial filters from props');
        if (props.initialAgeGroupId) {
          selectedAgeGroupId.value = props.initialAgeGroupId;
        }
        if (props.initialLeagueId) {
          selectedLeagueId.value = props.initialLeagueId;
          filterDivisionsByLeague();
        }
        if (props.initialDivisionId) {
          selectedDivisionId.value = props.initialDivisionId;
        }
      } else if (!authStore.isAdmin.value && authStore.userTeamId.value) {
        // For non-admins without explicit filters, auto-select based on their team
        try {
          // Fetch the user's team to get its league and division
          const teams = await authStore.apiRequest(
            `${getApiBaseUrl()}/api/teams`
          );
          const userTeam = teams.find(t => t.id === authStore.userTeamId.value);
 
          if (userTeam) {
            // Get division for selected age group
            // Ensure type-safe lookup: divisions_by_age_group uses string keys
            const division =
              userTeam.divisions_by_age_group[String(selectedAgeGroupId.value)];
            if (division) {
              selectedLeagueId.value = division.league_id;
              selectedDivisionId.value = division.id;
 
              // Re-filter divisions by league
              filterDivisionsByLeague();
            }
          }
        } catch (err) {
          console.error('Error fetching user team info:', err);
        }
      }
 
      fetchTableData();
      checkBracketExists();
    });
 
    return {
      tableData,
      ageGroups,
      leagues,
      divisions,
      seasons,
      selectedAgeGroupId,
      selectedLeagueId,
      selectedLeagueName,
      selectedDivisionId,
      selectedSeasonId,
      formatSeasonDates,
      getTeamDisplayName,
      error,
      loading,
      bracketExists,
      showBracket,
      authStore,
    };
  },
};
</script>