#include "game/scenes/banner_scene.hpp"

#include <cstdlib>

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

namespace Scenes {

    void BannerScene::onEnter() {
        playMusic("music/banner.ogg");

        gfx_ = SurfaceHandle("gfx/ffase.gif");

        Jd8::clearScreen(0);
        // Títols superior i inferior del banner (compartits per tots els nivells)
        Jd8::blit(81, 24, gfx_, 81, 155, 168, 21);
        Jd8::blit(39, 150, gfx_, 39, 175, 248, 20);

        // Número de piràmide: les 4 variants del vell `doBanner` es reduïxen
        // a coordenades (SX,SY) calculades a partir de l'índex 0..3.
        const int IDX = Info::ctx.num_piramide - 2;  // 2..5 → 0..3
        if (IDX >= 0 && IDX <= 3) {
            const int SX = (IDX % 2) * 160;
            const int SY = (IDX / 2) * 75;
            Jd8::blit(82, 60, gfx_, SX, SY, 160, 75);
        }

        // PaletteFade copia internament amb memcpy; alliberem la paleta temporal.
        Jd8::Palette pal = Jd8::loadPalette("gfx/ffase.gif");
        fade_.startFadeTo(pal);
        delete[] pal;

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

    void BannerScene::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) {
                    Audio::get()->fadeOutMusic(250);
                    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
