import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEditContext } from "./client/editContext";
import { useFieldModification } from "./client/fieldModificationStore";
import { openCommentsFeedback } from "./reviews/openCommentsFeedback";
import { showCommentPopoverForTrigger } from "./reviews/CommentPopover";
import { shouldRemoveNoOpSuggestion } from "./reviews/suggestionContentChange";
import { getSuggestedEditItemLanguage, getSuggestedEditItemVersion, } from "./reviews/suggestionDisplayValue";
import { useSlotContext } from "./views/editorSlotContext";
import { useEffect, useRef, useState } from "react";
import { getSessionWithFieldLock } from "./utils";
import { loadFieldButtons, forceUnlockField } from "./services/editService";
import { FieldActionsOverlay, } from "./FieldActionsOverlay";
import { SimpleIconButton } from "./ui/SimpleIconButton";
import { FieldHistory } from "./FieldHistory";
import { History, MessageCircle, MessageCirclePlus, WandSparkles, ExternalLink, Loader2, LockOpen, } from "lucide-react";
import { Checkbox } from "../components/ui/checkbox";
import { CopyButton } from "../components/ui/copy-button";
import { PasteButton } from "../components/ui/paste-button";
import { CountBadge } from "../components/ui/badge";
import { containsGuidInText, findGuidsInText } from "./utils";
import { logFieldValueDiagnostic, summarizeField, summarizeFieldDescriptor, summarizeFieldValue, } from "./fieldValueDiagnostics";
import { Popover, PopoverContent, PopoverTrigger, } from "../components/ui/popover";
import { Tooltip, TooltipContent, TooltipTrigger, } from "../components/ui/tooltip";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "../components/ui/dialog";
import { Button } from "../components/ui/button";
import { getFieldTypeConfiguration } from "./fieldTypeConfiguration";
const BRIDGE_INLINE_EDIT_RELEASE_EVENT = "parhelia:bridge-inline-edit-release";
const fieldActionButtonBaseClassName = "-mx-1 inline-flex items-center rounded-[4px] px-1 py-0.5 text-xs text-neutral-grey-100 transition-colors";
const fieldActionButtonWithIconClassName = `${fieldActionButtonBaseClassName} gap-1`;
const fieldActionButtonInteractiveClassName = "cursor-pointer hover:bg-neutral-grey-5 hover:text-neutral-grey-100";
const fieldActionButtonDisabledClassName = "cursor-not-allowed opacity-50";
export default function FieldListField({ field, validators, simplified, title, isFocusedField, showFallbackButton, compareToField, readonly, isHoveringField, tabIndex, }) {
    const editContext = useEditContext();
    const slotContext = useSlotContext();
    if (!editContext)
        return;
    const fieldItem = field.descriptor.item;
    // Field-specific subscription - only rerenders when THIS field changes
    const { isModified, isSaved } = useFieldModification(field.id, fieldItem.id, fieldItem.language, fieldItem.version, slotContext?.fieldModificationStore);
    const [showRawValue, setShowRawValue] = useState(false);
    const [showFieldJson, setShowFieldJson] = useState(false);
    const [fieldMenuOpen, setFieldMenuOpen] = useState(false);
    const [fieldHistoryOpen, setFieldHistoryOpen] = useState(false);
    const generatorsOverlay = useRef(null);
    const [generatorButtons, setButtons] = useState();
    const [forceUnlockDialogOpen, setForceUnlockDialogOpen] = useState(false);
    const [forceUnlockCooldown, setForceUnlockCooldown] = useState(0);
    const forceUnlockCooldowns = useRef(new Map());
    const COOLDOWN_MS = 60000; // 60 seconds
    async function handleActionClick(action, event) {
        editContext?.triggerFieldAction(field.descriptor, action, undefined, event);
    }
    async function handleParameterizedActionExecute(action, parameters) {
        editContext?.triggerFieldAction(field.descriptor, action, parameters);
    }
    useEffect(() => {
        setShowRawValue(false);
    }, [
        field.descriptor.item.id,
        field.descriptor.item.language,
        field.descriptor.item.version,
        field.descriptor.fieldId,
    ]);
    const fieldLockedBySession = getSessionWithFieldLock(field.descriptor, editContext);
    const setFieldValue = (value, capturedDescriptor) => {
        logFieldValueDiagnostic("field-form", "setFieldValue", {
            field: summarizeField(field),
            capturedDescriptor: summarizeFieldDescriptor(capturedDescriptor),
            nextValue: summarizeFieldValue(value),
            isFocusedField,
            slotId: slotContext?.slotId,
        });
        // Use the captured descriptor from edit time, not the current field.descriptor.
        // Persistence remains debounced inside operations.editField; this call updates
        // local modified-field state immediately so the preview can patch without lag.
        window.dispatchEvent(new CustomEvent(BRIDGE_INLINE_EDIT_RELEASE_EVENT, {
            detail: { field: capturedDescriptor },
        }));
        void editContext.operations.editField({
            field: capturedDescriptor,
            value,
            refresh: "none",
            originatingSlotId: slotContext?.slotId,
        });
    };
    const executingAction = editContext.activeFieldActions.find((x) => x.field.fieldId == field.id &&
        x.field.item?.id == fieldItem.id &&
        x.field.item?.language == fieldItem.language &&
        x.field.item?.version == fieldItem.version);
    const isReadOnly = executingAction?.state == "running" ||
        readonly ||
        !field.canWrite ||
        (fieldLockedBySession &&
            fieldLockedBySession.sessionId !== editContext.sessionId) ||
        false;
    let classNames = "flex items-stretch";
    if (executingAction?.state == "running")
        classNames += " executing-action ";
    else {
        if (isFocusedField)
            classNames += " focused-field ";
        if (isReadOnly)
            classNames += " readonly ";
        if (isModified && !isSaved)
            classNames += " saving ";
        if (isSaved)
            classNames += " saved ";
    }
    let validationBarClassNames = undefined;
    if (validators.find((x) => x.result > 1))
        validationBarClassNames = " pl-2 border-l-4 border-feedback-red";
    useEffect(() => {
        const load = async () => {
            if (!field.descriptor)
                return;
            const buttons = await loadFieldButtons(field.descriptor);
            field.buttons = buttons;
            setButtons(buttons);
        };
        if (isFocusedField || isHoveringField) {
            if (field.buttons)
                setButtons(field.buttons);
            else
                load();
        }
    }, [isFocusedField, isHoveringField]);
    const renderGeneratorButtons = generatorButtons?.length || 0 > 0 ? (_jsxs(_Fragment, { children: [(!executingAction || executingAction.state !== "running") && (_jsx(SimpleIconButton, { icon: _jsx(WandSparkles, { strokeWidth: 1, className: "h-3.5 w-3.5" }), label: "Generate", onClick: (e) => {
                    generatorsOverlay.current?.show(e);
                } })), executingAction && executingAction.state === "running" && (_jsxs("div", { className: "ml-auto flex items-center gap-1.5 text-xs", children: [_jsx(Loader2, { strokeWidth: 1, className: "h-3.5 w-3.5 animate-spin" }), " ", executingAction?.label] })), _jsx(FieldActionsOverlay, { ref: generatorsOverlay, generatorButtons: generatorButtons, onActionClick: handleActionClick, onParameterizedActionExecute: handleParameterizedActionExecute, currentOverlay: editContext.currentOverlay, fieldId: field.id, setCurrentOverlay: editContext.setCurrentOverlay })] })) : null;
    const config = getFieldTypeConfiguration(editContext.configuration, field.type);
    const handleOpenFieldItem = (e) => {
        // Load the field item in the editor
        const openInNewSlot = !!e?.altKey;
        editContext.loadItem({
            id: field.id,
            language: "en",
            version: 0,
        }, openInNewSlot ? { openInNewSlot: true } : undefined);
        setFieldMenuOpen(false);
    };
    const handleShowFieldJson = () => {
        setShowFieldJson(!showFieldJson);
        setFieldMenuOpen(false);
    };
    // Force unlock cooldown logic
    const fieldKey = `${fieldItem.id}_${field.id}`;
    const lastUnlock = forceUnlockCooldowns.current.get(fieldKey) || 0;
    const remainingCooldown = Math.max(0, COOLDOWN_MS - (Date.now() - lastUnlock));
    const isOnCooldown = remainingCooldown > 0;
    // Update cooldown display
    useEffect(() => {
        if (!isOnCooldown)
            return;
        const interval = setInterval(() => {
            const remaining = Math.max(0, COOLDOWN_MS -
                (Date.now() - (forceUnlockCooldowns.current.get(fieldKey) || 0)));
            setForceUnlockCooldown(Math.ceil(remaining / 1000));
            if (remaining <= 0) {
                clearInterval(interval);
            }
        }, 1000);
        return () => clearInterval(interval);
    }, [fieldKey, lastUnlock]);
    const handleForceUnlock = async () => {
        if (!fieldLockedBySession || isOnCooldown)
            return;
        const result = await forceUnlockField(fieldLockedBySession.sessionId, fieldItem, field.id);
        if (result.type === "success") {
            forceUnlockCooldowns.current.set(fieldKey, Date.now());
            setForceUnlockCooldown(Math.ceil(COOLDOWN_MS / 1000));
        }
        setForceUnlockDialogOpen(false);
    };
    // Filter comments and suggestedEdits for this field
    // Comments can be associated with either itemId (component) or mainItemId (page)
    const fieldComments = editContext.comments.filter((comment) => !comment.suggestedEditId &&
        comment.fieldId === field.id &&
        (comment.itemId === fieldItem.id ||
            comment.mainItemId === fieldItem.id) &&
        comment.language === fieldItem.language &&
        comment.version === fieldItem.version);
    const fieldSuggestedEdits = editContext.suggestedEdits.filter((suggestedEdit) => suggestedEdit.fieldId === field.id &&
        (suggestedEdit.itemId === fieldItem.id ||
            suggestedEdit.mainItemId === fieldItem.id) &&
        getSuggestedEditItemLanguage(suggestedEdit) === fieldItem.language &&
        (getSuggestedEditItemVersion(suggestedEdit) === 0 ||
            getSuggestedEditItemVersion(suggestedEdit) === fieldItem.version) &&
        // No-op suggestions without comments are hidden from the feedback
        // sidebar; don't count them here either.
        !shouldRemoveNoOpSuggestion(suggestedEdit.oldValue, suggestedEdit.newValue, () => editContext.comments.filter((c) => c.suggestedEditId === suggestedEdit.id).length));
    const hasUnresolvedComments = fieldComments.some((comment) => !comment.isResolved) ||
        fieldSuggestedEdits.some((edit) => edit.status === "pending");
    const hasResolvedComments = fieldComments.some((comment) => comment.isResolved) ||
        fieldSuggestedEdits.some((edit) => edit.status === "applied" || edit.status === "rejected");
    const hasAnyCommentsOrSuggestions = fieldComments.length > 0 || fieldSuggestedEdits.length > 0;
    const totalCount = fieldComments.length + fieldSuggestedEdits.length;
    const unresolvedCount = fieldComments.filter((c) => !c.isResolved).length +
        fieldSuggestedEdits.filter((e) => e.status === "pending").length;
    return (_jsxs("div", { className: classNames, children: [validationBarClassNames && (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("div", { className: validationBarClassNames, id: "validation_" + field.id }) }), _jsx(TooltipContent, { children: validators
                            .filter((x) => x.result > 1)
                            .map((x) => (_jsx("div", { children: x.message }, x.validator))) })] })), _jsxs("div", { className: "flex-1", children: [_jsxs("div", { className: "flex min-h-7 flex-wrap items-center gap-x-3 gap-y-1", children: [!simplified ? (_jsxs(Popover, { open: fieldMenuOpen, onOpenChange: setFieldMenuOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx("button", { className: "text-neutral-grey-100 hover:bg-neutral-grey-5 rounded py-0.5 text-left text-xs font-medium transition-colors", children: title || field.displayName || field.name }) }), _jsxs(PopoverContent, { className: "w-56 p-1", align: "start", side: "bottom", children: [_jsxs("button", { className: "hover:bg-neutral-grey-5 flex w-full items-center gap-2 rounded px-3 py-2 text-xs transition-colors", onClick: (e) => handleOpenFieldItem(e), children: [_jsx(ExternalLink, { strokeWidth: 1, className: "h-4 w-4" }), "Open Field Item"] }), _jsxs("button", { className: "hover:bg-neutral-grey-5 flex w-full items-center gap-2 rounded px-3 py-2 text-xs transition-colors", onClick: handleShowFieldJson, children: [_jsx("span", { className: "font-mono text-sm", children: "{}" }), showFieldJson ? "Hide" : "Show", " Field JSON"] })] })] })) : (_jsx("label", { className: "block text-xs font-medium select-text", children: title || field.displayName || field.name })), fieldLockedBySession &&
                                fieldLockedBySession.sessionId !== editContext.sessionId && (_jsxs("div", { className: "flex items-center gap-1", children: [_jsxs("div", { className: "badge-pad-sm rounded-sm text-xs text-white", style: { backgroundColor: fieldLockedBySession.color }, children: ["locked by", " ", fieldLockedBySession.user.fullName ||
                                                fieldLockedBySession.user.name] }), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("button", { className: `hover:bg-neutral-grey-5 cursor-pointer rounded p-1 transition-colors ${isOnCooldown ? "cursor-not-allowed opacity-50" : ""}`, onClick: () => !isOnCooldown && setForceUnlockDialogOpen(true), disabled: isOnCooldown, "aria-label": "Force Unlock", children: _jsx(LockOpen, { strokeWidth: 1, className: "h-3.5 w-3.5" }) }) }), _jsx(TooltipContent, { children: isOnCooldown
                                                    ? `Force unlock available in ${forceUnlockCooldown}s`
                                                    : "Force Unlock" })] }), _jsx(Dialog, { open: forceUnlockDialogOpen, onOpenChange: setForceUnlockDialogOpen, children: _jsxs(DialogContent, { className: "max-w-md", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: "Force Unlock Field?" }), _jsxs(DialogDescription, { children: ["This field is currently being edited by", " ", _jsx("strong", { children: fieldLockedBySession.user.fullName ||
                                                                        fieldLockedBySession.user.name }), ". Force unlocking may disrupt their work and cause unsaved changes to be lost."] })] }), _jsxs(DialogFooter, { className: "gap-2 px-6 pt-4 pb-6", children: [_jsx(Button, { variant: "outline", onClick: () => setForceUnlockDialogOpen(false), children: "Cancel" }), _jsx(Button, { variant: "destructive", onClick: handleForceUnlock, children: "Force Unlock" })] })] }) })] })), hasAnyCommentsOrSuggestions &&
                                !isFocusedField &&
                                !isHoveringField && (_jsx("div", { className: "ml-auto flex items-center gap-1", children: _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsxs("div", { className: "hover:bg-neutral-grey-5 relative cursor-pointer rounded p-1 opacity-60 transition-colors", onClick: () => {
                                                    openCommentsFeedback(editContext);
                                                    const firstComment = fieldComments.find((c) => !c.isResolved) ||
                                                        fieldComments[0];
                                                    if (firstComment) {
                                                        editContext.setSelectedComment(firstComment);
                                                        editContext.setSelectedSuggestedEdit(undefined);
                                                        editContext.setFocusedField(field.descriptor, false);
                                                    }
                                                }, children: [_jsx(MessageCircle, { strokeWidth: 1, className: "text-neutral-grey-100 hover:text-neutral-grey-100 h-3.5 w-3.5" }), _jsx(CountBadge, { className: "absolute -top-1 -right-1 min-w-3", children: totalCount })] }) }), _jsx(TooltipContent, { children: _jsxs("div", { className: "text-xs", children: [unresolvedCount > 0 && (_jsxs("div", { children: [unresolvedCount, " unresolved", " ", unresolvedCount === 1
                                                                ? "comment/suggestion"
                                                                : "comments/suggestions"] })), totalCount > unresolvedCount && (_jsxs("div", { children: [totalCount - unresolvedCount, " resolved"] })), totalCount === unresolvedCount && totalCount > 0 && (_jsxs("div", { children: ["Total: ", totalCount] })), (fieldComments.length > 0 ||
                                                        fieldSuggestedEdits.length > 0) && (_jsxs("div", { className: "text-neutral-grey-50 mt-1", children: [fieldComments.length > 0 && (_jsxs("div", { children: [fieldComments.length, " ", fieldComments.length === 1
                                                                        ? "comment"
                                                                        : "comments"] })), fieldSuggestedEdits.length > 0 && (_jsxs("div", { children: [fieldSuggestedEdits.length, " ", fieldSuggestedEdits.length === 1
                                                                        ? "suggestion"
                                                                        : "suggestions"] }))] }))] }) })] }) })), (isFocusedField || isHoveringField) &&
                                (!fieldLockedBySession ||
                                    fieldLockedBySession?.sessionId === editContext.sessionId) && (_jsxs(_Fragment, { children: [field.isShared && (_jsx("span", { className: "text-neutral-grey-50 text-xs", children: "[Shared]" })), ((!field.isFallback &&
                                        !field.isStandardValue &&
                                        (field.hasValue ||
                                            (field.rawValue != null &&
                                                String(field.rawValue).trim() !== ""))) ||
                                        showFallbackButton ||
                                        (config?.buttons && config.buttons.length > 0) ||
                                        !simplified) && _jsx("span", { className: "text-xs", children: "\u00B7" }), !field.isFallback &&
                                        !field.isStandardValue &&
                                        (field.hasValue ||
                                            (field.rawValue != null &&
                                                String(field.rawValue).trim() !== "")) ? (!isReadOnly ? (_jsx("button", { className: `${fieldActionButtonBaseClassName} ${fieldActionButtonInteractiveClassName}`, "data-testid": "field-reset-button", onClick: () => {
                                            editContext?.operations.editField({
                                                field: field.descriptor,
                                                rawValue: null,
                                                originatingSlotId: slotContext?.slotId,
                                            });
                                        }, children: "Reset" })) : null) : (showFallbackButton), config?.buttons?.map((x) => {
                                        const clientBtn = x;
                                        const isActionDisabled = typeof clientBtn.isDisabled === "function"
                                            ? clientBtn.isDisabled({ field })
                                            : false;
                                        return (_jsxs("button", { type: "button", disabled: isActionDisabled, className: `${fieldActionButtonWithIconClassName} ${isActionDisabled
                                                ? fieldActionButtonDisabledClassName
                                                : fieldActionButtonInteractiveClassName}`, onClick: (e) => {
                                                if (isActionDisabled)
                                                    return;
                                                editContext.triggerFieldAction(field.descriptor, x, undefined, e);
                                            }, children: [typeof x.icon === "string" ? (_jsx("i", { className: "pi text-xs " + x.icon })) : (_jsx("span", { className: "inline-flex items-center align-middle [&_svg]:h-3.5 [&_svg]:w-3.5", children: x.icon })), x.label] }, x.id));
                                    }), !simplified && (_jsxs("div", { className: `${fieldActionButtonBaseClassName} ${fieldActionButtonInteractiveClassName} gap-1.5`, children: [_jsx(Checkbox, { className: "size-3.5", checked: showRawValue, onCheckedChange: (checked) => setShowRawValue(!!checked), "data-testid": "field-raw-checkbox" }), _jsx("label", { className: "cursor-pointer", onClick: () => setShowRawValue(!showRawValue), children: "Raw" })] })), field.rawValue && (_jsx(CopyButton, { textToCopy: field.rawValue || "", "data-testid": "field-copy-button", className: `${fieldActionButtonWithIconClassName} ${fieldActionButtonInteractiveClassName}` })), !isReadOnly &&
                                        (() => {
                                            const typeConfig = getFieldTypeConfiguration(editContext.configuration, field.type);
                                            const pasteCfg = typeConfig?.paste;
                                            const enabled = pasteCfg?.enabled
                                                ? pasteCfg.enabled(field)
                                                : false;
                                            if (!enabled)
                                                return null;
                                            const hideIfInvalid = pasteCfg?.hideIfInvalidClipboard ?? true;
                                            const pasteKind = pasteCfg?.kind?.type;
                                            const validateClipboard = pasteCfg?.isValid ??
                                                (pasteKind === "guid"
                                                    ? (t) => containsGuidInText(t)
                                                    : pasteKind === "guid-list"
                                                        ? (t) => findGuidsInText(t).length > 0
                                                        : (t) => (t || "").trim().length > 0);
                                            const computeValueFromClipboard = (clipboardText) => {
                                                if (pasteKind === "guid") {
                                                    const guids = findGuidsInText(clipboardText);
                                                    return guids[0];
                                                }
                                                if (pasteKind === "guid-list") {
                                                    const guids = findGuidsInText(clipboardText);
                                                    if (!guids.length)
                                                        return undefined;
                                                    const separator = pasteCfg?.kind?.separator ?? "|";
                                                    return guids.join(separator);
                                                }
                                                if (pasteCfg?.transform) {
                                                    const transformed = pasteCfg.transform(clipboardText, field);
                                                    return typeof transformed === "string"
                                                        ? transformed
                                                        : undefined;
                                                }
                                                return clipboardText;
                                            };
                                            return (_jsx(PasteButton, { hideIfClipboardEmpty: hideIfInvalid, isClipboardValid: validateClipboard, "data-testid": "field-paste-button", className: `${fieldActionButtonWithIconClassName} ${fieldActionButtonInteractiveClassName}`, onPaste: async (clipboardText) => {
                                                    const valueToWrite = computeValueFromClipboard(clipboardText);
                                                    if (valueToWrite === undefined)
                                                        return;
                                                    const target = pasteCfg?.target ?? "value";
                                                    await editContext?.operations.editField({
                                                        field: field.descriptor,
                                                        [target]: valueToWrite,
                                                        originatingSlotId: slotContext?.slotId,
                                                    });
                                                } }));
                                        })(), _jsxs("div", { className: "ml-auto flex items-center gap-1", children: [hasAnyCommentsOrSuggestions && (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsxs("div", { className: "hover:bg-neutral-grey-5 relative cursor-pointer rounded p-1 transition-colors", onClick: () => {
                                                                openCommentsFeedback(editContext);
                                                                const firstComment = fieldComments.find((c) => !c.isResolved) ||
                                                                    fieldComments[0];
                                                                if (firstComment) {
                                                                    editContext.setSelectedComment(firstComment);
                                                                    editContext.setSelectedSuggestedEdit(undefined);
                                                                    editContext.setFocusedField(field.descriptor, false);
                                                                }
                                                            }, children: [_jsx(MessageCircle, { strokeWidth: 1, className: "text-neutral-grey-100 hover:text-neutral-grey-100 h-3.5 w-3.5" }), _jsx(CountBadge, { className: "absolute -top-1 -right-1 min-w-3", children: totalCount })] }) }), _jsx(TooltipContent, { children: _jsxs("div", { className: "text-xs", children: [unresolvedCount > 0 && (_jsxs("div", { children: [unresolvedCount, " unresolved", " ", unresolvedCount === 1
                                                                            ? "comment/suggestion"
                                                                            : "comments/suggestions"] })), totalCount > unresolvedCount && (_jsxs("div", { children: [totalCount - unresolvedCount, " resolved"] })), totalCount === unresolvedCount && totalCount > 0 && (_jsxs("div", { children: ["Total: ", totalCount] })), (fieldComments.length > 0 ||
                                                                    fieldSuggestedEdits.length > 0) && (_jsxs("div", { className: "text-neutral-grey-50 mt-1", children: [fieldComments.length > 0 && (_jsxs("div", { children: [fieldComments.length, " ", fieldComments.length === 1
                                                                                    ? "comment"
                                                                                    : "comments"] })), fieldSuggestedEdits.length > 0 && (_jsxs("div", { children: [fieldSuggestedEdits.length, " ", fieldSuggestedEdits.length === 1
                                                                                    ? "suggestion"
                                                                                    : "suggestions"] }))] }))] }) })] })), !editContext.configuration.forceFullscreen && (_jsx(SimpleIconButton, { icon: _jsx(MessageCirclePlus, { strokeWidth: 1, className: "h-3.5 w-3.5" }), onMouseDown: (event) => {
                                                    event.preventDefault();
                                                }, onClick: (event) => {
                                                    showCommentPopoverForTrigger(event.currentTarget, editContext, {
                                                        field: field.descriptor,
                                                        range: editContext.selectedRange,
                                                    });
                                                }, label: "Add Comment" })), !readonly && renderGeneratorButtons, _jsxs(Tooltip, { children: [_jsxs(Popover, { open: fieldHistoryOpen, onOpenChange: setFieldHistoryOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx(TooltipTrigger, { asChild: true, children: _jsx("button", { className: "text-neutral-grey-100 hover:border-neutral-grey-10 hover:bg-neutral-grey-5 cursor-pointer rounded-[4px] border border-transparent p-1 transition-colors", "aria-label": "Field History", "data-testid": "field-history-button", children: _jsx(History, { strokeWidth: 1, className: "h-3.5 w-3.5" }) }) }) }), _jsx(PopoverContent, { className: "w-[700px] p-2", align: "end", side: "top", children: _jsx(FieldHistory, { field: field, configuration: editContext.configuration, showRawValue: showRawValue, onRevert: () => {
                                                                        setFieldHistoryOpen(false);
                                                                    }, onClose: () => {
                                                                        setFieldHistoryOpen(false);
                                                                    } }) })] }), _jsx(TooltipContent, { children: "Field History" })] })] })] }))] }), field.shortDescription && (_jsx("div", { className: "text-neutral-grey-50 -mt-1 mb-2 text-[10px] font-normal", children: field.shortDescription })), executingAction?.message && (_jsx("div", { className: "mt-1 mb-1 p-0 text-xs", children: executingAction?.message })), showFieldJson && (_jsxs("div", { className: "bg-neutral-grey-5 mt-2 mb-2 rounded border p-2 text-xs", children: [_jsxs("div", { className: "mb-2 flex items-center justify-between", children: [_jsx("span", { className: "font-medium", children: "Field JSON" }), _jsx(CopyButton, { textToCopy: JSON.stringify(field, null, 2) })] }), _jsx("pre", { className: "max-h-40 overflow-auto text-xs whitespace-pre-wrap select-text", children: JSON.stringify(field, null, 2) })] })), !compareToField && (_jsx("div", { className: "mt-1 p-0 text-xs", children: getFieldEditor(field, showRawValue, isReadOnly, editContext.configuration, setFieldValue, isFocusedField, tabIndex) })), compareToField && (_jsxs("div", { className: "mt-1 flex w-full gap-1 p-0 text-xs", children: [_jsx("div", { className: "flex-1", children: getFieldEditor(field, showRawValue, isReadOnly, editContext.configuration, setFieldValue, isFocusedField, tabIndex) }), _jsx("div", { className: "flex-1", children: getFieldEditor(compareToField, showRawValue, true, editContext.configuration, setFieldValue, isFocusedField, undefined) })] }))] })] }, field.id +
        "_" +
        fieldItem.id +
        "_" +
        fieldItem.language +
        "_" +
        fieldItem.version));
}
export function getFieldEditor(field, showRawValue, isReadOnly, configuration, setFieldValue, isFocusedField, tabIndex) {
    let fieldType = showRawValue ? "raw" : field.type;
    var typeConfig = getFieldTypeConfiguration(configuration, fieldType);
    if (!typeConfig)
        typeConfig = configuration.fieldTypes["single-line text"];
    if (!typeConfig)
        return null;
    return (_jsx(typeConfig.editor, { field: field, readOnly: isReadOnly, isFocusedField: isFocusedField, updateFieldValue: (value) => {
            // Capture the field descriptor at the time of the edit
            setFieldValue(value, field.descriptor);
        }, tabIndex: tabIndex }));
}
//# sourceMappingURL=FieldListField.js.map