#include <iostream>
#include <nlohmann/json.hpp>
#include <chrono>
#include <thread>
#include "ClientUIModule.cpp"

using json = nlohmann::json;
using namespace warfactory;

int main() {
    std::cout << "🎮 ClientUI Module Standalone Test" << std::endl;
    std::cout << "==================================" << std::endl;

    ClientUIModule clientUI;

    // Initialize module
    clientUI.initialize({}, nullptr, nullptr);

    std::cout << "\n🧪 Test 1: UI Event Simulation" << std::endl;

    // Simulate UI button clicks
    json button_event = {
        {"type", "ui_event"},
        {"action", "button_click"},
        {"button", "get_economy_prices"}
    };
    clientUI.process(button_event);

    std::this_thread::sleep_for(std::chrono::milliseconds(100));

    json button_event2 = {
        {"type", "ui_event"},
        {"action", "button_click"},
        {"button", "get_companies"}
    };
    clientUI.process(button_event2);

    std::cout << "\n🧪 Test 2: Server Response Simulation" << std::endl;

    // Simulate server responses
    json server_response1 = {
        {"type", "server_response"},
        {"source", "economy"},
        {"data", {
            {"steel_plate", 5.2},
            {"iron_ore", 1.1},
            {"copper_wire", 2.0}
        }}
    };
    clientUI.process(server_response1);

    json server_response2 = {
        {"type", "server_response"},
        {"source", "macroentity"},
        {"data", {
            {"steel_corp", {{"cash", 2500000}, {"strategy", "aggressive"}}},
            {"iron_works", {{"cash", 1800000}, {"strategy", "conservative"}}}
        }}
    };
    clientUI.process(server_response2);

    std::cout << "\n🧪 Test 3: UI Rendering Simulation" << std::endl;

    // Simulate several frames of UI rendering
    for (int i = 0; i < 5; i++) {
        clientUI.process({});
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }

    std::cout << "\n🧪 Test 4: State Management" << std::endl;

    auto state = clientUI.getState();
    std::cout << "Current State: " << state.dump(2) << std::endl;

    // Test state restoration (hot-reload simulation)
    clientUI.setState(state);

    std::cout << "\n🧪 Test 5: Window State Management" << std::endl;

    json window_event = {
        {"type", "ui_event"},
        {"action", "button_click"},
        {"button", "show_economy_window"}
    };
    clientUI.process(window_event);

    json window_event2 = {
        {"type", "ui_event"},
        {"action", "button_click"},
        {"button", "show_macroentity_window"}
    };
    clientUI.process(window_event2);

    // Render a few more frames to show windows
    for (int i = 0; i < 3; i++) {
        clientUI.process({});
        std::this_thread::sleep_for(std::chrono::milliseconds(60));
    }

    clientUI.shutdown();

    std::cout << "\n🎉 ClientUI module test completed!" << std::endl;
    return 0;
}