package routes

import (
	"encoding/json"
	"fmt"
	"html/template"
	"net/http"
	"os"
	"strings"

	"bitbucket.org/imediabrands/oos-service/middlewares"
	"github.com/julienschmidt/httprouter"
)

// staticPageProps are the props forwarded to the React StaticPage component.
type staticPageProps struct {
	StartContentServiceOrigin string `json:"startContentServiceOrigin,omitempty"`
	PortalStaticOrigin        string `json:"portalStaticOrigin,omitempty"`
	SiteId                    string `json:"siteId,omitempty"`
	TesseractClient           string `json:"tesseractClient,omitempty"`
	DisplayName               string `json:"displayName,omitempty"`
	PageName                  string `json:"pageName"`
	GaId                      string `json:"gaId,omitempty"`
}

// StaticPageHandler serves an HTML shell for static informational pages
// (terms, privacy, about, contact, sitemap, for advertisers). The React Router + StaticPage
// component handle the actual rendering using the client-side config.
//
// pageName must match the key used under pages.* in homepageConfig.json:
//
//	"terms"          → /terms
//	"privacyPolicy"  → /privacy
//	"aboutUs"        → /about
//	"contactUs"      → /contact
//	"sitemap"        → /sitemap
//	"forAdvertisers" → /for_advertisers
func StaticPageHandler(pageName string) http.Handler {
	tpl := pageTemplates()

	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		serveStaticPageShell(w, req, tpl, pageName)
	})
}

// notFoundPageName is the page whose shell site-template sites serve for unknown
// URLs; the frontend renders its not-found page from the URL.
const notFoundPageName = "notFound"

// serveStaticPageShell writes the HTML shell of pageName. The notFound page
// is served with a 404 status, noindex and no canonical or structured data.
func serveStaticPageShell(w http.ResponseWriter, req *http.Request, tpl *template.Template, pageName string) {
	config := middlewares.GetClientConfig(req.Context())
	if config == nil {
		http.Error(w, "client config not found", http.StatusInternalServerError)
		return
	}
	notFound := pageName == notFoundPageName

	// Human-readable page title from pageName (e.g. "privacyPolicy" → "Privacy Policy")
	pageLabel := siteTemplatePageLabel(config.Raw, pageName)
	if pageLabel == "" {
		pageLabel = pageTitleFromName(pageName)
	}
	defaultTitle := pageLabel + " - " + config.GetString("displayName")
	pageTitle, metaDescription := pageMetaOverride(config, pageName, defaultTitle, defaultTitle)
	vars := pageShellVars(req, config, pageName, pageTitle, metaDescription)

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if notFound {
		vars.CanonicalUrl = ""
		applyMetaRobots(w, vars, req, metaRobotsNotFound)
		w.WriteHeader(http.StatusNotFound)
	} else {
		applyMetaRobots(w, vars, req, metaRobotsIndexable)
		applyStructuredData(vars, config, req, []breadcrumbItem{
			homeBreadcrumbItem(req),
			{Name: pageLabel, URL: canonicalURL(req)},
		})
	}
	if err := tpl.ExecuteTemplate(w, "root", vars); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

// pageShellVars returns the template vars of the StaticPage shell of pageName
// with this title and description: props, override config, site UI, GA and
// og defaults, and the request's canonical URL. Robots and structured data
// are left to the caller.
func pageShellVars(req *http.Request, config *middlewares.ClientConfig, pageName, pageTitle, metaDescription string) *templateVars {
	displayName := config.GetString("displayName")
	siteId := config.GetString("siteId")
	ga := gaSettingsFromConfig(config)
	tesseractClient := config.GetString("tesseractClient")
	tesseractCdnUrl := config.GetString("tesseract_cdn_url")
	portalStaticCdnUrl := config.GetString("portal_static_cdn_url")
	scsUrl := config.GetString("scs_url")

	if tesseractCdnUrl == "" {
		tesseractCdnUrl = "/static/tesseract"
	}

	hostname, _ := os.Hostname()
	deviceType := "\"desktop\""
	environment := "\"" + config.GetString("environment") + "\""

	props := staticPageProps{
		StartContentServiceOrigin: scsUrl,
		PortalStaticOrigin:        portalStaticCdnUrl,
		SiteId:                    siteId,
		TesseractClient:           tesseractClient,
		DisplayName:               displayName,
		PageName:                  pageName,
		GaId:                      ga.GaId,
	}
	propsJSON, _ := json.Marshal(props)

	overrideConfig := map[string]interface{}{
		"siteId":             siteId,
		"displayName":        displayName,
		"seoMeta":            config.GetStringMap("seoMeta"),
		"logoUrl":            logoURLFromConfig(config),
		"articleTitleSuffix": articleTitleSuffixFromConfig(config),
	}
	configJSON, _ := json.Marshal(overrideConfig)

	vars := &templateVars{
		PageTitle:              pageTitle,
		MetaDescription:        metaDescription,
		OgTitle:                pageTitle,
		OgDescription:          metaDescription,
		TwitterTitle:           pageTitle,
		TwitterDescription:     metaDescription,
		FaviconUrl:             faviconURLFromConfig(config),
		DNSPrefetch:            []string{tesseractCdnUrl, scsUrl, portalStaticCdnUrl},
		CanonicalUrl:           canonicalURL(req),
		TesseractCdnUrl:        tesseractCdnUrl,
		TesseractClient:        tesseractClient,
		SingleCubeComponent:    "\"singlecube.StaticPage\"",
		SingleCubeProps:        template.JS(string(propsJSON)),
		OverrideConfig:         template.JS(string(configJSON)),
		DeviceType:             deviceType,
		Environment:            environment,
		TsuahComment:           template.HTML(fmt.Sprintf("<!-- TSUAH: %s -->", hostname)),
		GaId:                   ga.GaId,
		GaGtm:                  ga.GaGtm,
		GaCx:                   ga.GaCx,
		GtmId:                  ga.GtmId,
		GoogleCsa:              ga.GoogleCsa,
		GoogleSiteVerification: googleSiteVerificationFromConfig(config),
	}
	applyClientUI(vars, config)
	applyOgDefaults(vars, config)
	return vars
}

// legacyInfoPages maps the legacy PHP sites' static page URLs, /info/{page}
// (womenwire.com/info/about) and /site/{page} (gaycommunity.com/site/terms),
// to the page's URL here.
var legacyInfoPages = map[string]string{
	"about":   "/about",
	"privacy": "/privacy",
	"terms":   "/terms",
	"sitemap": "/sitemap",
	"contact": "/contact",
}

// LegacyInfoPageHandler 301s /info/{page} and /site/{page} to the page's URL
// (query kept) and answers any other page name with the not-found page.
func LegacyInfoPageHandler() http.Handler {
	return legacyInfoPageHandler(NotFoundHandler())
}

func legacyInfoPageHandler(notFound http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		target, ok := legacyInfoPages[httprouter.ParamsFromContext(req.Context()).ByName("page")]
		if !ok {
			notFound.ServeHTTP(w, req)
			return
		}
		redirectPermanently(w, req, target, req.URL.RawQuery)
	})
}

// ConfiguredStaticPageHandler serves pageName like StaticPageHandler, but
// only for clients whose config defines pages.<pageName>.content; for every
// other client the URL is a real 404 rather than an empty page. Used for
// pages only some sites have (e.g. /for_advertisers).
func ConfiguredStaticPageHandler(pageName string) http.Handler {
	return configuredStaticPageHandler(pageName, false)
}

// SiteTemplateConfiguredStaticPageHandler is ConfiguredStaticPageHandler for
// site-template clients only (see siteTemplateNotFoundTitles), whose pages all
// live in their client config; classic clients always get the page, as its
// content is in the frontend's bundled config (e.g. /contact).
func SiteTemplateConfiguredStaticPageHandler(pageName string) http.Handler {
	return configuredStaticPageHandler(pageName, true)
}

// configuredStaticPageHandler serves pageName when servesConfiguredPage
// allows it, else the not-found page.
func configuredStaticPageHandler(pageName string, siteTemplateOnly bool) http.Handler {
	page := StaticPageHandler(pageName)
	notFound := NotFoundHandler()

	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		config := middlewares.GetClientConfig(req.Context())
		if config == nil || !servesConfiguredPage(config.Raw, pageName, siteTemplateOnly) {
			notFound.ServeHTTP(w, req)
			return
		}
		page.ServeHTTP(w, req)
	})
}

// servesConfiguredPage reports whether ConfiguredStaticPageHandler serves
// pageName for a client with this raw config (otherwise it 404s).
func servesConfiguredPage(raw map[string]interface{}, pageName string, siteTemplateOnly bool) bool {
	if siteTemplateOnly && !usesSiteTemplate(raw) {
		return true
	}
	return hasPageContent(raw, pageName)
}

// siteTemplateNotFoundTitles lists the frontend templates that render a whole
// site from its client config (pages, labels, its own not-found page), each
// with its default notFoundTitle label. Sites without one use the classic
// template, whose content is bundled in the frontend.
var siteTemplateNotFoundTitles = map[string]string{
	"editorial":           "Page not found",
	"magazine":            "Page not found",
	"automotive":          "Page not found",
	directoryTemplateName: "Page not found",
	shopTemplateName:      "Page not found",
}

// siteTemplatePageLabel returns the label a site template titles pageName
// with once rendered: the page's content.title, or the notFoundTitle label
// for the not-found page. "" for classic sites or pages without a title.
func siteTemplatePageLabel(raw map[string]interface{}, pageName string) string {
	defaultNotFoundTitle, ok := siteTemplateNotFoundTitles[siteTemplateName(raw)]
	if !ok {
		return ""
	}
	if pageName == notFoundPageName {
		shared, _ := raw["shared"].(map[string]interface{})
		labels, _ := shared["labels"].(map[string]interface{})
		if title, _ := labels["notFoundTitle"].(string); title != "" {
			return title
		}
		return defaultNotFoundTitle
	}
	pages, _ := raw["pages"].(map[string]interface{})
	page, _ := pages[pageName].(map[string]interface{})
	content, _ := page["content"].(map[string]interface{})
	title, _ := content["title"].(string)
	return title
}

// siteTemplateName returns the raw client config's "template", "" when unset.
func siteTemplateName(raw map[string]interface{}) string {
	name, _ := raw["template"].(string)
	return name
}

// usesSiteTemplate reports whether a raw client config renders with a site
// template (see siteTemplateNotFoundTitles).
func usesSiteTemplate(raw map[string]interface{}) bool {
	_, ok := siteTemplateNotFoundTitles[siteTemplateName(raw)]
	return ok
}

// hasPageContent reports whether a raw client config defines
// pages.<pageName>.content.
func hasPageContent(raw map[string]interface{}, pageName string) bool {
	pages, _ := raw["pages"].(map[string]interface{})
	page, _ := pages[pageName].(map[string]interface{})
	_, ok := page["content"].(map[string]interface{})
	return ok
}

// extraPageAt returns the name of the site's own page served at path: a
// config page with that "path" (e.g. "/faq") and content, as oos-singlecube's
// extraPages routes it (same rule: a path starting with one "/"). "" when
// there is none.
func extraPageAt(raw map[string]interface{}, path string) string {
	if !strings.HasPrefix(path, "/") || strings.HasPrefix(path, "//") || len(path) < 2 {
		return ""
	}
	pages, _ := raw["pages"].(map[string]interface{})
	for name, entry := range pages {
		page, _ := entry.(map[string]interface{})
		if pagePath, _ := page["path"].(string); pagePath == path && hasPageContent(raw, name) {
			return name
		}
	}
	return ""
}

// pageTitleFromName converts a camelCase pageName to a Title Case string.
// e.g. "privacyPolicy" → "Privacy Policy", "aboutUs" → "About Us"
func pageTitleFromName(name string) string {
	switch name {
	case "terms":
		return "Terms and Conditions"
	case "privacyPolicy":
		return "Privacy Policy"
	case "aboutUs":
		return "About Us"
	case "contactUs":
		return "Contact Us"
	case "sitemap":
		return "Sitemap"
	case "forAdvertisers":
		return "For Advertisers"
	case notFoundPageName:
		return "Page Not Found"
	}
	// Fallback: split on uppercase letters
	var result []string
	word := ""
	for i, r := range name {
		if i > 0 && r >= 'A' && r <= 'Z' {
			result = append(result, strings.Title(word)) //nolint:staticcheck
			word = ""
		}
		word += string(r)
	}
	if word != "" {
		result = append(result, strings.Title(word)) //nolint:staticcheck
	}
	return strings.Join(result, " ")
}
