import { motion } from "framer-motion";
import { staggerContainer, fadeUpItem } from "@/components/PageTransition";

type Content = Record<string, unknown>;

export type PortraitGoal = {
    emoji: string;
    title: string;
    color: string;
    characterGoal: string;
    mindsetGoal: string;
};

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

export const PORTRAIT_GOAL_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 defaultPortraitGoals: PortraitGoal[] = [
    {
        emoji: "🚀",
        title: "Bold Visionary Leader",
        color: "valencia",
        characterGoal: "Share at least one original idea per week in class discussions, progressing to leading a team brainstorm by Q3",
        mindsetGoal: "Shift from 'What if I'm wrong?' to 'What if I try?' — embrace possibility thinking",
    },
    {
        emoji: "⚖️",
        title: "Balanced Person",
        color: "sunflower",
        characterGoal: "Build a personal calm-down toolkit with 3 strategies; use independently by Q2",
        mindsetGoal: "Develop self-awareness: recognize body signals of frustration and name emotions accurately",
    },
    {
        emoji: "💬",
        title: "Inspiring Communicator",
        color: "deep-sea",
        characterGoal: "Progress from drawing-based expression to verbal + visual presentations by Q4 Showcase",
        mindsetGoal: "Believe that my voice matters — practice 'I think…because…' sentence frames daily",
    },
    {
        emoji: "💪",
        title: "Resilient Problem Solver",
        color: "moss",
        characterGoal: "Attempt at least two strategies before seeking help; document 'revision stories' monthly",
        mindsetGoal: "Reframe failure as data: 'This didn't work — what did I learn?' becomes automatic",
    },
    {
        emoji: "🤝",
        title: "Respectful Relationship Builder",
        color: "mist",
        characterGoal: "Learn active listening (eye contact, paraphrase) and practice daily in partner work",
        mindsetGoal: "Value diverse perspectives: seek out classmates with different ideas during projects",
    },
    {
        emoji: "🌍",
        title: "Caring Citizen",
        color: "salmon",
        characterGoal: "Identify one community need and take measurable action through the PBEL Water project",
        mindsetGoal: "See myself as someone who can make a difference — track impact with simple data",
    },
];

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

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

export function parsePortraitGoals(content?: Content): PortraitGoal[] {
    const raw = content?.goals;
    if (!Array.isArray(raw) || raw.length === 0) return defaultPortraitGoals;

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

export function PortraitGoalsGridBlock({ content }: { content?: Content }) {
    const stepLabel = str(content?.stepLabel).trim();
    const stepLabelColor = str(content?.stepLabelColor).trim() || "moss";
    const title = str(content?.title).trim();
    const subtitle = str(content?.subtitle).trim();
    const characterGoalLabel = str(content?.characterGoalLabel).trim() || "Character Goal";
    const mindsetGoalLabel = str(content?.mindsetGoalLabel).trim() || "Mindset Goal";
    const goals = parsePortraitGoals(content);
    const stepTextClass = resolveColor(stepLabelColor).text;

    if (goals.length === 0 && !stepLabel && !title && !subtitle) {
        return null;
    }

    return (
        <section className="py-16 bg-background">
            <div className="container mx-auto px-6 max-w-5xl">
                {(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}

                {goals.length > 0 ? (
                    <motion.div
                        className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4"
                        variants={staggerContainer}
                        initial="initial"
                        whileInView="animate"
                        viewport={{ once: true }}
                    >
                        {goals.map((goal, index) => {
                            const bg = resolveColor(goal.color).bg;
                            return (
                                <motion.div
                                    key={`${goal.title}-${index}`}
                                    variants={fadeUpItem}
                                    className="bg-card rounded-xl border border-border overflow-hidden"
                                >
                                    {(goal.emoji || goal.title) ? (
                                        <div className={`${bg} px-4 py-3 flex items-center gap-2`}>
                                            {goal.emoji ? (
                                                <span className="text-xl" aria-hidden>{goal.emoji}</span>
                                            ) : null}
                                            {goal.title ? (
                                                <h3 className="font-display text-xs font-bold text-milk tracking-wide">
                                                    {goal.title}
                                                </h3>
                                            ) : null}
                                        </div>
                                    ) : null}
                                    {(goal.characterGoal || goal.mindsetGoal) ? (
                                        <div className="p-5 space-y-4">
                                            {goal.characterGoal ? (
                                                <div>
                                                    {characterGoalLabel ? (
                                                        <p className="font-display text-[0.65rem] tracking-[0.15em] uppercase text-muted-foreground mb-1.5 flex items-center gap-1">
                                                            <span className="w-2 h-2 rounded-full bg-valencia inline-block" />{" "}
                                                            {characterGoalLabel}
                                                        </p>
                                                    ) : null}
                                                    <p className="text-sm text-foreground leading-relaxed">
                                                        {goal.characterGoal}
                                                    </p>
                                                </div>
                                            ) : null}
                                            {goal.mindsetGoal ? (
                                                <div>
                                                    {mindsetGoalLabel ? (
                                                        <p className="font-display text-[0.65rem] tracking-[0.15em] uppercase text-muted-foreground mb-1.5 flex items-center gap-1">
                                                            <span className="w-2 h-2 rounded-full bg-deep-sea inline-block" />{" "}
                                                            {mindsetGoalLabel}
                                                        </p>
                                                    ) : null}
                                                    <p className="text-sm text-foreground leading-relaxed">
                                                        {goal.mindsetGoal}
                                                    </p>
                                                </div>
                                            ) : null}
                                        </div>
                                    ) : null}
                                </motion.div>
                            );
                        })}
                    </motion.div>
                ) : null}
            </div>
        </section>
    );
}
