package routes

import (
	"context"
	"errors"
	"html/template"
	"log"
	"math"
	"net/http"
	"net/url"
	"reflect"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"

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

// directoryTemplateName is the "template" of the directory sites (business
// listings by location and keyword, plus the CMS articles).
const directoryTemplateName = "directory"

// listingsStore serves the directory sites' listings (see InitListingsStore).
var listingsStore listings.Store = listings.Disabled{}

// listingsAPICacheTTL is how long the listing API's answers are kept.
const listingsAPICacheTTL = time.Hour

// InitListingsStore serves the listings from the business listing API when
// the config has listings_api_url and listings_api_key, else from the import
// named by listings_jsonl_path. Neither, or a file that fails to load, leaves
// the store disabled: directory pages then answer 503 and the data API
// listings_unavailable.
func InitListingsStore() {
	apiURL, apiKey := viper.GetString("listings_api_url"), viper.GetString("listings_api_key")
	if apiURL != "" && apiKey != "" {
		log.Printf("[INFO] listings: serving from the listing API at %s", apiURL)
		listingsStore = listings.NewAPIStore(apiURL, apiKey, listingsAPICacheTTL, listingsSite)
		return
	}
	if apiURL != "" {
		log.Printf("[ERROR] listings: listings_api_url is set without listings_api_key; not using the listing API")
	}
	listingsStore = listings.NewStore(viper.GetString("listings_jsonl_path"))
}

// listingsSite is the request's site as the listing API names it: its client
// name ("localpages", "cured", ...).
func listingsSite(ctx context.Context) string {
	config := middlewares.GetClientConfig(ctx)
	if config == nil {
		return ""
	}
	return config.GetString("_client")
}

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

// directoryCategory is a directory.categories entry: the label the site shows,
// the slug of its browse URL and the keyword it searches. A category with
// Keywords (its subcategories) is a category group: it searches any of them
// or its keyword, and listings whose group is its label.
type directoryCategory struct {
	Label    string
	Slug     string
	Keyword  string
	Keywords []string
	// group is a category group's filter, compiled once (see
	// directorySettingsFrom); nil for other categories.
	group *listings.Matcher
}

// directorySettings is a directory site's "directory" config block.
type directorySettings struct {
	DefaultLocation listings.Location
	PageSize        int
	NearbyCount     int
	Categories      []directoryCategory
	// RadiusMiles > 0: searches find the listings within this distance of the
	// city's centre, nearest first; 0: the exact city.
	RadiusMiles   float64
	IndexBrowse   bool
	IndexDetail   bool
	IndexCity     bool
	IndexState    bool
	IndexCategory bool
	// PlaceTextState is the state page's place text: "intro", "full" (with
	// the article's sections) or "" (none); PlaceTextCity the city page's:
	// "intro" or "".
	PlaceTextState string
	PlaceTextCity  string
}

// placeTextFull is the placeText.state value that shows the state article's
// sections too.
const placeTextFull = "full"

const (
	defaultDirectoryNearbyCount = 5
	// listingsUnavailableRetryAfter is the Retry-After (seconds) of a
	// directory page while the listings store is unavailable.
	listingsUnavailableRetryAfter = "3600"
)

// directorySettingsFrom reads the client's "directory" block:
//
//	"directory": {
//	  "defaultLocation": {"city": "Ashburn", "state": "VA"},
//	  "pageSize": 10, "nearbyCount": 5,
//	  "radiusMiles": 15,
//	  "categories": [{"label": "Hotels", "slug": "hotels", "keyword": "hotels", "keywords": ["Motels", "Inns"]}],
//	  "seo": {"indexBrowse": false, "indexDetail": false, "indexCity": false, "indexState": false, "indexCategory": false},
//	  "placeText": {"state": "intro", "city": "intro"}
//	}
//
// A category without a slug gets its label's; one without a keyword searches
// its slug with hyphens as spaces. The frontend-only keys (home, newsletter,
// yextPublisherId, searchArticles...) reach the app with the raw block.
//
// Each config's settings are read once (see directorySettingsCache).
func directorySettingsFrom(config *middlewares.ClientConfig) directorySettings {
	var block map[string]interface{}
	if config != nil {
		block, _ = config.Raw["directory"].(map[string]interface{})
	}
	if block == nil {
		return parseDirectorySettings(nil)
	}
	key := reflect.ValueOf(block).Pointer()
	if cached, ok := directorySettingsCache.Load(key); ok {
		return cached.(cachedDirectorySettings).settings
	}
	settings := parseDirectorySettings(block)
	directorySettingsCache.Store(key, cachedDirectorySettings{block: block, settings: settings})
	return settings
}

// directorySettingsCache keeps each config's directory settings, keyed by the
// address of its "directory" block (loaded once at startup), so its category
// groups compile once per client. An entry holds its block, so no other map
// can take that address while it is cached.
var directorySettingsCache sync.Map // map[uintptr]cachedDirectorySettings

type cachedDirectorySettings struct {
	block    map[string]interface{}
	settings directorySettings
}

// parseDirectorySettings reads a "directory" block (see directorySettingsFrom).
func parseDirectorySettings(block map[string]interface{}) directorySettings {
	settings := directorySettings{PageSize: listings.DefaultPageSize, NearbyCount: defaultDirectoryNearbyCount}
	if loc, ok := block["defaultLocation"].(map[string]interface{}); ok {
		city, _ := loc["city"].(string)
		state, _ := loc["state"].(string)
		if city = strings.TrimSpace(city); city != "" && listings.IsStateCode(state) {
			settings.DefaultLocation = listings.Location{City: city, State: strings.ToUpper(state)}
		}
	}
	if n, ok := block["pageSize"].(float64); ok && n >= 1 {
		settings.PageSize = int(n)
	}
	if n, ok := block["nearbyCount"].(float64); ok && n >= 0 {
		settings.NearbyCount = int(n)
	}
	categories, _ := block["categories"].([]interface{})
	for _, item := range categories {
		entry, _ := item.(map[string]interface{})
		label, _ := entry["label"].(string)
		slug, _ := entry["slug"].(string)
		keyword, _ := entry["keyword"].(string)
		label, slug, keyword = strings.TrimSpace(label), listings.NameSlug(slug), strings.TrimSpace(keyword)
		if slug == "" {
			slug = listings.NameSlug(label)
		}
		if slug == "" {
			continue
		}
		if label == "" {
			label = ucwords(keywordFromSlug(slug))
		}
		if keyword == "" {
			keyword = keywordFromSlug(slug)
		}
		category := directoryCategory{Label: label, Slug: slug, Keyword: keyword}
		terms, _ := entry["keywords"].([]interface{})
		for _, term := range terms {
			if term, _ := term.(string); strings.TrimSpace(term) != "" {
				category.Keywords = append(category.Keywords, strings.TrimSpace(term))
			}
		}
		if len(category.Keywords) > 0 {
			group := listings.NewMatcher(settings.listingQuery("", category, true, listings.Location{}))
			category.group = &group
		}
		settings.Categories = append(settings.Categories, category)
	}
	if n, ok := block["radiusMiles"].(float64); ok && n > 0 {
		settings.RadiusMiles = n
	}
	seo, _ := block["seo"].(map[string]interface{})
	settings.IndexBrowse, _ = seo["indexBrowse"].(bool)
	settings.IndexDetail, _ = seo["indexDetail"].(bool)
	settings.IndexCity, _ = seo["indexCity"].(bool)
	settings.IndexState, _ = seo["indexState"].(bool)
	settings.IndexCategory, _ = seo["indexCategory"].(bool)
	placeText, _ := block["placeText"].(map[string]interface{})
	if state, _ := placeText["state"].(string); state == "intro" || state == placeTextFull {
		settings.PlaceTextState = state
	}
	if city, _ := placeText["city"].(string); city == "intro" {
		settings.PlaceTextCity = city
	}
	return settings
}

// category returns the site category with this slug.
func (s directorySettings) category(slug string) (directoryCategory, bool) {
	for _, c := range s.Categories {
		if c.Slug == slug {
			return c, true
		}
	}
	return directoryCategory{}, false
}

// categoryNamed returns the site category whose label, slug or keyword is
// this search keyword, any case.
func (s directorySettings) categoryNamed(keyword string) (directoryCategory, bool) {
	keyword = strings.TrimSpace(keyword)
	if keyword == "" {
		return directoryCategory{}, false
	}
	for _, c := range s.Categories {
		if strings.EqualFold(keyword, c.Label) || strings.EqualFold(keyword, c.Slug) || strings.EqualFold(keyword, c.Keyword) {
			return c, true
		}
	}
	return directoryCategory{}, false
}

// listingQuery is the store query for keyword in loc, page 1 of the site's
// page size and radius. For a category group (a site category with
// keywords) it searches the group instead: any of its terms, or its label as
// the record's group.
func (s directorySettings) listingQuery(keyword string, category directoryCategory, isCategory bool, loc listings.Location) listings.Query {
	q := listings.Query{Keyword: keyword, Location: loc, RadiusMiles: s.RadiusMiles, Page: 1, PageSize: s.PageSize}
	if isCategory && len(category.Keywords) > 0 {
		q.Keyword = ""
		q.AnyOf = append(append([]string{}, category.Keywords...), category.Keyword)
		q.Group = category.Label
	}
	return q
}

// listingCategory returns the first site category (in config order) that one
// of the listing's categories matches, by label or keyword, any case; else the
// first category group the listing is in, as a search of that group finds it
// (see listingQuery).
func (s directorySettings) listingCategory(l listings.Listing) (directoryCategory, bool) {
	for _, c := range s.Categories {
		for _, name := range l.Categories {
			if strings.EqualFold(name, c.Label) || strings.EqualFold(name, c.Keyword) {
				return c, true
			}
		}
	}
	for _, c := range s.Categories {
		if c.group != nil && c.group.Matches(l) {
			return c, true
		}
	}
	return directoryCategory{}, false
}

// keywordFromSlug is the keyword a browse slug searches: hyphens as spaces.
func keywordFromSlug(slug string) string {
	return strings.ReplaceAll(slug, "-", " ")
}

// directoryPathKind is the page a directory URL names.
type directoryPathKind int

const (
	directoryCityPath directoryPathKind = iota + 1
	directoryBrowsePath
	directoryDetailPath
)

// directoryPath is a parsed directory URL, /{st}/{city}[/{category}[/{n}]] or
// /{st}/{city}/{id}-{slug}.
type directoryPath struct {
	Kind     directoryPathKind
	State    string // lowercase
	CitySlug string
	Slug     string // browse: the category slug (canonical form)
	Page     int    // browse: 1-based
	ID       string // detail
}

// listingSegmentRe matches a listing detail segment, {id}-{slug} or {id}, the
// id digits or a verified listing's "lp-" and digits.
var listingSegmentRe = regexp.MustCompile(`^((?:lp-)?[0-9]+)(?:-.*)?$`)

// isDirectoryPath reports whether path is a directory URL: its first segment
// is a US state code (any case).
func isDirectoryPath(path string) bool {
	first, _, _ := strings.Cut(strings.TrimPrefix(path, "/"), "/")
	return listings.IsStateCode(first)
}

// parseDirectoryPath reads a directory URL (see isDirectoryPath) in any case
// or spelling (%20, +, spaces, a trailing slash). ok is false for a URL that
// names no directory page: /{st} alone, too many segments, a page number
// below 1, or a page number after a listing.
//
// A third segment of digits, or digits then "-" (each maybe after "lp-"), is
// a listing, unless it is one of the site's category slugs.
func parseDirectoryPath(path string, settings directorySettings) (directoryPath, bool) {
	segments := strings.Split(strings.Trim(path, "/"), "/")
	if len(segments) < 2 || len(segments) > 4 || !listings.IsStateCode(segments[0]) {
		return directoryPath{}, false
	}
	p := directoryPath{Kind: directoryCityPath, State: strings.ToLower(segments[0]), CitySlug: listings.CitySlug(segments[1])}
	if p.CitySlug == "" {
		return directoryPath{}, false
	}
	if len(segments) == 2 {
		return p, true
	}
	slug := listings.NameSlug(segments[2])
	if slug == "" {
		return directoryPath{}, false
	}
	if m := listingSegmentRe.FindStringSubmatch(segments[2]); m != nil {
		if _, isCategory := settings.category(slug); !isCategory {
			if len(segments) == 4 {
				return directoryPath{}, false
			}
			p.Kind, p.ID = directoryDetailPath, m[1]
			return p, true
		}
	}
	p.Kind, p.Slug, p.Page = directoryBrowsePath, slug, 1
	if len(segments) == 4 {
		n, err := strconv.Atoi(segments[3])
		if err != nil || !isNumericID(segments[3]) || n < 1 {
			return directoryPath{}, false
		}
		p.Page = n
	}
	return p, true
}

// location is the URL's location, its city as the slug spells it until the
// store gives its name.
func (p directoryPath) location() listings.Location {
	return listings.Location{City: p.CitySlug, State: p.State}
}

// canonicalPath is the URL's canonical form for a city or browse page (page 1
// without its number). A listing's canonical URL is its own url, from the store.
func (p directoryPath) canonicalPath() string {
	path := "/" + p.State + "/" + p.CitySlug
	if p.Kind == directoryBrowsePath {
		path += "/" + p.Slug
		if p.Page > 1 {
			path += "/" + strconv.Itoa(p.Page)
		}
	}
	return path
}

// canonicalDirectoryPath returns the canonical path of a directory URL: a
// listing's own url (when the store has it), /{st} for a state page, else the
// canonical form of a city or browse URL. found is false when that state,
// city or browse page is a 404 (see stateHasCities and directoryPageExists).
// ok is false when path isn't a directory page.
func canonicalDirectoryPath(ctx context.Context, path string, settings directorySettings) (canonical string, found, ok bool) {
	if state, ok := statePathCode(path); ok {
		return "/" + strings.ToLower(state), stateHasCities(ctx, state), true
	}
	p, ok := parseDirectoryPath(path, settings)
	if !ok {
		return "", false, false
	}
	if p.Kind == directoryDetailPath {
		if l, found, err := listingsStore.Get(ctx, p.ID); err == nil && found {
			return l.URL, true, true
		}
		return path, true, true
	}
	return p.canonicalPath(), directoryPageExists(ctx, p, settings), true
}

// browseQuery is the keyword and category of a browse slug: a site category's
// keyword and label, else the slug with hyphens as spaces.
func (s directorySettings) browseQuery(slug string) (keyword, label string) {
	if c, ok := s.category(slug); ok {
		return c.Keyword, c.Label
	}
	keyword = keywordFromSlug(slug)
	return keyword, ucwords(keyword)
}

// directoryPage is the head and status of a directory page shell.
type directoryPage struct {
	Name          string // the page name passed to the frontend, also its seoMeta key
	Title         string
	Description   string
	CanonicalPath string
	Robots        metaRobotsKind
	Breadcrumbs   []breadcrumbItem
	LocalBusiness template.JS
	Image         string // og:image and twitter:image, when the page has its own
}

// serveDirectoryPage writes a directory page's shell (the StaticPage shell,
// so header, footer, theme, GA and ads all apply; the frontend renders the
// page from the URL) with its own head.
func serveDirectoryPage(w http.ResponseWriter, req *http.Request, tpl *template.Template, page directoryPage) {
	config := middlewares.GetClientConfig(req.Context())
	vars := pageShellVars(req, config, page.Name, page.Title, page.Description)
	vars.CanonicalUrl = absoluteURL(req, page.CanonicalPath)
	applyMetaRobots(w, vars, req, page.Robots)
	applyStructuredData(vars, config, req, page.Breadcrumbs)
	vars.ArticleSchema = page.LocalBusiness
	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 err := tpl.ExecuteTemplate(w, "root", vars); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

// serveListingsUnavailable writes a directory page's shell while the listings
// store is unavailable: 503 with Retry-After, noindex, no canonical or
// structured data. The frontend shows labels.listingsUnavailable.
func serveListingsUnavailable(w http.ResponseWriter, req *http.Request, tpl *template.Template, pageName, title string) {
	config := middlewares.GetClientConfig(req.Context())
	vars := pageShellVars(req, config, pageName, title, title)
	vars.CanonicalUrl = ""
	applyMetaRobots(w, vars, req, metaRobotsNotFound)

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.Header().Set("Cache-Control", "no-store")
	w.Header().Set("Retry-After", listingsUnavailableRetryAfter)
	w.WriteHeader(http.StatusServiceUnavailable)
	if err := tpl.ExecuteTemplate(w, "root", vars); err != nil {
		log.Printf("[ERROR] directory: unavailable page: %v", err)
	}
}

// indexableKind is the robots policy of a directory page the site may or may
// not let search engines index (directory.seo): index,follow when it does,
// else noindex,follow (metaRobotsSearch's policy).
func indexableKind(index bool) metaRobotsKind {
	if index {
		return metaRobotsIndexable
	}
	return metaRobotsSearch
}

// listingsFailed logs a store error other than the store being unavailable.
func listingsFailed(what string, err error) {
	if err != listings.ErrUnavailable {
		log.Printf("[ERROR] directory: %s: %v", what, err)
	}
}

// serveDirectoryPath serves a directory URL (see isDirectoryPath) on a
// directory site: city, browse and listing pages, each 301ing in one hop to
// its canonical URL first. Reports whether it wrote a response; false for
// other sites and paths.
func serveDirectoryPath(w http.ResponseWriter, req *http.Request, tpl *template.Template) bool {
	config := middlewares.GetClientConfig(req.Context())
	if !isDirectorySite(config) || !isDirectoryPath(req.URL.Path) {
		return false
	}
	settings := directorySettingsFrom(config)
	if state, ok := statePathCode(req.URL.Path); ok {
		serveStatePage(w, req, tpl, config, settings, state)
		return true
	}
	p, ok := parseDirectoryPath(req.URL.Path, settings)
	if !ok {
		serveNotFoundPage(w, req, tpl)
		return true
	}
	if p.Kind == directoryDetailPath {
		serveListingDetail(w, req, tpl, config, settings, p)
		return true
	}
	siteCategory, isCategory := settings.category(p.Slug)
	keyword, category := settings.browseQuery(p.Slug)
	q := settings.listingQuery(keyword, siteCategory, isCategory, p.location())
	q.Page = p.Page
	if p.Kind == directoryCityPath {
		q = listings.Query{Location: p.location(), PageSize: 1} // only whether the city has listings
	}
	if canonical := p.canonicalPath(); canonical != req.URL.Path {
		// Only to a page: a junk URL is a 404, not a 301 to one.
		if !directoryPageExists(req.Context(), p, settings) {
			serveNotFoundPage(w, req, tpl)
			return true
		}
		redirectPermanently(w, req, canonical, req.URL.RawQuery)
		return true
	}

	displayName := config.GetString("displayName")
	tokens := listingMetaTokens{
		Keyword:     keyword,
		Category:    category,
		City:        ucwords(keywordFromSlug(p.CitySlug)),
		State:       strings.ToUpper(p.State),
		Page:        p.Page,
		DisplayName: displayName,
	}
	tokens.Location = tokens.City + ", " + tokens.State
	if isCategory {
		tokens.KeywordTitle = siteCategory.Label
	}

	result, err := listingsStore.Search(req.Context(), q)
	if err != nil {
		listingsFailed("search", err)
		title, _ := directoryPathMeta(config, p, tokens)
		serveListingsUnavailable(w, req, tpl, directoryPageName(p.Kind), title)
		return true
	}
	// A city no listing is in, a page past the last, or a slug that isn't a
	// site category and finds nothing, is no page. (The listing API names a
	// city it knows even when none of its listings is there.)
	if result.CityName == "" || p.Kind == directoryCityPath && result.Total == 0 || p.Page > 1 && p.Page > result.TotalPages || p.Kind == directoryBrowsePath && !isCategory && result.Total == 0 {
		serveNotFoundPage(w, req, tpl)
		return true
	}
	tokens.City = result.CityName
	tokens.Location = tokens.City + ", " + tokens.State

	title, description := directoryPathMeta(config, p, tokens)
	cityCrumb := breadcrumbItem{Name: tokens.Location, URL: absoluteURL(req, p.location().Path())}
	page := directoryPage{
		Name:          directoryPageName(p.Kind),
		Title:         title,
		Description:   description,
		CanonicalPath: p.canonicalPath(),
		Robots:        indexableKind(settings.IndexCity),
		Breadcrumbs:   []breadcrumbItem{homeBreadcrumbItem(req), cityCrumb},
	}
	if p.Kind == directoryBrowsePath {
		page.Robots = indexableKind(settings.IndexBrowse)
		page.Breadcrumbs = append(page.Breadcrumbs, breadcrumbItem{Name: category, URL: absoluteURL(req, page.CanonicalPath)})
	}
	serveDirectoryPage(w, req, tpl, page)
	return true
}

// directoryPageExists reports whether the city or browse page p (at its
// canonical URL, page 1) is a page: its city has listings and a browse slug
// that isn't a site category finds some. An unavailable store reports true,
// so the URL is still redirected.
func directoryPageExists(ctx context.Context, p directoryPath, settings directorySettings) bool {
	q := listings.Query{Location: p.location()}
	if _, isCategory := settings.category(p.Slug); p.Kind == directoryBrowsePath && !isCategory {
		keyword, _ := settings.browseQuery(p.Slug)
		q = settings.listingQuery(keyword, directoryCategory{}, false, p.location())
	}
	exists, err := listingsStore.Exists(ctx, q)
	return err != nil || exists
}

// stateHasCities reports whether the state page /{st} is a page: the state
// has cities with listings. An unavailable store reports true.
func stateHasCities(ctx context.Context, state string) bool {
	cities, err := listingsStore.Cities(ctx, state)
	return err != nil || len(cities) > 0
}

// statePathCode returns the state code of a state page URL, /{st} (any case,
// trailing slashes allowed). ok is false for any other path.
func statePathCode(path string) (string, bool) {
	segment := strings.TrimRight(strings.TrimPrefix(path, "/"), "/")
	if strings.Contains(segment, "/") || !listings.IsStateCode(segment) {
		return "", false
	}
	return segment, true
}

// serveStatePage serves a state page, /{st}: the state's cities with
// listings (the frontend lists them from /data/listings/cities). Another
// spelling (/VA, /va/) 301s to /{st}; a state without cities is a 404.
func serveStatePage(w http.ResponseWriter, req *http.Request, tpl *template.Template, config *middlewares.ClientConfig, settings directorySettings, code string) {
	state := strings.ToLower(code)
	canonical := "/" + state
	tokens := listingMetaTokens{
		State:       strings.ToUpper(state),
		StateName:   places.StateName(state),
		DisplayName: config.GetString("displayName"),
	}
	title, description := listingPageMeta(config, "listingState", "Businesses in {stateName} - {displayName}", "", tokens)
	cities, err := listingsStore.Cities(req.Context(), state)
	if err != nil {
		// The canonical form doesn't need the store.
		if canonical != req.URL.Path {
			redirectPermanently(w, req, canonical, req.URL.RawQuery)
			return
		}
		listingsFailed("cities "+state, err)
		serveListingsUnavailable(w, req, tpl, "listingState", title)
		return
	}
	if len(cities) == 0 {
		serveNotFoundPage(w, req, tpl)
		return
	}
	if canonical != req.URL.Path {
		redirectPermanently(w, req, canonical, req.URL.RawQuery)
		return
	}
	serveDirectoryPage(w, req, tpl, directoryPage{
		Name:          "listingState",
		Title:         title,
		Description:   description,
		CanonicalPath: canonical,
		Robots:        indexableKind(settings.IndexState),
		Breadcrumbs:   []breadcrumbItem{homeBreadcrumbItem(req), {Name: tokens.StateName, URL: absoluteURL(req, canonical)}},
	})
}

// directoryPageName is the page name of a directory URL's shell.
func directoryPageName(kind directoryPathKind) string {
	switch kind {
	case directoryBrowsePath:
		return "listingBrowse"
	case directoryDetailPath:
		return "listingDetail"
	}
	return "listingCity"
}

// directoryPathMeta is the title and description of a city or browse page.
func directoryPathMeta(config *middlewares.ClientConfig, p directoryPath, tokens listingMetaTokens) (string, string) {
	if p.Kind == directoryCityPath {
		return listingPageMeta(config, "listingCity", "Businesses in {location} - {displayName}", "", tokens)
	}
	titlePattern, descriptionPattern := pageMetaOverride(config, "listingBrowse", "{Keyword} in {location} - {displayName}", "")
	// The page number goes in the title from page 2, unless the pattern places it.
	if p.Page > 1 && !strings.Contains(titlePattern, "{page}") {
		titlePattern += " - Page {page}"
	}
	return expandListingMeta(titlePattern, descriptionPattern, tokens)
}

// serveListingDetail serves a listing page, /{st}/{city}/{id}-{slug}: a 301
// to the listing's own url when the URL differs, a 404 for an unknown id.
func serveListingDetail(w http.ResponseWriter, req *http.Request, tpl *template.Template, config *middlewares.ClientConfig, settings directorySettings, p directoryPath) {
	displayName := config.GetString("displayName")
	l, found, err := listingsStore.Get(req.Context(), p.ID)
	if err != nil {
		listingsFailed("get "+p.ID, err)
		serveListingsUnavailable(w, req, tpl, directoryPageName(p.Kind), displayName)
		return
	}
	if !found {
		serveNotFoundPage(w, req, tpl)
		return
	}
	if l.URL != req.URL.Path {
		redirectPermanently(w, req, l.URL, req.URL.RawQuery)
		return
	}

	tokens := listingMetaTokens{
		Name:        l.Name,
		City:        l.City,
		State:       l.State,
		Location:    listings.Location{City: l.City, State: l.State}.Label(),
		DisplayName: displayName,
	}
	category, hasCategory := settings.listingCategory(l)
	if hasCategory {
		tokens.Category, tokens.Keyword, tokens.KeywordTitle = category.Label, category.Keyword, category.Label
	} else if len(l.Categories) > 0 {
		tokens.Category, tokens.Keyword = l.Categories[0], l.Categories[0]
	}
	title, description := listingPageMeta(config, "listingDetail", "{name} - {city}, {state} - {displayName}", listingDescription(l), tokens)

	cityPath := listings.Location{City: l.City, State: l.State}.Path()
	breadcrumbs := []breadcrumbItem{homeBreadcrumbItem(req), {Name: tokens.Location, URL: absoluteURL(req, cityPath)}}
	if hasCategory {
		breadcrumbs = append(breadcrumbs, breadcrumbItem{Name: category.Label, URL: absoluteURL(req, cityPath+"/"+category.Slug)})
	}
	breadcrumbs = append(breadcrumbs, breadcrumbItem{Name: l.Name, URL: absoluteURL(req, l.URL)})

	image := ""
	if len(l.Images) > 0 {
		image = l.Images[0]
	}
	serveDirectoryPage(w, req, tpl, directoryPage{
		Image:         image,
		Name:          directoryPageName(p.Kind),
		Title:         title,
		Description:   description,
		CanonicalPath: l.URL,
		Robots:        indexableKind(settings.IndexDetail),
		Breadcrumbs:   breadcrumbs,
		LocalBusiness: localBusinessJSONLD(req, l),
	})
}

// listingDescriptionLength is the most characters of a listing's description
// its page's meta description keeps.
const listingDescriptionLength = 155

// listingDescription is a listing page's default meta description: its
// description cut on a word, else "{name}, {address}, {city}, {state} {zip}."
// (without the parts it doesn't have). Braces are dropped, so the listing's
// own text is never read as pattern tokens.
func listingDescription(l listings.Listing) string {
	text := cutOnWord(l.Description, listingDescriptionLength)
	if text == "" {
		parts := []string{l.Name}
		if l.Address != "" {
			parts = append(parts, l.Address)
		}
		parts = append(parts, strings.TrimSpace(l.City+", "+l.State+" "+l.Zip))
		text = strings.Join(parts, ", ") + "."
	}
	return strings.NewReplacer("{", "", "}", "").Replace(text)
}

// DirectorySearchHandler serves /search on directory sites: listing results
// for ?s={keyword}&loc={City, ST}&page={n}, always noindex,follow. Legacy
// ?search= / ?keyword= / ?q= 301 to ?s=. Shop sites get the shop listing
// (see serveShopSearch), other sites the article search. It also serves
// /search/, which 301s to /search (query kept) as the router did before; on
// shop sites in the same hop as the listing's own redirect.
func DirectorySearchHandler() http.Handler {
	return directorySearchHandler(SearchPageHandler(), pageTemplates())
}

func directorySearchHandler(articleSearch 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) {
			serveShopSearch(w, req, tpl, config, shopAPILookups{})
			return
		}
		if req.URL.Path != "/search" {
			redirectPermanently(w, req, "/search", req.URL.RawQuery)
			return
		}
		if !isDirectorySite(config) {
			articleSearch.ServeHTTP(w, req)
			return
		}
		if query, ok := directorySearchRedirectQuery(req.URL.RawQuery); ok {
			redirectPermanently(w, req, "/search", query)
			return
		}

		settings := directorySettingsFrom(config)
		params := req.URL.Query()
		keyword := strings.Join(strings.Fields(params.Get("s")), " ")
		loc := resolveSearchLocation(req.Context(), params.Get("loc"), settings)
		page := listingsPageParam(params.Get("page"))
		category, isCategory := settings.categoryNamed(keyword)
		q := settings.listingQuery(keyword, category, isCategory, loc)
		q.Page = page

		tokens := listingMetaTokens{
			Keyword:     keyword,
			Category:    ucwords(keyword),
			City:        loc.City,
			State:       loc.State,
			Location:    loc.Label(),
			Page:        page,
			DisplayName: config.GetString("displayName"),
		}
		if keyword == "" {
			tokens.Keyword, tokens.Category = "businesses", "Businesses"
		}
		if isCategory {
			tokens.KeywordTitle, tokens.Category = category.Label, category.Label
		}
		result, err := listingsStore.Search(req.Context(), q)
		if err == nil && result.CityName != "" {
			loc.City = result.CityName
			tokens.City, tokens.Location = loc.City, loc.Label()
		}
		title, description := listingPageMeta(config, "listingResults", "{Keyword} in {location} - {displayName}", "", tokens)
		if err != nil {
			listingsFailed("search", err)
			serveListingsUnavailable(w, req, tpl, "listingResults", title)
			return
		}
		if page > 1 && page > result.TotalPages {
			serveNotFoundPage(w, req, tpl)
			return
		}

		// Its own search, in the canonical form of its params.
		canonicalQuery := url.Values{}
		if keyword != "" {
			canonicalQuery.Set("s", keyword)
		}
		if !loc.IsZero() {
			canonicalQuery.Set("loc", loc.Label())
		}
		if page > 1 {
			canonicalQuery.Set("page", strconv.Itoa(page))
		}
		canonical := "/search"
		if len(canonicalQuery) > 0 {
			canonical += "?" + canonicalQuery.Encode()
		}
		serveDirectoryPage(w, req, tpl, directoryPage{
			Name:          "listingResults",
			Title:         title,
			Description:   description,
			CanonicalPath: canonical,
			Robots:        metaRobotsSearch,
			Breadcrumbs:   []breadcrumbItem{homeBreadcrumbItem(req), {Name: "Search", URL: absoluteURL(req, "/search")}},
		})
	})
}

// listingsPageParam reads a search's page param: 1 when it is missing, not a
// number or below 1. A number too big for an int reads as the largest, a page
// past the last like any other.
func listingsPageParam(raw string) int {
	page, err := strconv.Atoi(raw)
	switch {
	case errors.Is(err, strconv.ErrRange) && !strings.HasPrefix(raw, "-"):
		return math.MaxInt
	case err != nil || page < 1:
		return 1
	}
	return page
}

// resolveSearchLocation is the location of a search's loc param (see
// listings.Store.ResolveLocation): the site's directory.defaultLocation when
// it is empty or matches no city with listings.
func resolveSearchLocation(ctx context.Context, input string, settings directorySettings) listings.Location {
	if strings.TrimSpace(input) == "" {
		return settings.DefaultLocation
	}
	loc, ok, err := listingsStore.ResolveLocation(ctx, input)
	if err != nil {
		listingsFailed("resolve location", err)
	}
	if err != nil || !ok {
		return settings.DefaultLocation
	}
	return loc
}

// DirectoryCategoriesHandler serves /categories on directory sites (every
// directory.categories entry; the frontend renders the list), and on shop
// sites with that page (see ShopPageHandler). On other sites the URL is
// routed as before, by the not-found handler.
func DirectoryCategoriesHandler() http.Handler {
	tpl := pageTemplates()
	return directoryCategoriesHandler(shopPageHandler(shopCategoriesPage, NotFoundHandler(), tpl), tpl)
}

func directoryCategoriesHandler(other http.Handler, tpl *template.Template) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		config := middlewares.GetClientConfig(req.Context())
		if !isDirectorySite(config) {
			other.ServeHTTP(w, req)
			return
		}
		title, description := listingPageMeta(config, "categories", "Categories - {displayName}", "",
			listingMetaTokens{DisplayName: config.GetString("displayName")})
		serveDirectoryPage(w, req, tpl, directoryPage{
			Name:          "categories",
			Title:         title,
			Description:   description,
			CanonicalPath: "/categories",
			Robots:        metaRobotsIndexable,
			Breadcrumbs:   []breadcrumbItem{homeBreadcrumbItem(req), {Name: "Categories", URL: absoluteURL(req, "/categories")}},
		})
	})
}

// DirectoryStatesHandler serves /states on directory sites, the states with
// listings (the frontend lists them from /data/listings/states); /states/
// 301s to it. On other sites the URL is routed as before, by the not-found
// handler.
func DirectoryStatesHandler() http.Handler {
	return directoryStatesHandler(NotFoundHandler(), pageTemplates())
}

func directoryStatesHandler(other http.Handler, tpl *template.Template) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		config := middlewares.GetClientConfig(req.Context())
		if !isDirectorySite(config) {
			other.ServeHTTP(w, req)
			return
		}
		if req.URL.Path != "/states" {
			redirectPermanently(w, req, "/states", req.URL.RawQuery)
			return
		}
		title, description := listingPageMeta(config, "listingStates", "Browse by state - {displayName}", "",
			listingMetaTokens{DisplayName: config.GetString("displayName")})
		if _, err := listingsStore.States(req.Context()); err != nil {
			listingsFailed("states", err)
			serveListingsUnavailable(w, req, tpl, "listingStates", title)
			return
		}
		serveDirectoryPage(w, req, tpl, directoryPage{
			Name:          "listingStates",
			Title:         title,
			Description:   description,
			CanonicalPath: "/states",
			Robots:        indexableKind(directorySettingsFrom(config).IndexState),
			Breadcrumbs:   []breadcrumbItem{homeBreadcrumbItem(req), {Name: "States", URL: absoluteURL(req, "/states")}},
		})
	})
}

// DirectoryCategoryHandler serves /categories/{slug} on directory sites: the
// page of a category group (a site category with keywords; the frontend lists
// its subcategories from the config), not store-dependent. Another spelling of
// a group's slug 301s to it; any other slug, including a category without
// keywords (it has no subcategories to list), is a 404. On other sites the
// URL is routed as before, by the not-found handler.
func DirectoryCategoryHandler() http.Handler {
	return directoryCategoryHandler(NotFoundHandler(), pageTemplates())
}

func directoryCategoryHandler(other http.Handler, tpl *template.Template) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		config := middlewares.GetClientConfig(req.Context())
		if !isDirectorySite(config) {
			other.ServeHTTP(w, req)
			return
		}
		settings := directorySettingsFrom(config)
		slug := httprouter.ParamsFromContext(req.Context()).ByName("slug")
		category, ok := settings.category(listings.NameSlug(slug))
		if !ok || len(category.Keywords) == 0 {
			serveNotFoundPage(w, req, tpl)
			return
		}
		canonical := "/categories/" + category.Slug
		if canonical != req.URL.Path {
			redirectPermanently(w, req, canonical, "")
			return
		}
		tokens := listingMetaTokens{
			Keyword:      category.Keyword,
			KeywordTitle: category.Label,
			Category:     category.Label,
			DisplayName:  config.GetString("displayName"),
		}
		title, description := listingPageMeta(config, "listingCategory", "{category} - {displayName}", "", tokens)
		serveDirectoryPage(w, req, tpl, directoryPage{
			Name:          "listingCategory",
			Title:         title,
			Description:   description,
			CanonicalPath: canonical,
			Robots:        indexableKind(settings.IndexCategory),
			Breadcrumbs: []breadcrumbItem{
				homeBreadcrumbItem(req),
				{Name: "Categories", URL: absoluteURL(req, "/categories")},
				{Name: category.Label, URL: absoluteURL(req, canonical)},
			},
		})
	})
}
