#include "game/scenes/mort_scene.hpp"

#include <cstdlib>

#include "core/jail/jdraw8.hpp"
#include "core/jail/jinput.hpp"
#include "game/info.hpp"
#include "game/scenes/scene_utils.hpp"

namespace Scenes {

    void MortScene::onEnter() {
        playMusic("music/mort.ogg");
        Ji::disableKeyboard(60);
        Info::ctx.vida = 5;

        gfx_ = SurfaceHandle("gfx/gameover.gif");
        Jd8::clearScreen(0);
        Jd8::blit(gfx_);

        // PaletteFade en fa una còpia interna via memcpy, així que alliberem
        // la paleta temporal immediatament.
        Jd8::Palette pal = Jd8::loadPalette("gfx/gameover.gif");
        fade_.startFadeTo(pal);
        delete[] pal;

        phase_ = Phase::FADING_IN;
        remaining_ms_ = 10000;
    }

    void MortScene::tick(int delta_ms) {
        switch (phase_) {
            case Phase::FADING_IN:
                fade_.tick(delta_ms);
                if (fade_.done()) {
                    phase_ = Phase::SHOWING;
                }
                break;

            case Phase::SHOWING:
                if (Ji::anyKey()) {
                    remaining_ms_ = 0;
                } else {
                    remaining_ms_ -= delta_ms;
                }
                if (remaining_ms_ <= 0) {
                    // Arrenca música del següent mòdul abans del fade out,
                    // igual que la versió vella feia al final de doMort().
                    playMusic("music/menu.ogg");
                    Info::ctx.num_piramide = 0;
                    fade_.startFadeOut();
                    phase_ = Phase::FADING_OUT;
                }
                break;

            case Phase::FADING_OUT:
                fade_.tick(delta_ms);
                if (fade_.done()) {
                    phase_ = Phase::DONE;
                }
                break;

            case Phase::DONE:
                break;
        }
    }

}  // namespace Scenes
