/**
 * Apex stub homepage — one per dealer-facing apex domain.
 * Public URL is the apex root (/); proxy rewrites to /home/[domainSlug].
 * Direct /home/* hits on production 308 to / (proxy).
 *
 * The four apexes render four structurally different layouts (hero
 * composition, trust treatment, region treatment, section order) keyed
 * by `apex.layout` — Google flags duplicate layouts, not just duplicate
 * content. Copy stays config-driven in lib/apex-config.ts.
 *
 * Visual system mirrors the dealer landing-page template
 * (app/dealer-template.css): white/#f0f0f0 surfaces, #093b66 navy
 * headings, #f8981d orange pill CTAs with black text, #c6c6c6-bordered
 * rounded-lg cards. One PrimaryCta, one SecondaryCta, one Eyebrow, and
 * one region-tile shape feed all four layouts; the layouts differ by
 * composition and section order, not by restyled primitives.
 */
import type { Metadata } from 'next';
import type { ReactNode } from 'react';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { APEX_CONFIGS, getApexBySlug, type ApexConfig, type ApexLayout } from '@/lib/apex-config';
import { getDealersForApex, groupDealersByRegion } from '@/lib/dealer-directory';
import { ApexHeader } from '@/components/apex/ApexHeader';
import { ApexFooter } from '@/components/apex/ApexFooter';

// Daily: the stub is mostly static marketing copy. Its dealer-derived bits
// (region band counts + spotlight) can lag reality by up to a day, which is
// acceptable — the /dealers directory is the fresh surface (revalidate 3600).
export const revalidate = 86400;
export const dynamic = 'force-static';
export const dynamicParams = false; // only the four configured apexes exist

export async function generateStaticParams() {
  return Object.keys(APEX_CONFIGS).map((domainSlug) => ({ domainSlug }));
}

interface Props {
  params: Promise<{ domainSlug: string }>;
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { domainSlug } = await params;
  const apex = getApexBySlug(domainSlug);
  if (!apex) return {};
  const sibling = APEX_CONFIGS[apex.hreflangSiblingSlug];
  const origin = `https://${apex.hostname}`;
  const [usUrl, caUrl] =
    apex.country === 'US'
      ? [origin, `https://${sibling.hostname}`]
      : [`https://${sibling.hostname}`, origin];
  return {
    title: apex.meta.title,
    description: apex.meta.description,
    alternates: {
      canonical: origin,
      languages: { 'en-US': usUrl, 'en-CA': caUrl },
    },
    openGraph: {
      type: 'website',
      url: origin,
      siteName: apex.siteName,
      title: apex.meta.title,
      description: apex.meta.description,
      images: [`${origin}/media/amsoil-logo.png`],
    },
    twitter: {
      card: 'summary_large_image',
      title: apex.meta.title,
      description: apex.meta.description,
    },
  };
}

function buildJsonLd(apex: NonNullable<ReturnType<typeof getApexBySlug>>) {
  const origin = `https://${apex.hostname}`;
  return {
    '@context': 'https://schema.org',
    '@graph': [
      {
        '@type': 'WebSite',
        '@id': `${origin}/#website`,
        url: origin,
        name: apex.siteName,
        description: apex.meta.description,
      },
      {
        '@type': 'Organization',
        '@id': `${origin}/#organization`,
        name: apex.siteName,
        url: origin,
      },
    ],
  };
}

/* ---------------------------------------------------------------- */
/* Shared building blocks (dealer-template idioms)                   */
/* ---------------------------------------------------------------- */

/** Dealer-template region tile: white card, #c6c6c6 border, navy text. */
const REGION_TILE_CLASSES =
  'block h-full rounded-lg border border-[#c6c6c6] bg-white p-3 text-center text-sm font-semibold text-[#093b66] transition-colors hover:border-[#f8981d] hover:text-[#0d5a99] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#093b66]';

/** Dealer-template section heading: navy, bold, uppercase. */
const SECTION_HEADING_CLASSES =
  'text-xl font-bold uppercase tracking-tight text-[#093b66] md:text-2xl';

/** "1 dealer" vs "N dealers" — singular when a region has exactly one. */
export const dealerCountLabel = (n: number) => `${n} ${n === 1 ? 'dealer' : 'dealers'}`;

/**
 * Primary consumer CTA — the dealer template's .cta-button: AMSOIL
 * orange pill, black uppercase text (≈9.5:1), darker orange on hover.
 */
function PrimaryCta({
  href,
  className = '',
  children,
}: {
  href: string;
  className?: string;
  children: ReactNode;
}) {
  return (
    <Link
      href={href}
      className={`inline-flex items-center justify-center rounded-full bg-[#f8981d] px-8 py-3.5 text-sm font-bold uppercase tracking-[0.08em] text-black transition-colors hover:bg-[#d67800] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#093b66] ${className}`}
    >
      {children}
    </Link>
  );
}

/**
 * Secondary CTA — the ONE outline-pill button used for every "See all" /
 * jump link across all four layouts. Never filled (that is PrimaryCta's job).
 * tone="dark" inverts it for navy bands.
 */
function SecondaryCta({
  href,
  tone = 'light',
  className = '',
  children,
}: {
  href: string;
  tone?: 'light' | 'dark';
  className?: string;
  children: ReactNode;
}) {
  const tones = {
    light:
      'border-[#093b66] text-[#093b66] hover:bg-[#093b66] hover:text-white focus-visible:outline-[#093b66]',
    dark: 'border-white text-white hover:bg-white hover:text-[#093b66] focus-visible:outline-[#f8981d]',
  };
  return (
    <Link
      href={href}
      className={`inline-flex items-center justify-center rounded-full border px-6 py-2.5 text-sm font-semibold uppercase transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 ${tones[tone]} ${className}`}
    >
      {children}
    </Link>
  );
}

/**
 * Eyebrow — the ONE kicker treatment: short orange bar + uppercase label.
 * tone="dark" for navy bands; center centers it. (Replaces the per-layout
 * navy-pill / double-bar variants.)
 */
function Eyebrow({
  children,
  tone = 'light',
  center = false,
}: {
  children: ReactNode;
  tone?: 'light' | 'dark';
  center?: boolean;
}) {
  return (
    <p
      className={`flex items-center gap-3 text-sm font-bold uppercase tracking-[0.18em] ${
        center ? 'justify-center' : ''
      } ${tone === 'dark' ? 'text-white' : 'text-[#093b66]'}`}
    >
      <span aria-hidden className="h-1 w-8 rounded-full bg-[#f8981d]" />
      {children}
    </p>
  );
}

/** Dealer-recruitment band — dealer template's navy band (.preferred-customer) with orange CTA. */
function SignupBand({
  apex,
  className = 'pb-16 md:pb-20',
}: {
  apex: ApexConfig;
  className?: string;
}) {
  return (
    <section className={`px-4 sm:px-6 ${className}`}>
      <div className="mx-auto flex max-w-5xl flex-col items-center justify-between gap-5 rounded-lg bg-gradient-to-br from-[#093b66] to-[#0a4a7a] p-6 md:flex-row md:p-8">
        <p className="text-center md:text-left">
          <strong className="text-white">{apex.signupBand.title}</strong>{' '}
          <span className="text-white/85">{apex.signupBand.body}</span>
        </p>
        <PrimaryCta href="https://amsoil.aimclear.com/" className="shrink-0">
          {apex.signupBand.cta}
        </PrimaryCta>
      </div>
    </section>
  );
}

/**
 * A region tile in the stub preview. `href` points to the region's own page
 * when it clears the page threshold, otherwise to its anchor on the hub — so
 * the preview is never an empty band for a domain that has any dealers.
 */
interface PreviewRegion {
  name: string;
  slug: string;
  count: number;
  href: string;
}

interface LayoutProps {
  apex: ApexConfig;
  topRegions: PreviewRegion[];
  totalDealers: number;
  totalRegions: number;
  regionNounPlural: string;
}

/**
 * Marketing surfaces show an approximate dealer count ("650+"), not the
 * exact total (owner preference: don't publish a precise network size).
 * The directory hub keeps exact counts; there the list itself is the number.
 */
function approxDealerCount(n: number): string {
  if (n >= 100) return `${Math.floor(n / 50) * 50}+`;
  if (n >= 20) return `${Math.floor(n / 10) * 10}+`;
  return String(n);
}

/** 3-step ordering explainer (config-driven, distinct copy per domain). */
function HowItWorksBand({
  apex,
  className = 'pb-12 md:pb-16',
}: {
  apex: ApexConfig;
  className?: string;
}) {
  return (
    <section className={`px-4 sm:px-6 ${className}`}>
      <div className="mx-auto max-w-5xl">
        <h2 className={`mb-4 md:mb-6 ${SECTION_HEADING_CLASSES}`}>{apex.howItWorks.title}</h2>
        <ol className="grid grid-cols-1 gap-4 md:grid-cols-3 md:gap-6">
          {apex.howItWorks.steps.map((step, i) => (
            <li key={step.title} className="rounded-lg border border-[#c6c6c6] bg-white p-6">
              <span
                aria-hidden
                className="flex h-8 w-8 items-center justify-center rounded-full bg-[#093b66] text-sm font-bold text-white"
              >
                {i + 1}
              </span>
              <h3 className="mt-3 text-base font-bold tracking-tight text-[#093b66]">
                {step.title}
              </h3>
              <p className="mt-1.5 text-sm leading-relaxed text-[#1a1a1a]">{step.body}</p>
            </li>
          ))}
        </ol>
      </div>
    </section>
  );
}

/** Gating-objection Q&A band (no-membership, warranty, why-a-dealer). */
function StraightAnswersBand({
  apex,
  className = 'pb-12 md:pb-16',
}: {
  apex: ApexConfig;
  className?: string;
}) {
  return (
    <section className={`px-4 sm:px-6 ${className}`}>
      <div className="mx-auto max-w-5xl rounded-lg border border-[#c6c6c6] bg-[#f0f0f0] p-6 md:p-8">
        <h2 className={SECTION_HEADING_CLASSES}>Straight answers</h2>
        <div className="mt-4 grid grid-cols-1 gap-5 md:mt-6 md:grid-cols-3 md:gap-8">
          {apex.straightAnswers.map((qa) => (
            <div key={qa.q}>
              <h3 className="text-base font-bold tracking-tight text-[#093b66]">{qa.q}</h3>
              <p className="mt-1.5 text-sm leading-relaxed text-[#1a1a1a]">{qa.a}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------------------------------------------------------- */
/* relationship — myamsoil.com: local/relationship-led.              */
/* Split hero (copy left, region rail right) → stacked trust rows →  */
/* signup.                                                           */
/* ---------------------------------------------------------------- */
function RelationshipLayout({ apex, topRegions, regionNounPlural }: LayoutProps) {
  return (
    <>
      <section className="px-4 pb-12 pt-10 sm:px-6 md:pb-16 md:pt-16">
        <div className="mx-auto grid max-w-6xl items-start gap-8 lg:grid-cols-[1.2fr_minmax(300px,0.8fr)] lg:gap-12">
          <div className="max-w-2xl lg:pt-4">
            <Eyebrow>{apex.hero.eyebrow}</Eyebrow>
            <h1 className="mt-4 text-balance text-3xl font-extrabold uppercase leading-tight tracking-tight text-[#093b66] sm:text-4xl md:text-5xl md:leading-[1.05]">
              {apex.hero.title}
            </h1>
            <p className="mt-5 max-w-xl text-base text-[#1a1a1a] md:text-lg">
              {apex.hero.subtitle}
            </p>
            <PrimaryCta href="/dealers" className="mt-8">
              {apex.hero.cta}
            </PrimaryCta>
          </div>
          <div className="rounded-lg border border-[#c6c6c6] bg-[#f0f0f0] p-5 sm:p-6">
            <h2 className="text-base font-bold uppercase tracking-tight text-[#093b66]">
              {apex.regionBandTitle}
            </h2>
            <ul className="mt-3 divide-y divide-[#d1d1d1]">
              {topRegions.map((r) => (
                <li key={r.slug}>
                  <Link
                    href={r.href}
                    className="group flex items-center justify-between gap-3 py-2.5 text-sm font-semibold text-[#093b66] transition-colors hover:text-[#0d5a99] focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-[#093b66]"
                  >
                    <span className="group-hover:underline">{r.name}</span>
                    <span className="text-sm font-normal text-[#595959]">
                      {dealerCountLabel(r.count)}
                    </span>
                  </Link>
                </li>
              ))}
            </ul>
            <SecondaryCta href="/dealers" className="mt-4 w-full">
              See all {regionNounPlural}
            </SecondaryCta>
          </div>
        </div>
      </section>

      <section className="px-4 pb-12 sm:px-6 md:pb-16">
        <div className="mx-auto max-w-4xl space-y-4 md:space-y-5">
          {apex.trustCards.map((card, i) => (
            <div
              key={card.title}
              className="grid grid-cols-[auto_1fr] gap-4 rounded-lg border border-[#c6c6c6] bg-[#f0f0f0] p-5 sm:gap-6 sm:p-6"
            >
              <span aria-hidden className="mt-1 text-sm font-black tabular-nums text-[#093b66]">
                {String(i + 1).padStart(2, '0')}
              </span>
              <div>
                <h2 className="text-lg font-bold tracking-tight text-[#093b66]">{card.title}</h2>
                <p className="mt-1.5 text-sm leading-relaxed text-[#1a1a1a]">{card.body}</p>
              </div>
            </div>
          ))}
        </div>
      </section>

      <HowItWorksBand apex={apex} />
      <StraightAnswersBand apex={apex} />
      <SignupBand apex={apex} />
    </>
  );
}

/* ---------------------------------------------------------------- */
/* catalog — shopamsoil.com: product/commerce-led.                   */
/* Open banner hero + brand keyline → segmented trust panel →        */
/* region chip cloud → signup.                                       */
/* ---------------------------------------------------------------- */
function CatalogLayout({
  apex,
  topRegions,
  totalDealers,
  totalRegions,
  regionNounPlural,
}: LayoutProps) {
  return (
    <>
      <section className="px-4 pb-10 pt-12 sm:px-6 md:pb-14 md:pt-20">
        <div className="mx-auto max-w-6xl">
          <Eyebrow>{apex.hero.eyebrow}</Eyebrow>
          <h1 className="mt-5 max-w-4xl text-balance text-4xl font-extrabold uppercase leading-tight tracking-tight text-[#093b66] sm:text-5xl md:text-6xl md:leading-[1.02]">
            {apex.hero.title}
          </h1>
          <p className="mt-5 max-w-2xl text-base text-[#1a1a1a] md:text-lg">{apex.hero.subtitle}</p>
          <div className="mt-8 flex flex-wrap items-center gap-x-5 gap-y-3">
            <PrimaryCta href="/dealers">{apex.hero.cta}</PrimaryCta>
            <p className="text-sm text-[#595959]">
              {approxDealerCount(totalDealers)} dealers in {totalRegions}{' '}
              {totalRegions === 1 ? regionNounPlural.replace(/s$/, '') : regionNounPlural}
            </p>
          </div>
        </div>
      </section>

      <div aria-hidden className="mx-auto max-w-6xl px-4 sm:px-6">
        <div className="h-1 rounded-full bg-[#f8981d]" />
      </div>

      <section className="px-4 py-10 sm:px-6 md:py-14">
        <div className="mx-auto grid max-w-6xl grid-cols-1 divide-y divide-[#c6c6c6] overflow-hidden rounded-lg border border-[#c6c6c6] bg-[#f0f0f0] md:grid-cols-3 md:divide-x md:divide-y-0">
          {apex.trustCards.map((card, i) => (
            <div key={card.title} className="p-6 md:p-8">
              <span aria-hidden className="text-sm font-black tracking-[0.2em] text-[#093b66]">
                {String(i + 1).padStart(2, '0')}
              </span>
              <h2 className="mt-3 text-lg font-bold tracking-tight text-[#093b66]">{card.title}</h2>
              <p className="mt-2 text-sm leading-relaxed text-[#1a1a1a]">{card.body}</p>
            </div>
          ))}
        </div>
      </section>

      {topRegions.length > 0 && (
        <section className="px-4 pb-12 sm:px-6 md:pb-16">
          <div className="mx-auto max-w-6xl">
            <h2 className={`mb-4 md:mb-6 ${SECTION_HEADING_CLASSES}`}>{apex.regionBandTitle}</h2>
            <ul className="flex flex-wrap gap-2 sm:gap-2.5">
              {topRegions.map((r) => (
                <li key={r.slug}>
                  <Link
                    href={r.href}
                    className="inline-flex items-baseline gap-1.5 rounded-lg border border-[#c6c6c6] bg-white px-4 py-2 text-sm font-semibold text-[#093b66] transition-colors hover:border-[#f8981d] hover:text-[#0d5a99] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#093b66]"
                  >
                    {r.name}
                    <span className="text-sm font-normal text-[#757575]">{r.count}</span>
                  </Link>
                </li>
              ))}
            </ul>
            <SecondaryCta href="/dealers" className="mt-5">
              See all {regionNounPlural}
            </SecondaryCta>
          </div>
        </section>
      )}

      <StraightAnswersBand apex={apex} />
      <HowItWorksBand apex={apex} />
      <SignupBand apex={apex} />
    </>
  );
}

/* ---------------------------------------------------------------- */
/* coverage — myamsoil.ca: Canada-wide coverage-led.                 */
/* Centered navy hero card (dealer .contact band idiom) → prominent  */
/* two-column region block (before trust) → 3-col trust grid →       */
/* signup.                                                           */
/* ---------------------------------------------------------------- */
function CoverageLayout({
  apex,
  topRegions,
  totalDealers,
  totalRegions,
  regionNounPlural,
}: LayoutProps) {
  return (
    <>
      <section className="px-4 pb-10 pt-12 text-center sm:px-6 md:pb-14 md:pt-20">
        <div className="mx-auto max-w-3xl rounded-lg bg-gradient-to-br from-[#093b66] to-[#0a4a7a] p-8 sm:p-12 md:p-14">
          <Eyebrow tone="dark" center>
            {apex.hero.eyebrow}
          </Eyebrow>
          <h1 className="mt-4 text-balance text-3xl font-extrabold uppercase leading-tight tracking-tight text-white sm:text-4xl md:text-5xl md:leading-[1.05]">
            {apex.hero.title}
          </h1>
          <p className="mx-auto mt-5 max-w-xl text-base text-white/85 md:text-lg">
            {apex.hero.subtitle}
          </p>
          <PrimaryCta href="/dealers" className="mt-8">
            {apex.hero.cta}
          </PrimaryCta>
        </div>
      </section>

      {topRegions.length > 0 && (
        <section className="px-4 pb-12 sm:px-6 md:pb-16">
          <div className="mx-auto grid max-w-6xl gap-6 lg:grid-cols-[minmax(260px,0.55fr)_1.45fr] lg:items-start lg:gap-8">
            <div className="rounded-lg bg-[#093b66] p-6 md:p-7">
              <h2 className="text-xl font-bold uppercase tracking-tight text-white md:text-2xl">
                {apex.regionBandTitle}
              </h2>
              <p className="mt-3 text-sm leading-relaxed text-white/85">
                {approxDealerCount(totalDealers)} independent dealers across {totalRegions}{' '}
                {totalRegions === 1 ? regionNounPlural.replace(/s$/, '') : regionNounPlural}.
              </p>
              <SecondaryCta href="/dealers" tone="dark" className="mt-5">
                See all {regionNounPlural}
              </SecondaryCta>
            </div>
            <ul className="grid grid-cols-2 gap-2 sm:grid-cols-3 sm:gap-3">
              {topRegions.map((r) => (
                <li key={r.slug}>
                  <Link href={r.href} className={REGION_TILE_CLASSES}>
                    {r.name}
                    <span className="mt-0.5 block text-sm font-normal text-[#757575]">
                      {dealerCountLabel(r.count)}
                    </span>
                  </Link>
                </li>
              ))}
            </ul>
          </div>
        </section>
      )}

      <HowItWorksBand apex={apex} />

      <section className="px-4 pb-12 sm:px-6 md:pb-16">
        <div className="mx-auto grid max-w-5xl grid-cols-1 gap-4 md:grid-cols-3 md:gap-6">
          {apex.trustCards.map((card) => (
            <div
              key={card.title}
              className="rounded-lg border border-[#c6c6c6] bg-[#f0f0f0] p-6 md:p-7"
            >
              <span aria-hidden className="mb-4 block h-1 w-10 rounded-full bg-[#f8981d]" />
              <h2 className="text-lg font-bold tracking-tight text-[#093b66]">{card.title}</h2>
              <p className="mt-2 text-sm leading-relaxed text-[#1a1a1a]">{card.body}</p>
            </div>
          ))}
        </div>
      </section>

      <StraightAnswersBand apex={apex} />
      <SignupBand apex={apex} />
    </>
  );
}

/* ---------------------------------------------------------------- */
/* outfitter — shopamsoil.ca: Canadian commerce.                     */
/* Compact dual-CTA hero → wide region tiles → signup mid-page →     */
/* 2-col trust grid.                                                 */
/* ---------------------------------------------------------------- */
function OutfitterLayout({ apex, topRegions, regionNounPlural }: LayoutProps) {
  return (
    <>
      <section className="px-4 pb-10 pt-12 text-center sm:px-6 md:pb-12 md:pt-16">
        <div className="mx-auto max-w-2xl">
          <Eyebrow center>{apex.hero.eyebrow}</Eyebrow>
          <h1 className="mt-4 text-balance text-3xl font-extrabold uppercase leading-tight tracking-tight text-[#093b66] sm:text-4xl md:text-5xl">
            {apex.hero.title}
          </h1>
          <p className="mx-auto mt-5 max-w-xl text-base text-[#1a1a1a] md:text-lg">
            {apex.hero.subtitle}
          </p>
          <div className="mt-8 flex flex-col items-center justify-center gap-3 sm:flex-row sm:gap-4">
            <PrimaryCta href="/dealers">{apex.hero.cta}</PrimaryCta>
            {topRegions.length > 0 && (
              <SecondaryCta href="#regions">{apex.regionBandTitle}</SecondaryCta>
            )}
          </div>
        </div>
      </section>

      {topRegions.length > 0 && (
        <section id="regions" className="scroll-mt-24 px-4 pb-12 sm:px-6 md:pb-14">
          <div className="mx-auto max-w-6xl">
            <h2 className={`mb-4 md:mb-6 ${SECTION_HEADING_CLASSES}`}>{apex.regionBandTitle}</h2>
            <ul className="grid grid-cols-1 gap-2 sm:grid-cols-2 sm:gap-3 lg:grid-cols-4">
              {topRegions.map((r) => (
                <li key={r.slug}>
                  <Link
                    href={r.href}
                    className="flex h-full items-center justify-between gap-3 rounded-lg border border-[#c6c6c6] bg-white px-4 py-3 text-sm font-semibold text-[#093b66] transition-colors hover:border-[#f8981d] hover:text-[#0d5a99] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#093b66]"
                  >
                    <span>{r.name}</span>
                    <span className="text-sm font-normal text-[#757575]">
                      {dealerCountLabel(r.count)}
                    </span>
                  </Link>
                </li>
              ))}
            </ul>
            <SecondaryCta href="/dealers" className="mt-5">
              See all {regionNounPlural}
            </SecondaryCta>
          </div>
        </section>
      )}

      <SignupBand apex={apex} className="pb-12 md:pb-14" />

      <section className="px-4 pb-16 sm:px-6 md:pb-20">
        <div className="mx-auto grid max-w-5xl grid-cols-1 gap-4 md:grid-cols-2 md:gap-6">
          {apex.trustCards.map((card, i) => (
            <div
              key={card.title}
              className={`rounded-lg border border-[#c6c6c6] bg-[#f0f0f0] p-6 md:p-7 ${
                i === 2 ? 'md:col-span-2' : ''
              }`}
            >
              <span aria-hidden className="mb-4 block h-1 w-10 rounded-full bg-[#f8981d]" />
              <h2 className="text-lg font-bold tracking-tight text-[#093b66]">{card.title}</h2>
              <p className="mt-2 text-sm leading-relaxed text-[#1a1a1a]">{card.body}</p>
            </div>
          ))}
        </div>
      </section>

      <StraightAnswersBand apex={apex} />
      <HowItWorksBand apex={apex} className="pb-16 md:pb-20" />
    </>
  );
}

const LAYOUTS: Record<ApexLayout, (props: LayoutProps) => ReactNode> = {
  relationship: RelationshipLayout,
  catalog: CatalogLayout,
  coverage: CoverageLayout,
  outfitter: OutfitterLayout,
};

/** Region count shown per layout variant (rail vs chips vs grids). */
const REGION_COUNT: Record<ApexLayout, number> = {
  relationship: 6,
  catalog: 10,
  coverage: 9,
  outfitter: 7,
};

export default async function ApexStubPage({ params }: Props) {
  const { domainSlug } = await params;
  const apex = getApexBySlug(domainSlug);
  if (!apex) notFound();

  const dealers = await getDealersForApex(apex.domainPrefix, apex.domain);
  const grouped = groupDealersByRegion(dealers, apex.country);
  const pagedSlugs = new Set(grouped.paged.map((g) => g.region.slug));
  const topRegions: PreviewRegion[] = [...grouped.paged, ...grouped.inline]
    .sort((a, b) => b.count - a.count)
    .slice(0, REGION_COUNT[apex.layout])
    .map((g) => ({
      name: g.region.name,
      slug: g.region.slug,
      count: g.count,
      // Paged regions have their own page; smaller ones live inline on the hub.
      href: pagedSlugs.has(g.region.slug)
        ? `/dealers/${g.region.slug}`
        : `/dealers#${g.region.slug}`,
    }));

  // Count only dealers that resolve to a domestic region, so the hero
  // ("N dealers across M states/provinces") reconciles with the region
  // cards. Cross-border (foreign) and blank/unresolvable-region (other)
  // dealers still appear in the full /dealers directory, but counting
  // them here would overstate the per-region total shown on the stub.
  const totalDealers = [...grouped.paged, ...grouped.inline].reduce((sum, g) => sum + g.count, 0);

  const Layout = LAYOUTS[apex.layout];
  const layoutProps: LayoutProps = {
    apex,
    topRegions,
    totalDealers,
    totalRegions: grouped.paged.length + grouped.inline.length,
    regionNounPlural: apex.country === 'US' ? 'states' : 'provinces',
  };

  return (
    <div className="min-h-screen bg-white text-[#1a1a1a]">
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(buildJsonLd(apex)) }}
      />
      <ApexHeader apex={apex} />
      <main id="main">
        <Layout {...layoutProps} />
      </main>
      <ApexFooter apex={apex} />
      {/* GA4 is rendered once by the route layout (app/home/[domainSlug]/layout.tsx);
          rendering it here too would double-count every pageview. */}
    </div>
  );
}
