package gitgraph

import (
	"fmt"
	"html"
	"math"
	"strings"
)

// SVG tekent de lanelijnen met afgeronde 90-graden bochten.
// Alleen getallen en paletkleuren, veilig als HTML. De knopen zelf
// zijn de avatars in de HTML, niet de SVG.
func (g *Graph) SVG() string {
	if g == nil || len(g.Rows) == 0 || g.Lanes < 1 {
		return ""
	}
	w, h := g.Width, g.Height
	var b strings.Builder
	// Geen viewBox: 1 CSS-pixel = 1 tekenunit, zodat avatars en lijnen
	// dezelfde x gebruiken en de grafiek niet geschaald wordt.
	b.WriteString(fmt.Sprintf(`<svg class="commitgraph-svg" width="%d" height="%d" style="width:%dpx;height:%dpx;left:%dpx" aria-hidden="true">`, w, h, w, h, RefW))
	for _, e := range g.Edges {
		col := safeColor(e.Color)
		cls := ColorClass(e.Color)
		x1, y1 := laneX(e.FromLane), rowY(e.FromRow)
		x2, y2 := laneX(e.ToLane), rowY(e.ToRow)
		d := orthogonalPath(x1, y1, x2, y2, Corner)
		fmt.Fprintf(&b, `<path d="%s" fill="none" stroke="%s" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"`, d, col)
		if cls != "" {
			fmt.Fprintf(&b, ` class="%s"`, cls)
		}
		if e.Branch != "" {
			fmt.Fprintf(&b, ` data-branch="%s"`, html.EscapeString(e.Branch))
		}
		b.WriteString(`/>`)
	}
	b.WriteString(`</svg>`)
	return b.String()
}

// orthogonalPath gaat verticaal, dan horizontaal, dan weer verticaal,
// met afgeronde 90-graden bochten. Bij dezelfde lane is het een rechte lijn.
func orthogonalPath(x1, y1, x2, y2, r float64) string {
	if almostEq(x1, x2) {
		return fmt.Sprintf("M %.1f %.1f V %.1f", x1, y1, y2)
	}
	if almostEq(y1, y2) {
		return fmt.Sprintf("M %.1f %.1f H %.1f", x1, y1, x2)
	}
	// Vroege overstap: bocht halverwege de volgende rij, daarna verticaal in de doellane.
	turnY := y1 + float64(RowH)/2
	if (y2-y1) > 0 && turnY > y2-1 {
		turnY = (y1 + y2) / 2
	}
	dx := math.Abs(x2 - x1)
	up := math.Abs(turnY - y1)
	down := math.Abs(y2 - turnY)
	maxR := math.Min(r, dx/2)
	maxR = math.Min(maxR, up)
	maxR = math.Min(maxR, down)
	if maxR < 1 {
		// te krap voor een boog: alsnog een knik, zonder afronding
		return fmt.Sprintf("M %.1f %.1f V %.1f H %.1f V %.1f", x1, y1, turnY, x2, y2)
	}
	dir := 1.0
	if x2 < x1 {
		dir = -1
	}
	return fmt.Sprintf(
		"M %.1f %.1f V %.1f Q %.1f %.1f, %.1f %.1f H %.1f Q %.1f %.1f, %.1f %.1f V %.1f",
		x1, y1,
		turnY-maxR,
		x1, turnY, x1+dir*maxR, turnY,
		x2-dir*maxR,
		x2, turnY, x2, turnY+maxR,
		y2,
	)
}

func almostEq(a, b float64) bool {
	return math.Abs(a-b) < 0.05
}

func laneX(lane int) float64 {
	return float64(lane)*float64(LaneW) + float64(LaneW)/2
}

func rowY(row int) float64 {
	return float64(row)*float64(RowH) + float64(RowH)/2
}

func safeColor(c string) string {
	c = strings.TrimSpace(c)
	if c == "var(--blue)" || c == "var(--muted)" {
		return html.EscapeString(c)
	}
	if strings.HasPrefix(c, "var(--graph-") && strings.HasSuffix(c, ")") {
		mid := c[len("var(--graph-") : len(c)-1]
		if len(mid) == 1 && mid[0] >= '0' && mid[0] < '0'+byte(PaletteSize) {
			return html.EscapeString(c)
		}
	}
	return "var(--muted)"
}
