import { Component, EventEmitter, Input, Output } from '@angular/core';

type BoardTheme = 'arabian' | 'classic';

@Component({
  selector: 'app-chess-piece',
  standalone: true,
  templateUrl: './chess-piece.component.html',
  styleUrl: './chess-piece.component.css'
})
export class ChessPieceComponent {
  @Input({ required: true }) pieceCode: string | null = null;
  @Input() boardTheme: BoardTheme = 'arabian';
  @Input() draggable = false;
  @Output() pieceDragStart = new EventEmitter<DragEvent>();
  @Output() pieceDragEnd = new EventEmitter<void>();

  onDragStart(event: DragEvent): void {
    if (!this.draggable) {
      event.preventDefault();
      return;
    }

    this.pieceDragStart.emit(event);
  }

  onDragEnd(): void {
    this.pieceDragEnd.emit();
  }

  get spriteUrl(): string {
    if (!this.pieceCode) {
      return '';
    }

    const isWhite = this.pieceCode === this.pieceCode.toUpperCase();
    const pieceCode = this.pieceCode.toLowerCase();

    if (this.boardTheme === 'classic') {
      const colorPrefix = isWhite ? 'w' : 'b';
      const classicPieceName = this.getClassicPieceName(pieceCode);
      return `/assets/ChessAssets/${colorPrefix}_${classicPieceName}.png`;
    }

    const arabianColor = isWhite ? 'white' : 'black';
    const arabianPieceName = this.getArabianPieceName(pieceCode);
    return `/assets/arabian-chess/sprites/pieces/${arabianColor}_${arabianPieceName}.png`;
  }

  private getArabianPieceName(piece: string): string {
    switch (piece) {
      case 'k':
        return 'king';
      case 'q':
        return 'queen';
      case 'r':
        return 'rook';
      case 'b':
        return 'bishop';
      case 'n':
        return 'knight';
      case 'p':
        return 'pawn';
      default:
        return 'pawn';
    }
  }

  private getClassicPieceName(piece: string): string {
    switch (piece) {
      case 'k':
        return 'King';
      case 'q':
        return 'Queen';
      case 'r':
        return 'Rook';
      case 'b':
        return 'Bishop';
      case 'n':
        return 'Knight';
      case 'p':
        return 'Pawn';
      default:
        return 'Pawn';
    }
  }
}
