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

type Content = Record<string, unknown>;

export type SquadRoleItem = {
  role: string;
  emoji: string;
  desc: string;
};

const defaultTitle = "👥 The Squads: Teaming & Roles";
const defaultSubtitle = "Roles rotate each microcycle to ensure balanced growth.";

const defaultRoles: SquadRoleItem[] = [
  { role: "Team Lead", emoji: "👑", desc: "Facilitates sprints and keeps the squad on track" },
  { role: "Storyteller", emoji: "📝", desc: "Documents journey maps, writes narratives for exhibition" },
  { role: "Community Liaison", emoji: "🤝", desc: "Manages partner relationships and empathy interviews" },
  { role: "Prototype Engineer", emoji: "🔧", desc: "Leads builds, CAD, code, and physical prototypes" },
  { role: "Data Analyst", emoji: "📊", desc: "Tracks baselines, collects metrics, builds evidence" },
];

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

function parseRoles(content: Content | undefined): SquadRoleItem[] {
  const raw = content?.roles;
  if (!Array.isArray(raw) || raw.length === 0) return defaultRoles;
  return raw
    .filter((x): x is Record<string, unknown> => x != null && typeof x === "object")
    .map((o) => ({
      role: str(o.role).trim() || "Role",
      emoji: str(o.emoji).trim() || "•",
      desc: str(o.desc).trim() || "",
    }));
}

export function SquadRolesBlock({ content }: { content?: Content }) {
  const title = str(content?.title).trim() || defaultTitle;
  const subtitle = str(content?.subtitle).trim() || defaultSubtitle;
  const roles = parseRoles(content);

  return (
    <section className="py-12 bg-background">
      <div className="container mx-auto px-6 max-w-5xl">
        <motion.h2
          className="font-display text-xl md:text-2xl font-bold text-foreground text-center mb-2"
          initial={{ opacity: 0 }}
          whileInView={{ opacity: 1 }}
          viewport={{ once: true }}
        >
          {title}
        </motion.h2>
        <p className="text-center text-muted-foreground text-sm mb-8">{subtitle}</p>
        <motion.div
          className="grid grid-cols-2 md:grid-cols-5 gap-3"
          variants={staggerContainer}
          initial="initial"
          whileInView="animate"
          viewport={{ once: true }}
        >
          {roles.map((r) => (
            <motion.div
              key={r.role}
              variants={fadeUpItem}
              className="bg-card rounded-xl p-4 text-center border border-border hover:border-valencia/30 transition-colors"
            >
              <span className="text-2xl block mb-2">{r.emoji}</span>
              <h3 className="font-display text-xs font-bold text-foreground mb-1">{r.role}</h3>
              <p className="text-muted-foreground text-[10px] leading-relaxed">{r.desc}</p>
            </motion.div>
          ))}
        </motion.div>
      </div>
    </section>
  );
}
