package components

import (
	"fmt"
	"maps"
	"runtime"
	"strings"

	"dk/internal/template"

	sushi "git.sharkk.net/Sharkk/Sushi"
	"git.sharkk.net/Sharkk/Sushi/csrf"
	"git.sharkk.net/Sharkk/Sushi/timing"
)

// RenderPage renders a page using the layout template with common data and additional custom data
func RenderPage(ctx sushi.Ctx, title, tmplPath string, additionalData map[string]any) error {
	if template.Cache == nil {
		return fmt.Errorf("template.Cache not initialized")
	}

	tmpl, err := template.Cache.Load(tmplPath)
	if err != nil {
		return fmt.Errorf("failed to load layout template: %w", err)
	}

	var m runtime.MemStats
	runtime.ReadMemStats(&m)

	sess := ctx.GetCurrentSession()

	seconds := timing.GetRequestDuration(ctx).Seconds()
	var totalTime string
	if seconds < 0.001 {
		totalTime = fmt.Sprintf("%.0f", seconds)
	} else {
		totalTime = fmt.Sprintf("%.3f", seconds)
	}

	data := map[string]any{
		"_title":        PageTitle(title),
		"authenticated": ctx.IsAuthenticated(),
		"csrf":          csrf.HiddenField(ctx),
		"_totaltime":    totalTime,
		"_version":      "1.0.0",
		"_build":        "dev",
		"user":          ctx.GetCurrentUser(),
		"_memalloc":     m.Alloc / 1024 / 1024,
		"_errormsg":     sess.GetFlashMessage("error"),
		"_successmsg":   sess.GetFlashMessage("success"),
	}

	maps.Copy(data, LeftAside(ctx))
	maps.Copy(data, RightAside(ctx))
	maps.Copy(data, additionalData)

	return tmpl.WriteTo(ctx, data)
}

// PageTitle returns a proper title for a rendered page. If an empty string
// is given, returns "Dragon Knight". If the provided title already has " - Dragon Knight"
// at the end, returns title as-is. Appends " - Dragon Knight" to title otherwise.
func PageTitle(title string) string {
	if title == "" {
		return "Dragon Knight"
	}

	if strings.HasSuffix(" - Dragon Knight", title) {
		return title
	}

	return title + " - Dragon Knight"
}
