# Server rendering in any framework

Source: https://help.ruuster.com/idx/guide-server-rendering

> Render listing and area pages on your server in Next.js (App Router and Pages Router), Nuxt, SvelteKit, Astro, Remix or any server language over HTTP, with the same pattern and the same rules.

Every framework follows the same pattern. Only the file names change.

## The pattern

1. **On the server**, call the API with the secret key from `IDX_SECRET_KEY`.
2. **Check the answer.** On 404, answer 404. On 410 `listing_removed`, answer 410 with your "no longer
   available" page. On 429 or 503, throw, so your cache keeps serving the last good page. Never render
   or cache an error as if it were the page.
3. **Render the HTML** with the listings, real `<a href>` links, each card's attribution and every
   board's disclaimer from `meta.mls`.
4. **Put the head in the page**: the title, description, canonical link, robots value and Open Graph
   tags from `data.head`, and the JSON-LD from `data.jsonLd` (React) or `data.jsonLdHtml` (any other
   template).
5. **Cache the page** for about five minutes, and re-render it when a webhook says its listing changed.
6. **In the browser**, load the interactive parts on top: the search box, the map and the gallery.
   The ones that ask the API call your own listings route (`createListingsRoute` from
   `@ruuster/idx/route`), which adds the secret key on your server, so the page carries no key.

## Next.js, App Router

Server components call the SDK directly. `generateMetadata` passes `data.head` to `toMetadata`, the
page renders the recipe components, and `export const revalidate = 300` caches it. The complete page:

<p class="code-title"><code>app/neighborhoods/[area]/page.tsx</code></p>

```tsx
// /neighborhoods/<area>: an area page built to rank and to be quoted by AI assistants.
// Top to bottom: the one-sentence answer with today's numbers and the date, the market tiles, the
// questions people ask (each an <h2> answered in its first sentence), your own words, then the
// listings, pagination, the map, the MLS disclaimers and the JSON-LD.
import Link from "next/link";
import { notFound } from "next/navigation";
import { Filters, MarketStats } from "@ruuster/idx-recipes";
import { Results } from "@/components/results";
import { areaAnswer } from "@/content/answer";
import { AREAS, areaBySlug } from "@/content/areas";
import { getMeta, idx } from "@/lib/idx";
import { areaQuery, showsSoldData } from "@/lib/area-query";
import { failureAction, resultsMetadata } from "@/lib/results";

export const revalidate = 300;

type Props = { params: { area: string }; searchParams: Record<string, string | string[] | undefined> };

export function generateStaticParams() {
  return AREAS.map((a) => ({ area: a.slug }));
}

export async function generateMetadata({ params, searchParams }: Props) {
  const area = areaBySlug(params.area);
  if (!area) return {};
  const r = await idx.search(areaQuery(area, searchParams));
  return r.ok ? resultsMetadata(r.data.head, `Homes for sale in ${area.name}`) : {};
}

export default async function AreaPage({ params, searchParams }: Props) {
  const area = areaBySlug(params.area);
  if (!area) notFound();
  const q = areaQuery(area, searchParams);
  const [r, answer, meta] = await Promise.all([idx.search(q), areaAnswer(area), getMeta()]);
  if (!r.ok) {
    const action = failureAction(r);
    if (action === "not_found") notFound();
    throw new Error(`Listings API ${r.status} ${r.error.code}`);
  }
  const sold = area.soldPage && meta.ok && showsSoldData(meta.data.capabilities);
  return (
    <main>
      <nav aria-label="Breadcrumb">
        <Link href="/neighborhoods">Neighborhoods</Link> › {area.name}
      </nav>
      <h1>{`Homes for sale in ${area.name}`}</h1>
      {answer ? <p>{answer.answer.lead}</p> : null}
      {answer ? <MarketStats market={answer.market} /> : null}
      {answer?.answer.questions.map((x) => (
        <section key={x.question}>
          <h2>{x.question}</h2>
          <p>{x.answer}</p>
        </section>
      ))}
      {area.questions.map((x) => (
        <section key={x.question}>
          <h2>{x.question}</h2>
          <p>{x.answer}</p>
        </section>
      ))}
      <section aria-labelledby="our-take">
        <h2 id="our-take">Our take on {area.name}</h2>
        {area.ownWords.map((p) => (
          <p key={p}>{p}</p>
        ))}
      </section>
      <h2>Listings in {area.name}</h2>
      <Filters value={q} action={`/neighborhoods/${area.slug}`} fields={["price", "beds", "baths", "type", "sort"]} keep={[]} />
      <Results r={r} basePath={`/neighborhoods/${area.slug}`} searchParams={searchParams} listName={`Homes for sale in ${area.name}`} />
      {sold ? (
        <p>
          <Link href={`/neighborhoods/${area.slug}/sold`}>Recently sold homes in {area.name}</Link>
        </p>
      ) : null}
    </main>
  );
}
```

The listing page adds `notFound()` for 404 and the 301 and 410 decisions in `middleware.ts`
([Listing detail page](https://help.ruuster.com/idx/recipe-listing-detail)).

## Next.js, Pages Router

Use `getStaticProps` with `revalidate: 300` and `fallback: "blocking"` in `getStaticPaths` for area
and listing pages, or `getServerSideProps` for the search page. Import the same `lib/idx.ts` client
inside those functions only, so the secret key stays on the server. Return `{ notFound: true }` on 404
and `{ redirect: { destination, permanent: true } }` for an outdated slug. Pass `data.head` to
`next/head` as `<title>`, `<meta>` and `<link rel="canonical">` tags, and render `<JsonLd>` in the
page. For a 410, set `res.statusCode = 410` in `getServerSideProps` and render your "no longer
available" page.

## Nuxt

Call the API in a server route (`server/api/…`) or in `useAsyncData` on the page, which runs on the
server on the first load. Read the secret key from `useRuntimeConfig().idxSecretKey`, set from
`NUXT_IDX_SECRET_KEY`; no Listings API key goes under `public`. Set the head with `useHead` from
`data.head`, and print `data.jsonLdHtml` with `useHead({ script: [...] })` or `v-html` on a wrapper.
Throw `createError({ statusCode: 404 })` or `410` to answer those statuses. Cache with `routeRules`
(`swr: 300`).

## SvelteKit

Call the API in `+page.server.ts` `load`, reading the key from `$env/static/private`
(`IDX_SECRET_KEY`). Use `error(404)`, `error(410)` and `redirect(301, path)` from `@sveltejs/kit`.
Render `data.head` in `<svelte:head>` and print `{@html data.jsonLdHtml}` there. Set
`Cache-Control: s-maxage=300, stale-while-revalidate=600` with `setHeaders` when your host caches at
the edge.

## Astro

Use server output (`output: "server"` or `"hybrid"`) and call the API in the page's frontmatter with
`import.meta.env.IDX_SECRET_KEY`. Return `Astro.redirect(path, 301)`, or set `Astro.response.status`
to 404 or 410 and render the right page. Put `data.head` in the `<head>` of your layout and print
`<Fragment set:html={data.jsonLdHtml} />`. Mount your listings route as an Astro endpoint, such as
`src/pages/api/idx/[...path].ts` exporting `GET`, so the page carries no key.

## Remix and React Router

Call the API in the route's `loader`, reading `process.env.IDX_SECRET_KEY`. Throw
`new Response(null, { status: 404 })` or `410`, or `redirect(path, 301)`. Build the route's `meta`
export from `data.head`, render `<JsonLd docs={data.jsonLd} />` in the component, and set
`Cache-Control` in the `headers` export.

## Any server language over HTTP

The API is plain HTTPS and JSON, so PHP, Python, Ruby, Go, Java or .NET can render the same pages with
no package at all: send `Authorization: Bearer` with your secret key, read the JSON, print it with your
own templates and answer 301, 404 and 410 yourself. This dependency-free Node.js server does exactly
that, and every reference page shows each call in cURL, TypeScript, Python and PHP:

<p class="code-title"><code>server.mjs</code></p>

```js
// A dependency-free Node.js server (Node 18.17 or later) that renders area pages and listing pages from
// the Ruuster Listings API over plain HTTP. Port the same calls to PHP, Python, Ruby or Go: the API
// answers JSON, and this file shows every field a page needs.
//
//   IDX_SECRET_KEY=idx_sk_... SITE_ORIGIN=http://localhost:3000 SITE_NAME="Your Brokerage" node server.mjs
//
// Pages: /neighborhoods/<area>[?page=N&sort=…&priceMin=…] and /homes/<slug>. The server answers 301
// for an outdated listing slug, 410 for a listing that left the market and 404 for an unknown one.
// The pages print the recipe components' markup (templates.mjs), styled by /ruuster-idx.css and made
// interactive by /ruuster-idx.js, which this server sends from the @ruuster/idx-recipes static
// folder: the area page has the results toolbar and the More filters drawer; the listing page has
// every screen (header, photo grid and full gallery, share, contact and tour dialogs, open houses,
// location map and the mortgage calculator, whose first answer this server asks for).
// No key is ever in a page: the calculator asks this server's own route, GET /api/idx/..., which adds
// the secret key here and forwards only the few calls a page's widgets make (see pageRoute below).
// Lead routes (leads.mjs): POST /api/leads/fub, /api/leads/sierra and /api/leads/suresend for the
// registration, tour and contact forms, and POST /api/activity/fub for listing views.
import fs from "node:fs";
import http from "node:http";
import { pathToFileURL } from "node:url";
import { handleFubActivity, handleLead } from "./leads.mjs";
import { detail, disclaimers, esc, filtersDrawer, grid, mortgagePrefill, mortgageQueryString, mortgageStart, page, pagination, resultsToolbar } from "./templates.mjs";

// IDX_BASE_URL is optional; leave it unset to call the Ruuster Listings API itself.
const API_ORIGIN = "https://idx.ruuster.com";
const API = (process.env.IDX_BASE_URL || `${API_ORIGIN}/v1`).replace(/\/+$/, "");
const SITE_NAME = process.env.SITE_NAME || "Your Brokerage";
const PAGE_SIZE = 24;
// The lead route the tour form posts to (leads.mjs): fub, sierra or suresend.
const LEAD_CRM = ["fub", "sierra", "suresend"].includes(process.env.LEAD_CRM) ? process.env.LEAD_CRM : "fub";
const CONSENT_TEXT = `I agree that ${SITE_NAME} may contact me by phone, text or email about this request.`;
const ALERTS_TEXT = "Email me new listings like this one. I can unsubscribe at any time.";
// Optional: your Google Maps browser key turns on the location map and Street view, and your agent the
// contact surfaces. The mortgage calculator needs no key: it asks /api/idx on this server.
const MAPS_KEY = process.env.GOOGLE_MAPS_KEY || null;
const MAP_ID = process.env.GOOGLE_MAP_ID || null;
const AGENT = { name: process.env.AGENT_NAME || null, brokerage: SITE_NAME, license: process.env.AGENT_LICENSE || null, email: process.env.AGENT_EMAIL || null, phone: process.env.AGENT_PHONE || null, photoUrl: process.env.AGENT_PHOTO_URL || null };

// ruuster-idx.css and ruuster-idx.js: from a static/ folder next to this file when you copied them
// there, else from packages/ruuster-idx-recipes/static/ in this repository.
const STATIC_DIRS = [new URL("./static/", import.meta.url), new URL("../../packages/ruuster-idx-recipes/static/", import.meta.url)];
const STATIC_FILES = { "/ruuster-idx.css": "text/css; charset=utf-8", "/ruuster-idx.js": "text/javascript; charset=utf-8" };

// Your areas: each `where` is the row GET /v1/suggest answered, pasted in unchanged.
// This example row is replaced with your own.
export const AREAS = {
  midtown: { name: "Midtown", where: { label: "Atlanta, GA Midtown", value: "a0000000-0000-4000-8000-000000000001", source: "neighborhood", data: { state: "GA" } } },
};

const LISTING_ID = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;

/** GET an API path with the secret key, server side. Answers { status, body, retryAfter }. */
export async function api(path, params) {
  const url = new URL(`${API}${path}`);
  for (const [k, v] of Object.entries(params ?? {})) {
    if (v === undefined || v === null) continue;
    for (const one of Array.isArray(v) ? v : [v]) url.searchParams.append(k, typeof one === "object" ? JSON.stringify(one) : String(one));
  }
  const res = await fetch(url, { headers: { Authorization: `Bearer ${process.env.IDX_SECRET_KEY}` } });
  const body = await res.json().catch(() => null);
  return { status: res.status, body, retryAfter: res.headers.get("retry-after") };
}

/**
 * Your brand kit (GET /v1/meta data.themeVars), read again every 10 minutes. When the call fails, the
 * page keeps the last brand variables it had (none before the first answer) and asks again a minute later.
 */
let brand = { vars: null, at: 0, ttl: 0 };
export async function themeVars() {
  if (brand.at && Date.now() - brand.at < brand.ttl) return brand.vars;
  try {
    const r = await api("/meta", {});
    brand = r.status === 200 ? { vars: r.body?.data?.themeVars ?? null, at: Date.now(), ttl: 600_000 } : { vars: brand.vars, at: Date.now(), ttl: 60_000 };
  } catch {
    brand = { vars: brand.vars, at: Date.now(), ttl: 60_000 };
  }
  return brand.vars;
}

/** GET /ruuster-idx.css and /ruuster-idx.js. */
function sendStatic(res, pathname) {
  for (const dir of STATIC_DIRS) {
    const file = new URL(pathname.slice(1), dir);
    if (!fs.existsSync(file)) continue;
    res.writeHead(200, { "Content-Type": STATIC_FILES[pathname], "Cache-Control": "public, max-age=3600" });
    return res.end(fs.readFileSync(file));
  }
  send(res, 404, page({ siteName: SITE_NAME, fallbackTitle: "Not found", body: "<main><h1>Page not found</h1></main>" }));
}

function send(res, status, html, headers = {}) {
  res.writeHead(status, { "Content-Type": "text/html; charset=utf-8", ...headers });
  res.end(html);
}

/** 429 and 503: tell the visitor to try again; a cache in front of this server keeps the last good page. */
function busy(res, r) {
  send(res, 503, page({ siteName: SITE_NAME, fallbackTitle: "Please try again", body: "<main><h1>Please try again in a moment</h1></main>" }), { "Retry-After": r.retryAfter ?? "5" });
}

// The search parameters the area page passes on to GET /v1/listings (the toolbar's sort and the drawer's filters).
const SEARCH_PARAMS = ["sort", "priceMin", "priceMax", "bedsMin", "bathsMin", "subtype", "type", "status"];
const REPEATABLE = new Set(["subtype", "type", "status"]);

/** The page's own filters from its query: one value each, a list for the repeatable ones, numbers checked. */
export function searchQuery(searchParams) {
  const out = {};
  for (const k of SEARCH_PARAMS) {
    const all = searchParams.getAll(k).filter((v) => v !== "");
    if (all.length) out[k] = REPEATABLE.has(k) ? all : all[0];
  }
  for (const k of ["priceMin", "priceMax", "bedsMin", "bathsMin"]) if (out[k] !== undefined && !/^\d+(\.\d+)?$/.test(out[k])) delete out[k];
  return out;
}

async function areaPage(res, slug, pageNo, searchParams = new URLSearchParams()) {
  const area = AREAS[slug];
  if (!area) return send(res, 404, page({ siteName: SITE_NAME, fallbackTitle: "Not found", body: "<main><h1>Page not found</h1></main>" }));
  const q = searchQuery(searchParams);
  const r = await api("/listings", { where: area.where, status: "active", ...q, limit: PAGE_SIZE, page: pageNo, detailHref: "/homes/{slug}", pageHref: `/neighborhoods/${slug}` });
  if (r.status === 429 || r.status >= 500) return busy(res, r);
  if (r.status !== 200) return send(res, 404, page({ siteName: SITE_NAME, fallbackTitle: "Not found", body: "<main><h1>Page not found</h1></main>" }));
  const { data, meta } = r.body;
  const mls = meta?.mls ?? [];
  const pages = data.pages ?? Math.min(Math.ceil(data.total / data.limit), Math.floor(2000 / data.limit));
  const path = `/neighborhoods/${slug}`;
  const body = `<main>
    <h1>Homes for sale in ${esc(area.name)}</h1>
    ${filtersDrawer({ action: path, value: q })}
    ${resultsToolbar({ total: data.total, view: "list", basePath: path, searchParams: q })}
    ${grid(data.listings, mls, `Homes in ${area.name}`)}
    ${pagination(path, data.page, pages, q)}
    ${disclaimers(mls, meta?.freshness?.asOf)}
  </main>`;
  send(res, 200, page({ siteName: SITE_NAME, head: data.head, fallbackTitle: `Homes for sale in ${area.name}`, jsonLdHtml: data.jsonLdHtml ?? "", themeVars: await themeVars(), body }));
}

async function listingPage(res, slug) {
  const id = LISTING_ID.exec(slug)?.[1];
  if (!id) return send(res, 404, page({ siteName: SITE_NAME, fallbackTitle: "Not found", body: "<main><h1>Page not found</h1></main>" }));
  const r = await api(`/listings/${id}`, { detailHref: "/homes/{slug}" });
  if (r.status === 410) {
    // The listing left the market: 410 Gone with noindex, and similar homes to look at instead.
    const s = await api(`/listings/${id}/similar`, { limit: 6, detailHref: "/homes/{slug}" });
    const cards = s.status === 200 && s.body.data.listings.length ? grid(s.body.data.listings.map((x) => x.listing), s.body.meta?.mls ?? [], "Similar homes") : "";
    const body = `<main>
    <h1>This home is no longer available</h1>
    <p>The listing has left the market.${cards ? " Here are similar homes for sale." : ""}</p>
    ${cards}
    ${s.status === 200 ? disclaimers(s.body.meta?.mls ?? [], s.body.meta?.freshness?.asOf) : ""}
    <p><a href="/neighborhoods/midtown">Homes for sale in Midtown</a></p>
  </main>`;
    return send(res, 410, page({ siteName: SITE_NAME, head: { title: "This home is no longer available", description: "This listing has left the market.", robots: "noindex,follow", canonical: null }, fallbackTitle: "", themeVars: await themeVars(), body }), { "X-Robots-Tag": "noindex" });
  }
  if (r.status === 404) return send(res, 404, page({ siteName: SITE_NAME, fallbackTitle: "Not found", body: "<main><h1>Page not found</h1></main>" }));
  if (r.status !== 200) return busy(res, r);
  const listing = r.body.data;
  // The address in the URL is out of date: move permanently to the current one.
  if (listing.slug !== slug) {
    res.writeHead(301, { Location: `/homes/${listing.slug}` });
    return res.end();
  }
  const mls = r.body.meta?.mls ?? [];
  // The mortgage calculator's first answer, asked here with the secret key for the page's own starting
  // query; the browser asks /api/idx on this server again as the visitor changes it. Null on any
  // failure: the calculator then prints empty and the browser fills it.
  const estimate = await mortgageEstimate(listing);
  // The contact and tour dialogs post the LeadSubmission JSON to your lead route; ruuster-idx.js sends it.
  const html = detail(listing, mls, {
    backHref: `/neighborhoods/${Object.keys(AREAS)[0]}`,
    agent: AGENT,
    leadAction: `/api/leads/${LEAD_CRM}`,
    consentText: CONSENT_TEXT,
    alertsConsentText: ALERTS_TEXT,
    shareUrl: listing.head?.canonical || `${(process.env.SITE_ORIGIN || "").replace(/\/+$/, "")}/homes/${listing.slug}`,
    googleMapsKey: MAPS_KEY,
    mapId: MAP_ID,
    // The calculator's requests go to this server's own route, never to the API with a key in the page.
    apiBaseUrl: PAGE_ROUTE,
    estimate,
  });
  // The listing page prints its own board's disclaimer. When meta.mls has no entry for that board, it prints every board's.
  const hasBoard = mls.some((m) => m.mlsId === listing.mls.id);
  const body = `<main>
    ${html}
    ${hasBoard ? "" : disclaimers(mls, null)}
  </main>`;
  send(res, 200, page({ siteName: SITE_NAME, head: listing.head, fallbackTitle: listing.address.display, jsonLdHtml: listing.jsonLdHtml ?? "", themeVars: await themeVars(), body }));
}

/** GET /v1/mortgage/estimate for the listing's starting query (price, 20% down, state, ZIP, HOA dues, tax), or null. */
export async function mortgageEstimate(listing) {
  const prefill = mortgagePrefill(listing);
  if (!prefill.price || !prefill.state) return null;
  try {
    const r = await api("/mortgage/estimate", Object.fromEntries(new URLSearchParams(mortgageQueryString(mortgageStart(prefill)))));
    return r.status === 200 && r.body?.ok ? r.body.data : null;
  } catch {
    return null;
  }
}

// #region pageRoute
/** Where the widgets on these pages send their requests: this server's own route. */
const PAGE_ROUTE = "/api/idx";
/** The only API paths a page's widgets ask for here: suggestions, the filter lists and the mortgage estimate. */
const PAGE_PATHS = new Set(["/suggest", "/filters", "/filters/options", "/mortgage/estimate"]);

/**
 * GET /api/idx/<path>: the browser's calls, forwarded to the API with the secret key added here, so the
 * page carries no key. Anything outside PAGE_PATHS answers 404, so secret-only data stays out. In a
 * project that can install packages, `createListingsRoute` from `@ruuster/idx/route` does the same
 * with a per-visitor limit and every page-safe path.
 */
async function pageRoute(req, res, url) {
  if (req.method !== "GET") return sendJson(res, { status: 405, body: { ok: false, error: { code: "method_not_allowed", message: "This route answers GET requests only." } }, headers: { Allow: "GET" } });
  const path = url.pathname.slice(PAGE_ROUTE.length);
  if (!PAGE_PATHS.has(path)) return sendJson(res, { status: 404, body: { ok: false, error: { code: "not_found", message: "No such resource." } } });
  const query = new URLSearchParams(url.searchParams);
  query.delete("key");
  const upstream = await fetch(`${API}${path}?${query}`, { headers: { Authorization: `Bearer ${process.env.IDX_SECRET_KEY}`, Accept: "application/json" } });
  const headers = { "Content-Type": upstream.headers.get("content-type") ?? "application/json", "Cache-Control": upstream.ok ? "public, max-age=60" : "no-store" };
  const retryAfter = upstream.headers.get("retry-after");
  if (retryAfter) headers["Retry-After"] = retryAfter;
  res.writeHead(upstream.status, headers);
  res.end(Buffer.from(await upstream.arrayBuffer()));
}
// #endregion pageRoute

// #region leadRoutes
/** Reads a JSON request body of at most 64 KB. Null when it is too big or isn't JSON. */
async function readJson(req) {
  let size = 0;
  const chunks = [];
  for await (const chunk of req) {
    size += chunk.length;
    if (size > 65_536) return null;
    chunks.push(chunk);
  }
  try {
    return JSON.parse(Buffer.concat(chunks).toString("utf8"));
  } catch {
    return null;
  }
}

/** The listing a form or a view was about, from the API (null when it is gone or the call failed). */
async function getListing(listingId) {
  const r = await api(`/listings/${encodeURIComponent(listingId)}`, {});
  return r.status === 200 ? r.body.data : null;
}

function sendJson(res, out) {
  res.writeHead(out.status, { "Content-Type": "application/json", "Cache-Control": "no-store", ...out.headers });
  res.end(JSON.stringify(out.body));
}

/** POST /api/leads/<crm> and POST /api/activity/fub. Your CRM keys are read from this server's environment. */
async function leadRoute(req, res, pathname) {
  const deps = { env: process.env, getListing };
  const lead = /^\/api\/leads\/(fub|sierra|suresend)$/.exec(pathname);
  if (lead) return sendJson(res, await handleLead({ origin: req.headers.origin, body: await readJson(req) }, lead[1], deps));
  return sendJson(res, await handleFubActivity({ origin: req.headers.origin, cookie: req.headers.cookie, body: await readJson(req) }, deps));
}
// #endregion leadRoutes

/** The request handler (exported so a test can serve it on any port). */
export async function handle(req, res) {
  try {
    const url = new URL(req.url ?? "/", "http://localhost");
    if (STATIC_FILES[url.pathname]) return sendStatic(res, url.pathname);
    if (url.pathname.startsWith(`${PAGE_ROUTE}/`)) return await pageRoute(req, res, url);
    if (/^\/api\/(leads\/(fub|sierra|suresend)|activity\/fub)$/.test(url.pathname)) {
      if (req.method !== "POST") return sendJson(res, { status: 405, body: { ok: false, error: "Send this form with POST." }, headers: { Allow: "POST" } });
      return await leadRoute(req, res, url.pathname);
    }
    const area = /^\/neighborhoods\/([a-z0-9-]+)\/?$/.exec(url.pathname);
    if (area) {
      const n = Number(url.searchParams.get("page") ?? "1");
      return await areaPage(res, area[1], Number.isInteger(n) && n > 0 ? n : 1, url.searchParams);
    }
    const home = /^\/homes\/([^/]+)$/.exec(url.pathname);
    if (home) return await listingPage(res, decodeURIComponent(home[1]));
    if (url.pathname === "/") {
      const links = Object.entries(AREAS).map(([slug, a]) => `<li><a href="/neighborhoods/${esc(slug)}">Homes for sale in ${esc(a.name)}</a></li>`).join("");
      return send(res, 200, page({ siteName: SITE_NAME, fallbackTitle: SITE_NAME, body: `<main><h1>${esc(SITE_NAME)}</h1><ul>${links}</ul></main>` }));
    }
    send(res, 404, page({ siteName: SITE_NAME, fallbackTitle: "Not found", body: "<main><h1>Page not found</h1></main>" }));
  } catch {
    send(res, 503, page({ siteName: SITE_NAME, fallbackTitle: "Please try again", body: "<main><h1>Please try again in a moment</h1></main>" }), { "Retry-After": "5" });
  }
}

if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
  if (!process.env.IDX_SECRET_KEY) {
    console.error("Set IDX_SECRET_KEY (your idx_sk_ key) in this server's environment.");
    process.exit(1);
  }
  const port = Number(process.env.PORT || 3000);
  http.createServer(handle).listen(port, () => console.log(`Listening on http://localhost:${port}`));
}
```

<p class="code-title"><code>templates.mjs</code></p>

```js
// HTML templates for the plain-HTTP example. They print the same markup as the React recipe
// components (packages/ruuster-idx-recipes/static/html/), so ruuster-idx.css styles the page and
// ruuster-idx.js makes every screen work: the card photos, the listing page's header, full gallery,
// share, contact and tour dialogs, open houses, location map and mortgage calculator, and the search
// page's results toolbar and More filters drawer. templates.test.ts checks the templates against
// those files. Every value from the API is escaped, except jsonLdHtml, which the API already built
// as complete, escaped <script type="application/ld+json"> elements, and the icon bodies, which come
// from the package's own static/icons.json.
import fs from "node:fs";

/** Escapes text for HTML element content and attribute values (the same characters React escapes). */
export function esc(value) {
  return String(value ?? "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#x27;");
}

/** name="value" pairs in order; null, undefined and false leave the attribute out, true prints it empty. */
function attrs(pairs) {
  return pairs
    .filter(([, v]) => v !== null && v !== undefined && v !== false)
    .map(([k, v]) => (v === true ? ` ${k}=""` : ` ${k}="${esc(v)}"`))
    .join("");
}

// The visible text, from packages/ruuster-idx-recipes/src/copy.ts.
const COPY = {
  noPhoto: "No photo is available for this home.",
  noPhotoShort: "No photo available",
  previousPhoto: "Previous photo",
  nextPhoto: "Next photo",
  homeIn: "Home in",
  home: "Home",
  listingCourtesyOf: "Listing courtesy of",
  gridLabel: "Listings",
  emptyResults: "No homes match this search yet. Try a wider price range or fewer filters.",
  pagination: "Pages of results",
  previousPage: "Previous page",
  nextPage: "Next page",
  dataLastUpdated: "Data last updated",
  disclaimersLabel: "Listing data notices",
  mlsNumber: "MLS number",
  galleryTitle: "Photo gallery",
  closeGallery: "Close the photo gallery",
  description: "Description",
  virtualTour: "Take the virtual tour",
  propertyDetails: "Property details",
  listingInformation: "Listing information",
  tourSubmit: "Request a tour",
  tourSuccess: "Thank you. We received your tour request and will contact you soon to confirm a time.",
  consentRequired: "Check the box above to agree to be contacted, then send your request.",
  yes: "Yes",
  no: "No",
  back: "Back",
  closeListing: "Close",
  shareHome: "Share this home",
  streetView: "Street view",
  openHouseToday: "Today",
  openHouseTomorrow: "Tomorrow",
  happeningNow: "Happening now",
  tourPrompt: "Tour when it works for you.",
  scheduleTour: "Schedule a tour",
  agentInformation: "Agent information",
  agentNameLabel: "Agent name",
  brokerageLabel: "Brokerage",
  licenseLabel: "License number",
  emailLabel: "Email",
  phoneLabel: "Phone number",
  emailAgentNoName: "Email the agent",
  callAgentNoName: "Call the agent",
  locationMap: "Map of this home's location",
  expandMap: "Expand map",
  mapLoading: "The map is loading.",
  agentCardTitle: "Questions about this home?",
  agentCardText: "We are ready to answer any questions you have about this home, or to schedule a tour if you want to see it in person.",
  contactAgent: "Contact an agent",
  tourCardTitle: "Schedule a tour",
  tourCardText: "Choose a day and time that works for you to see this home in person or by video.",
  chooseTourTime: "Choose tour time",
  galleryTabs: "Photos and street view",
  tabPhotos: "Photos",
  tabStreetView: "Street view",
  closeFullGallery: "Close the gallery",
  shareButton: "Share",
  streetViewLoading: "Street view is loading.",
  closeDialog: "Close",
  shareTitle: "Share this home",
  shareHeading: "Send this home to someone",
  shareLinkLabel: "Link to this home",
  copyLink: "Copy link",
  shareOr: "or",
  shareFacebook: "Share on Facebook",
  shareWhatsApp: "Share on WhatsApp",
  shareEmail: "Share by email",
  shareMore: "More ways to share",
  contactHeading: "How can we reach you?",
  contactSentHeading: "Thank you. We will be in touch shortly.",
  contactSentText: "We can also set up a tour of this home. Which day and time work for you?",
  contactSubmit: "Send message",
  tourTitle: "Ready to tour?",
  tourHeading: "Choose a time that works for you.",
  tourSubheading: "Pick a day and a time of day, and we will confirm the tour with you.",
  tourDayLegend: "Day",
  previousDays: "Previous days",
  nextDays: "Next days",
  tourTimeLegend: "Time of day",
  pickDay: "Choose a day to continue.",
  next: "Next",
  backStep: "Back",
  tourInfoHeading: "How can we reach you?",
  fullName: "Name",
  fullNamePlaceholder: "First and last name",
  fullNameHint: "Enter your first and last name.",
  emailPlaceholder: "you@example.com",
  tourReceivedTitle: "Tour request received",
  tourReceivedText: "We received your request and will be in touch shortly to confirm.",
  summaryDate: "Tour date",
  summaryTime: "Tour time",
  summaryPhone: "Contact phone",
  summaryEmail: "Email",
  done: "Done",
  honeypot: "Leave this field empty",
  firstName: "First name",
  lastName: "Last name",
  email: "Email",
  phone: "Phone (optional)",
  message: "Message (optional)",
  mortgageTitle: "Estimate your monthly payment",
  homePrice: "Home price",
  downPayment: "Down payment",
  downPaymentDollars: "Dollars",
  downPaymentPercent: "Percent",
  interestRate: "Interest rate",
  loanType: "Loan type",
  loanTerm: "Term",
  moreOptions: "More options",
  creditScore: "Credit score",
  propertyTaxYearly: "Yearly property tax",
  insuranceYearly: "Yearly home insurance",
  hoaMonthly: "Monthly HOA dues",
  condoFeesMonthly: "Monthly condo fees",
  principalInterest: "Principal and interest",
  propertyTaxes: "Property taxes",
  homeInsurance: "Home insurance",
  mortgageInsurance: "Mortgage insurance",
  hoaDues: "HOA dues",
  condoFees: "Condo fees",
  monthlyTotal: "Total",
  perMonth: "per month",
  estimatedBadge: "est.",
  estimatedLabel: "Estimated. Enter your own figure under More options.",
  mortgageStale: "Some rates may be a few days old.",
  mortgageAdjust: "To qualify for this loan type, adjust the scenario:",
  tryAgain: "Try again",
  mortgageBreakdown: "Monthly payment breakdown",
  resultsToolbar: "Search results",
  resultsShowing: "Showing",
  sortApply: "Apply the sort order",
  viewSwitch: "How to see the listings",
  viewGrid: "Grid",
  viewMap: "Map",
  moreFilters: "More filters",
  filtersTitle: "More filters",
  closeFilters: "Close the filters",
  filtersLabel: "Filter homes",
  priceMin: "Minimum price",
  priceMax: "Maximum price",
  anyPrice: "Any price",
  bedsMin: "Bedrooms",
  bathsMin: "Bathrooms",
  anyNumber: "Any number",
  orMore: "or more",
  propertyType: "Property type",
  anyType: "Any property type",
  homeStyle: "Home type",
  anyStyle: "Any home type",
  status: "Status",
  sort: "Sort by",
  showResults: "Show results",
  resetFilters: "Reset filters",
};
const BADGES = { new: "New", back_on_market: "Back on market", price_change: "Price change", coming_soon: "Coming soon", sold: "Sold" };
const PARTS = [
  ["anytime", "Any time"],
  ["morning", "Morning (8 AM to 12 PM)"],
  ["afternoon", "Afternoon (12 PM to 4 PM)"],
  ["evening", "Evening (4 PM to 8 PM)"],
];

// ─── Icons (static/icons.json: every icon the recipes draw, as { viewBox, body }) ─────

const ICON_FILES = [new URL("./static/icons.json", import.meta.url), new URL("../../packages/ruuster-idx-recipes/static/icons.json", import.meta.url)];
const ICONS = JSON.parse(fs.readFileSync(ICON_FILES.find((f) => fs.existsSync(f)), "utf8"));

/** One icon as inline SVG, exactly as the Icon component prints it (decorative, currentColor). */
export function icon(name, size = 20, cls = "") {
  const def = ICONS[name];
  return `<svg class="rw-icon${cls ? ` ${cls}` : ""}" viewBox="${esc(def.viewBox)}" width="${size}" height="${size}" data-rw-icon="${name}" focusable="false" aria-hidden="true">${def.body}</svg>`;
}

// ─── Numbers and dates (en-US) ────────────────────────────────────────────────

const USD = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 0, maximumFractionDigits: 0 });
const NUMBER = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 });
const USD_COMPACT = new Intl.NumberFormat("en-US", { notation: "compact", maximumFractionDigits: 1 });
const finite = (n) => typeof n === "number" && Number.isFinite(n);
const usd = (n) => (finite(n) && n > 0 ? USD.format(n) : "");
const usdCompact = (n) => (finite(n) && n > 0 ? `$${USD_COMPACT.format(n)}` : "");
const plural = (n, one, many) => (finite(n) && n > 0 ? `${NUMBER.format(n)} ${n === 1 ? one : many}` : "");

/** "November 4, 2026 at 3:00 PM UTC" */
function asOfText(iso) {
  const t = Date.parse(iso);
  return Number.isFinite(t) ? `${new Intl.DateTimeFormat("en-US", { dateStyle: "long", timeStyle: "short", timeZone: "UTC" }).format(new Date(t))} UTC` : iso;
}

/** "Sep 1, 2026", read in UTC so the day never shifts. */
function shortDate(iso) {
  const t = iso ? Date.parse(iso) : Number.NaN;
  return Number.isFinite(t) ? new Intl.DateTimeFormat("en-US", { dateStyle: "medium", timeZone: "UTC" }).format(new Date(t)) : "";
}

const validZone = (z) => {
  if (!z) return null;
  try {
    new Intl.DateTimeFormat("en-US", { timeZone: z });
    return z;
  } catch {
    return null;
  }
};

/** "Sat, Nov 7, 1:00 PM to 3:00 PM EST": the card's open house badge, in the listing's own time zone. */
function openHouseText(o) {
  const s = Date.parse(o.start);
  if (!Number.isFinite(s)) return "";
  const zone = validZone(o.timeZone) ?? "UTC";
  const naive = !o.timeZone;
  const naiveDate = (raw) => {
    const m = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2}))?/.exec(raw);
    return m ? new Date(Date.UTC(+m[1], +m[2] - 1, +m[3], +(m[4] ?? 0), +(m[5] ?? 0))) : new Date(Date.parse(raw));
  };
  const startDate = naive ? naiveDate(o.start) : new Date(s);
  const endT = o.end ? Date.parse(o.end) : Number.NaN;
  const endDate = Number.isFinite(endT) ? (naive ? naiveDate(o.end) : new Date(endT)) : null;
  const time = new Intl.DateTimeFormat("en-US", { hour: "numeric", minute: "2-digit", timeZone: zone });
  const range = endDate ? `${time.format(startDate)} to ${time.format(endDate)}` : time.format(startDate);
  const tz = naive ? "" : (new Intl.DateTimeFormat("en-US", { timeZone: zone, timeZoneName: "short" }).formatToParts(startDate).find((p) => p.type === "timeZoneName")?.value ?? "");
  return `${new Intl.DateTimeFormat("en-US", { weekday: "short", month: "short", day: "numeric", timeZone: zone }).format(startDate)}, ${range}${tz ? ` ${tz}` : ""}`;
}

// ─── Listing facts ────────────────────────────────────────────────────────────

/** City, state and ZIP: "Powder Springs, GA 30127". */
const localityLine = (a) => [[a.city, a.state].filter(Boolean).join(", "), a.postalCode].filter(Boolean).join(" ").trim();

/** The one-line address. A hidden address shows the city, state and ZIP only, whatever `display` holds. */
export function addressLine(a) {
  const locality = localityLine(a);
  if (a.hidden) return locality;
  const street = [a.street, a.unit ? (/^#/.test(a.unit) ? a.unit : `#${a.unit}`) : null].filter(Boolean).join(" ");
  if (!street) return a.display || locality;
  return [street, locality].filter(Boolean).join(", ");
}

/** The address, or "Home in {city}" when it is hidden (photo alt text, GA4 and the lead forms). */
export function listingName(l) {
  if (l.address.hidden) {
    const place = l.address.city ?? l.address.state ?? null;
    return place ? `${COPY.homeIn} ${place}` : COPY.home;
  }
  return addressLine(l.address) || COPY.home;
}

/** The close price on a sold listing, else the price. */
const shownPrice = (l) => (l.status === "closed" && finite(l.closePrice) && l.closePrice > 0 ? l.closePrice : finite(l.price) && l.price > 0 ? l.price : null);

/** Beds, baths and square feet: [key, text] pairs, a missing or 0 fact left out. */
function factItems(l) {
  return [
    ["beds", plural(l.beds, "bed", "beds")],
    ["baths", plural(l.baths, "bath", "baths")],
    ["sqft", finite(l.sqft) && l.sqft > 0 ? `${new Intl.NumberFormat("en-US").format(Math.round(l.sqft))} sq ft` : ""],
  ].filter(([, text]) => text);
}
const FACT_ICONS = { beds: "beds", baths: "bath", sqft: "square" };

/** http(s) URLs only. */
function safeUrl(u) {
  if (!u) return null;
  try {
    const url = new URL(u, "https://example.invalid");
    return url.protocol === "https:" || url.protocol === "http:" ? u : null;
  } catch {
    return null;
  }
}

const dim = (v, d) => (finite(v) && v > 0 && v < 10_000 ? Math.round(v) : d);

/** A photo's <img> attributes: srcset and sizes on photos.ruuster.com only, width and height always. */
function imgAttrs(photo, { sizes, priority = false, fallbackAlt }) {
  const src = safeUrl(photo.url);
  if (!src) return null;
  const out = [
    ["src", src],
    ["width", dim(photo.width, 800)],
    ["height", dim(photo.height, 600)],
    ["alt", photo.alt && photo.alt.trim() ? photo.alt : fallbackAlt],
    ["loading", priority ? "eager" : "lazy"],
    ["decoding", "async"],
  ];
  if (new URL(src).host === "photos.ruuster.com") {
    const at = (w) => {
      const url = new URL(src);
      url.searchParams.set("width", String(w));
      return `${url.toString()} ${w}w`;
    };
    out.push(["srcset", [480, 800, 1200].map(at).join(", ")], ["sizes", sizes || "100vw"]);
  }
  if (priority) out.push(["fetchpriority", "high"]);
  return out;
}

/** What the card prints under the address for its board: the lines and logo its board requires on cards. */
function cardAttribution(l, mls) {
  const board = mls.find((m) => m.mlsId === l.mls.id) ?? null;
  const office = l.attribution.listOfficeName;
  const fallback = office ? `${COPY.listingCourtesyOf} ${office}` : null;
  if (!board) return { line: l.attribution.line, courtesy: l.attribution.courtesy, logo: null, boardName: l.mls.name };
  const onCard = board.required.filter((r) => r.placement === "card").map((r) => r.element);
  const line = onCard.some((e) => ["listing_office", "listing_agent", "agent_contact"].includes(e)) ? (l.attribution.line ?? fallback) : null;
  const courtesy = onCard.includes("courtesy_line") ? (l.attribution.courtesy ?? (line ? null : fallback)) : null;
  return { line, courtesy, logo: onCard.includes("mls_logo") ? board.logo : null, boardName: board.mlsName };
}

/** The one badge pill: Sold and its date, else the open house, else the API's first badge. */
function badgeText(l) {
  if (l.status === "closed") {
    const when = shortDate(l.closeDate);
    return { kind: "sold", text: when ? `${BADGES.sold} ${when}` : BADGES.sold };
  }
  const oh = (l.openHouses ?? [])[0];
  if ((l.badges ?? []).some((b) => b.kind === "open_house") && oh) {
    const when = openHouseText(oh);
    return { kind: "open_house", text: when ? `Open ${when}` : "Open house" };
  }
  const first = (l.badges ?? []).find((b) => b.kind !== "open_house");
  return first && BADGES[first.kind] ? { kind: first.kind, text: BADGES[first.kind] } : null;
}

// ─── GA4 (the same payloads as the React components) ─────────────────────────

function ga4Item(l, extra = {}) {
  const item = { item_id: l.mlsNumber ?? l.id, item_name: listingName(l) };
  const price = shownPrice(l);
  if (price !== null) item.price = price;
  if (l.type) item.item_category = l.type;
  if (l.subtype) item.item_category2 = l.subtype;
  if (l.mls?.name) item.item_brand = l.mls.name;
  if (extra.index !== undefined) item.index = extra.index;
  if (extra.listName) item.item_list_name = extra.listName;
  return item;
}

// ─── Page shell ───────────────────────────────────────────────────────────────

/** The <head> tags from the API's head object (title, description, canonical, robots, Open Graph, Twitter). */
export function headTags(head, fallbackTitle) {
  if (!head) return `<title>${esc(fallbackTitle)}</title>`;
  const tags = [`<title>${esc(head.title)}</title>`, `<meta name="description" content="${esc(head.description)}">`, `<meta name="robots" content="${esc(head.robots)}">`];
  if (head.canonical) tags.push(`<link rel="canonical" href="${esc(head.canonical)}">`);
  if (head.og) {
    tags.push(`<meta property="og:title" content="${esc(head.og.title)}">`, `<meta property="og:description" content="${esc(head.og.description)}">`, `<meta property="og:type" content="${esc(head.og.type)}">`);
    if (head.og.url) tags.push(`<meta property="og:url" content="${esc(head.og.url)}">`);
    if (head.og.image) tags.push(`<meta property="og:image" content="${esc(head.og.image)}">`);
  }
  if (head.twitter) {
    tags.push(`<meta name="twitter:card" content="${esc(head.twitter.card)}">`, `<meta name="twitter:title" content="${esc(head.twitter.title)}">`);
    if (head.twitter.image) tags.push(`<meta name="twitter:image" content="${esc(head.twitter.image)}">`);
  }
  return tags.join("\n    ");
}

/**
 * Your brand kit from GET /v1/meta (data.themeVars) as one CSS rule, printed after ruuster-idx.css.
 * Only --rw-* names, and values that cannot leave the declaration, are printed.
 */
export function themeVarsCss(vars) {
  const decls = Object.entries(vars ?? {})
    .filter(([k, v]) => /^--rw-[a-z0-9-]{1,80}$/.test(k) && typeof v === "string" && /^[^;{}<>\\]{1,200}$/.test(v.trim()))
    .map(([k, v]) => `${k}:${v.trim()}`);
  return decls.length ? `:where(.rw-recipes){${decls.join(";")}}` : "";
}

/** The whole page: the stylesheet, your brand rule and the script, then your header, the body and your footer. */
export function page({ siteName, head, fallbackTitle, jsonLdHtml = "", themeVars = null, body }) {
  const brand = themeVarsCss(themeVars);
  return `<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    ${headTags(head, fallbackTitle)}
    <link rel="stylesheet" href="/ruuster-idx.css">
    ${brand ? `<style>${brand}</style>` : ""}
    <style>body{margin:0;font-family:system-ui,sans-serif}.site{max-width:1280px;margin:0 auto;padding:16px}</style>
    <script src="/ruuster-idx.js" defer></script>
    ${jsonLdHtml}
  </head>
  <body>
    <div class="site">
    <header><a href="/">${esc(siteName)}</a></header>
    ${body}
    <footer><p>Equal Housing Opportunity. ${esc(siteName)} follows the Fair Housing Act.</p></footer>
    </div>
  </body>
</html>`;
}

// ─── Cards and the grid (html/listing-card.html, html/listing-grid.html) ─────────

const CARD_SIZES = "(min-width: 1600px) 25vw, (min-width: 1280px) 33vw, (min-width: 602px) 50vw, 100vw";
const photosJson = (photos) => JSON.stringify(photos.map((p) => ({ url: p.url, width: p.width, height: p.height, alt: p.alt })));
const NO_PHOTO = `<div class="rw-card__nophoto" role="img" aria-label="${COPY.noPhoto}">${icon("listing-no-image", 40, "rw-card__nophoto-icon")}<span class="rw-card__nophoto-text">${COPY.noPhotoShort}</span></div>`;

/** html/listing-card.html: one listing as a card. `priority` on the first card of the page only. */
export function card(listing, mls = [], priority = false) {
  const l = listing;
  const name = listingName(l);
  const fallbackHref = `/homes/${encodeURIComponent(l.slug)}`;
  const href = safeUrl(l.href ?? fallbackHref) ?? fallbackHref;
  const count = l.photos.length;
  const many = count > 1;
  const img = count ? imgAttrs(l.photos[0], { priority, sizes: CARD_SIZES, fallbackAlt: name }) : null;
  const att = cardAttribution(l, mls);
  const logoSrc = att.logo ? safeUrl(att.logo.url) : null;
  const logo = att.logo && logoSrc ? `<img${attrs([["class", "rw-card__logo"], ["src", logoSrc], ["alt", att.logo.alt || att.boardName], ["width", dim(att.logo.width, 80)], ["height", dim(att.logo.height, 32)], ["loading", "lazy"]])}>` : "";
  const dots = Array.from({ length: Math.min(count, 5) }, (_, i) => `<span class="${i === 0 ? "rw-card__dot rw-card__dot--on" : "rw-card__dot"}" data-rw-gallery-dot=""></span>`).join("");
  const arrows = many
    ? `<button type="button" class="rw-card__arrow rw-card__arrow--prev" aria-label="${COPY.previousPhoto}" data-rw-gallery-prev="">${icon("arrow-left-white", 18, "rw-card__arrow-icon")}</button>
      <button type="button" class="rw-card__arrow rw-card__arrow--next" aria-label="${COPY.nextPhoto}" data-rw-gallery-next="">${icon("arrow-right-white", 18, "rw-card__arrow-icon")}</button>
      <span class="rw-card__dots" aria-hidden="true" data-rw-gallery-dots="">${dots}</span>`
    : "";
  const badge = badgeText(l);
  const price = usd(shownPrice(l));
  const facts = factItems(l)
    .map(([k, text]) => `<li class="rw-fact">${icon(FACT_ICONS[k], 18, "rw-fact__icon")}${esc(text)}</li>`)
    .join("");
  return `<article class="rw-recipes rw-card"${attrs([["data-listing-id", l.id], ["data-status", l.status]])}>
    <div${attrs([["class", "rw-card__gallery"], ["data-rw-gallery", "card"], ["data-rw-photos", many ? photosJson(l.photos) : null], ["data-rw-photo-alt", many ? name : null]])}>
      ${img ? `<img${attrs([["class", "rw-card__photo"], ...img, ["data-rw-gallery-photo", true]])}>` : NO_PHOTO}
      ${logo}
      ${arrows}
    </div>
    ${badge ? `<span class="rw-card__badge rw-card__badge--${esc(badge.kind)}">${badge.kind === "open_house" ? icon("calendar-minimalistic", 14, "rw-card__badge-icon") : ""}${esc(badge.text)}</span>` : ""}
    <div class="rw-card__band">
      ${price ? `<p class="rw-card__price">${esc(price)}</p>` : ""}
      ${facts ? `<ul class="rw-card__facts">${facts}</ul>` : ""}
      <h3 class="rw-card__address"><a class="rw-card__link" href="${esc(href)}">${esc(addressLine(l.address) || name)}</a></h3>
      ${att.line ? `<p class="rw-card__attribution">${esc(att.line)}</p>` : ""}
      ${att.courtesy ? `<p class="rw-card__courtesy">${esc(att.courtesy)}</p>` : ""}
    </div>
  </article>`;
}

/** The ListingGrid: one card per listing, and the GA4 view_item_list event for ruuster-idx.js to push. */
export function grid(listings, mls = [], listName = COPY.gridLabel) {
  if (!listings.length) return `<div class="rw-recipes rw-grid rw-grid--empty"><p class="rw-empty">${COPY.emptyResults}</p></div>`;
  const ga4 = listName ? JSON.stringify({ ecommerce: { item_list_name: listName, items: listings.map((l, i) => ga4Item(l, { index: i, listName })) } }) : null;
  return `<div${attrs([["class", "rw-recipes rw-grid"], ["data-rw-ga4-event", ga4 ? "view_item_list" : null], ["data-rw-ga4-params", ga4]])}>
    <ul class="rw-grid__list" aria-label="${esc(listName || COPY.gridLabel)}">
      ${listings.map((l, i) => `<li class="rw-grid__item">${card(l, mls, i === 0)}</li>`).join("\n      ")}
    </ul>
  </div>`;
}

function boardLogo(logo, name, height) {
  const src = logo ? safeUrl(logo.url) : null;
  return logo && src ? `<img${attrs([["class", "rw-board-logo"], ["src", src], ["alt", logo.alt || name], ["width", dim(logo.width, 80)], ["height", dim(logo.height, height)], ["loading", "lazy"], ["decoding", "async"]])}>` : "";
}

/** Every board's logo, disclaimer and notices (each board once), and the "Data last updated" line. */
export function disclaimers(mls, asOf, placement = "page") {
  const seen = new Set();
  const boards = (mls ?? []).filter((m) => m && !seen.has(m.mlsId) && seen.add(m.mlsId));
  if (!boards.length && !asOf) return "";
  const paragraphs = (m) =>
    [m.disclaimer?.text, ...(m.notices ?? []).map((n) => n?.text)]
      .filter((t) => typeof t === "string" && t.trim() !== "")
      .flatMap((t) => t.split(/\n+/))
      .map((t) => t.trim())
      .filter(Boolean);
  const html = boards.map((m) => {
    const paras = paragraphs(m);
    return `<div class="rw-disclaimer" data-mls-id="${esc(m.mlsId)}">${boardLogo(m.logo, m.mlsName, 40)}<div class="rw-disclaimer__text">${(paras.length ? paras : [m.mlsName]).map((p) => `<p>${esc(p)}</p>`).join("")}</div></div>`;
  });
  if (asOf) html.push(`<p class="rw-asof">${COPY.dataLastUpdated} <time datetime="${esc(asOf)}">${esc(asOfText(asOf))}</time>.</p>`);
  return `<aside class="rw-recipes rw-disclaimers rw-disclaimers--${placement}" aria-label="${COPY.disclaimersLabel}">${html.join("\n")}</aside>`;
}

/** The pages to link: the first, the last and two on each side of the current one, null for a gap. */
function pageWindow(page, pages) {
  const keep = new Set([1, pages]);
  for (let p = page - 2; p <= page + 2; p++) if (p >= 1 && p <= pages) keep.add(p);
  const sorted = [...keep].sort((a, b) => a - b);
  const out = [];
  sorted.forEach((p, i) => {
    if (i > 0 && p - sorted[i - 1] > 1) out.push(p - sorted[i - 1] === 2 ? p - 1 : null);
    out.push(p);
  });
  return out;
}

/** A path with the given query pairs (in order) and nothing when there are none. */
function withQuery(basePath, pairs) {
  const q = new URLSearchParams();
  for (const [k, v] of pairs) q.append(k, v);
  const s = q.toString();
  return s ? `${basePath}?${s}` : basePath;
}

/** The current query as [name, value] pairs, in order; a repeated name gives one pair per value. */
const queryPairs = (sp) => Object.entries(sp ?? {}).flatMap(([k, v]) => (v === undefined || v === null ? [] : [].concat(v).map((one) => [k, String(one)])));

/** Real <a href> page links that keep the page's other query parameters. Page 1 has no ?page=. */
export function pagination(basePath, page, pages, searchParams = {}) {
  pages = Math.max(0, Math.floor(pages || 0));
  if (pages <= 1) return "";
  page = Math.min(Math.max(1, Math.floor(page || 1)), pages);
  const href = (n) => withQuery(basePath, [...queryPairs(searchParams).filter(([k]) => k !== "page"), ...(n > 1 ? [["page", String(n)]] : [])]);
  const items = [];
  const prev = page > 1 ? `<a class="rw-pagination__step" href="${esc(href(page - 1))}" rel="prev">${COPY.previousPage}</a>` : "";
  for (const p of pageWindow(page, pages)) {
    if (p === null) items.push(`<li class="rw-pagination__gap" aria-hidden="true">…</li>`);
    else items.push(`<li><a${attrs([["class", p === page ? "rw-pagination__page rw-pagination__page--current" : "rw-pagination__page"], ["href", href(p)], ["aria-current", p === page ? "page" : null], ["aria-label", `Page ${p}`]])}>${p}</a></li>`);
  }
  const next = page < pages ? `<a class="rw-pagination__step" href="${esc(href(page + 1))}" rel="next">${COPY.nextPage}</a>` : "";
  return `<nav class="rw-recipes rw-pagination" aria-label="${COPY.pagination}">${prev}<ul class="rw-pagination__list">${items.join("\n")}</ul>${next}</nav>`;
}

/** The listing's attribution block with its board's logo. */
export function attribution(compliance, board) {
  const lines = `${compliance.attributionLine ? `<p class="rw-attribution__line">${esc(compliance.attributionLine)}</p>` : ""}${compliance.courtesyLine ? `<p class="rw-attribution__courtesy">${esc(compliance.courtesyLine)}</p>` : ""}`;
  return `<section class="rw-recipes rw-attribution" data-mls-id="${esc(compliance.mlsId)}">${board ? boardLogo(board.logo, board.mlsName, 32) : ""}<div class="rw-attribution__text">${lines}</div></section>`;
}

// ─── The search page: results toolbar and More filters drawer ─────────────────

const SORT_OPTIONS = [
  ["", "Newest listings"],
  ["price_desc", "Price, high to low"],
  ["price_asc", "Price, low to high"],
  ["beds_desc", "Most bedrooms"],
  ["baths_desc", "Most bathrooms"],
  ["sqft_desc", "Largest homes"],
  ["lot_desc", "Largest lots"],
  ["price_reduced", "Recently reduced"],
  ["oldest", "Oldest listings"],
];
const STATUS_OPTIONS = [
  ["active", "For sale"],
  ["coming_soon", "Coming soon"],
  ["pending", "Pending"],
  ["under_contract", "Under contract"],
  ["closed", "Sold"],
];
const SUBTYPE_OPTIONS = [
  ["house", "House"],
  ["condo", "Condo"],
  ["townhome", "Townhome"],
  ["co-op", "Co-op"],
];
const TYPE_OPTIONS = [
  ["ResidentialIncome", "Multi-family"],
  ["ManufacturedInPark", "Manufactured home"],
  ["Land", "Land"],
  ["Farm", "Farm"],
];
/** The location parameters every filter form keeps (the React Filters' DEFAULT_KEEP). */
export const FILTER_KEEP = ["where", "boundariesId", "zip", "city", "state", "shape", "soldPeriod", "openHousePeriod"];

/** The React components' stable ids: djb2 of the path (xor), base 36. */
function stableId(prefix, key) {
  let h = 5381;
  for (let i = 0; i < key.length; i++) h = (Math.imul(h, 33) ^ key.charCodeAt(i)) >>> 0;
  return `${prefix}-${h.toString(36)}`;
}

const option = (value, label, selected) => `<option${attrs([["value", value], ["selected", selected]])}>${esc(label)}</option>`;

/** html/results-toolbar.html: "Showing N listings", the sort form (it keeps the rest of the query) and Grid | Map. */
export function resultsToolbar({ total, view = "list", basePath, searchParams = {} }) {
  const n = finite(total) && total > 0 ? Math.floor(total) : 0;
  const pairs = queryPairs(searchParams);
  const sort = pairs.find(([k]) => k === "sort")?.[1] ?? "";
  const current = sort && sort !== "recommended" && SORT_OPTIONS.some(([v]) => v === sort) ? sort : "";
  const id = stableId("rw-sort", `${basePath}#sort`);
  const viewHref = (v) => withQuery(basePath, [...pairs.filter(([k]) => k !== "view" && k !== "page"), ...(v === "map" ? [["view", "map"]] : [])]);
  const link = (v, label) => `<a${attrs([["class", view === v ? "rw-toolbar__view rw-toolbar__view--on" : "rw-toolbar__view"], ["href", viewHref(v)], ["aria-current", view === v ? "page" : null], ["data-rw-view", v]])}>${label}</a>`;
  return `<div class="rw-recipes rw-toolbar" role="group" aria-label="${COPY.resultsToolbar}" data-rw-toolbar="">
    <p class="rw-toolbar__count" data-rw-results-count=""><span class="rw-toolbar__showing">${COPY.resultsShowing}</span> <mark class="rw-toolbar__total">${n === 1 ? "1 listing" : `${new Intl.NumberFormat("en-US").format(n)} listings`}</mark></p>
    <div class="rw-toolbar__controls">
      <form class="rw-toolbar__sort" method="get" action="${esc(basePath)}" id="${id}" data-rw-sort="" data-rw-autosubmit="">
        ${pairs.filter(([k]) => k !== "sort" && k !== "page").map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`).join("")}
        <label class="rw-toolbar__sort-label" for="${id}-select">${COPY.sort}</label>
        <select class="rw-toolbar__select" id="${id}-select" name="sort">${SORT_OPTIONS.map(([v, label]) => option(v, label, v === current)).join("")}</select>
        <button class="rw-visually-hidden" type="submit">${COPY.sortApply}</button>
      </form>
      <nav class="rw-toolbar__views" aria-label="${COPY.viewSwitch}" data-rw-view-switch="">${link("list", COPY.viewGrid)}${link("map", COPY.viewMap)}</nav>
    </div>
  </div>`;
}

const listOf = (v) => (v === undefined || v === null || v === "" ? [] : [].concat(v).map(String));

/** The "More filters (N)" count: price, beds, baths, home type, property type, and status unless it is For sale alone. */
export function activeFilterCount(v) {
  const set = (x) => x !== undefined && x !== null && x !== "";
  const st = listOf(v.status);
  return [set(v.priceMin) || set(v.priceMax), set(v.bedsMin), set(v.bathsMin), listOf(v.subtype).length > 0, listOf(v.type).length > 0, st.length > 0 && !(st.length === 1 && st[0] === "active")].filter(Boolean).length;
}

/** html/filters.html without its own buttons: the GET form inside the drawer. `v` is the page's query. */
function filtersForm(action, v, id) {
  const kept = FILTER_KEEP.flatMap((k) => (k === "where" ? listOf(v.where).map((w) => [k, typeof w === "string" ? w : JSON.stringify(w)]) : listOf(v[k]).map((one) => [k, one])));
  const statuses = new Set(listOf(v.status));
  const field = (key, label, control, cls = "rw-field") => `<div class="${cls}"><label class="rw-field__label" for="${id}-${key}">${label}</label>${control}</div>`;
  const counts = (name, key, label, max, value) =>
    field(key, label, `<select class="rw-select" id="${id}-${key}" name="${name}">${option("", COPY.anyNumber, value === "")}${Array.from({ length: max }, (_, i) => option(String(i + 1), `${i + 1} ${COPY.orMore}`, value === String(i + 1))).join("")}</select>`);
  const choice = (name, label, any, options, value) => field(name, label, `<select class="rw-select" id="${id}-${name}" name="${name}">${option("", any, value === "")}${options.map(([o, text]) => option(o, text, o === value)).join("")}</select>`);
  const price = (key, name, label, value) => `<label class="rw-field__label" for="${id}-${key}">${label}</label><input class="rw-input" id="${id}-${key}" name="${name}" type="number" inputMode="numeric" min="0" step="1000" placeholder="${COPY.anyPrice}" value="${esc(value ?? "")}">`;
  const sort = listOf(v.sort)[0] ?? "";
  const statusBoxes = STATUS_OPTIONS.filter(([o]) => o !== "closed" || statuses.has("closed"))
    .map(([o, text]) => `<label class="rw-check"><input${attrs([["type", "checkbox"], ["name", "status"], ["checked", statuses.has(o) || (statuses.size === 0 && o === "active")], ["value", o]])}><span>${text}</span></label>`)
    .join("");
  return `<form class="rw-recipes rw-filters" method="get" action="${esc(action)}" id="${id}" aria-label="${COPY.filtersLabel}" data-rw-filters="">
      ${kept.map(([k, val]) => `<input type="hidden" name="${esc(k)}" value="${esc(val)}">`).join("")}
      <div class="rw-filters__row">
        <div class="rw-field rw-field--price">${price("pmin", "priceMin", COPY.priceMin, v.priceMin)}${price("pmax", "priceMax", COPY.priceMax, v.priceMax)}</div>
        ${counts("bedsMin", "beds", COPY.bedsMin, 6, v.bedsMin !== undefined ? String(v.bedsMin) : "")}
        ${counts("bathsMin", "baths", COPY.bathsMin, 5, v.bathsMin !== undefined ? String(v.bathsMin) : "")}
        ${choice("subtype", COPY.homeStyle, COPY.anyStyle, SUBTYPE_OPTIONS, listOf(v.subtype)[0] ?? "")}
        ${choice("type", COPY.propertyType, COPY.anyType, TYPE_OPTIONS, listOf(v.type)[0] ?? "")}
        ${field("sort", COPY.sort, `<select class="rw-select" id="${id}-sort" name="sort">${SORT_OPTIONS.map(([o, text]) => option(o, text, o === sort)).join("")}</select>`)}
      </div>
      <fieldset class="rw-field rw-field--status"><legend class="rw-field__label">${COPY.status}</legend>${statusBoxes}</fieldset>
    </form>`;
}

/** html/filters-drawer.html: the More filters pill and its drawer with the filters form. `v` is the page's query. */
export function filtersDrawer({ action, value = {} }) {
  const base = stableId("rw-filters", action);
  const dialogId = `${base}-drawer`;
  const formId = `${base}-drawer-form`;
  const n = activeFilterCount(value);
  const reset = withQuery(action, FILTER_KEEP.flatMap((k) => (k === "where" ? listOf(value.where).map((w) => [k, typeof w === "string" ? w : JSON.stringify(w)]) : listOf(value[k]).map((one) => [k, one]))));
  return `<div class="rw-recipes rw-morefilters-wrap" data-rw-drawer-root="">
    <button type="button" class="rw-morefilters" aria-haspopup="dialog" aria-expanded="false" aria-controls="${dialogId}" data-rw-drawer-open="${dialogId}">${icon("tuning-black", 24, "rw-morefilters__icon")}<span class="rw-morefilters__label">${n > 0 ? `${COPY.moreFilters} (${n})` : COPY.moreFilters}</span>${n > 0 ? `<span class="rw-morefilters__badge" aria-hidden="true">${n}</span>` : ""}</button>
    <dialog class="rw-drawer" id="${dialogId}" aria-labelledby="${dialogId}-title" data-rw-drawer="">
      <div class="rw-drawer__header"><h2 class="rw-drawer__title" id="${dialogId}-title">${COPY.filtersTitle}</h2><button type="button" class="rw-drawer__close" aria-label="${COPY.closeFilters}" data-rw-drawer-close="">${icon("drawer-header-close", 24)}</button></div>
      <div class="rw-drawer__body">${filtersForm(action, value, formId)}</div>
      <div class="rw-drawer__footer"><a class="rw-drawer__reset" href="${esc(reset)}" data-rw-drawer-reset="">${COPY.resetFilters}</a><button class="rw-button rw-drawer__show" type="submit" form="${formId}">${COPY.showResults}</button></div>
    </dialog>
  </div>`;
}

// ─── The listing page (html/listing-detail.html and its pieces) ──────────────

// A year field (yearBuilt, taxYear…) reads "2004", never "2,004", as in the React ListingDetail.
function detailValue(v, key = "") {
  if (typeof v === "boolean") return v ? COPY.yes : COPY.no;
  if (typeof v === "number") return /year/i.test(key) && Number.isInteger(v) ? String(v) : NUMBER.format(v);
  if (Array.isArray(v)) return v.join(", ");
  return String(v);
}

/** The pinned summary (MiniSummary): price, dot, address, then the facts with 18px icons. */
function miniSummary(l) {
  const price = usd(shownPrice(l));
  const facts = factItems(l);
  return `<div class="rw-mini" data-rw-mini=""><p class="rw-mini__line">${price ? `<span class="rw-mini__price">${esc(price)}</span><span class="rw-mini__dot" aria-hidden="true"></span>` : ""}<span class="rw-mini__address">${esc(addressLine(l.address) || listingName(l))}</span></p>${facts.length ? `<ul class="rw-mini__facts">${facts.map(([k, t]) => `<li class="rw-mini__fact">${icon(FACT_ICONS[k], 18)}${esc(t)}</li>`).join("")}</ul>` : ""}</div>`;
}

/** html/detail-header.html: Back, and the summary and X that show once the price block scrolls away. */
export function detailHeader(l, backHref) {
  const back = backHref || null;
  return `<header class="${back ? "rw-detail-header" : "rw-detail-header rw-detail-header--bare"}" data-rw-detail-header="">
    <div class="rw-detail-header__row">
      ${back ? `<a class="rw-detail-header__back" href="${esc(back)}" data-rw-header-back="">${icon("chevron-left", 20)}${COPY.back}</a>` : ""}
      <div class="rw-detail-header__summary" data-rw-header-summary="">${miniSummary(l)}</div>
      ${back ? `<a class="rw-detail-header__close" href="${esc(back)}" aria-label="${COPY.closeListing}" data-rw-header-close="">${icon("close", 20)}</a>` : ""}
    </div>
  </header>`;
}

/** html/photo-grid-N.html: up to five cells, the share button, the Street view pill and the "N photos" badge. */
export function photoGrid(l, { streetView = false, share = false, logo = null } = {}) {
  const photos = l.photos ?? [];
  const count = photos.length;
  const name = listingName(l);
  const logoSrc = logo ? safeUrl(logo.url) : null;
  const open = (tab, index) => attrs([["data-rw-open", "gallery"], ["data-rw-open-tab", tab], ["data-rw-open-index", index]]);
  const cells = photos
    .slice(0, 5)
    .map((p, i) => {
      const img = imgAttrs(p, { priority: i === 0, sizes: i === 0 ? "(min-width: 768px) 50vw, 100vw" : "25vw", fallbackAlt: name });
      const logoImg = i === 0 && logoSrc ? `<img${attrs([["class", "rw-photogrid__logo"], ["src", logoSrc], ["alt", logo.alt || ""], ["width", dim(logo.width, 100)], ["height", dim(logo.height, 40)], ["loading", "lazy"], ["decoding", "async"], ["data-rw-photo-logo", true]])}>` : "";
      return `<button type="button" class="rw-photogrid__cell rw-photogrid__cell--${i}" aria-label="View photo ${i + 1}"${open("photos", String(i))}>${img ? `<img${attrs([...img, ["class", "rw-photogrid__img"]])}>` : icon("listing-no-image", 64, "rw-photogrid__placeholder")}${logoImg}</button>`;
    })
    .join("\n");
  return `<div${attrs([["class", `rw-photogrid rw-photogrid--n${Math.min(count, 5)}`], ["data-rw-photo-grid", true], ["data-rw-photos", count ? photosJson(photos) : null], ["data-rw-photo-alt", count ? name : null]])}>
      ${count ? cells : `<div class="rw-photogrid__empty" role="img" aria-label="${COPY.noPhoto}">${icon("listing-no-image", 96, "rw-photogrid__placeholder")}</div>`}
      ${share ? `<div class="rw-photogrid__actions"><button type="button" class="rw-photogrid__iconbtn" aria-label="${COPY.shareHome}" data-rw-open="share">${icon("share-black", 17, "rw-icon--white")}</button></div>` : ""}
      ${streetView ? `<button type="button" class="rw-photogrid__street"${open("street")}>${icon("street-view-white", 20, "rw-icon--white")}${COPY.streetView}</button>` : ""}
      ${count > 1 ? `<button type="button" class="rw-photogrid__count"${open("photos", "0")}>${icon("gallery-round", 16)}${count} photos</button>` : ""}
    </div>`;
}

/** The status dot's colour by the label: closed or sold, pending, else green. */
const priceTone = (label) => (/closed|sold/i.test(label) ? "danger" : /pending/i.test(label) ? "accent" : "green");

/** html/price-block.html: the status, the price, the facts and the address (an h1 on the page, a p in the gallery). */
export function priceBlock(l, addressAs = "h1") {
  const label = l.statusLabel && l.statusLabel.trim() ? l.statusLabel : null;
  const price = usd(shownPrice(l));
  const facts = factItems(l);
  const tag = addressAs === "p" ? "p" : "h1";
  return `<section class="rw-price" data-rw-price-block="">${label ? `<p class="rw-price__status rw-price__status--${priceTone(label)}"><span class="rw-price__dot" aria-hidden="true"></span>${esc(label)}</p>` : ""}${price ? `<p class="rw-price__amount">${esc(price)}</p>` : ""}${facts.length ? `<ul class="rw-price__facts">${facts.map(([k, t]) => `<li class="rw-price__fact">${icon(FACT_ICONS[k], 16)}${esc(t)}</li>`).join("")}</ul>` : ""}<${tag} class="rw-price__address">${esc(addressLine(l.address) || listingName(l))}</${tag}></section>`;
}

// Your agent (never the MLS listing agent): name, brokerage, license, email, phone, photoUrl.
const cleanText = (s) => String(s ?? "").replace(/\s+/g, " ").trim();
const agentName = (a) => cleanText(a?.name) || cleanText(a?.brokerage) || null;
const contactLabel = (a) => (agentName(a) ? `Contact ${agentName(a)}` : COPY.contactAgent);
function agentInitials(a) {
  const words = (agentName(a) ?? "").split(" ").filter((w) => /[A-Za-z0-9]/.test(w));
  return ((words[0]?.[0] ?? "") + (words.length > 1 ? words[words.length - 1][0] : "")).toUpperCase();
}
function telHref(phone) {
  const digits = cleanText(phone).replace(/[^\d+]/g, "").replace(/(?!^)\+/g, "");
  return digits.replace(/\D/g, "").length >= 7 ? `tel:${digits}` : null;
}
const mailtoHref = (email) => (/^[^\s@<>"]+@[^\s@<>"]+\.[^\s@<>"]+$/.test(cleanText(email)) ? `mailto:${cleanText(email)}` : null);

function avatar(a, size, tone) {
  const photo = /^https?:\/\//i.test(cleanText(a?.photoUrl)) ? cleanText(a.photoUrl) : null;
  if (photo) return `<img class="rw-avatar rw-avatar--${size}" src="${esc(photo)}" alt="" width="${size}" height="${size}" loading="lazy" decoding="async">`;
  const initials = agentInitials(a);
  return initials ? `<span class="rw-avatar rw-avatar--${size} rw-avatar--${tone}" aria-hidden="true">${esc(initials)}</span>` : "";
}

/** html/agent-info.html: the labelled rows with the round email and phone links. */
export function agentInfo(a) {
  const who = agentName(a);
  const row = (label, value, side = "") => `<li class="rw-agentinfo__row"><div class="rw-agentinfo__text"><p class="rw-agentinfo__label">${label}</p><p class="rw-agentinfo__value">${esc(value)}</p></div>${side}</li>`;
  const rows = [];
  if (cleanText(a.name)) rows.push(row(COPY.agentNameLabel, cleanText(a.name), avatar(a, 45, "grey")));
  if (cleanText(a.brokerage)) rows.push(row(COPY.brokerageLabel, cleanText(a.brokerage)));
  if (cleanText(a.license)) rows.push(row(COPY.licenseLabel, cleanText(a.license)));
  if (cleanText(a.email)) {
    const href = mailtoHref(a.email);
    rows.push(row(COPY.emailLabel, cleanText(a.email), href ? `<a class="rw-agentinfo__round" href="${esc(href)}" aria-label="${esc(who ? `Email ${who}` : COPY.emailAgentNoName)}">${icon("letter", 20)}</a>` : ""));
  }
  if (cleanText(a.phone)) {
    const href = telHref(a.phone);
    rows.push(row(COPY.phoneLabel, cleanText(a.phone), href ? `<a class="rw-agentinfo__round" href="${esc(href)}" aria-label="${esc(who ? `Call ${who}` : COPY.callAgentNoName)}">${icon("phone", 20)}</a>` : ""));
  }
  return rows.length ? `<section class="rw-detail__block rw-agentinfo" data-rw-agent-info=""><h2 class="rw-detail__title">${COPY.agentInformation}</h2><ul class="rw-agentinfo__rows">${rows.join("")}</ul></section>` : "";
}

/** html/agent-card.html and html/tour-card.html stacked: the sidebar's contact cards. */
export function contactCards(a) {
  const name = agentName(a);
  return `<div class="rw-contactcards" data-rw-contact-cards=""><div class="rw-agentcard" data-rw-agent-card="">${name ? `<div class="rw-agentcard__who">${avatar(a, 48, "dark")}<p class="rw-agentcard__name">${esc(name)}</p></div>` : ""}<h2 class="rw-agentcard__title">${COPY.agentCardTitle}</h2><p class="rw-agentcard__text">${COPY.agentCardText}</p><button type="button" class="rw-button rw-button--block" data-rw-open="contact">${esc(contactLabel(a))}</button></div><div class="rw-tourcard" data-rw-tour-card=""><h2 class="rw-tourcard__title">${COPY.tourCardTitle}</h2><p class="rw-tourcard__text">${COPY.tourCardText}</p><button type="button" class="rw-button rw-button--accent rw-button--block" data-rw-open="tour">${COPY.chooseTourTime}</button></div></div>`;
}

/** html/mobile-bar.html: the two buttons fixed to the bottom under 992px. */
export const mobileBar = (a) => `<div class="rw-mobilebar" data-rw-mobile-bar=""><button type="button" class="rw-button rw-button--block" data-rw-open="contact">${esc(contactLabel(a))}</button><button type="button" class="rw-button rw-button--accent rw-button--block" data-rw-open="tour">${COPY.chooseTourTime}</button></div>`;

// Open houses on the listing's own clock (src/open-houses.tsx).
const OFFSET = /([+-])(\d{2}):?(\d{2})$/;
function clockOf(raw, timeZone) {
  const hasInstant = /Z$/i.test(raw) || OFFSET.test(raw);
  const zone = validZone(timeZone);
  if (zone && hasInstant) return { kind: "zone", zone };
  const m = OFFSET.exec(raw);
  if (m) return { kind: "offset", minutes: (m[1] === "-" ? -1 : 1) * (Number(m[2]) * 60 + Number(m[3])) };
  if (/Z$/i.test(raw)) return { kind: "offset", minutes: 0 };
  return { kind: "naive" };
}
function instantOf(raw) {
  if (/Z$/i.test(raw) || OFFSET.test(raw)) {
    const t = Date.parse(raw);
    return Number.isFinite(t) ? new Date(t) : null;
  }
  const m = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2}))?/.exec(raw);
  return m ? new Date(Date.UTC(+m[1], +m[2] - 1, +m[3], +(m[4] ?? 0), +(m[5] ?? 0))) : null;
}
function onClock(d, clock, o) {
  const shifted = clock.kind === "offset" ? new Date(d.getTime() + clock.minutes * 60000) : d;
  return new Intl.DateTimeFormat("en-US", { ...o, timeZone: clock.kind === "zone" ? clock.zone : "UTC" }).format(shifted).replace(/[  ]/g, " ");
}
const dayStamp = (d, clock) => onClock(d, clock, { year: "numeric", month: "2-digit", day: "2-digit" });

/** The open houses to show: not ended, starting within 30 days, sorted, with Today, Tomorrow and the times. */
export function openHouseEntries(list, now) {
  const rows = [];
  (list ?? []).forEach((o) => {
    if (!o || typeof o.start !== "string") return;
    const start = instantOf(o.start);
    if (!start) return;
    const end = typeof o.end === "string" ? instantOf(o.end) : null;
    if (start.getTime() > now.getTime() + 30 * 864e5) return;
    if (end ? end.getTime() <= now.getTime() : start.getTime() <= now.getTime()) return;
    const clock = clockOf(o.start, o.timeZone);
    const hour = Number(onClock(start, clock, { hour: "numeric", hourCycle: "h23" }));
    const trusted = clock.kind !== "naive" && hour >= 7 && hour <= 20;
    const today = dayStamp(start, clock) === dayStamp(now, clock);
    const tomorrow = !today && dayStamp(start, clock) === dayStamp(new Date(now.getTime() + 864e5), clock);
    const longDay = onClock(start, clock, { weekday: "long", month: "long", day: "numeric" });
    const times = trusted ? [start, end].filter(Boolean).map((d) => onClock(d, clock, { hour: "numeric", minute: "2-digit" })) : [];
    rows.push({
      at: start.getTime(),
      start: o.start,
      dayLabel: today ? COPY.openHouseToday : tomorrow ? COPY.openHouseTomorrow : longDay,
      absoluteDate: today || tomorrow ? longDay : null,
      timeRange: times.length ? times.join(" to ") : null,
      isLive: trusted && end !== null && start.getTime() <= now.getTime() && end.getTime() > now.getTime(),
      remarks: o.remarks && o.remarks.trim() ? o.remarks.trim() : null,
    });
  });
  return rows.sort((a, b) => a.at - b.at);
}

/** html/open-houses.html. `listId` is the list's id (any value unique on the page). */
export function openHouses(list, { tour = false, now = new Date(), listId = "open-houses" } = {}) {
  const entries = openHouseEntries(list, now);
  if (!entries.length) return "";
  const items = entries
    .map((e, i) => `<li${attrs([["class", "rw-openhouses__entry"], ["hidden", i >= 3], ["data-rw-oh-extra", i >= 3]])}><p class="rw-openhouses__day"><time datetime="${esc(e.start)}">${esc(e.dayLabel)}</time></p>${e.absoluteDate ? `<p class="rw-openhouses__date">${esc(e.absoluteDate)}</p>` : ""}${e.timeRange ? `<p class="rw-openhouses__time">${esc(e.timeRange)}</p>` : ""}${e.isLive ? `<p class="rw-openhouses__live"><span class="rw-openhouses__dot" aria-hidden="true"></span>${COPY.happeningNow}</p>` : ""}${e.remarks ? `<p class="rw-openhouses__remarks">${esc(e.remarks)}</p>` : ""}</li>`)
    .join("");
  const more = `Show all ${entries.length} open houses`;
  return `<section class="rw-detail__block rw-openhouses" data-rw-open-houses=""><h2 class="rw-detail__title">${entries.length === 1 ? "Open house" : "Open houses"}</h2><ul class="rw-openhouses__grid" id="${esc(listId)}">${items}</ul>${entries.length > 3 ? `<button type="button" class="rw-openhouses__toggle" aria-expanded="false" aria-controls="${esc(listId)}" data-rw-oh-toggle="" data-rw-oh-more="${more}" data-rw-oh-fewer="Show fewer open houses">${more}</button>` : ""}${tour ? `<div class="rw-openhouses__tour"><p class="rw-openhouses__prompt">${COPY.tourPrompt}</p><button type="button" class="rw-button rw-button--accent" data-rw-open="tour">${COPY.scheduleTour}</button></div>` : ""}</section>`;
}

const SECTION_ICONS = {
  "adabf788-a332-4729-98ef-9a950fe93aec": "checklist-minimalistic",
  "b1b0a859-8f18-4f10-8075-74e935e3ffd7": "lamp",
  "e7e42c57-1985-4dee-8499-de277c6652e7": "home",
  "4917d0d0-c2e4-4ead-a38a-7dd68cae1c0e": "garage",
  "0aeb8e6b-eeb7-4acd-af09-9e2775fd5411": "lightning",
  "6b1aa338-816e-4071-afcc-5d32e5d4b1f4": "point-on-map",
  "bf41618a-39fb-4b9e-9b59-848ab86141dd": "money-bag",
};

/** The Property details accordions: one per section with items, the first open, each with its icon. */
function propertyDetails(sections) {
  if (!sections.length) return "";
  const html = sections
    .map((s, i) => `<details${attrs([["class", "rw-accordion"], ["open", i === 0], ["data-category-id", s.categoryId]])}><summary class="rw-accordion__summary">${icon(SECTION_ICONS[String(s.categoryId ?? "").toLowerCase()] ?? "more-horizontal", 24, "rw-accordion__icon")}<span class="rw-accordion__title">${esc(s.label)}</span>${icon("chevron-down", 20, "rw-accordion__chevron")}</summary><ul class="rw-accordion__list">${s.items.map((it) => `<li class="rw-accordion__item"><span class="rw-accordion__label">${esc(it.label)}</span> ${esc(detailValue(it.value, it.key))}</li>`).join("")}</ul></details>`)
    .join("");
  return `<section class="rw-detail__block rw-details"><h2 class="rw-detail__title">${COPY.propertyDetails}</h2><div class="rw-details__list">${html}</div></section>`;
}

/** html/location-map.html. */
export function locationMap({ googleMapsKey, mapId = null, lat, lng, priceLabel = null, address }) {
  return `<div${attrs([["class", "rw-locmap"], ["role", "region"], ["aria-label", COPY.locationMap], ["data-rw-location-map", true], ["data-rw-maps-key", googleMapsKey], ["data-rw-map-id", mapId || null], ["data-rw-lat", String(lat)], ["data-rw-lng", String(lng)], ["data-rw-price-label", priceLabel || null], ["data-rw-address", address]])}><div class="rw-locmap__canvas" data-rw-map-canvas=""></div><p class="rw-locmap__message" role="status">${COPY.mapLoading}</p><button type="button" class="rw-locmap__street" disabled="" data-rw-street-toggle="">${icon("street-view-white", 20, "rw-icon--white")}${COPY.streetView}</button><button type="button" class="rw-locmap__expand" aria-label="${COPY.expandMap}" data-rw-expand="">${icon("maximize", 20)}</button></div>`;
}

// ─── The mortgage calculator (html/mortgage-calculator.html) ─────────────────

const MORTGAGE_LINES = ["principalAndInterest", "propertyTax", "homeInsurance", "mortgageInsurance", "hoa"];
const CREDIT_SCORES = ["760+", "740-759", "720-739", "700-719", "680-699", "660-679", "640-659", "620-639", "<620"];
const CA_PROVINCES = ["AB", "BC", "MB", "NB", "NL", "NS", "NT", "NU", "ON", "PE", "QC", "SK", "YT"];
const countryOf = (state) => (CA_PROVINCES.includes(String(state ?? "").toUpperCase()) ? "CA" : "US");
const MORTGAGE_ORDER = ["price", "downPayment", "downPaymentPercent", "loanType", "termYears", "rateType", "amortizationYears", "creditScore", "rate", "state", "zip", "hoaMonthly", "propertyTaxAnnual", "insuranceAnnual"];

function fallbackOptions(country) {
  if (country === "CA")
    return {
      loanTypes: [
        { value: "fixed", label: "Fixed rate" },
        { value: "variable", label: "Variable rate, fixed payment" },
        { value: "adjustable", label: "Adjustable rate" },
      ],
      terms: Array.from({ length: 10 }, (_, i) => ({ value: String(i + 1), label: i === 0 ? "1 year" : `${i + 1} years` })),
    };
  return {
    loanTypes: ["Conventional", "FHA", "VA", "USDA", "Jumbo"].map((label) => ({ value: label.toLowerCase(), label })),
    terms: [
      { value: "30", label: "30 years, fixed" },
      { value: "20", label: "20 years, fixed" },
      { value: "15", label: "15 years, fixed" },
      { value: "30-arm", label: "5/6 ARM" },
    ],
  };
}

/** A money figure from a number or a formatted string ("$7,412.50"); null when there is none. */
function moneyOf(v) {
  if (typeof v === "number") return Number.isFinite(v) && v >= 0 ? v : null;
  if (Array.isArray(v)) return v.length ? moneyOf(v[0]) : null;
  if (typeof v !== "string") return null;
  const m = /-?\d[\d,]*(?:\.\d+)?/.exec(v);
  if (!m || m[0].startsWith("-")) return null;
  const n = Number(m[0].replace(/,/g, ""));
  return Number.isFinite(n) ? n : null;
}

/** Payments per month for an MLS fee frequency; missing = monthly; one-time or unknown = null. */
function perMonth(frequency) {
  if (frequency === undefined || frequency === null || frequency === "") return 1;
  const f = String(Array.isArray(frequency) ? frequency[0] : frequency).toLowerCase().replace(/[^a-z]/g, "");
  if (!f || f.startsWith("month")) return 1;
  if (f === "bimonthly" || f.includes("everyothermonth")) return 1 / 2;
  if (f.startsWith("quarter")) return 1 / 3;
  if (f.startsWith("semiannual") || f.includes("twiceayear")) return 1 / 6;
  if (f.startsWith("annual") || f.startsWith("year")) return 1 / 12;
  if (f.startsWith("semimonth")) return 2;
  if (f.startsWith("biweek")) return 26 / 12;
  if (f.startsWith("week")) return 52 / 12;
  if (f.startsWith("dai")) return 365 / 12;
  return null;
}

/** What the calculator starts from: the price, state and ZIP, and the listing's HOA dues and yearly tax. */
export function mortgagePrefill(l) {
  const items = new Map();
  for (const s of l.details ?? []) for (const it of s.items) if (!items.has(it.key)) items.set(it.key, it.value);
  let hoa = null;
  for (const [fee, freq] of [["associationFee", "associationFeeFrequency"], ["associationFee2", "associationFee2Frequency"], ["associationFee3", "associationFee3Frequency"]]) {
    const amount = moneyOf(items.get(fee));
    const times = perMonth(items.get(freq));
    if (amount === null || times === null) continue;
    hoa = Math.round(((hoa ?? 0) + amount * times) * 100) / 100;
  }
  const postal = l.address.postalCode;
  return {
    price: finite(l.price) && l.price > 0 ? l.price : null,
    state: l.address.state,
    zip: typeof postal === "string" && /^\d{5}(-\d{4})?$/.test(postal) ? postal.slice(0, 5) : null,
    hoaMonthly: hoa,
    propertyTaxAnnual: moneyOf(items.get("taxAnnualAmount")),
  };
}

/** The starting query the page's calculator asks with (also data-rw-mortgage-query). */
export function mortgageStart(prefill) {
  const ca = countryOf(prefill.state) === "CA";
  return { price: prefill.price, downPaymentPercent: 20, loanType: null, termYears: null, state: prefill.state ? prefill.state.toUpperCase() : null, zip: ca ? null : (prefill.zip ?? null), hoaMonthly: prefill.hoaMonthly ?? null, propertyTaxAnnual: prefill.propertyTaxAnnual ?? null, insuranceAnnual: null };
}

/** The canonical query string of GET /v1/mortgage/estimate (the same as @ruuster/idx toMortgageQueryString). */
export function mortgageQueryString(q) {
  const out = new URLSearchParams();
  for (const name of MORTGAGE_ORDER) {
    const v = q[name];
    if (v === undefined || v === null || v === "") continue;
    if (typeof v !== "number" || Number.isFinite(v)) out.append(name, String(v));
  }
  return out.toString();
}

const money = (n) => `$${Math.round(n).toLocaleString("en-US")}`;
function rateDate(iso) {
  const d = new Date(`${String(iso).slice(0, 10)}T12:00:00Z`);
  return Number.isNaN(d.getTime()) ? iso : d.toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric", timeZone: "UTC" });
}

/**
 * html/mortgage-calculator.html. `estimate` is the first answer of GET /v1/mortgage/estimate (data),
 * asked on your server with your secret key; null prints the calculator empty and the browser fills
 * it. `baseUrl` is where the browser asks for new figures: your own server route (such as /api/idx),
 * or null for the API itself from your approved website address. The page carries no key. `id` is
 * any value unique on the page.
 */
export function mortgageCalculator({ baseUrl = null, prefill, estimate = null, id = "mortgage" }) {
  const est = estimate;
  const country = est?.country ?? countryOf(prefill.state);
  const ca = country === "CA";
  const price = prefill.price;
  const start = mortgageStart(prefill);
  const loanType = est?.inputs.loanType ?? (ca ? "fixed" : "conventional");
  const term = est ? (est.country === "US" && est.inputs.rateType === "arm" ? `${est.inputs.termYears}-arm` : String(est.inputs.termYears)) : ca ? "5" : "30";
  const options = est?.options ?? fallbackOptions(country);
  const m = est?.monthly ?? null;
  const rate = est?.rate.annualPercent ?? null;
  const priceMin = Math.min(50_000, Math.max(1000, Math.floor(price / 5000) * 5000));
  const priceMax = Math.max(2_500_000, Math.ceil((price * 3) / 5000) * 5000);
  const select = (field, label, key, value, opts) => `<div class="rw-field"><label class="rw-field__label" for="${id}-${key}">${label}</label><select class="rw-select" id="${id}-${key}" data-rw-mortgage-field="${field}">${opts.map((o) => option(o.value, o.label, o.value === value)).join("")}</select></div>`;
  const slider = (field, key, label, value, min, max, step, extra = "", hint = null) =>
    `<div class="rw-mortgage__slider"><div class="rw-mortgage__slider-head"><label class="rw-field__label" id="${id}-${key}-label" for="${id}-${key}">${label}</label>${extra}</div><input class="rw-input rw-mortgage__number" id="${id}-${key}" type="number" inputMode="decimal" min="${min}" max="${max}" step="${step}" data-rw-mortgage-field="${field}" value="${value ?? ""}"><input class="rw-mortgage__range" type="range" aria-labelledby="${id}-${key}-label" min="${min}" max="${max}" step="${step}" data-rw-mortgage-field="${field}" value="${value ?? min}">${hint === null ? "" : `<p class="rw-mortgage__hint" data-rw-mortgage-out="${hint[0]}">${esc(hint[1])}</p>`}</div>`;
  const mode = `<fieldset class="rw-mortgage__mode"><legend class="rw-visually-hidden">${COPY.downPayment}</legend><label class="rw-mortgage__mode-option"><input type="radio" name="${id}-downmode" data-rw-mortgage-field="downMode" value="$"><span>${COPY.downPaymentDollars}</span></label><label class="rw-mortgage__mode-option"><input type="radio" name="${id}-downmode" data-rw-mortgage-field="downMode" checked="" value="%"><span>${COPY.downPaymentPercent}</span></label></fieldset>`;
  const more = [
    ["propertyTaxAnnual", COPY.propertyTaxYearly, prefill.propertyTaxAnnual, m ? Math.round(m.propertyTax * 12) : null],
    ["insuranceAnnual", COPY.insuranceYearly, null, m ? Math.round(m.homeInsurance * 12) : null],
    ["hoaMonthly", ca ? COPY.condoFeesMonthly : COPY.hoaMonthly, prefill.hoaMonthly, m ? Math.round(m.hoa) : 0],
  ]
    .map(([field, label, value, placeholder]) => `<div class="rw-field"><label class="rw-field__label" for="${id}-${field}">${label}</label><input${attrs([["class", "rw-input"], ["id", `${id}-${field}`], ["type", "text"], ["inputMode", "decimal"], ["placeholder", placeholder === null ? null : placeholder.toLocaleString("en-US")], ["data-rw-mortgage-field", field], ["value", value === null || value === undefined ? "" : String(value)]])}></div>`)
    .join("");
  const circ = 2 * Math.PI * 54;
  let offset = 0;
  const arcs = MORTGAGE_LINES.map((line) => {
    const len = m && m[line] > 0 ? (m[line] / (m.total || 1)) * circ : 0;
    const at = m ? offset : 0;
    offset += len;
    return `<circle class="rw-mortgage__seg rw-mortgage__seg--${line}" cx="70" cy="70" r="54" fill="none" stroke-width="16" stroke-dasharray="${len.toFixed(3)} ${(circ - len).toFixed(3)}" stroke-dashoffset="${(-at).toFixed(3)}" transform="rotate(-90 70 70)" data-rw-mortgage-seg="${line}"></circle>`;
  }).join("");
  const labels = { principalAndInterest: COPY.principalInterest, propertyTax: COPY.propertyTaxes, homeInsurance: COPY.homeInsurance, mortgageInsurance: COPY.mortgageInsurance, hoa: ca ? COPY.condoFees : COPY.hoaDues };
  const rows = MORTGAGE_LINES.map((line) => {
    const badge = ["propertyTax", "homeInsurance", "hoa"].includes(line) ? `<span class="rw-mortgage__est" title="${COPY.estimatedLabel}"${m?.provenance[line] === "estimated" ? "" : ' hidden=""'} data-rw-mortgage-est="${line}"><span aria-hidden="true">${COPY.estimatedBadge}</span><span class="rw-visually-hidden">${COPY.estimatedLabel}</span></span>` : "";
    return `<li class="rw-mortgage__row" data-line="${line}"><span class="rw-mortgage__dot rw-mortgage__dot--${line}" aria-hidden="true"></span><span class="rw-mortgage__label">${labels[line]}</span>${badge}<span class="rw-mortgage__value" data-rw-mortgage-out="${line}">${m ? money(m[line]) : ""}</span></li>`;
  }).join("");
  const total = m ? money(m.total) : "";
  return `<section${attrs([["class", "rw-recipes rw-mortgage"], ["aria-labelledby", `${id}-title`], ["data-rw-mortgage", true], ["data-rw-base-url", baseUrl || null], ["data-rw-mortgage-query", JSON.stringify(start)], ["data-country", country]])}>
    <h2 class="rw-mortgage__title" id="${id}-title">${COPY.mortgageTitle}</h2>
    <div class="rw-mortgage__selects">${select("loanType", COPY.loanType, "loan", loanType, options.loanTypes)}${select("term", COPY.loanTerm, "term", term, options.terms)}</div>
    <div class="rw-mortgage__sliders">${slider("price", "price", COPY.homePrice, price, priceMin, priceMax, 5000)}${slider("downPayment", "down", COPY.downPayment, 20, 0, 100, 0.5, mode, ["downHint", `${money((price * 20) / 100)} down`])}${slider("rate", "rate", COPY.interestRate, rate, 0, 15, 0.01, "", ["rateHint", est ? `Market rate on ${rateDate(est.rate.asOf)}` : ""])}</div>
    <details class="rw-mortgage__more"><summary class="rw-mortgage__more-summary">${COPY.moreOptions}</summary><div class="rw-mortgage__more-grid">${ca ? "" : select("creditScore", COPY.creditScore, "score", "760+", CREDIT_SCORES.map((s) => ({ value: s, label: s })))}${more}</div></details>
    <div class="rw-mortgage__result"><div class="rw-mortgage__donut" data-rw-mortgage-donut=""><svg viewBox="0 0 140 140" width="160" height="160" aria-hidden="true" focusable="false"><circle class="rw-mortgage__track" cx="70" cy="70" r="54" fill="none" stroke-width="16"></circle>${arcs}</svg><p class="rw-mortgage__center"><span class="rw-mortgage__total" data-rw-mortgage-out="total">${total}</span><span class="rw-mortgage__per">${COPY.perMonth}</span></p></div><div class="rw-mortgage__lines"><h3 class="rw-visually-hidden">${COPY.mortgageBreakdown}</h3><ul class="rw-mortgage__list">${rows}<li class="rw-mortgage__row rw-mortgage__row--total"><span class="rw-mortgage__label">${COPY.monthlyTotal}</span><span class="rw-mortgage__value" data-rw-mortgage-out="total">${total}</span></li></ul><p class="rw-mortgage__note" data-rw-mortgage-out="note"${est?.mortgageInsuranceNote ? "" : ' hidden=""'}>${esc(est?.mortgageInsuranceNote ?? "")}</p></div></div>
    <div class="rw-mortgage__reasons" data-rw-mortgage-out="reasons"${!est || est.eligible ? ' hidden=""' : ""}><p class="rw-mortgage__reasons-title">${COPY.mortgageAdjust}</p><ul>${(est?.ineligibleReasons ?? []).map((r) => `<li>${esc(r)}</li>`).join("")}</ul></div>
    <p class="rw-mortgage__stale" data-rw-mortgage-out="stale"${est?.stale ? "" : ' hidden=""'}>${COPY.mortgageStale}</p>
    <p class="rw-mortgage__status" role="status" aria-live="polite"><span data-rw-mortgage-out="status"></span> <button type="button" class="rw-mortgage__link" hidden="" data-rw-mortgage-retry="">${COPY.tryAgain}</button></p>
    <div class="rw-mortgage__disclosures" data-rw-mortgage-out="disclosures">${(est?.requiredDisclosures ?? []).map((d) => `<p>${esc(d)}</p>`).join("")}</div>
  </section>`;
}

/**
 * Whether the page shows the calculator: somewhere to ask (an apiBaseUrl, or mortgage: true for the API
 * itself), mortgage not false, a price, and not closed, a lease or a rental.
 */
const mortgageShown = (l, price, o) => o.mortgage !== false && Boolean(o.apiBaseUrl || o.mortgage) && Boolean(price) && l.status !== "closed" && !/lease|rent/i.test(`${l.type ?? ""} ${l.subtype ?? ""}`);

// ─── The full gallery (html/full-gallery.html) ────────────────────────────────

const TILE_SIZES = { full: "(min-width: 1280px) 960px, (min-width: 992px) 60vw, 100vw", half: "(min-width: 1280px) 480px, (min-width: 992px) 30vw, (min-width: 768px) 50vw, 100vw" };
/** Every third tile from 0 is full width; a last half tile without a partner too. */
const mosaicVariant = (i, total) => (i % 3 === 0 || (i === total - 1 && (i % 3) % 2 === 1) ? "full" : "half");

/** html/full-gallery.html: closed; `id` is any value unique on the page. */
export function fullGallery(l, { streetView = false, share = false, sidebar = "", bar = "", id = "gallery" } = {}) {
  const photos = (l.photos ?? []).filter((p) => safeUrl(p.url));
  const n = photos.length;
  const tabs = streetView ? ["photos", "street"] : ["photos"];
  const tab = (t) => `<button type="button" role="tab" id="${id}-tab-${t}" aria-selected="${t === "photos"}" aria-controls="${id}-panel-${t}" tabindex="${t === "photos" ? "0" : "-1"}" class="rw-fullgallery__tab" data-rw-gallery-tab="${t}">${t === "photos" ? COPY.tabPhotos : COPY.tabStreetView}</button>`;
  const tiles = n
    ? `<div class="rw-fullgallery__mosaic" data-rw-mosaic="">${photos
        .map((p, i) => {
          const v = mosaicVariant(i, n);
          const img = imgAttrs(p, { sizes: TILE_SIZES[v], fallbackAlt: listingName(l) }).map(([k, x]) => [k, k === "alt" ? "" : k === "loading" ? "lazy" : x]);
          return `<button type="button" class="rw-fullgallery__tile rw-fullgallery__tile--${v}" aria-label="Open photo ${i + 1} of ${n}" data-rw-mosaic-tile="${i}"><img${attrs(img)}></button>`;
        })
        .join("")}</div>`
    : `<p class="rw-fullgallery__empty">${COPY.noPhoto}</p>`;
  const street = streetView
    ? `<div role="tabpanel" id="${id}-panel-street" aria-labelledby="${id}-tab-street" class="rw-fullgallery__panel rw-fullgallery__panel--street" data-rw-gallery-panel="street" hidden=""><div class="rw-fullgallery__street"><div class="rw-fullgallery__pano" data-rw-street-pano=""></div><div class="rw-fullgallery__street-wait" role="status">${icon("street-view-white", 48, "rw-fullgallery__street-icon")}<span class="rw-visually-hidden">${COPY.streetViewLoading}</span></div></div></div>`
    : "";
  const steps = n > 1 ? `<button type="button" class="rw-lightbox__step rw-lightbox__step--prev" aria-label="${COPY.previousPhoto}" data-rw-lightbox-prev="">${icon("chevron-left", 24)}</button><button type="button" class="rw-lightbox__step rw-lightbox__step--next" aria-label="${COPY.nextPhoto}" data-rw-lightbox-next="">${icon("chevron-right", 24)}</button>` : "";
  return `<dialog class="rw-recipes rw-fullgallery" aria-label="${COPY.galleryTitle}" data-rw-screen="gallery">
    <div class="rw-fullgallery__header" data-rw-gallery-header=""><div class="rw-fullgallery__header-inner"><div role="tablist" aria-label="${COPY.galleryTabs}" class="rw-fullgallery__tabs">${tabs.map(tab).join("")}</div>${share ? `<div class="rw-fullgallery__actions"><button type="button" class="rw-fullgallery__share" data-rw-open="share">${icon("share-white", 20)}${COPY.shareButton}</button></div>` : ""}<button type="button" class="rw-fullgallery__close" aria-label="${COPY.closeFullGallery}" data-rw-gallery-close="">${icon("close", 20)}</button></div></div>
    <div class="rw-fullgallery__content${bar ? "" : " rw-fullgallery__content--nobar"}"><div class="rw-fullgallery__columns"><div class="rw-fullgallery__main"><div class="rw-fullgallery__mark" data-rw-gallery-mark="" aria-hidden="true"></div><div class="rw-fullgallery__tabcontent"><div role="tabpanel" id="${id}-panel-photos" aria-labelledby="${id}-tab-photos" class="rw-fullgallery__panel" data-rw-gallery-panel="photos">${tiles}</div>${street}${share ? `<button type="button" class="rw-fullgallery__float-share" aria-label="${COPY.shareHome}" data-rw-open="share">${icon("share-white", 16, "rw-icon--white")}</button>` : ""}</div></div><div class="rw-fullgallery__sidebar" data-rw-gallery-sidebar="">${priceBlock(l, "p")}${sidebar ? `<div class="rw-fullgallery__sticky">${sidebar}</div>` : ""}</div></div></div>
    ${bar ? `<div class="rw-fullgallery__bar">${bar}</div>` : ""}
    <dialog class="rw-lightbox" aria-label="${COPY.galleryTitle}" data-rw-lightbox=""><button type="button" class="rw-lightbox__close" aria-label="${COPY.closeGallery}" data-rw-lightbox-close="">${icon("close", 20)}</button>${steps}</dialog>
  </dialog>`;
}

// ─── The dialogs (html/share-modal.html, html/contact-modal.html, html/tour-modal.html) ──

/** The dialog shell (Modal): a dark header with the title and X, then the body. */
const modal = (name, title, titleId, body) =>
  `<div class="rw-modal-host" data-rw-screen="${name}"><dialog class="rw-recipes rw-modal rw-modal--md" data-rw-modal="${name}" aria-labelledby="${esc(titleId)}"><div class="rw-modal__panel"><div class="rw-modal__header"><h2 class="rw-modal__title" id="${esc(titleId)}">${esc(title)}</h2><button type="button" class="rw-modal__close" aria-label="${COPY.closeDialog}" data-rw-modal-close="">${icon("close-white", 24)}</button></div><div class="rw-modal__body">${body}</div></div></dialog></div>`;

/** encodeURIComponent, as the share links use it. */
const enc = (s) => encodeURIComponent(s);

/** "A home at {address}", or "A home in {city}" when the address is hidden. */
function shareSubject(l) {
  const a = l.address;
  if (a.hidden) {
    const city = a.city ?? a.state ?? null;
    return city ? `A home in ${city}` : COPY.shareTitle;
  }
  const address = addressLine(a);
  return address ? `A home at ${address}` : COPY.shareTitle;
}

/** html/share-modal.html: `url` is your own URL of the listing page. */
export function shareModal(l, url, { titleId = "share-title", id = "share" } = {}) {
  const text = `Take a look at this home: ${url}`;
  const subject = shareSubject(l);
  const social = (name, cls, href, label, ico) => `<a class="rw-share__social rw-share__social--${cls}" href="${esc(href)}" target="_blank" rel="noopener noreferrer" aria-label="${label}" data-rw-share="${name}">${icon(ico, 24)}</a>`;
  return modal(
    "share",
    COPY.shareTitle,
    titleId,
    `<div class="rw-share" data-rw-share-url="${esc(url)}" data-rw-share-native="true"><h3 class="rw-share__heading">${COPY.shareHeading}</h3><div class="rw-share__link"><label class="rw-field__label" for="${id}-url">${COPY.shareLinkLabel}</label><div class="rw-share__row"><input class="rw-share__input" id="${id}-url" type="url" readonly="" data-rw-share-input="" value="${esc(url)}"><button type="button" class="rw-share__copy" aria-describedby="${id}-copy-status" data-rw-copy="">${icon("link", 18)}<span data-rw-copy-label="">${COPY.copyLink}</span></button></div><p class="rw-share__status" id="${id}-copy-status" role="status" aria-live="polite" data-rw-copy-status=""></p></div><p class="rw-share__or">${COPY.shareOr}</p><div class="rw-share__socials">${social("facebook", "facebook", `https://www.facebook.com/sharer/sharer.php?u=${enc(url)}`, COPY.shareFacebook, "facebook")}${social("whatsapp", "whatsapp", `https://wa.me/?text=${enc(text)}`, COPY.shareWhatsApp, "whats-app")}${social("email", "email", `mailto:?subject=${enc(subject)}&body=${enc(text)}`, COPY.shareEmail, "letter")}</div><button type="button" class="rw-share__more" hidden="" data-rw-share-more="">${COPY.shareMore}</button></div>`,
  );
}

/** The listing as the lead forms send it (data-rw-lead-listing). */
const leadListing = (l) => JSON.stringify({ id: l.id, mlsNumber: l.mlsNumber, url: l.href, name: listingName(l), price: shownPrice(l) });

const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

/** The 16 days from today in the listing's time zone (the zone of its first open house; else UTC on this server). */
export function tourDays(now, timeZone) {
  const zone = validZone(timeZone) ?? "UTC";
  const parts = Object.fromEntries(new Intl.DateTimeFormat("en-US", { year: "numeric", month: "numeric", day: "numeric", timeZone: zone }).formatToParts(now).map((p) => [p.type, p.value]));
  const start = Date.UTC(Number(parts.year), Number(parts.month) - 1, Number(parts.day), 12);
  return Array.from({ length: 16 }, (_, i) => {
    const d = new Date(start + i * 864e5);
    return { iso: d.toISOString().slice(0, 10), weekday: WEEKDAYS[d.getUTCDay()], day: String(d.getUTCDate()), month: MONTHS[d.getUTCMonth()] };
  });
}

/** The compact card of the home in the tour steps. */
function tourCard(l) {
  const photo = l.photos[0] ? imgAttrs(l.photos[0], { sizes: "114px", fallbackAlt: listingName(l) }) : null;
  const price = usd(shownPrice(l));
  const facts = factItems(l);
  return `<div class="rw-tour__card" data-rw-tour-listing="">${photo ? `<img${attrs([["class", "rw-tour__card-img"], ...photo])}>` : `<span class="rw-tour__card-img rw-tour__card-img--empty">${icon("listing-no-image", 32)}</span>`}<div class="rw-tour__card-body">${price ? `<p class="rw-tour__card-price">${esc(price)}</p>` : ""}${facts.length ? `<ul class="rw-tour__card-facts">${facts.map(([k, t]) => `<li class="rw-tour__card-fact">${icon(FACT_ICONS[k], 18)}${esc(t)}</li>`).join("")}</ul>` : ""}${l.address.hidden ? "" : `<p class="rw-tour__card-address">${esc(addressLine(l.address))}</p>`}</div></div>`;
}

/** The day carousel, the times of day and the hint (as the dialog prints them before a pick). */
function tourDateFields(days, hintId, legendId, zone = null) {
  const dayButtons = days.map((d, i) => `<button${attrs([["type", "button"], ["class", "rw-tour__day"], ["aria-pressed", "false"], ["hidden", i >= 7], ["data-rw-day", d.iso]])}><span class="rw-tour__weekday">${d.weekday}</span><span class="rw-tour__date">${d.day}</span><span class="rw-tour__month">${d.month}</span></button>`).join("");
  const parts = PARTS.map(([p, label]) => `<button type="button" class="rw-tour__part" aria-pressed="false" data-rw-part="${p}">${label}</button>`).join("");
  return `<div class="rw-tour__days" data-rw-days="${esc(JSON.stringify(days))}"${zone ? ` data-rw-time-zone="${esc(zone)}"` : ""}><button type="button" class="rw-tour__nav rw-tour__nav--prev" aria-label="${COPY.previousDays}" disabled="" data-rw-days-prev="">${icon("chevron-left", 20)}</button><div class="rw-tour__day-list" role="group" aria-label="${COPY.tourDayLegend}">${dayButtons}</div><button type="button" class="rw-tour__nav rw-tour__nav--next" aria-label="${COPY.nextDays}" data-rw-days-next="">${icon("chevron-right", 20)}</button></div><fieldset class="rw-tour__parts" aria-labelledby="${esc(legendId)}"><legend class="rw-field__label" id="${esc(legendId)}">${COPY.tourTimeLegend}</legend><div class="rw-tour__part-list">${parts}</div></fieldset><p class="rw-form__hint rw-tour__hint" id="${esc(hintId)}" data-rw-tour-hint="">${COPY.pickDay}</p>`;
}

/** The summary after a tour request; the script fills it. */
const tourSuccess = () =>
  `<section class="rw-tour__success" hidden="" data-rw-step="sent" role="status"><span class="rw-tour__check">${icon("check-white", 28)}</span><h3 class="rw-tour__success-title" tabindex="-1">${COPY.tourReceivedTitle}</h3><p class="rw-tour__success-text">${COPY.tourReceivedText}</p><dl class="rw-tour__summary">${[
    ["date", COPY.summaryDate],
    ["time", COPY.summaryTime],
    ["phone", COPY.summaryPhone],
    ["email", COPY.summaryEmail],
  ]
    .map(([k, label]) => `<div class="rw-tour__summary-row" hidden="" data-rw-summary="${k}"><dt>${label}</dt><dd></dd></div>`)
    .join("")}</dl><div class="rw-modal__footer rw-modal__footer--end"><button type="button" class="rw-button" data-rw-done="">${COPY.done}</button></div></section>`;

/** The consent box (your wording) and, with your alerts wording, the alerts box. */
const consentBoxes = (id, consentText, alertsConsentText) =>
  `<div class="rw-modal__consent"><label class="rw-check rw-consent" for="${id}-consent"><input id="${id}-consent" type="checkbox" name="consentContact" aria-labelledby="${id}-consent-text" data-rw-consent="" value="yes"><span id="${id}-consent-text" data-rw-consent-text="">${esc(consentText)}</span></label>${alertsConsentText ? `<label class="rw-check rw-consent" for="${id}-alerts"><input id="${id}-alerts" type="checkbox" name="consentAlerts" aria-labelledby="${id}-alerts-text" value="yes"><span id="${id}-alerts-text">${esc(alertsConsentText)}</span></label>` : ""}</div>`;
const honeypot = (id) => `<div class="rw-hp" aria-hidden="true"><label for="${id}-website">${COPY.honeypot}</label><input id="${id}-website" name="website" type="text" tabindex="-1" autoComplete="off" value=""></div>`;
const statusLine = `<p class="rw-form__status" role="status" aria-live="polite" data-rw-form-status=""></p>`;
const inputField = (id, key, label, input, required) => `<div class="rw-field"><label class="rw-field__label${required ? " rw-field__label--required" : ""}" for="${id}-${key}">${label}</label>${input}</div>`;

/** html/contact-modal.html: the message form, the tour step and the summary. `ids` names the elements. */
export function contactModal(l, { agent = null, action, consentText, alertsConsentText = "", now = new Date(), ids = {} }) {
  const id = ids.contact ?? "contact";
  const message = l.address.hidden ? "I would like more information about this home." : `I would like more information about ${addressLine(l.address)}.`;
  const zone = (l.openHouses ?? []).find((o) => o.timeZone)?.timeZone ?? null;
  const days = tourDays(now, zone);
  const form = `<form class="rw-form rw-modal__form rw-contact__step" method="post" action="${esc(action)}" novalidate="" data-rw-step="form" data-rw-lead="contact" data-rw-success="${COPY.contactSentHeading}" data-rw-lead-listing="${esc(leadListing(l))}"><h3 class="rw-modal__heading">${COPY.contactHeading}</h3><div class="rw-form__row">${inputField(id, "first", COPY.firstName, `<input class="rw-input" id="${id}-first" name="firstName" autoComplete="given-name" required="" maxLength="80" value="">`, true)}${inputField(id, "last", COPY.lastName, `<input class="rw-input" id="${id}-last" name="lastName" autoComplete="family-name" required="" maxLength="80" value="">`, true)}</div>${inputField(id, "email", COPY.email, `<input class="rw-input" id="${id}-email" name="email" type="email" autoComplete="email" required="" maxLength="254" value="">`, true)}${inputField(id, "phone", COPY.phone, `<input class="rw-input" id="${id}-phone" name="phone" type="tel" autoComplete="tel" maxLength="40" value="">`, false)}${inputField(id, "message", COPY.message, `<textarea class="rw-input rw-textarea" id="${id}-message" name="message" rows="4" maxLength="2000">${esc(message)}</textarea>`, false)}${honeypot(id)}${consentBoxes(id, consentText, alertsConsentText)}<div class="rw-modal__footer rw-modal__footer--end"><button class="rw-button" type="submit" disabled="" aria-describedby="${id}-needconsent" data-rw-submit="">${COPY.contactSubmit}</button></div><p class="rw-form__hint" id="${id}-needconsent" data-rw-consent-hint="">${COPY.consentRequired}</p>${statusLine}</form>`;
  const tour = `<section class="rw-contact__step" hidden="" data-rw-step="tour"><div class="rw-modal__intro"><h3 class="rw-modal__heading" tabindex="-1">${COPY.contactSentHeading}</h3><p class="rw-modal__text">${COPY.contactSentText}</p></div>${tourCard(l)}${tourDateFields(days, `${id}-date-hint`, ids.contactLegend ?? `${id}-legend`, zone)}<div class="rw-modal__footer rw-modal__footer--end"><button type="button" class="rw-button" disabled="" aria-describedby="${id}-date-hint" data-rw-tour-submit="">${COPY.tourSubmit}</button></div>${statusLine}</section>`;
  return modal("contact", contactLabel(agent), ids.contactTitle ?? `${id}-title`, `<div class="rw-contact">${form}${tour}${tourSuccess()}</div>`);
}

/** html/tour-modal.html: the date step, the contact form and the summary. `ids` names the elements. */
export function tourModal(l, { action, consentText, alertsConsentText = "", now = new Date(), ids = {} }) {
  const id = ids.tour ?? "tour";
  const zone = (l.openHouses ?? []).find((o) => o.timeZone)?.timeZone ?? null;
  const days = tourDays(now, zone);
  const date = `<section class="rw-tour__step" data-rw-step="date"><div class="rw-modal__intro"><h3 class="rw-modal__heading" tabindex="-1">${COPY.tourHeading}</h3><p class="rw-modal__text">${COPY.tourSubheading}</p></div>${tourCard(l)}${tourDateFields(days, `${id}-date-hint`, ids.tourLegend ?? `${id}-legend`, zone)}<div class="rw-modal__footer rw-modal__footer--end"><button type="button" class="rw-button" disabled="" aria-describedby="${id}-date-hint" data-rw-next="">${COPY.next}</button></div></section>`;
  const info = `<form class="rw-form rw-modal__form rw-tour__step" method="post" action="${esc(action)}" novalidate="" hidden="" data-rw-step="info" data-rw-lead="tour" data-rw-success="${COPY.tourReceivedTitle}" data-rw-lead-listing="${esc(leadListing(l))}"><h3 class="rw-modal__heading" tabindex="-1">${COPY.tourInfoHeading}</h3><input type="hidden" name="tourDate" value=""><input type="hidden" name="tourTime" value="">${inputField(id, "name", COPY.fullName, `<input class="rw-input" id="${id}-name" name="fullName" autoComplete="name" required="" maxLength="160" placeholder="${COPY.fullNamePlaceholder}" value=""><p class="rw-form__hint rw-field__error" id="${id}-name-hint" hidden="" data-rw-name-hint="">${COPY.fullNameHint}</p>`, true)}${inputField(id, "phone", COPY.phone, `<input class="rw-input" id="${id}-phone" name="phone" type="tel" autoComplete="tel" maxLength="40" value="">`, false)}${inputField(id, "email", COPY.email, `<input class="rw-input" id="${id}-email" name="email" type="email" autoComplete="email" required="" maxLength="254" placeholder="${COPY.emailPlaceholder}" value="">`, true)}${honeypot(id)}${consentBoxes(id, consentText, alertsConsentText)}<div class="rw-modal__footer"><button type="button" class="rw-modal__back" data-rw-back="">${icon("chevron-left", 20)}${COPY.backStep}</button><button class="rw-button" type="submit" disabled="" aria-describedby="${id}-needconsent" data-rw-submit="">${COPY.tourSubmit}</button></div><p class="rw-form__hint" id="${id}-needconsent" data-rw-consent-hint="">${COPY.consentRequired}</p>${statusLine}</form>`;
  return modal("tour", COPY.tourTitle, ids.tourTitle ?? `${id}-title`, `<div class="rw-tour">${date}${info}${tourSuccess()}</div>`);
}

// ─── The whole listing page ───────────────────────────────────────────────────

const validCoords = (lat, lng) => finite(lat) && finite(lng) && Math.abs(lat) <= 90 && Math.abs(lng) <= 180 && !(lat === 0 && lng === 0);
const requires = (rules, element, placement) => rules.some((r) => r.element === element && r.placement === placement);

/**
 * html/listing-detail.html: the listing page with every screen. `o`:
 *   backHref     your search page (the header's Back link and X)
 *   agent        your agent or office: { name, brokerage, license, email, phone, photoUrl }
 *   leadAction   your lead route; with consentText it turns on the cards, the bar and the dialogs
 *   consentText, alertsConsentText   your wording beside the boxes
 *   shareUrl     your own URL of this page (the canonical URL); null turns sharing off
 *   googleMapsKey, mapId             your Google Maps browser key and Map ID
 *   apiBaseUrl   where the mortgage calculator asks for figures: your own server route (such as /api/idx)
 *   mortgage     true shows the calculator asking the API itself, from your approved website address,
 *                when you have no server route; false leaves it out. No key goes in the page.
 *   estimate     the first GET /v1/mortgage/estimate answer (data), asked with your secret key; null prints the calculator empty
 *   now          the time the open houses and tour days are read against (default now)
 *   ids          ids unique on the page for each screen (defaults are fine for one listing per page)
 */
export function detail(listing, mls = [], o = {}) {
  const l = listing;
  const name = listingName(l);
  const board = mls.find((m) => m.mlsId === l.mls.id) ?? null;
  const rules = [...(board?.required ?? []), ...(l.compliance?.required ?? [])];
  const tour = safeUrl(l.virtualTourUrl);
  const sections = (l.details ?? []).filter((s) => s.items.length > 0);
  const attributionLine = l.compliance.attributionLine ?? l.attribution.line;
  const courtesyLine = l.compliance.courtesyLine ?? l.attribution.courtesy;
  const courtesyTop = courtesyLine && requires(rules, "courtesy_line", "detail") ? courtesyLine : null;
  const inlineLine = l.description && attributionLine && ["listing_office", "listing_agent", "agent_contact"].some((e) => requires(rules, e, "detail")) ? attributionLine : null;
  const compliance = { ...l.compliance, attributionLine: inlineLine ? null : attributionLine, courtesyLine: courtesyTop ? null : courtesyLine };
  const ids = o.ids ?? {};
  const now = o.now ? new Date(o.now) : new Date();
  const lead = Boolean(o.leadAction) && Boolean(o.consentText);
  const shareUrl = o.shareUrl !== undefined ? o.shareUrl || null : l.head?.canonical || l.href || null;
  const geo = l.geo && validCoords(l.geo.lat, l.geo.lng) ? l.geo : null;
  const located = Boolean(o.googleMapsKey && geo && !l.address.hidden);
  const agent = o.agent ?? null;
  const prefill = mortgagePrefill(l);
  const showMortgage = mortgageShown(l, prefill.price, o);
  const sidebar = o.aside || (lead ? contactCards(agent) : "");
  const bar = !o.aside && lead ? mobileBar(agent) : "";
  const item = ga4Item(l);
  const ga4 = o.ga4 === false ? null : JSON.stringify({ ecommerce: { currency: "USD", ...(item.price !== undefined ? { value: item.price } : {}), items: [item] } });
  const logo = board?.logo && requires(rules, "mls_logo", "detail") ? { url: board.logo.url, alt: board.logo.alt || board.mlsName, width: board.logo.width, height: board.logo.height } : null;
  const description =
    l.description || inlineLine
      ? `<section class="rw-detail__block"><h2 class="rw-detail__title">${COPY.description}</h2>${l.description ? `<p class="rw-detail__description rw-detail__description--clamped" data-rw-description="">${esc(l.description)}</p>` : ""}${tour ? `<p><a class="rw-detail__tour" href="${esc(tour)}" target="_blank" rel="noopener noreferrer">${COPY.virtualTour}</a></p>` : ""}${inlineLine ? `<p class="rw-detail__inline-attribution">${esc(inlineLine)}</p>` : ""}</section>`
      : "";
  const showAgentInfo = Boolean(agent && (cleanText(agent.license) || requires(rules, "agent_contact", "detail")));
  return `<article${attrs([["class", bar ? "rw-recipes rw-detail rw-detail--bar" : "rw-recipes rw-detail"], ["data-rw-detail", l.id], ["data-listing-id", l.id], ["data-status", l.status], ["data-rw-ga4-event", ga4 ? "view_item" : null], ["data-rw-ga4-params", ga4]])}>
    ${detailHeader(l, o.backHref)}
    <div class="rw-detail__content">
      ${photoGrid(l, { streetView: located, share: Boolean(shareUrl), logo })}
      <div class="rw-detail__columns">
        <div class="rw-detail__main">
          ${courtesyTop ? `<p class="rw-detail__courtesy">${esc(courtesyTop)}</p>` : ""}
          ${priceBlock(l)}
          ${description}
          ${showAgentInfo ? agentInfo(agent) : ""}
          ${openHouses(l.openHouses ?? [], { tour: lead, now, listId: ids.openHouses ?? "open-houses" })}
          ${propertyDetails(sections)}
          ${showMortgage ? mortgageCalculator({ baseUrl: o.apiBaseUrl ?? null, prefill, estimate: o.estimate ?? null, id: ids.mortgage ?? "mortgage" }) : ""}
          ${located ? locationMap({ googleMapsKey: o.googleMapsKey, mapId: o.mapId ?? null, lat: geo.lat, lng: geo.lng, priceLabel: usdCompact(shownPrice(l)) || null, address: name }) : ""}
          <section class="rw-detail__block rw-detail__compliance" aria-label="${COPY.listingInformation}">
            ${attribution(compliance, board)}
            ${l.mlsNumber ? `<p class="rw-detail__mlsnumber">${COPY.mlsNumber} ${esc(l.mlsNumber)} (${esc(l.mls.name)})</p>` : ""}
            ${disclaimers(board ? [board] : [], l.compliance.asOf)}
          </section>
        </div>
        ${o.aside ? `<aside class="rw-detail__aside">${o.aside}</aside>` : sidebar ? `<aside class="rw-detail__aside rw-detail__aside--cards">${sidebar}</aside>` : ""}
      </div>
    </div>
    ${bar}
    ${fullGallery(l, { streetView: located, share: Boolean(shareUrl), sidebar, bar, id: ids.gallery ?? "gallery" })}
    ${shareUrl ? shareModal(l, shareUrl, { titleId: ids.shareTitle ?? "share-title", id: ids.share ?? "share" }) : ""}
    ${lead ? contactModal(l, { agent, action: o.leadAction, consentText: o.consentText, alertsConsentText: o.alertsConsentText, now, ids }) + tourModal(l, { action: o.leadAction, consentText: o.consentText, alertsConsentText: o.alertsConsentText, now, ids }) : ""}
  </article>`;
}

/**
 * html/tour-form.html: the tour request form. ruuster-idx.js enables the button once the consent box
 * is checked, and POSTs the LeadSubmission JSON to `action` (your lead route in leads.mjs).
 * `idBase` makes the ids unique on the page.
 */
export function tourForm({ action, listing, consentText, alertsConsentText = "", idBase = "tour-form" }) {
  const id = (s) => `${idBase}-${s}`;
  const message = listing.address.hidden ? "I would like more information about this home." : `I would like more information about ${addressLine(listing.address)}.`;
  const field = (key, label, input) => `<div class="rw-field"><label class="rw-field__label" for="${id(key)}">${label}</label>${input}</div>`;
  const times = `<option value="" selected="">Any time</option><option value="morning">Morning (8 AM to 12 PM)</option><option value="afternoon">Afternoon (12 PM to 4 PM)</option><option value="evening">Evening (4 PM to 8 PM)</option>`;
  const alerts = alertsConsentText
    ? `<label class="rw-check rw-consent" for="${id("alerts")}"><input id="${id("alerts")}" type="checkbox" name="consentAlerts" aria-labelledby="${id("alerts-text")}" value="yes"><span id="${id("alerts-text")}">${esc(alertsConsentText)}</span></label>`
    : "";
  return `<form${attrs([["class", "rw-recipes rw-form rw-form--tour"], ["method", "post"], ["action", action], ["data-rw-lead", "tour"], ["data-rw-success", COPY.tourSuccess], ["data-rw-lead-listing", leadListing(listing)]])}>
      <div class="rw-form__row">${field("first", "First name", `<input class="rw-input" id="${id("first")}" name="firstName" autocomplete="given-name" required="" maxlength="80">`)}${field("last", "Last name", `<input class="rw-input" id="${id("last")}" name="lastName" autocomplete="family-name" required="" maxlength="80">`)}</div>
      ${field("email", "Email", `<input class="rw-input" id="${id("email")}" name="email" type="email" autocomplete="email" required="" maxlength="254">`)}
      ${field("phone", "Phone (optional)", `<input class="rw-input" id="${id("phone")}" name="phone" type="tel" autocomplete="tel" maxlength="40">`)}
      <div class="rw-form__row">${field("date", "Preferred tour date", `<input class="rw-input" id="${id("date")}" name="tourDate" type="date">`)}${field("time", "Preferred time of day", `<select class="rw-select" id="${id("time")}" name="tourTime">${times}</select>`)}</div>
      ${field("message", "Message (optional)", `<textarea class="rw-input rw-textarea" id="${id("message")}" name="message" rows="4" maxlength="2000">${esc(message)}</textarea>`)}
      <div class="rw-hp" aria-hidden="true"><label for="${id("website")}">Leave this field empty</label><input id="${id("website")}" name="website" type="text" tabindex="-1" autocomplete="off" value=""></div>
      <label class="rw-check rw-consent" for="${id("consent")}"><input id="${id("consent")}" type="checkbox" name="consentContact" aria-labelledby="${id("consent-text")}" data-rw-consent="" value="yes"><span id="${id("consent-text")}" data-rw-consent-text="">${esc(consentText)}</span></label>
      ${alerts}
      <button class="rw-button rw-button--block" type="submit" disabled="" aria-describedby="${id("needconsent")}" data-rw-submit="">${COPY.tourSubmit}</button>
      <p class="rw-form__hint" id="${id("needconsent")}" data-rw-consent-hint="">${COPY.consentRequired}</p>
      <p class="rw-form__status" role="status" aria-live="polite" data-rw-form-status=""></p>
    </form>`;
}
```

When you print the JSON yourself, follow [Rendering the JSON yourself](https://help.ruuster.com/idx/guide-render-json-yourself):
it lists what each page must show.

## Single-page apps

A site that renders only in the browser can show listings through your listings route, but search engines
and AI crawlers may not see them, so those pages rarely rank. Server-render at least the listing pages,
the area pages and the first page of search results.
