import { useMemo, useState } from "react";
import { Check, ChevronsUpDown } from "lucide-react";
import { Input } from "@/components/ui/input";
import {
    Command,
    CommandGroup,
    CommandInput,
    CommandItem,
    CommandList,
} from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { CardEditGroup, CardEditPanel } from "./CardEditLayout";
import { EmojiPickerField } from "./EmojiPickerField";
import { ImageIconField } from "./ImageIconField";
import { useComponentDefaults } from "@/hooks/useComponentDefaults";
import { cn } from "@/lib/utils";
import {
    emptyCompetitionNavItem,
    getCompetitionNavigation,
    type CompetitionNavItem,
} from "@/lib/competitionNavigation";

type BlockContent = Record<string, unknown>;
type TextListKey = "featureHighlights" | "badges";
type HeroButtonEdit = {
    id: string;
    label: string;
    icon: string;
    href: string;
    variant: "primary" | "secondary";
};
type HeroStatisticEdit = { value: string; label: string };
type CompetitionNavEdit = CompetitionNavItem;
type TargetComponentOption = {
    id: number;
    value: string;
    slug: string;
    label: string;
    preferred: boolean;
};

export type EnsurePageComponentTarget = {
    id: number;
    name: string;
    slug: string;
};

export type EnsurePageComponentResult = {
    status: "created" | "linked";
    sectionIndex: number;
    blockIndex: number;
};

const labelCls = "block text-sm font-medium text-slate-700 mb-1.5";
const fieldGroupCls = "space-y-4";

function TargetComponentPicker({
    value,
    options,
    disabled,
    onSelectOption,
}: {
    value: string;
    options: TargetComponentOption[];
    disabled?: boolean;
    onSelectOption: (option: TargetComponentOption) => void;
}) {
    const [open, setOpen] = useState(false);
    const [query, setQuery] = useState("");
    const selected = options.find((option) => (
        option.value === value || option.slug === value
    ));
    const trimmedQuery = query.trim();
    const filteredOptions = useMemo(() => {
        if (!trimmedQuery) return [];
        const needle = trimmedQuery.toLowerCase();
        return options.filter((option) => (
            option.value.toLowerCase().includes(needle)
            || option.slug.toLowerCase().includes(needle)
            || option.label.toLowerCase().includes(needle)
        ));
    }, [options, trimmedQuery]);

    const handleOpenChange = (nextOpen: boolean) => {
        setOpen(nextOpen);
        if (!nextOpen) setQuery("");
    };

    return (
        <Popover open={open} onOpenChange={handleOpenChange}>
            <PopoverTrigger asChild>
                <button
                    type="button"
                    role="combobox"
                    aria-expanded={open}
                    disabled={disabled}
                    className={cn(
                        "flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-left text-sm",
                        !selected && !value && "text-muted-foreground",
                        disabled && "cursor-not-allowed opacity-50",
                    )}
                >
                    <span className="truncate">
                        {selected?.label || value || "Select Component"}
                    </span>
                    <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                </button>
            </PopoverTrigger>
            <PopoverContent
                align="start"
                className="w-[var(--radix-popover-trigger-width)] p-0"
            >
                <Command shouldFilter={false}>
                    <CommandInput
                        placeholder="Search by name or slug…"
                        autoFocus
                        value={query}
                        onValueChange={setQuery}
                    />
                    <CommandList>
                        {!trimmedQuery ? (
                            <p className="py-6 px-3 text-center text-sm text-muted-foreground">
                                Type to search components…
                            </p>
                        ) : filteredOptions.length === 0 ? (
                            <p className="py-6 px-3 text-center text-sm text-muted-foreground">
                                No matching components found.
                            </p>
                        ) : (
                            <CommandGroup>
                                {filteredOptions.map((option) => (
                                    <CommandItem
                                        key={option.slug}
                                        value={`${option.label} ${option.value} ${option.slug}`}
                                        onSelect={() => {
                                            onSelectOption(option);
                                            setOpen(false);
                                            setQuery("");
                                        }}
                                    >
                                        <Check
                                            className={cn(
                                                "mr-2 h-4 w-4",
                                                selected?.slug === option.slug
                                                    ? "opacity-100"
                                                    : "opacity-0",
                                            )}
                                        />
                                        <span className="min-w-0">
                                            <span className="block truncate">{option.value}</span>
                                            <span className="block truncate text-xs text-muted-foreground">
                                                {option.slug}
                                            </span>
                                        </span>
                                    </CommandItem>
                                ))}
                            </CommandGroup>
                        )}
                    </CommandList>
                </Command>
            </PopoverContent>
        </Popover>
    );
}

function textItems(value: unknown): string[] {
    if (!Array.isArray(value)) return [];

    return value.map((item) => {
        if (typeof item === "string") return item;
        const record = item as Record<string, unknown>;
        return typeof record.label === "string"
            ? record.label
            : typeof record.text === "string"
                ? record.text
                : "";
    });
}

function moveItem<T>(items: T[], index: number, direction: -1 | 1): T[] {
    const target = index + direction;
    if (target < 0 || target >= items.length) return items;

    const next = [...items];
    [next[index], next[target]] = [next[target], next[index]];
    return next;
}

function ToggleField({
    checked,
    label,
    hint,
    onChange,
}: {
    checked: boolean;
    label: string;
    hint?: string;
    onChange: (checked: boolean) => void;
}) {
    return (
        <label className="flex items-start gap-2 text-sm text-slate-700 cursor-pointer">
            <input
                type="checkbox"
                checked={checked}
                onChange={(event) => onChange(event.target.checked)}
                className="mt-0.5"
            />
            <span>
                <span className="font-medium">{label}</span>
                {hint ? <span className="block text-[10px] text-slate-500 mt-0.5">{hint}</span> : null}
            </span>
        </label>
    );
}

function TextRepeater({
    title,
    items,
    placeholder,
    onChange,
}: {
    title: string;
    items: string[];
    placeholder: string;
    onChange: (items: string[]) => void;
}) {
    const insertAfter = (index: number) => {
        onChange([...items.slice(0, index + 1), "", ...items.slice(index + 1)]);
    };

    return (
        <CardEditGroup
            label={title}
            layout="vertical"
            onAdd={() => onChange([...items, ""])}
            addLabel={`Add ${title.replace(/s$/, "")}`}
            isEmpty={items.length === 0}
            emptyMessage={`No ${title.toLowerCase()} configured. This section is hidden on the hero.`}
        >
            {items.map((item, index) => (
                <CardEditPanel
                    key={index}
                    index={index}
                    total={items.length}
                    layout="vertical"
                    positionLabel={`Item ${index + 1}`}
                    label={item}
                    onMoveUp={index > 0 ? () => onChange(moveItem(items, index, -1)) : undefined}
                    onMoveDown={index < items.length - 1 ? () => onChange(moveItem(items, index, 1)) : undefined}
                    onInsertAfter={() => insertAfter(index)}
                    onRemove={() => onChange(items.filter((_, itemIndex) => itemIndex !== index))}
                >
                    <div>
                        <label className={labelCls}>Text</label>
                        <Input
                            value={item}
                            onChange={(event) => onChange(items.map((value, itemIndex) => (
                                itemIndex === index ? event.target.value : value
                            )))}
                            placeholder={placeholder}
                        />
                    </div>
                </CardEditPanel>
            ))}
        </CardEditGroup>
    );
}

export function GradeHeroForm({
    content,
    onChange,
    onEnsurePageComponent,
    onApplyAndOpenBlock,
}: {
    content: BlockContent;
    onChange: (content: BlockContent) => void;
    /** Ensure the selected Competition Navigation target exists as a normal page block. */
    onEnsurePageComponent?: (target: EnsurePageComponentTarget) => EnsurePageComponentResult | null;
    /** Persist current Grade Hero content, then open another page block for editing. */
    onApplyAndOpenBlock?: (
        nextContent: BlockContent,
        location: { sectionIndex: number; blockIndex: number },
    ) => void;
}) {
    const { components, loading: componentsLoading, error: componentsError } = useComponentDefaults({
        source: "admin",
    });
    const set = (key: string, value: unknown) => onChange({ ...content, [key]: value });
    const setTextList = (key: TextListKey, items: string[]) => {
        const next = { ...content, [key]: items };
        if (key === "featureHighlights") delete next.pills;
        onChange(next);
    };

    const featureHighlights = Array.isArray(content.featureHighlights)
        ? textItems(content.featureHighlights)
        : textItems(content.pills);
    const badges = textItems(content.badges);
    const competitionNavigation: CompetitionNavEdit[] = Array.isArray(content.competitionNavigation)
        ? content.competitionNavigation.map((item, index) => {
            const record = item != null && typeof item === "object"
                ? item as Record<string, unknown>
                : {};
            return {
                id: typeof record.id === "string" && record.id.trim()
                    ? record.id
                    : `competition-nav-${index + 1}`,
                label: typeof record.label === "string" ? record.label : "",
                icon: typeof record.icon === "string" ? record.icon : "",
                targetComponent: typeof record.targetComponent === "string"
                    ? record.targetComponent
                    : typeof record.targetSlug === "string"
                        ? record.targetSlug
                        : "",
                badgeCount: typeof record.badgeCount === "string"
                    ? record.badgeCount
                    : typeof record.badgeCount === "number"
                        ? String(record.badgeCount)
                        : "",
            };
        })
        : getCompetitionNavigation(content);
    const preferredTargetSlugs = new Set([
        "orion-competitions",
        "public-competitions",
        "competition-tabs",
        "progress-how-it-works",
        "progress-sample-report",
    ]);
    const targetComponentOptions = components
        .map((component) => {
            const name = component.name?.trim() || component.slug;
            return {
                id: component.id,
                value: name,
                slug: component.slug,
                label: `${name} (${component.slug})`,
                preferred: preferredTargetSlugs.has(component.slug),
            };
        })
        .sort((a, b) => {
            if (a.preferred !== b.preferred) return a.preferred ? -1 : 1;
            return a.label.localeCompare(b.label);
        });

    const selectTargetComponent = (index: number, option: TargetComponentOption) => {
        const nextNavigation = competitionNavigation.map((item, itemIndex) => (
            itemIndex === index
                ? { ...item, targetComponent: option.value }
                : item
        ));
        const nextContent = { ...content, competitionNavigation: nextNavigation };
        onChange(nextContent);

        if (!onEnsurePageComponent) return;

        const result = onEnsurePageComponent({
            id: option.id,
            name: option.value,
            slug: option.slug,
        });
        if (result?.status === "created" && onApplyAndOpenBlock) {
            onApplyAndOpenBlock(nextContent, {
                sectionIndex: result.sectionIndex,
                blockIndex: result.blockIndex,
            });
        }
    };
    const buttons: HeroButtonEdit[] = Array.isArray(content.buttons)
        ? content.buttons.map((item, index) => {
            const record = typeof item === "string" ? { label: item } : item as Record<string, unknown>;
            return {
                id: typeof record.id === "string" ? record.id : `button-${index + 1}`,
                label: typeof record.label === "string" ? record.label : "",
                icon: typeof record.icon === "string" ? record.icon : "",
                href: typeof record.href === "string" ? record.href : "",
                variant: record.variant === "primary" ? "primary" : "secondary",
            };
        })
        : [];
    const statistics: HeroStatisticEdit[] = Array.isArray(content.statistics)
        ? content.statistics.map((item) => {
            if (typeof item === "string") return { value: "", label: item };
            const record = item as Record<string, unknown>;
            return {
                value: typeof record.value === "string" ? record.value : "",
                label: typeof record.label === "string" ? record.label : "",
            };
        })
        : [];

    const updateButton = (index: number, patch: Partial<HeroButtonEdit>) => {
        set("buttons", buttons.map((button, itemIndex) => (
            itemIndex === index ? { ...button, ...patch } : button
        )));
    };
    const insertButtonAfter = (index: number) => {
        const button: HeroButtonEdit = {
            id: `button-${Date.now()}`,
            label: "",
            icon: "",
            href: "",
            variant: "secondary",
        };
        set("buttons", [...buttons.slice(0, index + 1), button, ...buttons.slice(index + 1)]);
    };
    const updateStatistic = (index: number, patch: Partial<HeroStatisticEdit>) => {
        set("statistics", statistics.map((statistic, itemIndex) => (
            itemIndex === index ? { ...statistic, ...patch } : statistic
        )));
    };
    const insertStatisticAfter = (index: number) => {
        set("statistics", [
            ...statistics.slice(0, index + 1),
            { value: "", label: "" },
            ...statistics.slice(index + 1),
        ]);
    };
    const updateCompetitionNav = (index: number, patch: Partial<CompetitionNavEdit>) => {
        set("competitionNavigation", competitionNavigation.map((item, itemIndex) => {
            if (itemIndex !== index) return item;
            const next = { ...item, ...patch };
            // If label matches a known component and target is empty, auto-link it.
            if (patch.label && !next.targetComponent) {
                const match = targetComponentOptions.find((option) => (
                    option.value.toLowerCase() === patch.label!.trim().toLowerCase()
                    || option.slug === patch.label!.trim()
                ));
                if (match) next.targetComponent = match.value;
            }
            return next;
        }));
    };
    const insertCompetitionNavAfter = (index: number) => {
        set("competitionNavigation", [
            ...competitionNavigation.slice(0, index + 1),
            emptyCompetitionNavItem(),
            ...competitionNavigation.slice(index + 1),
        ]);
    };

    const tabClassName = "text-xs sm:text-sm whitespace-nowrap";

    return (
        <Tabs defaultValue="general" className="w-full">
            <TabsList className="w-full justify-start overflow-x-auto flex-nowrap h-auto p-1 mb-5">
                <TabsTrigger value="general" className={tabClassName}>General</TabsTrigger>
                <TabsTrigger value="hero-icon" className={tabClassName}>Hero Icon</TabsTrigger>
                <TabsTrigger value="navigation" className={tabClassName}>Navigation</TabsTrigger>
                <TabsTrigger value="competition-nav" className={tabClassName}>Competition Navigation</TabsTrigger>
                <TabsTrigger value="branding" className={tabClassName}>Branding</TabsTrigger>
                <TabsTrigger value="highlights" className={tabClassName}>Highlights</TabsTrigger>
                <TabsTrigger value="buttons" className={tabClassName}>Buttons</TabsTrigger>
                <TabsTrigger value="badges" className={tabClassName}>Badges &amp; Stats</TabsTrigger>
                <TabsTrigger value="theme" className={tabClassName}>Theme</TabsTrigger>
                <TabsTrigger value="appearance" className={tabClassName}>Appearance</TabsTrigger>
            </TabsList>

            <TabsContent value="general" className={fieldGroupCls}>
                <div>
                    <label className={labelCls}>Small label</label>
                    <Input
                        value={(content.smallLabel as string) ?? ""}
                        onChange={(event) => set("smallLabel", event.target.value)}
                        placeholder="Optional eyebrow label"
                    />
                </div>
                <div>
                    <label className={labelCls}>Title</label>
                    <Input
                        value={(content.title as string) ?? ""}
                        onChange={(event) => set("title", event.target.value)}
                        placeholder="e.g. Clubs"
                    />
                </div>
                <div>
                    <label className={labelCls}>Subtitle</label>
                    <textarea
                        value={(content.subtitle as string) ?? ""}
                        onChange={(event) => set("subtitle", event.target.value)}
                        rows={2}
                        className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[60px]"
                        placeholder="Optional subtitle"
                    />
                </div>
                <div>
                    <label className={labelCls}>Description</label>
                    <textarea
                        value={(content.description as string) ?? ""}
                        onChange={(event) => set("description", event.target.value)}
                        rows={3}
                        className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[80px]"
                        placeholder="Optional supporting description"
                    />
                </div>
            </TabsContent>

            <TabsContent value="hero-icon" className={fieldGroupCls}>
                <div>
                    <label className={labelCls}>Built-in emoji</label>
                    <EmojiPickerField
                        value={(content.heroIconEmoji as string) ?? ""}
                        onChange={(value) => set("heroIconEmoji", value)}
                        placeholder="Choose an optional hero emoji"
                    />
                </div>
                <div>
                    <label className={labelCls}>Custom image or icon URL</label>
                    <ImageIconField
                        value={(content.heroIconImage as string) ?? ""}
                        onChange={(value) => set("heroIconImage", value)}
                        placeholder="Upload an image, choose an asset, or paste a URL"
                    />
                    <p className="text-[10px] text-slate-500 mt-1">
                        PNG, SVG, and JPG images are supported. A configured image takes priority over the emoji.
                    </p>
                </div>
                {!content.heroIconImage && !content.heroIconEmoji ? (
                    <p className="text-xs text-slate-500 rounded-lg border border-dashed border-slate-300 bg-slate-50 p-3">
                        No hero icon configured. The icon area will be hidden without reserving space.
                    </p>
                ) : null}
            </TabsContent>

            <TabsContent value="navigation" className={fieldGroupCls}>
                <ToggleField
                    checked={content.showBackButton !== false}
                    label="Show back button"
                    onChange={(checked) => set("showBackButton", checked)}
                />
                <div>
                    <label className={labelCls}>Back label</label>
                    <Input
                        value={(content.backLabel as string) ?? ""}
                        onChange={(event) => set("backLabel", event.target.value)}
                        placeholder="Back to Kaleidoscope"
                    />
                </div>
                <div>
                    <label className={labelCls}>Back URL</label>
                    <Input
                        value={(content.backHref as string) ?? ""}
                        onChange={(event) => set("backHref", event.target.value)}
                        placeholder="/grade/kg"
                    />
                </div>
            </TabsContent>

            <TabsContent value="competition-nav">
                <CardEditGroup
                    label="Competition Navigation"
                    layout="vertical"
                    onAdd={() => set("competitionNavigation", [
                        ...competitionNavigation,
                        emptyCompetitionNavItem(),
                    ])}
                    addLabel="Add navigation item"
                    isEmpty={competitionNavigation.length === 0}
                    emptyMessage="No competition navigation configured. Add items to show tabs in the Grade Hero and switch between page components."
                >
                    {competitionNavigation.map((item, index) => (
                        <CardEditPanel
                            key={item.id || index}
                            index={index}
                            total={competitionNavigation.length}
                            layout="vertical"
                            positionLabel={`Tab ${index + 1}`}
                            label={item.label}
                            preview={{
                                emoji: item.icon,
                                title: item.label,
                                subtitle: item.targetComponent || "No target linked",
                            }}
                            onMoveUp={index > 0
                                ? () => set("competitionNavigation", moveItem(competitionNavigation, index, -1))
                                : undefined}
                            onMoveDown={index < competitionNavigation.length - 1
                                ? () => set("competitionNavigation", moveItem(competitionNavigation, index, 1))
                                : undefined}
                            onInsertAfter={() => insertCompetitionNavAfter(index)}
                            onRemove={() => set(
                                "competitionNavigation",
                                competitionNavigation.filter((_, itemIndex) => itemIndex !== index),
                            )}
                        >
                            <div className="grid sm:grid-cols-[auto_1fr] gap-3">
                                <div>
                                    <label className={labelCls}>Icon</label>
                                    <EmojiPickerField
                                        compact
                                        value={item.icon}
                                        onChange={(value) => updateCompetitionNav(index, { icon: value })}
                                        placeholder="Icon"
                                    />
                                </div>
                                <div>
                                    <label className={labelCls}>Label</label>
                                    <Input
                                        value={item.label}
                                        onChange={(event) => updateCompetitionNav(index, { label: event.target.value })}
                                        placeholder="e.g. Orion Competitions"
                                    />
                                </div>
                            </div>
                            <div>
                                <label className={labelCls}>Target Component</label>
                                <TargetComponentPicker
                                    value={item.targetComponent}
                                    options={targetComponentOptions}
                                    disabled={componentsLoading}
                                    onSelectOption={(option) => selectTargetComponent(index, option)}
                                />
                                {componentsLoading ? (
                                    <p className="text-[10px] text-slate-500 mt-1">Loading components…</p>
                                ) : componentsError ? (
                                    <p className="text-[10px] text-red-600 mt-1">
                                        Could not load components: {componentsError}
                                    </p>
                                ) : targetComponentOptions.length === 0 ? (
                                    <p className="text-[10px] text-amber-700 mt-1">
                                        No components found. Check that component modules are seeded, then reopen this editor.
                                    </p>
                                ) : !item.targetComponent ? (
                                    <p className="text-[10px] text-amber-700 mt-1">
                                        Required for page switching. Search and select a component — it will be added to this page automatically if needed.
                                    </p>
                                ) : (
                                    <p className="text-[10px] text-slate-500 mt-1">
                                        Linked. This tab shows that component on the page. Selecting a new target adds it to the page if it is not already there.
                                    </p>
                                )}
                            </div>
                            <div>
                                <label className={labelCls}>Badge Count</label>
                                <Input
                                    value={item.badgeCount}
                                    onChange={(event) => updateCompetitionNav(index, {
                                        badgeCount: event.target.value,
                                    })}
                                    placeholder="e.g. 16"
                                />
                            </div>
                        </CardEditPanel>
                    ))}
                </CardEditGroup>
                <p className="text-xs text-slate-500 mt-3">
                    Competition Navigation tabs replace CTA Buttons in the hero preview as soon as a Label is entered.
                    Search for a Target Component by name or slug — selecting one links the tab and adds the component to this page if it is not already present.
                </p>
            </TabsContent>

            <TabsContent value="branding" className={fieldGroupCls}>
                <ToggleField
                    checked={content.showLogo !== false}
                    label="Show logo"
                    hint="Disable it for icon-only detail pages."
                    onChange={(checked) => set("showLogo", checked)}
                />
                <div>
                    <label className={labelCls}>Logo URL</label>
                    <Input
                        value={(content.logoSrc as string) ?? ""}
                        onChange={(event) => set("logoSrc", event.target.value)}
                        placeholder="Uses the Orion logo when empty"
                    />
                </div>
                <div>
                    <label className={labelCls}>Logo alt text</label>
                    <Input
                        value={(content.logoAlt as string) ?? ""}
                        onChange={(event) => set("logoAlt", event.target.value)}
                        placeholder="Orion"
                    />
                </div>
            </TabsContent>

            <TabsContent value="highlights">
                <TextRepeater
                    title="Feature Highlights"
                    items={featureHighlights}
                    placeholder="e.g. Empowered Learning"
                    onChange={(items) => setTextList("featureHighlights", items)}
                />
            </TabsContent>

            <TabsContent value="buttons">
                <CardEditGroup
                    label="CTA Buttons"
                    layout="vertical"
                    onAdd={() => set("buttons", [
                        ...buttons,
                        { id: `button-${Date.now()}`, label: "", icon: "", href: "", variant: "secondary" },
                    ])}
                    addLabel="Add Button"
                    isEmpty={buttons.length === 0}
                    emptyMessage="No buttons configured. The button row is hidden on the hero."
                >
                    {buttons.map((button, index) => (
                        <CardEditPanel
                            key={button.id || index}
                            index={index}
                            total={buttons.length}
                            layout="vertical"
                            positionLabel={`Button ${index + 1}`}
                            label={button.label}
                            preview={{ emoji: button.icon, title: button.label, subtitle: button.href }}
                            onMoveUp={index > 0 ? () => set("buttons", moveItem(buttons, index, -1)) : undefined}
                            onMoveDown={index < buttons.length - 1 ? () => set("buttons", moveItem(buttons, index, 1)) : undefined}
                            onInsertAfter={() => insertButtonAfter(index)}
                            onRemove={() => set("buttons", buttons.filter((_, itemIndex) => itemIndex !== index))}
                        >
                            <div className="grid sm:grid-cols-[auto_1fr] gap-3">
                                <div>
                                    <label className={labelCls}>Icon</label>
                                    <EmojiPickerField
                                        compact
                                        value={button.icon}
                                        onChange={(value) => updateButton(index, { icon: value })}
                                        placeholder="Icon"
                                    />
                                </div>
                                <div>
                                    <label className={labelCls}>Label</label>
                                    <Input
                                        value={button.label}
                                        onChange={(event) => updateButton(index, { label: event.target.value })}
                                        placeholder="e.g. How It Works"
                                    />
                                </div>
                            </div>
                            <div>
                                <label className={labelCls}>URL or anchor (optional)</label>
                                <Input
                                    value={button.href}
                                    onChange={(event) => updateButton(index, { href: event.target.value })}
                                    placeholder="/page or #section"
                                />
                            </div>
                            <div>
                                <label className={labelCls}>Default style</label>
                                <select
                                    value={button.variant}
                                    onChange={(event) => updateButton(index, {
                                        variant: event.target.value === "primary" ? "primary" : "secondary",
                                    })}
                                    className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm h-10"
                                >
                                    <option value="secondary">Secondary</option>
                                    <option value="primary">Primary</option>
                                </select>
                            </div>
                        </CardEditPanel>
                    ))}
                </CardEditGroup>
            </TabsContent>

            <TabsContent value="badges" className="space-y-6">
                <TextRepeater
                    title="Badges"
                    items={badges}
                    placeholder="e.g. Sample for Families"
                    onChange={(items) => setTextList("badges", items)}
                />
                <CardEditGroup
                    label="Statistics"
                    layout="vertical"
                    onAdd={() => set("statistics", [...statistics, { value: "", label: "" }])}
                    addLabel="Add Statistic"
                    isEmpty={statistics.length === 0}
                    emptyMessage="No statistics configured. The statistics row is hidden on the hero."
                >
                    {statistics.map((statistic, index) => (
                        <CardEditPanel
                            key={index}
                            index={index}
                            total={statistics.length}
                            layout="vertical"
                            positionLabel={`Statistic ${index + 1}`}
                            label={[statistic.value, statistic.label].filter(Boolean).join(" ")}
                            onMoveUp={index > 0 ? () => set("statistics", moveItem(statistics, index, -1)) : undefined}
                            onMoveDown={index < statistics.length - 1 ? () => set("statistics", moveItem(statistics, index, 1)) : undefined}
                            onInsertAfter={() => insertStatisticAfter(index)}
                            onRemove={() => set("statistics", statistics.filter((_, itemIndex) => itemIndex !== index))}
                        >
                            <div className="grid sm:grid-cols-2 gap-3">
                                <div>
                                    <label className={labelCls}>Value</label>
                                    <Input
                                        value={statistic.value}
                                        onChange={(event) => updateStatistic(index, { value: event.target.value })}
                                        placeholder="e.g. 57"
                                    />
                                </div>
                                <div>
                                    <label className={labelCls}>Label</label>
                                    <Input
                                        value={statistic.label}
                                        onChange={(event) => updateStatistic(index, { label: event.target.value })}
                                        placeholder="clubs across 9 steering committees"
                                    />
                                </div>
                            </div>
                        </CardEditPanel>
                    ))}
                </CardEditGroup>
            </TabsContent>

            <TabsContent value="theme" className={fieldGroupCls}>
                <div>
                    <label className={labelCls}>Theme label</label>
                    <Input
                        value={(content.themeLabel as string) ?? ""}
                        onChange={(event) => set("themeLabel", event.target.value)}
                        placeholder="e.g. This year's theme:"
                    />
                </div>
                <div>
                    <label className={labelCls}>Theme line</label>
                    <Input
                        value={(content.themeLine as string) ?? ""}
                        onChange={(event) => set("themeLine", event.target.value)}
                        placeholder="e.g. Water — Every Drop Counts"
                    />
                    <p className="text-[10px] text-slate-500 mt-1">Both fields are optional; empty values reserve no space.</p>
                </div>
            </TabsContent>

            <TabsContent value="appearance" className={fieldGroupCls}>
                <div>
                    <label className={labelCls}>Layout</label>
                    <select
                        value={content.layout === "detail" ? "detail" : "brand"}
                        onChange={(event) => set("layout", event.target.value)}
                        className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm h-10"
                    >
                        <option value="brand">Brand — logo-led grade / Design to Impact</option>
                        <option value="detail">Detail — icon-led destination page</option>
                    </select>
                </div>
                <div>
                    <label className={labelCls}>Title size</label>
                    <select
                        value={content.titleSize === "compact" ? "compact" : "standard"}
                        onChange={(event) => set("titleSize", event.target.value)}
                        className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm h-10"
                    >
                        <option value="standard">Standard</option>
                        <option value="compact">Compact</option>
                    </select>
                </div>
                <ToggleField
                    checked={content.showBackgroundDecorations !== false}
                    label="Show background decoration"
                    onChange={(checked) => set("showBackgroundDecorations", checked)}
                />
                <div>
                    <label className={labelCls}>Background pattern</label>
                    <select
                        value={(content.backgroundPattern as string) ?? (content.layout === "detail" ? "radial" : "rays")}
                        onChange={(event) => set("backgroundPattern", event.target.value)}
                        className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm h-10"
                    >
                        <option value="none">None</option>
                        <option value="rays">Decorative SVG rays</option>
                        <option value="radial">Radial glow</option>
                    </select>
                </div>
                <div>
                    <label className={labelCls}>Accent color</label>
                    <select
                        value={(content.accentColor as string) ?? "deep-sea"}
                        onChange={(event) => set("accentColor", event.target.value)}
                        className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm h-10"
                    >
                        {["deep-sea", "valencia", "moss", "sunflower", "mist", "salmon"].map((color) => (
                            <option key={color} value={color}>{color}</option>
                        ))}
                    </select>
                </div>
                <div>
                    <label className={labelCls}>SVG ray count</label>
                    <Input
                        type="number"
                        min={1}
                        max={24}
                        value={typeof content.rayCount === "number" ? content.rayCount : 6}
                        onChange={(event) => set("rayCount", Number(event.target.value))}
                    />
                </div>
                <div>
                    <label className={labelCls}>Pattern position</label>
                    <Input
                        value={(content.patternPosition as string) ?? "50% 50%"}
                        onChange={(event) => set("patternPosition", event.target.value)}
                        placeholder="e.g. 40% 60%"
                    />
                </div>
                <div>
                    <label className={labelCls}>Background image URL</label>
                    <Input
                        value={(content.backgroundImage as string) ?? ""}
                        onChange={(event) => set("backgroundImage", event.target.value)}
                        placeholder="Optional image URL"
                    />
                </div>
                <ToggleField
                    checked={content.showOverlay !== false}
                    label="Show image overlay"
                    hint="Only visible when a background image is configured."
                    onChange={(checked) => set("showOverlay", checked)}
                />
                <div>
                    <label className={labelCls}>Overlay opacity (0–1)</label>
                    <Input
                        type="number"
                        min={0}
                        max={1}
                        step={0.05}
                        value={typeof content.overlayOpacity === "number" ? content.overlayOpacity : 0.35}
                        onChange={(event) => set("overlayOpacity", Number(event.target.value))}
                    />
                </div>
            </TabsContent>
        </Tabs>
    );
}
