/**
 * @file main.cpp
 * @brief Godot Render Pipeline Visualizer
 *
 * Interactive tool to visualize the 6 stages of the render pipeline:
 *   Object Space -> World Space -> View Space -> Clip Space -> NDC -> Screen Space
 *
 * Controls:
 *   Left/Right arrows: Navigate between pipeline stages
 *   1-6:               Jump to a specific stage
 *   WASD:              Move object (X/Z plane)
 *   Q/E:               Move object (Y axis)
 *   Mouse drag:        Orbit the display camera
 *   Scroll wheel:      Zoom in/out
 *   Space:             Toggle auto-rotation
 *   R:                 Reset all transforms
 *   P:                 Pause
 *   ESC:               Quit
 */

#define SDL_MAIN_HANDLED
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>

#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif

#include "game.hpp"
#include "pipeline.hpp"

#include <cstdio>
#include <cstdlib>

// Global context for emscripten callback
static GameContext* g_ctx = nullptr;

#ifdef __EMSCRIPTEN__
static void em_main_loop() {
    if (!game_loop(*g_ctx)) {
        emscripten_cancel_main_loop();
    }
}
#endif

int main(int argc, char *argv[]) {
    (void)argc;
    (void)argv;

    SDL_SetMainReady();

    static GameContext ctx;
    static PipelineState pipeline;
    ctx.pipeline = &pipeline;
    g_ctx = &ctx;

    WindowConfig config{
        .title = "Render Pipeline Visualizer",
        .width = 1280,
        .height = 720,
        .flags = SDL_WINDOW_RESIZABLE
    };

    if (!game_init(ctx, config)) {
        std::fprintf(stderr, "Failed to initialize\n");
        return EXIT_FAILURE;
    }

    std::printf("Render Pipeline Visualizer running.\n");
    std::printf("Use Left/Right arrows to navigate stages, WASD/QE to move object.\n");

#ifdef __EMSCRIPTEN__
    emscripten_set_main_loop(em_main_loop, 0, 1);
#else
    while (game_loop(ctx)) {
        // Game loop handles everything
    }
#endif

    game_shutdown(ctx);
    return EXIT_SUCCESS;
}
