import { Link } from "react-router-dom";
import { motion } from "framer-motion";
import { staggerContainer, fadeUpItem } from "@/components/PageTransition";
import { getCoreCourses } from "@/data/courseOverviews";

type Content = Record<string, unknown>;

export interface CoreCourseItem {
  name: string;
  emoji: string;
  tagline: string;
  slug: string;
  /** Link label, e.g. "Learn More →". Default "Learn More →" */
  linkText?: string;
  /** Full URL for the link. If empty, uses /course/{slug} */
  linkHref?: string;
}

const defaultHeading = "The 9 Core Courses";
const defaultTitle = "Integrated Learning Across Every Subject";
const defaultSubtitle = "Click any course to see how it develops your child across all grade levels.";

function parseCourses(content: Content | undefined): CoreCourseItem[] {
  const raw = content?.courses;
  if (!Array.isArray(raw) || raw.length === 0) {
    return getCoreCourses().map((c) => ({
      name: c.name,
      emoji: c.emoji,
      tagline: c.tagline,
      slug: c.slug,
    }));
  }
  return raw
    .filter((x): x is Record<string, unknown> => x != null && typeof x === "object")
    .map((o) => ({
      name: typeof o.name === "string" ? o.name : "",
      emoji: typeof o.emoji === "string" ? o.emoji : "•",
      tagline: typeof o.tagline === "string" ? o.tagline : "",
      slug: typeof o.slug === "string" ? o.slug : "#",
      linkText: typeof o.linkText === "string" ? o.linkText : undefined,
      linkHref: typeof o.linkHref === "string" ? o.linkHref : undefined,
    }))
    .filter((c) => c.name || c.slug !== "#");
}

export function CoreCoursesBlock({ content }: { content?: Content }) {
  const heading = (content?.heading as string) ?? defaultHeading;
  const title = (content?.title as string) ?? defaultTitle;
  const subtitle = (content?.subtitle as string) ?? defaultSubtitle;
  const courses = parseCourses(content);

  return (
    <section className="py-16 md:py-24 bg-background">
      <div className="container mx-auto px-6">
        <motion.div
          className="text-center mb-12"
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.5 }}
        >
          <p className="font-display text-xs tracking-[0.2em] uppercase text-deep-sea mb-2">
            {heading}
          </p>
          <h2 className="font-display text-3xl md:text-4xl font-bold text-foreground">
            {title}
          </h2>
          <p className="text-muted-foreground mt-3 max-w-2xl mx-auto">
            {subtitle}
          </p>
        </motion.div>
        <motion.div
          className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-3 gap-4 max-w-4xl mx-auto"
          variants={staggerContainer}
          initial="initial"
          whileInView="animate"
          viewport={{ once: true, margin: "-80px" }}
        >
          {courses.map((course, idx) => {
            const href = course.linkHref?.trim() || `/course/${course.slug}`;
            const linkLabel = course.linkText?.trim() || "Learn More →";
            const isExternal = href.startsWith("http://") || href.startsWith("https://");
            const linkClass = "group block bg-card rounded-xl p-5 border border-border hover:border-primary/30 transition-all hover:shadow-lg text-center";
            const inner = (
              <>
                  <motion.span
                    className="text-3xl block mb-2"
                    whileHover={{ rotate: [0, -10, 10, 0] }}
                    transition={{ duration: 0.4 }}
                  >
                    {course.emoji}
                  </motion.span>
                  <h3 className="font-display text-sm font-bold text-foreground mb-1">
                    {course.name}
                  </h3>
                  <p className="text-muted-foreground text-xs line-clamp-2">
                    {course.tagline ? course.tagline.split("—")[0].trim() : ""}
                  </p>
                  <span className="font-display text-xs text-deep-sea font-semibold mt-2 block group-hover:translate-x-1 transition-transform">
                    {linkLabel}
                  </span>
              </>
            );
            return (
              <motion.div
                key={`${course.slug}-${idx}`}
                variants={fadeUpItem}
                whileHover={{ y: -4 }}
                transition={{ type: "spring", stiffness: 400, damping: 20 }}
              >
                {isExternal ? (
                  <a href={href} className={linkClass} target="_blank" rel="noopener noreferrer">
                    {inner}
                  </a>
                ) : (
                  <Link to={href} className={linkClass}>
                    {inner}
                  </Link>
                )}
              </motion.div>
            );
          })}
        </motion.div>
      </div>
    </section>
  );
}
