import { getEntries, getSiteSettings } from "@/lib/api";
import { formatDate, list, obj, sortStates, str, toNotice, toState } from "@/lib/content";
import { noticeDay } from "@/components/notices/NoticeCard";
import Masthead from "./Masthead";
import SiteNav from "./SiteNav";
import Footer from "./Footer";

/**
 * Page frame: banner, nav, masthead + ticker (home only by default), footer.
 * `cssScope` picks the page-specific styles in globals.css (".pg-<scope>"),
 * which carry over each source page's own look. Everything visible here is
 * read from the CMS site settings (dim_web_sites + theme_json + navigation).
 */
const strMap = (o: Record<string, unknown>) => Object.fromEntries(Object.entries(o).map(([k, v]) => [k, String(v)]));

export default async function SiteChrome({
  slug,
  cssScope,
  edition,
  children
}: {
  slug: string;
  cssScope: string;
  /** A state page: show the masthead as that state's statewide edition. */
  edition?: { stateName: string; stateCode: string };
  children: React.ReactNode;
}) {
  const site = await getSiteSettings();
  const t = site.theme;
  const bannerBySlug = obj(t, "bannerBySlug");
  const banner = str(bannerBySlug, slug) || str(t, "bannerHtml");
  const minimal = list(t, "minimalChromeSlugs").includes(slug);

  if (minimal) {
    const footerHtml = str(obj(t, "minimalFooterBySlug"), slug);
    return (
      <div className={`pg pg-${cssScope}`}>
        {banner && <div className="prototype-banner" dangerouslySetInnerHTML={{ __html: banner }} />}
        {children}
        {footerHtml && <footer dangerouslySetInnerHTML={{ __html: footerHtml }} />}
      </div>
    );
  }

  const states = sortStates((await getEntries(str(t, "statesCollection", "states"))).map(toState));

  // Ticker: the latest published notices, newest first (this state's only on
  // a state page), e.g. "South Carolina · Chester · LarCare Inc. · Notice No.
  // 00001 · Nov 12, 2026". Falls back to the theme's ticker text.
  let tickerItems = "";
  if (str(t, "tickerSource") === "notices") {
    const all = (await getEntries("notices"))
      .map((e) => ({ n: toNotice(e), city: str(e.fields, "city") }))
      .filter(({ n }) => !n.isSample && n.status !== "scheduled" && (!edition || n.stateCode === edition.stateCode))
      .sort((a, b) => (noticeDay(b.n) + b.n.noticeNumber).localeCompare(noticeDay(a.n) + a.n.noticeNumber))
      .slice(0, Number(str(t, "tickerLimit", "10")) || 10);
    const tpl = str(t, "tickerItemTemplate", "{state} · {city} · {company} · Notice No. {number} · {date}");
    tickerItems = all
      .map(({ n, city }) =>
        tpl
          .split("{state}").join(n.stateName || n.stateCode.toUpperCase())
          .split("{city}").join(city || n.county.replace(/\s+County$/i, ""))
          .split("{company}").join(n.organization)
          .split("{number}").join(n.noticeNumber)
          .split("{date}").join(formatDate(noticeDay(n)))
          .replace(/(\s·\s)+/g, " · ")
          .replace(/^\s·\s|\s·\s$/g, "")
      )
      .join(str(t, "tickerSeparator", "     |     "));
  }
  const mastheadSlugs = list(t, "mastheadSlugs");
  const showMasthead = !!edition || (mastheadSlugs.length ? mastheadSlugs.includes(slug) : slug === "home");
  const ctaLabel = str(t, "navCtaLabel");
  const ctaHref = str(t, "navCtaHref");

  return (
    <div className={`pg pg-${cssScope}`}>
      <a className="skip-link" href="#main">
        Skip to main content
      </a>
      {banner && <div className="prototype-banner" dangerouslySetInnerHTML={{ __html: banner }} />}
      <SiteNav
        brand={site.companyName}
        logoUrl={str(t, "logoUrl") || undefined}
        links={site.primaryNav}
        cta={ctaLabel && ctaHref ? { label: ctaLabel, href: ctaHref } : null}
        states={states}
        statePickerHref={str(t, "statePickerHref", "/states")}
        stateSearchPlaceholder={str(t, "stateSearchPlaceholder", "Search states…")}
        allStatesLabel={str(t, "statePickerAllLabel", "All states & territories")}
        compactBrand={showMasthead}
      />
      {showMasthead && (
        <Masthead
          title={site.companyName}
          tagline={str(t, "mastheadTagline") || site.tagline}
          taglineByState={strMap(obj(t, "mastheadTaglineByState"))}
          editionEpoch={str(t, "editionEpoch")}
          issueLabel={str(t, "mastheadIssueLabel")}
          centerLabel={str(t, "mastheadCenterLabel")}
          editionLabel={str(t, "mastheadEditionLabel")}
          editionByState={strMap(obj(t, "mastheadEditionByState"))}
          stateName={edition?.stateName}
          stateCode={edition?.stateCode}
          stateEditionTemplate={str(t, "stateEditionLabel", "{name} Statewide Edition")}
          stateTaglineTemplate={str(t, "stateMastheadTagline")}
          tickerLabel={str(t, "tickerLabel")}
          tickerText={tickerItems || (edition ? str(t, "stateTickerText") : str(t, "tickerText"))}
          logoUrl={str(t, "logoUrl") || undefined}
        />
      )}
      <main id="main" tabIndex={-1}>
        {children}
      </main>
      <Footer site={site} />
    </div>
  );
}
