"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { useEditContext } from "../client/editContext";
import { Plus } from "lucide-react";
import { cn } from "../../lib/utils";
import { Tooltip, TooltipContent, TooltipTrigger, } from "../../components/ui/tooltip";
import { buildInsertMenuItems, getVisibleInsertOptions, } from "../insertMenuItems";
export function PlaceholderDropZone({ placeholder, description, index, parentName, spotPosition, spotPositionElement, spotPositionAnchor, size, className, insertMenuTitle, typeIdOnCtrlClick, isLayoutZone, }) {
    const [isHovering, setIsHovering] = useState(false);
    const dropZoneRef = useRef(null);
    const editContext = useEditContext();
    function dragOver(ev) {
        if (editContext?.mode !== "edit" || editContext?.readonly) {
            ev.dataTransfer.dropEffect = "none";
            return;
        }
        ev.dataTransfer.dropEffect =
            editContext?.dragObject?.type == "template" ? "copy" : "move";
        if (!isHovering)
            setIsHovering(true);
        ev.preventDefault();
    }
    function drop(ev) {
        if (editContext?.mode !== "edit" || editContext?.readonly) {
            ev.preventDefault();
            setIsHovering(false);
            return;
        }
        ev.preventDefault();
        setIsHovering(false);
        editContext.setStatusMessage("");
        editContext.droppedInPlaceholder(placeholder.key, index, spotPositionElement, spotPositionAnchor);
    }
    const overlayStyle = {
        top: spotPosition.y,
        left: spotPosition.x,
        zIndex: isHovering ? 40 : 30,
        transform: "none",
    };
    if (size === "small")
        overlayStyle.transform = "scale(0.5)";
    useEffect(() => {
        if (!editContext)
            return;
        if (isHovering) {
            editContext.setStatusMessage(_jsxs("div", { children: ["Drop into placeholder ", _jsx("span", { className: "font-bold", children: parentName }), " ", "/ ", _jsx("span", { className: "font-bold", children: description || placeholder.name }), " ", "at position ", _jsx("span", { className: "font-bold", children: index + 1 })] }));
        }
        else {
            editContext.setStatusMessage("");
        }
        return () => {
            // Clear status message when unmounting or when effect re-runs
            editContext.setStatusMessage("");
        };
        // Intentionally exclude editContext from deps to avoid effect loops when the
        // provider recreates the context value during updates.
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [isHovering]);
    // Return null after all hooks have been called to avoid breaking React's Rules of Hooks
    if (!editContext || editContext.readonly)
        return null;
    const visibleInsertOptions = getVisibleInsertOptions(placeholder.insertOptions);
    if (visibleInsertOptions.length === 0)
        return null;
    const formatPlaceholderLabel = (rawLabel, currentPlaceholder) => {
        const isImplicit = currentPlaceholder.key.startsWith("implicit_");
        if (!isImplicit)
            return rawLabel;
        const guidRegex = /([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})/;
        const guidMatch = rawLabel.match(guidRegex);
        if (!guidMatch)
            return rawLabel;
        const guid = guidMatch[1].toLowerCase();
        const parentComponent = currentPlaceholder.parentComponent;
        const matchingItem = [
            parentComponent?.datasourceItem,
            ...(parentComponent?.items ?? []),
        ].find((item) => item?.id?.toLowerCase() === guid);
        const resolvedName = matchingItem?.displayName || matchingItem?.name;
        if (!resolvedName)
            return rawLabel;
        return rawLabel.replace(guidRegex, resolvedName);
    };
    const ctrlTypeOption = typeIdOnCtrlClick
        ? visibleInsertOptions.find((x) => x.typeId === typeIdOnCtrlClick)
        : undefined;
    const ctrlTypeName = ctrlTypeOption?.name;
    const placeholderLabel = `${formatPlaceholderLabel(description ?? placeholder.name, placeholder)} (${index + 1})`;
    const tooltipBody = typeIdOnCtrlClick ? (_jsxs("div", { className: "p-1 text-sm", children: [_jsx("div", { className: "text-neutral-grey-50 mb-1.5 text-xs", children: placeholderLabel }), _jsxs("div", { className: "text-neutral-grey-50 space-y-0.5 text-xs", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "badge-pad-sm rounded bg-white/10 font-mono text-[10px]", children: "Click" }), _jsx("span", { children: "Open menu" })] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "badge-pad-sm rounded bg-white/10 font-mono text-[10px]", children: "Ctrl+Click" }), _jsxs("span", { children: ["Quick-add ", ctrlTypeName || "same type"] })] })] })] })) : (_jsx("div", { className: "p-1 text-sm", children: _jsx("div", { className: "text-neutral-grey-50 text-xs", children: placeholderLabel }) }));
    function dragLeave(ev) {
        // Check if we're actually leaving the drop zone (not just moving to a child element)
        const relatedTarget = ev.relatedTarget;
        if (dropZoneRef.current &&
            relatedTarget &&
            dropZoneRef.current.contains(relatedTarget)) {
            // Still within the drop zone, don't clear hovering state
            return;
        }
        setIsHovering(false);
    }
    return (_jsx("div", { className: "pointer-events-auto absolute", style: overlayStyle, children: _jsxs("div", { ref: dropZoneRef, onDragOver: dragOver, "data-testid": "placeholder-dropzone", "data-testindex": index, onDrop: drop, onDragLeave: dragLeave, onClick: (e) => {
                // Prevent the initiating click from bubbling to the window-level
                // context menu close handlers, which would immediately close the menu
                // after opening it.
                e.stopPropagation();
                // Quick-insert on Ctrl+Click: add a component of the provided type immediately
                if (e.ctrlKey && typeIdOnCtrlClick) {
                    e.preventDefault();
                    e.stopPropagation();
                    const sameTypeOption = visibleInsertOptions.find((x) => x.typeId === typeIdOnCtrlClick);
                    if (sameTypeOption) {
                        editContext.droppedInPlaceholder(placeholder.key, index, spotPositionElement, spotPositionAnchor, sameTypeOption);
                    }
                    else {
                        editContext.operations.addComponent(typeIdOnCtrlClick, placeholder.key, index, editContext.currentItemDescriptor);
                    }
                    return;
                }
                //const placeholderKeyComponents = placeholder.key.split("_");
                // const parentId =
                //   placeholderKeyComponents.length === 1
                //     ? undefined
                //     : placeholderKeyComponents[0];
                const insertOption = visibleInsertOptions.find((x) => x.typeId === editContext.selectedForInsertion);
                if (insertOption) {
                    editContext.droppedInPlaceholder(placeholder.key, index, spotPositionElement, spotPositionAnchor, insertOption);
                    return;
                }
                const insertMenuItems = buildInsertMenuItems(visibleInsertOptions, async (x) => {
                    await editContext.operations.addComponent(x.typeId, placeholder.key, index, editContext.currentItemDescriptor);
                });
                if (insertMenuItems.length > 0)
                    editContext.showContextMenu(e, [
                        {
                            id: "header",
                            label: insertMenuTitle || "Insert Component",
                            disabled: true,
                            className: "pb-0.5 text-neutral-grey-50",
                        },
                        ...insertMenuItems,
                    ]);
                e.preventDefault();
            }, className: "placeholder placeholder-dropzone pointer-events-auto cursor-pointer", children: [isHovering && (_jsx("div", { className: "pointer-events-none absolute top-full left-1/2 z-50 mt-3 min-w-max -translate-x-1/2", "data-testid": "placeholder-dropzone-drag-label", children: _jsx("div", { className: "bg-neutral-grey-100/95 rounded-md border-0 text-white shadow-xl backdrop-blur-md", children: tooltipBody }) })), _jsxs(Tooltip, { delayDuration: 500, children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("div", { draggable: false, className: cn("test-ph-dropzone tour-placeholder-dropzone", "absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2", "flex items-center justify-center rounded-full", "h-8 w-8", "text-white", "transition-all duration-300 ease-out", "border border-white/50", isHovering ? "z-40 scale-[1.15]" : "z-30 hover:scale-[1.15]", isLayoutZone ? "bg-highlight-100" : "bg-component-default", className), style: {
                                    boxShadow: isLayoutZone
                                        ? isHovering
                                            ? "0 8px 24px color-mix(in srgb, var(--color-highlight-100) 50%, transparent)"
                                            : "0 4px 12px color-mix(in srgb, var(--color-highlight-100) 30%, transparent)"
                                        : isHovering
                                            ? "0 8px 24px color-mix(in srgb, var(--color-component-default) 50%, transparent)"
                                            : "0 4px 12px color-mix(in srgb, var(--color-component-default) 30%, transparent)",
                                }, "data-testid": "placeholder-dropzone-button", children: _jsx(Plus, { className: "h-4 w-4", strokeWidth: 2.5, style: { pointerEvents: "none" } }) }) }), _jsx(TooltipContent, { className: "bg-neutral-grey-100/95 border-0 text-white shadow-xl backdrop-blur-md", sideOffset: 8, children: tooltipBody })] })] }) }));
}
//# sourceMappingURL=PlaceholderDropZone.js.map