package tabloicons

import (
	"strconv"
	"strings"
)

type Presentation struct {
	Icon   string
	Bg     string
	Fg     string
	Accent string
}

type paletteEntry struct {
	Presentation
	r int
	g int
	b int
}

var palette = []paletteEntry{
	{Presentation: Presentation{Icon: "bolt", Bg: "bg-blue-500", Fg: "text-white", Accent: "blue"}, r: 59, g: 130, b: 246},
	{Presentation: Presentation{Icon: "leaf", Bg: "bg-green-500", Fg: "text-white", Accent: "green"}, r: 34, g: 197, b: 94},
	{Presentation: Presentation{Icon: "gem", Bg: "bg-purple-500", Fg: "text-white", Accent: "purple"}, r: 168, g: 85, b: 247},
	{Presentation: Presentation{Icon: "flame", Bg: "bg-red-500", Fg: "text-white", Accent: "red"}, r: 239, g: 68, b: 68},
	{Presentation: Presentation{Icon: "star", Bg: "bg-yellow-500", Fg: "text-gray-700", Accent: "yellow"}, r: 234, g: 179, b: 8},
	{Presentation: Presentation{Icon: "compass", Bg: "bg-indigo-500", Fg: "text-white", Accent: "indigo"}, r: 99, g: 102, b: 241},
	{Presentation: Presentation{Icon: "heart", Bg: "bg-pink-500", Fg: "text-white", Accent: "pink"}, r: 236, g: 72, b: 153},
	{Presentation: Presentation{Icon: "waves", Bg: "bg-teal-500", Fg: "text-white", Accent: "teal"}, r: 20, g: 184, b: 166},
	{Presentation: Presentation{Icon: "sun", Bg: "bg-orange-500", Fg: "text-white", Accent: "orange"}, r: 249, g: 115, b: 22},
	{Presentation: Presentation{Icon: "sparkles", Bg: "bg-cyan-500", Fg: "text-gray-700", Accent: "cyan"}, r: 6, g: 182, b: 212},
}

func ForColor(color string) Presentation {
	r, g, b, ok := parseHexColor(color)
	if !ok {
		return palette[0].Presentation
	}

	best := palette[0]
	bestDistance := colorDistanceSquared(r, g, b, best.r, best.g, best.b)
	for _, entry := range palette[1:] {
		distance := colorDistanceSquared(r, g, b, entry.r, entry.g, entry.b)
		if distance < bestDistance {
			best = entry
			bestDistance = distance
		}
	}

	return best.Presentation
}

func parseHexColor(color string) (int, int, int, bool) {
	trimmed := strings.TrimSpace(color)
	if len(trimmed) != 7 || trimmed[0] != '#' {
		return 0, 0, 0, false
	}

	r, err := strconv.ParseInt(trimmed[1:3], 16, 0)
	if err != nil {
		return 0, 0, 0, false
	}
	g, err := strconv.ParseInt(trimmed[3:5], 16, 0)
	if err != nil {
		return 0, 0, 0, false
	}
	b, err := strconv.ParseInt(trimmed[5:7], 16, 0)
	if err != nil {
		return 0, 0, 0, false
	}

	return int(r), int(g), int(b), true
}

func colorDistanceSquared(r1 int, g1 int, b1 int, r2 int, g2 int, b2 int) int {
	dr := r1 - r2
	dg := g1 - g2
	db := b1 - b2
	return dr*dr + dg*dg + db*db
}
