package sparkline

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"
)

func loadGolden(t *testing.T, name string) string {
	t.Helper()
	b, err := os.ReadFile(filepath.Join("testdata", name))
	if err != nil {
		t.Fatalf("read golden %s: %v", name, err)
	}
	return strings.TrimRight(string(b), "\n")
}

func TestSparkline_Empty(t *testing.T) {
	got := strings.TrimRight(string(RenderSparkline(nil, 80, 20)), "\n")
	want := loadGolden(t, "empty.svg")
	if got != want {
		t.Errorf("empty sparkline mismatch:\nwant:\n%s\ngot:\n%s", want, got)
	}
}

func TestSparkline_SinglePoint(t *testing.T) {
	got := strings.TrimRight(string(RenderSparkline([]float64{100}, 80, 20)), "\n")
	want := loadGolden(t, "single_point.svg")
	if got != want {
		t.Errorf("single_point sparkline mismatch:\nwant:\n%s\ngot:\n%s", want, got)
	}
}

func TestSparkline_ThreePoints(t *testing.T) {
	got := strings.TrimRight(string(RenderSparkline([]float64{10, 30, 20}, 80, 20)), "\n")
	want := loadGolden(t, "three_points.svg")
	if got != want {
		t.Errorf("three_points sparkline mismatch:\nwant:\n%s\ngot:\n%s", want, got)
	}
}

func TestChart_Empty(t *testing.T) {
	got := strings.TrimRight(string(RenderChart(nil, nil, ChartOpts{Width: 600, Height: 220})), "\n")
	want := loadGolden(t, "chart_empty.svg")
	if got != want {
		t.Errorf("empty chart mismatch:\nwant:\n%s\ngot:\n%s", want, got)
	}
}

func TestChart_TwoSeries(t *testing.T) {
	days := []time.Time{
		time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC),
		time.Date(2026, 5, 2, 0, 0, 0, 0, time.UTC),
		time.Date(2026, 5, 3, 0, 0, 0, 0, time.UTC),
		time.Date(2026, 5, 4, 0, 0, 0, 0, time.UTC),
	}
	series := []Series{
		{
			Name: "size", Stroke: "#3b82f6", Axis: AxisLeft, Format: FormatBytes,
			Points: []float64{1024, 2048, 4096, 8192},
		},
		{
			Name: "snapshots", Stroke: "#f59e0b", Axis: AxisRight, Format: FormatCount,
			Points: []float64{1, 2, 3, 4},
		},
	}
	got := strings.TrimRight(string(RenderChart(series, days, ChartOpts{Width: 600, Height: 220})), "\n")
	want := loadGolden(t, "chart_two_series.svg")
	if got != want {
		t.Errorf("two_series chart mismatch:\nwant:\n%s\ngot:\n%s", want, got)
	}
}
