#include <genesis.h>
#include "menu.h"
#include "megasplash.h"
#include <string.h>

static u16 selection = 0;
static u16 idleFrames = 0;
int scrollDelay = 0;
const int scrollSpeed = 10; // lower number = faster, higher = slower

// Smooth input — detect only when button *becomes pressed*
static void handleInput(u16 joy, u16 changed, u16 state)
{
    if (joy != JOY_1) return;

    // ANY button press cancels idle
    if (changed & state)
        idleFrames = 0;

    if ((changed & state & BUTTON_UP))
    {
        if (selection > 0) selection--;
    }

    if ((changed & state & BUTTON_DOWN))
    {
        if (selection < 3) selection++;
    }
}


//menu update global and function declaration for wait screen


void menu_update();

int menu_show()
{
    VDP_resetScreen();
    VDP_setTextPlane(BG_A);

    VDP_drawText("MEGACOLLECTION", 12, 4);
    VDP_drawText("------------------", 10, 5);

    const char* entries[4] = {
        "1. MEGAPONG",
        "2. MEGARUNNER",
        "3. MEGALAGA",
        "4. MEGATILER"
    };

    // --- scrolling text setup ---
    const char* scroll1 = " PRESS UP OR DOWN TO CHOOSE GAME ";
    const char* scroll2 = " PRESS START TO PLAY ";
    

    int scroll1_x = 40;
    int scroll2_x = 40;
    scrollDelay = 0;
    

    selection = 0;
    JOY_setEventHandler(handleInput);

    while(1)
{
    menu_update();   //idle timer works

    for(int i = 0; i < 4; i++)
    {
        if (i == selection)
            VDP_drawText("* ", 10, 8 + i);
        else
            VDP_drawText("  ", 10, 8 + i);

        VDP_drawText(entries[i], 12, 8 + i);
    }

    VDP_clearTextArea(0, 20, 40, 2);

    VDP_drawText(scroll1, scroll1_x, 20);
    VDP_drawText(scroll2, scroll2_x, 21);

    // ---- scrolling text update ----
    scrollDelay++;
    if (scrollDelay >= scrollSpeed)
    {
    scrollDelay = 0;

    scroll1_x--;
    scroll2_x--;

    // wrap when text is fully off-screen
    if (scroll1_x < -(s16)strlen(scroll1))
        scroll1_x = 40;

    if (scroll2_x < -(s16)strlen(scroll2))
        scroll2_x = 40;
    }

    SYS_doVBlankProcess();

    if (JOY_readJoypad(JOY_1) & BUTTON_START)
        return selection + 1;
}

}



void menu_update()
{
    idleFrames++;

    if (idleFrames > IDLE_TRIGGER_FRAMES)
    {
        showMegaSplash();
        idleFrames = 0;

        // Important: redraw menu after splash
        VDP_resetScreen();
        VDP_setTextPlane(BG_A);

        //Potentian Bug 1 Fix
        JOY_setEventHandler(handleInput);
    }
}
