package main

import (
	"fmt"
	"os"

	tea "github.com/charmbracelet/bubbletea"
)

// Model holds application state
type model struct {
	choices  []string
	cursor   int
	selected map[int]struct{}
}

// Init runs on startup
func (m model) Init() tea.Cmd {
	return nil // No initial command
}

// Update handles messages and updates state
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case tea.KeyMsg:
		switch msg.String() {
		case "ctrl+c", "q":
			return m, tea.Quit
		case "up", "k":
			if m.cursor > 0 {
				m.cursor--
			}
		case "down", "j":
			if m.cursor < len(m.choices)-1 {
				m.cursor++
			}
		case "enter", " ":
			_, ok := m.selected[m.cursor]
			if ok {
				delete(m.selected, m.cursor)
			} else {
				m.selected[m.cursor] = struct{}{}
			}
		}
	}
	return m, nil
}

// View renders the UI
func (m model) View() string {
	s := "What should we buy at the store?\n\n"

	for i, choice := range m.choices {
		cursor := " " // no cursor
		if m.cursor == i {
			cursor = ">" // cursor
		}

		checked := " " // not selected
		if _, ok := m.selected[i]; ok {
			checked = "x" // selected
		}

		s += fmt.Sprintf("%s [%s] %s\n", cursor, checked, choice)
	}

	s += "\nPress q to quit.\n"
	return s
}

func main() {
	// Initialize model
	m := model{
		choices:  []string{"Carrots", "Celery", "Potatoes", "Bread", "Milk"},
		selected: make(map[int]struct{}),
	}

	// Create and run the program
	p := tea.NewProgram(m)
	if _, err := p.Run(); err != nil {
		fmt.Printf("Error: %v", err)
		os.Exit(1)
	}
}

// Bubbletea follows the Elm Architecture:
//
// 1. Model - Application state
// 2. Update - Handle events and update state
// 3. View - Render state to string
//
// Messages flow through Update, which returns:
// - New model (updated state)
// - Optional Cmd (side effects like HTTP, timers, etc.)
//
// Common message types:
// - tea.KeyMsg: Keyboard input
// - tea.MouseMsg: Mouse input
// - tea.WindowSizeMsg: Terminal resize
// - Custom types: Your own messages
//
// Common commands:
// - tea.Quit: Exit the program
// - tea.Batch(): Run multiple commands
// - tea.Tick(): Create timers
// - Custom Cmds: HTTP, file I/O, etc.
