package gitgraph

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

// SVG tekent lanelijnen en commitknopen (avatars) in één coördinatenstelsel.
// Geen style-attributen: CSP style-src is 'self' zonder unsafe-inline.
// 1 CSS-pixel = 1 tekenunit (geen viewBox), zodat knopen op de lane-x blijven.
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" width="%d" height="%d" aria-hidden="true">`, w, h))
	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(`/>`)
	}
	writeSVGNodes(&b, g.Rows, g.CommitBase)
	b.WriteString(`</svg>`)
	return b.String()
}

func writeSVGNodes(b *strings.Builder, rows []Row, commitBase string) {
	var clips strings.Builder
	for i, r := range rows {
		if r.Avatar == "" {
			continue
		}
		x, y := laneX(r.Lane), rowY(i)
		fmt.Fprintf(&clips, `<clipPath id="cg-a-%d"><circle cx="%.1f" cy="%.1f" r="%.0f"/></clipPath>`, i, x, y, DotR)
	}
	if clips.Len() > 0 {
		b.WriteString(`<defs>`)
		b.WriteString(clips.String())
		b.WriteString(`</defs>`)
	}
	for i, r := range rows {
		x, y := laneX(r.Lane), rowY(i)
		b.WriteString(`<a class="commitgraph-node`)
		if r.Class != "" {
			fmt.Fprintf(b, ` %s`, html.EscapeString(r.Class))
		}
		b.WriteByte('"')
		if commitBase != "" && r.SHA != "" {
			fmt.Fprintf(b, ` href="%s"`, html.EscapeString(commitBase+r.SHA))
		}
		if r.Branch != "" {
			fmt.Fprintf(b, ` data-branch="%s"`, html.EscapeString(r.Branch))
		}
		if tip := r.Tip; tip != "" {
			fmt.Fprintf(b, ` aria-label="%s"`, html.EscapeString(tip))
		}
		b.WriteByte('>')
		if r.Tip != "" {
			fmt.Fprintf(b, `<title>%s</title>`, html.EscapeString(r.Tip))
		}
		col := safeColor(r.Color)
		cls := ColorClass(r.Color)
		fmt.Fprintf(b, `<circle cx="%.1f" cy="%.1f" r="%.0f" fill="%s"`, x, y, DotR, col)
		if cls != "" {
			fmt.Fprintf(b, ` class="%s"`, cls)
		}
		b.WriteString(`/>`)
		if r.Avatar != "" {
			fmt.Fprintf(b, `<image href="%s" x="%.1f" y="%.1f" width="%.0f" height="%.0f" clip-path="url(#cg-a-%d)" preserveAspectRatio="xMidYMid slice"/>`,
				html.EscapeString(r.Avatar), x-DotR, y-DotR, DotR*2, DotR*2, i)
		} else if init := nodeInitial(r.Initial); init != "" {
			fmt.Fprintf(b, `<text x="%.1f" y="%.1f" text-anchor="middle" dominant-baseline="central" fill="#fff" font-size="9" font-weight="700">%s</text>`, x, y, init)
		}
		b.WriteString(`</a>`)
	}
}

func nodeInitial(s string) string {
	s = strings.TrimSpace(s)
	if s == "" {
		return ""
	}
	for _, r := range s {
		return html.EscapeString(string(r))
	}
	return ""
}

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