import { motion } from "framer-motion";
import { staggerContainer, fadeUpItem } from "@/components/PageTransition";
import { BrandscapeShell } from "@/components/BrandscapeShell";

type Content = Record<string, unknown>;

function str(c: unknown): string {
  return typeof c === "string" ? c : "";
}

const defaultHeading = "What Your Child Will Create";
const defaultHeadingIcon = "🎨";
const defaultItems = [
  { emoji: "📓", title: "Observation Journals", desc: "Detailed records of scientific findings" },
  { emoji: "📊", title: "Data Charts & Graphs", desc: "Visual representations of collected data" },
  { emoji: "🗺️", title: "System Models", desc: "Maps and models showing ecosystem connections" },
];

type CreateItem = { emoji: string; title: string; desc: string };

function ensureCreateItem(raw: unknown): CreateItem {
  const o = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
  return {
    emoji: str(o.emoji).trim() || "•",
    title: str(o.title).trim() || "Item",
    desc: str(o.desc).trim() || "",
  };
}

function ensureCreateItems(raw: unknown): CreateItem[] {
  if (!Array.isArray(raw) || raw.length === 0) return defaultItems;
  return raw.slice(0, 24).map(ensureCreateItem);
}

export function CourseWhatTheyCreateBlock({ content }: { content?: Content }) {
  const heading = str(content?.heading).trim() || defaultHeading;
  const headingIcon = str(content?.headingIcon).trim() || defaultHeadingIcon;
  const items = ensureCreateItems(content?.items);
  const itemsKey = JSON.stringify(items);

  return (
    <BrandscapeShell variant="content" paddingY>
    <motion.section
      className="w-full min-w-0"
      initial={{ opacity: 0, y: 20 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true }}
      transition={{ duration: 0.5 }}
    >
      <h2 className="font-display text-xl font-bold text-deep-sea mb-4 flex items-center gap-2 border-b-2 border-deep-sea pb-2">
        <span className="text-2xl">{headingIcon}</span> {heading}
      </h2>
      <motion.div
        key={itemsKey}
        className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4"
        variants={staggerContainer}
        initial="initial"
        animate="animate"
      >
        {items.map((item, index) => (
          <motion.div
            key={`${index}-${item.title}`}
            variants={fadeUpItem}
            className="bg-card border-2 border-deep-sea rounded-xl p-4 text-center"
          >
            <span className="text-3xl block mb-2">{item.emoji}</span>
            <p className="font-display text-xs font-bold text-foreground mb-1">{item.title}</p>
            <p className="text-muted-foreground text-[0.7rem]">{item.desc}</p>
          </motion.div>
        ))}
      </motion.div>
    </motion.section>
    </BrandscapeShell>
  );
}
