#include "GameLogic.h"
#include <iostream>

GameLogic::GameLogic() 
    : currentLevel(PlayerInput::chooseDifficulty()),
      wordManager(currentLevel),
      score(0) 
{
    attemptsLeft = (currentLevel == 1) ? 8 : (currentLevel == 2) ? 6 : 4;
}

void GameLogic::startGame() {
    bool playAgain = true;
    while (playAgain) {
        playRound();
        playAgain = PlayerInput::askContinue();
    }
    std::cout << "Игра окончена. Ваш итоговый счёт: " << score << "\n";
}

void GameLogic::resetRound() {
    wordManager = WordManager(currentLevel);
    usedLetters.clear();
    attemptsLeft = (currentLevel == 1) ? 8 : (currentLevel == 2) ? 6 : 4;
}

void GameLogic::playRound() {
    resetRound();
    while (true) {
        displayGameState();
        char letter = PlayerInput::getValidInput();
        if (usedLetters.find(letter) != usedLetters.end()) {
            std::cout << "Вы уже вводили эту букву. Попробуйте другую.\n";
            continue;
        }
        usedLetters.insert(letter);
        if (!wordManager.checkLetter(letter)) {
            attemptsLeft--;
            std::cout << "Неверная буква! Осталось попыток: " << attemptsLeft << "\n";
        }
        if (checkWin()) {
            calculateScore();
            std::cout << "Поздравляем! Вы угадали слово: " << wordManager.getDisplayedWord() << "\n";
            std::cout << "Вы заработали " << getScore() << " очков!\n";
            break;
        }
        if (checkGameOver()) {
            std::cout << "Вы проиграли. Загаданное слово было: " << wordManager.getDisplayedWord() << "\n";
            break;
        }
    }
}

void GameLogic::displayGameState() const {
    std::cout << "\nСлово: " << wordManager.getDisplayedWord() 
              << "\nПопыток осталось: " << attemptsLeft 
              << "\nИспользованные буквы: ";
    for (char c : usedLetters) std::cout << c << " ";
    std::cout << "\n";
}

bool GameLogic::checkWin() const {
    return wordManager.isWordGuessed();
}

bool GameLogic::checkGameOver() const {
    return attemptsLeft <= 0;
}

void GameLogic::calculateScore() {
    int basePoints = (currentLevel == 1) ? 100 : (currentLevel == 2) ? 200 : 300;
    score += basePoints + attemptsLeft * 10;
}

int GameLogic::getScore() const {
    return score;
}
