import Link from "next/link";
import type { Entry, WebBlock } from "@/lib/types";
import { getEntries, getFormSchema, getSiteSettings } from "@/lib/api";
import { bool, list, obj, sortStates, str, toNotice, toState } from "@/lib/content";
import NoticeCard, { DEFAULT_NOTICE_LABELS, type NoticeCardLabels } from "@/components/notices/NoticeCard";
import StateSelectorHero from "@/components/widgets/StateSelectorHero";
import HeroSearch from "@/components/widgets/HeroSearch";
import { NoticeDirectory, RecentNotices, type DirectoryLabels } from "@/components/widgets/NoticeFilters";
import StatesGrid, { type StatesGridText } from "@/components/widgets/StatesGrid";
import ConProfileSection, { DEFAULT_CON_LABELS, type ConLabels } from "@/components/widgets/ConProfileSection";
import RequirementsRegister, { type RegisterText } from "@/components/widgets/RequirementsRegister";
import FaqList from "@/components/widgets/FaqList";
import WaitlistForm, { type WaitlistText } from "@/components/widgets/WaitlistForm";
import SubscribeForm from "@/components/widgets/SubscribeForm";
import CardForm from "@/components/widgets/CardForm";
import SubmitWizard, { type StateRule, type WizardConfig } from "@/components/widgets/SubmitWizard";
import PortalCard from "@/components/widgets/PortalCard";
import type { FieldExtras } from "@/components/widgets/SchemaFields";
import { NamedIcon } from "@/components/icons";
import { COMIC_ART } from "@/components/widgets/comicArt";
import { BannerHospital, BannerNotice, COMIC_STRIP_ART } from "@/components/widgets/ComicStripArt";
import ComicPlayer from "@/components/widgets/ComicPlayer";
import TypewriterText from "@/components/widgets/TypewriterText";
import { longDay, paperDay, volumeLabel, volumeOf } from "@/lib/editions";
import TypewriterSheet from "@/components/notices/TypewriterSheet";

/**
 * Renders a CMS page's block tree (dim_web_pages.layout_json) in the
 * MyStateCONNews design. Only block types Aggie's Page Builder knows are used
 * (hero, richText, numberedGrid, pillarGrid, pricedGrid, flatList,
 * faqAccordion, ctaBanner, formEmbed, columns, button, spacer, image); a
 * `variant` prop picks which of this site's looks a block takes.
 *
 * Repeating content (notices, states, steps, pricing, requirements, FAQs...)
 * lives in CMS collections and is referenced by `collectionKey`, so adding a
 * notice or opening a state is a data change in Aggie, never a code change.
 *
 * Consecutive blocks with `layout: "main"` share one `.main-content` wrapper,
 * matching the source pages' centred content column.
 *
 * Front page (broadsheet) props: `look: "broadsheet"` renders a section as a
 * newspaper section (kicker, serif title, italic deck); `tone` picks its
 * background ("alt" or "dark"); `ruleBefore: "thick"` draws the heavy column
 * rule above a block.
 */
type P = Record<string, unknown>;

const html = (s: string) => ({ __html: s });

/** A newspaper section flag across the top of a section: "Section B", the
 *  section's name, the paper's name, today's date and the page ("B1").
 *  The letter and page come from a CSS counter, so sections are lettered
 *  in page order (the front page above them is Section A). Decorative:
 *  the section's own heading is what screen readers get. */
/** A section's name from its own HTML: its kicker label, else its first heading. */
function folioFromHtml(body: string): string {
  const label = /class="section-label"[^>]*>([\s\S]*?)<\/div>/.exec(body);
  if (label) return label[1]!;
  const h2 = /<h2[^>]*>([\s\S]*?)<\/h2>/.exec(body);
  return h2 ? h2[1]! : "";
}

function Folio({ name }: { name: string }) {
  const label = name.replace(/<[^>]*>/g, "").replace(/&amp;/g, "&").replace(/&nbsp;/g, " ").trim();
  if (!label) return null;
  return (
    <div className="np-folio" aria-hidden="true">
      <span className="np-folio-sec" />
      <span className="np-folio-name">{label}</span>
      <span className="np-folio-meta">
        <span className="np-folio-paper">mystateCONnews</span>
        <span className="np-folio-date">{longDay(paperDay(new Date()))}</span>
        <span className="np-folio-page" />
      </span>
    </div>
  );
}

function Section({
  p,
  children,
  light
}: {
  p: P;
  children?: React.ReactNode;
  light?: boolean;
}) {
  const eyebrow = str(p, "eyebrow");
  const heading = str(p, "heading");
  const description = str(p, "description");
  const sectionClass = str(p, "sectionClass");
  const anchor = str(p, "anchor");
  if (str(p, "look") === "broadsheet") {
    const tone = str(p, "tone");
    return (
      <div className={`broadsheet-section${tone ? ` ${tone}-bg` : ""}`} id={anchor || undefined}>
        <Folio name={eyebrow || heading} />
        <div className="broadsheet-body">
          {(eyebrow || heading || description) && (
            <div className="section-masthead">
              {eyebrow && <div className="section-kicker">{eyebrow}</div>}
              {heading && <h2 className="section-title-serif" dangerouslySetInnerHTML={html(heading)} />}
              {description && <p className="section-deck">{description}</p>}
            </div>
          )}
          {children}
        </div>
      </div>
    );
  }
  return (
    <section className={`section${sectionClass ? " " + sectionClass : ""}`} id={anchor || undefined}>
      <Folio name={eyebrow || heading} />
      <div className="container">
        {eyebrow && (
          <div className="section-label" style={light ? { color: "var(--gold)" } : undefined}>
            {eyebrow}
          </div>
        )}
        {heading && <h2 className={`section-title${light ? " light" : ""}`}>{heading}</h2>}
        {description && <p className={`section-subtitle${light ? " light" : ""}`}>{description}</p>}
        {children}
      </div>
    </section>
  );
}

function Alert({ kind, body, style }: { kind: string; body: string; style?: React.CSSProperties }) {
  if (!body) return null;
  return (
    <div className={`alert alert-${kind === "info" ? "info" : "warning"}`} style={style}>
      <span />
      <div dangerouslySetInnerHTML={html(body)} />
    </div>
  );
}

function strMap(o: P, key: string): Record<string, string> {
  return Object.fromEntries(Object.entries(obj(o, key)).map(([k, v]) => [k, String(v)]));
}

function rowsProp(p: P): string[][] {
  const r = p.rows;
  return Array.isArray(r) ? r.filter(Array.isArray).map((x) => (x as unknown[]).map(String)) : [];
}

function extrasProp(p: P): FieldExtras {
  return { placeholders: strMap(p, "placeholders"), hints: strMap(p, "hints") };
}

function waitlistText(p: P, fallbackSource: string): WaitlistText {
  return {
    emailPlaceholder: str(p, "emailPlaceholder", "Your email address"),
    statePlaceholder: str(p, "statePlaceholder", "Your state"),
    submitLabel: str(p, "submitLabel", "Join Waitlist"),
    successText: str(p, "successText", "You're on the list!"),
    source: str(p, "source", fallbackSource)
  };
}

function noticeLabels(p: P, theme: P = {}): NoticeCardLabels {
  return {
    sampleBadge: str(p, "sampleBadge", DEFAULT_NOTICE_LABELS.sampleBadge),
    numberPrefix: str(p, "numberPrefix", DEFAULT_NOTICE_LABELS.numberPrefix),
    published: str(p, "publishedLabel", DEFAULT_NOTICE_LABELS.published),
    scheduled: str(p, "scheduledLabel", DEFAULT_NOTICE_LABELS.scheduled),
    volumeTemplate: str(theme, "volumeLabel", DEFAULT_NOTICE_LABELS.volumeTemplate),
    editionEpoch: str(theme, "editionEpoch", DEFAULT_NOTICE_LABELS.editionEpoch),
    readLabel: str(p, "readLabel", DEFAULT_NOTICE_LABELS.readLabel)
  };
}

function ButtonLink({
  label,
  href,
  className,
  style,
  icon
}: {
  label: string;
  href: string;
  className: string;
  style?: React.CSSProperties;
  icon?: string;
}) {
  if (!label || !href) return null;
  const external = /^https?:\/\//.test(href);
  const body = (
    <>
      {icon && <NamedIcon name={icon} size={16} strokeWidth={2.5} />}
      {label}
    </>
  );
  return external ? (
    <a href={href} className={className} style={style}>
      {body}
    </a>
  ) : (
    <Link href={href} className={className} style={style}>
      {body}
    </Link>
  );
}

// ─── hero ────────────────────────────────────────────────────────────────────

async function Hero({ p }: { p: P }) {
  const variant = str(p, "variant", "page");
  const heading = str(p, "heading");
  const sub = str(p, "subheading");
  const cta = { label: str(p, "ctaLabel"), href: str(p, "ctaHref") };
  const second = { label: str(p, "secondaryLabel"), href: str(p, "secondaryHref") };

  if (variant === "front") {
    // The headline (and deck) typed slowly on paper coming out of a vintage
    // typewriter on the left; the "Place a Notice" ear with the buttons on
    // the right.
    const facts = list(p, "earFacts").map(String).filter(Boolean);
    return (
      <div className="broadsheet-body">
        <div className="front-page-hero front-hero-split">
          <div className="hero-headline-block">
            {str(p, "kicker") && (
              <div className="hero-kicker">
                <NamedIcon name={str(p, "kickerIcon", "newspaper")} size={18} />
                {str(p, "kicker")}
              </div>
            )}
            <TypewriterSheet className="hero-typewriter" speedMs={Number(str(p, "typeSpeedMs", "70"))} startDelayMs={900}>
              <h2 className="hero-main-headline">
                {heading}
                {str(p, "headingAccent") && (
                  <>
                    <br />
                    <em>{str(p, "headingAccent")}</em>
                  </>
                )}
              </h2>
              {sub && <p className="hero-typed-deck">{sub.replace(/<[^>]+>/g, "")}</p>}
            </TypewriterSheet>
          </div>
          <aside className="hero-ear" aria-label={str(p, "earKicker", "Place a Notice")}>
            {str(p, "earKicker") && <div className="hero-ear-kicker">{str(p, "earKicker")}</div>}
            {str(p, "earHeading") && <h3 className="hero-ear-heading">{str(p, "earHeading")}</h3>}
            {str(p, "earText") && <p className="hero-ear-text">{str(p, "earText")}</p>}
            <div className="hero-ear-actions">
              <ButtonLink {...cta} className="btn-primary" icon={str(p, "ctaIcon")} />
              <ButtonLink {...second} className="btn-outline" icon={str(p, "secondaryIcon")} />
            </div>
            {facts.length > 0 && (
              <ul className="hero-ear-facts">
                {facts.map((x) => (
                  <li key={x}>{x}</li>
                ))}
              </ul>
            )}
          </aside>
        </div>
      </div>
    );
  }

  if (variant === "home") {
    const sel = obj(p, "stateSelector");
    const states = Object.keys(sel).length ? sortStates((await getEntries(str(sel, "collectionKey", "states"))).map(toState)) : [];
    const accent = str(p, "headingAccent");
    return (
      <section className="hero">
        <h1>
          {heading}
          {accent && (
            <>
              <br />
              <span>{accent}</span>
            </>
          )}
        </h1>
        {sub && <p dangerouslySetInnerHTML={html(sub)} />}
        <div className="hero-actions">
          <ButtonLink {...cta} className="btn-primary" />
          <ButtonLink {...second} className="btn-outline" />
        </div>
        {states.length > 0 && (
          <StateSelectorHero
            states={states}
            heading={str(sel, "heading", "Pick Your State")}
            description={str(sel, "description")}
            placeholder={str(sel, "placeholder", "Select a state or territory")}
            goLabel={str(sel, "goLabel", "Go")}
            soonGroupLabel={str(sel, "soonGroupLabel", "Coming Soon")}
            openSuffix={str(sel, "openSuffix", " (Open)")}
            defaultNoteHtml={str(sel, "defaultNoteHtml")}
            openNoteTemplate={str(sel, "openNoteTemplate", "<strong>{name}</strong> is open and accepting submissions now.")}
            soonNoteTemplate={str(sel, "soonNoteTemplate", "<strong>{name}</strong> is coming soon.")}
            pickFirstMessage={str(sel, "pickFirstMessage", "Please select a state first.")}
          />
        )}
      </section>
    );
  }

  const breadcrumb = Array.isArray(p.breadcrumb) ? (p.breadcrumb as P[]) : [];
  const badge = str(p, "badgeHtml");
  const search = str(p, "searchPlaceholder");
  const inner = (
    <>
      {breadcrumb.length > 0 && (
        <div className="breadcrumb">
          {breadcrumb.map((b, i) => {
            const label = str(b, "label");
            const href = str(b, "href");
            return (
              <span key={i} style={{ display: "contents" }}>
                {i > 0 && <span>/</span>}
                {href ? <Link href={href}>{label}</Link> : label}
              </span>
            );
          })}
        </div>
      )}
      {badge && <div className={`state-badge${str(p, "badgeClass") ? " " + str(p, "badgeClass") : ""}`} dangerouslySetInnerHTML={html(badge)} />}
      <h1>{heading}</h1>
      {sub && <p dangerouslySetInnerHTML={html(sub)} />}
      {search && <HeroSearch placeholder={search} eventName="msc:state-search" />}
    </>
  );
  // The right side of a page headline: a newspaper "ear" with today's
  // edition and the page's buttons (theme.pageHeroEar sets its words).
  const theme = (await getSiteSettings()).theme as P;
  const earCfg = obj(theme, "pageHeroEar");
  const today = paperDay(new Date());
  const vol = volumeOf(today, str(theme, "editionEpoch", "2026-11-12"));
  const ear = (
    <aside className="page-hero-ear" aria-label={str(earCfg, "kicker", "Today's Edition")}>
      <div className="hero-ear-kicker">{str(earCfg, "kicker", "Today's Edition")}</div>
      <div className="phe-date">{longDay(today)}</div>
      {vol && <div className="phe-no">{volumeLabel(str(theme, "mastheadIssueLabel", "No. {n}"), vol)}</div>}
      {str(earCfg, "text") && <p className="phe-text">{str(earCfg, "text")}</p>}
      {(cta.label || second.label) && (
        <div className="hero-ear-actions">
          <ButtonLink {...cta} className="btn-primary" />
          <ButtonLink {...second} className="btn-outline" />
        </div>
      )}
    </aside>
  );
  const body = (
    <div className="page-hero-split">
      <div className="page-hero-main">{inner}</div>
      {ear}
    </div>
  );
  return <section className="page-hero">{bool(p, "inner") ? <div className="hero-inner">{body}</div> : body}</section>;
}

// ─── numberedGrid ────────────────────────────────────────────────────────────

async function NumberedGrid({ p }: { p: P }) {
  const entries = await getEntries(str(p, "collectionKey"));
  if (str(p, "variant") === "timeline") {
    return (
      <section className={`section ${str(p, "sectionClass", "section-alt")}`}>
        <Folio name={str(p, "eyebrow") || str(p, "heading")} />
        <div className="container">
          {str(p, "eyebrow") && <div className="section-label">{str(p, "eyebrow")}</div>}
          {str(p, "heading") && <h2 className="section-title">{str(p, "heading")}</h2>}
          {str(p, "description") && <p style={{ color: "var(--gray-600)", marginBottom: 48, lineHeight: 1.65 }}>{str(p, "description")}</p>}
          {entries.map((e) => {
            const f = e.fields;
            const flow = list(f, "statusFlow");
            const active = str(f, "activeStatus");
            const checklist = list(f, "fieldList");
            const note = str(f, "note");
            return (
              <div className="step-row" key={e.slug}>
                <div className="step-num-big">{str(f, "number")}</div>
                <div className="step-content">
                  <h3>{e.title}</h3>
                  <p>{str(f, "description")}</p>
                  {checklist.length > 0 && (
                    <div className="step-fields">
                      <ul>
                        {checklist.map((c) => (
                          <li key={c}>{c}</li>
                        ))}
                      </ul>
                    </div>
                  )}
                  {flow.length > 0 && (
                    <div className="status-flow">
                      {flow.map((s, i) => (
                        <span key={s} style={{ display: "contents" }}>
                          {i > 0 && (
                            <span className="status-arrow">
                              <NamedIcon name="chevron-right" size={14} />
                            </span>
                          )}
                          <span className={`status-pill${s === active ? " active" : ""}`}>{s}</span>
                        </span>
                      ))}
                    </div>
                  )}
                  <Alert kind={str(f, "noteType", "info")} body={note} style={flow.length ? { marginTop: 16 } : undefined} />
                </div>
              </div>
            );
          })}
        </div>
      </section>
    );
  }
  return (
    <Section p={{ sectionClass: "section-alt", ...p }}>
      <div className="steps-grid">
        {entries.map((e) => (
          <div className="step-card" key={e.slug}>
            <div className="step-num">{str(e.fields, "number")}</div>
            <div className="step-icon-wrap">
              <NamedIcon name={str(e.fields, "icon")} />
            </div>
            <h3>{e.title}</h3>
            <p>{str(e.fields, "description")}</p>
          </div>
        ))}
      </div>
    </Section>
  );
}

// ─── pillarGrid ──────────────────────────────────────────────────────────────

async function PillarGrid({ p }: { p: P }) {
  const offset = Number(str(p, "offset", "0")) || 0;
  const limit = Number(str(p, "limit", "0")) || 0;
  const all = await getEntries(str(p, "collectionKey"));
  const entries = limit > 0 ? all.slice(offset, offset + limit) : all.slice(offset);
  const variant = str(p, "variant", "features");
  const desc = (e: Entry) => str(e.fields, "description");

  if (variant === "comic") {
    return <ComicStrip p={p} entries={entries} />;
  }
  if (variant === "stack") {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: Number(str(p, "gapPx", "16")) }}>
        {entries.map((e) => (
          <div className="feature-card" key={e.slug}>
            <div className="feature-icon">
              <NamedIcon name={str(e.fields, "icon")} />
            </div>
            <div>
              <h4>{e.title}</h4>
              <p dangerouslySetInnerHTML={html(desc(e))} />
            </div>
          </div>
        ))}
      </div>
    );
  }
  if (variant === "trust") {
    return (
      <Section p={{ sectionClass: "section-navy", ...p }} light>
        <div className="trust-grid">
          {entries.map((e) => (
            <div className="trust-item" key={e.slug}>
              {str(p, "look") === "broadsheet" ? (
                <div className="trust-icon">
                  <NamedIcon name={str(e.fields, "icon")} />
                </div>
              ) : (
                <span className="trust-icon">{str(e.fields, "icon")}</span>
              )}
              <h4>{e.title}</h4>
              <p dangerouslySetInnerHTML={html(desc(e))} />
            </div>
          ))}
        </div>
      </Section>
    );
  }
  if (variant === "included") {
    return (
      <div>
        {str(p, "eyebrow") && (
          <div className="section-label" style={{ marginTop: 0 }}>
            {str(p, "eyebrow")}
          </div>
        )}
        {str(p, "heading") && (
          <h3 style={{ fontFamily: "'Playfair Display',serif", color: "var(--navy)", fontSize: "1.3rem", marginBottom: 20 }}>{str(p, "heading")}</h3>
        )}
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {entries.map((e) => (
            <div
              key={e.slug}
              style={{
                display: "flex",
                gap: 14,
                alignItems: "flex-start",
                padding: 16,
                background: "white",
                borderRadius: "var(--radius-lg)",
                border: "1px solid var(--gray-200)",
                boxShadow: "var(--shadow)"
              }}
            >
              <div style={{ fontSize: "1.5rem" }}>{str(e.fields, "icon")}</div>
              <div>
                <div style={{ fontWeight: 700, color: "var(--navy)", marginBottom: 4, fontSize: ".9rem" }}>{e.title}</div>
                <div style={{ fontSize: ".82rem", color: "var(--gray-600)" }} dangerouslySetInnerHTML={html(desc(e))} />
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }
  return (
    <Section p={p}>
      <div className="features-grid">
        {entries.map((e) => (
          <div className="feature-card" key={e.slug}>
            <div className="feature-icon">
              <NamedIcon name={str(e.fields, "icon")} />
            </div>
            <div>
              <h4>{e.title}</h4>
              <p dangerouslySetInnerHTML={html(desc(e))} />
            </div>
          </div>
        ))}
      </div>
    </Section>
  );
}

// ─── comic strip (pillarGrid variant "comic") ───────────────────────────────

/** "The CON Chronicle Comics": a strip of panels from a collection (fields:
 *  speech, caption, tone = "" | "crimson" | "success", art = a COMIC_ART key). */
function ComicStrip({ p, entries }: { p: P; entries: Entry[] }) {
  return (
    <section className="comics-section">
      <Folio name={str(p, "eyebrow") || str(p, "heading")} />
      <div className="comics-header">
        {str(p, "eyebrow") && <div className="section-kicker">{str(p, "eyebrow")}</div>}
        {str(p, "heading") && <div className="comics-banner" dangerouslySetInnerHTML={html(str(p, "heading"))} />}
        {str(p, "description") && <p className="comics-intro">{str(p, "description")}</p>}
      </div>
      <div className="comic-strip-wrapper pc-strip">
        {/* Title banner, like a Sunday strip's: the hospital, the title, the public notice. */}
        {(str(p, "stripTitle") || str(p, "stripSubtitle")) && (
          <div className="pc-banner">
            <span className="pc-banner-art" aria-hidden="true"><BannerHospital /></span>
            <div className="pc-banner-titles">
              {str(p, "stripTitle") && <h3 className="pc-title">{str(p, "stripTitle")}</h3>}
              {str(p, "stripSubtitle") && <div className="pc-subtitle">{str(p, "stripSubtitle")}</div>}
            </div>
            <span className="pc-banner-art" aria-hidden="true"><BannerNotice /></span>
          </div>
        )}
        <ComicPlayer replayLabel={str(p, "replayLabel", "Read it again")}>
          <ol className="cs-panels">
            {entries.map((e, i) => {
              const tone = str(e.fields, "tone");
              const Art = COMIC_STRIP_ART[str(e.fields, "art")];
              const legacy = !Art ? COMIC_ART[str(e.fields, "art")] : "";
              const speech = str(e.fields, "speech");
              const bubbleAt = str(e.fields, "bubble", "right");
              return (
                <li className={`cs-panel${tone ? " cs-tone-" + tone : ""}`} key={e.slug} style={{ "--i": i } as React.CSSProperties}>
                  <span className="sr-only">{e.title}. </span>
                  <div className="cs-art">
                    <span className="cs-art-img" aria-hidden="true">
                      {Art ? <Art /> : legacy ? <span className="panel-illustration" dangerouslySetInnerHTML={html(legacy)} /> : null}
                    </span>
                    {speech && (
                      <div className={`cs-bubble cs-bubble-${bubbleAt}${tone === "thought" ? " is-thought" : ""}`}>
                        {speech}
                        {tone === "thought" && <span className="cs-thought-dots" aria-hidden="true"><i /><i /></span>}
                      </div>
                    )}
                  </div>
                  {str(e.fields, "caption") && <p className="cs-caption">{str(e.fields, "caption")}</p>}
                </li>
              );
            })}
          </ol>
        </ComicPlayer>
      </div>
      {str(p, "disclaimer") && <p className="comics-disclaimer">{str(p, "disclaimer")}</p>}
    </section>
  );
}

// ─── pricedGrid ──────────────────────────────────────────────────────────────

async function PricedGrid({ p }: { p: P }) {
  const entries = await getEntries(str(p, "collectionKey"));
  if (str(p, "variant") === "table") {
    const code = str(p, "stateCode");
    const rows = entries.filter((e) => !code || str(e.fields, "stateCode").toLowerCase() === code);
    return (
      <>
        {str(p, "eyebrow") && (
          <div className="section-label" style={{ marginTop: 36 }}>
            {str(p, "eyebrow")}
          </div>
        )}
        {str(p, "heading") && (
          <h3 style={{ fontFamily: "'Playfair Display',serif", color: "var(--navy)", fontSize: "1.4rem", marginBottom: 16 }}>{str(p, "heading")}</h3>
        )}
        <Alert kind="info" body={str(p, "alertHtml")} />
        <table className="pricing-table">
          <thead>
            <tr>
              <th>{str(p, "colService", "Service")}</th>
              <th>
                {str(p, "colRate", "Proposed Rate")} {str(p, "badge") && <span className="estimate-badge">{str(p, "badge")}</span>}
              </th>
            </tr>
          </thead>
          <tbody>
            {rows.map((e) => (
              <tr key={e.slug}>
                <td>{e.title}</td>
                <td>{str(e.fields, "rate")}</td>
              </tr>
            ))}
          </tbody>
        </table>
        {str(p, "viewAllLabel") && (
          <div style={{ marginTop: 16 }}>
            <ButtonLink
              label={str(p, "viewAllLabel")}
              href={str(p, "viewAllHref")}
              className="btn-primary"
              style={{ background: "var(--navy)", color: "white", fontSize: ".875rem", padding: "10px 20px" }}
            />
          </div>
        )}
      </>
    );
  }
  return (
    <>
      {str(p, "eyebrow") && <div className="section-label">{str(p, "eyebrow")}</div>}
      {str(p, "heading") && <h2 className="section-title">{str(p, "heading")}</h2>}
      <div className="pricing-grid">
        {entries.map((e) => (
          <div className={`price-card${bool(e.fields, "featured") ? " featured" : ""}`} key={e.slug}>
            <div className="price-icon">{str(e.fields, "icon")}</div>
            <div className="price-title">{e.title}</div>
            <div className="price-range">{str(e.fields, "price")}</div>
            <div className="price-unit">{str(e.fields, "unit")}</div>
            <ul className="price-features">
              {list(e.fields, "features").map((x) => (
                <li key={x}>{x}</li>
              ))}
            </ul>
            {str(e.fields, "note") && <span className="estimate-note">{str(e.fields, "note")}</span>}
          </div>
        ))}
      </div>
    </>
  );
}

// ─── flatList ────────────────────────────────────────────────────────────────

async function FlatList({ p }: { p: P }) {
  const variant = str(p, "variant", "recent");
  const key = str(p, "collectionKey");

  if (variant === "recent" || variant === "directory" || variant === "state-notices") {
    let notices = (await getEntries(key || "notices")).map(toNotice);
    const code = str(p, "stateCode");
    if (code) notices = notices.filter((n) => n.stateCode === code);
    const limit = Number(str(p, "limit", "0"));
    if (limit > 0) notices = notices.slice(0, limit);
    const labels = noticeLabels(p, (await getSiteSettings()).theme);

    if (variant === "directory") {
      const d: DirectoryLabels = {
        panelHeading: str(p, "panelHeading", "Filter Notices"),
        search: str(p, "searchLabel", "Search"),
        searchPlaceholder: str(p, "searchPlaceholder", "Organization, county…"),
        state: str(p, "stateLabel", "State"),
        allStates: str(p, "allStatesLabel", "All States"),
        county: str(p, "countyLabel", "County"),
        allCounties: str(p, "allCountiesLabel", "All Counties"),
        facility: str(p, "facilityLabel", "Facility Type"),
        allFacilities: str(p, "allFacilitiesLabel", "All Types"),
        status: str(p, "statusLabel", "Status"),
        allStatuses: str(p, "allStatusesLabel", "All Statuses"),
        clear: str(p, "clearLabel", "x Clear Filters"),
        showing: str(p, "showingTemplate", "Showing {count} notices"),
        showingOne: str(p, "showingOneTemplate", "Showing {count} notice"),
        noResults: str(p, "noResultsText", "No notices match your filters."),
        clearInline: str(p, "clearInlineLabel", "Clear filters")
      };
      const allStates = sortStates((await getEntries(str(p, "statesCollection", "states"))).map(toState));
      return (
        <NoticeDirectory
          notices={notices}
          labels={d}
          cardLabels={labels}
          stateOptions={allStates.map((s) => ({ value: s.code, label: s.name }))}
        />
      );
    }

    if (variant === "state-notices" && str(p, "look") === "broadsheet") {
      return (
        <Section p={p}>
          <div className="notice-cascade">
            {notices.map((n) => (
              <NoticeCard key={n.slug} notice={n} look="state" labels={labels} />
            ))}
          </div>
          {notices.length === 0 && <div className="no-results msc-empty">{str(p, "emptyText", "No notices have been published for this state yet.")}</div>}
          {str(p, "ctaLabel") && (
            <div style={{ textAlign: "center", marginTop: 28 }}>
              <ButtonLink label={str(p, "ctaLabel")} href={str(p, "ctaHref")} className="btn-primary" icon={str(p, "ctaIcon")} />
            </div>
          )}
        </Section>
      );
    }

    if (variant === "state-notices") {
      return (
        <>
          <div className="section-label" id={str(p, "anchor") || undefined} style={{ marginTop: Number(str(p, "marginTop", "40")) }}>
            {str(p, "eyebrow")}
          </div>
          <h3 style={{ fontFamily: "'Playfair Display',serif", color: "var(--navy)", fontSize: "1.4rem", marginBottom: 16 }}>{str(p, "heading")}</h3>
          {str(p, "description") && <p style={{ color: "var(--gray-600)", fontSize: ".875rem", marginBottom: 20 }}>{str(p, "description")}</p>}
          <div className="notice-cascade">
            {notices.map((n) => (
              <NoticeCard key={n.slug} notice={n} look="state" labels={labels} />
            ))}
          </div>
          {notices.length === 0 && (
            <div className="no-results msc-empty" style={{ marginBottom: 24 }}>
              {str(p, "emptyText", "No notices have been published for this state yet.")}
            </div>
          )}
        </>
      );
    }

    // recent (home)
    const states = sortStates((await getEntries(str(p, "statesCollection", "states"))).map(toState));
    const filterCodes = list(p, "filterStates");
    // Every state and territory unless the block limits it with filterStates.
    const stateOptions = filterCodes.length
      ? filterCodes.map((c) => ({ value: c, label: states.find((s) => s.code === c)?.name || c.toUpperCase() }))
      : states.map((s) => ({ value: s.code, label: s.name }));
    return (
      <Section p={{ sectionClass: "section-alt", ...p }}>
        <RecentNotices
          notices={notices}
          labels={labels}
          filterLabel={str(p, "filterLabel", "Filter by State:")}
          allStatesLabel={str(p, "allStatesLabel", "All States")}
          stateOptions={stateOptions}
          emptyText={str(p, "emptyText", "No notices have been published yet.")}
        />
        {str(p, "viewAllLabel") && (
          <div style={{ textAlign: "center", marginTop: 28 }}>
            <ButtonLink
              label={str(p, "viewAllLabel")}
              href={str(p, "viewAllHref")}
              className="btn-primary"
              icon={str(p, "viewAllIcon")}
              style={str(p, "look") === "broadsheet" ? undefined : { background: "var(--navy)", color: "white" }}
            />
          </div>
        )}
      </Section>
    );
  }

  if (variant === "state-con") {
    // One state's CON requirements (statewide edition pages).
    const code = str(p, "stateCode");
    const state = sortStates((await getEntries(key || "states")).map(toState)).find((x) => x.code === code);
    if (!state) return null;
    const L = obj(p, "labels");
    const labels: ConLabels = {
      ...DEFAULT_CON_LABELS,
      ...(Object.fromEntries(Object.entries(L).filter(([, v]) => typeof v === "string")) as Partial<ConLabels>),
      status: { ...DEFAULT_CON_LABELS.status, ...(obj(L, "status") as Partial<ConLabels["status"]>) },
      confidence: { ...DEFAULT_CON_LABELS.confidence, ...(obj(L, "confidence") as Record<string, string>) },
      noticeByValue: { ...DEFAULT_CON_LABELS.noticeByValue, ...(obj(L, "noticeByValue") as Record<string, string>) }
    };
    return (
      <Section p={p}>
        <ConProfileSection name={state.name} con={state.con} labels={labels} />
      </Section>
    );
  }

  if (variant === "state-picker") {
    const states = sortStates((await getEntries(key || "states")).map(toState));
    return (
      <StateSelectorHero
        look="box"
        states={states}
        heading={str(p, "heading", "Select Your State")}
        description={str(p, "description")}
        placeholder={str(p, "placeholder", "Select a state or territory")}
        goLabel={str(p, "goLabel", "Go to State")}
        soonGroupLabel={str(p, "soonGroupLabel", "Coming Soon")}
        groupLabels={strMap(p, "groupLabels")}
        openSuffix={str(p, "openSuffix", " (Open)")}
        defaultNoteHtml={str(p, "defaultNoteHtml")}
        openNoteTemplate={str(p, "openNoteTemplate", "<strong>{name}</strong> is open and accepting submissions now.")}
        soonNoteTemplate={str(p, "soonNoteTemplate", "<strong>{name}</strong> is coming soon.")}
        pickFirstMessage={str(p, "pickFirstMessage", "Please select a state first.")}
      />
    );
  }

  if (variant === "states") {
    const states = sortStates((await getEntries(key || "states")).map(toState));
    const t: StatesGridText = {
      openEyebrow: str(p, "openEyebrow", "Open Now"),
      openHeading: str(p, "openHeading", "Open States"),
      soonEyebrow: str(p, "soonEyebrow", "Coming Soon"),
      soonHeading: str(p, "soonHeading", "All States & Territories"),
      soonSubtitle: str(p, "soonSubtitle", "Research in progress"),
      joinLabel: str(p, "joinLabel", "Join waitlist"),
      soonPill: str(p, "soonPill", "Soon"),
      openPill: str(p, "openPill", "Open"),
      noResults: str(p, "noResultsText", "No states match your search."),
      modalTitle: str(p, "modalTitle", "{name}: Coming Soon"),
      modalText: str(p, "modalText", "{name} is not yet open."),
      modalSubmit: str(p, "modalSubmitLabel", "Notify Me When It Opens"),
      modalSuccess: str(p, "modalSuccessText", "You're on the list!")
    };
    return (
      <StatesGrid
        states={states}
        text={t}
        formKey={str(p, "formKey", "waitlist")}
        waitlist={waitlistText(obj(p, "waitlist"), "States page")}
      />
    );
  }

  if (variant === "register" || variant === "state-requirements") {
    const [stateEntries, reqEntries, questionEntries, sourceEntries] = await Promise.all([
      getEntries(str(p, "statesCollection", "states")),
      getEntries(key || "requirements"),
      getEntries(str(p, "questionsCollection", "open-questions")),
      getEntries(str(p, "sourcesCollection", "official-sources"))
    ]);
    const code = str(p, "stateCode", "sc");

    if (variant === "state-requirements") {
      const rows = reqEntries.filter((e) => str(e.fields, "stateCode").toLowerCase() === code && str(e.fields, "statePageLabel"));
      const qs = questionEntries.filter((e) => str(e.fields, "stateCode").toLowerCase() === code && str(e.fields, "statePageText"));
      return (
        <>
          {str(p, "eyebrow") && <div className="section-label">{str(p, "eyebrow")}</div>}
          {str(p, "heading") && <h2 className="section-title">{str(p, "heading")}</h2>}
          <Alert kind="warning" body={str(p, "alertHtml")} />
          {rows.length > 0 && (
            <div className="card">
              <h3>{str(p, "cardHeading", "Governing Law")}</h3>
              {rows.map((e) => (
                <div className="req-row" key={e.slug}>
                  <div className={`req-status ${str(e.fields, "status", "open")}`}>{str(e.fields, "statusLabel")}</div>
                  <div>
                    <div className="req-label">{str(e.fields, "statePageLabel")}</div>
                    <div className="req-detail">{str(e.fields, "statePageDetail")}</div>
                  </div>
                </div>
              ))}
            </div>
          )}
          {qs.length > 0 && (
            <div className="gap-checklist">
              <h4>{str(p, "questionsHeading")}</h4>
              {qs.map((e) => (
                <div className="gap-item" key={e.slug}>
                  <span className="check-icon">?</span> {str(e.fields, "statePageText")}
                </div>
              ))}
            </div>
          )}
        </>
      );
    }

    const t: RegisterText = {
      selectLabel: str(p, "selectLabel", "Select State:"),
      openPill: str(p, "openPill", "Open"),
      soonPill: str(p, "soonPill", "Coming Soon"),
      soonGroupLabel: str(p, "soonGroupLabel", "Coming Soon"),
      alertHtml: str(p, "alertHtml"),
      eyebrowTemplate: str(p, "eyebrowTemplate", "{name}"),
      headingTemplate: str(p, "headingTemplate", "{code} CON Publication Requirements"),
      introByState: strMap(p, "introByState"),
      colRequirement: str(p, "colRequirement", "Requirement"),
      colFinding: str(p, "colFinding", "Finding"),
      colStatus: str(p, "colStatus", "Verification Status"),
      questionsHeading: str(p, "questionsHeadingTemplate", "Open Questions: {code} Verification Checklist"),
      sourcesHeading: str(p, "sourcesHeadingTemplate", "Official {code} Sources"),
      sourcesFootnote: str(p, "sourcesFootnote"),
      soonTitleTemplate: str(p, "soonTitleTemplate", "{name}: Coming Soon"),
      soonHtml: str(p, "soonHtml")
    };
    return (
      <RequirementsRegister
        states={sortStates(stateEntries.map(toState))}
        rows={reqEntries.map((e) => ({
          stateCode: str(e.fields, "stateCode").toLowerCase(),
          label: e.title,
          description: str(e.fields, "description"),
          finding: str(e.fields, "finding"),
          status: str(e.fields, "status", "open"),
          statusLabel: str(e.fields, "statusLabel")
        }))}
        questions={questionEntries
          .filter((e) => str(e.fields, "registerText"))
          .map((e) => ({ stateCode: str(e.fields, "stateCode").toLowerCase(), text: str(e.fields, "registerText") }))}
        sources={sourceEntries.map((e) => ({
          stateCode: str(e.fields, "stateCode").toLowerCase(),
          label: e.title,
          url: str(e.fields, "url"),
          note: str(e.fields, "note")
        }))}
        text={t}
        initialState={code}
        formKey={str(p, "formKey", "waitlist")}
        waitlist={waitlistText(obj(p, "waitlist"), "Requirements page")}
      />
    );
  }

  return null;
}

// ─── faqAccordion ────────────────────────────────────────────────────────────

async function Faq({ p }: { p: P }) {
  let items: { question: string; answer: string }[] = Array.isArray(p.items)
    ? (p.items as P[]).map((i) => ({ question: str(i, "question"), answer: str(i, "answer") }))
    : [];
  const key = str(p, "collectionKey");
  if (key) items = (await getEntries(key)).map((e) => ({ question: e.title, answer: str(e.fields, "answer") }));
  return (
    <Section p={p}>
      <FaqList items={items} />
    </Section>
  );
}

// ─── ctaBanner ───────────────────────────────────────────────────────────────

function CtaBanner({ p }: { p: P }) {
  return (
    <section className="section section-navy">
      <Folio name={str(p, "eyebrow") || str(p, "heading")} />
      <div className="container" style={{ textAlign: "center" }}>
        <h2 className="section-title light">{str(p, "heading")}</h2>
        {str(p, "description") && (
          <p style={{ color: "rgba(255,255,255,.75)", maxWidth: 500, margin: "0 auto 28px", lineHeight: 1.65 }}>{str(p, "description")}</p>
        )}
        <ButtonLink label={str(p, "ctaLabel")} href={str(p, "ctaHref")} className="btn-primary" style={{ fontSize: "1.05rem", padding: "16px 32px" }} />
        {str(p, "secondaryLabel") && (
          <>
            {" "}
            <ButtonLink label={str(p, "secondaryLabel")} href={str(p, "secondaryHref")} className="btn-outline" />
          </>
        )}
      </div>
    </section>
  );
}

// ─── formEmbed ───────────────────────────────────────────────────────────────

async function FormEmbed({ p }: { p: P }) {
  const variant = str(p, "variant", "card");
  const formKey = str(p, "formKey");

  if (variant === "subscribe") {
    // Subscribe to new notices by email, phone, or both, for the whole
    // country or chosen states (a section of its own). On a statewide
    // edition, `stateName` starts ticked.
    const defaultState = str(p, "stateName");
    const states = (await getEntries(str(p, "statesCollection", "states"))).map(toState).map((x) => x.name).sort((a, b) => a.localeCompare(b));
    return (
      <Section p={p}>
        <div className="subscribe-box">
          <SubscribeForm
            formKey={formKey || "subscribe"}
            states={states}
            defaultState={defaultState || undefined}
            text={{
              emailLabel: str(p, "emailLabel", "Email"),
              emailPlaceholder: str(p, "emailPlaceholder", "you@example.com"),
              phoneLabel: str(p, "phoneLabel", "Phone (text alerts)"),
              phonePlaceholder: str(p, "phonePlaceholder", "(800) 555 0100"),
              orLabel: str(p, "orLabel", "or"),
              stateLabel: str(p, "stateLabel", "Notices from"),
              nationwideLabel: str(p, "nationwideLabel", "Nationwide: every state and territory"),
              pickStatesText: str(p, "pickStatesText", "Choose one or more states:"),
              needStateText: str(p, "needStateText", "Choose at least one state, or tick Nationwide."),
              submitLabel: str(p, "submitLabel", "Subscribe"),
              sendingLabel: str(p, "sendingLabel", "Sending"),
              needOneText: str(p, "needOneText", "Enter an email address, a phone number, or both."),
              noteHtml: str(p, "noteHtml"),
              successText: str(p, "successText", "You are subscribed."),
              source: str(p, "source", "Subscribe section")
            }}
          />
        </div>
      </Section>
    );
  }

  if (variant === "waitlist" || variant === "cta") {
    const t = waitlistText(p, variant === "waitlist" ? "Home page waitlist" : "States page waitlist");
    if (variant === "cta") {
      return (
        <div className="coming-soon-cta">
          <h2>{str(p, "heading")}</h2>
          <p>{str(p, "description")}</p>
          <WaitlistForm formKey={formKey || "waitlist"} text={t} />
        </div>
      );
    }
    const box = (
      <div className="waitlist-section">
        <h2>{str(p, "heading")}</h2>
        <p>{str(p, "description")}</p>
        <WaitlistForm formKey={formKey || "waitlist"} text={t} />
      </div>
    );
    if (str(p, "look") === "broadsheet") {
      return (
        <div className="broadsheet-section">
          <div className="broadsheet-body">{box}</div>
        </div>
      );
    }
    return (
      <section className="section">
        <div className="container">{box}</div>
      </section>
    );
  }

  if (variant === "portal") {
    const site = await getSiteSettings();
    const form = formKey ? await getFormSchema(formKey) : null;
    return (
      <PortalCard
        brand={str(p, "brand") || site.companyName}
        subtitle={str(p, "subtitle")}
        form={form}
        extras={extrasProp(p)}
        buttonLabel={str(p, "buttonLabel", "Continue")}
        buttonHref={str(p, "buttonHref")}
        noteHtml={str(p, "noteHtml")}
        successHtml={str(p, "successHtml")}
        backLabel={str(p, "backLabel", "Back")}
        backHref={str(p, "backHref", "/")}
        source={str(p, "source", "Customer portal")}
      />
    );
  }

  const form = await getFormSchema(formKey);
  if (!form) return null;

  if (variant === "wizard") {
    const cfg = obj(p, "wizard") as unknown as WizardConfig;
    // Each state's own rules, shown in the form once the state is chosen.
    const states = sortStates((await getEntries(str(p, "statesCollection", "states"))).map(toState));
    const stateRules: StateRule[] = states.map((s) => ({
      name: s.name,
      slug: s.slug,
      status: s.con.status,
      statusLabel: DEFAULT_CON_LABELS.status[s.con.status || "unknown"],
      noticeRule: s.con.noticeRule,
      noticeCitation: s.con.noticeCitation,
      noticeBy: DEFAULT_CON_LABELS.noticeByValue[s.con.noticeBy] || "",
      href: s.href
    }));
    return <SubmitWizard form={form} config={cfg} extras={extrasProp(p)} stateRules={stateRules} />;
  }

  return (
    <div>
      {str(p, "eyebrow") && <div className="section-label">{str(p, "eyebrow")}</div>}
      {str(p, "heading") && <h2 className="section-title">{str(p, "heading")}</h2>}
      {str(p, "description") && (
        <p className={str(p, "descriptionClass") || undefined} style={str(p, "descriptionClass") ? undefined : { color: "var(--gray-600)", lineHeight: 1.65, marginBottom: 24 }}>
          {str(p, "description")}
        </p>
      )}
      <div className={str(p, "wrapClass", "quote-form-wrap")}>
        <CardForm
          form={form}
          rows={rowsProp(p)}
          extras={extrasProp(p)}
          submitLabel={str(p, "submitLabel", "Submit")}
          successHtml={str(p, "successHtml")}
          source={str(p, "source")}
        />
      </div>
    </div>
  );
}

// ─── columns ─────────────────────────────────────────────────────────────────

function Columns({ p, children }: { p: P; children: WebBlock[] }) {
  const count = Math.max(1, Number(str(p, "columnCount", "2")));
  const cols: WebBlock[][] = Array.from({ length: count }, () => []);
  children.forEach((c, i) => {
    const n = Number(str(c.props, "column", String(Math.min(i + 1, count))));
    (cols[Math.min(Math.max(n, 1), count) - 1] ?? cols[0]!).push(c);
  });
  const className = str(p, "className");
  const grid = (
    <div
      className={className || "msc-split"}
      style={
        className
          ? undefined
          : {
              gridTemplateColumns: str(p, "template") || `repeat(${count}, 1fr)`,
              gap: Number(str(p, "gapPx", "48")),
              alignItems: str(p, "align", "center")
            }
      }
    >
      {cols.map((c, i) => (
        <div key={i} className={list(p, "columnClasses")[i] || undefined}>
          <Blocks blocks={c} />
        </div>
      ))}
    </div>
  );
  if (str(p, "wrap") === "front") {
    return (
      <div className="broadsheet-body">
        <div className="front-page-hero front-cols">{grid}</div>
      </div>
    );
  }
  if (str(p, "wrap") === "section") {
    return (
      <section className={`section${str(p, "sectionClass") ? " " + str(p, "sectionClass") : ""}`}>
        <Folio name={str(p, "eyebrow") || str(p, "heading")} />
        <div className="container">{grid}</div>
      </section>
    );
  }
  return grid;
}

// ─── dispatcher ──────────────────────────────────────────────────────────────

function RichText({ p }: { p: P }) {
  const body = str(p, "html");
  if (str(p, "wrap") === "section") {
    return (
      <section className={`section${str(p, "sectionClass") ? " " + str(p, "sectionClass") : ""}`}>
        <Folio name={str(p, "eyebrow") || folioFromHtml(body)} />
        <div className="container" dangerouslySetInnerHTML={html(body)} />
      </section>
    );
  }
  return <div style={{ display: "contents" }} dangerouslySetInnerHTML={html(body)} />;
}

function Block({ block }: { block: WebBlock }) {
  const p = block.props || {};
  const rule = str(p, "ruleBefore");
  if (rule) {
    return (
      <>
        <hr className={`${rule}-rule`} />
        <BlockBody block={block} />
      </>
    );
  }
  return <BlockBody block={block} />;
}

function BlockBody({ block }: { block: WebBlock }) {
  const p = block.props || {};
  switch (block.type) {
    case "hero":
      return <Hero p={p} />;
    case "richText":
      return <RichText p={p} />;
    case "numberedGrid":
      return <NumberedGrid p={p} />;
    case "pillarGrid":
      return <PillarGrid p={p} />;
    case "pricedGrid":
      return <PricedGrid p={p} />;
    case "flatList":
      return <FlatList p={p} />;
    case "faqAccordion":
      return <Faq p={p} />;
    case "ctaBanner":
      return <CtaBanner p={p} />;
    case "formEmbed":
      return <FormEmbed p={p} />;
    case "columns":
      return <Columns p={p}>{block.children || []}</Columns>;
    case "button":
      return (
        <ButtonLink
          label={str(p, "label")}
          href={str(p, "href")}
          className={str(p, "variant") === "outline" ? "btn-outline" : "btn-primary"}
          icon={str(p, "icon")}
          style={str(p, "marginTop") ? { marginTop: Number(str(p, "marginTop")) } : undefined}
        />
      );
    case "spacer":
      return <div style={{ height: Number(str(p, "heightPx", "40")) }} />;
    case "image":
      // Renders nothing until an image is uploaded in the Page Builder.
      return str(p, "url") ? (
        <figure className={str(p, "className") || undefined}>
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img src={str(p, "url")} alt={str(p, "altText")} style={{ maxWidth: "100%" }} />
          {str(p, "caption") && <figcaption>{str(p, "caption")}</figcaption>}
        </figure>
      ) : null;
    default:
      return null;
  }
}

function Blocks({ blocks }: { blocks: WebBlock[] }) {
  const out: React.ReactNode[] = [];
  let main: WebBlock[] = [];
  const flush = () => {
    if (main.length) {
      const group = main;
      out.push(
        <div className="main-content" key={`main-${group[0]!.id}`}>
          {group.map((b) => (
            <Block key={b.id} block={b} />
          ))}
        </div>
      );
      main = [];
    }
  };
  for (const b of blocks) {
    if (str(b.props, "layout") === "main") {
      main.push(b);
    } else {
      flush();
      out.push(<Block key={b.id} block={b} />);
    }
  }
  flush();
  return <>{out}</>;
}

export default function BlockRenderer({ blocks }: { blocks: WebBlock[] }) {
  return <Blocks blocks={blocks} />;
}
