import { BrandscapeShell } from "@/components/BrandscapeShell";
type Content = Record<string, unknown>;

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

function arr(c: unknown): string[] {
  if (!Array.isArray(c)) return [];
  return c.filter((x): x is string => typeof x === "string");
}

type Card = { title?: string; color?: string; items?: string[] };

function parseCards(raw: unknown): Card[] {
  if (!Array.isArray(raw)) return defaultCards;
  return raw.slice(0, 6).map((b) => {
    const x = b as Card;
    return { title: str(x?.title).trim(), color: str(x?.color).trim() || "primary", items: arr(x?.items) };
  });
}

const defaultCards: Card[] = [
  { title: "Academic Growth", color: "primary", items: ["Applies science & math to real measurements and data", "Builds literacy through research and clear communication", "Introduces coding, sensors, and design skills"] },
  { title: "Life & Leadership", color: "accent", items: ["Teamwork with rotating roles (lead, builder, data, liaison)", "Growth mindset through testing and iteration", "Community contribution and empathy"] },
];

const defaultTitle = "Benefits for Your Child";
const defaultIcon = "🌟";

const borderTopClass: Record<string, string> = {
  primary: "border-t-primary",
  accent: "border-t-accent",
  moss: "border-t-moss",
  sunflower: "border-t-sunflower",
  salmon: "border-t-salmon",
};

const BulletItem = ({ children }: { children: React.ReactNode }) => (
  <li className="relative pl-5 py-0.5 text-[12.5px] leading-relaxed text-muted-foreground before:content-[''] before:absolute before:left-0 before:top-[9px] before:w-1.5 before:h-1.5 before:rounded-full before:bg-primary">
    {children}
  </li>
);

export function BenefitsForYourChildBlock({ content }: { content?: Content }) {
  const title = str(content?.title).trim() || defaultTitle;
  const icon = str(content?.icon).trim() || defaultIcon;
  const cards = parseCards(content?.cards);

  return (
    <BrandscapeShell variant="narrow">
    <div className="mt-6">
      <h2 className="font-display text-[17px] font-normal text-primary flex items-center gap-2 mb-2">
        <span className="text-base opacity-70">{icon}</span>
        {title}
      </h2>
      <div className="grid md:grid-cols-2 gap-3.5">
        {cards.map((card, idx) => (
          <div
            key={idx}
            className={`border border-border rounded-[10px] p-3.5 border-t-[3px] hover:shadow-md transition-shadow ${borderTopClass[card.color ?? "primary"] ?? "border-t-primary"}`}
          >
            {card.title && <h3 className="text-[13px] font-bold text-primary mb-1">{card.title}</h3>}
            <ul className="list-none">
              {(card.items ?? []).map((item, i) => (
                <BulletItem key={i}>{item}</BulletItem>
              ))}
            </ul>
          </div>
        ))}
      </div>
    </div>
    </BrandscapeShell>
  );
}
