import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useState, useRef, useEffect } from "react";
import { Popover, PopoverContent, PopoverAnchor, } from "../components/ui/popover";
import { Button } from "../components/ui/button";
import { ArrowLeft } from "lucide-react";
import { cn } from "../lib/utils";
const FieldActionsOverlay = React.forwardRef(({ generatorButtons, onActionClick, onParameterizedActionExecute, currentOverlay, fieldId, setCurrentOverlay, preSelectedAction, hideBackButton, iframe, onOpenChange, }, ref) => {
    const [isOpen, setIsOpen] = useState(false);
    const handleOpenChangeInternal = (open) => {
        setIsOpen(open);
        onOpenChange?.(open);
    };
    const suppressOutsideInteractionsUntilRef = useRef(0);
    const contentRef = useRef(null);
    const [anchorPosition, setAnchorPosition] = useState({ x: 0, y: 0 });
    const [selectedParameterizedAction, setSelectedParameterizedAction] = useState(null);
    const [parameterValues, setParameterValues] = useState({});
    const [touchedFields, setTouchedFields] = useState(new Set());
    const overlayId = fieldId + "_generators";
    useEffect(() => {
        // Only close when switching to another named overlay; ignore undefined resets
        if (currentOverlay && currentOverlay !== overlayId) {
            handleOpenChangeInternal(false);
            resetParameterizedAction();
        }
    }, [currentOverlay, overlayId]);
    // Close overlay when iframe scrolls
    useEffect(() => {
        if (!iframe || !isOpen)
            return;
        const handleScroll = () => {
            handleOpenChangeInternal(false);
            resetParameterizedAction();
        };
        const scrollContainer = iframe.contentDocument?.scrollingElement ||
            iframe.contentDocument?.body;
        scrollContainer?.addEventListener("scroll", handleScroll);
        iframe.contentWindow?.addEventListener("scroll", handleScroll);
        return () => {
            scrollContainer?.removeEventListener("scroll", handleScroll);
            iframe.contentWindow?.removeEventListener("scroll", handleScroll);
        };
    }, [iframe, isOpen]);
    // Auto-select preSelectedAction if provided (removed from useEffect)
    // Now handled in the show function
    function resetParameterizedAction() {
        setSelectedParameterizedAction(null);
        setParameterValues({});
        setTouchedFields(new Set());
    }
    function handleActionClick(action, event) {
        if (action.parameters && action.parameters.length > 0) {
            setSelectedParameterizedAction(action);
            // Initialize parameter values with defaults
            const initialValues = {};
            action.parameters.forEach((param) => {
                initialValues[param.id] = param.defaultValue || "";
            });
            setParameterValues(initialValues);
        }
        else {
            onActionClick(action, event);
            handleOpenChangeInternal(false);
        }
    }
    function executeParameterizedAction() {
        if (selectedParameterizedAction) {
            onParameterizedActionExecute(selectedParameterizedAction, parameterValues);
            resetParameterizedAction();
            handleOpenChangeInternal(false);
        }
    }
    function goBackToActionList() {
        resetParameterizedAction();
    }
    function cancelParameterizedAction() {
        resetParameterizedAction();
        handleOpenChangeInternal(false);
    }
    function updateParameterValue(paramId, value) {
        setParameterValues((prev) => ({ ...prev, [paramId]: value }));
    }
    function areRequiredParametersFilled() {
        if (!selectedParameterizedAction?.parameters)
            return true;
        return selectedParameterizedAction.parameters.every((param) => {
            if (!param.required)
                return true;
            const value = parameterValues[param.id] || "";
            return value.trim().length > 0;
        });
    }
    function renderParameterInput(param, shouldAutoFocus = false) {
        const value = parameterValues[param.id] || "";
        const isEmpty = value.trim().length === 0;
        const isRequired = param.required || false;
        const isTouched = touchedFields.has(param.id);
        const showError = isRequired && isEmpty && isTouched;
        const commonProps = {
            value,
            onChange: (e) => updateParameterValue(param.id, e.target.value),
            onBlur: () => {
                setTouchedFields((prev) => new Set(prev).add(param.id));
            },
            onKeyDown: (e) => {
                if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
                    e.preventDefault();
                    if (areRequiredParametersFilled()) {
                        executeParameterizedAction();
                    }
                }
                else if (e.key === "Escape") {
                    e.preventDefault();
                    goBackToActionList();
                }
            },
            className: cn("w-full rounded-lg border bg-white p-2.5 text-xs text-zinc-700 transition-all", showError
                ? "border-red-300 focus:border-red-400 focus:ring-2 focus:ring-red-100"
                : "border-zinc-200 focus:border-zinc-400 focus:outline-none focus:ring-2 focus:ring-zinc-100"),
            placeholder: param.placeholder || "",
            autoFocus: shouldAutoFocus,
        };
        switch (param.type) {
            case "textarea":
                return (_jsx("textarea", { ...commonProps, rows: param.rows || 3, className: commonProps.className + " resize-none" }));
            case "number":
                return _jsx("input", { ...commonProps, type: "number" });
            case "select":
                return (_jsxs("select", { ...commonProps, children: [_jsx("option", { value: "", children: param.placeholder || "Select an option..." }), param.options?.map((option) => (_jsx("option", { value: option.value, children: option.label }, option.value)))] }));
            case "text":
            default:
                return _jsx("input", { ...commonProps, type: "text" });
        }
    }
    function getAnchorPositionFromEvent(event) {
        try {
            const target = event?.target;
            if (target && typeof target.getBoundingClientRect === "function") {
                const rect = target.getBoundingClientRect();
                return { x: rect.left + rect.width / 2, y: rect.top + rect.height };
            }
            if (typeof event?.clientX === "number" &&
                typeof event?.clientY === "number") {
                return { x: event.clientX, y: event.clientY };
            }
        }
        catch { }
        return { x: window.innerWidth / 2, y: window.innerHeight / 2 };
    }
    function show(event, actionToSelect) {
        // Track which overlay is active
        setCurrentOverlay(overlayId);
        // Compute anchor position from the event (real or synthetic)
        const pos = getAnchorPositionFromEvent(event);
        setAnchorPosition(pos);
        // Suppress outside interaction closing briefly to avoid immediate close
        suppressOutsideInteractionsUntilRef.current = Date.now() + 500;
        // Open on next tick so the original click doesn't count as outside
        setTimeout(() => handleOpenChangeInternal(true), 0);
        // Use the passed actionToSelect or fall back to preSelectedAction prop
        const actionToAutoSelect = actionToSelect || preSelectedAction;
        // Auto-select the action after overlay is shown
        if (actionToAutoSelect &&
            actionToAutoSelect.parameters &&
            actionToAutoSelect.parameters.length > 0) {
            // Small delay to ensure the popover is visible before rendering inputs
            setTimeout(() => {
                handleActionClick(actionToAutoSelect);
            }, 50);
        }
    }
    function hide() {
        handleOpenChangeInternal(false);
    }
    React.useImperativeHandle(ref, () => ({
        show,
        hide,
    }));
    const handlePopoverOpenChange = (open) => {
        if (!open) {
            if (Date.now() < suppressOutsideInteractionsUntilRef.current)
                return;
            if (selectedParameterizedAction)
                return;
        }
        handleOpenChangeInternal(open);
    };
    const [portalContainer, setPortalContainer] = useState(null);
    useEffect(() => {
        try {
            setPortalContainer(document.body);
        }
        catch { }
    }, []);
    return (_jsxs(Popover, { open: isOpen, onOpenChange: handlePopoverOpenChange, enableIframeClickDetection: false, modal: true, children: [_jsx(PopoverAnchor, { asChild: true, children: _jsx("div", { style: {
                        position: "fixed",
                        left: anchorPosition.x,
                        top: anchorPosition.y,
                        width: 1,
                        height: 1,
                        pointerEvents: "none",
                        zIndex: -1,
                    } }) }), _jsx(PopoverContent, { ref: contentRef, className: "min-w-64 rounded-xl border border-zinc-200/50 bg-white/95 p-1.5 shadow-2xl backdrop-blur-md", align: "start", side: "bottom", "data-testid": "field-actions-overlay", container: portalContainer, onOpenAutoFocus: (e) => {
                    e.preventDefault();
                    setTimeout(() => {
                        try {
                            const el = contentRef.current?.querySelector("input, textarea, select, button:not([disabled])");
                            el?.focus();
                        }
                        catch { }
                    }, 0);
                }, onCloseAutoFocus: (e) => e.preventDefault(), onInteractOutside: (e) => {
                    if (Date.now() < suppressOutsideInteractionsUntilRef.current ||
                        selectedParameterizedAction)
                        e.preventDefault();
                }, onPointerDownOutside: (e) => {
                    if (Date.now() < suppressOutsideInteractionsUntilRef.current ||
                        selectedParameterizedAction)
                        e.preventDefault();
                }, onFocusOutside: (e) => {
                    if (Date.now() < suppressOutsideInteractionsUntilRef.current ||
                        selectedParameterizedAction)
                        e.preventDefault();
                }, onEscapeKeyDown: (e) => {
                    e.preventDefault();
                    if (selectedParameterizedAction)
                        goBackToActionList();
                    else
                        handleOpenChangeInternal(false);
                }, onMouseDown: (e) => e.stopPropagation(), onClick: (e) => e.stopPropagation(), children: selectedParameterizedAction ? (_jsxs("div", { className: "p-3", children: [_jsxs("div", { className: "mb-4", children: [_jsxs("div", { className: "mb-3 flex items-center", children: [!hideBackButton && (_jsx(Button, { size: "xs", variant: "ghost", className: "mr-2 h-7 w-7 rounded-full p-0 transition-colors hover:bg-zinc-100", onClick: goBackToActionList, "aria-label": "Back", children: _jsx(ArrowLeft, { size: 14, strokeWidth: 1.5 }) })), _jsx("span", { className: "text-sm font-semibold text-zinc-900", children: selectedParameterizedAction.label })] }), _jsx("div", { className: "mb-4 text-xs leading-relaxed text-zinc-500", children: selectedParameterizedAction.description }), selectedParameterizedAction.parameters?.map((param, index) => {
                                    const value = parameterValues[param.id] || "";
                                    const isEmpty = value.trim().length === 0;
                                    const isRequired = param.required || false;
                                    const isTouched = touchedFields.has(param.id);
                                    const showError = isRequired && isEmpty && isTouched;
                                    return (_jsxs("div", { className: "mb-4 last:mb-0", children: [_jsxs("label", { className: "mb-1.5 block text-[10px] font-semibold tracking-wider text-zinc-400 uppercase", children: [param.label, param.required && (_jsx("span", { className: "ml-1 text-red-500", children: "*" }))] }), renderParameterInput(param, index === 0), showError && (_jsx("p", { className: "mt-1.5 text-[10px] text-red-500", children: "This field is required" }))] }, param.id));
                                }), _jsxs("div", { className: "mt-4 text-[10px] font-medium tracking-tight text-zinc-400", children: [_jsx("span", { className: "rounded bg-zinc-100 px-1 py-0.5 font-mono text-zinc-600", children: "Ctrl+Enter" }), " ", "to execute,", " ", _jsx("span", { className: "rounded bg-zinc-100 px-1 py-0.5 font-mono text-zinc-600", children: "Esc" }), " ", "to cancel"] })] }), _jsxs("div", { className: "flex justify-end gap-2 border-t border-zinc-100 pt-3", children: [_jsx(Button, { size: "sm", variant: "outline", onClick: cancelParameterizedAction, children: "Cancel" }), _jsx(Button, { size: "sm", onClick: executeParameterizedAction, disabled: !areRequiredParametersFilled(), children: "Execute" })] })] })) : (_jsx("div", { className: "flex flex-col gap-0.5", children: generatorButtons?.map((x) => (_jsxs(Button, { size: "xs", variant: "ghost", className: "flex w-full items-center justify-start gap-3 rounded-lg px-3 py-2 text-sm font-medium text-zinc-700 transition-colors hover:bg-zinc-50 hover:text-zinc-900", onClick: (e) => handleActionClick(x, e.nativeEvent), children: [x.icon && (_jsx("span", { className: "flex h-4 w-4 items-center justify-center text-zinc-500", children: typeof x.icon === "string" ? (_jsx("i", { className: x.icon })) : (x.icon) })), x.label] }, x.id))) })) })] }));
});
FieldActionsOverlay.displayName = "FieldActionsOverlay";
export { FieldActionsOverlay };
//# sourceMappingURL=FieldActionsOverlay.js.map