import { notFound } from "next/navigation";
import BlockRenderer from "@/components/blocks/BlockRenderer";
import SiteChrome from "@/components/layout/SiteChrome";
import { getEntry, getSiteSettings } from "@/lib/api";
import { obj, str, toState } from "@/lib/content";
import type { WebBlock } from "@/lib/types";

export const revalidate = 300;

/** Replace {name} {code} {CODE} {slug} in every string of a block tree. */
function fill<T>(value: T, vars: Record<string, string>): T {
  if (typeof value === "string") {
    let s: string = value;
    for (const [k, v] of Object.entries(vars)) s = s.split(`{${k}}`).join(v);
    return s as unknown as T;
  }
  if (Array.isArray(value)) return value.map((v) => fill(v, vars)) as unknown as T;
  if (value && typeof value === "object") {
    return Object.fromEntries(Object.entries(value as Record<string, unknown>).map(([k, v]) => [k, fill(v, vars)])) as T;
  }
  return value;
}

export async function generateMetadata({ params }: { params: { slug: string } }) {
  const e = await getEntry("states", params.slug);
  return e ? { title: `${e.title} CON Notices` } : {};
}

/**
 * A page for any state in the CMS "states" collection. The layout is a block
 * template in theme_json.stateTemplate ({ open: [...], soon: [...] }) with
 * {name}/{code}/{CODE}/{slug} placeholders, so every state gets a consistent
 * page, and opening a new state is just flipping its status in the CMS. A
 * state with its own hand-built CMS page (e.g. South Carolina) links there
 * from the states collection instead.
 */
export default async function StatePage({ params }: { params: { slug: string } }) {
  const [entry, site] = await Promise.all([getEntry("states", params.slug), getSiteSettings()]);
  if (!entry) notFound();
  const s = toState(entry);
  const tpl = obj(site.theme, "stateTemplate");
  const raw = tpl[s.status];
  const blocks = Array.isArray(raw) ? (raw as WebBlock[]) : [];
  const vars = { name: s.name, code: s.code, CODE: s.code.toUpperCase(), slug: s.slug, subtitle: s.subtitle };
  return (
    <SiteChrome slug="state" cssScope={str(site.theme, "stateCssScope", "south-carolina")} edition={{ stateName: s.name, stateCode: s.code }}>
      <BlockRenderer blocks={fill(blocks, vars)} />
    </SiteChrome>
  );
}
