package controllers

import (
	"bytes"
	"html/template"
	"path/filepath"

	"github.com/gofiber/fiber/v2"
)

func renderPublic(c *fiber.Ctx, page string, data map[string]any) error {
	viewData := map[string]any{}
	for k, v := range localsTemplateData(c) {
		viewData[k] = v
	}
	for k, v := range data {
		viewData[k] = v
	}

	if _, ok := viewData["Title"]; !ok {
		viewData["Title"] = "Trustcontact"
	}
	if _, ok := viewData["NavSection"]; !ok {
		viewData["NavSection"] = "public"
	}

	files := []string{
		"web/templates/layout.html",
		"web/templates/public/_navbar.html",
		"web/templates/partials/language_dropdown.html",
		"web/templates/public/_flash.html",
		filepath.Join("web/templates/public", page),
	}

	tmpl, err := template.ParseFiles(files...)
	if err != nil {
		return err
	}

	var out bytes.Buffer
	if err := tmpl.ExecuteTemplate(&out, "layout.html", viewData); err != nil {
		return err
	}

	c.Type("html", "utf-8")
	return c.Send(out.Bytes())
}

func renderPrivate(c *fiber.Ctx, _ string, data map[string]any) error {
	viewData := map[string]any{}
	for k, v := range localsTemplateData(c) {
		viewData[k] = v
	}
	for k, v := range data {
		viewData[k] = v
	}

	if _, ok := viewData["Title"]; !ok {
		viewData["Title"] = "Trustcontact"
	}
	if _, ok := viewData["NavSection"]; !ok {
		viewData["NavSection"] = "private"
	}

	files := []string{
		"web/templates/layout.html",
		"web/templates/public/_navbar.html",
		"web/templates/partials/language_dropdown.html",
		"web/templates/public/_flash.html",
		"web/templates/private.html",
	}

	tmpl, err := template.ParseFiles(files...)
	if err != nil {
		return err
	}

	var out bytes.Buffer
	if err := tmpl.ExecuteTemplate(&out, "layout.html", viewData); err != nil {
		return err
	}

	c.Type("html", "utf-8")
	return c.Send(out.Bytes())
}

func localsTemplateData(c *fiber.Ctx) map[string]any {
	data, ok := c.Locals("template_data").(map[string]any)
	if !ok || data == nil {
		return map[string]any{}
	}
	return data
}
