import { Component, computed, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
  ActivatedRoute,
  Router,
  RouterLink,
  RouterLinkActive,
  RouterOutlet,
} from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { MatToolbarModule } from '@angular/material/toolbar';
import { AuthStore } from '../../auth/auth-store';
import { MyTeamsStore } from '../../team/my-teams-store';
import { TeamStore } from '../../team/team-store';
import { Team } from '../../../models/team.model';

@Component({
  selector: 'app-shell',
  imports: [
    RouterOutlet,
    RouterLink,
    RouterLinkActive,
    MatToolbarModule,
    MatIconModule,
    MatMenuModule,
    MatButtonModule,
  ],
  templateUrl: './shell.html',
  styleUrl: './shell.scss',
})
export class Shell {
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly authStore = inject(AuthStore);
  private readonly myTeamsStore = inject(MyTeamsStore);
  private readonly teamStore = inject(TeamStore);

  protected readonly currentTeam = this.teamStore.team;

  protected readonly myTeams = computed(() => {
    const seen = new Set<number>();
    const teams: Team[] = [];
    for (const player of this.myTeamsStore.players()) {
      if (player.team && !seen.has(player.team.id)) {
        seen.add(player.team.id);
        teams.push(player.team);
      }
    }
    return teams;
  });

  constructor() {
    const userId = this.authStore.currentUser()?.id;
    if (userId) {
      this.myTeamsStore.ensureLoaded(userId);
    }

    // A direct subscription (not `effect()` + `toSignal()`) so the initial
    // team load happens synchronously during construction, exactly like
    // `ensureLoaded` above — `ActivatedRoute.paramMap` always replays its
    // current value synchronously to a new subscriber. This keeps the
    // component's behavior deterministic and trivial to test: no signal
    // effect scheduling to wait for.
    this.route.paramMap.pipe(takeUntilDestroyed()).subscribe((params) => {
      const raw = params.get('id');
      const id = raw === null ? Number.NaN : Number(raw);
      if (Number.isInteger(id) && id > 0) {
        this.teamStore.loadTeam(id);
      }
    });
  }

  protected switchTeam(teamId: number): void {
    void this.router.navigate(['/team', teamId, 'overview']);
  }
}
