import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { motion, AnimatePresence } from "framer-motion";
import { staggerContainer, fadeUpItem } from "@/components/PageTransition";
import sparkHorse from "@/assets/spark-horse.png";

type Content = Record<string, unknown>;

export interface KaleidoscopeSlice {
  label: string;
  emoji: string;
  color: string;
  route: string;
  description: string;
}

const DEFAULT_SLICES: KaleidoscopeSlice[] = [
  { label: "PBL", emoji: "🔬", color: "deep-sea", route: "/grade/kg/curriculum", description: "Project-Based Learning curriculum integrated across all subjects" },
  { label: "Design to Impact", emoji: "💧", color: "valencia", route: "/course/pbel-design-to-impact", description: "Problem-Based Experiential Learning — A Kaleidoscope of Inquiry, Design, and Impact" },
  { label: "Clubs", emoji: "🎭", color: "moss", route: "/grade/kg/clubs", description: "Student-led interest groups that build community and passion" },
  { label: "Competitions", emoji: "🏆", color: "sunflower", route: "/grade/kg/competitions", description: "Academic and creative competitions to showcase excellence" },
  { label: "Steering Committees", emoji: "🧭", color: "mist", route: "/grade/kg/steering-committees", description: "Student voice in school governance and decision-making" },
  { label: "Progress Report", emoji: "📊", color: "deep-sea", route: "/grade/kg/progress-report", description: "Mastery-based assessment — growth over grades, evidence over averages" },
  { label: "My Growth Plan", emoji: "🌱", color: "salmon", route: "/grade/kg/growth-plan", description: "Personalized growth tracking across all Portrait dimensions" },
];

const CARD_COLOR_CLASS: Record<string, string> = {
  "deep-sea": "bg-deep-sea",
  valencia: "bg-valencia",
  moss: "bg-moss",
  sunflower: "bg-sunflower",
  mist: "bg-mist",
  salmon: "bg-salmon",
};
const OUTER_R = 230;
const INNER_R = 70;
const CENTER = 260;

function polarToXY(cx: number, cy: number, r: number, angleDeg: number) {
  const rad = ((angleDeg - 90) * Math.PI) / 180;
  return { x: cx + r * Math.cos(rad), y: cy + r * Math.sin(rad) };
}

/** Build one even wedge (or full ring when totalSegments === 1). */
function slicePath(index: number, anglePerSlice: number) {
  if (anglePerSlice >= 360) {
    return [
      `M ${CENTER} ${CENTER - OUTER_R}`,
      `A ${OUTER_R} ${OUTER_R} 0 1 1 ${CENTER} ${CENTER + OUTER_R}`,
      `A ${OUTER_R} ${OUTER_R} 0 1 1 ${CENTER} ${CENTER - OUTER_R}`,
      `M ${CENTER} ${CENTER - INNER_R}`,
      `A ${INNER_R} ${INNER_R} 0 1 0 ${CENTER} ${CENTER + INNER_R}`,
      `A ${INNER_R} ${INNER_R} 0 1 0 ${CENTER} ${CENTER - INNER_R}`,
      `Z`,
    ].join(" ");
  }

  const startAngle = index * anglePerSlice;
  const endAngle = startAngle + anglePerSlice;
  const largeArc = anglePerSlice > 180 ? 1 : 0;
  const outerStart = polarToXY(CENTER, CENTER, OUTER_R, startAngle);
  const outerEnd = polarToXY(CENTER, CENTER, OUTER_R, endAngle);
  const innerEnd = polarToXY(CENTER, CENTER, INNER_R, endAngle);
  const innerStart = polarToXY(CENTER, CENTER, INNER_R, startAngle);

  return [
    `M ${outerStart.x} ${outerStart.y}`,
    `A ${OUTER_R} ${OUTER_R} 0 ${largeArc} 1 ${outerEnd.x} ${outerEnd.y}`,
    `L ${innerEnd.x} ${innerEnd.y}`,
    `A ${INNER_R} ${INNER_R} 0 ${largeArc} 0 ${innerStart.x} ${innerStart.y}`,
    `Z`,
  ].join(" ");
}

function labelPosition(index: number, anglePerSlice: number) {
  const midAngle = index * anglePerSlice + anglePerSlice / 2;
  const labelR = (OUTER_R + INNER_R) / 2 + 10;
  return { ...polarToXY(CENTER, CENTER, labelR, midAngle), angle: midAngle };
}

function emojiPosition(index: number, anglePerSlice: number) {
  const midAngle = index * anglePerSlice + anglePerSlice / 2;
  return polarToXY(CENTER, CENTER, (OUTER_R + INNER_R) / 2 - 18, midAngle);
}

function labelFontSize(totalSegments: number, mobile: boolean) {
  const base = mobile ? 11 : 13;
  if (totalSegments <= 7) return base;
  return Math.max(mobile ? 8 : 9, Math.round(base - (totalSegments - 7) * 0.6));
}

function emojiFontSize(totalSegments: number, mobile: boolean) {
  const base = mobile ? 16 : 20;
  if (totalSegments <= 7) return base;
  return Math.max(mobile ? 12 : 14, Math.round(base - (totalSegments - 7) * 0.8));
}

function parseItems(content: Content | undefined): KaleidoscopeSlice[] {
  const raw = content?.items;
  if (raw == null) return DEFAULT_SLICES;
  // Support both array and object (e.g. API may return { "0": {...}, "1": {...} })
  const arr = Array.isArray(raw) ? raw : typeof raw === "object" ? Object.values(raw) : [];
  if (arr.length === 0) return DEFAULT_SLICES;
  const parsed = arr
    .filter((x): x is Record<string, unknown> => x != null && typeof x === "object")
    .map((o) => ({
      label: typeof o.label === "string" ? o.label : "",
      emoji: typeof o.emoji === "string" ? o.emoji : "•",
      color: typeof o.color === "string" ? o.color : "deep-sea",
      route: typeof o.route === "string" ? o.route : "#",
      description: typeof o.description === "string" ? o.description : "",
    }));
  return parsed.length === 0 ? DEFAULT_SLICES : parsed;
}

export function KaleidoscopeBlock({ content }: { content?: Content }) {
  const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
  const heading = (content?.heading as string) ?? "The Orion Kaleidoscope";
  const title = (content?.title as string) ?? "Six Dimensions of the Student Experience";
  const subtitle = (content?.subtitle as string) ?? "Click any slice to explore that dimension.";
  const items = parseItems(content);
  const totalSegments = Math.max(items.length, 1);
  const anglePerSlice = 360 / totalSegments;

  useEffect(() => {
    if (hoveredIndex !== null && hoveredIndex >= items.length) {
      setHoveredIndex(null);
    }
  }, [items.length, hoveredIndex]);

  return (
    <section className="flex-1 py-16 md:py-24 bg-background relative overflow-hidden">
      <div className="absolute inset-0 pointer-events-none">
        <div className="absolute left-1/2 top-[320px] -translate-x-1/2 -translate-y-1/2 w-[700px] h-[700px] rounded-full bg-[radial-gradient(circle,hsl(var(--deep-sea)/0.03)_0%,transparent_70%)]" />
      </div>

      <div className="container mx-auto px-6 relative z-10">
        <motion.div className="text-center mb-14" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.3 }}>
          <p className="font-display text-xs tracking-[0.2em] uppercase text-deep-sea mb-2">{heading}</p>
          <h2 className="font-display text-2xl md:text-3xl font-bold text-foreground">{title}</h2>
          <p className="text-muted-foreground mt-2 text-sm max-w-md mx-auto">{subtitle}</p>
        </motion.div>

        {/* Desktop Radial Wheel */}
        <div className="hidden md:flex justify-center items-center">
          <div className="relative" style={{ width: CENTER * 2, height: CENTER * 2 }}>
            <motion.svg
              viewBox={`0 0 ${CENTER * 2} ${CENTER * 2}`}
              className="w-full h-full"
              initial={{ opacity: 0, rotate: -20, scale: 0.85 }}
              animate={{ opacity: 1, rotate: 0, scale: 1 }}
              transition={{ duration: 0.8, ease: "easeOut" }}
            >
              <circle cx={CENTER} cy={CENTER} r={OUTER_R + 6} fill="none" stroke="hsl(var(--card))" strokeWidth={12} />
              {items.map((item, i) => {
                const path = slicePath(i, anglePerSlice);
                const lbl = labelPosition(i, anglePerSlice);
                const emoji = emojiPosition(i, anglePerSlice);
                let textAngle = lbl.angle - 90;
                if (lbl.angle > 90 && lbl.angle < 270) textAngle += 180;
                const hslVar = `--${item.color}`;
                return (
                  <g key={`${item.label}-${i}`}>
                    <Link to={item.route}>
                      <motion.path
                        d={path}
                        fill={`hsl(var(${hslVar}))`}
                        stroke="hsl(var(--card))"
                        strokeWidth={3}
                        className="cursor-pointer"
                        initial={{ opacity: 0, scale: 0.8 }}
                        animate={{ opacity: 1, scale: hoveredIndex === i ? 1.04 : 1 }}
                        whileHover={{ scale: 1.06 }}
                        transition={{ delay: 0.1 * i + 0.2, duration: 0.4 }}
                        onHoverStart={() => setHoveredIndex(i)}
                        onHoverEnd={() => setHoveredIndex(null)}
                        style={{ transformOrigin: `${CENTER}px ${CENTER}px` }}
                      />
                    </Link>
                    <text
                      x={lbl.x}
                      y={lbl.y}
                      textAnchor="middle"
                      dominantBaseline="middle"
                      transform={`rotate(${textAngle}, ${lbl.x}, ${lbl.y})`}
                      className="pointer-events-none select-none"
                      fill="white"
                      fontSize={labelFontSize(totalSegments, false)}
                      fontWeight={700}
                      fontFamily="Outfit, sans-serif"
                      letterSpacing="0.05em"
                    >
                      {item.label}
                    </text>
                    <text
                      x={emoji.x}
                      y={emoji.y}
                      textAnchor="middle"
                      dominantBaseline="middle"
                      className="pointer-events-none"
                      fontSize={emojiFontSize(totalSegments, false)}
                    >
                      {item.emoji}
                    </text>
                  </g>
                );
              })}
              <circle cx={CENTER} cy={CENTER} r={INNER_R} fill="hsl(var(--card))" stroke="hsl(var(--border))" strokeWidth={2} />
              <foreignObject x={CENTER - INNER_R + 5} y={CENTER - INNER_R + 5} width={(INNER_R - 5) * 2} height={(INNER_R - 5) * 2}>
                <div className="w-full h-full flex items-center justify-center">
                  <img src={sparkHorse} alt="SPARK" className="w-full h-full object-contain drop-shadow-lg" />
                </div>
              </foreignObject>
            </motion.svg>

            <AnimatePresence>
              {hoveredIndex !== null && items[hoveredIndex] && (
                <motion.div
                  className="absolute left-1/2 -translate-x-1/2 bg-card border border-border rounded-xl shadow-xl p-4 max-w-xs text-center pointer-events-none z-30"
                  style={{ top: CENTER * 2 + 16 }}
                  initial={{ opacity: 0, y: -8 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -8 }}
                  transition={{ duration: 0.15 }}
                >
                  <div className="flex items-center justify-center gap-2 mb-1">
                    <span className="text-lg">{items[hoveredIndex].emoji}</span>
                    <span className="font-display text-sm font-bold text-foreground">{items[hoveredIndex].label}</span>
                  </div>
                  <p className="text-muted-foreground text-xs">{items[hoveredIndex].description}</p>
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        </div>

        {/* Mobile: Radial wheel */}
        <div className="md:hidden flex flex-col items-center">
          <div className="relative" style={{ width: 300, height: 300 }}>
            <svg viewBox={`0 0 ${CENTER * 2} ${CENTER * 2}`} className="w-full h-full">
              <circle cx={CENTER} cy={CENTER} r={OUTER_R + 6} fill="none" stroke="hsl(var(--card))" strokeWidth={12} />
              {items.map((item, i) => {
                const path = slicePath(i, anglePerSlice);
                const lbl = labelPosition(i, anglePerSlice);
                const emoji = emojiPosition(i, anglePerSlice);
                let textAngle = lbl.angle - 90;
                if (lbl.angle > 90 && lbl.angle < 270) textAngle += 180;
                const hslVar = `--${item.color}`;
                return (
                  <Link key={`${item.label}-${i}`} to={item.route}>
                    <g>
                      <path d={path} fill={`hsl(var(${hslVar}))`} stroke="hsl(var(--card))" strokeWidth={3} />
                      <text
                        x={lbl.x}
                        y={lbl.y}
                        textAnchor="middle"
                        dominantBaseline="middle"
                        transform={`rotate(${textAngle}, ${lbl.x}, ${lbl.y})`}
                        fill="white"
                        fontSize={labelFontSize(totalSegments, true)}
                        fontWeight={700}
                        fontFamily="Outfit, sans-serif"
                      >
                        {item.label}
                      </text>
                      <text
                        x={emoji.x}
                        y={emoji.y}
                        textAnchor="middle"
                        dominantBaseline="middle"
                        fontSize={emojiFontSize(totalSegments, true)}
                      >
                        {item.emoji}
                      </text>
                    </g>
                  </Link>
                );
              })}
              <circle cx={CENTER} cy={CENTER} r={INNER_R} fill="hsl(var(--card))" stroke="hsl(var(--border))" strokeWidth={2} />
              <foreignObject x={CENTER - INNER_R + 5} y={CENTER - INNER_R + 5} width={(INNER_R - 5) * 2} height={(INNER_R - 5) * 2}>
                <div className="w-full h-full flex items-center justify-center">
                  <img src={sparkHorse} alt="SPARK" className="w-full h-full object-contain drop-shadow-lg" />
                </div>
              </foreignObject>
            </svg>
          </div>
        </div>

        {/* Description cards below */}
        <motion.div
          className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4 max-w-4xl mx-auto mt-16"
          variants={staggerContainer}
          initial="initial"
          whileInView="animate"
          viewport={{ once: true }}
        >
          {items.map((item, cardIndex) => (
            <motion.div key={`slice-${cardIndex}`} variants={fadeUpItem}>
              <Link
                to={item.route}
                className="group block bg-card rounded-xl p-5 border border-border hover:border-primary/30 transition-all hover:shadow-lg"
              >
                <div className="flex items-center gap-3 mb-2">
                  <span className={`w-8 h-8 rounded-full ${CARD_COLOR_CLASS[item.color] ?? "bg-deep-sea"} flex items-center justify-center text-lg`}>
                    {item.emoji}
                  </span>
                  <h3 className="font-display text-sm font-bold text-foreground">{item.label || "Untitled"}</h3>
                </div>
                <p className="text-muted-foreground text-xs leading-relaxed">{item.description || "—"}</p>
                <span className="font-display text-xs text-primary font-semibold mt-2 block group-hover:translate-x-1 transition-transform">
                  Explore →
                </span>
              </Link>
            </motion.div>
          ))}
        </motion.div>
      </div>
    </section>
  );
}
