import { useState, useMemo } from "react";
import { Link } from "react-router-dom";
import { motion, AnimatePresence } from "framer-motion";
import { PageTransition } from "@/components/PageTransition";
import { TopNav } from "@/components/TopNav";
import { portraitDimensions, getTraitsForDimension, grades } from "@/data/portraitData";
import { courseOverviews } from "@/data/courseOverviews";
import sparkHorse from "@/assets/spark-horse.png";
import orionLogo from "@/assets/orion-logo.svg";

const dimensionColors: Record<string, string> = {
  valencia: "bg-valencia",
  sunflower: "bg-sunflower",
  "deep-sea": "bg-deep-sea",
  moss: "bg-moss",
  mist: "bg-mist",
  salmon: "bg-salmon",
};

const dimensionBorderColors: Record<string, string> = {
  valencia: "border-valencia",
  sunflower: "border-sunflower",
  "deep-sea": "border-deep-sea",
  moss: "border-moss",
  mist: "border-mist",
  salmon: "border-salmon",
};

const dimensionTextColors: Record<string, string> = {
  valencia: "text-valencia",
  sunflower: "text-sunflower",
  "deep-sea": "text-deep-sea",
  moss: "text-moss",
  mist: "text-mist",
  salmon: "text-salmon",
};

// Map PoL dimension title used in courseOverviews to the dimension key
const dimensionTitleToKey: Record<string, string> = {
  "Bold Visionary Leader": "boldVisionaryLeader",
  "Balanced Person": "balancedPerson",
  "Inspiring Communicator": "inspiringCommunicator",
  "Resilient Problem Solver": "resilientProblemSolver",
  "Respectful Relationship Builder": "respectfulRelationshipBuilder",
  "Caring Citizen": "caringCitizen",
};

const Landing = () => {
  const [selectedDimension, setSelectedDimension] = useState<string | null>(null);

  const selected = selectedDimension
    ? portraitDimensions.find((d) => d.key === selectedDimension)
    : null;

  const traits = selectedDimension ? getTraitsForDimension(selectedDimension) : [];

  // Group traits by mindset
  const groupedTraits = traits.reduce<Record<string, { trait: string; pct: number }[]>>((acc, t) => {
    if (!acc[t.mindset]) acc[t.mindset] = [];
    acc[t.mindset].push({ trait: t.trait, pct: t.pct });
    return acc;
  }, {});

  // Subject category mapping for core courses
  const coreSubjectCategory: Record<string, string> = {
    "Science": "STEM",
    "Mathematics": "STEM",
    "ELA / Literacy": "Humanities & Language",
    "Humanities": "Humanities & Language",
    "World Languages": "Humanities & Language",
    "Entrepreneurship": "Leadership & Life Skills",
    "Path to Self-Efficacy": "Leadership & Life Skills",
    "Music / Performing Arts": "Arts & Wellness",
    "Physical Education / Health": "Arts & Wellness",
  };

  // Get courses contributing to the selected dimension, grouped by subject category
  const dimensionCourses = useMemo(() => {
    if (!selected) return [];
    return courseOverviews
      .map((course) => {
        const match = course.portraitDimensions?.find(
          (pd) => dimensionTitleToKey[pd.name] === selected.key
        );
        const category = course.type === "core"
          ? coreSubjectCategory[course.name] || "Core"
          : course.strand || "DNA Strand";
        return match ? { name: course.name, emoji: course.emoji, slug: course.slug, type: course.type, pct: match.pct, category } : null;
      })
      .filter(Boolean) as { name: string; emoji: string; slug: string; type: "core" | "dna"; pct: number; category: string }[];
  }, [selected]);

  // Group courses by category, sorted by avg pct desc within each group
  const groupedCourses = useMemo(() => {
    const groups: Record<string, typeof dimensionCourses> = {};
    dimensionCourses.forEach((c) => {
      if (!groups[c.category]) groups[c.category] = [];
      groups[c.category].push(c);
    });
    // Sort courses within each group by pct desc
    Object.values(groups).forEach((arr) => arr.sort((a, b) => b.pct - a.pct));
    // Sort groups by max pct desc
    return Object.entries(groups).sort(
      ([, a], [, b]) => Math.max(...b.map((c) => c.pct)) - Math.max(...a.map((c) => c.pct))
    );
  }, [dimensionCourses]);

  const toggle = (key: string) => setSelectedDimension(selectedDimension === key ? null : key);

  return (
    <PageTransition>
      <div className="min-h-screen bg-background flex flex-col">
        <TopNav />
        {/* Hero — Horse + Attributes */}
        <section className="flex-1 flex flex-col items-center justify-center bg-milk px-6 py-12 md:py-20">
          {/* Title */}
          <motion.div
            className="text-center mb-8"
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5 }}
          >
            <img src={orionLogo} alt="Orion STEM Schools" className="h-16 md:h-20 mx-auto mb-2" />
            <h1 className="font-display text-3xl md:text-5xl font-bold text-bark mb-2">
              Light the World.
            </h1>
            <p className="text-muted-foreground text-sm md:text-base max-w-xl mx-auto">
              Click any attribute to explore character traits, mindsets, and courses behind it.
            </p>
          </motion.div>

          {/* Horse with attributes */}
          <div className="relative max-w-3xl mx-auto w-full">
            <motion.div
              className="flex justify-center"
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ duration: 0.6, delay: 0.2 }}
            >
              <img
                src={sparkHorse}
                alt="SPARK — Orion's horse mascot with Portrait of the Learner attributes"
                className="w-full max-w-[280px] sm:max-w-md md:max-w-lg"
              />
            </motion.div>

            {/* Attribute buttons - stacked list on mobile, absolute on md+ */}
            <div className="flex flex-col gap-2 mt-4 md:hidden">
              {portraitDimensions.map((dim) => (
                <motion.button
                  key={dim.key}
                  onClick={() => toggle(dim.key)}
                  className={`font-display text-xs tracking-[0.1em] uppercase font-bold px-4 py-2.5 rounded-full transition-all w-full ${
                    selectedDimension === dim.key
                      ? `${dimensionColors[dim.color]} text-milk shadow-lg`
                      : "text-foreground/80 bg-secondary/50 hover:bg-secondary"
                  }`}
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.4 }}
                >
                  {dim.emoji} {dim.title}
                </motion.button>
              ))}
            </div>

            {/* Desktop absolute-positioned labels */}
            {/* Top - Bold Visionary Leader */}
            <motion.button
              onClick={() => toggle("boldVisionaryLeader")}
              className={`hidden md:block absolute top-0 left-1/2 -translate-x-1/2 font-display text-xs tracking-[0.15em] uppercase font-bold px-3 py-1.5 rounded-full transition-all ${
                selectedDimension === "boldVisionaryLeader"
                  ? "bg-valencia text-milk shadow-lg scale-110"
                  : "text-foreground/80 hover:text-valencia hover:bg-valencia/10 cursor-pointer"
              }`}
              initial={{ opacity: 0, y: -10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.4 }}
            >
              Bold Visionary Leader
            </motion.button>

            {/* Top-left - Respectful Relationship Builder */}
            <motion.button
              onClick={() => toggle("respectfulRelationshipBuilder")}
              className={`hidden md:block absolute top-[25%] -left-4 font-display text-xs tracking-[0.1em] uppercase font-bold px-3 py-1.5 rounded-full transition-all ${
                selectedDimension === "respectfulRelationshipBuilder"
                  ? "bg-mist text-milk shadow-lg scale-110"
                  : "text-foreground/80 hover:text-mist hover:bg-mist/10 cursor-pointer"
              }`}
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.5 }}
            >
              Respectful Relationship Builder
            </motion.button>

            {/* Top-right - Resilient Problem Solver */}
            <motion.button
              onClick={() => toggle("resilientProblemSolver")}
              className={`hidden md:block absolute top-[25%] -right-4 font-display text-xs tracking-[0.1em] uppercase font-bold px-3 py-1.5 rounded-full transition-all ${
                selectedDimension === "resilientProblemSolver"
                  ? "bg-moss text-milk shadow-lg scale-110"
                  : "text-foreground/80 hover:text-moss hover:bg-moss/10 cursor-pointer"
              }`}
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.55 }}
            >
              Resilient Problem Solver
            </motion.button>

            {/* Bottom-left - Inspiring Communicator */}
            <motion.button
              onClick={() => toggle("inspiringCommunicator")}
              className={`hidden md:block absolute bottom-[25%] -left-4 font-display text-xs tracking-[0.1em] uppercase font-bold px-3 py-1.5 rounded-full transition-all ${
                selectedDimension === "inspiringCommunicator"
                  ? "bg-deep-sea text-milk shadow-lg scale-110"
                  : "text-foreground/80 hover:text-deep-sea hover:bg-deep-sea/10 cursor-pointer"
              }`}
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.6 }}
            >
              Inspiring Communicator
            </motion.button>

            {/* Bottom-right - Caring Citizen */}
            <motion.button
              onClick={() => toggle("caringCitizen")}
              className={`hidden md:block absolute bottom-[25%] -right-4 font-display text-xs tracking-[0.1em] uppercase font-bold px-3 py-1.5 rounded-full transition-all ${
                selectedDimension === "caringCitizen"
                  ? "bg-salmon text-milk shadow-lg scale-110"
                  : "text-foreground/80 hover:text-salmon hover:bg-salmon/10 cursor-pointer"
              }`}
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.65 }}
            >
              Caring Citizen
            </motion.button>

            {/* Bottom - Balanced Human */}
            <motion.button
              onClick={() => toggle("balancedPerson")}
              className={`hidden md:block absolute bottom-2 left-1/2 -translate-x-1/2 font-display text-xs tracking-[0.15em] uppercase font-bold px-3 py-1.5 rounded-full transition-all ${
                selectedDimension === "balancedPerson"
                  ? "bg-sunflower text-milk shadow-lg scale-110"
                  : "text-foreground/80 hover:text-sunflower hover:bg-sunflower/10 cursor-pointer"
              }`}
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.7 }}
            >
              Balanced Human
            </motion.button>
          </div>
        </section>

        {/* Expanded Detail Panel — Traits + Courses */}
        <AnimatePresence mode="wait">
          {selected && (
            <motion.section
              key={selected.key}
              initial={{ opacity: 0, y: 30 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              transition={{ duration: 0.35 }}
              className="bg-background"
            >
              <div className="container mx-auto px-6 py-10 max-w-5xl">
                <div className={`rounded-2xl border-2 ${dimensionBorderColors[selected.color]} bg-card p-6 md:p-8`}>
                  {/* Header */}
                  <div className="flex items-center gap-3 mb-2">
                    <span className="text-3xl">{selected.emoji}</span>
                    <div>
                      <h2 className="font-display text-xl md:text-2xl font-bold text-foreground">{selected.title}</h2>
                      <p className="text-muted-foreground text-sm">{selected.desc}</p>
                    </div>
                  </div>

                  {/* Two columns: Traits | Courses */}
                  <div className="grid md:grid-cols-2 gap-8 mt-6">
                    {/* Left — Character Traits & Mindsets */}
                    <div>
                      <p className="font-display text-xs tracking-[0.2em] uppercase text-muted-foreground mb-4">
                        Character Traits & Mindsets
                      </p>
                      <div className="space-y-3">
                        {Object.entries(groupedTraits).map(([mindset, items]) => (
                          <div key={mindset} className="bg-muted rounded-xl p-4">
                            <p className="font-display text-[0.65rem] tracking-[0.15em] uppercase text-muted-foreground mb-2">
                              {mindset}
                            </p>
                            <div className="space-y-2">
                              {items.map((item) => (
                                <div key={item.trait} className="flex items-center justify-between gap-2">
                                  <span className="text-sm font-display font-medium text-foreground">{item.trait}</span>
                                  <div className="flex items-center gap-2 shrink-0">
                                    <div className="w-14 h-2 bg-secondary rounded-full overflow-hidden">
                                      <motion.div
                                        className={`h-full rounded-full ${dimensionColors[selected.color]}`}
                                        initial={{ width: 0 }}
                                        animate={{ width: `${item.pct}%` }}
                                        transition={{ duration: 0.5, delay: 0.1 }}
                                      />
                                    </div>
                                    <span className={`text-xs font-display font-bold ${dimensionTextColors[selected.color]} w-8 text-right`}>
                                      {item.pct}%
                                    </span>
                                  </div>
                                </div>
                              ))}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>

                    {/* Right — Courses contributing to this dimension */}
                    <div>
                      <p className="font-display text-xs tracking-[0.2em] uppercase text-muted-foreground mb-4">
                        Courses at Orion
                      </p>
                      <div className="space-y-4">
                        {groupedCourses.map(([category, courses]) => (
                          <div key={category}>
                            <p className="font-display text-[0.65rem] tracking-[0.15em] uppercase text-muted-foreground mb-2 border-b border-border pb-1">
                              {category}
                            </p>
                            <div className="space-y-1.5">
                              {courses.map((course) => (
                                <Link
                                  key={course.slug}
                                  to={`/course/${course.slug}`}
                                  className="group flex items-center gap-3 bg-muted rounded-xl p-3 hover:bg-muted/80 transition-colors"
                                >
                                  <span className="text-xl shrink-0">{course.emoji}</span>
                                  <div className="flex-1 min-w-0">
                                    <p className="font-display text-sm font-bold text-foreground group-hover:text-valencia transition-colors truncate">
                                      {course.name}
                                    </p>
                                  </div>
                                  <div className="flex items-center gap-2 shrink-0">
                                    <div className="w-16 h-2 bg-secondary rounded-full overflow-hidden">
                                      <motion.div
                                        className={`h-full rounded-full ${dimensionColors[selected.color]}`}
                                        initial={{ width: 0 }}
                                        animate={{ width: `${course.pct}%` }}
                                        transition={{ duration: 0.5, delay: 0.15 }}
                                      />
                                    </div>
                                    <span className={`text-xs font-display font-bold ${dimensionTextColors[selected.color]} w-8 text-right`}>
                                      {course.pct}%
                                    </span>
                                  </div>
                                </Link>
                              ))}
                            </div>
                          </div>
                        ))}
                        {dimensionCourses.length === 0 && (
                          <p className="text-muted-foreground text-sm italic">No course data available for this dimension yet.</p>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </motion.section>
          )}
        </AnimatePresence>

        {/* Grade Family Guides */}
        <section className="py-10 bg-card">
          <div className="container mx-auto px-6 max-w-3xl text-center">
            <p className="font-display text-xs tracking-[0.2em] uppercase text-deep-sea mb-4">Family Guides by Grade</p>
            <div className="flex flex-wrap justify-center gap-2">
              {grades.map((g) =>
                g.available ? (
                  <Link
                    key={g.id}
                    to={g.route}
                    className="inline-flex items-center justify-center font-display text-sm font-bold rounded-full w-12 h-12 bg-deep-sea text-milk hover:bg-valencia transition-colors shadow-md hover:shadow-lg"
                  >
                    {g.shortLabel}
                  </Link>
                ) : (
                  <span
                    key={g.id}
                    className="inline-flex items-center justify-center font-display text-sm font-medium rounded-full w-12 h-12 bg-secondary text-muted-foreground cursor-not-allowed"
                    title="Coming soon"
                  >
                    {g.shortLabel}
                  </span>
                )
              )}
            </div>
            <p className="text-muted-foreground text-xs mt-3 font-display">KG is live · Other grades coming soon</p>
          </div>
        </section>

        {/* Footer */}
        <footer className="py-10 bg-bark text-center mt-auto">
          <p className="font-display text-milk/60 text-sm">
            Orion STEM Schools · Family Curriculum Portal · 2026–2027
          </p>
        </footer>
      </div>
    </PageTransition>
  );
};

export default Landing;
