/**
 * Single source of truth for "what is this store called?" — the twin of
 * `resolve-currency.ts` / `use-currency.ts`, and the ONLY file that carries
 * the name the scaffolder knew at generation time.
 *
 * The chain, strongest first:
 *   1. `storeInfo.name` — live, from `/api/vc/<id>/info`. Server components
 *      and `generateMetadata` get it from `fetchStoreInfo()`; client
 *      components from `useStoreInfo()`. Always right, and free wherever the
 *      layout already fetched it.
 *   2. `process.env.NEXT_PUBLIC_STORE_NAME` — written to `.env.local` by
 *      `npm run setup` (which `npm run connect` runs for you) and inlined at
 *      BUILD time. It is what the client bundle carries before the live data
 *      arrives, and what a page renders when the API is unreachable. Refresh
 *      it with `npm run setup`, then rebuild.
 *   3. `SCAFFOLD_STORE_NAME` — the literal below, baked when the project was
 *      generated. Under `--defer-connection` the scaffolder knew no store, so
 *      this is just the project directory name: a placeholder, never a brand.
 *      It must never be the only source anywhere (it once was, and a Hebrew
 *      sports store went live titled "storefront").
 *
 * ⛔ No imports here, on purpose: this file is used by server components,
 * `generateMetadata`, route handlers, the OG image and `'use client'` hooks
 * alike, so it must never pull in `next/headers` or React.
 */

/** The name the scaffolder knew — see (3) above. Rendered by the scaffolder
 *  as a complete JS string literal (`storeNameJs`), so quotes, backticks and
 *  `</script>` inside a real store name are already escaped here; every
 *  consumer still escapes for ITS context (React text, JSON-LD, `<title>`). */
export const SCAFFOLD_STORE_NAME: string = <%- storeNameJs %>;

/**
 * Resolve the display name for this store.
 *
 * @param storeInfo result of `fetchStoreInfo()` / `useStoreInfo()` — may be
 *                  null when the fetch failed or has not resolved yet
 * @param override  pass when the caller already has a more specific name
 *                  (a sales-channel label, an order's captured store name)
 */
export function resolveStoreName(
  storeInfo: { name?: string | null } | null | undefined,
  override?: string | null
): string {
  return (
    override?.trim() ||
    storeInfo?.name?.trim() ||
    process.env.NEXT_PUBLIC_STORE_NAME?.trim() ||
    SCAFFOLD_STORE_NAME
  );
}

/** `<title>` template for pages that set their own title: "Page | Store". */
export function buildTitleTemplate(storeName: string): string {
  return `%s | ${storeName}`;
}
