#include "states/GameState.h"
#include "states/MainMenuState.h"
#include "states/InGameState.h"
#include "Renderer.h"
#include <SDL2/SDL.h>
#include <memory>
#include <unordered_map>

int main() {
    TTF_Init();

    SDL_Window* window = SDL_CreateWindow("Obstacle Game",
                                          SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                          WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    std::unordered_map<std::string, std::shared_ptr<GameState>> states;
    states["main_menu"] = std::make_shared<MainMenuState>();
    states["game"] = std::make_shared<InGameState>();

    std::shared_ptr<GameState> currentState = states["main_menu"];

    currentState->init();

    bool running = true;
    while (running) {
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                running = false;
            }
            currentState->handleEvents(event);
        }

        currentState->update();
        currentState->render(renderer);

        if (!currentState->getNextState().empty()) {
            std::string nextStateName = currentState->getNextState();
            if (nextStateName == "exit") {
                running = false;
            } else if (states.find(nextStateName) != states.end()) {
                currentState = states[nextStateName];
                currentState->init();
            }
            currentState->clearNextState();
        }

        SDL_Delay(16);
    }

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    TTF_Quit();

    return 0;
}
