import { motion } from "framer-motion";
import { BrandscapeShell } from "@/components/BrandscapeShell";

type Content = Record<string, unknown>;

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

const defaultHeading = "Simple Ways to Support at Home";
const defaultHeadingIcon = "🏠";
const defaultTips = [
  { title: "Explore Together", emoji: "🌿", items: ["Go on nature walks and observe what lives around you", "Keep a family nature journal", "Visit gardens, parks, or nature centers"] },
  { title: "Ask Great Questions", emoji: "❓", items: ["'Why do you think that is?' instead of giving answers", "Encourage wondering and hypothesizing", "Model curiosity about everyday phenomena"] },
];

type TipItem = { title: string; emoji: string; items: string[] };

function ensureTip(raw: unknown): TipItem {
  const o = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
  const rawItems = o.items;
  const items = Array.isArray(rawItems)
    ? rawItems.filter((x): x is string => typeof x === "string").map((s) => s.trim()).filter(Boolean)
    : [];
  return {
    title: str(o.title).trim() || "Tip",
    emoji: str(o.emoji).trim() || "•",
    items: items.length ? items : ["Item"],
  };
}

function ensureTips(raw: unknown): TipItem[] {
  if (!Array.isArray(raw) || raw.length === 0) return defaultTips;
  return raw.slice(0, 12).map(ensureTip);
}

export function CourseSupportAtHomeBlock({ content }: { content?: Content }) {
  const heading = str(content?.heading).trim() || defaultHeading;
  const headingIcon = str(content?.headingIcon).trim() || defaultHeadingIcon;
  const tips = ensureTips(content?.tips);

  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>
      <div className="grid md:grid-cols-2 gap-4">
        {tips.map((tip) => (
          <div
            key={tip.title}
            className="bg-card rounded-xl p-5 border border-border hover:border-deep-sea transition-colors"
          >
            <h3 className="font-display text-sm font-bold text-deep-sea mb-2 flex items-center gap-2">
              <span className="text-xl">{tip.emoji}</span> {tip.title}
            </h3>
            <ul className="space-y-1.5">
              {tip.items.map((item, i) => (
                <li key={i} className="text-muted-foreground text-sm flex items-start gap-2">
                  <span className="text-deep-sea font-bold text-xs mt-0.5">✓</span> {item}
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
    </motion.section>
    </BrandscapeShell>
  );
}
