#include "core/jail/jgame.hpp"

namespace {

    bool is_quitting = false;
    Uint32 update_ticks = 0;
    Uint32 update_time = 0;
    Uint32 cycle_counter = 0;
    Uint32 last_delta_time = 0;

}  // namespace

void Jg::init() {
    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);
    update_time = SDL_GetTicks();
    last_delta_time = update_time;
}

void Jg::finalize() {
    SDL_Quit();
}

void Jg::quitSignal() {
    is_quitting = true;
}

auto Jg::quitting() -> bool {
    return is_quitting;
}

void Jg::setUpdateTicks(Uint32 milliseconds) {
    update_ticks = milliseconds;
}

auto Jg::shouldUpdate() -> bool {
    const Uint32 NOW = SDL_GetTicks();
    if (NOW - update_time > update_ticks) {
        update_time = NOW;
        cycle_counter++;
        return true;
    }
    // No toca update — retornem false sense més. Des de Phase B.2 ja no
    // hi ha fibers: cap caller fa spin-waits (`while (!Jg::shouldUpdate())`)
    // i el Director pren el control del main loop frame a frame.
    return false;
}

auto Jg::getCycleCounter() -> Uint32 {
    return cycle_counter;
}

auto Jg::getDeltaMs() -> Uint32 {
    const Uint32 NOW = SDL_GetTicks();
    const Uint32 DELTA = NOW - last_delta_time;
    last_delta_time = NOW;
    return DELTA;
}
