'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useCallback, useMemo } from 'react';
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, } from '@dnd-kit/core';
import { SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy, useSortable, arrayMove, } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Plus, GripVertical, Trash2, ChevronDown, ChevronRight, Layout, Megaphone, Columns3, Image, Quote, Play, X, } from 'lucide-react';
import { PRESET_BLOCKS } from './block-types.js';
const BLOCK_ICONS = {
    layout: Layout,
    megaphone: Megaphone,
    columns: Columns3,
    image: Image,
    quote: Quote,
    play: Play,
};
function BlockField({ field, value, onChange }) {
    if (field.type === 'select' && field.options) {
        return (_jsxs("div", { children: [_jsxs("label", { className: "mb-1 block text-sm font-medium", children: [field.label, field.required && _jsx("span", { className: "ml-0.5 text-[var(--destructive)]", children: "*" })] }), _jsxs("select", { value: value ?? '', onChange: (e) => onChange(e.target.value), className: "w-full rounded-md border border-[var(--border)] bg-[var(--input-background)] px-3 py-2 text-sm transition-colors outline-none focus:ring-2 focus:ring-[var(--ring)]", children: [_jsx("option", { value: "", children: "Select..." }), field.options.map((opt) => (_jsx("option", { value: opt.value, children: opt.label }, opt.value)))] })] }));
    }
    if (field.type === 'richText') {
        return (_jsxs("div", { children: [_jsxs("label", { className: "mb-1 block text-sm font-medium", children: [field.label, field.required && _jsx("span", { className: "ml-0.5 text-[var(--destructive)]", children: "*" })] }), _jsx("textarea", { value: value ?? '', onChange: (e) => onChange(e.target.value), rows: 4, className: "w-full rounded-md border border-[var(--border)] bg-[var(--input-background)] px-3 py-2 text-sm transition-colors outline-none focus:ring-2 focus:ring-[var(--ring)]" })] }));
    }
    if (field.type === 'media') {
        return (_jsxs("div", { children: [_jsxs("label", { className: "mb-1 block text-sm font-medium", children: [field.label, field.required && _jsx("span", { className: "ml-0.5 text-[var(--destructive)]", children: "*" })] }), _jsxs("div", { className: "flex items-center gap-3 rounded-md border border-dashed border-[var(--border)] p-3", children: [_jsx("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-[var(--muted)]", children: _jsx(Image, { className: "h-5 w-5 text-[var(--muted-foreground)]" }) }), _jsx("span", { className: "text-sm text-[var(--muted-foreground)]", children: value ? 'Media selected' : 'No media selected' })] })] }));
    }
    return (_jsxs("div", { children: [_jsxs("label", { className: "mb-1 block text-sm font-medium", children: [field.label, field.required && _jsx("span", { className: "ml-0.5 text-[var(--destructive)]", children: "*" })] }), _jsx("input", { type: "text", value: value ?? '', onChange: (e) => onChange(e.target.value), required: field.required, className: "w-full rounded-md border border-[var(--border)] bg-[var(--input-background)] px-3 py-2 text-sm transition-colors outline-none focus:ring-2 focus:ring-[var(--ring)]" })] }));
}
function SortableBlock({ block, blockDef, expanded, onToggle, onRemove, onFieldChange, }) {
    const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
        id: block.id,
    });
    const style = {
        transform: CSS.Transform.toString(transform),
        transition,
        opacity: isDragging ? 0.5 : 1,
        zIndex: isDragging ? 10 : undefined,
    };
    const IconComponent = blockDef ? BLOCK_ICONS[blockDef.icon] : undefined;
    return (_jsxs("div", { ref: setNodeRef, style: style, className: "rounded-md border border-[var(--border)] bg-[var(--card)]", children: [_jsxs("div", { className: "flex items-center gap-2 border-b border-[var(--border)] px-3 py-2", children: [_jsx("button", { type: "button", className: "cursor-grab touch-none text-[var(--muted-foreground)] hover:text-[var(--foreground)]", ...attributes, ...listeners, children: _jsx(GripVertical, { className: "h-4 w-4" }) }), IconComponent && _jsx(IconComponent, { className: "h-4 w-4 text-[var(--muted-foreground)]" }), _jsxs("button", { type: "button", onClick: onToggle, className: "flex flex-1 items-center gap-1.5 text-sm font-medium", children: [blockDef?.label ?? block.type, expanded ? (_jsx(ChevronDown, { className: "h-3.5 w-3.5 text-[var(--muted-foreground)]" })) : (_jsx(ChevronRight, { className: "h-3.5 w-3.5 text-[var(--muted-foreground)]" }))] }), _jsx("button", { type: "button", onClick: onRemove, className: "text-[var(--muted-foreground)] hover:text-[var(--destructive)]", "aria-label": "Remove block", children: _jsx(Trash2, { className: "h-4 w-4" }) })] }), expanded && blockDef && (_jsx("div", { className: "space-y-4 p-4", children: blockDef.fields.map((field) => (_jsx(BlockField, { field: field, value: block.data[field.name], onChange: (val) => onFieldChange(field.name, val) }, field.name))) })), expanded && !blockDef && (_jsxs("div", { className: "p-4 text-sm text-[var(--muted-foreground)]", children: ["Unknown block type: ", _jsx("code", { children: block.type })] }))] }));
}
export function BlockBuilderField({ label, value = [], onChange, blocks: customBlocks, helpText, }) {
    const [expandedIds, setExpandedIds] = useState(new Set());
    const [pickerOpen, setPickerOpen] = useState(false);
    const allBlockTypes = useMemo(() => {
        if (!customBlocks?.length)
            return PRESET_BLOCKS;
        const customTypes = new Set(customBlocks.map((b) => b.type));
        const filtered = PRESET_BLOCKS.filter((b) => !customTypes.has(b.type));
        return [...filtered, ...customBlocks];
    }, [customBlocks]);
    const blockDefMap = useMemo(() => {
        const map = new Map();
        for (const def of allBlockTypes) {
            map.set(def.type, def);
        }
        return map;
    }, [allBlockTypes]);
    const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }), useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }));
    const handleDragEnd = useCallback((event) => {
        const { active, over } = event;
        if (!over || active.id === over.id)
            return;
        const oldIndex = value.findIndex((b) => b.id === active.id);
        const newIndex = value.findIndex((b) => b.id === over.id);
        if (oldIndex === -1 || newIndex === -1)
            return;
        onChange?.(arrayMove(value, oldIndex, newIndex));
    }, [value, onChange]);
    function addBlock(type) {
        const newBlock = {
            id: crypto.randomUUID(),
            type,
            data: {},
        };
        const newId = newBlock.id;
        onChange?.([...value, newBlock]);
        setExpandedIds((prev) => new Set(prev).add(newId));
        setPickerOpen(false);
    }
    function removeBlock(id) {
        onChange?.(value.filter((b) => b.id !== id));
        setExpandedIds((prev) => {
            const next = new Set(prev);
            next.delete(id);
            return next;
        });
    }
    function toggleExpand(id) {
        setExpandedIds((prev) => {
            const next = new Set(prev);
            if (next.has(id)) {
                next.delete(id);
            }
            else {
                next.add(id);
            }
            return next;
        });
    }
    function updateBlockField(blockId, fieldName, fieldValue) {
        onChange?.(value.map((b) => b.id === blockId ? { ...b, data: { ...b.data, [fieldName]: fieldValue } } : b));
    }
    const blockIds = value.map((b) => b.id);
    return (_jsxs("div", { children: [label && _jsx("label", { className: "mb-2 block text-sm font-medium", children: label }), _jsx(DndContext, { sensors: sensors, collisionDetection: closestCenter, onDragEnd: handleDragEnd, children: _jsx(SortableContext, { items: blockIds, strategy: verticalListSortingStrategy, children: _jsx("div", { className: "space-y-2", children: value.map((block) => (_jsx(SortableBlock, { block: block, blockDef: blockDefMap.get(block.type), expanded: expandedIds.has(block.id), onToggle: () => toggleExpand(block.id), onRemove: () => removeBlock(block.id), onFieldChange: (name, val) => updateBlockField(block.id, name, val) }, block.id))) }) }) }), value.length === 0 && (_jsx("div", { className: "rounded-md border border-dashed border-[var(--border)] px-4 py-8 text-center text-sm text-[var(--muted-foreground)]", children: "No blocks added yet. Click \u201CAdd Block\u201D to get started." })), _jsx("div", { className: "relative mt-3", children: _jsxs("button", { type: "button", onClick: () => setPickerOpen((prev) => !prev), className: "inline-flex items-center gap-1.5 rounded-md border border-dashed border-[var(--border)] px-3 py-2 text-sm text-[var(--muted-foreground)] transition-colors hover:border-[var(--foreground)] hover:text-[var(--foreground)]", children: [_jsx(Plus, { className: "h-4 w-4" }), "Add Block"] }) }), pickerOpen && (_jsx("div", { className: "fixed inset-0 z-50 flex items-center justify-center bg-black/50", children: _jsxs("div", { className: "w-full max-w-2xl rounded-lg border border-[var(--border)] bg-[var(--card)] shadow-xl", children: [_jsxs("div", { className: "flex items-center justify-between border-b border-[var(--border)] px-5 py-4", children: [_jsx("h3", { className: "text-base font-semibold", children: "Add Block" }), _jsx("button", { type: "button", onClick: () => setPickerOpen(false), className: "text-[var(--muted-foreground)] hover:text-[var(--foreground)]", "aria-label": "Close", children: _jsx(X, { className: "h-5 w-5" }) })] }), _jsx("div", { className: "grid grid-cols-2 gap-3 p-5 sm:grid-cols-3", children: allBlockTypes.map((bt) => {
                                const Icon = BLOCK_ICONS[bt.icon];
                                return (_jsxs("button", { type: "button", onClick: () => addBlock(bt.type), className: "flex flex-col items-start gap-1.5 rounded-md border border-[var(--border)] p-3 text-left transition-colors hover:border-[var(--primary)] hover:bg-[var(--accent)]", children: [Icon && _jsx(Icon, { className: "h-5 w-5 text-[var(--primary)]" }), _jsx("span", { className: "text-sm font-medium", children: bt.label }), _jsx("span", { className: "text-xs leading-snug text-[var(--muted-foreground)]", children: bt.description })] }, bt.type));
                            }) })] }) })), helpText && _jsx("p", { className: "mt-1 text-xs text-[var(--muted-foreground)]", children: helpText })] }));
}
//# sourceMappingURL=BlockBuilderField.js.map