/*
  ui/guesses.js
  fffadedev
  08/23/25

  Controls the interface that displays each attempt
 */

const GUESS_COUNT = 6;

class Guesses
{
  constructor() {
    // Fetch each document element for a guess
    this.elements = [];
    for(let i = 0; i < GUESS_COUNT; i++) {
      const el = document.getElementById('guess-' + i);
      this.elements.push(el);
    }

    this.reset();
  }

  // Resets the display so every attempt is blank
  reset() {
    for(let i = 0; i < GUESS_COUNT; i++) {
      const el = this.elements[i];
      const letters = el.querySelectorAll('.guess-letter');
      letters.forEach((letter, i) => {
        letter.innerHTML = '';
        letter.classList.remove('incorrect', 'correct', 'possible');
      });
    }
  }

  // Updates an attempt on the interface by comparing the attempt to the actual word
  updateGuess(guessIndex, guess, actualAsArray) {

    const el = this.elements[guessIndex];

    let lettersRemaining = actualAsArray.join('').split('');

    // Initial green check and html setup
    for(let x = 0; x < guess.length; x++) {

      const inputLetter = guess[x];

      const letter = el.querySelectorAll('.guess-letter')[x];
      letter.innerHTML = '<span>' + inputLetter + '</span>';

      // If possible, set style and remove from remaining letters
      if(actualAsArray[x] === inputLetter) {

        lettersRemaining.splice(lettersRemaining.indexOf(actualAsArray[x]), 1);

        letter.classList.add(LetterStateToStyleClass[LetterState.CORRECT]);
      }
    }

    // Second pass for yellows/grays
    for(let x = 0; x < guess.length; x++) {

      const inputLetter = guess[x];

      const letter = el.querySelectorAll('.guess-letter')[x];

      if(letter.classList.contains('correct'))
        continue;

      // Letter present in word
      if(lettersRemaining.includes(inputLetter)) {
        letter.classList.add(LetterStateToStyleClass[LetterState.POSSIBLE]);
        lettersRemaining.splice(lettersRemaining.indexOf(inputLetter), 1);
      }
      else {
        letter.classList.add(LetterStateToStyleClass[LetterState.INCORRECT]);
      }
    }
  }
}
