package routes

import (
	"context"
	"encoding/json"
	"fmt"
	"html/template"
	"log"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"
	"unicode"

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

// shopTemplateName is the "template" of the shop sites (sparknoes.com,
// beyondcheap.com, brandzones.com): a commonshop catalogue at the legacy
// shop's own URLs (/search, /product_detail/{sku}/{slug}), plus the CMS blog.
const shopTemplateName = "shop"

// isShopSite reports whether the client config uses the shop template.
func isShopSite(config *middlewares.ClientConfig) bool {
	return config != nil && siteTemplateName(config.Raw) == shopTemplateName
}

// shopLookupTimeout bounds the shop API lookups one listing or sitemap
// makes (master categories, a category check), well within the server's
// WriteTimeout.
const shopLookupTimeout = 4 * time.Second

// shopProductLookupTimeout bounds a product page's product lookup: longer,
// as the head (title, canonical, Product JSON-LD) needs it and the API can
// take several seconds uncached, but below the 10s WriteTimeout.
const shopProductLookupTimeout = 7 * time.Second

// The site-specific shop pages: their shared.shop.pages key and URL. A site
// has one only when its config has that key (brandzones today); elsewhere
// the URL is routed as before (a 404, as on live).
const (
	shopDealsPage      = "deals"
	shopTopBrandsPage  = "topBrands"
	shopCategoriesPage = "categories"
)

var shopPagePaths = map[string]string{
	shopDealsPage:      "/deals",
	shopTopBrandsPage:  "/top-brands",
	shopCategoriesPage: "/categories",
}

// shopPageDefaultTitles title a site-specific page whose config has no title.
var shopPageDefaultTitles = map[string]string{
	shopDealsPage:      "Deals",
	shopTopBrandsPage:  "Top Brands",
	shopCategoriesPage: "Categories",
}

// shopBlock is the site's shared.shop block (also read by the frontend).
func shopBlock(config *middlewares.ClientConfig) map[string]interface{} {
	if config == nil {
		return nil
	}
	shared, _ := config.Raw["shared"].(map[string]interface{})
	block, _ := shared["shop"].(map[string]interface{})
	return block
}

// shopPageTitle returns the title of the site-specific shop page name
// (shared.shop.pages.<name>.title, else its default title); ok is false
// when the site doesn't have the page.
func shopPageTitle(config *middlewares.ClientConfig, name string) (title string, ok bool) {
	pages, _ := shopBlock(config)["pages"].(map[string]interface{})
	page, ok := pages[name].(map[string]interface{})
	if !ok {
		return "", false
	}
	if title, _ := page["title"].(string); strings.TrimSpace(title) != "" {
		return strings.TrimSpace(title), true
	}
	return shopPageDefaultTitles[name], true
}

// shopEnabledPagePaths are the URLs of the site-specific shop pages the site
// has, in a fixed order.
func shopEnabledPagePaths(config *middlewares.ClientConfig) []string {
	if !isShopSite(config) {
		return nil
	}
	var paths []string
	for _, name := range []string{shopDealsPage, shopTopBrandsPage, shopCategoriesPage} {
		if _, ok := shopPageTitle(config, name); ok {
			paths = append(paths, shopPagePaths[name])
		}
	}
	return paths
}

// cmsUnlistedShopSite reports whether the request is for a shop site the CMS
// doesn't list (beyondcheap.com: no blog). Such a site has no CMS content,
// so none of another site's is served: the CMS fallbacks that read an
// unlisted domain as "every site" (categories, sitemaps, article ids) are
// off for it. A failed CMS request reports false, as categoryRouteMissing
// serves the page then. Other templates are never checked.
func cmsUnlistedShopSite(req *http.Request) bool {
	if !isShopSite(middlewares.GetClientConfig(req.Context())) {
		return false
	}
	response, err := loadCMSCategories()
	if err != nil {
		log.Printf("[ERROR] cmsUnlistedShopSite: categories: %v", err)
		return false
	}
	data, _ := response["data"].(map[string]interface{})
	_, listed := domainCategories(data, middlewares.ResolveToProductionDomain(requestPublicHost(req)))
	return !listed
}

// ---------------------------------------------------------------------------
// Page shell and meta
// ---------------------------------------------------------------------------

// shopPage is the head and status of a shop page shell.
type shopPage struct {
	Name          string // the page name passed to the frontend
	Title         string
	Description   string
	CanonicalPath string // "" for none
	Robots        metaRobotsKind
	Breadcrumbs   []breadcrumbItem
	Product       template.JS // Product JSON-LD
	Image         string      // og:image and twitter:image, when the page has its own
	NoStore       bool        // a page made without its data (upstream failed)
}

// serveShopPage writes a shop page's shell (the StaticPage shell, as for
// the directory pages: header, footer, theme, GA and ads all apply; the
// frontend renders the page from the URL) with its own head.
func serveShopPage(w http.ResponseWriter, req *http.Request, tpl *template.Template, page shopPage) {
	config := middlewares.GetClientConfig(req.Context())
	vars := pageShellVars(req, config, page.Name, page.Title, page.Description)
	vars.CanonicalUrl = ""
	if page.CanonicalPath != "" {
		vars.CanonicalUrl = absoluteURL(req, page.CanonicalPath)
	}
	applyMetaRobots(w, vars, req, page.Robots)
	applyStructuredData(vars, config, req, page.Breadcrumbs)
	vars.ArticleSchema = page.Product
	if page.Image != "" {
		vars.OgImage, vars.TwitterImage, vars.TwitterCard = page.Image, page.Image, "summary_large_image"
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if page.NoStore {
		w.Header().Set("Cache-Control", "no-store")
	}
	if err := tpl.ExecuteTemplate(w, "root", vars); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

// shopMetaTokens are the values a shop page's seoMeta.<key> title and
// description patterns can use: {category} (shopCategory), {query}
// (shopSearch), {name}, {brand}, {description} (shopProduct), {page} and
// {displayName} (all).
type shopMetaTokens struct {
	Category, Query, Name, Brand, Description, DisplayName string
	Page                                                   int
}

// shopPageMeta returns a shop page's title and description: the
// seoMeta.<key> patterns (see pageMetaOverride), else the defaults, with
// their tokens filled. A description that comes out empty reads as the
// title. Values are filled in one pass, so a product name holding "{page}"
// stays as it is.
func shopPageMeta(config *middlewares.ClientConfig, key, defaultTitle, defaultDescription string, t shopMetaTokens) (title, description string) {
	titlePattern, descriptionPattern := pageMetaOverride(config, key, defaultTitle, defaultDescription)
	// The page number goes in a listing's title from page 2, unless the pattern places it.
	if t.Page > 1 && !strings.Contains(titlePattern, "{page}") {
		titlePattern += " - Page {page}"
	}
	replacer := strings.NewReplacer(
		"{category}", t.Category,
		"{query}", t.Query,
		"{name}", t.Name,
		"{brand}", t.Brand,
		"{description}", t.Description,
		"{page}", strconv.Itoa(t.Page),
		"{displayName}", t.DisplayName,
	)
	title = strings.TrimSpace(replacer.Replace(titlePattern))
	description = strings.TrimSpace(replacer.Replace(descriptionPattern))
	if description == "" {
		description = title
	}
	return title, description
}

// ---------------------------------------------------------------------------
// Listing: /search
// ---------------------------------------------------------------------------

// shopSearchKeys are the /search params a shop listing keeps, in the order
// its canonical URL lists them. Any other key (per_page, the legacy app's
// empty placeholders...) is dropped by a 301.
var shopSearchKeys = []string{"keyword", "master_category", "category", "brand", "prices", "availability", "sort", "page"}

// shopSearchParams is a shop listing's query, normalised.
type shopSearchParams struct {
	Keyword, MasterCategory, Category, Brand, Prices, Availability, Sort string
	Page                                                                 int
}

// shopLegacyValues decodes the legacy shop's slug encodings of a
// master_category, category or brand value: "-sp--and--sp-" and "--and--"
// are " & ", "-sp-" a space, "-obl-" an apostrophe. Earlier pairs win where
// two match at the same place.
var shopLegacyValues = strings.NewReplacer("-sp--and--sp-", " & ", "--and--", " & ", "-sp-", " ", "-obl-", "'")

// shopValueKeys are the params whose values get shopLegacyValues and whose
// value may be split by a raw "&" (see parseShopSearch).
var shopValueKeys = []string{"master_category", "category", "brand"}

// parseShopSearch reads a /search query on a shop site into its params, and
// reports whether the query differs from their canonical form (so the page
// 301s to it). Rules:
//   - Only shopSearchKeys are kept, the first of each; empty values and
//     values that don't decode are dropped. The legacy facet form's "price"
//     is read as "prices".
//   - keyword, master_category, category and brand have their whitespace
//     trimmed and collapsed; the last three are decoded (shopLegacyValues).
//   - A raw "&" inside a value, as beyondcheap's links write
//     "master_category=Home & Kitchen", arrives as "master_category=Home "
//     and a stray key " Kitchen": a key-only part starting with a space that
//     follows a value ending in one is joined back into it.
//   - prices is kept when it is a band 1-5; availability unless "0" (the
//     legacy app's "none"); sort when price or price-desc (relevance is the
//     default, so not in the URL); page when it is a number above 1.
//
// Which master_category or category a "-" between words means needs the
// shop API, so it is resolveShopSearch's job.
func parseShopSearch(rawQuery string) (shopSearchParams, bool) {
	type pair struct{ key, value string }
	var pairs []pair
	changed := false
	if rawQuery != "" {
		for _, part := range strings.Split(rawQuery, "&") {
			k, v, hasValue := strings.Cut(part, "=")
			key, err := url.QueryUnescape(k)
			value, verr := url.QueryUnescape(v)
			if err != nil || verr != nil || part == "" {
				changed = true
				continue
			}
			if last := len(pairs) - 1; !hasValue && strings.HasPrefix(key, " ") && last >= 0 &&
				strings.HasSuffix(pairs[last].value, " ") && isOneOf(pairs[last].key, shopValueKeys) {
				pairs[last].value += "&" + key
				changed = true
				continue
			}
			pairs = append(pairs, pair{key, value})
		}
	}

	var p shopSearchParams
	seen := map[string]bool{}
	for _, kv := range pairs {
		// The legacy facet form's name for prices.
		if kv.key == "price" {
			kv.key, changed = "prices", true
		}
		if !isOneOf(kv.key, shopSearchKeys) || seen[kv.key] {
			changed = true
			continue
		}
		seen[kv.key] = true
		value := strings.Join(strings.Fields(kv.value), " ")
		switch kv.key {
		case "keyword":
			p.Keyword = value
		case "master_category":
			value = strings.Join(strings.Fields(shopLegacyValues.Replace(value)), " ")
			p.MasterCategory = value
		case "category":
			value = strings.Join(strings.Fields(shopLegacyValues.Replace(value)), " ")
			p.Category = value
		case "brand":
			value = strings.Join(strings.Fields(shopLegacyValues.Replace(value)), " ")
			p.Brand = value
		case "prices":
			if len(value) != 1 || value < "1" || value > "5" {
				value = ""
			}
			p.Prices = value
		case "availability":
			if value == "0" {
				value = ""
			}
			p.Availability = value
		case "sort":
			if value != "price" && value != "price-desc" {
				value = ""
			}
			p.Sort = value
		case "page":
			if n, err := strconv.Atoi(value); err == nil && n > 1 && isNumericID(value) {
				p.Page = n
				value = strconv.Itoa(n)
			} else {
				value = ""
			}
		}
		if value == "" || value != kv.value {
			changed = true
		}
	}
	return p, changed
}

// query is the params' canonical query string: shopSearchKeys order, values
// form-encoded (url.QueryEscape: space as "+", "&" as "%26"), sort only
// when withSort.
func (p shopSearchParams) query(withSort bool) string {
	var parts []string
	add := func(key, value string) {
		if value != "" {
			parts = append(parts, key+"="+url.QueryEscape(value))
		}
	}
	add("keyword", p.Keyword)
	add("master_category", p.MasterCategory)
	add("category", p.Category)
	add("brand", p.Brand)
	add("prices", p.Prices)
	add("availability", p.Availability)
	if withSort {
		add("sort", p.Sort)
	}
	if p.Page > 1 {
		add("page", strconv.Itoa(p.Page))
	}
	return strings.Join(parts, "&")
}

// path is the listing's canonical URL (sort only when withSort).
func (p shopSearchParams) path(withSort bool) string {
	if q := p.query(withSort); q != "" {
		return "/search?" + q
	}
	return "/search"
}

// isCategoryListing reports whether the listing is a category page (indexed):
// a master_category and/or category, maybe a page, and nothing else.
func (p shopSearchParams) isCategoryListing() bool {
	return (p.MasterCategory != "" || p.Category != "") &&
		p.Keyword == "" && p.Brand == "" && p.Prices == "" && p.Availability == "" && p.Sort == ""
}

// shopLookups are the shop API answers resolveShopSearch needs, so it can
// be tested without the API.
type shopLookups interface {
	// MasterCategories lists the shop's master category names.
	MasterCategories(ctx context.Context) ([]string, error)
	// CategoryName searches the category: found is whether it finds products,
	// name the shop's own spelling of the category when the first product's
	// category has the same slug ("" otherwise).
	CategoryName(ctx context.Context, category string) (name string, found bool, err error)
}

// resolveShopSearch settles the master_category and category values whose
// spelling the shop API decides, and reports whether it changed one:
//   - a master_category is the API's own name for it when its slug is one's
//     (e.g. "home-and-kitchen" or "home & kitchen" → "Home & Kitchen");
//   - a category with a "-" between two letters or digits (the legacy
//     menu's "Vacuum-Food-Sealers") is the shop's own spelling of it, read
//     from a search on it ("Vacuum Food Sealers"; "T-Shirts" stays): the API
//     reads such a "-" as a space too, so both spellings would otherwise be
//     pages;
//   - a value that still doesn't match (a master category the API doesn't
//     list, a category no product has) has each such "-" read as a space,
//     and a master category is matched again.
//
// When the API can't tell, the value is left as it is.
func resolveShopSearch(ctx context.Context, p *shopSearchParams, lookups shopLookups) bool {
	changed := false
	if p.MasterCategory != "" {
		if masters, err := lookups.MasterCategories(ctx); err != nil {
			log.Printf("[WARN] shop search: master categories: %v", err)
		} else {
			value := shopMasterCategoryNamed(masters, p.MasterCategory)
			if value == "" {
				value = shopMasterCategoryNamed(masters, dashesAsSpaces(p.MasterCategory))
			}
			if value == "" {
				value = dashesAsSpaces(p.MasterCategory)
			}
			if value != p.MasterCategory {
				p.MasterCategory, changed = value, true
			}
		}
	}
	if spaced := dashesAsSpaces(p.Category); spaced != p.Category {
		value := p.Category
		name, found, err := lookups.CategoryName(ctx, p.Category)
		switch {
		case err != nil:
			log.Printf("[WARN] shop search: category %q: %v", p.Category, err)
		case name != "":
			value = name
		case !found:
			value = spaced
		}
		if value != p.Category {
			p.Category, changed = value, true
		}
	}
	return changed
}

// shopMasterCategoryNamed returns the master category (of masters) whose slug
// is value's, "" when none is.
func shopMasterCategoryNamed(masters []string, value string) string {
	slug := slugify(value)
	for _, name := range masters {
		if slug != "" && slugify(name) == slug {
			return name
		}
	}
	return ""
}

// dashesAsSpaces turns each "-" between two letters or digits into a space.
func dashesAsSpaces(value string) string {
	runes := []rune(value)
	for i := 1; i+1 < len(runes); i++ {
		if runes[i] == '-' && isLetterOrDigit(runes[i-1]) && isLetterOrDigit(runes[i+1]) {
			runes[i] = ' '
		}
	}
	return string(runes)
}

func isLetterOrDigit(r rune) bool {
	return unicode.IsLetter(r) || unicode.IsDigit(r)
}

// shopAPILookups answers shopLookups from the shop API (through shopCache).
type shopAPILookups struct{}

func (shopAPILookups) MasterCategories(ctx context.Context) ([]string, error) {
	return shopMasterCategories(ctx)
}

func (shopAPILookups) CategoryName(ctx context.Context, category string) (string, bool, error) {
	status, body, err := shopGet(ctx, shopAPIBaseURL()+"/commonshop/search?category="+url.QueryEscape(category)+"&per_page=1")
	if err != nil {
		return "", false, err
	}
	if status != http.StatusOK {
		return "", false, fmt.Errorf("upstream returned %d", status)
	}
	var response struct {
		Data struct {
			Result []struct {
				Category string `json:"category"`
			} `json:"result"`
			MetaInfo struct {
				TotalFound json.Number `json:"total_found"`
			} `json:"metaInfo"`
		} `json:"data"`
	}
	if err := json.Unmarshal(body, &response); err != nil {
		return "", false, err
	}
	total, err := response.Data.MetaInfo.TotalFound.Int64()
	if err != nil {
		return "", false, err
	}
	name := ""
	if len(response.Data.Result) > 0 {
		if first := strings.TrimSpace(response.Data.Result[0].Category); slugify(first) == slugify(category) {
			name = first
		}
	}
	return name, total > 0, nil
}

// shopMasterCategories lists the shop's master category names
// (getMasterCategories, in its order).
func shopMasterCategories(ctx context.Context) ([]string, error) {
	status, body, err := shopGet(ctx, shopAPIBaseURL()+"/commonshop/getMasterCategories")
	if err != nil {
		return nil, err
	}
	if status != http.StatusOK {
		return nil, fmt.Errorf("upstream returned %d", status)
	}
	var response struct {
		Data []struct {
			MasterCategory string `json:"master_category"`
		} `json:"data"`
	}
	if err := json.Unmarshal(body, &response); err != nil {
		return nil, err
	}
	var names []string
	for _, item := range response.Data {
		if name := strings.TrimSpace(item.MasterCategory); name != "" {
			names = append(names, name)
		}
	}
	return names, nil
}

// serveShopSearch serves /search (and /search/) on a shop site: the listing
// shell, after one 301 to the canonical query when the URL isn't it (see
// parseShopSearch and resolveShopSearch).
//   - Category listing (master_category and/or category, maybe page):
//     seoMeta.shopCategory, indexed, canonical to itself, BreadcrumbList.
//   - Any other listing (keyword, brand, prices, availability, sort, or
//     nothing): seoMeta.shopSearch, noindex,follow, canonical to itself
//     without sort.
func serveShopSearch(w http.ResponseWriter, req *http.Request, tpl *template.Template, config *middlewares.ClientConfig, lookups shopLookups) {
	p, changed := parseShopSearch(req.URL.RawQuery)
	ctx, cancel := context.WithTimeout(req.Context(), shopLookupTimeout)
	defer cancel()
	if resolveShopSearch(ctx, &p, lookups) {
		changed = true
	}
	if changed || req.URL.Path != "/search" {
		redirectPermanently(w, req, "/search", p.query(true))
		return
	}

	tokens := shopMetaTokens{DisplayName: config.GetString("displayName"), Page: p.Page}
	if p.isCategoryListing() {
		tokens.Category = p.Category
		if tokens.Category == "" {
			tokens.Category = p.MasterCategory
		}
		title, description := shopPageMeta(config, "shopCategory", "{category} - {displayName}", "", tokens)
		breadcrumbs := []breadcrumbItem{homeBreadcrumbItem(req)}
		if p.MasterCategory != "" {
			breadcrumbs = append(breadcrumbs, breadcrumbItem{Name: p.MasterCategory, URL: absoluteURL(req, shopSearchParams{MasterCategory: p.MasterCategory}.path(false))})
		}
		if p.Category != "" {
			breadcrumbs = append(breadcrumbs, breadcrumbItem{Name: p.Category, URL: absoluteURL(req, shopSearchParams{MasterCategory: p.MasterCategory, Category: p.Category}.path(false))})
		}
		serveShopPage(w, req, tpl, shopPage{
			Name:          "shopSearch",
			Title:         title,
			Description:   description,
			CanonicalPath: p.path(true),
			Robots:        metaRobotsIndexable,
			Breadcrumbs:   breadcrumbs,
		})
		return
	}

	tokens.Page = 0 // a search isn't indexed, so its title has no page number
	for _, value := range []string{p.Keyword, p.Brand, p.Category, p.MasterCategory} {
		if value != "" {
			tokens.Query = value
			break
		}
	}
	if tokens.Query == "" {
		tokens.Query = "Search"
	}
	title, description := shopPageMeta(config, "shopSearch", "{query} - {displayName}", "", tokens)
	serveShopPage(w, req, tpl, shopPage{
		Name:          "shopSearch",
		Title:         title,
		Description:   description,
		CanonicalPath: p.path(false),
		Robots:        metaRobotsSearch,
	})
}

// ---------------------------------------------------------------------------
// Product: /product_detail/:sku/:slug
// ---------------------------------------------------------------------------

// shopProduct is the part of a commonshop product/{sku} answer
// (data.product_details) the page head uses.
type shopProduct struct {
	SKU            string `json:"sku"`
	Name           string `json:"product_name"`
	Description    string `json:"description_string"`
	ImageZoom      string `json:"image_zoom"`
	ImageSmall     string `json:"image_small"`
	Brand          string `json:"brand"`
	Availability   string `json:"availability"`
	Price          string `json:"price"`
	Currency       string `json:"currency"`
	Category       string `json:"category"`
	MasterCategory string `json:"master_category"`
	Feature        string `json:"feature"`
}

// image is the product's image URL.
func (p shopProduct) image() string {
	if p.ImageZoom != "" {
		return p.ImageZoom
	}
	return p.ImageSmall
}

// shopProductURL is the shop API URL of a product, with the site's
// affiliate when it has one (the same URL /data/shop/product/:sku fetches,
// so the two share shopCache).
func shopProductURL(sku, affiliate string) string {
	target := shopAPIBaseURL() + "/commonshop/product/" + url.PathEscape(sku)
	if affiliate != "" {
		target += "?affiliate=" + url.QueryEscape(affiliate)
	}
	return target
}

// errShopProductMissing: the shop API has no such product (404).
var errShopProductMissing = fmt.Errorf("product not found")

// fetchShopProduct loads a product from the shop API: errShopProductMissing
// for a 404, another error when there is no product to show (400 for an
// affiliate the API doesn't know, 5xx, timeout, an answer without one).
func fetchShopProduct(ctx context.Context, sku, affiliate string) (shopProduct, error) {
	status, body, err := shopGet(ctx, shopProductURL(sku, affiliate))
	if err != nil {
		return shopProduct{}, err
	}
	if status == http.StatusNotFound {
		return shopProduct{}, errShopProductMissing
	}
	if status != http.StatusOK {
		return shopProduct{}, fmt.Errorf("upstream returned %d", status)
	}
	var response struct {
		Data struct {
			Product *shopProduct `json:"product_details"`
		} `json:"data"`
	}
	if err := json.Unmarshal(body, &response); err != nil {
		return shopProduct{}, err
	}
	if response.Data.Product == nil || strings.TrimSpace(response.Data.Product.Name) == "" {
		return shopProduct{}, fmt.Errorf("no product in the answer")
	}
	product := *response.Data.Product
	if product.SKU == "" {
		product.SKU = sku
	}
	return product, nil
}

// shopProductSlug is the slug of a product's canonical URL: "1" on a site
// whose shared.shop.productSlug is "index" (beyondcheap's live URLs), else
// the product name as the frontend's titleToSlug makes it.
func shopProductSlug(config *middlewares.ClientConfig, name string) string {
	if mode, _ := shopBlock(config)["productSlug"].(string); mode == "index" {
		return "1"
	}
	return shopTitleSlug(name)
}

// shopProductSlugLength is the most UTF-16 code units of the title
// titleToSlug keeps.
const shopProductSlugLength = 120

// shopTitleSlug mirrors oos-singlecube's titleToSlug (src/utils/shop.ts):
//
//	encodeURIComponent(title.replace(/\s+/g, '-').slice(0, 120))
//
// Each run of JS whitespace is one "-", the result is cut to 120 UTF-16 code
// units, then percent-encoded as encodeURIComponent does. Where the cut
// would split a surrogate pair (JS then throws) the pair is left out.
func shopTitleSlug(title string) string {
	var b strings.Builder
	inSpace := false
	for _, r := range title {
		if isJSSpace(r) {
			if !inSpace {
				b.WriteByte('-')
			}
			inSpace = true
			continue
		}
		inSpace = false
		b.WriteRune(r)
	}
	s := b.String()
	units := 0
	for i, r := range s {
		n := 1 // UTF-16 code units
		if r > 0xFFFF {
			n = 2
		}
		if units+n > shopProductSlugLength {
			s = s[:i]
			break
		}
		units += n
	}
	return encodeURIComponent(s)
}

// isJSSpace reports whether r is whitespace to JS's \s.
func isJSSpace(r rune) bool {
	switch r {
	case '\t', '\n', '\v', '\f', '\r', ' ', '\u00a0', '\u1680', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000', '\ufeff':
		return true
	}
	return r >= '\u2000' && r <= '\u200a'
}

// encodeURIComponent percent-encodes s as JS's encodeURIComponent does: every
// UTF-8 byte but A-Z a-z 0-9 - _ . ! ~ * ' ( ).
func encodeURIComponent(s string) string {
	const hex = "0123456789ABCDEF"
	var b strings.Builder
	for i := 0; i < len(s); i++ {
		c := s[i]
		if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' || strings.IndexByte("-_.!~*'()", c) >= 0 {
			b.WriteByte(c)
			continue
		}
		b.WriteByte('%')
		b.WriteByte(hex[c>>4])
		b.WriteByte(hex[c&15])
	}
	return b.String()
}

// shopProductPath is a product's canonical path.
func shopProductPath(config *middlewares.ClientConfig, p shopProduct) string {
	return "/product_detail/" + encodeURIComponent(p.SKU) + "/" + shopProductSlug(config, p.Name)
}

// shopProductDescriptionLength is the most characters of a product's
// description its meta description keeps.
const shopProductDescriptionLength = 155

// ShopProductHandler serves /product_detail/:sku/:slug (and with a trailing
// slash, or without the slug) on shop sites; other sites get the URL routed
// as before, by the not-found handler. The slug is ignored, as on live.
//   - No slug: 404, as on live.
//   - The shop API has the product: the product shell with
//     seoMeta.shopProduct, canonical /product_detail/{sku}/{slug} (see
//     shopProductSlug), og:image and Product JSON-LD.
//   - The API has no such product (404): the not-found page.
//   - No answer (400 while the API doesn't know the site's affiliate, 5xx,
//     timeout): the shell with a generic title, noindex, no canonical.
func ShopProductHandler() http.Handler {
	return shopProductHandler(NotFoundHandler(), pageTemplates())
}

func shopProductHandler(other http.Handler, tpl *template.Template) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		config := middlewares.GetClientConfig(req.Context())
		if !isShopSite(config) {
			other.ServeHTTP(w, req)
			return
		}
		params := httprouter.ParamsFromContext(req.Context())
		sku := params.ByName("sku")
		if params.ByName("slug") == "" || strings.TrimSpace(sku) == "" {
			serveNotFoundPage(w, req, tpl)
			return
		}

		displayName := config.GetString("displayName")
		ctx, cancel := context.WithTimeout(req.Context(), shopProductLookupTimeout)
		defer cancel()
		product, err := fetchShopProduct(ctx, sku, shopAffiliateFromConfig(config))
		if err == errShopProductMissing {
			serveNotFoundPage(w, req, tpl)
			return
		}
		// Digit slugs only where the canonical slug is "1" (beyondcheap's live
		// URLs 404 any other): another slug 301s to it.
		if shopProductSlug(config, "") == "1" && !isNumericID(params.ByName("slug")) {
			if err == nil {
				sku = product.SKU
			}
			redirectPermanently(w, req, "/product_detail/"+sku+"/1", req.URL.RawQuery)
			return
		}
		if err != nil {
			log.Printf("[WARN] shop product %q: %v", sku, err)
			title := "Product Details - " + displayName
			serveShopPage(w, req, tpl, shopPage{Name: "shopProduct", Title: title, Description: title, Robots: metaRobotsSearch, NoStore: true})
			return
		}

		canonical := shopProductPath(config, product)
		title, description := shopPageMeta(config, "shopProduct", "{name} - {displayName}", "{description}", shopMetaTokens{
			Name:        product.Name,
			Brand:       product.Brand,
			Category:    product.Category,
			Description: cutOnWord(product.Description, shopProductDescriptionLength),
			DisplayName: displayName,
		})
		breadcrumbs := []breadcrumbItem{homeBreadcrumbItem(req)}
		if product.MasterCategory != "" {
			breadcrumbs = append(breadcrumbs, breadcrumbItem{Name: product.MasterCategory, URL: absoluteURL(req, shopSearchParams{MasterCategory: product.MasterCategory}.path(false))})
		}
		if product.Category != "" {
			breadcrumbs = append(breadcrumbs, breadcrumbItem{Name: product.Category, URL: absoluteURL(req, shopSearchParams{MasterCategory: product.MasterCategory, Category: product.Category}.path(false))})
		}
		breadcrumbs = append(breadcrumbs, breadcrumbItem{Name: product.Name, URL: absoluteURL(req, canonical)})
		serveShopPage(w, req, tpl, shopPage{
			Name:          "shopProduct",
			Title:         title,
			Description:   description,
			CanonicalPath: canonical,
			Robots:        metaRobotsIndexable,
			Breadcrumbs:   breadcrumbs,
			Product:       productJSONLD(product, absoluteURL(req, canonical)),
			Image:         product.image(),
		})
	})
}

// shopAvailability maps the shop API's availability to schema.org's.
var shopAvailability = map[string]string{
	"in stock":     "https://schema.org/InStock",
	"out of stock": "https://schema.org/OutOfStock",
	"pre order":    "https://schema.org/PreOrder",
	"preorder":     "https://schema.org/PreOrder",
	"backorder":    "https://schema.org/BackOrder",
}

// gtinProperties is the schema.org property of a GTIN by its length.
var gtinProperties = map[int]string{8: "gtin8", 12: "gtin12", 13: "gtin13", 14: "gtin14"}

// productJSONLD builds a product page's Product schema: name, image,
// description, sku, brand, the GTIN (gtin8/12/13/14 by its length) and mpn
// from the product's feature JSON, and an Offer (price, currency,
// availability, the page URL) when it has a price.
func productJSONLD(p shopProduct, pageURL string) template.JS {
	data := map[string]interface{}{
		"@context": "https://schema.org",
		"@type":    "Product",
		"name":     p.Name,
		"sku":      p.SKU,
		"url":      pageURL,
	}
	if image := p.image(); image != "" {
		data["image"] = []string{image}
	}
	if description := strings.TrimSpace(p.Description); description != "" {
		data["description"] = description
	}
	if p.Brand != "" {
		data["brand"] = map[string]interface{}{"@type": "Brand", "name": p.Brand}
	}
	var feature map[string]interface{}
	if json.Unmarshal([]byte(p.Feature), &feature) == nil {
		if gtin, _ := feature["gtin"].(string); isNumericID(gtin) {
			property := gtinProperties[len(gtin)]
			if property == "" {
				property = "gtin"
			}
			data[property] = gtin
		}
		if mpn, _ := feature["mpn"].(string); strings.TrimSpace(mpn) != "" {
			data["mpn"] = strings.TrimSpace(mpn)
		}
	}
	if price, err := strconv.ParseFloat(strings.TrimSpace(p.Price), 64); err == nil && price > 0 {
		offer := map[string]interface{}{
			"@type": "Offer",
			"price": strconv.FormatFloat(price, 'f', 2, 64),
			"url":   pageURL,
		}
		if p.Currency != "" {
			offer["priceCurrency"] = p.Currency
		}
		if availability, ok := shopAvailability[strings.ToLower(strings.TrimSpace(p.Availability))]; ok {
			offer["availability"] = availability
		}
		data["offers"] = offer
	}
	return marshalJSONLD(data)
}

// ---------------------------------------------------------------------------
// Site-specific pages: /deals, /top-brands, /categories
// ---------------------------------------------------------------------------

// ShopPageHandler serves the site-specific shop page name (see
// shopPagePaths) on shop sites that have it; its trailing-slash URL 301s to
// it. Other sites, and shop sites without the page, get the URL routed as
// before, by the not-found handler.
func ShopPageHandler(name string) http.Handler {
	return shopPageHandler(name, NotFoundHandler(), pageTemplates())
}

func shopPageHandler(name string, other http.Handler, tpl *template.Template) http.Handler {
	path := shopPagePaths[name]
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		config := middlewares.GetClientConfig(req.Context())
		pageTitle, ok := shopPageTitle(config, name)
		if !isShopSite(config) || !ok {
			other.ServeHTTP(w, req)
			return
		}
		if req.URL.Path != path {
			redirectPermanently(w, req, path, req.URL.RawQuery)
			return
		}
		title, description := pageMetaOverride(config, name, pageTitle+" - "+config.GetString("displayName"), "")
		if description == "" {
			description = title
		}
		serveShopPage(w, req, tpl, shopPage{
			Name:          name,
			Title:         title,
			Description:   description,
			CanonicalPath: path,
			Robots:        metaRobotsIndexable,
			Breadcrumbs:   []breadcrumbItem{homeBreadcrumbItem(req), {Name: pageTitle, URL: absoluteURL(req, path)}},
		})
	})
}

// shopIndexPHPTarget returns where a legacy CodeIgniter URL on a shop site,
// /index.php?/{path}[&{query}] (e.g. /index.php?/deals), goes: /{path} with
// the rest of the query. ok is false for any other URL, and for a {path}
// that isn't a plain same-site path ("//host", a backslash), so it never
// leaves the site.
func shopIndexPHPTarget(path, rawQuery string) (target, query string, ok bool) {
	if strings.TrimSuffix(path, "/") != "/index.php" {
		return "", "", false
	}
	first, rest, _ := strings.Cut(rawQuery, "&")
	target, err := url.PathUnescape(first)
	if err != nil || !strings.HasPrefix(target, "/") || strings.HasPrefix(target, "//") || strings.ContainsAny(target, "\\?#") {
		return "", "", false
	}
	return target, rest, true
}

// serveShopIndexPHPRedirect 301s a shop site's /index.php?/{path} URL (see
// shopIndexPHPTarget) to /{path}, before the site's legacyUrls rules (whose
// /index.php rule would keep the "?/{path}" query). Reports whether it
// wrote a redirect.
func serveShopIndexPHPRedirect(w http.ResponseWriter, req *http.Request) bool {
	if !isShopSite(middlewares.GetClientConfig(req.Context())) {
		return false
	}
	target, query, ok := shopIndexPHPTarget(req.URL.Path, req.URL.RawQuery)
	if !ok {
		return false
	}
	redirectPermanently(w, req, target, query)
	return true
}

// shopHasSitemapPage reports whether the site serves the /sitemap page: on
// a shop site only with pages.sitemap content (beyondcheap has none; its
// live /sitemap is a 500), as on every other site always.
func shopHasSitemapPage(config *middlewares.ClientConfig) bool {
	return !isShopSite(config) || hasPageContent(config.Raw, "sitemap")
}

// SitemapPageHandler serves /sitemap: the HTML sitemap page, a 404 on a
// shop site without one (see shopHasSitemapPage).
func SitemapPageHandler() http.Handler {
	page := StaticPageHandler("sitemap")
	notFound := NotFoundHandler()
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if !shopHasSitemapPage(middlewares.GetClientConfig(req.Context())) {
			notFound.ServeHTTP(w, req)
			return
		}
		page.ServeHTTP(w, req)
	})
}

// shopSitemapListingPaths are the master-category listing URLs a shop
// site's /sitemap_pages.xml lists, in the API's order; none when the shop
// API can't list them.
func shopSitemapListingPaths(ctx context.Context) []string {
	ctx, cancel := context.WithTimeout(ctx, shopLookupTimeout)
	defer cancel()
	masters, err := shopMasterCategories(ctx)
	if err != nil {
		log.Printf("[WARN] shop sitemap: master categories: %v", err)
		return nil
	}
	paths := make([]string, 0, len(masters))
	for _, name := range masters {
		paths = append(paths, shopSearchParams{MasterCategory: name}.path(false))
	}
	return paths
}
