import { motion } from "framer-motion";

type Content = Record<string, unknown>;

export type FishboneBranch = {
    category: string;
    emoji: string;
    color: string;
    causes: string[];
};

const colorClass: Record<string, { bg: string; text: string; hsl: string }> = {
    "deep-sea": { bg: "bg-deep-sea", text: "text-deep-sea", hsl: "hsl(var(--deep-sea))" },
    valencia: { bg: "bg-valencia", text: "text-valencia", hsl: "hsl(var(--valencia))" },
    moss: { bg: "bg-moss", text: "text-moss", hsl: "hsl(var(--moss))" },
    sunflower: { bg: "bg-sunflower", text: "text-sunflower", hsl: "hsl(var(--sunflower))" },
    salmon: { bg: "bg-salmon", text: "text-salmon", hsl: "hsl(var(--salmon))" },
    mist: { bg: "bg-mist", text: "text-mist", hsl: "hsl(var(--mist))" },
};

export const FISHBONE_COLOR_OPTIONS = [
    { value: "deep-sea", label: "Deep Sea" },
    { value: "valencia", label: "Valencia" },
    { value: "moss", label: "Moss" },
    { value: "sunflower", label: "Sunflower" },
    { value: "salmon", label: "Salmon" },
    { value: "mist", label: "Mist" },
] as const;

export const defaultFishboneBranches: FishboneBranch[] = [
    {
        category: "Mindset",
        emoji: "🧠",
        color: "valencia",
        causes: [
            "Fixed mindset — believes ability is innate",
            "Perfectionism discourages risk-taking",
            "Fear of being wrong in front of peers",
        ],
    },
    {
        category: "Experience",
        emoji: "📚",
        color: "deep-sea",
        causes: [
            "Limited exposure to iterative processes",
            "Few opportunities for public speaking",
            "No modeled 'productive struggle' from adults",
        ],
    },
    {
        category: "Environment",
        emoji: "🏠",
        color: "moss",
        causes: [
            "Praise at home centers on outcomes, not effort",
            "Screen time reduces focus during deep work",
            "Transitions at school feel abrupt",
        ],
    },
    {
        category: "Social-Emotional",
        emoji: "💛",
        color: "sunflower",
        causes: [
            "No personal calming toolkit yet",
            "Sensory overload during unstructured moments",
            "Limited conflict-resolution models at home",
        ],
    },
    {
        category: "Pedagogy",
        emoji: "🎓",
        color: "mist",
        causes: [
            "Needs more think-time before responding",
            "Large-group settings are intimidating",
            "Assessment focus on product over process",
        ],
    },
    {
        category: "Support",
        emoji: "🤝",
        color: "salmon",
        causes: [
            "Family unsure how to encourage growth mindset",
            "Peer dynamics amplify self-doubt",
            "Inconsistent language between home and school",
        ],
    },
];

export const defaultFishboneInterventions = [
    "Embed 'fail forward' rituals — celebrate revision stories daily",
    "Co-create a personal 'calm-down menu' with student",
    "Use think-pair-share before whole-group discussions",
    "Parent workshop on growth-mindset praise techniques",
    "Visual countdown timers for smoother transitions",
    "Create a 'brave ideas' jar for safe opinion sharing",
];

function str(value: unknown): string {
    return typeof value === "string" ? value : "";
}

function resolveColor(color: string) {
    return colorClass[color] ?? colorClass.valencia;
}

function parseCauses(raw: unknown): string[] {
    if (typeof raw === "string") {
        return raw.split("\n").map((line) => line.trim()).filter(Boolean);
    }
    if (!Array.isArray(raw)) return [];
    return raw
        .map((item) => {
            if (typeof item === "string") return item.trim();
            if (item != null && typeof item === "object") return str((item as Record<string, unknown>).text).trim();
            return "";
        })
        .filter(Boolean);
}

export function parseFishboneBranches(content?: Content): FishboneBranch[] {
    const raw = content?.branches;
    if (!Array.isArray(raw) || raw.length === 0) return defaultFishboneBranches;

    return raw
        .filter((item): item is Record<string, unknown> => item != null && typeof item === "object")
        .map((item) => ({
            category: str(item.category).trim(),
            emoji: str(item.emoji).trim(),
            color: str(item.color).trim() || "valencia",
            causes: parseCauses(item.causes),
        }))
        .filter((item) => item.category || item.emoji || item.causes.length > 0);
}

export function parseFishboneInterventions(content?: Content): string[] {
    const raw = content?.interventions;
    if (!Array.isArray(raw) || raw.length === 0) {
        return content?.interventions === undefined ? defaultFishboneInterventions : [];
    }
    return raw
        .map((item) => {
            if (typeof item === "string") return item.trim();
            if (item != null && typeof item === "object") return str((item as Record<string, unknown>).text).trim();
            return "";
        })
        .filter(Boolean);
}

export function parseEffectShortLines(content?: Content): string[] {
    const raw = content?.effectShortLines;
    if (!Array.isArray(raw) || raw.length === 0) {
        return content?.effectShortLines === undefined
            ? ["Growth gaps in", "resilience & voice"]
            : [];
    }
    return raw.map((line) => str(line).trim()).filter(Boolean);
}

export function RootCauseFishboneBlock({ content }: { content?: Content }) {
    const stepLabel = str(content?.stepLabel).trim();
    const stepLabelColor = str(content?.stepLabelColor).trim() || "valencia";
    const title = str(content?.title).trim();
    const subtitle = str(content?.subtitle).trim();
    const effect = str(content?.effect).trim()
        || "Student struggles with resilience, self-regulation, and confident self-expression";
    const effectLabel = str(content?.effectLabel).trim() || "EFFECT";
    const effectShortLines = parseEffectShortLines(content);
    const branches = parseFishboneBranches(content);
    const interventionsTitle = str(content?.interventionsTitle).trim() || "🎯 Targeted Interventions";
    const interventions = parseFishboneInterventions(content);
    const stepTextClass = resolveColor(stepLabelColor).text;

    if (
        branches.length === 0
        && interventions.length === 0
        && !stepLabel
        && !title
        && !subtitle
        && !str(content?.effect).trim()
    ) {
        return null;
    }

    return (
        <section className="py-16 bg-card">
            <div className="container mx-auto px-6 max-w-6xl">
                {(stepLabel || title || subtitle) ? (
                    <motion.div
                        className="text-center mb-10"
                        initial={{ opacity: 0, y: 10 }}
                        whileInView={{ opacity: 1, y: 0 }}
                        viewport={{ once: true }}
                    >
                        {stepLabel ? (
                            <p className={`font-display text-xs tracking-[0.2em] uppercase ${stepTextClass} mb-2`}>
                                {stepLabel}
                            </p>
                        ) : null}
                        {title ? (
                            <h2 className="font-display text-2xl md:text-3xl font-bold text-foreground">
                                {title}
                            </h2>
                        ) : null}
                        {subtitle ? (
                            <p className="text-muted-foreground mt-2 text-sm max-w-lg mx-auto">
                                {subtitle}
                            </p>
                        ) : null}
                    </motion.div>
                ) : null}

                <motion.div
                    className="bg-background rounded-2xl border border-border p-6 md:p-8 overflow-hidden"
                    initial={{ opacity: 0, y: 20 }}
                    whileInView={{ opacity: 1, y: 0 }}
                    viewport={{ once: true }}
                    transition={{ duration: 0.5 }}
                >
                    {branches.length > 0 ? (
                        <>
                            <div className="hidden md:block">
                                <svg viewBox="0 0 1000 500" className="w-full" style={{ maxHeight: 500 }}>
                                    <motion.line
                                        x1={80}
                                        y1={250}
                                        x2={860}
                                        y2={250}
                                        stroke="hsl(var(--foreground))"
                                        strokeWidth={3}
                                        initial={{ pathLength: 0 }}
                                        whileInView={{ pathLength: 1 }}
                                        viewport={{ once: true }}
                                        transition={{ duration: 0.8 }}
                                    />

                                    <motion.g
                                        initial={{ opacity: 0, x: 20 }}
                                        whileInView={{ opacity: 1, x: 0 }}
                                        viewport={{ once: true }}
                                        transition={{ delay: 0.8 }}
                                    >
                                        <rect x={860} y={215} width={130} height={70} rx={12} fill="hsl(var(--valencia))" />
                                        <text
                                            x={925}
                                            y={242}
                                            textAnchor="middle"
                                            fill="white"
                                            fontSize={10}
                                            fontWeight={700}
                                            fontFamily="Outfit"
                                        >
                                            {effectLabel}
                                        </text>
                                        {effectShortLines.map((line, lineIndex) => (
                                            <text
                                                key={`${line}-${lineIndex}`}
                                                x={925}
                                                y={258 + lineIndex * 12}
                                                textAnchor="middle"
                                                fill="white"
                                                fontSize={8}
                                                fontFamily="Outfit"
                                                opacity={0.9}
                                            >
                                                {line}
                                            </text>
                                        ))}
                                    </motion.g>

                                    {branches.map((branch, i) => {
                                        const isTop = i < 3;
                                        const xPositions = [180, 420, 660];
                                        const xIdx = i % 3;
                                        const bx = xPositions[xIdx] ?? 180;
                                        const by = isTop ? 80 : 420;
                                        const spineY = 250;
                                        const color = resolveColor(branch.color).hsl;

                                        return (
                                            <motion.g
                                                key={`${branch.category}-${i}`}
                                                initial={{ opacity: 0, y: isTop ? -20 : 20 }}
                                                whileInView={{ opacity: 1, y: 0 }}
                                                viewport={{ once: true }}
                                                transition={{ delay: 0.3 + i * 0.12 }}
                                            >
                                                <line
                                                    x1={bx + 60}
                                                    y1={isTop ? by + 60 : by - 60}
                                                    x2={bx + 120}
                                                    y2={spineY}
                                                    stroke={color}
                                                    strokeWidth={2}
                                                    opacity={0.6}
                                                />
                                                <rect
                                                    x={bx}
                                                    y={by - 10}
                                                    width={120}
                                                    height={28}
                                                    rx={6}
                                                    fill={color}
                                                />
                                                <text
                                                    x={bx + 60}
                                                    y={by + 9}
                                                    textAnchor="middle"
                                                    fill="white"
                                                    fontSize={10}
                                                    fontWeight={700}
                                                    fontFamily="Outfit"
                                                >
                                                    {(branch.emoji ? `${branch.emoji} ` : "") + branch.category}
                                                </text>
                                                {branch.causes.map((cause, ci) => {
                                                    const cy = by + 24 + ci * 18;
                                                    return (
                                                        <text
                                                            key={`${cause}-${ci}`}
                                                            x={bx + 8}
                                                            y={cy}
                                                            fontSize={8}
                                                            fill="hsl(var(--muted-foreground))"
                                                            fontFamily="Outfit"
                                                        >
                                                            ─ {cause.length > 38 ? `${cause.slice(0, 38)}…` : cause}
                                                        </text>
                                                    );
                                                })}
                                            </motion.g>
                                        );
                                    })}
                                </svg>
                            </div>

                            <div className="md:hidden space-y-3">
                                {(effect || effectLabel) ? (
                                    <div className="bg-valencia rounded-xl p-4 text-center">
                                        {effectLabel ? (
                                            <p className="font-display text-xs tracking-[0.15em] uppercase text-milk/70 mb-1">
                                                {effectLabel}
                                            </p>
                                        ) : null}
                                        {effect ? (
                                            <p className="font-display text-sm font-bold text-milk">{effect}</p>
                                        ) : null}
                                    </div>
                                ) : null}

                                <div className="grid grid-cols-2 gap-3">
                                    {branches.map((branch, index) => {
                                        const bg = resolveColor(branch.color).bg;
                                        return (
                                            <div
                                                key={`${branch.category}-${index}`}
                                                className="bg-muted rounded-xl overflow-hidden"
                                            >
                                                {(branch.emoji || branch.category) ? (
                                                    <div className={`${bg} px-3 py-2 flex items-center gap-1.5`}>
                                                        {branch.emoji ? (
                                                            <span className="text-sm" aria-hidden>{branch.emoji}</span>
                                                        ) : null}
                                                        {branch.category ? (
                                                            <span className="font-display text-xs font-bold text-milk">
                                                                {branch.category}
                                                            </span>
                                                        ) : null}
                                                    </div>
                                                ) : null}
                                                {branch.causes.length > 0 ? (
                                                    <div className="p-3 space-y-1.5">
                                                        {branch.causes.map((cause, causeIndex) => (
                                                            <p
                                                                key={`${cause}-${causeIndex}`}
                                                                className="text-[0.65rem] text-foreground leading-tight flex items-start gap-1"
                                                            >
                                                                <span className="text-muted-foreground shrink-0">─</span>
                                                                {cause}
                                                            </p>
                                                        ))}
                                                    </div>
                                                ) : null}
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>
                        </>
                    ) : null}

                    {interventions.length > 0 ? (
                        <div className="mt-8 bg-muted rounded-xl p-6">
                            {interventionsTitle ? (
                                <p className="font-display text-xs tracking-[0.15em] uppercase text-deep-sea mb-3">
                                    {interventionsTitle}
                                </p>
                            ) : null}
                            <div className="grid sm:grid-cols-2 gap-2">
                                {interventions.map((item, i) => (
                                    <div key={`${item}-${i}`} className="flex items-start gap-2 text-sm text-foreground">
                                        <span className="shrink-0 w-5 h-5 rounded-full bg-deep-sea text-milk flex items-center justify-center font-display text-[0.6rem] font-bold mt-0.5">
                                            {i + 1}
                                        </span>
                                        {item}
                                    </div>
                                ))}
                            </div>
                        </div>
                    ) : null}
                </motion.div>
            </div>
        </section>
    );
}
