package display

import (
	
	

	
	
	
	
	
	
)

// Refresh recomputes and redisplays the entire readline interface, except
// the first lines of the primary prompt when the latter is a multiline one.
func ( *Engine) () {
	// Buffer the whole frame and flush once, so the terminal never shows a
	// partial repaint and we issue a single write instead of dozens.
	term.BeginBuffer()
	defer term.EndBuffer()

	// 1. Preparation & Coordinates
	term.WriteString(term.HideCursor)
	// Go back to the first column, and if the primary prompt
	// was not printed yet, back up to the line's beginning row.
	term.MoveCursorBackwards(term.GetWidth())

	if !.primaryPrinted {
		term.MoveCursorUp(.cursorRow)
	}
	// 2. Primary Prompt
	.prompt.LastPrint()
	// Compute Coordinates: StartPos, LineHeight, CursorPos (row/col).
	.computeCoordinates(true)

	// Ensure that the indicator is printed if the prompt is empty,
	// and that we have enough space to print the line.
	.ensureIndicatorSpace()

	// Recompute coordinates with the new indentation/cursor position.
	if .line.Lines() > 0 {
		.cursorCol, .cursorRow = core.CoordinatesCursor(.cursor, .startCols)
		.lineCol, .lineRows = core.CoordinatesLine(.coordinatesLine(true), .startCols)
	}

	// Ensure that we have enough space to print the line.
	// We probe the terminal to verify that we are not at the bottom of the screen.
	// If we are, we scroll the screen to make space for the line.
	.ensureInputSpace()

	// Keep a multi-line prompt's upper lines correct now that the start row is
	// settled: they are printed only once and not otherwise refreshed, so a
	// scroll (typically at the bottom of the window) would leave them stale.
	.repaintPromptUpperLines()

	// 3. Input Area Rendering
	.renderInputArea()

	// 4. Helpers Rendering
	// We clear everything below the input area to ensure that no artifacts
	// from previous renders (like longer lines or helpers) remain visible.
	//
	// We need to move one row below the input, clear everything there, and
	// come back. However, CUD (\x1b[1B) is a no-op on the last terminal
	// row, so we check whether we're already at the bottom. If we are,
	// there's nothing below to clear and we can skip. If we're not, we use
	// CUD + clear + CUU to clean up artifacts from previous renders.
	 := term.GetLength()
	 := (.startRows + .lineRows) >= 

	if ! {
		term.MoveCursorDown(1)
		term.MoveCursorBackwards(term.GetWidth())
		term.WriteString(term.ClearScreenBelow)
		term.MoveCursorUp(1)
		term.MoveCursorForwards(.lineCol)
	}

	.renderHelpers()

	// 5. Final Cursor Positioning
	// The cursor is currently at the end of the input line (lineRows, lineCol).
	// We need to move it to the actual cursor position (cursorRow, cursorCol).
	if .lineRows > .cursorRow {
		term.MoveCursorUp(.lineRows - .cursorRow)
	}

	term.MoveCursorBackwards(term.GetWidth())
	term.MoveCursorForwards(.cursorCol)

	term.WriteString(term.ShowCursor)
}

// repaintPromptUpperLines reprints the upper lines of a multi-line prompt at
// the (now settled) start row. Those lines are printed only once initially and
// are not otherwise refreshed, so when the view scrolls -- typically when the
// prompt sits at the bottom of the window -- they would be left stale or
// overwritten (issue #98 / reeflective/console#78). The cursor is at the
// input-line start on entry and is restored there on return.
func ( *Engine) () {
	 := .prompt.PrimaryUsed()
	if  == 0 {
		return
	}

	// Go to the first prompt row at column 0, repaint the upper lines (each
	// ends in a newline, leaving us at column 0 of the last prompt-line row),
	// then restore the cursor to the input-line start.
	term.MoveCursorBackwards(term.GetWidth())
	term.MoveCursorUp()
	.prompt.UpperPrint()
	term.MoveCursorForwards(.startCols)
}

func ( *Engine) () {
	.displayLine()
	.renderMultilineIndicators()
	.renderRightPrompt()
}

func ( *Engine) () {
	.completer.Autocomplete()

	// 1. Check if we have anything to print.
	 := ui.CoordinatesHint(.hint)
	 := .completer.Matches()
	 := .completer.DisplaySkipped()

	// Refresh() already cleared below the input line before calling us,
	// so no additional clear is needed here.

	if  == 0 && ( == 0 || ) {
		.hintRows = 0
		.compRows = 0

		return
	}

	term.WriteString(term.NewlineReturn)

	// 3. Display Hints
	ui.DisplayHint(.hint)
	.hintRows = ui.CoordinatesHint(.hint)

	// 4. Display Completions
	if  > 0 && ! {
		completion.Display(.completer, .AvailableHelperLines())
		.compRows = completion.Coordinates(.completer)
	} else {
		.completer.ResetUsedRows()
		.compRows = 0
	}

	// 5. Restore Cursor to the "bottom of input area"
	// The cursor is currently at the bottom of the helpers.
	// We need to move it back up to the line just below the input text.
	term.MoveCursorUp(.compRows)
	term.MoveCursorUp(.hintRows)
	term.MoveCursorUp(1)

	// We are now on the same row as the end of the input line,
	// but at column 0. We need to move to e.lineCol.
	term.MoveCursorForwards(.lineCol)
}

func ( *Engine) () {
	.prompt.RightPrint(.lineCol, true)

	// Restore cursor to the end of the input line.
	term.MoveCursorBackwards(term.GetWidth())
	term.MoveCursorForwards(.lineCol)
}

func ( *Engine) () {
	// Determine the width of the multiline indicator.
	// We need to ensure that the indentation of the input line is at least
	// as wide as the indicator, otherwise the indicator will overwrite the text
	// on subsequent lines.
	var  int
	if .opts.GetBool("multiline-column-numbered") {
		 = len(strconv.Itoa(1)) + 1
	} else {
		 = 2
	}

	// Adjust indentation if the primary prompt is empty,
	// because we will print a column indicator on the first line.
	if .prompt.LastUsed() == 0 && .line.Lines() > 0 {
		var  string
		if .opts.GetBool("multiline-column-numbered") {
			 = fmt.Sprintf(color.FgBlackBright+"%d"+color.Reset+" ", 1)
		} else {
			 = ui.DefaultMultilineColumn
		}

		.startCols += 
		// Print the indicator on the first line.
		term.WriteString()
	} else if .line.Lines() > 0 && .startCols <  {
		// If the prompt is shorter than the indicator, pad with spaces
		// to ensure the input text starts aligned with subsequent lines
		// and isn't overwritten by the indicator.
		 :=  - .startCols
		term.Printf("%*s", , "")

		.startCols = 
	}
}

func ( *Engine) () {
	// The input area occupies lineRows+1 visual rows starting at startRows, and
	// the redraw/helper machinery always steps one further row below it (e.g. the
	// "move down 1, clear below, move up 1" sequences). When the prompt is
	// rendered at the bottom of the window that trailing row does not exist: the
	// terminal clamps our downward moves while the paired upward moves still
	// travel, so the row bookkeeping drifts and the prompt's lines get
	// overwritten/overlapped (issue #98, reeflective/console#78).
	//
	// startRows was just probed in computeCoordinates, so we can tell purely from
	// it whether the area plus its trailing row runs past the bottom, and scroll
	// the screen up by exactly the missing rows (adjusting startRows to match)
	// without issuing another cursor-position query.
	// Reserving space requires the cursor's absolute row, which only the
	// cursor-position probe provides. When probing is disabled or unavailable
	// (startRows < 1), we cannot detect the bottom of the window, so we skip
	// this step -- the documented degraded behavior is that a prompt at the very
	// bottom may overlap (see disable-cursor-position-probe).
	if .startRows < 1 {
		return
	}

	 := .lineRows + 1

	 := (.startRows + ) - term.GetLength()
	if  <= 0 {
		return
	}

	// We are at the input-line start. Drop to the bottom of the input area
	// (clamped at the last row), emit newlines to scroll the screen up by the
	// deficit, then climb back to the new input-line start.
	term.MoveCursorDown(.lineRows)

	for range  {
		term.WriteString(term.NewlineReturn)
	}

	.startRows -= 

	term.MoveCursorUp()
	term.MoveCursorForwards(.startCols)
}

// displayLine renders the input line — highlighting, history-autosuggest and
// inline-suggestion suffixes, and tab expansion — at the current cursor row. It
// is the single line renderer shared by the main refresh path (renderInputArea)
// and the transient-prompt redraw (RefreshTransient).
func ( *Engine) () {
	var  string
	// Apply user-defined highlighter to the input line.
	if .highlighter != nil {
		 = .highlighter(*.line)
	} else {
		 = string(*.line)
	}
	// Highlight matching parenthesis
	if .opts.GetBool("blink-matching-paren") {
		core.HighlightMatchers(.selection)
		defer core.ResetMatchers(.selection)
	}
	// Apply visual selections highlighting if any
	 = .highlightLine([]rune(), *.selection)
	// Get the subset of the suggested line to print.
	 := false
	if len(.suggested) > .line.Len() && .opts.GetBool("history-autosuggest") {
		 += color.Dim + color.Fmt(color.Fg+"242") + string(.suggested[.line.Len():]) + color.Reset
		 = true
	}

	 := string(*.line)
	if ! && .inlineSuggestionApplies() {
		 += color.Dim + color.Fmt(color.Fg+"242") + .inline[len():] + color.Reset
	}

	// Format tabs as spaces, for consistent display. When the rendered input
	// lands exactly on the terminal's right edge (lineCol == 0), the cursor is
	// left in the terminal's pending-wrap state; emitting clear-to-end-of-line
	// there can erase the edge glyph, so skip it in that case.
	 := .lineCol == 0 && len() > 0
	 = strutil.FormatTabs()
	if ! {
		 += term.ClearLineAfter
	}

	// And display the line.
	.suggested.Set([]rune()...)
	core.DisplayLine(&.suggested, .startCols)

	// Force the pending wrap before any later clear/cursor-movement sequences,
	// so redraws do not overwrite the edge character or scroll one row per key.
	if  {
		term.WriteString(term.NewlineReturn)
	}
}

func ( *Engine) () {
	// Check if we have multiple lines to manage.
	if .line.Lines() == 0 {
		return
	}

	// 1. Determine if we need to print columns.
	 := .opts.GetBool("multiline-column") ||
		.opts.GetBool("multiline-column-numbered") ||
		.opts.GetString("multiline-column-custom") != ""
	 := .prompt.LastUsed() == 0

	// If no columns are requested and the prompt is not empty, we have nothing to do.
	if ! && ! {
		return
	}

	// 2. Move to the top of the input area (first line).
	term.MoveCursorUp(.lineRows)
	term.MoveCursorBackwards(term.GetWidth())

	// 3. Print the indicators for subsequent lines (1..N).
	 := 0
	 := .opts.GetBool("multiline-column-numbered")

	// Indicators
	 := ui.DefaultMultilineColumn

	for  := 1;  <= .line.Lines(); ++ {
		term.WriteString("\n")

		switch {
		case :
			term.Printf(color.FgBlackBright+"%d"+color.Reset+" ", +1)
		case  == .line.Lines():
			.prompt.SecondaryPrint()
		default:
			term.WriteString()
		}

		++
	}

	// 4. Return cursor to the bottom of the input area.
	 := .lineRows - 
	if  > 0 {
		term.MoveCursorDown()
	}

	// 5. Restore horizontal position to the end of the input text.
	term.MoveCursorBackwards(term.GetWidth())
	term.MoveCursorForwards(.lineCol)
}