package world

import (
	"github.com/stretchr/testify/require"
	"image"
	"image/color"
	"testing"
)

// TestStyleOverrideApply_OverridesOnlyProvidedFields verifies style Override Apply Overrides Only Provided Fields.
func TestStyleOverrideApply_OverridesOnlyProvidedFields(t *testing.T) {
	t.Parallel()

	base := Style{
		FillColor:        color.RGBA{R: 1, A: 255},
		StrokeColor:      color.RGBA{G: 2, A: 255},
		StrokeWidthPx:    1.0,
		StrokeDashes:     []float64{3, 1},
		StrokeDashOffset: 0.5,
		PointRadiusPx:    2.0,
	}

	newWidth := 5.0
	newRadius := 7.0

	override := StyleOverride{
		StrokeWidthPx: &newWidth,
		PointRadiusPx: &newRadius,
		// Everything else is unset (nil) => must remain from base.
	}

	out := override.Apply(base)

	require.Equal(t, base.FillColor, out.FillColor)
	require.Equal(t, base.StrokeColor, out.StrokeColor)
	require.Equal(t, 5.0, out.StrokeWidthPx)
	require.Equal(t, base.StrokeDashes, out.StrokeDashes)
	require.Equal(t, base.StrokeDashOffset, out.StrokeDashOffset)
	require.Equal(t, 7.0, out.PointRadiusPx)
}

// TestStyleTable_DefaultsExistAndAreStable verifies style Table Defaults Exist And Are Stable.
func TestStyleTable_DefaultsExistAndAreStable(t *testing.T) {
	t.Parallel()

	tbl := NewStyleTable()

	_, ok := tbl.Get(StyleIDDefaultLine)
	require.True(t, ok)

	_, ok = tbl.Get(StyleIDDefaultCircle)
	require.True(t, ok)

	_, ok = tbl.Get(StyleIDDefaultPoint)
	require.True(t, ok)
}

// TestStyleTable_AddDerived_StoresResolvedStyleAndCopiesSlices verifies style Table Add Derived Stores Resolved Style And Copies Slices.
func TestStyleTable_AddDerived_StoresResolvedStyleAndCopiesSlices(t *testing.T) {
	t.Parallel()

	tbl := NewStyleTable()

	dashes := []float64{10, 5}
	override := StyleOverride{
		StrokeDashes: &dashes,
	}
	id := tbl.AddDerived(StyleIDDefaultLine, override)

	got, ok := tbl.Get(id)
	require.True(t, ok)
	require.Equal(t, []float64{10, 5}, got.StrokeDashes)

	// Mutate caller slice; table must not change.
	dashes[0] = 999

	got2, ok := tbl.Get(id)
	require.True(t, ok)
	require.Equal(t, []float64{10, 5}, got2.StrokeDashes)

	// Mutate returned slice; table must not change.
	got2.StrokeDashes[0] = 123

	got3, ok := tbl.Get(id)
	require.True(t, ok)
	require.Equal(t, []float64{10, 5}, got3.StrokeDashes)
}

// TestDefaultPriorities_AreOrderedAndStepped verifies default Priorities Are Ordered And Stepped.
func TestDefaultPriorities_AreOrderedAndStepped(t *testing.T) {
	t.Parallel()

	require.Equal(t, 100, DefaultPriorityLine)
	require.Equal(t, 200, DefaultPriorityCircle)
	require.Equal(t, 300, DefaultPriorityPoint)

	require.Less(t, DefaultPriorityLine, DefaultPriorityCircle)
	require.Less(t, DefaultPriorityCircle, DefaultPriorityPoint)
}

type cacheTheme struct{}

func (cacheTheme) ID() string                                 { return "cache" }
func (cacheTheme) Name() string                               { return "cache" }
func (cacheTheme) BackgroundColor() color.Color               { return color.RGBA{A: 255} }
func (cacheTheme) BackgroundImage() image.Image               { return nil }
func (cacheTheme) BackgroundTileMode() BackgroundTileMode     { return BackgroundTileNone }
func (cacheTheme) BackgroundScaleMode() BackgroundScaleMode   { return BackgroundScaleNone }
func (cacheTheme) BackgroundAnchorMode() BackgroundAnchorMode { return BackgroundAnchorWorld }
func (cacheTheme) PointStyle() Style                          { return Style{FillColor: color.RGBA{A: 255}, PointRadiusPx: 2} }
func (cacheTheme) LineStyle() Style                           { return Style{StrokeColor: color.RGBA{A: 255}, StrokeWidthPx: 1} }
func (cacheTheme) CircleStyle() Style {
	return Style{FillColor: color.RGBA{A: 255}, StrokeColor: color.RGBA{A: 255}, StrokeWidthPx: 1}
}
func (cacheTheme) PointClassOverride(PointClassID) (StyleOverride, bool) {
	return StyleOverride{}, false
}
func (cacheTheme) LineClassOverride(LineClassID) (StyleOverride, bool) { return StyleOverride{}, false }
func (cacheTheme) CircleClassOverride(CircleClassID) (StyleOverride, bool) {
	return StyleOverride{}, false
}

type cacheTheme2 struct{ cacheTheme }

func (cacheTheme2) ID() string   { return "cache2" }
func (cacheTheme2) Name() string { return "cache2" }
func (cacheTheme2) CircleStyle() Style {
	return Style{FillColor: color.RGBA{B: 200, A: 255}, StrokeColor: color.RGBA{A: 255}, StrokeWidthPx: 3}
}
func (cacheTheme2) PointClassOverride(PointClassID) (StyleOverride, bool) {
	return StyleOverride{}, false
}
func (cacheTheme2) LineClassOverride(LineClassID) (StyleOverride, bool) {
	return StyleOverride{}, false
}
func (cacheTheme2) CircleClassOverride(CircleClassID) (StyleOverride, bool) {
	return StyleOverride{}, false
}

// TestDerivedStyleCache_ReusesDerivedStylesAcrossObjectsAndThemes verifies derived Style Cache Reuses Derived Styles Across Objects And Themes.
func TestDerivedStyleCache_ReusesDerivedStylesAcrossObjectsAndThemes(t *testing.T) {
	t.Parallel()

	w := NewWorld(10, 10)
	w.SetTheme(cacheTheme{})

	before := w.styles.Count()

	white := color.RGBA{R: 255, G: 255, B: 255, A: 255}
	ov := StyleOverride{StrokeColor: white}

	id1, err := w.AddCircle(5, 5, 2, CircleWithStyleOverride(ov))
	require.NoError(t, err)
	id2, err := w.AddCircle(6, 5, 2, CircleWithStyleOverride(ov))
	require.NoError(t, err)

	c1 := w.objects[id1].(Circle)
	c2 := w.objects[id2].(Circle)
	require.Equal(t, c1.StyleID, c2.StyleID, "same override must reuse derived style ID")

	afterAdd := w.styles.Count()
	require.Equal(t, before+1, afterAdd, "only one derived style should be added for identical overrides")

	// Change theme: derived cache is cleared and new base IDs are created; override must still be applied,
	// and both objects should again share one derived style for the new base.
	w.SetTheme(cacheTheme2{})

	c1b := w.objects[id1].(Circle)
	c2b := w.objects[id2].(Circle)
	require.Equal(t, c1b.StyleID, c2b.StyleID)

	afterTheme := w.styles.Count()
	// Theme change creates 3 new theme default styles + 1 new derived for the override.
	require.GreaterOrEqual(t, afterTheme, afterAdd+4)
}

type testTheme struct{}

func (testTheme) ID() string   { return "t1" }
func (testTheme) Name() string { return "Theme1" }

func (testTheme) BackgroundColor() color.Color { return color.RGBA{R: 1, G: 2, B: 3, A: 255} }
func (testTheme) BackgroundImage() image.Image { return nil }

func (testTheme) BackgroundTileMode() BackgroundTileMode     { return BackgroundTileRepeat }
func (testTheme) BackgroundScaleMode() BackgroundScaleMode   { return BackgroundScaleNone }
func (testTheme) BackgroundAnchorMode() BackgroundAnchorMode { return BackgroundAnchorWorld }
func (testTheme) PointClassOverride(PointClassID) (StyleOverride, bool) {
	return StyleOverride{}, false
}
func (testTheme) LineClassOverride(LineClassID) (StyleOverride, bool) { return StyleOverride{}, false }
func (testTheme) CircleClassOverride(CircleClassID) (StyleOverride, bool) {
	return StyleOverride{}, false
}

func (testTheme) PointStyle() Style {
	return Style{
		FillColor:        color.RGBA{R: 9, A: 255},
		StrokeColor:      nil,
		StrokeWidthPx:    0,
		StrokeDashes:     nil,
		StrokeDashOffset: 0,
		PointRadiusPx:    4,
	}
}
func (testTheme) LineStyle() Style {
	return Style{
		FillColor:        nil,
		StrokeColor:      color.RGBA{G: 9, A: 255},
		StrokeWidthPx:    3,
		StrokeDashes:     []float64{2, 2},
		StrokeDashOffset: 1,
		PointRadiusPx:    0,
	}
}
func (testTheme) CircleStyle() Style {
	return Style{
		FillColor:        color.RGBA{B: 9, A: 255},
		StrokeColor:      color.RGBA{A: 255},
		StrokeWidthPx:    2,
		StrokeDashes:     nil,
		StrokeDashOffset: 0,
		PointRadiusPx:    0,
	}
}

// TestWorldSetTheme_MaterializesThemeDefaultStyles verifies world Set Theme Materializes Theme Default Styles.
func TestWorldSetTheme_MaterializesThemeDefaultStyles(t *testing.T) {
	t.Parallel()

	w := NewWorld(10, 10)

	// Built-ins should remain stable (1/2/3).
	require.Equal(t, StyleIDDefaultLine, StyleID(1))
	require.Equal(t, StyleIDDefaultCircle, StyleID(2))
	require.Equal(t, StyleIDDefaultPoint, StyleID(3))

	// Set a custom theme.
	w.SetTheme(testTheme{})

	// Theme defaults should NOT be built-in IDs anymore.
	require.NotEqual(t, StyleIDDefaultLine, w.themeDefaultLineStyleID)
	require.NotEqual(t, StyleIDDefaultCircle, w.themeDefaultCircleStyleID)
	require.NotEqual(t, StyleIDDefaultPoint, w.themeDefaultPointStyleID)

	ls, ok := w.styles.Get(w.themeDefaultLineStyleID)
	require.True(t, ok)
	require.Equal(t, 3.0, ls.StrokeWidthPx)
	require.Equal(t, []float64{2, 2}, ls.StrokeDashes)
	require.Equal(t, 1.0, ls.StrokeDashOffset)

	cs, ok := w.styles.Get(w.themeDefaultCircleStyleID)
	require.True(t, ok)
	require.Equal(t, 2.0, cs.StrokeWidthPx)

	ps, ok := w.styles.Get(w.themeDefaultPointStyleID)
	require.True(t, ok)
	require.Equal(t, 4.0, ps.PointRadiusPx)
}

// TestRender_UsesThemeBackgroundColor_WhenNoOptionOverride verifies render Uses Theme Background Color When No Option Override.
func TestRender_UsesThemeBackgroundColor_WhenNoOptionOverride(t *testing.T) {
	t.Parallel()

	w := NewWorld(10, 10)
	w.SetTheme(testTheme{})

	// Minimal index.
	w.resetGrid(2 * SCALE)

	params := RenderParams{
		ViewportWidthPx:  10,
		ViewportHeightPx: 10,
		MarginXPx:        0,
		MarginYPx:        0,
		CameraXWorldFp:   5 * SCALE,
		CameraYWorldFp:   5 * SCALE,
		CameraZoom:       1.0,
	}

	d := &fakePrimitiveDrawer{}
	require.NoError(t, w.Render(d, params))

	// Should clear with theme background color via ClearAllTo(bg).
	require.NotEmpty(t, d.CommandsByName("ClearAllTo"))
}

// TestRender_OptionsBackgroundColor_OverridesThemeBackgroundColor verifies render Options Background Color Overrides Theme Background Color.
func TestRender_OptionsBackgroundColor_OverridesThemeBackgroundColor(t *testing.T) {
	t.Parallel()

	w := NewWorld(10, 10)
	w.SetTheme(testTheme{})

	w.resetGrid(2 * SCALE)

	params := RenderParams{
		ViewportWidthPx:  10,
		ViewportHeightPx: 10,
		MarginXPx:        0,
		MarginYPx:        0,
		CameraXWorldFp:   5 * SCALE,
		CameraYWorldFp:   5 * SCALE,
		CameraZoom:       1.0,
		Options: &RenderOptions{
			BackgroundColor: color.RGBA{R: 200, A: 255},
		},
	}

	d := &fakePrimitiveDrawer{}
	require.NoError(t, w.Render(d, params))
	require.NotEmpty(t, d.CommandsByName("ClearAllTo"))
}

const (
	testPointClassExtended  PointClassID  = 1
	testCircleClassExtended CircleClassID = 1
)

type classThemeA struct{}

func (classThemeA) ID() string                                 { return "classA" }
func (classThemeA) Name() string                               { return "classA" }
func (classThemeA) BackgroundColor() color.Color               { return color.RGBA{A: 255} }
func (classThemeA) BackgroundImage() image.Image               { return nil }
func (classThemeA) BackgroundTileMode() BackgroundTileMode     { return BackgroundTileNone }
func (classThemeA) BackgroundScaleMode() BackgroundScaleMode   { return BackgroundScaleNone }
func (classThemeA) BackgroundAnchorMode() BackgroundAnchorMode { return BackgroundAnchorWorld }

func (classThemeA) PointStyle() Style {
	return Style{FillColor: color.RGBA{R: 10, A: 255}, PointRadiusPx: 2}
}
func (classThemeA) LineStyle() Style {
	return Style{StrokeColor: color.RGBA{G: 10, A: 255}, StrokeWidthPx: 1}
}
func (classThemeA) CircleStyle() Style {
	return Style{FillColor: color.RGBA{B: 10, A: 255}, StrokeColor: color.RGBA{A: 255}, StrokeWidthPx: 1}
}

func (classThemeA) PointClassOverride(c PointClassID) (StyleOverride, bool) {
	if c == testPointClassExtended {
		r := 6.0
		return StyleOverride{PointRadiusPx: &r}, true
	}
	return StyleOverride{}, false
}
func (classThemeA) LineClassOverride(LineClassID) (StyleOverride, bool) {
	return StyleOverride{}, false
}
func (classThemeA) CircleClassOverride(c CircleClassID) (StyleOverride, bool) {
	if c == testCircleClassExtended {
		w := 3.0
		return StyleOverride{StrokeWidthPx: &w}, true
	}
	return StyleOverride{}, false
}

type classThemeB struct{ classThemeA }

func (classThemeB) ID() string   { return "classB" }
func (classThemeB) Name() string { return "classB" }
func (classThemeB) PointStyle() Style {
	return Style{FillColor: color.RGBA{R: 99, A: 255}, PointRadiusPx: 3}
}
func (classThemeB) CircleStyle() Style {
	return Style{FillColor: color.RGBA{B: 99, A: 255}, StrokeColor: color.RGBA{A: 255}, StrokeWidthPx: 2}
}

func (classThemeB) PointClassOverride(c PointClassID) (StyleOverride, bool) {
	if c == testPointClassExtended {
		r := 9.0
		return StyleOverride{PointRadiusPx: &r}, true
	}
	return StyleOverride{}, false
}

// TestThemeClassOverride_AppliesAndUpdatesOnThemeChange verifies theme Class Override Applies And Updates On Theme Change.
func TestThemeClassOverride_AppliesAndUpdatesOnThemeChange(t *testing.T) {
	t.Parallel()

	w := NewWorld(10, 10)
	w.SetTheme(classThemeA{})

	id, err := w.AddPoint(1, 1, PointWithClass(testPointClassExtended))
	require.NoError(t, err)

	p := w.objects[id].(Point)
	s1, ok := w.styles.Get(p.StyleID)
	require.True(t, ok)
	require.Equal(t, 6.0, s1.PointRadiusPx)

	w.SetTheme(classThemeB{})

	p2 := w.objects[id].(Point)
	s2, ok := w.styles.Get(p2.StyleID)
	require.True(t, ok)
	require.Equal(t, 9.0, s2.PointRadiusPx)
}

// TestThemeClassOverride_MergesWithUserOverride_UserWins verifies theme Class Override Merges With User Override User Wins.
func TestThemeClassOverride_MergesWithUserOverride_UserWins(t *testing.T) {
	t.Parallel()

	w := NewWorld(10, 10)
	w.SetTheme(classThemeA{})

	// class would set point radius to 6, but user override sets it to 12.
	rUser := 12.0
	id, err := w.AddPoint(1, 1,
		PointWithClass(testPointClassExtended),
		PointWithStyleOverride(StyleOverride{PointRadiusPx: &rUser}),
	)
	require.NoError(t, err)

	p := w.objects[id].(Point)
	s1, ok := w.styles.Get(p.StyleID)
	require.True(t, ok)
	require.Equal(t, 12.0, s1.PointRadiusPx)

	// After theme change, class would set to 9, but user override must still win.
	w.SetTheme(classThemeB{})
	p2 := w.objects[id].(Point)
	s2, ok := w.styles.Get(p2.StyleID)
	require.True(t, ok)
	require.Equal(t, 12.0, s2.PointRadiusPx)
}

type themeA struct{}

func (themeA) ID() string                                 { return "A" }
func (themeA) Name() string                               { return "A" }
func (themeA) BackgroundColor() color.Color               { return color.RGBA{A: 255} }
func (themeA) BackgroundImage() image.Image               { return nil }
func (themeA) BackgroundTileMode() BackgroundTileMode     { return BackgroundTileNone }
func (themeA) BackgroundScaleMode() BackgroundScaleMode   { return BackgroundScaleNone }
func (themeA) BackgroundAnchorMode() BackgroundAnchorMode { return BackgroundAnchorWorld }
func (themeA) PointStyle() Style {
	return Style{FillColor: color.RGBA{R: 10, A: 255}, PointRadiusPx: 2}
}
func (themeA) LineStyle() Style {
	return Style{StrokeColor: color.RGBA{G: 10, A: 255}, StrokeWidthPx: 1}
}
func (themeA) CircleStyle() Style {
	return Style{FillColor: color.RGBA{B: 10, A: 255}, StrokeColor: color.RGBA{A: 255}, StrokeWidthPx: 1}
}
func (themeA) PointClassOverride(PointClassID) (StyleOverride, bool)   { return StyleOverride{}, false }
func (themeA) LineClassOverride(LineClassID) (StyleOverride, bool)     { return StyleOverride{}, false }
func (themeA) CircleClassOverride(CircleClassID) (StyleOverride, bool) { return StyleOverride{}, false }

type themeB struct{}

func (themeB) ID() string                                 { return "B" }
func (themeB) Name() string                               { return "B" }
func (themeB) BackgroundColor() color.Color               { return color.RGBA{A: 255} }
func (themeB) BackgroundImage() image.Image               { return nil }
func (themeB) BackgroundTileMode() BackgroundTileMode     { return BackgroundTileNone }
func (themeB) BackgroundScaleMode() BackgroundScaleMode   { return BackgroundScaleNone }
func (themeB) BackgroundAnchorMode() BackgroundAnchorMode { return BackgroundAnchorWorld }
func (themeB) PointStyle() Style {
	return Style{FillColor: color.RGBA{R: 99, A: 255}, PointRadiusPx: 5}
}
func (themeB) LineStyle() Style {
	return Style{StrokeColor: color.RGBA{G: 99, A: 255}, StrokeWidthPx: 3}
}
func (themeB) CircleStyle() Style {
	return Style{FillColor: color.RGBA{B: 99, A: 255}, StrokeColor: color.RGBA{A: 255}, StrokeWidthPx: 4}
}
func (themeB) PointClassOverride(PointClassID) (StyleOverride, bool)   { return StyleOverride{}, false }
func (themeB) LineClassOverride(LineClassID) (StyleOverride, bool)     { return StyleOverride{}, false }
func (themeB) CircleClassOverride(CircleClassID) (StyleOverride, bool) { return StyleOverride{}, false }

// TestThemeChange_UpdatesThemeDefaultStyleObjects verifies theme Change Updates Theme Default Style Objects.
func TestThemeChange_UpdatesThemeDefaultStyleObjects(t *testing.T) {
	t.Parallel()

	w := NewWorld(10, 10)
	w.SetTheme(themeA{})

	id, err := w.AddPoint(1, 1) // default => theme-managed
	require.NoError(t, err)

	p := w.objects[id].(Point)
	styleBefore := p.StyleID

	w.SetTheme(themeB{})

	p2 := w.objects[id].(Point)
	styleAfter := p2.StyleID

	require.NotEqual(t, styleBefore, styleAfter)

	s, ok := w.styles.Get(styleAfter)
	require.True(t, ok)
	// From themeB point style
	require.Equal(t, 5.0, s.PointRadiusPx)
}

// TestThemeChange_UpdatesThemeRelativeOverride verifies theme Change Updates Theme Relative Override.
func TestThemeChange_UpdatesThemeRelativeOverride(t *testing.T) {
	t.Parallel()

	w := NewWorld(10, 10)
	w.SetTheme(themeA{})

	white := color.RGBA{R: 255, G: 255, B: 255, A: 255}
	ov := StyleOverride{StrokeColor: white}

	id, err := w.AddCircle(5, 5, 2, CircleWithStyleOverride(ov))
	require.NoError(t, err)

	c1 := w.objects[id].(Circle)
	s1, ok := w.styles.Get(c1.StyleID)
	require.True(t, ok)

	// Stroke overridden to white, fill from themeA (B=10).
	require.Equal(t, uint32(0xffff), alphaOf(s1.StrokeColor))
	require.Equal(t, u16FromU8(10), blueOf(s1.FillColor))

	w.SetTheme(themeB{})

	c2 := w.objects[id].(Circle)
	s2, ok := w.styles.Get(c2.StyleID)
	require.True(t, ok)

	// Still white stroke, but fill should now come from themeB (B=99).
	require.Equal(t, uint32(0xffff), alphaOf(s2.StrokeColor))
	require.Equal(t, u16FromU8(99), blueOf(s2.FillColor))
}

// TestThemeChange_DoesNotAffectFixedStyleID verifies theme Change Does Not Affect Fixed Style ID.
func TestThemeChange_DoesNotAffectFixedStyleID(t *testing.T) {
	t.Parallel()

	w := NewWorld(10, 10)
	w.SetTheme(themeA{})

	sw := 2.0
	fixed := w.AddStyleCircle(StyleOverride{
		FillColor:     color.RGBA{A: 0},
		StrokeColor:   color.RGBA{R: 1, A: 255},
		StrokeWidthPx: &sw,
	})

	id, err := w.AddCircle(5, 5, 2, CircleWithStyleID(fixed))
	require.NoError(t, err)

	c1 := w.objects[id].(Circle)
	require.Equal(t, fixed, c1.StyleID)

	w.SetTheme(themeB{})

	c2 := w.objects[id].(Circle)
	require.Equal(t, fixed, c2.StyleID)
}

func alphaOf(c color.Color) uint32 {
	_, _, _, a := c.RGBA()
	return a
}
func blueOf(c color.Color) uint32 {
	_, _, b, _ := c.RGBA()
	return b
}

// u16FromU8 converts an 8-bit channel value to the 16-bit value returned by color.Color.RGBA().
// The standard conversion is v * 257 (0x0101) so that 0xAB becomes 0xABAB.
func u16FromU8(v uint8) uint32 {
	return uint32(v) * 257
}
