package uv

import (
	
	
	
	

	
)

// Position represents a position in a coordinate system.
type Position = image.Point

// Pos is a shorthand for creating a new [Position].
func (,  int) Position {
	return Position{X: , Y: }
}

// Rectangle represents a rectangular area.
type Rectangle = image.Rectangle

// Rect is a shorthand for creating a new [Rectangle].
func (, , ,  int) Rectangle {
	return Rectangle{Min: image.Point{X: , Y: }, Max: image.Point{X:  + , Y:  + }}
}

// Line represents cells in a line.
type Line []Cell

// NewLine creates a new line with the given width, filled with empty cells.
func ( int) Line {
	 := make(Line, )
	for  := range  {
		[] = EmptyCell
	}
	return 
}

// Set sets the cell at the given x position.
func ( Line) ( int,  *Cell) {
	 := len()
	if  < 0 ||  >=  {
		return
	}

	// When a wide cell is partially overwritten, we need
	// to fill the rest of the cell with space cells to
	// avoid rendering issues.
	var  *Cell
	if  = .At();  != nil { //nolint:nestif
		if  := .Width;  > 1 {
			// Writing to the first wide cell
			for  := 0;  <  && + < ; ++ {
				[+] = *
				[+].Empty()
			}
		} else if  == 0 {
			// Writing to wide cell placeholders
			for  := 1; - >= 0; ++ {
				if  := .At( - );  != nil {
					if  := .Width;  > 1 &&  <  {
						for  := range  {
							[-+] = *
							[-+].Empty()
						}
						break
					}
				}
			}
		}
	}

	if  == nil {
		// Nil cells are treated as blank empty cells.
		[] = EmptyCell
		return
	}

	[] = *
	 := .Width
	if + >  {
		// If the cell is too wide, we write blanks with the same style.
		for  := 0;  <  && + < ; ++ {
			[+] = *
			[+].Empty()
		}
		return
	}

	if  > 1 {
		// Mark wide cells with zero-width placeholder cells.
		for  := 1;  <  && + < ; ++ {
			[+] = Cell{}
		}
	}
}

// At returns the cell at the given x position.
// If the cell does not exist, it returns nil.
func ( Line) ( int) *Cell {
	if  < 0 ||  >= len() {
		return nil
	}

	return &[]
}

// String returns the string representation of the line. Any trailing spaces
// are removed.
func ( Line) () string {
	var  strings.Builder
	var  bytes.Buffer
	for ,  := range  {
		if .IsZero() {
			continue
		}
		if .Equal(&EmptyCell) {
			.WriteByte(' ')
			continue
		}
		if .Len() > 0 {
			.WriteString(.String())
			.Reset()
		}
		.WriteString(.String())
	}

	return .String()
}

// Render renders the line to a string with all the required attributes and
// styles.
func ( Line) () string {
	var  strings.Builder
	renderLine(&, )
	return .String()
}

func ( io.StringWriter,  Line) {
	var  Style
	var  Link
	var  bytes.Buffer

	for ,  := range  {
		if .IsZero() {
			continue
		}
		if .Equal(&EmptyCell) {
			if !.IsZero() {
				_, _ = .WriteString(ansi.ResetStyle)
				 = Style{}
			}
			if !.IsZero() {
				_, _ = .WriteString(ansi.ResetHyperlink())
				 = Link{}
			}
			.WriteByte(' ')
			continue
		}

		if .Len() > 0 {
			_, _ = .WriteString(.String())
			.Reset()
		}

		if .Style.IsZero() && !.IsZero() {
			_, _ = .WriteString(ansi.ResetStyle)
			 = Style{}
		}
		if !.Style.Equal(&) {
			 := .Style.Diff(&)
			_, _ = .WriteString()
			 = .Style
		}

		// Write the URL escape sequence
		if .Link !=  && .URL != "" {
			_, _ = .WriteString(ansi.ResetHyperlink())
			 = Link{}
		}
		if .Link !=  {
			_, _ = .WriteString(ansi.SetHyperlink(.Link.URL, .Link.Params))
			 = .Link
		}

		_, _ = .WriteString(.String())
	}

	if .Len() > 0 {
		_, _ = .WriteString(.String())
	}
	if .URL != "" {
		_, _ = .WriteString(ansi.ResetHyperlink())
	}
	if !.IsZero() {
		_, _ = .WriteString(ansi.ResetStyle)
	}
}

// Lines represents a slice of lines.
type Lines []Line

// Height returns the height of the lines.
func ( Lines) () int {
	return len()
}

// Width returns the width of the widest line.
func ( Lines) () int {
	 := 0
	for ,  := range  {
		 = max(, len())
	}
	return 
}

// String returns the string representation of the lines.
func ( Lines) () string {
	var  strings.Builder
	for ,  := range  {
		.WriteString(.String())
		if  < len()-1 {
			_ = .WriteByte('\n')
		}
	}
	return .String()
}

// Render renders the lines to a styled string with all the required attributes
// and styles.
func ( Lines) () string {
	var  strings.Builder
	for ,  := range  {
		renderLine(&, )
		if  < len()-1 {
			_ = .WriteByte('\n')
		}
	}
	return .String()
}

// Buffer represents a cell buffer that contains the contents of a screen.
type Buffer struct {
	// Lines is a slice of lines that make up the cells of the buffer.
	Lines []Line
}

var _ Drawable = (*Buffer)(nil)

// NewBuffer creates a new buffer with the given width and height.
// This is a convenience function that initializes a new buffer and resizes it.
func ( int,  int) *Buffer {
	 := new(Buffer)
	.Lines = make([]Line, )
	for  := range .Lines {
		.Lines[] = make(Line, )
		for  := range .Lines[] {
			.Lines[][] = EmptyCell
		}
	}
	.Resize(, )
	return 
}

// String returns the string representation of the buffer.
func ( *Buffer) () string {
	return Lines(.Lines).String()
}

// Render renders the buffer to a styled string with all the required
// attributes and styles.
func ( *Buffer) () string {
	return Lines(.Lines).Render()
}

// Line returns a pointer to the line at the given y position.
// If the line does not exist, it returns nil.
func ( *Buffer) ( int) Line {
	if  < 0 ||  >= len(.Lines) {
		return nil
	}
	return .Lines[]
}

// CellAt returns the cell at the given position. It returns nil if the
// position is out of bounds.
func ( *Buffer) ( int,  int) *Cell {
	if  < 0 ||  >= len(.Lines) {
		return nil
	}
	return .Lines[].At()
}

// SetCell sets the cell at the given x, y position.
func ( *Buffer) (,  int,  *Cell) {
	if  < 0 ||  >= len(.Lines) {
		return
	}

	.Lines[].Set(, )
}

// Height implements Screen.
func ( *Buffer) () int {
	return len(.Lines)
}

// Width implements Screen.
func ( *Buffer) () int {
	if len(.Lines) == 0 {
		return 0
	}
	return len(.Lines[0])
}

// Bounds returns the bounds of the buffer.
// The origin is always at (0, 0) and the maximum coordinates are determined by
// the width and height of the buffer.
func ( *Buffer) () Rectangle {
	return Rect(0, 0, .Width(), .Height())
}

// Resize resizes the buffer to the given width and height.
func ( *Buffer) ( int,  int) {
	,  := .Width(), .Height()
	if  ==  &&  ==  {
		// No need to resize if the dimensions are the same.
		return
	}

	if  >  {
		 := make(Line, -)
		for  := range  {
			[] = EmptyCell
		}
		for  := range .Lines {
			.Lines[] = append(.Lines[], ...)
		}
	} else if  <  {
		for  := range .Lines {
			.Lines[] = .Lines[][:]
		}
	}

	if  > len(.Lines) {
		for  := len(.Lines);  < ; ++ {
			 := make(Line, )
			for  := range  {
				[] = EmptyCell
			}
			.Lines = append(.Lines, )
		}
	} else if  < len(.Lines) {
		.Lines = .Lines[:]
	}
}

// Fill fills the buffer with the given cell and rectangle.
func ( *Buffer) ( *Cell) {
	.FillArea(, .Bounds())
}

// FillArea fills the buffer with the given cell and rectangle.
func ( *Buffer) ( *Cell,  Rectangle) {
	 := 1
	if  != nil && .Width > 1 {
		 = .Width
	}
	for  := .Min.Y;  < .Max.Y; ++ {
		for  := .Min.X;  < .Max.X;  +=  {
			.SetCell(, , )
		}
	}
}

// Clear clears the buffer with space cells and rectangle.
func ( *Buffer) () {
	 := .Bounds()
	for  := .Min.Y;  < .Max.Y; ++ {
		for  := .Min.X;  < .Max.X; ++ {
			.Lines[][] = EmptyCell
		}
	}
}

// ClearArea clears the buffer with space cells within the specified
// rectangles. Only cells within the rectangle's bounds are affected.
func ( *Buffer) ( Rectangle) {
	.FillArea(nil, )
}

// CloneArea clones the area of the buffer within the specified rectangle. If
// the area is out of bounds, it returns nil.
func ( *Buffer) ( Rectangle) *Buffer {
	 := .Bounds()
	if !.In() {
		return nil
	}
	 := NewBuffer(.Dx(), .Dy())
	for  := .Min.Y;  < .Max.Y; ++ {
		for  := .Min.X;  < .Max.X; {
			 := .CellAt(, )
			if  == nil || .IsZero() {
				++
				continue
			}
			.SetCell(-.Min.X, -.Min.Y, )
			 += max(.Width, 1)
		}
	}
	return 
}

// Clone clones the entire buffer into a new buffer.
func ( *Buffer) () *Buffer {
	return .CloneArea(.Bounds())
}

// Draw draws the buffer to the given screen at the specified area.
// It implements the [Drawable] interface.
func ( *Buffer) ( Screen,  Rectangle) {
	if .Empty() {
		return
	}

	// Ensure the area is within the bounds of the screen.
	 := .Bounds()
	if !.Overlaps() {
		return
	}

	for  := .Min.Y;  < .Max.Y; ++ {
		for  := .Min.X;  < .Max.X; {
			 := .CellAt(-.Min.X, -.Min.Y)
			if  == nil || .IsZero() {
				++
				continue
			}
			.SetCell(, , )
			 := .Width
			if  <= 0 {
				 = 1
			}
			 += 
		}
	}
}

// InsertLine inserts n lines at the given line position, with the given
// optional cell, within the specified rectangles. If no rectangles are
// specified, it inserts lines in the entire buffer. Only cells within the
// rectangle's horizontal bounds are affected. Lines are pushed out of the
// rectangle bounds and lost. This follows terminal [ansi.IL] behavior.
// It returns the pushed out lines.
func ( *Buffer) (,  int,  *Cell) {
	.InsertLineArea(, , , .Bounds())
}

// InsertLineArea inserts new lines at the given line position, with the
// given optional cell, within the rectangle bounds. Only cells within the
// rectangle's horizontal bounds are affected. Lines are pushed out of the
// rectangle bounds and lost. This follows terminal [ansi.IL] behavior.
func ( *Buffer) (,  int,  *Cell,  Rectangle) {
	if  <= 0 ||  < .Min.Y ||  >= .Max.Y ||  >= .Height() {
		return
	}

	// Limit number of lines to insert to available space
	if + > .Max.Y {
		 = .Max.Y - 
	}

	// Move existing lines down within the bounds
	for  := .Max.Y - 1;  >= +; -- {
		for  := .Min.X;  < .Max.X; ++ {
			// We don't need to clone c here because we're just moving lines down.
			.Lines[][] = .Lines[-][]
		}
	}

	// Clear the newly inserted lines within bounds
	for  := ;  < +; ++ {
		for  := .Min.X;  < .Max.X; ++ {
			.SetCell(, , )
		}
	}
}

// DeleteLineArea deletes lines at the given line position, with the given
// optional cell, within the rectangle bounds. Only cells within the
// rectangle's bounds are affected. Lines are shifted up within the bounds and
// new blank lines are created at the bottom. This follows terminal [ansi.DL]
// behavior.
func ( *Buffer) (,  int,  *Cell,  Rectangle) {
	if  <= 0 ||  < .Min.Y ||  >= .Max.Y ||  >= .Height() {
		return
	}

	// Limit deletion count to available space in scroll region
	if  > .Max.Y- {
		 = .Max.Y - 
	}

	// Shift cells up within the bounds
	for  := ;  < .Max.Y-; ++ {
		 :=  + 
		for  := .Min.X;  < .Max.X; ++ {
			// We don't need to clone c here because we're just moving cells up.
			.Lines[][] = .Lines[][]
		}
	}

	// Fill the bottom n lines with blank cells
	for  := .Max.Y - ;  < .Max.Y; ++ {
		for  := .Min.X;  < .Max.X; ++ {
			.SetCell(, , )
		}
	}
}

// DeleteLine deletes n lines at the given line position, with the given
// optional cell, within the specified rectangles. If no rectangles are
// specified, it deletes lines in the entire buffer.
func ( *Buffer) (,  int,  *Cell) {
	.DeleteLineArea(, , , .Bounds())
}

// InsertCell inserts new cells at the given position, with the given optional
// cell, within the specified rectangles. If no rectangles are specified, it
// inserts cells in the entire buffer. This follows terminal [ansi.ICH]
// behavior.
func ( *Buffer) (, ,  int,  *Cell) {
	.InsertCellArea(, , , , .Bounds())
}

// InsertCellArea inserts new cells at the given position, with the given
// optional cell, within the rectangle bounds. Only cells within the
// rectangle's bounds are affected, following terminal [ansi.ICH] behavior.
func ( *Buffer) (, ,  int,  *Cell,  Rectangle) {
	if  <= 0 ||  < .Min.Y ||  >= .Max.Y ||  >= .Height() ||
		 < .Min.X ||  >= .Max.X ||  >= .Width() {
		return
	}

	// Limit number of cells to insert to available space
	if + > .Max.X {
		 = .Max.X - 
	}

	// Move existing cells within rectangle bounds to the right
	for  := .Max.X - 1;  >= + && - >= .Min.X; -- {
		// We don't need to clone c here because we're just moving cells to the
		// right.
		.Lines[][] = .Lines[][-]
	}

	// Clear the newly inserted cells within rectangle bounds
	for  := ;  < + &&  < .Max.X; ++ {
		.SetCell(, , )
	}
}

// DeleteCell deletes cells at the given position, with the given optional
// cell, within the specified rectangles. If no rectangles are specified, it
// deletes cells in the entire buffer. This follows terminal [ansi.DCH]
// behavior.
func ( *Buffer) (, ,  int,  *Cell) {
	.DeleteCellArea(, , , , .Bounds())
}

// DeleteCellArea deletes cells at the given position, with the given
// optional cell, within the rectangle bounds. Only cells within the
// rectangle's bounds are affected, following terminal [ansi.DCH] behavior.
func ( *Buffer) (, ,  int,  *Cell,  Rectangle) {
	if  <= 0 ||  < .Min.Y ||  >= .Max.Y ||  >= .Height() ||
		 < .Min.X ||  >= .Max.X ||  >= .Width() {
		return
	}

	// Calculate how many positions we can actually delete
	 := .Max.X - 
	if  >  {
		 = 
	}

	// Shift the remaining cells to the left
	for  := ;  < .Max.X-; ++ {
		if + < .Max.X {
			// We need to use SetCell here to ensure we blank out any wide
			// cells we encounter.
			.SetCell(, , .CellAt(+, ))
		}
	}

	// Fill the vacated positions with the given cell
	for  := .Max.X - ;  < .Max.X; ++ {
		.SetCell(, , )
	}
}

// ScreenBuffer is a buffer that can be used as a [Screen].
type ScreenBuffer struct {
	*RenderBuffer
	Method ansi.Method
}

var (
	_ Screen   = ScreenBuffer{}
	_ Drawable = ScreenBuffer{}
)

// NewScreenBuffer creates a new ScreenBuffer with the given width and height.
func (,  int) ScreenBuffer {
	return ScreenBuffer{
		RenderBuffer: NewRenderBuffer(, ),
		Method:       ansi.WcWidth,
	}
}

// WidthMethod returns the width method used by the screen.
// It defaults to [ansi.WcWidth].
func ( ScreenBuffer) () WidthMethod {
	return .Method
}

// TrimSpace trims trailing spaces from the end of each line in the given
// string.
func ( string) string {
	 := strings.Split(, "\n")
	for ,  := range  {
		// Check if we have a trailing '\r' and preserve it
		 := strings.HasSuffix(, "\r")
		if  {
			 = strings.TrimSuffix(, "\r")
		}
		 = strings.TrimRight(, " ")
		if  {
			 =  + "\r"
		}
		[] = 
	}
	return strings.Join(, "\n")
}

// RenderBuffer represents a buffer that keeps track of the current and new
// state of the screen, allowing for efficient rendering by only updating the
// parts of the screen that have changed.
type RenderBuffer struct {
	*Buffer
	Touched []*LineData
}

// NewRenderBuffer creates a new [RenderBuffer] with the given width and height.
func (,  int) *RenderBuffer {
	return &RenderBuffer{
		Buffer:  NewBuffer(, ),
		Touched: make([]*LineData, ),
	}
}

// TouchLine marks a line n times starting at the given x position as touched.
func ( *RenderBuffer) (, ,  int) {
	if  < 0 ||  >= len(.Lines) {
		return
	}

	if  >= len(.Touched) {
		.Touched = append(.Touched, make([]*LineData, -len(.Touched)+1)...)
	}

	// Re-check bounds: a concurrent resize may have cleared Touched
	if  >= len(.Touched) {
		return
	}

	 := .Touched[]
	if  == nil {
		 = &LineData{FirstCell: , LastCell:  + }
	} else {
		.FirstCell = min(.FirstCell, )
		.LastCell = max(.LastCell, +)
	}
	.Touched[] = 
}

// Touch marks the cell at the given x, y position as touched.
func ( *RenderBuffer) (,  int) {
	.TouchLine(, , 0)
}

// TouchedLines returns the number of touched lines in the buffer.
func ( *RenderBuffer) () int {
	if .Touched == nil {
		return 0
	}
	 := 0
	for ,  := range .Touched {
		if  != nil {
			++
		}
	}
	return 
}

// SetCell sets the cell at the given x, y position and marks the line as
// touched.
func ( *RenderBuffer) (,  int,  *Cell) {
	if  := .CellAt(, ); !cellEqual(, ) {
		 := 1
		if  != nil && .Width > 0 {
			 = .Width
		}
		if  != nil && .Width > 0 {
			 = max(, .Width)
		}
		.TouchLine(, , )
	}
	.Buffer.SetCell(, , )
}

// InsertLine inserts n lines at the given line position, with the given
// optional cell, within the specified rectangles. If no rectangles are
// specified, it inserts lines in the entire buffer. Only cells within the
// rectangle's horizontal bounds are affected. Lines are pushed out of the
// rectangle bounds and lost. This follows terminal [ansi.IL] behavior.
func ( *RenderBuffer) (,  int,  *Cell) {
	.InsertLineArea(, , , .Bounds())
}

// InsertLineArea inserts new lines at the given line position, with the given
// optional cell, within the rectangle bounds. Only cells within the
// rectangle's horizontal bounds are affected. Lines are pushed out of the
// rectangle bounds and lost. This follows terminal [ansi.IL] behavior.
func ( *RenderBuffer) (,  int,  *Cell,  Rectangle) {
	.Buffer.InsertLineArea(, , , )
	for  := .Min.Y;  < .Max.Y; ++ {
		.TouchLine(.Min.X, , .Max.X-.Min.X)
		.TouchLine(.Min.X, -, .Max.X-.Min.X)
	}
}

// DeleteLine deletes n lines at the given line position, with the given
// optional cell, within the specified rectangles. If no rectangles are
// specified, it deletes lines in the entire buffer.
func ( *RenderBuffer) (,  int,  *Cell) {
	.DeleteLineArea(, , , .Bounds())
}

// DeleteLineArea deletes lines at the given line position, with the given
// optional cell, within the rectangle bounds. Only cells within the
// rectangle's bounds are affected. Lines are shifted up within the bounds and
// new blank lines are created at the bottom. This follows terminal [ansi.DL]
// behavior.
func ( *RenderBuffer) (,  int,  *Cell,  Rectangle) {
	.Buffer.DeleteLineArea(, , , )
	for  := .Min.Y;  < .Max.Y; ++ {
		.TouchLine(.Min.X, , .Max.X-.Min.X)
		.TouchLine(.Min.X, +, .Max.X-.Min.X)
	}
}

// InsertCell inserts new cells at the given position, with the given optional
// cell, within the specified rectangles. If no rectangles are specified, it
// inserts cells in the entire buffer. This follows terminal [ansi.ICH]
// behavior.
func ( *RenderBuffer) (, ,  int,  *Cell) {
	.InsertCellArea(, , , , .Bounds())
}

// InsertCellArea inserts new cells at the given position, with the given
// optional cell, within the rectangle bounds. Only cells within the
// rectangle's bounds are affected, following terminal [ansi.ICH] behavior.
func ( *RenderBuffer) (, ,  int,  *Cell,  Rectangle) {
	.Buffer.InsertCellArea(, , , , )
	if + > .Max.X {
		 = .Max.X - 
	}
	.TouchLine(, , )
}

// DeleteCell deletes cells at the given position, with the given optional
// cell, within the specified rectangles. If no rectangles are specified, it
// deletes cells in the entire buffer. This follows terminal [ansi.DCH]
// behavior.
func ( *RenderBuffer) (, ,  int,  *Cell) {
	.DeleteCellArea(, , , , .Bounds())
}

// DeleteCellArea deletes cells at the given position, with the given
// optional cell, within the rectangle bounds. Only cells within the
// rectangle's bounds are affected, following terminal [ansi.DCH] behavior.
func ( *RenderBuffer) (, ,  int,  *Cell,  Rectangle) {
	.Buffer.DeleteCellArea(, , , , )
	 := .Max.X - 
	if  >  {
		 = 
	}
	.TouchLine(, , )
}

// Clear clears the buffer with space cells and marks all lines as touched.
func ( *RenderBuffer) () {
	.Buffer.Clear()
	 := .Width()
	for  := range .Lines {
		.TouchLine(0, , )
	}
}

// ClearArea clears the buffer with space cells within the specified rectangle
// and marks the affected lines as touched.
func ( *RenderBuffer) ( Rectangle) {
	.Buffer.ClearArea()
	 := .Max.X - .Min.X
	for  := .Min.Y;  < .Max.Y; ++ {
		.TouchLine(.Min.X, , )
	}
}

// Fill fills the buffer with the given cell and marks all lines as touched.
func ( *RenderBuffer) ( *Cell) {
	.FillArea(, .Bounds())
}

// FillArea fills the buffer with the given cell within the specified rectangle
// and marks the affected lines as touched.
func ( *RenderBuffer) ( *Cell,  Rectangle) {
	.Buffer.FillArea(, )
	 := .Max.X - .Min.X
	for  := .Min.Y;  < .Max.Y; ++ {
		.TouchLine(.Min.X, , )
	}
}