package gitgraph

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

// SVG tekent de lanelijnen. Alleen getallen en paletkleuren, veilig als HTML.
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
	b.WriteString(fmt.Sprintf(`<svg class="commitgraph-svg" viewBox="0 0 %d %d" width="%d" height="%d" aria-hidden="true">`, w, h, w, h))
	for _, e := range g.Edges {
		col := safeColor(e.Color)
		x1, y1 := laneX(e.FromLane), rowY(e.FromRow)
		x2, y2 := laneX(e.ToLane), rowY(e.ToRow)
		if e.FromLane == e.ToLane {
			fmt.Fprintf(&b, `<path d="M %.1f %.1f V %.1f" fill="none" stroke="%s" stroke-width="2" stroke-linecap="round"/>`, x1, y1, y2, col)
			continue
		}
		// Boog tussen lanes: horizontaal op halve rij, dan verticaal.
		midY := y1 + float64(RowH)/2
		if e.ToRow == e.FromRow+1 {
			// korte merge/fork naar de volgende rij
			fmt.Fprintf(&b, `<path d="M %.1f %.1f C %.1f %.1f, %.1f %.1f, %.1f %.1f" fill="none" stroke="%s" stroke-width="2" stroke-linecap="round"/>`,
				x1, y1, x1, midY, x2, midY, x2, y2, col)
			continue
		}
		fmt.Fprintf(&b, `<path d="M %.1f %.1f C %.1f %.1f, %.1f %.1f, %.1f %.1f V %.1f" fill="none" stroke="%s" stroke-width="2" stroke-linecap="round"/>`,
			x1, y1, x1, midY, x2, midY, x2, y1+float64(RowH), y2, col)
	}
	for i, r := range g.Rows {
		fmt.Fprintf(&b, `<circle cx="%.1f" cy="%.1f" r="%.1f" fill="%s"/>`, laneX(r.Lane), rowY(i), DotR, safeColor(r.Color))
	}
	b.WriteString(`</svg>`)
	return b.String()
}

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)"
}
