package handlers

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

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

type MainMenu struct {
	menu *ui.Menu
}

func NewMainMenu(fsm state.Transitioner) *MainMenu {
	return &MainMenu{
		menu: ui.NewMenu([]ui.Widget{
			ui.NewButton("Start", func() { fsm.Switch("gameplay") }),
			ui.NewButton("Quit", func() { fsm.Switch("quit") }),
		}).OnSelect(uievents.MenuSelect),
	}
}

func (main *MainMenu) Enter() {
	main.menu.Select(0)
}

func (MainMenu) Exit() {
}

func (menu *MainMenu) Update(fsm state.Transitioner, delta float32) {
	menu.menu.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) renderEntries(offset_x, offset_y int32) {
	y := offset_y
	for i, entry := range menu.menu.Entries() {
		entry.Draw(offset_x, y, menu.menu.IsSelected(i))
		y += 40
	}
}

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

	menu.renderLogo(20, 150)
	menu.renderEntries(340, 400)

	render.End()
}
