import { Link, useLocation } from "react-router-dom";
import { ArrowLeft } from "lucide-react";
import { motion } from "framer-motion";
import { staggerContainer, scaleFadeItem } from "@/components/PageTransition";
import orionLogo from "@/assets/orion-logo.svg";
import heroImage from "@/assets/hero-habitat.jpg";
import { yearOverview } from "@/data/curriculum";
import { resolveCurriculumHeroBackNav } from "@/lib/curriculumHeroBackNav";

type Content = Record<string, unknown>;

export interface CurriculumHeroStat {
  label: string;
  value: string;
}

function parseStats(content: Content | undefined): CurriculumHeroStat[] {
  const raw = content?.stats;
  if (!Array.isArray(raw) || raw.length === 0) return yearOverview.stats;
  return raw
    .filter((x): x is Record<string, unknown> => x != null && typeof x === "object")
    .map((o) => ({
      label: typeof o.label === "string" ? o.label : "",
      value: typeof o.value === "string" ? o.value : "",
    }))
    .filter((s) => s.label || s.value);
}

export function CurriculumHeroBlock({ content }: { content?: Content }) {
  const location = useLocation();
  // Prefer the real browser path so admin (/secure-access) and /preview are detectable.
  const browserPath =
    typeof window !== "undefined" ? window.location.pathname : location.pathname;

  const backLabel = (content?.backLabel as string) ?? "Back to Kaleidoscope";
  const backNav = resolveCurriculumHeroBackNav(content?.backHref, browserPath);
  const imageSrc = (content?.imageSrc as string) || heroImage;
  const imageAlt = (content?.imageAlt as string) ?? "Schoolyard habitat illustration";
  const label = (content?.label as string) ?? `${yearOverview.school} · ${yearOverview.year}`;
  const title = (content?.title as string) ?? yearOverview.title;
  const subtitle = (content?.subtitle as string) ?? `Comprehensive Family Guide · ${yearOverview.grade}`;
  const bigIdea = (content?.bigIdea as string) ?? yearOverview.bigIdea;
  const stats = parseStats(content);

  const backLinkClassName =
    "inline-flex items-center gap-2 text-milk/70 hover:text-milk font-display text-sm mb-6 transition-colors";

  return (
    <section className="relative overflow-hidden">
      <div className="absolute inset-0">
        <img src={imageSrc} alt={imageAlt} className="w-full h-full object-cover" />
        <div className="absolute inset-0 bg-gradient-to-b from-bark/80 via-bark/60 to-bark/90" />
      </div>
      <div className="relative z-10 container mx-auto px-6 py-20 md:py-32 text-center">
        {backNav.useRouterLink ? (
          <Link to={backNav.href} className={backLinkClassName}>
            <ArrowLeft className="w-4 h-4" /> {backLabel}
          </Link>
        ) : (
          <a href={backNav.href} className={backLinkClassName}>
            <ArrowLeft className="w-4 h-4" /> {backLabel}
          </a>
        )}
        <img src={orionLogo} alt="Orion STEM Schools" className="h-14 md:h-18 mx-auto mb-4" />
        <motion.p
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
          className="font-display text-sm md:text-base tracking-[0.3em] uppercase text-mist mb-4"
        >
          {label}
        </motion.p>
        <motion.h1
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6, delay: 0.1 }}
          className="font-display text-4xl md:text-6xl lg:text-7xl font-bold text-milk mb-4 leading-tight"
        >
          {title}
        </motion.h1>
        <motion.p
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.5, delay: 0.25 }}
          className="font-display text-lg md:text-xl text-salmon mb-8"
        >
          {subtitle}
        </motion.p>
        <motion.p
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.5, delay: 0.35 }}
          className="max-w-2xl mx-auto text-milk/80 text-base md:text-lg leading-relaxed"
        >
          {bigIdea}
        </motion.p>
        <motion.div
          className="flex flex-wrap justify-center gap-3 mt-10"
          variants={staggerContainer}
          initial="initial"
          animate="animate"
        >
          {stats.map((stat) => (
            <motion.div
              key={stat.label}
              variants={scaleFadeItem}
              className="bg-milk/10 backdrop-blur-sm border border-milk/20 rounded-lg px-4 py-3 text-center"
            >
              <div className="font-display text-2xl font-bold text-valencia">{stat.value}</div>
              <div className="text-milk/70 text-xs font-display">{stat.label}</div>
            </motion.div>
          ))}
        </motion.div>
      </div>
    </section>
  );
}
