import orionLogo from "@/assets/orion-logo.svg";
import sparkHorse from "@/assets/spark-horse.png";
import { grades, portraitDimensions } from "@/data/portraitData";
import { ParentCourseOverviewBlock } from "@/components/page-blocks/ParentCourseOverviewBlock";
import {
  getGradeHeroIcon,
  getHeroButtons,
  getHeroFeatureHighlights,
  getHeroStatistics,
} from "@/components/page-blocks/GradeHeroBlock";
import { normalizeHeroContent } from "@/components/page-blocks/hero/normalizeContent";
import { resolvePreviewContent } from "@/lib/contentPlaceholders";
import { getCompetitionNavigation } from "@/lib/competitionNavigation";

type ContentMap = Record<string, unknown>;

/** Hero section — same design + content as Landing */
export function HeroPreview({ content }: { content?: ContentMap }) {
  const hero = normalizeHeroContent(content);
  const logoSrc = hero.logo.src.trim() || orionLogo;
  const horseSrc = hero.horseImage.src.trim() || sparkHorse;

  return (
    <section className="flex flex-col items-center justify-center bg-milk px-4 py-8 rounded-xl">
      <div className="text-center mb-4">
        <img src={logoSrc} alt={hero.logo.alt} className="h-12 mx-auto mb-2" />
        <h1 className="font-display text-2xl font-bold text-bark mb-1">{hero.title}</h1>
        <p className="text-muted-foreground text-xs max-w-md mx-auto">
          {hero.subtitle}
        </p>
      </div>
      <div className="flex justify-center w-full">
        <img
          src={horseSrc}
          alt={hero.horseImage.alt}
          className="w-full max-w-[180px]"
        />
      </div>
      <div className="flex flex-wrap justify-center gap-1.5 mt-3">
        {hero.tabs.slice(0, 4).map((tab) => (
          <span
            key={tab.key}
            className="font-display text-[10px] tracking-wide uppercase font-bold px-2 py-1 rounded-full text-foreground/80 bg-secondary/50"
          >
            {tab.emoji} {(tab.buttonLabel || tab.title).split(" ")[0]}
          </span>
        ))}
      </div>
    </section>
  );
}

/** Dimension Detail — one sample dimension card, same design as Landing */
export function DimensionDetailPreview() {
  const selected = portraitDimensions[0];
  return (
    <section className="bg-background rounded-xl overflow-hidden border border-border">
      <div className="p-4">
        <div className={`rounded-xl border-2 border-valencia bg-card p-4`}>
          <div className="flex items-center gap-2 mb-3">
            <span className="text-2xl">{selected.emoji}</span>
            <div>
              <h2 className="font-display text-lg font-bold text-foreground">{selected.title}</h2>
              <p className="text-muted-foreground text-xs">{selected.desc}</p>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4 mt-3">
            <div>
              <p className="font-display text-[10px] tracking-widest uppercase text-muted-foreground mb-2">
                Character Traits & Mindsets
              </p>
              <div className="space-y-2">
                <div className="bg-muted rounded-lg p-2">
                  <p className="font-display text-[0.6rem] uppercase text-muted-foreground mb-1">Big Dreams</p>
                  <div className="flex justify-between items-center gap-1">
                    <span className="text-xs font-display font-medium text-foreground">Courage</span>
                    <span className="text-[10px] font-display font-bold text-valencia">100%</span>
                  </div>
                </div>
              </div>
            </div>
            <div>
              <p className="font-display text-[10px] tracking-widest uppercase text-muted-foreground mb-2">
                Courses at Orion
              </p>
              <div className="space-y-1">
                <div className="bg-muted rounded-lg p-2 flex items-center gap-2">
                  <span className="text-sm">📘</span>
                  <span className="text-xs font-display font-bold text-foreground truncate">Science</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/** Grade Family Guides — same design as Landing */
export function GradeFamilyGuidesPreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "Family Guides by Grade";
  const footerText = content?.footerText ?? "KG is live · Other grades coming soon";
  return (
    <section className="py-6 bg-card rounded-xl">
      <div className="px-4 text-center">
        <p className="font-display text-xs tracking-[0.2em] uppercase text-deep-sea mb-3">{heading}</p>
        <div className="flex flex-wrap justify-center gap-2">
          {grades.slice(0, 6).map((g) =>
            g.available ? (
              <span
                key={g.id}
                className="inline-flex items-center justify-center font-display text-xs font-bold rounded-full w-10 h-10 bg-deep-sea text-milk"
              >
                {g.shortLabel}
              </span>
            ) : (
              <span
                key={g.id}
                className="inline-flex items-center justify-center font-display text-xs font-medium rounded-full w-10 h-10 bg-secondary text-muted-foreground"
              >
                {g.shortLabel}
              </span>
            )
          )}
        </div>
        <p className="text-muted-foreground text-[10px] mt-2 font-display">{footerText}</p>
      </div>
    </section>
  );
}

/** Footer — same design as Landing */
export function FooterPreview({ content }: { content?: ContentMap }) {
  const text = content?.text ?? "Orion STEM Schools · Family Curriculum Portal · 2026–2027";
  return (
    <footer className="py-6 bg-bark text-center rounded-xl">
      <p className="font-display text-milk/60 text-xs">
        {text}
      </p>
    </footer>
  );
}

/** PBEL Guide Footer — reference /course/pbel-water FooterBar */
export function PbelGuideFooterPreview({ content }: { content?: ContentMap }) {
  const leftTitle = String(content?.leftTitle ?? "Orion STEM Schools");
  const middleTitle = String(content?.middleTitle ?? "PBEL Family Flyer (Water)");
  const rightText = String(content?.rightText ?? "Print double‑sided");
  const currentPageLabel = String(content?.currentPageLabel ?? "Page 1");
  const totalPageLabel = String(content?.totalPageLabel ?? "Page 2");
  const label = [leftTitle, middleTitle, rightText].map((p) => p.trim()).filter(Boolean).join(" · ");
  const pageLabel = totalPageLabel.trim()
    ? `${currentPageLabel.trim()} / ${totalPageLabel.trim()}`
    : currentPageLabel.trim();
  const dot1 = String(content?.dot1Color ?? "--primary");
  const dot2 = String(content?.dot2Color ?? "--accent");
  const dot3 = String(content?.dot3Color ?? "--sunflower");
  const token = (v: string) => (v.startsWith("--") ? v : `--${v}`);

  return (
    <footer className="mt-auto pt-3.5 border-t border-border flex justify-between items-center text-[11px] text-muted-foreground opacity-70">
      <span>{label}</span>
      <span className="flex items-center gap-1.5">
        {pageLabel}
        <span className="inline-block w-1.5 h-1.5 rounded-full ml-1" style={{ backgroundColor: `hsl(var(${token(dot1)}))` }} />
        <span className="inline-block w-1.5 h-1.5 rounded-full" style={{ backgroundColor: `hsl(var(${token(dot2)}))` }} />
        <span className="inline-block w-1.5 h-1.5 rounded-full" style={{ backgroundColor: `hsl(var(${token(dot3)}))` }} />
      </span>
    </footer>
  );
}

/** Year-Long Story — curriculum page section */
export function YearLongStoryPreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "The Year-Long Story";
  const story = content?.story ?? "Kindergarteners spend their year as scientists, engineers, and community builders...";
  return (
    <section className="py-4 px-4 bg-card rounded-xl border border-border text-center">
      <p className="font-display text-[10px] tracking-widest uppercase text-deep-sea mb-2">{heading}</p>
      <p className="text-foreground text-xs leading-relaxed line-clamp-3">{story}</p>
    </section>
  );
}

/** Developing the Whole Child — curriculum page section (Portrait of the Learner) */
export function DevelopingWholeChildPreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "Developing the Whole Child";
  const title = content?.title ?? "Portrait of the Learner";
  const raw = content as Record<string, unknown> | undefined;
  const dimensions = Array.isArray(raw?.dimensions) ? raw.dimensions as { emoji?: string; title?: string; desc?: string }[] : [];
  return (
    <section className="py-4 px-4 bg-background rounded-xl border border-border text-center">
      <p className="font-display text-[10px] tracking-widest uppercase text-deep-sea mb-1">{heading}</p>
      <p className="font-display text-sm font-bold text-foreground mb-2">{title}</p>
      <div className="flex flex-wrap justify-center gap-1.5">
        {dimensions.slice(0, 4).map((d, i) => (
          <span key={i} className="text-xs text-muted-foreground">
            {d.emoji ?? "✨"} {d.title ?? ""}
          </span>
        ))}
        {dimensions.length > 4 && <span className="text-xs text-muted-foreground">+{dimensions.length - 4}</span>}
      </div>
    </section>
  );
}

/** Fink's Taxonomy of Significant Learning — curriculum / quarter section */
export function FinksTaxonomyPreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "Fink's Taxonomy of Significant Learning";
  const raw = content as Record<string, unknown> | undefined;
  const items = Array.isArray(raw?.items) ? raw.items as { category?: string; emoji?: string }[] : [];
  return (
    <section className="py-4 px-4 bg-card rounded-xl border border-border text-center">
      <p className="font-display text-xs font-bold text-foreground mb-2">{heading}</p>
      <div className="flex flex-wrap justify-center gap-1.5">
        {items.slice(0, 4).map((item, i) => (
          <span key={i} className="text-xs text-muted-foreground">
            {item.emoji ?? "📚"} {item.category ?? ""}
          </span>
        ))}
        {items.length > 4 && <span className="text-xs text-muted-foreground">+{items.length - 4}</span>}
      </div>
    </section>
  );
}

/** Year at a Glance — curriculum page section (quarter cards) */
export function YearAtGlancePreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "The Year at a Glance";
  const title = content?.title ?? "One Project. Four Roles. Infinite Growth.";
  return (
    <section className="py-4 px-4 bg-background rounded-xl border border-border text-center">
      <p className="font-display text-[10px] tracking-widest uppercase text-deep-sea mb-1">{heading}</p>
      <p className="font-display text-sm font-bold text-foreground">{title}</p>
    </section>
  );
}

/** DNA Strands — curriculum page section (4 DNA Strands · 16 Rotating Courses) */
export function DnaStrandsPreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "4 DNA Strands · 16 Rotating Courses";
  const title = content?.title ?? "Specialty Skills That Rotate Every Quarter";
  return (
    <section className="py-4 px-4 bg-background rounded-xl border border-border text-center">
      <p className="font-display text-[10px] tracking-widest uppercase text-valencia mb-1">{heading}</p>
      <p className="font-display text-sm font-bold text-foreground">{title}</p>
    </section>
  );
}

/** Core Courses — curriculum page section (The 9 Core Courses) */
export function CoreCoursesPreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "The 9 Core Courses";
  const title = content?.title ?? "Integrated Learning Across Every Subject";
  return (
    <section className="py-4 px-4 bg-background rounded-xl border border-border text-center">
      <p className="font-display text-[10px] tracking-widest uppercase text-deep-sea mb-1">{heading}</p>
      <p className="font-display text-sm font-bold text-foreground">{title}</p>
    </section>
  );
}

/** Essential Question — curriculum page section */
export function EssentialQuestionPreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "Essential Question";
  const question = content?.question ?? "How can we design spaces that help living things (including us) stay healthy and comfortable?";
  return (
    <section className="py-4 px-4 bg-card rounded-xl border border-border text-center">
      <p className="font-display text-[10px] tracking-widest uppercase text-deep-sea mb-2">{heading}</p>
      <p className="font-display text-sm italic text-foreground">"{question}"</p>
    </section>
  );
}

/** One Project, Not 13 Tests — curriculum page section */
export function OneProjectNot13TestsPreview({ content }: { content?: ContentMap }) {
  const title = content?.title ?? "One Project, Not 13 Tests";
  const raw = content as Record<string, unknown> | undefined;
  const stats = Array.isArray(raw?.stats) ? raw.stats as { val?: string; label?: string }[] : [];
  return (
    <section className="py-4 px-4 orion-gradient rounded-xl border border-border text-center">
      <p className="font-display text-sm font-bold text-milk mb-2">{title}</p>
      <div className="flex flex-wrap justify-center gap-2">
        {stats.slice(0, 3).map((s, i) => (
          <span key={i} className="text-xs text-milk/80">
            {s.val ?? ""} {s.label ?? ""}
          </span>
        ))}
      </div>
    </section>
  );
}

/** Curriculum Architecture — curriculum page section (strand × quarter table) */
export function CurriculumArchitecturePreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "Curriculum Architecture";
  const title = content?.title ?? "9 Core + 4 DNA Strands = 1 Integrated Project";
  return (
    <section className="py-4 px-4 bg-card rounded-xl border border-border text-center">
      <p className="font-display text-[10px] tracking-widest uppercase text-deep-sea mb-1">{heading}</p>
      <p className="font-display text-sm font-bold text-foreground">{title}</p>
    </section>
  );
}

/** Problem-Based Experiential Learning — curriculum page section */
export function PbelPreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "Problem-Based Experiential Learning";
  const title = content?.title ?? "💧 PBEL: Water — Every Drop Counts";
  return (
    <section className="py-4 px-4 bg-background rounded-xl border border-border text-center">
      <p className="font-display text-[10px] tracking-widest uppercase text-valencia mb-1">{heading}</p>
      <p className="font-display text-sm font-bold text-foreground">{title}</p>
    </section>
  );
}

/** Course Hero — course overview header (e.g. /course/science) */
export function CourseHeroPreview({ content }: { content?: ContentMap }) {
  const name = content?.name ?? "{subject}";
  const emoji = content?.emoji ?? "📚";
  const tagline = content?.tagline ?? "Empowering your child to learn, grow, and thrive...";
  const weeklyTimeK5 = (content?.weeklyTimeK5 as string)?.trim() || "—";
  const weeklyTime612 = (content?.weeklyTime612 as string)?.trim() || "—";
  return (
    <section className="py-4 px-4 orion-gradient rounded-xl border border-border text-center">
      <span className="text-3xl block mb-2">{emoji}</span>
      <p className="font-display text-sm font-bold text-milk">{name}</p>
      <p className="font-display text-xs text-milk/80 line-clamp-2 mt-1">{tagline}</p>
      <p className="font-display text-[10px] text-milk/70 mt-2">
        K-5: {weeklyTimeK5} · 6-12: {weeklyTime612}
      </p>
    </section>
  );
}

/** Why This Course Matters — course overview section */
export function WhyThisCourseMattersPreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "Why This Course Matters";
  const body = content?.body ?? "{subject} is the foundation of curiosity...";
  return (
    <section className="py-4 px-4 bg-card rounded-xl border border-border">
      <p className="font-display text-xs font-bold text-deep-sea mb-2">{heading}</p>
      <p className="text-foreground text-xs leading-relaxed line-clamp-3">{body}</p>
    </section>
  );
}

/** How [Course] Connects to All Learning — course overview section */
export function HowConnectsPreview({ content }: { content?: ContentMap }) {
  const heading = (content?.heading as string) ?? "How This Subject Connects to All Learning";
  const headingIcon = content?.headingIcon ?? "🎭";
  const body = content?.body ?? "{subject} provides the CONTENT KNOWLEDGE...";
  const otherSubjectsTitle = content?.otherSubjectsTitle ?? "What Other Subjects Teach";
  const otherSubjectsIcon = content?.otherSubjectsIcon ?? "📚";
  const otherSubjectsText = (content?.otherSubjectsText as string) ?? "Math: Count and measure...";
  const thisAddsTitle = (content?.thisAddsTitle as string) ?? "What This Subject Adds";
  const thisAddsIcon = content?.thisAddsIcon ?? "🔬";
  const thisAddsText = (content?.thisAddsText as string) ?? "{subject} provides the WHY...";
  return (
    <section className="py-4 px-4 bg-card rounded-xl border border-border w-full">
      <p className="font-display text-xs font-bold text-deep-sea mb-2 flex items-center gap-1">
        <span>{headingIcon}</span> {heading}
      </p>
      <p className="text-foreground text-[10px] leading-relaxed line-clamp-2 mb-3">{body}</p>
      <div className="grid grid-cols-2 gap-2">
        <div className="bg-muted/50 rounded-lg p-2 border-l-2 border-sunflower">
          <p className="font-display text-[9px] font-bold text-sunflower mb-0.5 flex items-center gap-0.5">
            <span>{otherSubjectsIcon}</span> {otherSubjectsTitle}
          </p>
          <p className="text-muted-foreground text-[9px] line-clamp-2">{otherSubjectsText}</p>
        </div>
        <div className="bg-muted/50 rounded-lg p-2 border-l-2 border-deep-sea">
          <p className="font-display text-[9px] font-bold text-deep-sea mb-0.5 flex items-center gap-0.5">
            <span>{thisAddsIcon}</span> {thisAddsTitle}
          </p>
          <p className="text-muted-foreground text-[9px] line-clamp-2">{thisAddsText}</p>
        </div>
      </div>
    </section>
  );
}

/** Smarter Assessment = Less Stress — course overview section */
export function SmarterAssessmentPreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "Smarter Assessment = Less Stress";
  const headingIcon = content?.headingIcon ?? "✅";
  const rawItems = content?.items;
  const items = Array.isArray(rawItems)
    ? rawItems.slice(0, 3).map((o: unknown) => {
        const x = o && typeof o === "object" ? (o as Record<string, unknown>) : {};
        return {
          icon: (x.icon as string) ?? "•",
          title: (x.title as string) ?? "Item",
          color: (x.color as string) ?? "deep-sea",
        };
      })
    : [
        { icon: "1️⃣", title: "ONE Diagnostic", color: "deep-sea" },
        { icon: "📊", title: "Daily Check-ins", color: "valencia" },
        { icon: "1️⃣", title: "ONE Final Project", color: "moss" },
      ];
  const benefitLabel = (content?.benefitLabel as string) ?? "💡 The Benefit:";
  return (
    <section className="py-4 px-4 bg-card rounded-xl border border-border w-full">
      <p className="font-display text-xs font-bold text-deep-sea mb-2 flex items-center gap-1">
        <span>{headingIcon}</span> {heading}
      </p>
      <div className="grid grid-cols-3 gap-1 mb-2">
        {items.map((item, i) => (
          <div key={i} className="rounded p-1.5 border border-border text-center">
            <span className="text-sm">{item.icon}</span>
            <p className="font-display text-[9px] font-bold text-foreground truncate">{item.title}</p>
          </div>
        ))}
      </div>
      <p className="text-muted-foreground text-[9px]">
        <strong className="text-sunflower">{benefitLabel}</strong> One meaningful project...
      </p>
    </section>
  );
}

/** What Your Child Will Gain — course overview section */
export function WhatYourChildWillGainPreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "What Your Child Will Gain";
  const headingIcon = content?.headingIcon ?? "🌟";
  const rawItems = content?.items;
  const items = Array.isArray(rawItems)
    ? rawItems.slice(0, 4).map((x: unknown) => (typeof x === "string" ? x : String(x)))
    : ["Scientific thinking...", "Observation skills...", "Understanding of systems...", "Confidence in asking..."];
  return (
    <section className="py-4 px-4 bg-card rounded-xl border border-border w-full">
      <p className="font-display text-xs font-bold text-deep-sea mb-2 flex items-center gap-1">
        <span>{headingIcon}</span> {heading}
      </p>
      <div className="grid grid-cols-2 gap-1">
        {items.map((item, i) => (
          <div key={i} className="rounded p-1.5 orion-gradient text-center">
            <p className="text-milk text-[9px] font-display line-clamp-2">{item}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

/** Developing the Whole Child (Course) — portrait dimensions with % bars */
export function CoursePortraitPreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "Developing the Whole Child";
  const headingIcon = content?.headingIcon ?? "🎨";
  const rawDimensions = content?.dimensions;
  const dimensions = Array.isArray(rawDimensions)
    ? rawDimensions.slice(0, 3).map((o: unknown) => {
        const x = o && typeof o === "object" ? (o as Record<string, unknown>) : {};
        return { name: (x.name as string) ?? "Dimension", pct: (x.pct as number) ?? 0 };
      })
    : [
        { name: "Inspiring Communicator", pct: 85 },
        { name: "Balanced Person", pct: 60 },
        { name: "Caring Citizen", pct: 80 },
      ];
  return (
    <section className="py-4 px-4 bg-card rounded-xl border border-border w-full">
      <p className="font-display text-xs font-bold text-deep-sea mb-2 flex items-center gap-1">
        <span>{headingIcon}</span> {heading}
      </p>
      <p className="text-muted-foreground text-[9px] mb-2 line-clamp-1">This course intentionally develops all six Portrait...</p>
      <div className="space-y-1">
        {dimensions.map((d, i) => (
          <div key={i} className="flex justify-between text-[9px]">
            <span className="truncate">{d.name}</span>
            <span className="font-bold text-deep-sea">{d.pct}%</span>
          </div>
        ))}
      </div>
    </section>
  );
}

/** Core Skills Your Child Will Master — course overview section */
export function CourseCoreSkillsPreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "Core Skills Your Child Will Master";
  const headingIcon = content?.headingIcon ?? "🎯";
  const rawSkills = content?.skills;
  const skills = Array.isArray(rawSkills)
    ? rawSkills.slice(0, 2).map((o: unknown) => {
        const x = o && typeof o === "object" ? (o as Record<string, unknown>) : {};
        return { title: (x.title as string) ?? "Skill", emoji: (x.emoji as string) ?? "•" };
      })
    : [
        { title: "Observation & Inquiry", emoji: "🔍" },
        { title: "Investigation & Evidence", emoji: "🧪" },
      ];
  return (
    <section className="py-4 px-4 bg-card rounded-xl border border-border w-full">
      <p className="font-display text-xs font-bold text-deep-sea mb-2 flex items-center gap-1">
        <span>{headingIcon}</span> {heading}
      </p>
      <div className="grid grid-cols-2 gap-1">
        {skills.map((s, i) => (
          <div key={i} className="rounded p-2 border border-border">
            <p className="font-display text-[9px] font-bold text-deep-sea flex items-center gap-1">
              <span>{s.emoji}</span> {s.title}
            </p>
          </div>
        ))}
      </div>
    </section>
  );
}

/** Your Child's Year-Long Journey — course overview section */
export function CourseJourneyPreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "Your Child's Year-Long Journey";
  const headingIcon = content?.headingIcon ?? "🗓️";
  const rawPhases = content?.phases;
  const phases = Array.isArray(rawPhases)
    ? rawPhases.slice(0, 3).map((o: unknown) => {
        const x = o && typeof o === "object" ? (o as Record<string, unknown>) : {};
        return { weeks: (x.weeks as string) ?? "Q1", title: (x.title as string) ?? "Phase" };
      })
    : [
        { weeks: "Q1", title: "Observe & Discover" },
        { weeks: "Q2", title: "Measure & Analyze" },
        { weeks: "Q3", title: "Design & Test" },
      ];
  return (
    <section className="py-4 px-4 bg-card rounded-xl border border-border w-full">
      <p className="font-display text-xs font-bold text-deep-sea mb-2 flex items-center gap-1">
        <span>{headingIcon}</span> {heading}
      </p>
      <div className="space-y-1">
        {phases.map((p, i) => (
          <div key={i} className="flex gap-2 text-[9px]">
            <span className="font-bold text-deep-sea w-6">{p.weeks}</span>
            <span className="truncate text-muted-foreground">{p.title}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

/** What Your Child Will Create — course overview section */
export function CourseWhatTheyCreatePreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "What Your Child Will Create";
  const headingIcon = content?.headingIcon ?? "🎨";
  const rawItems = content?.items;
  const items = Array.isArray(rawItems)
    ? rawItems.slice(0, 3).map((o: unknown) => {
        const x = o && typeof o === "object" ? (o as Record<string, unknown>) : {};
        return { emoji: (x.emoji as string) ?? "•", title: (x.title as string) ?? "Item" };
      })
    : [
        { emoji: "📓", title: "Observation Journals" },
        { emoji: "📊", title: "Data Charts & Graphs" },
        { emoji: "🗺️", title: "System Models" },
      ];
  return (
    <section className="py-4 px-4 bg-card rounded-xl border border-border w-full">
      <p className="font-display text-xs font-bold text-deep-sea mb-2 flex items-center gap-1">
        <span>{headingIcon}</span> {heading}
      </p>
      <div className="grid grid-cols-3 gap-1">
        {items.map((item, i) => (
          <div key={i} className="rounded p-2 border-2 border-deep-sea text-center">
            <span className="text-lg">{item.emoji}</span>
            <p className="font-display text-[9px] font-bold text-foreground truncate">{item.title}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

/** Deep Inquiry Questions to Ask Your Child — course overview section */
export function CourseInquiryQuestionsPreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "Deep Inquiry Questions to Ask Your Child";
  const headingIcon = content?.headingIcon ?? "💭";
  const introTitle = (content?.introTitle as string) ?? "Ask About Learning, Not Just Activities";
  const rawCategories = content?.categories;
  const categories = Array.isArray(rawCategories)
    ? rawCategories.slice(0, 2).map((o: unknown) => {
        const x = o && typeof o === "object" ? (o as Record<string, unknown>) : {};
        return { title: (x.title as string) ?? "Category", emoji: (x.emoji as string) ?? "💭" };
      })
    : [
        { title: "About Their Observations", emoji: "🔍" },
        { title: "About Evidence & Reasoning", emoji: "🧠" },
      ];
  return (
    <section className="py-4 px-4 bg-card rounded-xl border border-border w-full">
      <p className="font-display text-xs font-bold text-deep-sea mb-2 flex items-center gap-1">
        <span>{headingIcon}</span> {heading}
      </p>
      <div className="rounded-lg p-2 bg-sunflower/10 border border-sunflower mb-2">
        <p className="font-display text-[9px] font-bold text-foreground flex items-center gap-1">
          <span>{content?.introIcon ?? "🧠"}</span> {introTitle}
        </p>
      </div>
      <div className="space-y-1">
        {categories.map((c, i) => (
          <div key={i} className="text-[9px] flex items-center gap-1">
            <span>{c.emoji}</span>
            <span className="truncate text-muted-foreground">{c.title}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

/** Simple Ways to Support at Home — course overview section */
export function CourseSupportAtHomePreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "Simple Ways to Support at Home";
  const headingIcon = content?.headingIcon ?? "🏠";
  const rawTips = content?.tips;
  const tips = Array.isArray(rawTips)
    ? rawTips.slice(0, 2).map((o: unknown) => {
        const x = o && typeof o === "object" ? (o as Record<string, unknown>) : {};
        return { title: (x.title as string) ?? "Tip", emoji: (x.emoji as string) ?? "•" };
      })
    : [
        { title: "Explore Together", emoji: "🌿" },
        { title: "Ask Great Questions", emoji: "❓" },
      ];
  return (
    <section className="py-4 px-4 bg-card rounded-xl border border-border w-full">
      <p className="font-display text-xs font-bold text-deep-sea mb-2 flex items-center gap-1">
        <span>{headingIcon}</span> {heading}
      </p>
      <div className="grid grid-cols-2 gap-1">
        {tips.map((t, i) => (
          <div key={i} className="rounded p-2 border border-border">
            <p className="font-display text-[9px] font-bold text-deep-sea flex items-center gap-1">
              <span>{t.emoji}</span> {t.title}
            </p>
          </div>
        ))}
      </div>
    </section>
  );
}

/** Quarter-End Celebration — course overview section */
export function CourseQuarterCelebrationPreview({ content }: { content?: ContentMap }) {
  const heading = content?.heading ?? "Quarter-End Celebration";
  const headingIcon = content?.headingIcon ?? "🎊";
  const body = (content?.body as string) ?? "At the end of each quarter, your child presents...";
  return (
    <section className="py-4 px-4 bg-card rounded-xl border border-border w-full">
      <p className="font-display text-xs font-bold text-deep-sea mb-2 flex items-center gap-1">
        <span>{headingIcon}</span> {heading}
      </p>
      <p className="text-foreground text-[10px] leading-relaxed line-clamp-3">{body}</p>
    </section>
  );
}

/** Quarter Hero — quarter detail header (e.g. /quarter/1 — The Nature Investigator) */
export function QuarterHeroPreview({ content }: { content?: ContentMap }) {
  const quarterLabel = (content?.quarterLabel as string) ?? "Quarter 1 · ...";
  const role = (content?.role as string) ?? "The Nature Investigator";
  const emoji = (content?.emoji as string) ?? "🌱";
  const color = (content?.color as string) ?? "moss";
  const bgClass = color === "deep-sea" ? "bg-deep-sea" : color === "valencia" ? "bg-valencia" : color === "sunflower" ? "bg-sunflower" : "bg-moss";
  return (
    <section className={`py-4 px-4 ${bgClass} rounded-xl text-milk w-full`}>
      <p className="font-display text-[9px] uppercase tracking-wider text-milk/70 mb-0.5">{quarterLabel}</p>
      <p className="font-display text-sm font-bold flex items-center gap-1">
        <span>{emoji}</span> {role}
      </p>
    </section>
  );
}

/** Big Idea — quarter Big Idea & Problem Context section */
export function BigIdeaPreview({ content }: { content?: ContentMap }) {
  const bigIdea = (content?.bigIdea as string) ?? "";
  const problemContext = (content?.problemContext as string) ?? "Our schoolyard is full of living things...";
  const color = (content?.color as string) ?? "moss";
  const textClass = color === "deep-sea" ? "text-deep-sea" : color === "valencia" ? "text-valencia" : color === "sunflower" ? "text-sunflower" : "text-moss";
  return (
    <section className="py-3 px-4 bg-card rounded-xl border border-border w-full">
      {bigIdea && <p className={`font-display text-[9px] uppercase tracking-wider ${textClass} mb-1`}>Big Idea</p>}
      {bigIdea && <p className="text-foreground text-xs mb-2 line-clamp-2">{bigIdea}</p>}
      <p className={`font-display text-[9px] uppercase tracking-wider ${textClass} mb-1`}>Problem Context</p>
      <p className="text-foreground text-xs italic line-clamp-2">"{problemContext}"</p>
    </section>
  );
}

/** How Each Course Sees This Quarter — multi-tab quarter courses + learning */
export function HowEachCourseSeesPreview({ content }: { content?: ContentMap }) {
  const title =
    (content?.lensesTitle as string) ||
    (content?.title as string) ||
    "How Each Course Sees This Quarter";
  const lenses = (Array.isArray(content?.lensesItems) ? content.lensesItems : content?.items) as ContentMap[] | undefined;
  const items = lenses ?? [];
  const coreCount = Array.isArray(content?.coreCourses) ? (content.coreCourses as unknown[]).length : 0;
  const dnaCount = Array.isArray(content?.dnaCourses) ? (content.dnaCourses as unknown[]).length : 0;
  return (
    <section className="py-3 px-4 bg-card rounded-xl border border-border w-full">
      <p className="font-display text-xs font-bold text-foreground mb-1">{title}</p>
      <p className="text-[10px] text-muted-foreground mb-1">Courses · Assessment · Evidence · Inquiry · Growth</p>
      <div className="flex flex-wrap gap-1.5 mt-1">
        {items.slice(0, 4).map((item: ContentMap, i: number) => (
          <span key={i} className="text-[10px] text-muted-foreground bg-muted/50 px-1.5 py-0.5 rounded">
            {(item.emoji as string) ?? "📚"} {(item.name as string) ?? "Course"}
          </span>
        ))}
        {items.length > 4 && <span className="text-[10px] text-muted-foreground">+{items.length - 4}</span>}
        <span className="text-[9px] px-1.5 py-0.5 rounded bg-muted">Core ({coreCount})</span>
        <span className="text-[9px] px-1.5 py-0.5 rounded bg-muted">DNA ({dnaCount})</span>
      </div>
    </section>
  );
}

/** Quarter Learning Tabs — Assessment, Evidence, Inquiry, Growth in one section */
export function QuarterLearningTabsPreview({ content }: { content?: ContentMap }) {
  const evidenceCount = Array.isArray(content?.evidenceItems) ? (content.evidenceItems as unknown[]).length : 0;
  const inquiryCount = Array.isArray(content?.deepInquiry) ? (content.deepInquiry as unknown[]).length : 0;
  return (
    <section className="py-3 px-4 bg-card rounded-xl border border-border w-full">
      <p className="font-display text-xs font-bold text-foreground mb-1">Assessment, Evidence & Growth</p>
      <p className="text-[10px] text-muted-foreground">Assessment · Evidence ({evidenceCount}) · Inquiry ({inquiryCount}) · Growth Portrait</p>
    </section>
  );
}

/** Quarter Courses — section with 3 tabs: How Each Course Sees | Core Courses | DNA Strand Courses */
export function QuarterCoursesPreview({ content }: { content?: ContentMap }) {
  const lensesCount = Array.isArray(content?.lensesItems) ? (content.lensesItems as unknown[]).length : 0;
  const coreCount = Array.isArray(content?.coreCourses) ? (content.coreCourses as unknown[]).length : 0;
  const dnaCount = Array.isArray(content?.dnaCourses) ? (content.dnaCourses as unknown[]).length : 0;
  return (
    <section className="py-3 px-4 bg-card rounded-xl border border-border w-full">
      <p className="font-display text-xs font-bold text-foreground mb-1">Quarter Courses</p>
      <p className="text-[10px] text-muted-foreground">How Each Course Sees · Core ({coreCount}) · DNA ({dnaCount})</p>
      <div className="flex gap-1.5 mt-1.5">
        <span className="text-[9px] px-1.5 py-0.5 rounded bg-muted">Lenses ({lensesCount})</span>
        <span className="text-[9px] px-1.5 py-0.5 rounded bg-muted">Core</span>
        <span className="text-[9px] px-1.5 py-0.5 rounded bg-muted">DNA</span>
      </div>
    </section>
  );
}

/** Combined Courses + Assessment, Evidence & Growth — two top-level tabs */
export function QuarterCoursesAndLearningPreview({ content }: { content?: ContentMap }) {
  const coursesLabel = (typeof content?.coursesTabLabel === "string" && content.coursesTabLabel) || "Courses (13)";
  const learningLabel = (typeof content?.learningTabLabel === "string" && content.learningTabLabel) || "Assessment, Evidence & Growth";
  const coreCount = Array.isArray(content?.coreCourses) ? (content.coreCourses as unknown[]).length : 0;
  const evidenceCount = Array.isArray(content?.evidenceItems) ? (content.evidenceItems as unknown[]).length : 0;
  return (
    <section className="py-3 px-4 bg-card rounded-xl border border-border w-full">
      <p className="font-display text-xs font-bold text-foreground mb-1">Courses (13) – Assessment, Evidence & Growth</p>
      <p className="text-[10px] text-muted-foreground">Tab 1: {coursesLabel} · Tab 2: {learningLabel}</p>
      <div className="flex gap-1.5 mt-1.5">
        <span className="text-[9px] px-1.5 py-0.5 rounded bg-muted">Courses ({coreCount})</span>
        <span className="text-[9px] px-1.5 py-0.5 rounded bg-muted">Evidence ({evidenceCount})</span>
      </div>
    </section>
  );
}

/** Orion STEM Schools — header with logo, label, title, subtitle (e.g. course/pbel-water) */
export function OrionSchoolHeaderPreview({ content }: { content?: ContentMap }) {
  const label = (content?.label as string) ?? "Orion STEM Schools";
  const title = (content?.title as string) ?? "Learning by Solving Real Problems";
  return (
    <section className="py-3 px-4 bg-card rounded-xl border border-border w-full flex items-center gap-3">
      <div className="w-8 h-8 rounded-lg bg-primary/20 shrink-0" />
      <div className="min-w-0">
        <p className="font-display text-[9px] uppercase tracking-wider text-primary">{label}</p>
        <p className="font-display text-xs font-bold text-foreground truncate">{title}</p>
      </div>
    </section>
  );
}

/** What is PBEL? — callout block (e.g. course/pbel-water) */
export function WhatIsPbelPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "What is PBEL?";
  const body = (content?.body as string) ?? "Problem‑Based Experiential Learning is where students learn by tackling real community challenges…";
  return (
    <section className="py-2 px-3 bg-primary/5 rounded-xl border-l-4 border-primary w-full">
      <p className="font-display text-[9px] uppercase tracking-wider text-primary mb-0.5">{title}</p>
      <p className="text-[9px] text-muted-foreground line-clamp-2">{body}</p>
    </section>
  );
}

/** Why Water? Why Now? — section with icon, title, body (e.g. course/pbel-water) */
export function WhyWaterWhyNowPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "Why Water? Why Now?";
  const icon = (content?.icon as string) ?? "🌊";
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary flex items-center gap-1 mb-0.5">
        <span>{icon}</span>
        {title}
      </p>
      <p className="text-[9px] text-muted-foreground line-clamp-2">Many families around the world cannot access safe water…</p>
    </section>
  );
}

/** How It Works — The PBEL Cycle (e.g. course/pbel-water) */
export function PbelCyclePreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "How It Works — The PBEL Cycle";
  const icon = (content?.icon as string) ?? "🔄";
  const steps = Array.isArray(content?.steps) ? content.steps : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary flex items-center gap-1 mb-1">
        <span>{icon}</span>
        {title}
      </p>
      <div className="flex gap-1 flex-wrap">
        {steps.slice(0, 5).map((s: { title?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">{s?.title ?? `Step ${i + 1}`}</span>
        ))}
        {steps.length === 0 && <span className="text-[8px] text-muted-foreground">5 steps</span>}
      </div>
    </section>
  );
}

/** What Your Child Might Do (e.g. course/pbel-water) */
export function WhatYourChildMightDoPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "What Your Child Might Do";
  const icon = (content?.icon as string) ?? "🎒";
  const bands = Array.isArray(content?.gradeBands) ? content.gradeBands : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary flex items-center gap-1 mb-1">
        <span>{icon}</span>
        {title}
      </p>
      <div className="flex gap-1 flex-wrap">
        {bands.slice(0, 4).map((b: { label?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">{b?.label ?? `Band ${i + 1}`}</span>
        ))}
        {bands.length === 0 && <span className="text-[8px] text-muted-foreground">4 bands + Safety & Success</span>}
      </div>
    </section>
  );
}

/** What Families Can Expect — and How You Can Help (e.g. course/pbel-water Page 2) */
export function FamiliesExpectHelpPreview({ content }: { content?: ContentMap }) {
  const label = (content?.label as string) ?? "Orion STEM Schools";
  const title = (content?.title as string) ?? "What Families Can Expect — and How You Can Help";
  return (
    <section className="py-3 px-4 bg-card rounded-xl border border-border w-full flex items-center gap-3">
      <div className="w-8 h-8 rounded-lg bg-primary/20 shrink-0" />
      <div className="min-w-0">
        <p className="font-display text-[9px] uppercase tracking-wider text-primary">{label}</p>
        <p className="font-display text-xs font-bold text-foreground truncate">{title}</p>
      </div>
    </section>
  );
}

/** Benefits for Your Child (e.g. course/pbel-water Page 2) */
export function BenefitsForYourChildPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "Benefits for Your Child";
  const icon = (content?.icon as string) ?? "🌟";
  const cards = Array.isArray(content?.cards) ? content.cards : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary flex items-center gap-1 mb-1">
        <span>{icon}</span>
        {title}
      </p>
      <div className="flex gap-1 flex-wrap">
        {cards.slice(0, 4).map((c: { title?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">{c?.title ?? `Card ${i + 1}`}</span>
        ))}
        {cards.length === 0 && <span className="text-[8px] text-muted-foreground">2 cards</span>}
      </div>
    </section>
  );
}

/** Our Service Learning Plan (IPARDE) (e.g. course/pbel-water Page 2) */
export function ServiceLearningIpardPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "Our Service Learning Plan (IPARDE)";
  const icon = (content?.icon as string) ?? "🔗";
  const steps = Array.isArray(content?.stepLabels) ? content.stepLabels : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary flex items-center gap-1 mb-1">
        <span>{icon}</span>
        {title}
      </p>
      <div className="flex gap-0.5 flex-wrap">
        {steps.slice(0, 6).map((s: string, i: number) => (
          <span key={i} className="text-[7px] px-1 py-0.5 rounded bg-muted">{s || `Step ${i + 1}`}</span>
        ))}
        {steps.length === 0 && <span className="text-[8px] text-muted-foreground">IPARDE bar + items</span>}
      </div>
    </section>
  );
}

/** Year Timeline at a Glance (e.g. course/pbel-water Page 2) */
export function YearTimelineAtGlancePreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "Year Timeline at a Glance";
  const icon = (content?.icon as string) ?? "📅";
  const cycles = Array.isArray(content?.cycles) ? content.cycles : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary flex items-center gap-1 mb-1">
        <span>{icon}</span>
        {title}
      </p>
      <div className="flex gap-1 flex-wrap">
        {cycles.slice(0, 4).map((c: { title?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted truncate max-w-[80px]">{c?.title ?? `Cycle ${i + 1}`}</span>
        ))}
        {cycles.length === 0 && <span className="text-[8px] text-muted-foreground">3 cycles + traits</span>}
      </div>
    </section>
  );
}

/** How Families Can Help (e.g. course/pbel-water Page 2) */
export function HowFamiliesCanHelpPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "How Families Can Help";
  const icon = (content?.icon as string) ?? "🏡";
  const columns = Array.isArray(content?.columns) ? content.columns : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary flex items-center gap-1 mb-1">
        <span>{icon}</span>
        {title}
      </p>
      <p className="text-[8px] text-muted-foreground">{columns.length} column(s)</p>
    </section>
  );
}

/** Deep Inquiry Questions (e.g. course/pbel-water Page 2) */
export function DeepInquiryQuestionsPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "Deep Inquiry Questions";
  const icon = (content?.icon as string) ?? "🔍";
  const questions = Array.isArray(content?.questions) ? content.questions : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary flex items-center gap-1 mb-1">
        <span>{icon}</span>
        {title}
      </p>
      <p className="text-[8px] text-muted-foreground">{questions.length} Q&amp;A</p>
    </section>
  );
}

/** Stay in the Loop (e.g. course/pbel-water Page 2 contact bar) */
export function StayInTheLoopPreview({ content }: { content?: ContentMap }) {
  const leftTitle = (content?.leftTitle as string) ?? "Stay in the Loop";
  const rightTitle = (content?.rightTitle as string) ?? "Questions?";
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full flex gap-2">
      <span className="text-[9px] font-bold text-primary truncate flex-1">{leftTitle}</span>
      <span className="text-[9px] font-bold text-primary truncate flex-1">{rightTitle}</span>
    </section>
  );
}

/** Parent-Facing Course Overview — full document from HTML builder */
export function ParentCourseOverviewPreview({ content }: { content?: ContentMap }) {
  return (
    <div className="max-h-[520px] overflow-auto rounded-xl border border-slate-200 bg-slate-50">
      <ParentCourseOverviewBlock content={content} />
    </div>
  );
}

/** Grade / Design hero with optional feature highlights. */
export function GradeHeroPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "Kindergarten";
  const subtitle = typeof content?.subtitle === "string" ? content.subtitle.trim() : "";
  const heroIcon = getGradeHeroIcon(content);
  const featureHighlights = getHeroFeatureHighlights(content);
  const competitionNavigation = getCompetitionNavigation(content);
  const buttons = getHeroButtons(content);
  const statistics = getHeroStatistics(content);
  const badges = Array.isArray(content?.badges)
    ? content.badges.filter((badge): badge is string => typeof badge === "string" && badge.trim() !== "")
    : [];
  const summaryItems = [
    ...featureHighlights,
    ...badges,
    ...statistics.map((statistic) => [statistic.value, statistic.label].filter(Boolean).join(" ")),
  ];
  return (
    <section className="py-2 px-3 bg-bark rounded-xl w-full text-center">
      <div className="flex items-center justify-center gap-1 mb-0.5">
        {heroIcon.image ? (
          <img src={heroIcon.image} alt="" className="w-3 h-3 object-contain" />
        ) : heroIcon.emoji ? (
          <span className="text-[9px]" aria-hidden>{heroIcon.emoji}</span>
        ) : null}
        <p className="font-display text-[9px] font-bold text-milk">{title}</p>
      </div>
      {subtitle && <p className={`text-[8px] text-milk/70 line-clamp-1 ${summaryItems.length > 0 ? "mb-1" : ""}`}>{subtitle}</p>}
      {summaryItems.length > 0 && (
        <div className="flex gap-1 flex-wrap justify-center">
          {summaryItems.slice(0, 3).map((item, index) => (
            <span key={`${item}-${index}`} className="text-[7px] px-1 py-0.5 rounded bg-milk/10 text-milk/80">{item}</span>
          ))}
        </div>
      )}
      {competitionNavigation.length > 0 ? (
        <div className="flex gap-1 flex-wrap justify-center mt-1">
          {competitionNavigation.slice(0, 3).map((item, index) => (
            <span
              key={item.id || index}
              className={`text-[7px] px-1.5 py-0.5 rounded-full ${
                index === 0 ? "bg-sunflower text-bark font-bold" : "bg-milk/10 text-milk/70"
              }`}
            >
              {item.icon ? `${item.icon} ` : ""}
              {item.label}
            </span>
          ))}
        </div>
      ) : buttons.length > 0 ? (
        <p className="text-[7px] text-milk/50 mt-1">{buttons.length} button(s)</p>
      ) : null}
    </section>
  );
}

/** Impact Kaleidoscope */
export function ImpactKaleidoscopePreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "9 Lenses of Inquiry, Design & Impact";
  const lenses = Array.isArray(content?.lenses) ? content.lenses : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1">{title}</p>
      <div className="flex gap-1 flex-wrap">
        {lenses.slice(0, 5).map((l: { emoji?: string; label?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">{l?.emoji ?? "•"} {l?.label ?? `Lens ${i + 1}`}</span>
        ))}
        {lenses.length === 0 && <span className="text-[8px] text-muted-foreground">9 lenses + mirrors</span>}
      </div>
    </section>
  );
}

/** Three Journey Phases */
export function ThreeJourneyPhasesPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "Three Phases of the Journey";
  const phases = Array.isArray(content?.phases) ? content.phases : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1">{title}</p>
      <div className="flex gap-1 flex-wrap">
        {phases.slice(0, 3).map((p: { emoji?: string; name?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">{p?.emoji ?? "•"} {p?.name ?? `Phase ${i + 1}`}</span>
        ))}
        {phases.length === 0 && <span className="text-[8px] text-muted-foreground">3 phases</span>}
      </div>
    </section>
  );
}

/** Cross-Cutting Mirrors */
export function CrossCuttingMirrorsPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "The Mirrors: Cross-Cutting Overlays";
  const mirrors = Array.isArray(content?.mirrors) ? content.mirrors : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1 truncate">{title}</p>
      <div className="flex gap-1 flex-wrap">
        {mirrors.slice(0, 3).map((m: { emoji?: string; label?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">{m?.emoji ?? "•"} {m?.label ?? `Mirror ${i + 1}`}</span>
        ))}
        {mirrors.length === 0 && <span className="text-[8px] text-muted-foreground">3 mirrors</span>}
      </div>
    </section>
  );
}

/** Annual Flow Quarters */
export function AnnualFlowQuartersPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "Turning the Kaleidoscope: The Annual Flow";
  const quarters = Array.isArray(content?.quarters) ? content.quarters : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1 truncate">{title}</p>
      <div className="flex gap-1 flex-wrap">
        {quarters.slice(0, 4).map((q: { emoji?: string; title?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted truncate max-w-[80px]">{q?.emoji ?? "•"} {q?.title ?? `Q${i + 1}`}</span>
        ))}
        {quarters.length === 0 && <span className="text-[8px] text-muted-foreground">4 quarters</span>}
      </div>
    </section>
  );
}

/** Diverge Converge Viz */
export function DivergeConvergeVizPreview({ content }: { content?: ContentMap }) {
  const microLabel = (content?.microLabel as string) ?? "Micro cycle";
  const macroLabel = (content?.macroLabel as string) ?? "Macro cycle";
  const microSteps = Array.isArray(content?.microSteps) ? content.microSteps : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1">{microLabel} · {macroLabel}</p>
      <div className="flex gap-1 flex-wrap">
        {microSteps.slice(0, 4).map((s: { emoji?: string; label?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">{s?.emoji ?? "•"} {s?.label ?? `Step ${i + 1}`}</span>
        ))}
        {microSteps.length === 0 && <span className="text-[8px] text-muted-foreground">Diverge / converge viz</span>}
      </div>
    </section>
  );
}

/** Squad Roles */
export function SquadRolesPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "The Squads: Teaming & Roles";
  const roles = Array.isArray(content?.roles) ? content.roles : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1 truncate">{title}</p>
      <div className="flex gap-1 flex-wrap">
        {roles.slice(0, 5).map((r: { emoji?: string; role?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">{r?.emoji ?? "•"} {r?.role ?? `Role ${i + 1}`}</span>
        ))}
        {roles.length === 0 && <span className="text-[8px] text-muted-foreground">5 roles</span>}
      </div>
    </section>
  );
}

/** Grade Band Entrepreneurship */
export function GradeBandEntrepreneurshipPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "Disciplined Entrepreneurship by Grade Band";
  const bands = Array.isArray(content?.gradeBands) ? content.gradeBands : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1 truncate">{title}</p>
      <div className="flex gap-1 flex-wrap">
        {bands.slice(0, 4).map((b: { band?: string; label?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">{b?.band ?? `Band ${i + 1}`}{b?.label ? ` · ${b.label}` : ""}</span>
        ))}
        {bands.length === 0 && <span className="text-[8px] text-muted-foreground">4 grade bands</span>}
      </div>
    </section>
  );
}

/** Deliverables Evidence */
export function DeliverablesEvidencePreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "Deliverables & Evidence of Impact";
  const deliverables = Array.isArray(content?.deliverables) ? content.deliverables : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1 truncate">{title}</p>
      <div className="flex gap-1 flex-wrap">
        {deliverables.slice(0, 4).map((d: { emoji?: string; title?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">{d?.emoji ?? "•"} {d?.title ?? `Item ${i + 1}`}</span>
        ))}
        {deliverables.length === 0 && <span className="text-[8px] text-muted-foreground">6 deliverables</span>}
      </div>
    </section>
  );
}

/** Club Category Grid */
export function ClubCategoryGridPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "Writing & Literature";
  const emoji = (content?.emoji as string) ?? "✍️";
  const cards = Array.isArray(content?.cards) ? content.cards : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1 truncate">{emoji} {title}</p>
      <div className="flex gap-1 flex-wrap">
        {cards.slice(0, 5).map((c: { name?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">{c?.name ?? `Card ${i + 1}`}</span>
        ))}
        {cards.length === 0 && <span className="text-[8px] text-muted-foreground">5 cards</span>}
      </div>
    </section>
  );
}

/** Steering Committees Grid */
export function SteeringCommitteesGridPreview({ content }: { content?: ContentMap }) {
  const committees = Array.isArray(content?.committees)
    ? content.committees
    : Array.isArray(content?.cards)
      ? content.cards
      : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1 truncate">🧭 Steering Committees</p>
      <div className="flex gap-1 flex-wrap">
        {committees.slice(0, 6).map((c: { badgeLabel?: string; name?: string; emoji?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">
            {c?.emoji ? `${c.emoji} ` : ""}
            {c?.badgeLabel ?? c?.name ?? `Committee ${i + 1}`}
          </span>
        ))}
        {committees.length === 0 && (
          <span className="text-[8px] text-muted-foreground">9 colored committee cards</span>
        )}
      </div>
    </section>
  );
}

/** SWOT Analysis Grid */
export function SwotAnalysisGridPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "SWOT Analysis";
  const quadrants = Array.isArray(content?.quadrants) ? content.quadrants : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1 truncate">{title}</p>
      <div className="flex gap-1 flex-wrap">
        {quadrants.slice(0, 4).map((q: { emoji?: string; label?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">
            {q?.emoji ? `${q.emoji} ` : ""}
            {q?.label ?? `Quadrant ${i + 1}`}
          </span>
        ))}
        {quadrants.length === 0 && <span className="text-[8px] text-muted-foreground">4 SWOT quadrants</span>}
      </div>
    </section>
  );
}

/** Root Cause Fishbone */
export function RootCauseFishbonePreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "Root Cause Analysis";
  const branches = Array.isArray(content?.branches) ? content.branches : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1 truncate">{title}</p>
      <div className="flex gap-1 flex-wrap">
        {branches.slice(0, 6).map((b: { emoji?: string; category?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">
            {b?.emoji ? `${b.emoji} ` : ""}
            {b?.category ?? `Branch ${i + 1}`}
          </span>
        ))}
        {branches.length === 0 && <span className="text-[8px] text-muted-foreground">6 fishbone branches</span>}
      </div>
    </section>
  );
}

/** Progress How It Works */
export function ProgressHowItWorksPreview({ content }: { content?: ContentMap }) {
  const title = (content?.whyTitle as string) ?? "Why Mastery, Not Grades?";
  const cards = Array.isArray(content?.whyCards) ? content.whyCards : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1 truncate">📖 {title}</p>
      <div className="flex gap-1 flex-wrap">
        {cards.slice(0, 3).map((card: { emoji?: string; title?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">
            {card?.emoji ? `${card.emoji} ` : ""}
            {card?.title ?? `Card ${i + 1}`}
          </span>
        ))}
        {cards.length === 0 && (
          <span className="text-[8px] text-muted-foreground">Mastery overview sections</span>
        )}
      </div>
    </section>
  );
}

/** Progress Sample Report */
export function ProgressSampleReportPreview({ content }: { content?: ContentMap }) {
  const title = (content?.reportTitle as string) ?? "Sample Mastery Report";
  const student = (content?.studentName as string) ?? "Sample student";
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1 truncate">📄 {title}</p>
      <p className="text-[8px] text-muted-foreground truncate">{student} · tables, spiderweb, narratives</p>
    </section>
  );
}

/** Portrait Goals Grid */
export function PortraitGoalsGridPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "Portrait of the Learner Goals";
  const goals = Array.isArray(content?.goals) ? content.goals : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1 truncate">{title}</p>
      <div className="flex gap-1 flex-wrap">
        {goals.slice(0, 6).map((g: { emoji?: string; title?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">
            {g?.emoji ? `${g.emoji} ` : ""}
            {g?.title ?? `Goal ${i + 1}`}
          </span>
        ))}
        {goals.length === 0 && <span className="text-[8px] text-muted-foreground">6 PoL goals</span>}
      </div>
    </section>
  );
}

/** Growth Radar Chart */
export function GrowthRadarChartPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "Exposure vs. Current Level";
  const quarters = Array.isArray(content?.quarters) ? content.quarters : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1 truncate">{title}</p>
      <div className="flex gap-1 flex-wrap">
        {quarters.slice(0, 4).map((q: { label?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">
            {q?.label ?? `Q${i + 1}`}
          </span>
        ))}
        {quarters.length === 0 && <span className="text-[8px] text-muted-foreground">4 quarter radar charts</span>}
      </div>
    </section>
  );
}

/** Orion / Public Competitions — shared month timeline + flexible grid */
export function OrionCompetitionsPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "Orion Competitions";
  const emoji = (content?.emoji as string) ?? "🏫";
  const competitions = Array.isArray(content?.competitions) ? content.competitions : [];
  const flexibleCount = competitions.filter((c: { month?: string }) => !c?.month).length;
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1 truncate">{emoji} {title}</p>
      <div className="flex gap-1 flex-wrap">
        {competitions.slice(0, 5).map((c: { title?: string; name?: string; month?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">
            {c?.title ?? c?.name ?? `Comp ${i + 1}`}
            {c?.month ? ` · ${c.month}` : " · Flexible"}
          </span>
        ))}
        {competitions.length === 0 && <span className="text-[8px] text-muted-foreground">Timeline + flexible competitions</span>}
        {flexibleCount > 0 && competitions.length > 5 ? (
          <span className="text-[8px] text-muted-foreground">+{flexibleCount} flexible</span>
        ) : null}
      </div>
    </section>
  );
}

/** Public Competitions — same timeline preview with public defaults */
export function PublicCompetitionsPreview({ content }: { content?: ContentMap }) {
  return (
    <OrionCompetitionsPreview
      content={{
        title: "Public Competitions",
        emoji: "🌍",
        ...(content ?? {}),
      }}
    />
  );
}

/** Competition Tabs — legacy nested panels (navigation moved to Grade Hero) */
export function CompetitionTabsPreview({ content }: { content?: ContentMap }) {
  const tabs = Array.isArray(content?.tabs) ? content.tabs : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-muted-foreground mb-1 truncate">Competition Tabs (legacy)</p>
      <p className="text-[8px] text-muted-foreground">
        {tabs.length > 0
          ? `${tabs.length} nested panel(s) — use Grade Hero Competition Navigation`
          : "Use Grade Hero Competition Navigation + Orion/Public blocks"}
      </p>
    </section>
  );
}

/** Design Impact Summit */
export function DesignImpactSummitPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "Design to Impact Summit";
  const days = Array.isArray(content?.days) ? content.days : [];
  return (
    <section className="py-2 px-3 rounded-xl border border-border w-full">
      <p className="font-display text-[9px] text-primary mb-1 truncate">{title}</p>
      <div className="flex gap-1 flex-wrap">
        {days.slice(0, 3).map((d: { emoji?: string; day?: string; title?: string }, i: number) => (
          <span key={i} className="text-[8px] px-1.5 py-0.5 rounded bg-muted">{d?.emoji ?? "•"} {d?.day ?? `Day ${i + 1}`}</span>
        ))}
        {days.length === 0 && <span className="text-[8px] text-muted-foreground">3 days + invitees</span>}
      </div>
    </section>
  );
}

/** Closing Vision */
export function ClosingVisionPreview({ content }: { content?: ContentMap }) {
  const title = (content?.title as string) ?? "Where Learning Meets Legacy";
  const traits = Array.isArray(content?.traits) ? content.traits : [];
  return (
    <section className="py-2 px-3 bg-bark rounded-xl w-full text-center">
      <p className="font-display text-[9px] font-bold text-milk mb-0.5">{title}</p>
      <div className="flex gap-1 flex-wrap justify-center">
        {traits.slice(0, 3).map((t: unknown, i: number) => (
          <span key={i} className="text-[7px] px-1 py-0.5 rounded bg-milk/10 text-milk/80">{typeof t === "string" ? t : `Trait ${i + 1}`}</span>
        ))}
        {traits.length === 0 && <span className="text-[8px] text-milk/50">Vision + traits</span>}
      </div>
    </section>
  );
}

/** Curriculum Hero — hero section for /grade/kg/curriculum (Healthy Habitats & Sun-Safe Spaces) */
export function CurriculumHeroPreview({ content }: { content?: ContentMap }) {
  const label = content?.label ?? "Orion STEM Schools · 2026–2027";
  const title = content?.title ?? "Healthy Habitats & Sun-Safe Spaces";
  const subtitle = content?.subtitle ?? "Comprehensive Family Guide · Kindergarten";
  return (
    <section className="py-6 px-4 bg-bark rounded-xl text-center">
      <p className="font-display text-[10px] tracking-widest uppercase text-mist mb-1">{label}</p>
      <h2 className="font-display text-lg font-bold text-milk mb-1">{title}</h2>
      <p className="font-display text-xs text-salmon">{subtitle}</p>
    </section>
  );
}

const PREVIEW_MAP: Record<string, (props: { content?: ContentMap }) => JSX.Element> = {
  hero: HeroPreview,
  "dimension-detail": DimensionDetailPreview,
  "grade-family-guides": GradeFamilyGuidesPreview,
  "grade-family-guides-api": GradeFamilyGuidesPreview,
  "grade-hero": GradeHeroPreview,
  "curriculum-hero": CurriculumHeroPreview,
  "essential-question": EssentialQuestionPreview,
  "core-courses": CoreCoursesPreview,
  "dna-strands": DnaStrandsPreview,
  "year-at-glance": YearAtGlancePreview,
  "year-long-story": YearLongStoryPreview,
  "developing-the-whole-child": DevelopingWholeChildPreview,
  "finks-taxonomy": FinksTaxonomyPreview,
  "one-project-not-13-tests": OneProjectNot13TestsPreview,
  "curriculum-architecture": CurriculumArchitecturePreview,
  "pbel": PbelPreview,
  "course-hero": CourseHeroPreview,
  "why-this-course-matters": WhyThisCourseMattersPreview,
  "how-connects": HowConnectsPreview,
  "smarter-assessment": SmarterAssessmentPreview,
  "what-your-child-will-gain": WhatYourChildWillGainPreview,
  "course-portrait": CoursePortraitPreview,
  "course-core-skills": CourseCoreSkillsPreview,
  "course-journey": CourseJourneyPreview,
  "course-what-they-create": CourseWhatTheyCreatePreview,
  "course-inquiry-questions": CourseInquiryQuestionsPreview,
  "course-support-at-home": CourseSupportAtHomePreview,
  "course-quarter-celebration": CourseQuarterCelebrationPreview,
  "quarter-hero": QuarterHeroPreview,
  "big-idea": BigIdeaPreview,
  "how-each-course-sees": HowEachCourseSeesPreview,
  "quarter-learning-tabs": HowEachCourseSeesPreview,
  "quarter-courses": HowEachCourseSeesPreview,
  "quarter-courses-and-learning": HowEachCourseSeesPreview,
  "orion-school-header": OrionSchoolHeaderPreview,
  "what-is-pbel": WhatIsPbelPreview,
  "why-water-why-now": WhyWaterWhyNowPreview,
  "pbel-cycle": PbelCyclePreview,
  "what-your-child-might-do": WhatYourChildMightDoPreview,
  "families-expect-help": FamiliesExpectHelpPreview,
  "benefits-for-your-child": BenefitsForYourChildPreview,
  "service-learning-ipard": ServiceLearningIpardPreview,
  "year-timeline-at-glance": YearTimelineAtGlancePreview,
  "how-families-can-help": HowFamiliesCanHelpPreview,
  "deep-inquiry-questions": DeepInquiryQuestionsPreview,
  "stay-in-the-loop": StayInTheLoopPreview,
  "parent-course-overview": ParentCourseOverviewPreview,
  "design-to-impact-hero": GradeHeroPreview,
  "impact-kaleidoscope": ImpactKaleidoscopePreview,
  "three-journey-phases": ThreeJourneyPhasesPreview,
  "cross-cutting-mirrors": CrossCuttingMirrorsPreview,
  "annual-flow-quarters": AnnualFlowQuartersPreview,
  "diverge-converge-viz": DivergeConvergeVizPreview,
  "squad-roles": SquadRolesPreview,
  "grade-band-entrepreneurship": GradeBandEntrepreneurshipPreview,
  "deliverables-evidence": DeliverablesEvidencePreview,
  "design-impact-summit": DesignImpactSummitPreview,
  "closing-vision": ClosingVisionPreview,
  "club-category-grid": ClubCategoryGridPreview,
  "steering-committees-grid": SteeringCommitteesGridPreview,
  "swot-analysis-grid": SwotAnalysisGridPreview,
  "root-cause-fishbone": RootCauseFishbonePreview,
  "portrait-goals-grid": PortraitGoalsGridPreview,
  "growth-radar-chart": GrowthRadarChartPreview,
  "orion-competitions": OrionCompetitionsPreview,
  "public-competitions": PublicCompetitionsPreview,
  "competition-tabs": CompetitionTabsPreview,
  "progress-how-it-works": ProgressHowItWorksPreview,
  "progress-sample-report": ProgressSampleReportPreview,
  footer: FooterPreview,
  "pbel-guide-footer": PbelGuideFooterPreview,
};

export function ComponentPreviewBySlug({ slug, content }: { slug: string; content?: Record<string, unknown> }) {
  const Preview = PREVIEW_MAP[slug];
  if (!Preview) return <span className="text-muted-foreground text-sm italic">No preview</span>;
  const contentMap = resolvePreviewContent((content ?? {}) as Record<string, unknown>, { blockSlug: slug }) as ContentMap;
  return (
    <div className="component-preview-wrap">
      <Preview content={contentMap} />
    </div>
  );
}
