package lipgloss

import (
	
	
	

	uv 
)

// Layer represents a visual layer with content and positioning. It's a pure
// data structure that defines the layer hierarchy without any computation.
type Layer struct {
	id            string
	content       string
	width, height int
	x, y, z       int
	layers        []*Layer
}

// NewLayer creates a new [Layer] with the given content and optional child layers.
func ( string,  ...*Layer) *Layer {
	 := &Layer{
		content: ,
	}
	.AddLayers(...)
	return 
}

// GetContent returns the content of the Layer.
func ( *Layer) () string {
	return .content
}

// Width returns the width of the Layer.
func ( *Layer) () int {
	return .width
}

// Height returns the height of the Layer.
func ( *Layer) () int {
	return .height
}

// GetID returns the ID of the Layer.
func ( *Layer) () string {
	return .id
}

// ID sets the ID of the Layer.
func ( *Layer) ( string) *Layer {
	.id = 
	return 
}

// X sets the x-coordinate of the Layer relative to its parent.
func ( *Layer) ( int) *Layer {
	.x = 
	return 
}

// Y sets the y-coordinate of the Layer relative to its parent.
func ( *Layer) ( int) *Layer {
	.y = 
	return 
}

// Z sets the z-index of the Layer relative to its parent.
func ( *Layer) ( int) *Layer {
	.z = 
	return 
}

// GetX returns the x-coordinate of the Layer relative to its parent.
func ( *Layer) () int {
	return .x
}

// GetY returns the y-coordinate of the Layer relative to its parent.
func ( *Layer) () int {
	return .y
}

// GetZ returns the z-index of the Layer relative to its parent.
func ( *Layer) () int {
	return .z
}

// AddLayers adds child layers to the Layer.
func ( *Layer) ( ...*Layer) *Layer {
	for ,  := range  {
		if  == nil {
			panic(fmt.Sprintf("layer at index %d is nil", ))
		}
		.layers = append(.layers, )
	}
	 := .boundsWithOffset(0, 0)
	.width = .Dx()
	.height = .Dy()
	return 
}

// GetLayer returns a descendant layer by its ID, or nil if not found.
// Layers with empty IDs are skipped.
func ( *Layer) ( string) *Layer {
	if  == "" {
		return nil
	}
	if .id ==  {
		return 
	}
	for ,  := range .layers {
		if  := .();  != nil {
			return 
		}
	}
	return nil
}

// MaxZ returns the maximum z-index among this layer and all its descendants.
func ( *Layer) () int {
	 := .z
	for ,  := range .layers {
		 := .()
		if  >  {
			 = 
		}
	}
	return 
}

// boundsWithOffset calculates bounds with parent offset applied.
func ( *Layer) (,  int) image.Rectangle {
	 := .x + 
	 := .y + 

	,  := Width(.content), Height(.content)
	 := image.Rectangle{
		Min: image.Pt(, ),
		Max: image.Pt(+, +),
	}

	for ,  := range .layers {
		 = .Union(.(, ))
	}

	return 
}

var _ uv.Drawable = (*Layer)(nil)

// Draw draws the content of the layer on the screen at the specified area.
func ( *Layer) ( uv.Screen,  uv.Rectangle) {
	 := uv.NewStyledString(.content)
	.Draw(, )
}

// LayerHit represents the result of a hit test on a [Layer].
type LayerHit struct {
	id     string
	layer  *Layer
	bounds image.Rectangle
}

// Empty returns true if the LayerHit represents no hit.
func ( LayerHit) () bool {
	return .layer == nil
}

// ID returns the ID of the hit Layer.
func ( LayerHit) () string {
	return .id
}

// Layer returns the layer that was hit.
func ( LayerHit) () *Layer {
	return .layer
}

// Bounds returns the bounds of the LayerHit.
func ( LayerHit) () image.Rectangle {
	return .bounds
}

// Compositor manages the composition of layers. It flattens a layer hierarchy
// once and provides efficient drawing and hit testing operations. All computation
// related to layers happens in the Compositor.
type Compositor struct {
	root   *Layer
	layers []compositeLayer
	index  map[string]*Layer
	bounds image.Rectangle
}

// compositeLayer holds a flattened layer with its calculated absolute position and bounds.
type compositeLayer struct {
	layer  *Layer
	absX   int
	absY   int
	bounds image.Rectangle
}

// NewCompositor creates a new Compositor with an internal root layer. Optional
// layers can be provided which will be added as children of the root. The layer
// hierarchy is flattened and sorted by z-index for efficient rendering and hit testing.
func ( ...*Layer) *Compositor {
	 := NewLayer("")
	.AddLayers(...)
	 := &Compositor{
		root:  ,
		index: make(map[string]*Layer),
	}
	.flatten()
	return 
}

// AddLayers adds layers to the compositor's root and refreshes the internal state.
func ( *Compositor) ( ...*Layer) *Compositor {
	.root.AddLayers(...)
	.flatten()
	return 
}

// flatten builds the internal flattened layer list and calculates overall bounds.
func ( *Compositor) () {
	.layers = nil
	.index = make(map[string]*Layer)
	.flattenRecursive(.root, 0, 0)

	// Sort by absolute z-index (lowest to highest for drawing)
	slices.SortFunc(.layers, func(,  compositeLayer) int {
		return .layer.z - .layer.z
	})

	// Calculate overall bounds
	if len(.layers) > 0 {
		.bounds = .layers[0].bounds
		for  := 1;  < len(.layers); ++ {
			.bounds = .bounds.Union(.layers[].bounds)
		}
	}
}

// flattenRecursive recursively collects all layers with their absolute positions.
func ( *Compositor) ( *Layer, ,  int) {
	 := .x + 
	 := .y + 

	,  := Width(.content), Height(.content)
	 := image.Rectangle{
		Min: image.Pt(, ),
		Max: image.Pt(+, +),
	}

	.layers = append(.layers, compositeLayer{
		layer:  ,
		absX:   ,
		absY:   ,
		bounds: ,
	})

	// Index layer by ID if it has one
	if .id != "" {
		.index[.id] = 
	}

	for ,  := range .layers {
		.(, , )
	}
}

// Bounds returns the overall bounds of all layers in the compositor.
func ( *Compositor) () image.Rectangle {
	return .bounds
}

// Draw draws all layers onto the given [uv.Screen] in z-index order.
func ( *Compositor) ( uv.Screen,  image.Rectangle) {
	for ,  := range .layers {
		if .bounds.Overlaps() {
			.layer.Draw(, .bounds)
		}
	}
}

// Hit performs a hit test at the given (x, y) coordinates. If a layer is hit,
// it returns the ID of the top-most layer at that point. Layers with empty IDs
// are ignored. If no layer is hit, it returns an empty [LayerHit].
func ( *Compositor) (,  int) LayerHit {
	var  LayerHit
	 := image.Pt(, )
	// Check from highest z to lowest (reverse order)
	for  := len(.layers) - 1;  >= 0; -- {
		 := .layers[]
		if .layer.id != "" && .In(.bounds) {
			.id = .layer.id
			.layer = .layer
			.bounds = .bounds
			return 
		}
	}
	return 
}

// GetLayer returns a layer by its ID, or nil if not found.
// Layers with empty IDs are not indexed and cannot be retrieved.
func ( *Compositor) ( string) *Layer {
	if  == "" {
		return nil
	}
	return .index[]
}

// Refresh re-flattens the layer hierarchy. Call this after modifying the layer
// tree structure or positions to update the compositor's internal state.
func ( *Compositor) () {
	.flatten()
}

// Render renders the compositor into a styled string. This is a helper
// function that creates a temporary canvas, draws the compositor onto it, and
// returns the resulting string.
func ( *Compositor) () string {
	,  := .bounds.Dx(), .bounds.Dy()
	 := NewCanvas(, )
	return .Compose().Render()
}