package handlers

import (
	"tetris/assets"
	"tetris/engine/audio"
	"tetris/engine/render"
	"tetris/game"
	"tetris/game/state"
	"tetris/game/ui"
	"tetris/game/ui/layouts"
	"tetris/game/ui/widgets"
	"tetris/game/uievents"

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

type MainMenu struct {
	list *layouts.ListBox
}

func enterState(fsm state.Transitioner, state string) func() {
	return func() {
		audio.Play(assets.SFX_MENU_ENTER)
		fsm.Switch(state)
	}
}

func NewMainMenu(fsm state.Transitioner) *MainMenu {
	return &MainMenu{
		list: layouts.NewListBox([]ui.InputWidget{
			widgets.NewButton("Start", 32, enterState(fsm, "gameplay")),
			widgets.NewButton("Options", 32, enterState(fsm, "options")),
			widgets.NewButton("Quit", 32, enterState(fsm, "quit")),
		}).Spacing(10).
			OnSelect(uievents.MenuSelect),
	}
}

func (main *MainMenu) Enter() {
	main.list.SetSelected(0)
}

func (MainMenu) Exit() {
}

func (menu *MainMenu) Update(fsm state.Transitioner, delta float32) {
	menu.list.HandleInput()
}

func (MainMenu) renderLogo(offset_x, offset_y int32) {
	for y := range assets.LOGO_HEIGHT {
		for x := range assets.LOGO_STRIDE {
			index := assets.Logo[x+(y*assets.LOGO_STRIDE)]
			block := game.Block(index)

			if block == game.BLOCK_EMPTY {
				continue
			}

			src := block.Tile().GetTexRect()

			render.DrawTextureRec(src, rl.Rectangle{
				X:      float32(offset_x) + (float32(x) * src.Width * 2),
				Y:      float32(offset_y) + (float32(y) * src.Height * 2),
				Width:  src.Width * 2,
				Height: src.Height * 2,
			})
		}
	}
}

func (menu MainMenu) Render() {
	render.Begin(rl.Black)

	menu.renderLogo(20, 150)
	menu.list.Draw(340, 400)

	render.End()
}
