// Package routes: seo.go is the single home for everything SEO-related in
// oos-service — canonical/base URL + slug helpers, meta robots policy,
// CMS→meta parsing, config-derived SEO metadata, and JSON-LD structured
// data. HTTP handlers that *use* this (robots.txt, sitemap.xml, page routes)
// stay in their own files; this file only holds the shared logic underneath
// them.
package routes

import (
	"encoding/json"
	"fmt"
	"html"
	"html/template"
	"log"
	"mime"
	"net/http"
	"net/url"
	"path"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"
	"unicode"

	"bitbucket.org/imediabrands/oos-service/internal/listings"
	"bitbucket.org/imediabrands/oos-service/middlewares"
	"github.com/spf13/viper"
)

// -----------------------------------------------------------------------------
// URL, host, and slug helpers
// -----------------------------------------------------------------------------

// requestPublicHost returns the public host of the request (X-Forwarded-Host
// or Host), without a port.
func requestPublicHost(req *http.Request) string {
	host := ""
	if forwarded := req.Header.Get("X-Forwarded-Host"); forwarded != "" {
		// May be a comma-separated list; take the first.
		host = cleanDomain(strings.Split(forwarded, ",")[0])
	}
	if host == "" {
		host = cleanDomain(req.Host)
	}
	if host == "" {
		host = "localhost"
	}
	return host
}

// requestPublicBaseURL returns https://{request-host} using the public host
// (X-Forwarded-Host or Host). Never hardcodes a client domain.
func requestPublicBaseURL(req *http.Request) string {
	host := requestPublicHost(req)

	scheme := "https"
	if proto := req.Header.Get("X-Forwarded-Proto"); proto != "" {
		scheme = strings.ToLower(strings.TrimSpace(strings.Split(proto, ",")[0]))
	} else if req.TLS == nil && (host == "localhost" || strings.HasPrefix(host, "127.")) {
		scheme = "http"
	}
	return scheme + "://" + host
}

// canonicalURL builds the absolute canonical href for a request:
//   - public scheme + host (via X-Forwarded-* / Host, no port)
//   - clean path (homepage → trailing slash)
//   - omits tracking/search query params
//   - keeps ?page=N only when N > 1 (paginated category/list self-refs)
func canonicalURL(req *http.Request) string {
	if req == nil {
		return ""
	}

	base := strings.TrimRight(requestPublicBaseURL(req), "/")
	path := req.URL.Path
	if path == "" {
		path = "/"
	}
	if !strings.HasPrefix(path, "/") {
		path = "/" + path
	}
	// Collapse accidental duplicate slashes in the path (keep leading slash).
	for strings.Contains(path, "//") {
		path = strings.ReplaceAll(path, "//", "/")
	}

	url := base + path
	if path == "/" {
		url = base + "/"
	}

	if page := strings.TrimSpace(req.URL.Query().Get("page")); page != "" {
		if n, err := strconv.Atoi(page); err == nil && n > 1 {
			url += "?page=" + strconv.Itoa(n)
		}
	}
	return url
}

// absoluteURL joins the request's public base URL (scheme + host) with path.
func absoluteURL(req *http.Request, path string) string {
	if !strings.HasPrefix(path, "/") {
		path = "/" + path
	}
	if req == nil {
		return path
	}
	return strings.TrimRight(requestPublicBaseURL(req), "/") + path
}

// isSitemapIndexableHost reports whether this host/environment should advertise
// sitemaps to crawlers (production only; excludes UAT/staging/dev/test).
func isSitemapIndexableHost(req *http.Request) bool {
	env := strings.ToLower(strings.TrimSpace(viper.GetString("environment")))
	if env != "" && env != "prod" && env != "production" {
		return false
	}

	host := cleanDomain(req.Host)
	if forwarded := req.Header.Get("X-Forwarded-Host"); forwarded != "" {
		host = cleanDomain(strings.Split(forwarded, ",")[0])
	}
	if host == "" {
		return false
	}
	if host == "localhost" || strings.HasPrefix(host, "127.") {
		return false
	}
	if strings.HasPrefix(host, "uat-") || strings.HasPrefix(host, "staging-") || strings.HasPrefix(host, "dev-") || strings.HasPrefix(host, "test-") {
		return false
	}
	if strings.Contains(host, ".imds.tv") {
		// Internal UAT/CDN-style hosts are not public production domains.
		return false
	}
	return true
}

// slugify mirrors oos-singlecube/src/utils/articleUrl.ts slugify().
func slugify(value string) string {
	// "&" reads as "and" in slugs ("Risk & Planning" -> risk-and-planning), as on the
	// production sites; every other punctuation mark is dropped.
	value = strings.ToLower(strings.TrimSpace(strings.ReplaceAll(value, "&", " and ")))
	if value == "" {
		return ""
	}

	var b strings.Builder
	b.Grow(len(value))
	prevHyphen := false
	for _, r := range value {
		switch {
		// ASCII letters/digits only, like JS \w — non-ASCII letters (é, ü)
		// are dropped exactly as oos-singlecube's slugify drops them.
		case r < unicode.MaxASCII && (unicode.IsLetter(r) || unicode.IsDigit(r)):
			b.WriteRune(r)
			prevHyphen = false
		// Any whitespace (incl. tabs and non-breaking spaces, like JS \s),
		// underscores and hyphens become a single hyphen.
		case unicode.IsSpace(r) || r == '_' || r == '-':
			if !prevHyphen && b.Len() > 0 {
				b.WriteByte('-')
				prevHyphen = true
			}
		default:
			// drop punctuation (matches JS /[^\w\s-]/g)
		}
	}
	return strings.Trim(b.String(), "-")
}

// slugifyArticleTitle mirrors oos-singlecube's slugifyArticleTitle: slugify
// with "&" dropped instead of spelled out, so article slugs stay exactly as
// already published and listed in the legacy sites' sitemaps
// ("Timeline & Steps" → "timeline-steps").
func slugifyArticleTitle(value string) string {
	return slugify(strings.ReplaceAll(value, "&", ""))
}

// humanizeSlug converts a URL slug (e.g. "wine-tips") into a human-readable
// title (e.g. "Wine Tips") for use as a breadcrumb label fallback when no
// CMS-resolved display name is available.
func humanizeSlug(slug string) string {
	slug = strings.TrimSpace(slug)
	if slug == "" {
		return ""
	}
	words := strings.FieldsFunc(slug, func(r rune) bool {
		return r == '-' || r == '_' || r == ' '
	})
	for i, w := range words {
		words[i] = strings.Title(strings.ToLower(w)) //nolint:staticcheck
	}
	return strings.Join(words, " ")
}

// extractArticleIDFromSlug returns the numeric article ID from a URL slug segment.
// Examples: "1778500-wine-faults" → "1778500", "1774289" → "1774289".
func extractArticleIDFromSlug(slug string) string {
	if slug == "" {
		return ""
	}
	if idx := strings.Index(slug, "-"); idx > 0 {
		return slug[:idx]
	}
	return slug
}

// parseArticleDetailPath detects SEO article URLs: /{categorySlug}/{id}-{slugTitle}.
// Returns category slug, article slug segment, and whether the path matched.
func parseArticleDetailPath(path string) (category string, slug string, ok bool) {
	path = strings.Trim(path, "/")
	if path == "" {
		return "", "", false
	}

	parts := strings.Split(path, "/")
	if len(parts) != 2 {
		return "", "", false
	}

	category, slug = parts[0], parts[1]
	if category == "" || slug == "" {
		return "", "", false
	}

	// Article slug must begin with the numeric article ID.
	for _, r := range slug {
		if unicode.IsDigit(r) {
			return category, slug, true
		}
		if r == '-' {
			return "", "", false
		}
		break
	}

	return "", "", false
}

// parseSubcategoryArticleDetailPath detects SEO article URLs nested under a
// subcategory: /{categorySlug}/{subcategorySlug}/{id}-{slugTitle}.
// Returns the category slug, subcategory slug, article slug segment, and
// whether the path matched.
func parseSubcategoryArticleDetailPath(path string) (category string, subcategory string, slug string, ok bool) {
	path = strings.Trim(path, "/")
	if path == "" {
		return "", "", "", false
	}

	parts := strings.Split(path, "/")
	if len(parts) != 3 {
		return "", "", "", false
	}

	category, subcategory, slug = parts[0], parts[1], parts[2]
	if category == "" || subcategory == "" || slug == "" {
		return "", "", "", false
	}

	// Article slug must begin with the numeric article ID.
	for _, r := range slug {
		if unicode.IsDigit(r) {
			return category, subcategory, slug, true
		}
		break
	}

	return "", "", "", false
}

// staticPageSegments are the single-segment page routes registered in main.go
// (static pages and their aliases, search, shop, the all-articles list).
var staticPageSegments = map[string]bool{
	"articles": true, "search": true, "terms": true, "privacy": true,
	"privacypolicy": true, "about": true, "aboutus": true,
	"contact": true, "contactus": true, "sitemap": true, "shop": true,
	"for_advertisers": true,
}

// reservedSingleSegments are paths already handled by registered router routes
// and must not be treated as category slugs: the page routes above plus the
// non-page ones.
var reservedSingleSegments = withSegments(staticPageSegments,
	"article", "components", "sitemap.xml", "sitemap_pages.xml",
	"robots.txt", "ads.txt", "health-check", "data")

// withSegments returns a copy of base with extra segments added.
func withSegments(base map[string]bool, extra ...string) map[string]bool {
	out := make(map[string]bool, len(base)+len(extra))
	for seg := range base {
		out[seg] = true
	}
	for _, seg := range extra {
		out[seg] = true
	}
	return out
}

// parseCategoryPath detects SEO category URLs: /{cat_name_slug}  e.g. /wine, /spirits.
// Returns the slug and whether the path matched.
// A category path is exactly one plain slug segment (see slugSegmentRe) that
// is not a reserved word, so junk like /~ or /Fitness isn't served as a page.
func parseCategoryPath(path string) (slug string, ok bool) {
	seg := strings.Trim(path, "/")
	if !slugSegmentRe.MatchString(seg) {
		return "", false
	}
	if reservedSingleSegments[strings.ToLower(seg)] {
		return "", false
	}
	return seg, true
}

// parseSubcategoryPath detects SEO subcategory URLs: /{catSlug}/{subcatSlug}
// e.g. /wine-tips/red-wines. The second segment must NOT start with a digit
// (which distinguishes it from article detail URLs like /wine-tips/1778500-wine-faults).
func parseSubcategoryPath(path string) (catSlug, subcatSlug string, ok bool) {
	path = strings.Trim(path, "/")
	if path == "" {
		return "", "", false
	}

	parts := strings.Split(path, "/")
	if len(parts) != 2 {
		return "", "", false
	}

	// Both segments must be plain slugs (see slugSegmentRe), so junk like
	// /~/abc isn't served as a second URL for a subcategory page.
	catSlug, subcatSlug = parts[0], parts[1]
	if !slugSegmentRe.MatchString(catSlug) || !slugSegmentRe.MatchString(subcatSlug) {
		return "", "", false
	}

	// Reserved top-level segments are not valid category slugs.
	if reservedSingleSegments[strings.ToLower(catSlug)] {
		return "", "", false
	}

	// If the second segment starts with a digit it's an article slug, not a subcategory.
	if len(subcatSlug) > 0 && unicode.IsDigit(rune(subcatSlug[0])) {
		return "", "", false
	}

	return catSlug, subcatSlug, true
}

// slugSegmentRe matches one URL slug segment as slugify produces it:
// lowercase ASCII letters/digits separated by single hyphens.
var slugSegmentRe = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`)

// redirectLocation builds a same-origin URL (a Location header value or a
// rewritten link) from a path, raw query and fragment. url.URL escapes
// anything a browser could reinterpret as an off-site URL (e.g. a backslash
// or tab after the leading slash).
func redirectLocation(path, rawQuery, fragment string) string {
	return (&url.URL{Path: path, RawQuery: rawQuery, Fragment: fragment}).String()
}

// seoRedirectCacheControl caps how long browsers keep an SEO 301. Without it
// browsers hold a 301 indefinitely, so a redirect that later changes (e.g. a
// category renamed and renamed back) would stay stuck for anyone who saw it.
const seoRedirectCacheControl = "public, max-age=3600"

// redirectPermanently writes a 301 to path (keeping rawQuery) with a one-hour
// browser cache lifetime.
func redirectPermanently(w http.ResponseWriter, req *http.Request, path, rawQuery string) {
	w.Header().Set("Cache-Control", seoRedirectCacheControl)
	http.Redirect(w, req, redirectLocation(path, rawQuery, ""), http.StatusMovedPermanently)
}

// isNumericID reports whether s is a non-empty string of ASCII digits.
func isNumericID(s string) bool {
	if s == "" {
		return false
	}
	for _, r := range s {
		if r < '0' || r > '9' {
			return false
		}
	}
	return true
}

// trailingSlashRedirectPath returns the clean path a category or subcategory
// URL with a trailing slash should redirect to, e.g. /fitness/ → /fitness and
// /wine-101/wine-types/ → /wine-101/wine-types. Anything that wouldn't be
// served as a category/subcategory page once cleaned (deeper paths, reserved
// words such as /about/, the homepage) is left alone so it 404s directly.
func trailingSlashRedirectPath(path string) (string, bool) {
	if !strings.HasSuffix(path, "/") {
		return "", false
	}
	target := listingPagePath(path)
	return target, target != ""
}

// listingPagePath returns the clean path of a category or subcategory page,
// e.g. /fitness/ → /fitness, or "" when path isn't one.
//
// The category/subcategory parsers only accept plain slug segments
// ([a-z0-9-]), so paths such as //evil.com/, /\evil.com/ or /%09/evil.com/
// never match — they would otherwise produce a URL browsers treat as another
// site.
func listingPagePath(path string) string {
	clean := "/" + strings.Trim(path, "/")
	if _, ok := parseCategoryPath(clean); ok {
		return clean
	}
	if _, _, ok := parseSubcategoryPath(clean); ok {
		return clean
	}
	return ""
}

// legacySearchRedirectQuery returns the query an older search URL,
// /search?keyword=X[&page=N] or /search?search=X, should redirect to: the same
// query with "keyword" / "search" renamed to "term" (what the search page
// reads, as on the live sites). Every param is kept exactly as written, in its
// original order and encoding. Queries without either, with "term" already
// set, or that don't parse are left alone.
func legacySearchRedirectQuery(rawQuery string) (string, bool) {
	return renameQueryParam(rawQuery, "term", "keyword", "search")
}

// directorySearchRedirectQuery is legacySearchRedirectQuery for directory
// sites, whose search page reads "s": "search", "keyword" and "q" are renamed.
func directorySearchRedirectQuery(rawQuery string) (string, bool) {
	return renameQueryParam(rawQuery, "s", "search", "keyword", "q")
}

// renameQueryParam returns rawQuery with the first of the legacy params
// renamed to "to" and the other legacy params dropped, every other param kept
// as written. ok is false when the query has none of them, already has "to",
// or doesn't parse.
func renameQueryParam(rawQuery, to string, legacy ...string) (string, bool) {
	if _, err := url.ParseQuery(rawQuery); err != nil {
		return "", false
	}
	params := strings.Split(rawQuery, "&")
	out := make([]string, 0, len(params))
	renamed := false
	for _, param := range params {
		key, value, hasValue := strings.Cut(param, "=")
		if key == to {
			return "", false
		}
		if !isOneOf(key, legacy) {
			out = append(out, param)
			continue
		}
		// The first legacy name is the keyword, the others are dropped.
		if renamed {
			continue
		}
		param = to
		if hasValue {
			param += "=" + value
		}
		renamed = true
		out = append(out, param)
	}
	if !renamed {
		return "", false
	}
	return strings.Join(out, "&"), true
}

func isOneOf(s string, list []string) bool {
	for _, item := range list {
		if s == item {
			return true
		}
	}
	return false
}

// serveLegacySearchRedirect 301s a /search?keyword= or ?search= URL to the
// same search on ?term=. Reports whether it wrote a redirect.
func serveLegacySearchRedirect(w http.ResponseWriter, req *http.Request) bool {
	query, ok := legacySearchRedirectQuery(req.URL.RawQuery)
	if !ok {
		return false
	}
	redirectPermanently(w, req, "/search", query)
	return true
}

// buildArticleSlugSegment mirrors oos-singlecube's buildArticleSlug: the
// article URL segment `{id}-{slug}`, or just `{id}` when there's no title
// to slugify.
func buildArticleSlugSegment(articleID, titleForSlug string) string {
	return articleSlugSegment(articleID, slugifyArticleTitle(titleForSlug))
}

// articleSlugSegment is `{id}-{slug}`, or just `{id}` without a slug.
func articleSlugSegment(articleID, slug string) string {
	if slug == "" {
		return articleID
	}
	return articleID + "-" + slug
}

// buildArticleDetailPath mirrors oos-singlecube's buildArticlePath: the
// canonical article path `/{categorySlug}/{subcategorySlug}/{id}-{slugTitle}`,
// nested under the subcategory segment only when one is available.
func buildArticleDetailPath(category, subCategory, articleID, titleForSlug string) string {
	return articleDetailPath(category, subCategory, buildArticleSlugSegment(articleID, titleForSlug))
}

// buildLegacyArticleDetailPath is buildArticleDetailPath with the slug made by
// legacyArticleSlug (see articleURLOptions.LegacySlug).
func buildLegacyArticleDetailPath(category, subCategory, articleID, titleForSlug string) string {
	return articleDetailPath(category, subCategory, articleSlugSegment(articleID, legacyArticleSlug(titleForSlug)))
}

// articleDetailPath nests an article's `{id}-{slug}` segment under its category
// and, when it has one, its subcategory.
func articleDetailPath(category, subCategory, articleSlug string) string {
	// Fall back to "article" when the category is missing or slugifies to
	// nothing, so the path never starts with "//".
	categorySlug := slugify(category)
	if categorySlug == "" {
		categorySlug = "article"
	}
	if subCategory != "" {
		if subSlug := slugify(subCategory); subSlug != "" {
			return "/" + categorySlug + "/" + subSlug + "/" + articleSlug
		}
	}
	return "/" + categorySlug + "/" + articleSlug
}

// articleCanonicalRedirectPath returns the canonical SEO-friendly article
// path a request should permanently redirect to, or "" when the current
// path is already canonical (no redirect needed). Any article URL whose path
// differs from the canonical one redirects, e.g.:
//   - missing subcategory: legacy /article/:slug or /{categorySlug}/{slug}
//     for an article that belongs to a subcategory
//   - bare numeric slug (/fitness/1775223) when a title is available
//   - old/wrong category or legacy prefix (/articles/1780517-..., /weight-loss/...)
//   - a slug that no longer matches the CMS slug title
//   - a trailing slash (/fitness/1775223-functional-training/)
//
// Without a CMS category the canonical path can't be built reliably, so no
// redirect is issued.
func articleCanonicalRedirectPath(meta articlePageMeta, articleID, currentPath string) string {
	target := canonicalArticlePath(meta, articleID)
	// Guard against redirect loops (e.g. a title that slugifies to empty) by
	// only redirecting when the canonical path actually differs.
	if target == "" || target == currentPath {
		return ""
	}
	return target
}

// canonicalArticlePath returns an article's canonical path from its CMS meta,
// or "" when it can't be built reliably (no CMS category, non-numeric ID).
func canonicalArticlePath(meta articlePageMeta, articleID string) string {
	if meta.Category == "" || !isNumericID(articleID) {
		return ""
	}
	if meta.LegacySlug {
		return buildLegacyArticleDetailPath(meta.Category, meta.SubCategory, articleID, meta.SlugTitle)
	}
	return buildArticleDetailPath(meta.Category, meta.SubCategory, articleID, meta.SlugTitle)
}

// -----------------------------------------------------------------------------
// Internal links inside CMS article content
// -----------------------------------------------------------------------------

// contentHrefRe matches an href attribute (double- or single-quoted) in CMS
// article HTML. Group 1 is everything up to the value, group 2/3 the value.
var contentHrefRe = regexp.MustCompile(`(?i)(\shref\s*=\s*)(?:"([^"]*)"|'([^']*)')`)

// articleLinkLookups caps concurrent CMS lookups while resolving the article
// links of one content body.
const articleLinkLookups = 4

// rewriteInternalLinks points the site's own links inside CMS article HTML at
// their final URLs. Editors paste absolute live links such as
// https://www.centerweightloss.com/articles/1780517-old-slug/ — old
// category/prefix, outdated slug, trailing slash — which would otherwise only
// reach the page through a 301. Each own-site link becomes root-relative:
//   - article links → canonical path from the CMS (resolveArticlePath), so
//     category, subcategory and slug match the page's own canonical URL
//   - homepage / static page / category / subcategory links → "/" or the
//     path without a trailing slash
//
// utm_* params are dropped; other params and #fragments are kept. External
// links, unparseable values and articles resolveArticlePath can't resolve
// ("") are left exactly as written.
func rewriteInternalLinks(content, siteDomain string, resolveArticlePath func(articleID string) string) string {
	if siteDomain == "" || !strings.Contains(content, "href") && !strings.Contains(content, "HREF") {
		return content
	}

	// Resolve each distinct linked article once, a few at a time.
	var ids []string
	seen := map[string]bool{}
	for _, m := range contentHrefRe.FindAllStringSubmatch(content, -1) {
		if u := ownSiteLinkURL(m[2]+m[3], siteDomain); u != nil {
			if id := linkedArticleID(u.Path); id != "" && !seen[id] {
				seen[id] = true
				ids = append(ids, id)
			}
		}
	}
	paths := make(map[string]string, len(ids))
	var mu sync.Mutex
	forEachConcurrently(ids, articleLinkLookups, func(id string) {
		path := resolveArticlePath(id)
		mu.Lock()
		paths[id] = path
		mu.Unlock()
	})

	return contentHrefRe.ReplaceAllStringFunc(content, func(attr string) string {
		m := contentHrefRe.FindStringSubmatch(attr)
		u := ownSiteLinkURL(m[2]+m[3], siteDomain)
		if u == nil {
			return attr
		}
		var target string
		if id := linkedArticleID(u.Path); id != "" {
			target = paths[id]
		} else {
			target = ownSitePagePath(u.Path)
		}
		if target == "" {
			return attr
		}
		href := redirectLocation(target, withoutUTMParams(u.RawQuery), u.Fragment)
		if href == strings.TrimSpace(html.UnescapeString(m[2]+m[3])) {
			return attr
		}
		return m[1] + `"` + html.EscapeString(href) + `"`
	})
}

// forEachConcurrently runs fn on every item with a fixed pool of workers and
// returns when all are done.
func forEachConcurrently(items []string, workers int, fn func(item string)) {
	var wg sync.WaitGroup
	jobs := make(chan string)
	for w := 0; w < workers && w < len(items); w++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for item := range jobs {
				fn(item)
			}
		}()
	}
	for _, item := range items {
		jobs <- item
	}
	close(jobs)
	wg.Wait()
}

// ownSiteLinkURL parses an href value (HTML-escaped, as written in the CMS)
// and returns it when it points at this site — absolute http(s) or
// protocol-relative on any of the site's hosts (live, www., UAT), or written
// without a scheme as "{domain}/path". Root-relative paths ("/x") count too.
// Anything else (external, mailto:, javascript:, plain text) returns nil.
func ownSiteLinkURL(value, siteDomain string) *url.URL {
	value = strings.TrimSpace(html.UnescapeString(value))
	u, err := url.Parse(value)
	if err != nil || value == "" {
		return nil
	}
	switch {
	case u.Host != "":
		if u.Scheme != "" && u.Scheme != "http" && u.Scheme != "https" {
			return nil
		}
		if !isOwnSiteHost(u.Host, siteDomain) {
			return nil
		}
	case u.Scheme != "" || u.Opaque != "":
		return nil
	case strings.HasPrefix(u.Path, "/"):
		// root-relative link on this site
	default:
		// "kidsactivitypage.com/raising-kids/…": browsers resolve this
		// relative to the current page, so it's broken as written.
		host, rest, _ := strings.Cut(u.Path, "/")
		if !strings.Contains(host, ".") || !isOwnSiteHost(host, siteDomain) {
			return nil
		}
		u.Path = "/" + rest
	}
	return u
}

// isOwnSiteHost reports whether host is one of siteDomain's hosts (the live
// domain, its www. variant, or a UAT alias from site_to_client.json).
func isOwnSiteHost(host, siteDomain string) bool {
	normalize := func(h string) string {
		return strings.TrimPrefix(middlewares.ResolveToProductionDomain(cleanDomain(h)), "www.")
	}
	host = normalize(host)
	return host != "" && host == normalize(siteDomain)
}

// linkedArticleID returns the article ID when path is an article URL —
// /{category}/{id}-{slug} or /{category}/{subcategory}/{id}-{slug}, with any
// old category, the legacy /articles/ prefix, or a trailing slash — and ""
// otherwise.
func linkedArticleID(path string) string {
	_, _, slug, ok := parseSubcategoryArticleDetailPath(path)
	if !ok {
		_, slug, _ = parseArticleDetailPath(path)
	}
	if id := extractArticleIDFromSlug(slug); isNumericID(id) {
		return id
	}
	return ""
}

// ownSitePagePath returns the clean path for a homepage, static page,
// category or subcategory link ("/", "/about", "/fitness",
// "/wine-101/wine-types"), or "" for anything else.
func ownSitePagePath(path string) string {
	seg := strings.Trim(path, "/")
	if seg == "" || staticPageSegments[seg] {
		return "/" + seg
	}
	return listingPagePath(path)
}

// withoutUTMParams drops utm_* tracking params (e.g. ?utm_source=chatgpt.com
// pasted along with a link) from a raw query. Every other param is kept
// exactly as written, in its original order and encoding.
func withoutUTMParams(rawQuery string) string {
	if rawQuery == "" {
		return rawQuery
	}
	params := strings.Split(rawQuery, "&")
	kept := params[:0]
	for _, param := range params {
		key, _, _ := strings.Cut(param, "=")
		if len(key) >= 4 && strings.EqualFold(key[:4], "utm_") {
			continue
		}
		kept = append(kept, param)
	}
	return strings.Join(kept, "&")
}

// -----------------------------------------------------------------------------
// Per-page meta title/description overrides (client_configs)
// -----------------------------------------------------------------------------

// pageMetaOverride returns a client-config-driven title/description for a
// page, keyed under seoMeta.<key> in client_configs, e.g.:
//
//	"seoMeta": {
//	  "home":                   { "title": "...", "description": "..." },
//	  "health":                 { "title": "...", "description": "..." },  // category slug
//	  "kids-health/treatments": { "title": "...", "description": "..." },  // subcategory
//	  "contactUs":              { "title": "...", "description": "..." }   // static page name
//	}
//
// Falls back to fallbackTitle/fallbackDescription when no override — or only
// a partial override — is configured for key.
func pageMetaOverride(config *middlewares.ClientConfig, key, fallbackTitle, fallbackDescription string) (title, description string) {
	title, description = fallbackTitle, fallbackDescription
	if config == nil || key == "" {
		return
	}
	if t := strings.TrimSpace(config.GetString("seoMeta." + key + ".title")); t != "" {
		title = t
	}
	if d := strings.TrimSpace(config.GetString("seoMeta." + key + ".description")); d != "" {
		description = d
	}
	return
}

// articleTitleSuffixFromConfig reports whether article pages append
// " - {displayName}" to their <title>, from the top-level client config key
// "articleTitleSuffix". Unset means true (the default); sites whose live
// article titles are the bare article title set it to false. The same value
// is passed to the frontend so client-side navigation titles match.
func articleTitleSuffixFromConfig(config *middlewares.ClientConfig) bool {
	if config == nil || config.ViperConfig == nil || !config.ViperConfig.IsSet("articleTitleSuffix") {
		return true
	}
	return config.ViperConfig.GetBool("articleTitleSuffix")
}

// articleURLOptions is how a site builds its article URLs, from its config's
// shared block (where the frontend reads the same keys):
//   - WithSubcategory: nest under the subcategory, /{category}/{subcategory}/{id}-{slug}
//     ("articleUrlSubcategory", default true; womenwire.com's URLs leave it out).
//   - SlugFromTitle: without a CMS slug_title, slug the title rather than the meta
//     title ("articleSlugFromTitle", default false; the legacy magazine sites' rule).
//   - AmpersandAsAnd: spell "&" as "and" in the slug ("articleSlugAmpersandAsAnd",
//     default false, which drops it as the theme2 sites' URLs do).
//   - TitleOnly: always slug the title, even when the CMS has a slug_title
//     ("articleSlugTitleOnly", default false; lifeinterest.com, fists.com).
//   - LegacySlug: make the slug with legacyArticleSlug rather than slugify
//     ("articleSlugLegacy", default false; fists.com).
//   - CategoryPaths: the URL slug of a category whose live URL isn't its
//     name's slug ("categoryPaths", see categoryPathsFromConfig).
type articleURLOptions struct {
	WithSubcategory bool
	SlugFromTitle   bool
	AmpersandAsAnd  bool
	TitleOnly       bool
	LegacySlug      bool
	CategoryPaths   *categoryPaths
}

func articleURLOptionsFromConfig(config *middlewares.ClientConfig) articleURLOptions {
	opts := articleURLOptions{WithSubcategory: true}
	if config == nil {
		return opts
	}
	shared, _ := config.Raw["shared"].(map[string]interface{})
	if withSubcategory, ok := shared["articleUrlSubcategory"].(bool); ok {
		opts.WithSubcategory = withSubcategory
	}
	if fromTitle, ok := shared["articleSlugFromTitle"].(bool); ok {
		opts.SlugFromTitle = fromTitle
	}
	if asAnd, ok := shared["articleSlugAmpersandAsAnd"].(bool); ok {
		opts.AmpersandAsAnd = asAnd
	}
	if titleOnly, ok := shared["articleSlugTitleOnly"].(bool); ok {
		opts.TitleOnly = titleOnly
	}
	if legacy, ok := shared["articleSlugLegacy"].(bool); ok {
		opts.LegacySlug = legacy
	}
	opts.CategoryPaths = categoryPathsFromConfig(config)
	return opts
}

// categoryPaths maps a CMS category's slug (its name slugified) to the URL
// slug the site serves it at instead (see categoryPathsFromConfig).
type categoryPaths map[string]string

// categoryPathsFromConfig reads the site's shared.categoryPaths, the CMS
// categories whose URL isn't their name's slug, by CMS name:
//
//	"shared": {"categoryPaths": {"Blogs": "blog"}}
//
// serves the CMS category "Blogs" at /blog (its articles at
// /blog/{id}-{slug}, its sitemap at /sitemap_blog.xml) rather than /blogs,
// which is then no page. A name matches by its slug (any case or spelling
// that slugifies the same). A path must be one plain slug segment (see
// slugSegmentRe) that isn't a route of its own (reservedSingleSegments);
// others are logged and skipped. Subcategories keep their names' slugs.
// nil when the site has none.
func categoryPathsFromConfig(config *middlewares.ClientConfig) *categoryPaths {
	if config == nil {
		return nil
	}
	shared, _ := config.Raw["shared"].(map[string]interface{})
	block, _ := shared["categoryPaths"].(map[string]interface{})
	paths := categoryPaths{}
	for name, value := range block {
		path, _ := value.(string)
		key := slugify(name)
		if key == "" || !slugSegmentRe.MatchString(path) || reservedSingleSegments[path] {
			log.Printf("[WARN] categoryPaths: skipping %q -> %q", name, path)
			continue
		}
		paths[key] = path
	}
	if len(paths) == 0 {
		return nil
	}
	return &paths
}

// urlCategory is the category name a URL is built from: the category's path
// (see categoryPathsFromConfig), which slugifies to itself, else name as it is.
func (p *categoryPaths) urlCategory(name string) string {
	if p != nil {
		if path, ok := (*p)[slugify(name)]; ok {
			return path
		}
	}
	return name
}

// categoryShowsArticle reports whether the site's page for the category at
// slug shows the category's newest article in full instead of listing it,
// from its pages.category.layouts (oos-singlecube's magazine CategoryPage):
//
//	"pages": {"category": {"layouts": {"schedule": "article"}}}
//
// as fists' /rankings and /schedule do, the one article the content team
// keeps updating in each. The articles' own URLs 301 to that page, and the
// category's sitemap lists only the page.
func categoryShowsArticle(config *middlewares.ClientConfig, slug string) bool {
	if config == nil || slug == "" {
		return false
	}
	pages, _ := config.Raw["pages"].(map[string]interface{})
	category, _ := pages["category"].(map[string]interface{})
	layouts, _ := category["layouts"].(map[string]interface{})
	layout, _ := layouts[slug].(string)
	return layout == "article"
}

// slug is the URL slug of the CMS category name.
func (p *categoryPaths) slug(name string) string {
	return slugify(p.urlCategory(name))
}

// withPaths returns categories (from extractSitemapCategories) with each
// one's Slug its URL slug.
func (p *categoryPaths) withPaths(categories []sitemapCategory) []sitemapCategory {
	if p == nil {
		return categories
	}
	out := make([]sitemapCategory, len(categories))
	for i, c := range categories {
		c.Slug = p.slug(c.Name)
		out[i] = c
	}
	return out
}

// legacyArticleSlug is the article slug of the legacy PHP sites that keep it
// (see articleURLOptions.LegacySlug): the text lowercased, every character but
// a-z, 0-9 and spaces dropped, then each space a hyphen, with nothing collapsed
// or trimmed ("Record & World Titles" → "record--world-titles").
func legacyArticleSlug(value string) string {
	var b strings.Builder
	b.Grow(len(value))
	for _, r := range strings.ToLower(value) {
		switch {
		case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
			b.WriteRune(r)
		case r == ' ':
			b.WriteByte('-')
		}
	}
	return b.String()
}

// articleSlugSource is the text an article slug is made from, with "&" spelled
// out when the site's URLs do (slugifyArticleTitle drops it otherwise).
func articleSlugSource(text string, opts articleURLOptions) string {
	if opts.AmpersandAsAnd {
		return strings.ReplaceAll(text, "&", " and ")
	}
	return text
}

// articleTitlePlaceholders are the fields seoMeta.articleDetails.title can use:
// {title} the article's SEO title (meta_title, else title), {headline} its title
// as shown on the page, {Headline} that title with each word capitalised (ucwords).
var articleTitlePlaceholders = []string{"{title}", "{headline}", "{Headline}"}

// articleTitlePattern returns the site's own article <title> format, from
// seoMeta.articleDetails.title ("Gaycommunity : {Headline}"), or "" when it has
// none (or no placeholder), leaving the "{title} - {site}" default.
func articleTitlePattern(config *middlewares.ClientConfig) string {
	if config == nil || config.ViperConfig == nil {
		return ""
	}
	// Through viper, like the other seoMeta entries, so key case doesn't matter.
	pattern := config.ViperConfig.GetString("seoMeta.articleDetails.title")
	for _, placeholder := range articleTitlePlaceholders {
		if strings.Contains(pattern, placeholder) {
			return pattern
		}
	}
	return ""
}

// expandArticleTitlePattern fills an article title pattern (see
// articleTitlePlaceholders); a missing headline falls back to the SEO title.
func expandArticleTitlePattern(pattern, seoTitle, headline string) string {
	if headline == "" {
		headline = seoTitle
	}
	return strings.NewReplacer("{title}", seoTitle, "{headline}", headline, "{Headline}", ucwords(headline)).Replace(pattern)
}

// forArticleURL returns meta as the site's article URLs use it (see
// articleURLOptions); its Category is the one its URL is built from (see
// categoryPaths.urlCategory).
func forArticleURL(meta articlePageMeta, opts articleURLOptions) articlePageMeta {
	if !opts.WithSubcategory {
		meta.SubCategory = ""
	}
	if (opts.TitleOnly || opts.SlugFromTitle && meta.CMSSlugTitle == "") && meta.CMSTitle != "" {
		meta.SlugTitle = meta.CMSTitle
	}
	meta.SlugTitle = articleSlugSource(meta.SlugTitle, opts)
	meta.LegacySlug = opts.LegacySlug
	meta.Category = opts.CategoryPaths.urlCategory(meta.Category)
	return meta
}

// -----------------------------------------------------------------------------
// Config-derived SEO metadata (favicon, logo, Google Search Console)
// -----------------------------------------------------------------------------

// faviconURLFromConfig returns the favicon URL for a client site.
//
// Priority:
//  1. favicon_url in client/global config (full URL)
//  2. {portal_static_cdn_url}/oos/{siteId}/favicon.png
func faviconURLFromConfig(config *middlewares.ClientConfig) string {
	if config == nil {
		return ""
	}
	if url := config.GetString("favicon_url"); url != "" {
		return url
	}

	siteId := config.GetString("siteId")
	portalStatic := config.GetString("portal_static_cdn_url")
	if siteId == "" || portalStatic == "" {
		return ""
	}

	return strings.TrimRight(portalStatic, "/") + "/oos/" + siteId + "/favicon.png"
}

// googleSiteVerificationFromConfig returns the Google Search Console verification
// token from client_configs (key: google_site_verification). Empty when unset.
func googleSiteVerificationFromConfig(config *middlewares.ClientConfig) string {
	if config == nil {
		return ""
	}
	return strings.TrimSpace(config.GetString("google_site_verification"))
}

// logoURLFromConfig returns the organization/site logo URL from client_configs
// (key: logo_url). Empty when unset.
func logoURLFromConfig(config *middlewares.ClientConfig) string {
	if config == nil {
		return ""
	}
	return strings.TrimSpace(config.GetString("logo_url"))
}

// -----------------------------------------------------------------------------
// Meta robots / X-Robots-Tag policy
// -----------------------------------------------------------------------------

// metaRobotsKind selects the production robots policy for a page type.
type metaRobotsKind string

const (
	metaRobotsIndexable metaRobotsKind = "indexable" // homepage, static, category, articles list, shop
	metaRobotsSearch    metaRobotsKind = "search"
	metaRobotsArticle   metaRobotsKind = "article"
	metaRobotsNotFound  metaRobotsKind = "notFound"
)

const (
	robotsNoIndexNoFollow = "noindex,nofollow"
	robotsIndexFollow     = "index,follow"
	robotsNoIndexFollow   = "noindex,follow"
)

// applyMetaRobots sets vars.MetaRobots and the X-Robots-Tag response header.
//
//	UAT / staging / dev / test hosts → noindex,nofollow (all pages)
//	Production:
//	  search   → noindex,follow
//	  article  → index,follow (or noindex,nofollow when CMS is_index=0)
//	  notFound → noindex,nofollow
//	  other    → index,follow
func applyMetaRobots(w http.ResponseWriter, vars *templateVars, req *http.Request, kind metaRobotsKind) {
	value := robotsNoIndexNoFollow
	if req != nil && isSitemapIndexableHost(req) {
		switch kind {
		case metaRobotsSearch:
			value = robotsNoIndexFollow
		case metaRobotsNotFound:
			value = robotsNoIndexNoFollow
		case metaRobotsArticle:
			if vars != nil && strings.Contains(strings.ToLower(vars.MetaRobots), "noindex") {
				value = robotsNoIndexNoFollow
			} else {
				value = robotsIndexFollow
			}
		default:
			value = robotsIndexFollow
		}
	}

	if vars != nil {
		vars.MetaRobots = value
	}
	setXRobotsTag(w, value)
}

// setXRobotsTag writes the X-Robots-Tag header using the spaced form
// expected by SEO audits (e.g. "noindex, nofollow").
func setXRobotsTag(w http.ResponseWriter, value string) {
	if w == nil || value == "" {
		return
	}
	header := strings.ReplaceAll(value, ", ", ",")
	header = strings.ReplaceAll(header, ",", ", ")
	w.Header().Set("X-Robots-Tag", header)
}

// NonProdXRobotsTagMiddleware adds X-Robots-Tag: noindex, nofollow on every
// response for UAT/staging/dev/test environments and hosts.
func NonProdXRobotsTagMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if !isSitemapIndexableHost(req) {
			setXRobotsTag(w, robotsNoIndexNoFollow)
		}
		next.ServeHTTP(w, req)
	})
}

// RedirectCacheControlMiddleware gives every 301 without a Cache-Control the
// same one-hour lifetime as redirectPermanently. It covers the router's own
// redirects (/about/ → /about, /About → /about), which can't set headers.
func RedirectCacheControlMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		next.ServeHTTP(redirectCacheControlWriter{w}, req)
	})
}

type redirectCacheControlWriter struct {
	http.ResponseWriter
}

func (w redirectCacheControlWriter) WriteHeader(statusCode int) {
	if statusCode == http.StatusMovedPermanently && w.Header().Get("Cache-Control") == "" {
		w.Header().Set("Cache-Control", seoRedirectCacheControl)
	}
	w.ResponseWriter.WriteHeader(statusCode)
}

// Unwrap lets http.ResponseController reach the underlying writer (Flush etc.).
func (w redirectCacheControlWriter) Unwrap() http.ResponseWriter {
	return w.ResponseWriter
}

// -----------------------------------------------------------------------------
// CMS → article SEO/social meta parsing
// -----------------------------------------------------------------------------

// articlePageMeta holds SEO and social meta parsed from a CMS getarticledata response.
type articlePageMeta struct {
	Title         string
	Description   string
	Keywords      string
	Author        string
	Robots        string
	Image         string
	ImageAlt      string
	Category      string
	SubCategory   string
	SlugTitle     string // article URL slug source: slug_title, else meta_title, else title
	PublishedTime string // ISO 8601
	// KeywordsFromCategory is true when the CMS has no keywords and Keywords
	// is the "{category}, {subcategory}" fallback (see categoryKeywords).
	KeywordsFromCategory bool
	// CMSSlugTitle and CMSTitle are the CMS slug_title and title as they are, for sites
	// whose URLs fall back to the title rather than the meta title (see forArticleURL).
	CMSSlugTitle string
	CMSTitle     string
	// LegacySlug: SlugTitle becomes the URL slug through legacyArticleSlug (see forArticleURL).
	LegacySlug bool
}

// articlePageMetaFromCMS extracts SEO/social fields from CMS JSON.
func articlePageMetaFromCMS(data []byte) articlePageMeta {
	var response struct {
		Data map[string]interface{} `json:"data"`
	}
	if err := json.Unmarshal(data, &response); err != nil || response.Data == nil {
		return articlePageMeta{}
	}

	d := response.Data

	title := getStringField(d, "meta_title")
	if title == "" {
		title = getStringField(d, "title")
	}

	description := getStringField(d, "sub_head")
	if description == "" {
		description = getStringField(d, "meta_title")
	}
	if description == "" {
		description = getStringField(d, "title")
	}
	description = normalizeMetaDescription(description)

	keywords := getStringField(d, "keywords")
	category := getStringField(d, "category")
	subCategory := getStringField(d, "sub_category")
	keywordsFromCategory := keywords == "" && category != ""
	if keywordsFromCategory {
		keywords = categoryKeywords(category, subCategory)
	}

	author := getStringField(d, "author_name")
	if author == "" {
		author = getStringField(d, "author")
	}

	robots := robotsIndexFollow
	if !isIndexable(d) {
		robots = robotsNoIndexNoFollow
	}

	// Mirrors oos-singlecube's buildArticlePath / sitemap.go's firstNonEmptyField
	// priority: slug_title, then meta_title, then the plain title as a last resort
	// so a URL slug can always be built even when the CMS only has a title.
	slugTitle := getStringField(d, "slug_title")
	if slugTitle == "" {
		slugTitle = getStringField(d, "meta_title")
	}
	if slugTitle == "" {
		slugTitle = getStringField(d, "title")
	}

	imageAlt := imageAltFromImagesAttr(getStringField(d, "images_attr"))
	if imageAlt == "" {
		imageAlt = slugTitle
	}

	return articlePageMeta{
		Title:                title,
		Description:          description,
		Keywords:             keywords,
		Author:               author,
		Robots:               robots,
		Image:                getStringField(d, "image"),
		ImageAlt:             imageAlt,
		Category:             category,
		SubCategory:          subCategory,
		SlugTitle:            slugTitle,
		CMSSlugTitle:         getStringField(d, "slug_title"),
		CMSTitle:             getStringField(d, "title"),
		PublishedTime:        formatArticleTimestamp(d),
		KeywordsFromCategory: keywordsFromCategory,
	}
}

// articleOgImageWidth and articleOgImageHeight describe the fixed crop CMS
// article images are served at, used for the og:image:width/height tags on
// blog detail pages; articleOgImageType is the og:image:type for an image
// whose extension doesn't name an image type.
const (
	articleOgImageWidth  = "800"
	articleOgImageHeight = "533"
	articleOgImageType   = "image/jpeg"
)

// categoryKeywords is the meta keywords fallback for an article without CMS
// keywords: "{category}, {subcategory}", or "" without a category.
func categoryKeywords(category, subCategory string) string {
	if category == "" {
		return ""
	}
	if subCategory != "" {
		return category + ", " + subCategory
	}
	return category
}

// ogImageType returns the og:image:type for an article image URL from its
// extension (CMS heroes are .jpg, .png or .webp), else articleOgImageType.
func ogImageType(imageURL string) string {
	u, err := url.Parse(imageURL)
	if err != nil {
		return articleOgImageType
	}
	if t := mime.TypeByExtension(strings.ToLower(path.Ext(u.Path))); strings.HasPrefix(t, "image/") {
		return t
	}
	return articleOgImageType
}

// applyTo sets template variables from parsed article meta. The <title> is
// "{title} - {displayName}", or the bare title when displayName is empty
// (see articleTitleSuffixFromConfig); og:title and twitter:title are always
// the bare title.
func (m articlePageMeta) applyTo(vars *templateVars, displayName string) {
	if m.Title != "" {
		vars.PageTitle = m.Title
		if displayName != "" {
			vars.PageTitle += " - " + displayName
		}
		vars.OgTitle = m.Title
		vars.TwitterTitle = m.Title
	}
	if m.Description != "" {
		vars.MetaDescription = m.Description
		vars.OgDescription = m.Description
		vars.TwitterDescription = m.Description
	}
	vars.MetaKeywords = m.Keywords
	vars.MetaAuthor = m.Author
	vars.MetaRobots = m.Robots
	vars.OgImage = m.Image
	vars.OgImageAlt = m.ImageAlt
	vars.OgType = "article"
	vars.ArticlePublishedTime = m.PublishedTime
	vars.ArticleSection = m.Category
	if m.Image != "" {
		vars.OgImageWidth = articleOgImageWidth
		vars.OgImageHeight = articleOgImageHeight
		vars.OgImageType = ogImageType(m.Image)
		vars.TwitterCard = "summary_large_image"
		vars.TwitterImage = m.Image
	}
}

// applyOgDefaults fills in the OG/Twitter fields shared by every page type —
// og:site_name, og:locale, og:type (defaults to "website"; article pages set
// "article" themselves beforehand via articlePageMeta.applyTo), and a
// fallback og:image/twitter:image (the site logo) for pages that don't have
// their own image (home, static, category/search, or an article missing a
// CMS image). Call this last, after any page-specific Og*/Twitter* fields
// have already been set.
func applyOgDefaults(vars *templateVars, config *middlewares.ClientConfig) {
	if vars == nil || config == nil {
		return
	}
	if vars.OgSiteName == "" {
		vars.OgSiteName = config.GetString("displayName")
	}
	if vars.OgLocale == "" {
		vars.OgLocale = "en_US"
	}
	if vars.OgType == "" {
		vars.OgType = "website"
	}
	if vars.OgImage == "" {
		vars.OgImage = logoURLFromConfig(config)
	}
	if vars.OgImage != "" && vars.TwitterCard == "" {
		vars.TwitterCard = "summary_large_image"
	}
	if vars.TwitterImage == "" {
		vars.TwitterImage = vars.OgImage
	}
}

// normalizeMetaDescription trims whitespace and the CMS teaser link text
// "Read more" (any casing) when it is appended after a finished sentence,
// e.g. "...every day.  Read more". A sentence that genuinely ends in
// "read more" ("Kids should read more") is left intact. Mirrored by
// oos-singlecube's articleMetaDescription so server- and client-rendered
// descriptions match.
func normalizeMetaDescription(s string) string {
	s = strings.TrimSpace(s)
	const suffix = "read more"
	if len(s) >= len(suffix) && strings.EqualFold(s[len(s)-len(suffix):], suffix) {
		rest := strings.TrimSpace(s[:len(s)-len(suffix)])
		if rest == "" || strings.HasSuffix(rest, ".") || strings.HasSuffix(rest, "!") ||
			strings.HasSuffix(rest, "?") || strings.HasSuffix(rest, "…") {
			s = rest
		}
	}
	return strings.TrimSpace(s)
}

func isIndexable(d map[string]interface{}) bool {
	v, ok := d["is_index"]
	if !ok {
		return true
	}
	switch x := v.(type) {
	case float64:
		return x != 0
	case int:
		return x != 0
	case int64:
		return x != 0
	case string:
		return x != "0" && strings.ToLower(x) != "false"
	case bool:
		return x
	default:
		return true
	}
}

func formatArticleTimestamp(d map[string]interface{}) string {
	raw := d["timestamp"]
	if raw == nil {
		return ""
	}

	var unix int64
	switch x := raw.(type) {
	case float64:
		unix = int64(x)
	case int:
		unix = int64(x)
	case int64:
		unix = x
	case string:
		parsed, err := strconv.ParseInt(strings.TrimSpace(x), 10, 64)
		if err != nil {
			return ""
		}
		unix = parsed
	default:
		return ""
	}

	// CMS timestamps are Unix seconds.
	if unix < 1_000_000_000_000 {
		return time.Unix(unix, 0).UTC().Format(time.RFC3339)
	}
	return time.UnixMilli(unix).UTC().Format(time.RFC3339)
}

func imageAltFromImagesAttr(raw string) string {
	if raw == "" {
		return ""
	}
	var parsed struct {
		Img struct {
			Alt string `json:"alt"`
		} `json:"img"`
	}
	if err := json.Unmarshal([]byte(raw), &parsed); err != nil {
		return ""
	}
	return strings.TrimSpace(parsed.Img.Alt)
}

// -----------------------------------------------------------------------------
// JSON-LD structured data
// -----------------------------------------------------------------------------

// breadcrumbItem is one entry in a BreadcrumbList JSON-LD trail.
type breadcrumbItem struct {
	Name string
	URL  string
}

// homeBreadcrumbItem returns the root "Home" crumb pointing at the site root.
func homeBreadcrumbItem(req *http.Request) breadcrumbItem {
	return breadcrumbItem{Name: "Home", URL: absoluteURL(req, "/")}
}

// marshalJSONLD serializes data as indented JSON for embedding directly
// (unescaped) inside a <script type="application/ld+json"> tag via
// html/template's template.JS type.
func marshalJSONLD(data map[string]interface{}) template.JS {
	b, err := json.MarshalIndent(data, "", "  ")
	if err != nil {
		return ""
	}
	return template.JS(b)
}

// organizationJSONLD builds the site-wide Organization schema. name/logo are
// sourced from client_configs (displayName, logo_url); description always
// mirrors the homepage's SEO meta description (seoMeta.home.description) —
// the Organization's identity shouldn't change per-page — falling back to
// the site-wide client_configs meta.description when seoMeta.home isn't set.
func organizationJSONLD(vars *templateVars, config *middlewares.ClientConfig, req *http.Request) template.JS {
	if config == nil {
		return ""
	}
	name := config.GetString("displayName")
	if name == "" {
		return ""
	}

	data := map[string]interface{}{
		"@context": "https://schema.org",
		"@type":    "Organization",
		"name":     name,
		"url":      absoluteURL(req, "/"),
	}
	if logo := logoURLFromConfig(config); logo != "" {
		data["logo"] = logo
	}
	desc := strings.TrimSpace(config.GetString("seoMeta.home.description"))
	if desc == "" {
		desc = strings.TrimSpace(config.GetString("meta.description"))
	}
	if desc != "" {
		data["description"] = desc
	}
	return marshalJSONLD(data)
}

// websiteJSONLD builds the site-wide WebSite schema (with a SearchAction
// pointing at /search?term=, /search?s= on directory sites).
func websiteJSONLD(config *middlewares.ClientConfig, req *http.Request) template.JS {
	if config == nil {
		return ""
	}
	name := config.GetString("displayName")
	if name == "" {
		return ""
	}
	searchParam := "term"
	if isDirectorySite(config) {
		searchParam = "s"
	}

	data := map[string]interface{}{
		"@context": "https://schema.org",
		"@type":    "WebSite",
		"name":     name,
		"url":      absoluteURL(req, "/"),
		"potentialAction": map[string]interface{}{
			"@type":       "SearchAction",
			"target":      absoluteURL(req, "/search") + "?" + searchParam + "={search_term_string}",
			"query-input": "required name=search_term_string",
		},
	}
	return marshalJSONLD(data)
}

// breadcrumbJSONLD builds a BreadcrumbList schema from a trail of crumbs.
// Returns empty when fewer than 2 items are given — e.g. the blog homepage,
// which never shows a breadcrumb trail.
func breadcrumbJSONLD(items []breadcrumbItem) template.JS {
	if len(items) < 2 {
		return ""
	}

	elements := make([]map[string]interface{}, 0, len(items))
	for i, item := range items {
		el := map[string]interface{}{
			"@type":    "ListItem",
			"position": i + 1,
			"name":     item.Name,
		}
		if item.URL != "" {
			el["item"] = item.URL
		}
		elements = append(elements, el)
	}

	data := map[string]interface{}{
		"@context":        "https://schema.org",
		"@type":           "BreadcrumbList",
		"itemListElement": elements,
	}
	return marshalJSONLD(data)
}

// webPageJSONLD builds the page-specific WebPage schema from already-resolved
// template vars (PageTitle/OgTitle, CanonicalUrl, MetaDescription) plus the
// site's WebSite/Organization identity.
func webPageJSONLD(vars *templateVars, config *middlewares.ClientConfig, req *http.Request) template.JS {
	return pageSchemaJSONLD(vars, config, req, "WebPage")
}

// collectionPageJSONLD builds the same schema as webPageJSONLD but typed as
// CollectionPage — the standard schema.org type for a page whose main content
// is a list of other items (e.g. a category/subcategory articles listing).
func collectionPageJSONLD(vars *templateVars, config *middlewares.ClientConfig, req *http.Request) template.JS {
	return pageSchemaJSONLD(vars, config, req, "CollectionPage")
}

// pageSchemaJSONLD builds a WebPage-shaped schema under the given @type
// (WebPage or CollectionPage) from already-resolved template vars
// (PageTitle/OgTitle, CanonicalUrl, MetaDescription) plus the site's
// WebSite/Organization identity.
func pageSchemaJSONLD(vars *templateVars, config *middlewares.ClientConfig, req *http.Request, schemaType string) template.JS {
	if vars == nil || config == nil {
		return ""
	}

	name := vars.OgTitle
	if name == "" {
		name = vars.PageTitle
	}
	if name == "" {
		return ""
	}

	siteName := config.GetString("displayName")

	data := map[string]interface{}{
		"@context":    "https://schema.org",
		"@type":       schemaType,
		"name":        name,
		"url":         vars.CanonicalUrl,
		"description": vars.MetaDescription,
		"inLanguage":  "en-US",
		"isPartOf": map[string]interface{}{
			"@type": "WebSite",
			"name":  siteName,
			"url":   absoluteURL(req, "/"),
		},
	}
	if logo := logoURLFromConfig(config); logo != "" {
		data["publisher"] = map[string]interface{}{
			"@type": "Organization",
			"name":  siteName,
			"logo": map[string]interface{}{
				"@type": "ImageObject",
				"url":   logo,
			},
		}
	}
	return marshalJSONLD(data)
}

// articleJSONLD builds the schema.org Article schema for a blog article
// detail page. It reads from vars fields already populated by
// articlePageMeta.applyTo (OgTitle, MetaDescription, OgImage,
// ArticlePublishedTime, ArticleSection, MetaAuthor) — call this after that.
func articleJSONLD(vars *templateVars, config *middlewares.ClientConfig, req *http.Request) template.JS {
	if vars == nil || config == nil {
		return ""
	}

	headline := vars.OgTitle
	if headline == "" {
		headline = vars.PageTitle
	}
	if headline == "" {
		return ""
	}

	siteName := config.GetString("displayName")

	data := map[string]interface{}{
		"@context": "https://schema.org",
		"@type":    "Article",
		"headline": headline,
		"mainEntityOfPage": map[string]interface{}{
			"@type": "WebPage",
			"@id":   vars.CanonicalUrl,
		},
	}
	if vars.MetaDescription != "" {
		data["description"] = vars.MetaDescription
	}
	if vars.ArticlePublishedTime != "" {
		data["datePublished"] = vars.ArticlePublishedTime
		data["dateModified"] = vars.ArticlePublishedTime
	}
	if vars.ArticleSection != "" {
		data["articleSection"] = vars.ArticleSection
	}
	if vars.OgImage != "" {
		data["image"] = []string{vars.OgImage}
	}
	if vars.MetaAuthor != "" {
		data["author"] = map[string]interface{}{"@type": "Person", "name": vars.MetaAuthor}
	} else if siteName != "" {
		data["author"] = map[string]interface{}{"@type": "Organization", "name": siteName}
	}
	if logo := logoURLFromConfig(config); logo != "" {
		data["publisher"] = map[string]interface{}{
			"@type": "Organization",
			"name":  siteName,
			"logo": map[string]interface{}{
				"@type": "ImageObject",
				"url":   logo,
			},
		}
	} else if siteName != "" {
		data["publisher"] = map[string]interface{}{"@type": "Organization", "name": siteName}
	}
	return marshalJSONLD(data)
}

// applyStructuredData populates the JSON-LD schema fields on vars:
//   - Organization and WebSite are site-wide and rendered on every page.
//   - WebPage is page-specific, derived from vars set earlier by the caller.
//   - BreadcrumbList is page-specific and omitted when breadcrumbs has fewer
//     than 2 items (the blog homepage passes nil — it never shows breadcrumbs).
//
// Call this after all other vars fields (PageTitle, OgTitle, CanonicalUrl,
// MetaDescription, …) have been set, since WebPage reads from them.
//
// Used by page types that haven't been migrated to a more specific
// applyXStructuredData function yet (all-articles list, search, static
// pages, shop). See applyHomepageStructuredData, applyCategoryStructuredData,
// and applyArticleStructuredData for the per-page-type schema sets.
func applyStructuredData(vars *templateVars, config *middlewares.ClientConfig, req *http.Request, breadcrumbs []breadcrumbItem) {
	if vars == nil {
		return
	}
	vars.OrganizationSchema = organizationJSONLD(vars, config, req)
	vars.WebsiteSchema = websiteJSONLD(config, req)
	vars.WebPageSchema = webPageJSONLD(vars, config, req)
	vars.BreadcrumbSchema = breadcrumbJSONLD(breadcrumbs)
}

// applyHomepageStructuredData sets only the site-wide Organization and
// WebSite schemas. The homepage never shows a breadcrumb trail and doesn't
// get its own WebPage schema — Organization + WebSite are its identity.
func applyHomepageStructuredData(vars *templateVars, config *middlewares.ClientConfig, req *http.Request) {
	if vars == nil {
		return
	}
	vars.OrganizationSchema = organizationJSONLD(vars, config, req)
	vars.WebsiteSchema = websiteJSONLD(config, req)
}

// applyCategoryStructuredData sets BreadcrumbList + CollectionPage (the
// standard schema.org type for a page whose main content lists other items,
// e.g. a category/subcategory articles listing) for category pages.
//
// Call this after all other vars fields (PageTitle, CanonicalUrl,
// MetaDescription, …) have been set, since CollectionPage reads from them.
func applyCategoryStructuredData(vars *templateVars, config *middlewares.ClientConfig, req *http.Request, breadcrumbs []breadcrumbItem) {
	if vars == nil {
		return
	}
	vars.BreadcrumbSchema = breadcrumbJSONLD(breadcrumbs)
	vars.WebPageSchema = collectionPageJSONLD(vars, config, req)
}

// applyArticleStructuredData sets BreadcrumbList + WebPage + Article for a
// blog article detail page.
//
// Call this after articlePageMeta.applyTo has populated vars (OgTitle,
// MetaDescription, OgImage, ArticlePublishedTime, ArticleSection,
// MetaAuthor), since WebPage and Article both read from those fields.
func applyArticleStructuredData(vars *templateVars, config *middlewares.ClientConfig, req *http.Request, breadcrumbs []breadcrumbItem) {
	if vars == nil {
		return
	}
	vars.BreadcrumbSchema = breadcrumbJSONLD(breadcrumbs)
	vars.WebPageSchema = webPageJSONLD(vars, config, req)
	vars.ArticleSchema = articleJSONLD(vars, config, req)
}

// -----------------------------------------------------------------------------
// Directory listing pages: meta patterns and LocalBusiness structured data
// -----------------------------------------------------------------------------

// listingMetaTokens are the values a directory page's seoMeta.<page> title and
// description patterns can use: {keyword}, {Keyword} (KeywordTitle, else the
// keyword in ucwords), {location} ("City, ST"), {city}, {state} (the code),
// {stateName}, {name}, {category}, {page} and {displayName}.
type listingMetaTokens struct {
	Keyword, Location, City, State, StateName, Name, Category, DisplayName string
	// KeywordTitle is {Keyword} for a site category: its label as the site
	// spells it ("Food & Dining", not "Food And Dining").
	KeywordTitle string
	Page         int
}

// expandListingPattern fills a directory meta pattern's tokens.
func expandListingPattern(pattern string, t listingMetaTokens) string {
	keywordTitle := t.KeywordTitle
	if keywordTitle == "" {
		keywordTitle = ucwords(t.Keyword)
	}
	return strings.NewReplacer(
		"{keyword}", t.Keyword,
		"{Keyword}", keywordTitle,
		"{location}", t.Location,
		"{city}", t.City,
		"{state}", t.State,
		"{stateName}", t.StateName,
		"{name}", t.Name,
		"{category}", t.Category,
		"{page}", strconv.Itoa(t.Page),
		"{displayName}", t.DisplayName,
	).Replace(pattern)
}

// listingPageMeta returns a directory page's title and description: the
// seoMeta.<key> patterns (see pageMetaOverride), else the defaults, with
// their tokens filled. An empty default description reads as the title.
func listingPageMeta(config *middlewares.ClientConfig, key, defaultTitle, defaultDescription string, t listingMetaTokens) (title, description string) {
	titlePattern, descriptionPattern := pageMetaOverride(config, key, defaultTitle, defaultDescription)
	return expandListingMeta(titlePattern, descriptionPattern, t)
}

// expandListingMeta fills a title and description pattern; an empty
// description reads as the title.
func expandListingMeta(titlePattern, descriptionPattern string, t listingMetaTokens) (title, description string) {
	title = expandListingPattern(titlePattern, t)
	if descriptionPattern == "" {
		return title, title
	}
	return title, expandListingPattern(descriptionPattern, t)
}

// cutOnWord cuts s to at most max characters, at a word boundary when it has
// to cut.
func cutOnWord(s string, max int) string {
	runes := []rune(strings.Join(strings.Fields(s), " "))
	if len(runes) <= max {
		return string(runes)
	}
	cut := string(runes[:max])
	if !unicode.IsSpace(runes[max]) {
		if i := strings.LastIndex(cut, " "); i > 0 {
			cut = cut[:i]
		}
	}
	return strings.TrimRight(cut, " ,;:-")
}

// localBusinessJSONLD builds the LocalBusiness schema of a listing detail
// page: name, url, PostalAddress, the first phone, geo when the listing has
// coordinates, and its images, description, opening hours and payment
// options when it has them.
func localBusinessJSONLD(req *http.Request, l listings.Listing) template.JS {
	if l.Name == "" {
		return ""
	}
	address := map[string]interface{}{
		"@type":           "PostalAddress",
		"addressLocality": l.City,
		"addressRegion":   l.State,
	}
	if l.Address != "" {
		address["streetAddress"] = l.Address
	}
	if l.Zip != "" {
		address["postalCode"] = l.Zip
	}
	data := map[string]interface{}{
		"@context": "https://schema.org",
		"@type":    "LocalBusiness",
		"name":     l.Name,
		"url":      absoluteURL(req, l.URL),
		"address":  address,
	}
	if len(l.Phones) > 0 {
		data["telephone"] = l.Phones[0].Number
	}
	if l.Lat != nil && l.Lon != nil {
		data["geo"] = map[string]interface{}{
			"@type":     "GeoCoordinates",
			"latitude":  *l.Lat,
			"longitude": *l.Lon,
		}
	}
	if len(l.Images) > 0 {
		data["image"] = l.Images
	}
	if description := strings.Join(strings.Fields(l.Description), " "); description != "" {
		data["description"] = description
	}
	if hours := openingHours(l.Hours); len(hours) > 0 {
		data["openingHours"] = hours
	}
	if len(l.PaymentOptions) > 0 {
		data["paymentAccepted"] = strings.Join(l.PaymentOptions, ", ")
	}
	return marshalJSONLD(data)
}

// openingHoursDays are the schema.org openingHours day codes of the days the
// listings' hours name.
var openingHoursDays = map[string]string{
	"monday": "Mo", "tuesday": "Tu", "wednesday": "We", "thursday": "Th", "friday": "Fr", "saturday": "Sa", "sunday": "Su",
}

// hoursRangeRe matches one opening time range of a listing's hours,
// "8:00 AM - 5:00 PM" (minutes optional).
var hoursRangeRe = regexp.MustCompile(`(?i)^(\d{1,2})(?::(\d{2}))?\s*([AP]M)\s*-\s*(\d{1,2})(?::(\d{2}))?\s*([AP]M)$`)

// openAllDayHours are the hours texts (lowercased) of a day open around the
// clock: the listings' "Open All Day", and "Open 24 Hours".
var openAllDayHours = map[string]bool{"open all day": true, "open 24 hours": true}

// openingHours turns a listing's hours lines, "Monday : 8:00 AM - 5:00 PM"
// (ranges may be comma-separated), into schema.org openingHours values,
// "Mo 08:00-17:00", one per range; "Monday : Open All Day" is
// "Mo 00:00-23:59". "Closed" and lines it can't read are skipped.
func openingHours(lines []string) []string {
	var out []string
	for _, line := range lines {
		day, ranges, ok := strings.Cut(line, ":")
		code := openingHoursDays[strings.ToLower(strings.TrimSpace(day))]
		if !ok || code == "" {
			continue
		}
		if openAllDayHours[strings.ToLower(strings.Join(strings.Fields(ranges), " "))] {
			out = append(out, code+" 00:00-23:59")
			continue
		}
		for _, r := range strings.Split(ranges, ",") {
			m := hoursRangeRe.FindStringSubmatch(strings.TrimSpace(r))
			if m == nil {
				continue
			}
			from, okFrom := clockTime(m[1], m[2], m[3])
			to, okTo := clockTime(m[4], m[5], m[6])
			if okFrom && okTo {
				out = append(out, code+" "+from+"-"+to)
			}
		}
	}
	return out
}

// clockTime is a 12-hour time as "HH:MM" (24-hour); ok is false when it isn't one.
func clockTime(hour, minute, meridiem string) (string, bool) {
	h, err := strconv.Atoi(hour)
	if err != nil || h < 1 || h > 12 {
		return "", false
	}
	if minute == "" {
		minute = "00"
	}
	if m, err := strconv.Atoi(minute); err != nil || m > 59 {
		return "", false
	}
	h %= 12
	if strings.EqualFold(meridiem, "PM") {
		h += 12
	}
	return fmt.Sprintf("%02d:%s", h, minute), true
}
