#pragma once

#include <functional>
#include <unordered_map>
#include <vector>
#include <string>
#include <SDL3/SDL.h>

// Forward declarations
class RenderManager;

// Application states used across the app
enum class AppState {
    Loading,
    Video,
    Menu,
    Options,
    LevelSelector,
    Playing,
    LevelSelect,
    GameOver
};

/**
 * Enhanced StateManager - Manages application state transitions and lifecycle
 * 
 * Improvements over original:
 * - Better error handling and validation
 * - Support for update and render cycles
 * - State transition validation
 * - Logging for debugging
 * - Cleaner API design
 */
class StateManager {
public:
    using EventHandler = std::function<void(const SDL_Event&)>;
    using UpdateHandler = std::function<void(float deltaTime)>;
    using RenderHandler = std::function<void(RenderManager& renderer)>;
    using Hook = std::function<void()>;

    StateManager(AppState initial);
    ~StateManager() = default;

    // State registration
    void registerEventHandler(AppState state, EventHandler handler);
    void registerUpdateHandler(AppState state, UpdateHandler handler);
    void registerRenderHandler(AppState state, RenderHandler handler);
    void registerOnEnter(AppState state, Hook hook);
    void registerOnExit(AppState state, Hook hook);

    // Legacy compatibility
    void registerHandler(AppState s, EventHandler h) { registerEventHandler(s, std::move(h)); }
    void registerHandler(AppState s, std::function<void()> h); // overload used in some places

    // State management
    bool setState(AppState newState);
    AppState getState() const { return m_currentState; }
    AppState getPreviousState() const { return m_previousState; }

    // State operations
    void handleEvent(const SDL_Event& event);
    void update(float deltaTime);
    void render(RenderManager& renderer);

    // Validation
    bool isValidState(AppState state) const;
    bool canTransitionTo(AppState newState) const;

    // Utility
    const char* getStateName(AppState state) const;

private:
    // State data
    AppState m_currentState;
    AppState m_previousState;
    
    // Handler storage
    std::unordered_map<int, std::vector<EventHandler>> m_eventHandlers;
    std::unordered_map<int, std::vector<UpdateHandler>> m_updateHandlers;
    std::unordered_map<int, std::vector<RenderHandler>> m_renderHandlers;
    std::unordered_map<int, std::vector<Hook>> m_onEnterHooks;
    std::unordered_map<int, std::vector<Hook>> m_onExitHooks;

    // Helper methods
    void executeEnterHooks(AppState state);
    void executeExitHooks(AppState state);
    int stateToInt(AppState state) const { return static_cast<int>(state); }
};
