package main

import (
	"fmt"
	"strings"
)

// ServerItem renders a single server in the server bar.
func ServerItem(server Server, isActive, isHovered bool, width int) string {
	// Show first letter(s) of server name as icon
	name := server.Name
	if len(name) > 2 {
		name = name[:2]
	}
	// Use icon if available
	if server.Icon != "" {
		name = server.Icon
	}
	name = strings.ToUpper(name)

	style := ServerInactive
	if isActive {
		style = ServerActive
	} else if isHovered {
		style = ServerHover
	}

	return style.Width(width - 2).Render(fmt.Sprintf(" %s ", name))
}

// ServerBar renders the vertical server list.
func ServerBar(servers []Server, activeIdx, hoverIdx, height int) string {
	if len(servers) == 0 {
		return ServerBarStyle.
			Width(6).
			Height(height).
			Render(HelpStyle.Render("No\nservers"))
	}

	var items []string
	for i, s := range servers {
		items = append(items, ServerItem(s, i == activeIdx, i == hoverIdx, 6))
	}

	bar := strings.Join(items, "\n")
	return ServerBarStyle.
		Width(6).
		Height(height).
		Render(bar)
}

// ServerInitials returns 2-char initials for a server name.
func ServerInitials(name string) string {
	if len(name) == 0 {
		return "??"
	}
	parts := strings.Fields(name)
	if len(parts) >= 2 {
		return strings.ToUpper(string([]rune(parts[0])[0:1]) + string([]rune(parts[1])[0:1]))
	}
	if len(name) >= 2 {
		return strings.ToUpper(name[:2])
	}
	return strings.ToUpper(name) + " "
}
