package editor

import (
	tea "github.com/charmbracelet/bubbletea"
)

func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	var cmd tea.Cmd

	switch msg := msg.(type) {

	case tea.WindowSizeMsg:
		m.termHeight = msg.Height
		m.termWidth = msg.Width

		// TODO: Implement a layout method that handles this
		//
		//   func (m *Model) layoutWindows() {
		//     if len(m.windows) == 0 {
		//         return
		//     }
		//
		//     if len(m.windows) == 1 {
		//         // Single window - full screen
		//         m.windows[0].Width = m.termWidth
		//         m.windows[0].Height = m.termHeight
		//         return
		//     }
		//
		//     // Multiple windows - distribute space
		//     // This is where you'd implement split layout logic
		//     // For example, horizontal split:
		//     halfHeight := m.termHeight / 2
		//     for i, win := range m.windows {
		//         win.Width = m.termWidth
		//         if i < len(m.windows)-1 {
		//             win.Height = halfHeight
		//         } else {
		//             // Last window gets remainder
		//             win.Height = m.termHeight - (halfHeight * (len(m.windows) - 1))
		//         }
		//     }
		// }
		for i := range m.windows {
			m.windows[i].Height = msg.Height
			m.windows[i].Width = msg.Width
		}

	case tea.KeyMsg:
		// TODO: This needs to be removed, but for now its required for the tests.
		// Ctrl+C always quits regardless of mode
		if msg.Type == tea.KeyCtrlC {
			return m, tea.Quit
		}
		cmd = m.input.Handle(m, msg.String())
	}

	// Keep cursor in view after any update
	m.AdjustScroll()

	return m, cmd
}
