package tcelllivepage

import (
	
	

	
)

// runKey identifies a run of cells rendered with the same style. The cursor is
// rendered as a separate run.
type runKey struct {
	style  tcell.Style
	cursor bool
}

// gridHTML returns the HTML snapshot of the last completed frame.
func ( *Screen) () string {
	.mu.Lock()
	defer .mu.Unlock()

	// Fallback for direct calls before the first Show.
	if .html == "" {
		.html = .renderGrid()
		.dirty = false
	}
	return .html
}

// renderGrid converts the current tcell grid into HTML. Cells are grouped into
// spans of equal style.
func ( *Screen) () string {
	,  := .Size()
	if  <= 0 ||  <= 0 {
		return `<div class="tcell-grid"></div>`
	}

	var  strings.Builder
	// Rough estimate: a space per cell, plus some markup.
	.Grow(* + *64 + 128)

	.WriteString(`<div class="tcell-grid">`)
	.WriteString(`<span class="tcell-probe" aria-hidden="true">M</span>`)

	, ,  := .GetCursor()

	var (
		    strings.Builder
		    runKey
		 bool
	)
	 := func() {
		if ! {
			return
		}
		 := .String()
		 = false
		.Reset()
		if  == "" {
			return
		}
		writeSpan(&, , .styleCSS(.style), .cursor, 0)
	}

	for  := 0;  < ; ++ {
		.WriteString(`<div class="tcell-row">`)
		for  := 0;  < ; {
			, ,  := .Get(, )
			if  < 1 {
				 = 1
			}
			 :=  &&  ==  &&  == 

			// Wide graphemes are wrapped to enforce their cell width, as font
			// fallbacks may render them narrower than two cells.
			if  > 1 {
				()
				writeSpan(&, , .styleCSS(), , )
				 += 
				continue
			}

			 := runKey{style: , cursor: }
			if  &&  !=  {
				()
			}
			if ! {
				 = 
				 = true
			}
			.WriteString()
			 += 
		}
		()
		.WriteString(`</div>`)
	}

	.WriteString(`</div>`)
	return .String()
}

// writeSpan writes a styled span. A non-zero width marks a wide cell, which is
// enforced via CSS to keep the grid aligned.
func writeSpan( *strings.Builder, ,  string,  bool,  int) {
	if  == "" {
		return
	}

	 := ""
	if  > 1 {
		 = "tc-wide"
	}
	if  {
		if  != "" {
			 += " "
		}
		 += "tc-cursor"
	}

	if  == "" &&  == "" {
		writeEscaped(, )
		return
	}

	.WriteString(`<span`)
	if  != "" {
		.WriteString(` class="`)
		.WriteString()
		.WriteString(`"`)
	}
	if  != "" ||  > 1 {
		.WriteString(` style="`)
		if  > 1 {
			.WriteString("width:")
			.WriteString(strconv.Itoa())
			.WriteString("ch;")
		}
		.WriteString()
		.WriteString(`"`)
	}
	.WriteString(`>`)
	writeEscaped(, )
	.WriteString(`</span>`)
}

// styleCSS converts a tcell style into a CSS style. Default colors are omitted
// to keep the HTML small.
func ( *Screen) ( tcell.Style) string {
	if ,  := .styles[];  {
		return 
	}

	, ,  := .Decompose()
	if &tcell.AttrReverse != 0 {
		,  = , 
	}

	var  strings.Builder
	if  := colorHex(, .theme.Fg);  != .theme.Fg.CSS() {
		.WriteString("color:")
		.WriteString()
		.WriteString(";")
	}
	if  := colorHex(, .theme.Bg);  != .theme.Bg.CSS() {
		.WriteString("background-color:")
		.WriteString()
		.WriteString(";")
	}

	var  []string
	if &tcell.AttrUnderline != 0 {
		 = append(, "underline")
	}
	if &tcell.AttrStrikeThrough != 0 {
		 = append(, "line-through")
	}
	if len() > 0 {
		.WriteString("text-decoration:")
		.WriteString(strings.Join(, " "))
		.WriteString(";")
	}
	if &tcell.AttrBold != 0 {
		.WriteString("font-weight:700;")
	}
	if &tcell.AttrDim != 0 {
		.WriteString("opacity:.7;")
	}
	if &tcell.AttrItalic != 0 {
		.WriteString("font-style:italic;")
	}
	if &tcell.AttrBlink != 0 {
		.WriteString("animation:tc-blink 1s step-end infinite;")
	}

	 := .String()
	.styles[] = 
	return 
}

// colorHex returns a CSS color, falling back to def for unset colors.
func colorHex(,  tcell.Color) string {
	if !.Valid() {
		 = 
	}
	return .CSS()
}

// writeEscaped writes s with HTML special characters escaped.
func writeEscaped( *strings.Builder,  string) {
	for  := 0;  < len(); ++ {
		switch [] {
		case '&':
			.WriteString("&amp;")
		case '<':
			.WriteString("&lt;")
		case '>':
			.WriteString("&gt;")
		case '"':
			.WriteString("&quot;")
		case '\'':
			.WriteString("&#39;")
		default:
			.WriteByte([])
		}
	}
}

// injectHead adds tags at the end of <head>, or at the start of the document.
func injectHead(,  string) string {
	 := strings.Index(strings.ToLower(), "</head>")
	if  < 0 {
		return  + 
	}
	return [:] +  + [:]
}