import {
  ChangeDetectionStrategy,
  Component,
  Input,
  OnChanges,
  SimpleChanges,
  inject,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { PlayingCardComponent } from '../playing-card/playing-card.component';
import { Card } from '@blackjack/models/blackjack.model';
import { GameControlsService } from '@blackjack/services/game-controls.service';

@Component({
  selector: 'app-player-hand',
  standalone: true,
  imports: [CommonModule, PlayingCardComponent],
  template: `
    <div class="space-y-4">
      <div class="flex justify-between items-center">
        <h3 class="section-heading text-2xl">Deine Karten</h3>
        <div class="flex items-center gap-2">
          <div class="text-text-secondary">Punkte:</div>
          <div class="text-xl font-bold text-emerald">
            {{ gameControlsService.calculateHandValue(cards) }}
          </div>
        </div>
      </div>
      <div class="card p-6 !bg-emerald">
        <div
          class="flex justify-center gap-4 min-h-[160px] p-4 border-2 border-emerald-400 rounded-lg"
        >
          @if (cards.length > 0) {
            @for (card of cardsWithState; track card.id) {
              <app-playing-card
                [rank]="card.rank"
                [suit]="card.suit"
                [hidden]="card.hidden"
                [isNew]="card.isNew"
              ></app-playing-card>
            }
          } @else {
            <div class="flex items-center justify-center text-white/70 text-lg font-medium">
              Platziere eine Wette um zu spielen...
            </div>
          }
        </div>
      </div>
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PlayerHandComponent implements OnChanges {
  @Input() cards: Card[] = [];
  cardsWithState: (Card & { isNew: boolean; id: string })[] = [];

  private lastCardCount = 0;

  protected gameControlsService = inject(GameControlsService);

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['cards']) {
      this.updateCardsWithState();
    }
  }

  private updateCardsWithState(): void {
    const newCards = this.cards.length > this.lastCardCount;

    this.cardsWithState = this.cards.map((card, index) => {
      const isNew = newCards && index >= this.lastCardCount;

      return {
        ...card,
        isNew,
        id: `${card.suit}-${card.rank}-${index}`,
      };
    });

    this.lastCardCount = this.cards.length;
  }
}
