class BlackjackGame {
    constructor() {
      this.deck = this.shuffleDeck(this.generateDeck());
      this.playerHand = [];
      this.dealerHand = [];
      this.hasStarted = false;
    }
  
    generateDeck() {
      // Generate a deck of cards
        const deck = [];
        const suits = ['♠', '♣', '♥', '♦'];
        const ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9','10', 'J', 'Q', 'K'];
        for (let suit of suits) {
            for (let rank of ranks) {
                deck.push(rank + suit);
            }
        }
        return deck;
    }
  
    shuffleDeck(deck) {
        // Shuffle the deck
        for (let i = deck.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [deck[i], deck[j]] = [deck[j], deck[i]];
        }
        return deck;
      
    }
  
    dealInitialHands() {
      this.deck = this.shuffleDeck(this.generateDeck());
      this.playerHand = [this.deck.pop(), this.deck.pop()];
      this.dealerHand = [this.deck.pop(), this.deck.pop()];
      this.hasStarted = true;
    }
  
    playerHit() {
      const card = this.deck.pop();
      this.playerHand.push(card);
    }
  
    playerStand() {
        this.dealerPlay();
    }
  
    dealerPlay() {
      while (this.getHandValue(this.dealerHand) < 17 && this.getHandValue(this.dealerHand) <= this.getHandValue(this.playerHand)) {
        this.dealerHand.push(this.deck.pop());
      }
    }
  
    determineWinner() {
      const playerValue = this.getHandValue(this.playerHand);
      const dealerValue = this.getHandValue(this.dealerHand);
      this.hasStarted = false;
      if (playerValue > 21 || (dealerValue <= 21 && dealerValue > playerValue)) {
        return 'Dealer';
      } else if (playerValue === 21 || (dealerValue > 21) || (playerValue < 21 && playerValue > dealerValue)) {
        return 'Player';
      } else {
        return 'Push';
      }
    }
  
    getHandValue(hand) {
      // Calculate hand value
        let value = 0;
        let aces = 0;
        for (let card of hand) {
            const rank = card.slice(0, -1);
            if (rank === 'A') {
                aces++;
                value += 11;
            } else if (['J', 'Q', 'K'].includes(rank)) {
                value += 10;
            } else {
                value += Number(rank);
            }
        }
        while (value > 21 && aces > 0) {
            value -= 10;
            aces--;
        }
        return value;
    }
  }
  
  module.exports = BlackjackGame;
  