package table

import (
	
	

	
	
)

// resize resizes the table to fit the specified width.
//
// Given a user defined table width, we must ensure the table is exactly that
// width. This must account for all borders, column, separators, and column
// data.
//
// In the case where the table is narrower than the specified table width,
// we simply expand the columns evenly to fit the width.
// For example, a table with 3 columns takes up 50 characters total, and the
// width specified is 80, we expand each column by 10 characters, adding 30
// to the total width.
//
// In the case where the table is wider than the specified table width, we
// _could_ simply shrink the columns evenly but this would result in data
// being truncated (perhaps unnecessarily). The naive approach could result
// in very poor cropping of the table data. So, instead of shrinking columns
// evenly, we calculate the median non-whitespace length of each column, and
// shrink the columns based on the largest median.
//
// For example,
//
//	┌──────┬───────────────┬──────────┐
//	│ Name │ Age of Person │ Location │
//	├──────┼───────────────┼──────────┤
//	│ Kini │ 40            │ New York │
//	│ Eli  │ 30            │ London   │
//	│ Iris │ 20            │ Paris    │
//	└──────┴───────────────┴──────────┘
//
// Median non-whitespace length  vs column width of each column:
//
// Name: 4 / 5
// Age of Person: 2 / 15
// Location: 6 / 10
//
// The biggest difference is 15 - 2, so we can shrink the 2nd column by 13.
func ( *Table) () {
	 := len(.headers) > 0
	 := DataToMatrix(.data)
	 := newResizer(.width, .height, .headers, )
	.wrap = .wrap
	.borderColumn = .borderColumn
	.yPaddings = make([][]int, len(.allRows))

	.yOffset = .yOffset
	.useManualHeight = .useManualHeight
	.borderTop = .borderTop
	.borderBottom = .borderBottom
	.borderLeft = .borderLeft
	.borderRight = .borderRight
	.borderHeader = .borderHeader
	.borderRow = .borderRow

	var  [][]string
	if  {
		 = append([][]string{.headers}, ...)
	} else {
		 = 
	}

	 := .styleFunc
	if .styleFunc == nil {
		 = DefaultStyles
	}

	.rowHeights = .defaultRowHeights()

	for ,  := range  {
		.yPaddings[] = make([]int, len())

		for  := range  {
			 := &.columns[]

			// Making sure we're passing the right index to `styleFunc`. The header row should be `-1` and
			// the others should start from `0`.
			 := 
			if  {
				--
			}
			 := (, )

			.xPadding = max(.xPadding, .GetHorizontalFrameSize())
			.fixedWidth = max(.fixedWidth, .GetWidth())

			.rowHeights[] = max(.rowHeights[], .GetHeight())
			.yPaddings[][] = .GetVerticalFrameSize()
		}
	}

	switch {
	case .tableWidth <= 0:
		// A table width wasn't specified. In this case, detect according to
		// content width.
		.tableWidth = .detectTableWidth()
	case .fitContent:
		// Render at content width, treating the specified width as a maximum.
		if  := .detectTableWidth();  < .tableWidth {
			.tableWidth = 
		}
	}

	.widths, .heights = .optimizedWidths()
	.firstVisibleRowIndex, .lastVisibleRowIndex, .overflowHeight = .visibleRowIndexes()
}

// resizerColumn is a column in the resizer.
type resizerColumn struct {
	index      int
	min        int
	max        int
	median     int
	rows       [][]string
	xPadding   int // horizontal padding
	fixedWidth int
}

// resizer is a table resizer.
type resizer struct {
	tableWidth  int
	tableHeight int
	headers     []string
	allRows     [][]string
	rowHeights  []int
	columns     []resizerColumn

	wrap         bool
	borderColumn bool
	yPaddings    [][]int // vertical paddings

	yOffset         int
	useManualHeight bool
	borderTop       bool
	borderBottom    bool
	borderLeft      bool
	borderRight     bool
	borderHeader    bool
	borderRow       bool
}

// newResizer creates a new resizer.
func (,  int,  []string,  [][]string) *resizer {
	 := &resizer{
		tableWidth:  ,
		tableHeight: ,
		headers:     ,
	}

	if len() > 0 {
		.allRows = append([][]string{}, ...)
	} else {
		.allRows = 
	}

	for ,  := range .allRows {
		for ,  := range  {
			 := lipgloss.Width()

			// Header or first row. Just add as is.
			if len(.columns) <=  {
				.columns = append(.columns, resizerColumn{
					index:  ,
					min:    ,
					max:    ,
					median: ,
				})
				continue
			}

			.columns[].rows = append(.columns[].rows, )
			.columns[].min = min(.columns[].min, )
			.columns[].max = max(.columns[].max, )
		}
	}
	for  := range .columns {
		 := make([]int, len(.columns[].rows))
		for ,  := range .columns[].rows {
			[] = lipgloss.Width([])
		}
		.columns[].median = median()
	}

	return 
}

// optimizedWidths returns the optimized column widths and row heights.
func ( *resizer) () (,  []int) {
	if .maxTotal() <= .tableWidth {
		return .expandTableWidth(), .rowHeights
	}
	return .shrinkTableWidth(), .rowHeights
}

// detectTableWidth detects the table width.
func ( *resizer) () int {
	return .maxCharCount() + .totalHorizontalPadding() + .totalHorizontalBorder()
}

// expandTableWidth expands the table width.
func ( *resizer) () ( []int) {
	 = .maxColumnWidths()

	for {
		 := sum() + .totalHorizontalBorder()
		if  >= .tableWidth {
			break
		}

		 := 0
		 := math.MaxInt32

		for ,  := range  {
			if  == .columns[].fixedWidth {
				continue
			}
			if  <  {
				 = 
				 = 
			}
		}

		[]++
	}

	.expandRowHeights()

	return
}

// minWidth returns the minimum width floor for a column: horizontal padding
// plus at least 1 to ensure the "…" truncation marker or one character is
// always visible. A column must never shrink below this floor.
func ( *resizer) ( int) int {
	return .xPaddingForCol() + max(.columns[].min, 1)
}

// shrinkTableWidth shrinks the table width.
func ( *resizer) () ( []int) {
	 = .maxColumnWidths()

	// Cut width of columns that are way too big.
	 := func(,  bool) {
		for {
			 := sum() + .totalHorizontalBorder()
			if  <= .tableWidth {
				break
			}

			 := -math.MaxInt32
			 := -math.MaxInt32

			for ,  := range  {
				if  == .columns[].fixedWidth {
					continue
				}
				if  &&  <= .minWidth() {
					continue
				}
				if  {
					if  >= (.tableWidth/2) &&  >  { //nolint:mnd
						 = 
						 = 
					}
				} else {
					if  >  {
						 = 
						 = 
					}
				}
			}

			if  < 0 || [] == 0 {
				break
			}
			[]--
		}
	}

	// Cut width of columns that differ the most from the median.
	 := func( bool) {
		for {
			 := sum() + .totalHorizontalBorder()
			if  <= .tableWidth {
				break
			}

			 := -math.MaxInt32
			 := -math.MaxInt32

			for ,  := range  {
				if  == .columns[].fixedWidth {
					continue
				}
				if  &&  <= .minWidth() {
					continue
				}
				 :=  - .columns[].median
				if  > 0 &&  >  {
					 = 
					 = 
				}
			}

			if  <= 0 || [] == 0 {
				break
			}
			[]--
		}
	}

	// First pass: shrink respecting column minimum widths so short columns
	// don't collapse to zero.
	(true, true)
	(true)
	(false, true)

	// If the table is still too wide (e.g. impossible width budgets like
	// Width(1)), fall back to unreserved shrinking without a floor.
	if sum()+.totalHorizontalBorder() > .tableWidth {
		(true, false)
		(false)
		(false, false)
	}

	.expandRowHeights()

	return 
}

// expandRowHeights expands the row heights.
func ( *resizer) ( []int) {
	.rowHeights = .defaultRowHeights()
	if !.wrap {
		return
	}
	 := len(.headers) > 0

	for ,  := range .allRows {
		for ,  := range  {
			// NOTE(@andreynering): Headers always have a height of 1 (+ padding), even when wrap is enabled.
			if  &&  == 0 {
				.rowHeights[] = 1 + .yPaddingForCell(, )
				continue
			}
			 := .detectContentHeight(, []-.xPaddingForCol()) + .yPaddingForCell(, )
			.rowHeights[] = max(.rowHeights[], )
		}
	}
}

// defaultRowHeights returns the default row heights.
func ( *resizer) () ( []int) {
	 = make([]int, len(.allRows))
	for  := range  {
		if  < len(.rowHeights) {
			[] = .rowHeights[]
		}
		[] = max([], 1)
	}
	return
}

// maxColumnWidths returns the maximum column widths.
func ( *resizer) () []int {
	 := make([]int, len(.columns))
	for ,  := range .columns {
		if .fixedWidth > 0 {
			[] = .fixedWidth
		} else {
			[] = .max + .xPaddingForCol(.index)
		}
	}
	return 
}

// columnCount returns the column count.
func ( *resizer) () int {
	return len(.columns)
}

// maxCharCount returns the maximum character count.
func ( *resizer) () int {
	var  int
	for ,  := range .columns {
		if .fixedWidth > 0 {
			 += .fixedWidth - .xPaddingForCol(.index)
		} else {
			 += .max
		}
	}
	return 
}

// maxTotal returns the maximum total width.
func ( *resizer) () ( int) {
	for ,  := range .columns {
		if .fixedWidth > 0 {
			 += .fixedWidth
		} else {
			 += .max + .xPaddingForCol()
		}
	}
	return
}

// totalHorizontalPadding returns the total padding.
func ( *resizer) () ( int) {
	for ,  := range .columns {
		 += .xPadding
	}
	return
}

// xPaddingForCol returns the horizontal padding for a column.
func ( *resizer) ( int) int {
	if  >= len(.columns) {
		return 0
	}
	return .columns[].xPadding
}

// yPaddingForCell returns the horizontal padding for a cell.
func ( *resizer) (,  int) int {
	if  >= len(.yPaddings) ||  >= len(.yPaddings[]) {
		return 0
	}
	return .yPaddings[][]
}

// totalHorizontalBorder returns the total border.
func ( *resizer) () int {
	return btoi(.borderLeft) + btoi(.borderRight) + (.columnCount()-1)*btoi(.borderColumn)
}

// detectContentHeight detects the content height.
func ( *resizer) ( string,  int) ( int) {
	if  == 0 {
		return 1
	}
	 = strings.ReplaceAll(, "\r\n", "\n")
	for ,  := range strings.Split(, "\n") {
		 += strings.Count(ansi.Wrap(, , ""), "\n") + 1
	}
	return
}

// visibleRowIndexes calculates the indexes of the first and last visible rows
// according to the current yOffset and tableHeight. If the table height is not
// fixed or if the last row is visible, lastVisibleRowIndex will be -2.
// Note that the calculated indexes ignore the header row, so 0 corresponds to
// the first data row. The header row is always visible if it exists.
// The last return value is the number of cells that the overflow row should
// take up for the table to fill the available height.
func ( *resizer) () (, ,  int) {
	if !.useManualHeight {
		return 0, -2, 0
	}

	 := len(.headers) > 0
	 := len(.allRows) - 1 - btoi()

	// Account for fixed elements (top/bottom borders, headers with their border).
	 := .tableHeight - btoi(.borderTop) -
		btoi(.borderBottom) -
		bton(, .rowHeights[0]) -
		btoi( && .borderHeader)

	// The first row we add does not need a row border.
	 += btoi(.borderRow)

	// Start from the offset with no visible rows.
	 = .yOffset
	 =  - 1

	// First add rows at the bottom until we reach the available height, or the last row.
	for  > 0 &&  <  {
		 := .rowHeights[+1+btoi()] + btoi(.borderRow)
		 := bton(+1 < , 1+btoi(.borderRow)+.yPaddingForCell(+2, 0))

		if -- < 0 {
			break
		}

		++
		 -= 
	}

	if  ==  {
		// Then add rows at the top until we reach the available height, or the first row.
		for  > 0 &&  > 0 {
			 := .rowHeights[-1+btoi()] + btoi(.borderRow)

			if - < 0 {
				break
			}

			--
			 -= 
		}
	}

	if  >=  {
		return , -2, 0
	}

	 := 1 + .yPaddingForCell(+1, 0)

	return , , 
}