import { useEffect, useState } from "react";
import { motion } from "framer-motion";
import { yearOverview, quarters } from "@/data/curriculum";
import { PageTransition, staggerContainer, fadeUpItem, scaleFadeItem } from "@/components/PageTransition";
import { GrowthDashboard } from "@/components/GrowthDashboard";
import { apiUrl } from "@/lib/apiUrl";
import { getBlockComponent, type BlockContent } from "@/components/page-blocks";
import { CurriculumHeroBlock, EssentialQuestionBlock, CoreCoursesBlock, DnaStrandsBlock, YearAtGlanceBlock, YearLongStoryBlock, DevelopingWholeChildBlock, OneProjectNot13TestsBlock, CurriculumArchitectureBlock, PbelBlock } from "@/components/page-blocks";

type PageBlock = { componentId: number; componentName: string; content: Record<string, unknown> };
type PageSection = { width: string; layout: string; blocks: PageBlock[] };

function isSection(x: unknown): x is PageSection {
  return typeof x === "object" && x !== null && "width" in x && "layout" in x && "blocks" in x;
}

function normalizeContent(content: unknown): PageSection[] {
  if (!Array.isArray(content) || content.length === 0) return [];
  if (isSection(content[0])) return content as PageSection[];
  return [{ width: "full", layout: "100", blocks: content as PageBlock[] }];
}

const curriculumNameToSlug: Record<string, string> = {
  Hero: "hero",
  "Dimension Detail": "dimension-detail",
  "Grade Family Guides": "grade-family-guides",
  "Grade Family Guides with API": "grade-family-guides-api",
  "Grade Hero": "grade-hero",
  "Grade Kaleidoscope": "grade-kaleidoscope",
  "Curriculum Hero": "curriculum-hero",
  "Essential Question": "essential-question",
  "Core Courses": "core-courses",
  "DNA Strands": "dna-strands",
  "Year at a Glance": "year-at-glance",
  "Year-Long Story": "year-long-story",
  "Developing the Whole Child": "developing-the-whole-child",
  "Portrait of the Learner": "developing-the-whole-child",
  "Fink's Taxonomy of Significant Learning": "finks-taxonomy",
  "Finks Taxonomy": "finks-taxonomy",
  "One Project, Not 13 Tests": "one-project-not-13-tests",
  "Curriculum Architecture": "curriculum-architecture",
  "Problem-Based Experiential Learning": "pbel",
  Footer: "footer",
};

function getBlockSlug(block: PageBlock): string {
  return curriculumNameToSlug[block.componentName] ?? "hero";
}

const quarterColors = {
    moss: "bg-moss",
    "deep-sea": "bg-deep-sea",
    valencia: "bg-valencia",
    sunflower: "bg-sunflower",
} as const;

const quarterBorderColors = {
    moss: "border-moss",
    "deep-sea": "border-deep-sea",
    valencia: "border-valencia",
    sunflower: "border-sunflower",
} as const;

const Index = () => {
    const [pageBlocks, setPageBlocks] = useState<PageBlock[] | null>(null);

    useEffect(() => {
        let cancelled = false;
        fetch(apiUrl("/api/pages/preview/curriculum"))
            .then((res) => {
                if (!res.ok) throw new Error("not found");
                return res.json();
            })
            .then((data) => {
                if (!cancelled && data?.page?.content) {
                    const sections = normalizeContent(data.page.content);
                    const blocks = sections.flatMap((s) => s.blocks).filter(Boolean);
                    if (blocks.length > 0) setPageBlocks(blocks);
                }
            })
            .catch(() => {});
        return () => { cancelled = true; };
    }, []);

    const useEditableBlocks = Array.isArray(pageBlocks) && pageBlocks.length > 0;

    return (
        <PageTransition>
            <div className="min-h-full bg-background">
                {useEditableBlocks ? (
                    pageBlocks!.map((block, bi) => {
                        const slug = getBlockSlug(block);
                        const BlockComp = getBlockComponent(slug);
                        const content = (block.content ?? {}) as BlockContent;
                        if (!BlockComp) return null;
                        return <BlockComp key={bi} content={content} />;
                    })
                ) : (
                    <>
                        <CurriculumHeroBlock />
                        <EssentialQuestionBlock />
                        <CoreCoursesBlock />
                        <DnaStrandsBlock />
                        <YearAtGlanceBlock />
                        <YearLongStoryBlock />
                        <DevelopingWholeChildBlock />
                    </>
                )}
                <OneProjectNot13TestsBlock />
                <CurriculumArchitectureBlock />
                <PbelBlock />
            </div>
        </PageTransition>
    );
};

export default Index;
