package editor

import (
	"gioui.org/unit"

	"pad/internal/ui"
)

// ConfigEvent represents a window configuration change (resize, orientation).
type ConfigEvent struct {
	Width  unit.Dp
	Height unit.Dp
}

// InputEvent represents a user input event routed to an element.
type InputEvent struct {
	ElementID string
	Type      ui.InputType
	Data      any
}

// ResultEvent represents a completed async task result.
type ResultEvent struct {
	// Future: add result fields here
}

// Logic runs the logic goroutine and provides channels for communication.
type Logic struct {
	state     *State
	configChan chan ConfigEvent
	frameChan  chan []ui.Element
	inputChan  chan []InputEvent
	resultChan chan ResultEvent
}

// NewLogic creates a new Logic instance.
func NewLogic(screenWidth, screenHeight unit.Dp) *Logic {
	return &Logic{
		state:      NewState(screenWidth, screenHeight),
		configChan: make(chan ConfigEvent),
		frameChan:  make(chan []ui.Element),
		inputChan:  make(chan []InputEvent),
		resultChan: make(chan ResultEvent),
	}
}

// ConfigChan returns the config channel for the logic goroutine.
func (l *Logic) ConfigChan() chan<- ConfigEvent {
	return l.configChan
}

// FrameChan returns the frame channel for the logic goroutine.
func (l *Logic) FrameChan() <-chan []ui.Element {
	return l.frameChan
}

// InputChan returns the input channel for the logic goroutine.
func (l *Logic) InputChan() chan<- []InputEvent {
	return l.inputChan
}

// ResultChan returns the result channel for the logic goroutine.
func (l *Logic) ResultChan() <-chan ResultEvent {
	return l.resultChan
}

// Run runs the logic goroutine loop.
func (l *Logic) Run() {
	for {
		select {
		case cfg := <-l.configChan:
			// Update screen size and recompute layout
			l.state.ScreenWidth = cfg.Width
			l.state.ScreenHeight = cfg.Height
			l.state.Elems = EditorLayout(cfg.Width, cfg.Height)
			l.frameChan <- l.state.Elems
		case <-l.inputChan:
			// Process input (not implemented in mockup)
			l.frameChan <- l.state.Elems
		case <-l.resultChan:
			// Handle result (not implemented in mockup)
			l.frameChan <- l.state.Elems
		}
	}
}

// State returns the current state.
func (l *Logic) State() *State {
	return l.state
}
