package handlers

import (
	"tetris/assets"
	"tetris/engine/audio"
	"tetris/engine/render"
	"tetris/game/state"

	rl "github.com/gen2brain/raylib-go/raylib"
)

type entry struct {
	label string
	state string
}

type Menu struct {
	selected int
	entries  []entry
}

func NewMenu() *Menu {
	return &Menu{
		selected: 0,
		entries: []entry{
			{"Start", "gameplay"},
			{"Quit", "quit"},
		},
	}
}

func (menu *Menu) Enter() {
	menu.selected = 0
}

func (Menu) Exit() {
}

func (menu *Menu) Update(fsm state.Transitioner, delta float32) {
	if rl.IsKeyPressed(rl.KeyEnter) {
		fsm.Switch(menu.entries[menu.selected].state)
		audio.Play(assets.SFX_MENU_ENTER)
	} else if rl.IsKeyPressed(rl.KeyDown) {
		if menu.selected+1 < len(menu.entries) {
			menu.selected = menu.selected + 1
			audio.Play(assets.SFX_MENU_SELECT)
		}
	} else if rl.IsKeyPressed(rl.KeyUp) {
		if menu.selected-1 >= 0 {
			menu.selected = menu.selected - 1
			audio.Play(assets.SFX_MENU_SELECT)
		}
	}
}

func (menu Menu) Render() {
	render.Begin(rl.Black)
	y := int32(400)
	for i, entry := range menu.entries {

		col := rl.White
		if i == menu.selected {
			col = rl.Red
		}
		render.DrawTextCenter(340, y, 32, entry.label, col)
		y += 40
	}
	render.End()
}
