package uv

import (
	
	
	
	
	
	
	

	
	
	
)

// TerminalScreen represents a terminal screen, providing methods for managing
// the screen state and rendering content.
type TerminalScreen struct {
	win     *Window
	w       io.Writer
	buf     *bytes.Buffer
	rend    *TerminalRenderer
	rbuf    *RenderBuffer
	env     Environ
	profile colorprofile.Profile

	// Terminal state
	altScreen            bool
	keyboardEnhancements *KeyboardEnhancements
	bracketedPaste       bool
	mouseMode            MouseMode
	mouseEncoding        MouseEncoding
	cursor               *Cursor // initial state is cursor hidden
	backgroundColor      color.Color
	foregroundColor      color.Color
	progressBar          *ProgressBar
	windowTitle          string
	syncUpdates          bool // mode 2026
	resetTabs            bool // DECST8C - reset terminal tabs on start

	// mu serializes access to the render buffer, output buffer, and
	// width-method state so the terminal event loop (which negotiates
	// grapheme-cluster width) cannot race with the application's own
	// Render/Flush goroutine.
	mu sync.Mutex
	// widthMethodOverride is set when the application explicitly calls
	// [TerminalScreen.SetWidthMethod]. An explicit override suppresses the
	// automatic mode-2027 width-method negotiation.
	widthMethodOverride bool
}

var _ Screen = (*TerminalScreen)(nil)

// NewTerminalScreen creates a new [TerminalScreen] with the given writer and environment.
func ( io.Writer,  Environ) *TerminalScreen {
	 := &TerminalScreen{}
	.buf = &bytes.Buffer{}
	.win = NewWindow(0, 0, nil)
	.w = 
	.profile = colorprofile.Detect(, )
	.rend = NewTerminalRenderer(.buf, )
	.rend.SetFullscreen(false)    // by default, we start in inline mode
	.rend.SetRelativeCursor(true) // by default, we start in inline mode
	.rend.SetColorProfile(.profile)
	.rbuf = NewRenderBuffer(0, 0)
	.env = 

	if  := .Getenv("UV_DEBUG");  != "" {
		if ,  := os.OpenFile(, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644);  == nil {
			log.SetOutput()
			.rend.SetLogger(log.Default())
		}
	}

	// Configure renderer optimizations based on console settings.
	,  := .(term.File)
	if  {
		,  := term.GetState(.Fd())
		if  == nil || isWindows { // Windows supports tabs and backspace by default, so we can ignore errors here.
			,  := optimizeMovements()
			if  {
				.rend.SetTabStops(0) // the width will be set after calling [TerminalScreen.Resize]
			} else {
				.rend.SetTabStops(-1)
			}
			.rend.SetBackspace()
			.resetTabs = 
		}
	}
	// XXX: Do we still need map nl to crlf handling in the renderer?
	.rend.SetMapNewline(false)
	return 
}

// CellAt returns the cell at the specified x and y coordinates.
func ( *TerminalScreen) (,  int) *Cell {
	return .win.CellAt(, )
}

// SetCell sets the cell at the specified x and y coordinates.
func ( *TerminalScreen) (,  int,  *Cell) {
	.win.SetCell(, , )
}

// Bounds returns the bounds of the terminal screen as a rectangle.
func ( *TerminalScreen) () Rectangle {
	return .win.Bounds()
}

// Width returns the width of the terminal screen.
//
// Note that this is not the actual width of the terminal window, but rather
// the width of the screen we're managing. The actual width of the terminal
// window can be obtained using [Terminal.GetSize] or by reading the "COLUMNS"
// environment variable.
func ( *TerminalScreen) () int {
	return .win.Width()
}

// Height returns the height of the terminal screen.
//
// Note that this is not the actual height of the terminal window, but rather
// the height of the screen we're managing. The actual height of the terminal
// window can be obtained using [Terminal.GetSize] or by reading the "LINES"
// environment variable.
func ( *TerminalScreen) () int {
	return .win.Height()
}

// StringWidth returns the cell width of the given string using the terminal
// screen's width method. This accounts for the configured [WidthMethod]
// (e.g. wcwidth vs grapheme width) so callers don't need to import ansi
// directly.
func ( *TerminalScreen) ( string) int {
	return .win.WidthMethod().StringWidth()
}

// WidthMethod returns the width method used by the terminal screen.
func ( *TerminalScreen) () WidthMethod {
	return .win.WidthMethod()
}

// SetWidthMethod sets the width method for the terminal screen. This is an
// override that propagates to the window/buffer and the renderer so that all
// width measurements use the same method. Calling this marks the width method
// as explicitly overridden, which disables automatic mode-2027 negotiation.
func ( *TerminalScreen) ( ansi.Method) {
	.mu.Lock()
	defer .mu.Unlock()
	.widthMethodOverride = true
	.setWidthMethod()
}

// setWidthMethod propagates the width method to the window/buffer and the
// renderer. Callers must hold s.mu.
func ( *TerminalScreen) ( ansi.Method) {
	.win.SetWidthMethod()
	.rend.SetWidthMethod()
}

// requestGraphemeWidth queues a DECRQM request for Unicode core mode (DEC mode
// 2027) so the terminal reports whether it measures cell width using grapheme
// clustering. The response arrives as a [ModeReportEvent].
func ( *TerminalScreen) () {
	.mu.Lock()
	defer .mu.Unlock()
	.buf.WriteString(ansi.RequestMode(ansi.ModeUnicodeCore))
}

// enableGraphemeWidth enables Unicode core mode (DEC mode 2027) on the terminal
// and switches the screen's width method to [ansi.GraphemeWidth] so wide-glyph
// measurement matches the terminal. The change propagates to the
// window/buffer and renderer.
//
// If the application has explicitly set a width method via
// [TerminalScreen.SetWidthMethod], the explicit choice is preserved and this is
// a no-op. The change is committed to the underlying writer through the
// screen's normal locked write path so it cannot race with Render/Flush.
func ( *TerminalScreen) () {
	.mu.Lock()
	if .widthMethodOverride {
		.mu.Unlock()
		return
	}
	.buf.WriteString(ansi.SetMode(ansi.ModeUnicodeCore))
	.setWidthMethod(ansi.GraphemeWidth)
	.rend.SetGraphemeWidth(true)
	.mu.Unlock()
	_ = .Flush()
}

// SetColorProfile sets the color profile for the terminal screen.
// This is automatically detected when creating the terminal screen. However,
// you can override it using this method.
func ( *TerminalScreen) ( colorprofile.Profile) {
	.profile = 
	.rend.SetColorProfile()
}

// Resize resizes the terminal screen to the specified width and height,
// updating the render buffer and renderer accordingly.
func ( *TerminalScreen) (,  int) {
	.win.Resize(, )
	.rbuf.Resize(, )
	.rend.Resize(, )
	.rend.Erase()
	.rbuf.Touched = nil
}

// Display clears the screen and draws the given [Drawable] onto the terminal
// screen and flushes the changes to the underlying writer.
//
// This is a convenience method that combines [TerminalScreen.Render] and
// [TerminalScreen.Flush].
func ( *TerminalScreen) ( Drawable) error {
	if  != nil {
		.win.Clear()
		.Draw(, .win.Bounds())
	}
	.Render()
	return .Flush()
}

// Render renders changes that transform the screen from its current state to
// the state represented by the [TerminalScreen].
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) () {
	.mu.Lock()
	defer .mu.Unlock()
	for  := 0;  < .win.Height(); ++ {
		for  := 0;  < .win.Width(); {
			 := .win.CellAt(, )
			if  == nil || .IsZero() {
				++
				continue
			}
			.rbuf.SetCell(, , )
			 := .Width
			if  <= 0 {
				 = 1
			}
			 += 
		}
	}
	.rend.Render(.rbuf)
	_ = .rend.Flush()
}

// Flush writes any pending output to the underlying writer.
func ( *TerminalScreen) () error {
	.mu.Lock()
	defer .mu.Unlock()
	if .cursor != nil && !.cursor.Hidden && .cursor.X >= 0 && .cursor.Y >= 0 {
		.rend.MoveTo(.cursor.X, .cursor.Y)
	} else if !.altScreen {
		// We don't want the cursor to be dangling at the end of the line in
		// inline mode because it can cause unwanted line wraps in some
		// terminals. So we move it to the beginning of the next line if
		// necessary.
		// This is only needed when the cursor is hidden because when it's
		// visible, we already set its position above.
		,  := .rend.Position()
		if  >= .win.Width()-1 {
			.rend.MoveTo(0, )
		}
	}

	var  bytes.Buffer
	.Grow(.buf.Len())

	if .buf.Len() > 0 {
		if .syncUpdates {
			.Grow(len(ansi.SetModeSynchronizedOutput) + len(ansi.ResetModeSynchronizedOutput))

			// If synchronized updates are enabled, we need to wrap the output in
			// the appropriate control sequences to ensure that the terminal treats
			// it as a single atomic update. This is necessary to prevent flickering
			// and other visual artifacts that can occur when multiple updates are sent
			// separately.
			.WriteString(ansi.SetModeSynchronizedOutput)
		} else if .cursor != nil && !.cursor.Hidden {
			.Grow(len(ansi.HideCursor) + len(ansi.ShowCursor))

			// If synchronized updates are not enabled, we need to ensure that
			// the cursor is hidden before writing any output to prevent
			// unwanted cursor visual artifacts.
			.WriteString(ansi.HideCursor)
		}

		.Write(.buf.Bytes())

		if .syncUpdates {
			.WriteString(ansi.ResetModeSynchronizedOutput)
		} else if .cursor != nil && !.cursor.Hidden {
			.WriteString(ansi.ShowCursor)
		}
	}

	,  := .w.Write(.Bytes())
	if  != nil {
		return 
	}
	.buf.Reset()
	return nil
}

// EnterAltScreen switches the terminal to the alternate screen buffer, allowing
// applications to use a separate screen for their output without affecting the
// main screen.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) () {
	var  strings.Builder
	.WriteString(ansi.SetModeAltScreenSaveCursor)
	if .cursor == nil || .cursor.Hidden {
		.WriteString(ansi.HideCursor)
	} else if .cursor != nil && !.cursor.Hidden {
		.WriteString(ansi.ShowCursor)
	}
	if .keyboardEnhancements != nil {
		EncodeKeyboardEnhancements(&, .keyboardEnhancements)
	}
	.buf.WriteString(.String())

	if !.altScreen {
		.rend.SaveCursor()
		.rend.Erase()
		.rend.SetFullscreen(true)
		.rend.SetRelativeCursor(false)
		.altScreen = true
	}
}

// ExitAltScreen switches the terminal back to the main screen buffer, restoring
// the previous screen state.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) () {
	var  strings.Builder
	.WriteString(ansi.ResetModeAltScreenSaveCursor)
	if .cursor == nil || .cursor.Hidden {
		.WriteString(ansi.HideCursor)
	} else if .cursor != nil && !.cursor.Hidden {
		.WriteString(ansi.ShowCursor)
	}
	if .keyboardEnhancements != nil {
		EncodeKeyboardEnhancements(&, .keyboardEnhancements)
	}
	.buf.WriteString(.String())

	if .altScreen {
		.rend.RestoreCursor()
		.rend.Erase()
		.rend.SetFullscreen(false)
		.rend.SetRelativeCursor(true)
		.altScreen = false
	}
}

// AltScreen returns whether the terminal is currently in the alternate screen
// buffer.
func ( *TerminalScreen) () bool {
	return .altScreen
}

// HideCursor hides the terminal cursor.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) () {
	.buf.WriteString(ansi.HideCursor)
	if .cursor != nil {
		.cursor.Hidden = true
	}
}

// ShowCursor shows the terminal cursor.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) () {
	.buf.WriteString(ansi.ShowCursor)
	if .cursor != nil {
		.cursor.Hidden = false
	} else {
		.cursor = NewCursor(-1, -1)
	}
}

// CursorVisible returns whether the terminal cursor is currently visible.
func ( *TerminalScreen) () bool {
	return .cursor != nil && !.cursor.Hidden
}

// SetCursorPosition sets the position of the terminal cursor to the specified
// coordinates.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) (,  int) {
	if .cursor == nil {
		.cursor = NewCursor(, )
		.cursor.Hidden = true
	} else {
		.cursor.X = 
		.cursor.Y = 
	}
}

// CursorPosition returns the last set cursor position of the terminal. If the
// cursor position is not set, it returns (-1, -1).
//
// This can be affected by [TerminalScreen.Render] and
// [TerminalScreen.SetCursorPosition] calls.
func ( *TerminalScreen) () (,  int) {
	if .cursor != nil {
		return .cursor.X, .cursor.Y
	}
	return -1, -1
}

// SetCursorStyle sets the style of the terminal cursor.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) ( CursorShape,  bool) {
	EncodeCursorStyle(.buf, , )
	if .cursor == nil {
		.cursor = NewCursor(-1, -1)
	}
	.cursor.Shape = 
	.cursor.Blink = 
}

// CursorStyle returns the current style of the terminal cursor.
func ( *TerminalScreen) () ( CursorShape,  bool) {
	if .cursor != nil {
		return .cursor.Shape, .cursor.Blink
	}
	return CursorBlock, true
}

// SetCursorColor sets the color of the terminal cursor.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) ( color.Color) {
	EncodeCursorColor(.buf, )
	if .cursor == nil {
		.cursor = NewCursor(-1, -1)
	}
	.cursor.Color = 
}

// CursorColor returns the current color of the terminal cursor.
//
// A nil color indicates that the cursor color is the default terminal cursor
// color.
func ( *TerminalScreen) () color.Color {
	if .cursor != nil {
		return .cursor.Color
	}
	return nil
}

// SetBackgroundColor sets the background color of the terminal.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) ( color.Color) {
	EncodeBackgroundColor(.buf, )
	.backgroundColor = 
}

// BackgroundColor returns the current background color of the terminal.
//
// A nil color indicates that the background color is the default terminal
// background color.
func ( *TerminalScreen) () color.Color {
	return .backgroundColor
}

// SetForegroundColor sets the foreground color of the terminal.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) ( color.Color) {
	EncodeForegroundColor(.buf, )
	.foregroundColor = 
}

// ForegroundColor returns the current foreground color of the terminal.
//
// A nil color indicates that the foreground color is the default terminal
// foreground color.
func ( *TerminalScreen) () color.Color {
	return .foregroundColor
}

// EnableBracketedPaste enables bracketed paste mode, allowing the terminal to
// distinguish between pasted content and user input.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) () {
	.buf.WriteString(ansi.SetModeBracketedPaste)
	.bracketedPaste = true
}

// DisableBracketedPaste disables bracketed paste mode.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) () {
	.buf.WriteString(ansi.ResetModeBracketedPaste)
	.bracketedPaste = false
}

// BracketedPaste returns whether bracketed paste mode is currently enabled.
func ( *TerminalScreen) () bool {
	return .bracketedPaste
}

// SetSynchronizedUpdates sets whether to use synchronized updates (mode 2026),
// which allows applications to batch updates to the terminal screen and flush
// them all at once for improved performance.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) ( bool) {
	.syncUpdates = 
}

// SynchronizedUpdates returns whether synchronized updates (mode 2026) are
// currently enabled.
func ( *TerminalScreen) () bool {
	return .syncUpdates
}

// SetMouseMode sets the mouse tracking mode for the terminal, allowing
// applications to receive mouse events.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) ( MouseMode) {
	EncodeMouseMode(.buf, )
	.mouseMode = 
}

// MouseMode returns the current mouse tracking mode of the terminal.
func ( *TerminalScreen) () MouseMode {
	return .mouseMode
}

// SetMouseEncoding sets the mouse encoding for the terminal.
// The encoding determines how mouse coordinates and buttons are reported.
// This is only meaningful when mouse tracking is enabled via [TerminalScreen.SetMouseMode].
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) ( MouseEncoding) {
	EncodeMouseEncoding(.buf, )
	.mouseEncoding = 
}

// MouseEncoding returns the current mouse encoding of the terminal.
func ( *TerminalScreen) () MouseEncoding {
	return .mouseEncoding
}

// SetWindowTitle sets the title of the terminal window.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) ( string) {
	EncodeWindowTitle(.buf, )
	.windowTitle = 
}

// WindowTitle returns the current title of the terminal window.
func ( *TerminalScreen) () string {
	return .windowTitle
}

// SetKeyboardEnhancements sets the keyboard enhancements for the terminal,
// allowing applications to receive enhanced keyboard input.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) ( *KeyboardEnhancements) {
	EncodeKeyboardEnhancements(.buf, )
	.keyboardEnhancements = 
}

// KeyboardEnhancements returns the current keyboard enhancements of the terminal.
//
// A nil value indicates that no keyboard enhancements are currently enabled.
func ( *TerminalScreen) () *KeyboardEnhancements {
	return .keyboardEnhancements
}

// SetProgressBar sets the progress bar for the terminal, allowing applications
// to display progress information.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) ( *ProgressBar) {
	EncodeProgressBar(.buf, )
	.progressBar = 
}

// ProgressBar returns the current progress bar of the terminal.
//
// A nil value indicates that no progress bar is currently set.
func ( *TerminalScreen) () *ProgressBar {
	return .progressBar
}

// Reset resets the terminal screen to its default state, clearing the screen,
// switching back to the main screen buffer if necessary, and resetting all
// terminal settings to their defaults.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) () {
	var  strings.Builder

	 := .keyboardEnhancements != nil

	if .altScreen {
		if  {
			.WriteString(ansi.KittyKeyboard(0, 1))
		}
		.WriteString(ansi.ResetModeAltScreenSaveCursor)
	}
	if  {
		.WriteString(ansi.KittyKeyboard(0, 1))
	}
	if .mouseMode != MouseModeNone {
		EncodeMouseMode(&, MouseModeNone)
	}
	if .mouseEncoding != MouseEncodingLegacy {
		EncodeMouseEncoding(&, MouseEncodingLegacy)
	}

	if .cursor == nil || !.cursor.Hidden {
		.WriteString(ansi.ShowCursor)
	}
	if .cursor != nil {
		if .cursor.Shape != CursorBlock || !.cursor.Blink {
			.WriteString(ansi.SetCursorStyle(0))
		}
		if .cursor.Color != nil {
			.WriteString(ansi.ResetCursorColor)
		}
	}
	if .backgroundColor != nil {
		.WriteString(ansi.ResetBackgroundColor)
	}
	if .foregroundColor != nil {
		.WriteString(ansi.ResetForegroundColor)
	}
	if .bracketedPaste {
		.WriteString(ansi.ResetModeBracketedPaste)
	}
	if .windowTitle != "" {
		.WriteString(ansi.SetWindowTitle(""))
	}
	if .progressBar != nil && .progressBar.State != ProgressBarNone {
		.WriteString(ansi.ResetProgressBar)
	}

	.buf.WriteString(.String())

	// Go to the bottom of the screen.
	// We need to go to the bottom of the screen regardless of whether
	// we're in alt screen mode or not to avoid leaving the cursor in the
	// middle in terminals that don't support alt screen mode.
	//
	// This comes after resetting the screen state to ensure that moving the
	// cursor is the last thing we do, preventing any unwanted cursor movements
	// after resetting the screen.
	//
	// Note that both [TerminalScreen.rend] writes to [TerminalScreen.buf].
	.rend.MoveTo(0, .win.Height()-1)
}

// Restore restores the terminal screen to its previous state, applying any
// previous settings and state that were reset by the [TerminalScreen.Reset] method.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) () {
	var  strings.Builder

	if .resetTabs {
		.WriteString(ansi.SetTabEvery8Columns)
	}
	if .altScreen {
		.WriteString(ansi.SetModeAltScreenSaveCursor)
	}
	if .cursor != nil && !.cursor.Hidden {
		.WriteString(ansi.ShowCursor)
	} else {
		// Hide the cursor by default.
		.WriteString(ansi.HideCursor)
	}
	if .keyboardEnhancements != nil {
		EncodeKeyboardEnhancements(&, .keyboardEnhancements)
	}
	if .mouseMode != MouseModeNone {
		EncodeMouseMode(&, .mouseMode)
	}
	if .mouseEncoding != MouseEncodingLegacy {
		EncodeMouseEncoding(&, .mouseEncoding)
	}
	if .cursor != nil {
		if .cursor.Shape != CursorBlock || !.cursor.Blink {
			EncodeCursorStyle(&, .cursor.Shape, .cursor.Blink)
		}
		if .cursor.Color != nil {
			EncodeCursorColor(&, .cursor.Color)
		}
	}
	if .backgroundColor != nil {
		EncodeBackgroundColor(&, .backgroundColor)
	}
	if .foregroundColor != nil {
		EncodeForegroundColor(&, .foregroundColor)
	}
	if .bracketedPaste {
		.WriteString(ansi.SetModeBracketedPaste)
	}
	if .windowTitle != "" {
		EncodeWindowTitle(&, .windowTitle)
	}
	if .progressBar != nil && .progressBar.State != ProgressBarNone {
		EncodeProgressBar(&, .progressBar)
	}

	.buf.WriteString(.String())

	// This needs to be called after restoring the screen state and writing to
	// the buffer.
	//
	// [TerminalScreen.Render] will write to [TerminalScreen.buf], so we need
	// to call it after writing the restore commands to the buffer to ensure
	// that the restore commands are included in the render output. This
	// ensures that the screen is properly restored before rendering any
	// changes.
	.Render()

	// Cursor position will be restored by the caller after calling
	// [TerminalScreen.Flush].
}

// Write writes data to the underlying buffer queuing it for output.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) ( []byte) ( int,  error) {
	return .buf.Write()
}

// WriteString writes a string to the underlying buffer queuing it for output.
//
// The changes can be committed to the underlying writer by calling the
// [TerminalScreen.Flush] method.
func ( *TerminalScreen) ( string) ( int,  error) {
	return .buf.WriteString()
}

// InsertAbove inserts content above the screen pushing the current content
// down.
//
// This is useful for inserting content above the current screen content
// without affecting the current cursor position or screen state.
//
// Note that this won't have any visible effect if the screen is in alt screen
// mode, as the content will be inserted above the alt screen buffer, which is
// not visible. However, if the screen is in inline mode, the content will be
// inserted above and will not be managed by the renderer.
//
// Unlike other methods that modify the screen state, this method writes
// directly to the underlying writer, so there is no need to call
// [TerminalScreen.Flush] after calling this method.
func ( *TerminalScreen) ( string) error {
	if len() == 0 {
		return nil
	}

	var  strings.Builder
	,  := .win.Width(), .win.Height()
	,  := .rend.Position()

	// We need to scroll the screen up by the number of lines in the queue.
	.WriteByte('\r')
	 :=  -  - 1
	if  > 0 {
		.WriteString(ansi.CursorDown())
	}

	 := strings.Split(, "\n")
	 := len()
	for ,  := range  {
		 := .win.WidthMethod().StringWidth()
		if  > 0 &&  >  {
			 += ( / )
		}
	}

	// Scroll the screen up by the offset to make room for the new lines.
	.WriteString(strings.Repeat("\n", ))

	// XXX: Now go to the top of the screen, insert new lines, and write
	// the queued strings. It is important to use [Screen.moveCursor]
	// instead of [Screen.move] because we don't want to perform any checks
	// on the cursor position.
	 :=  +  - 1
	.WriteString(ansi.CursorUp())
	.WriteString(ansi.InsertLine())
	for ,  := range  {
		.WriteString()
		.WriteString(ansi.EraseLineRight)
		.WriteString("\r\n")
	}

	.rend.SetPosition(0, 0)

	,  := io.WriteString(.w, .String())
	return 
}