"use client";
import { jsx as _jsx } from "react/jsx-runtime";
import { Textarea } from "../../components/ui/textarea";
import { useEditContext } from "../client/editContext";
import { useEffect, useRef, useState, useCallback } from "react";
import { useDebouncedCallback } from "use-debounce";
export function RawEditor({ field, readOnly, tabIndex, }) {
    const editContext = useEditContext();
    const inputRef = useRef(null);
    if (!editContext)
        return;
    const [value, setValue] = useState(field.rawValue);
    useEffect(() => {
        if (inputRef.current !== document.activeElement)
            setValue(field.rawValue);
    }, [field.rawValue]);
    const debouncedSetFieldvalue = useDebouncedCallback((value, capturedDescriptor) => {
        // Use the captured descriptor from edit time to prevent saving to wrong language
        editContext.operations.editField({
            field: capturedDescriptor,
            rawValue: value,
            refresh: "waitForQuietPeriod",
        });
    }, 200);
    const fieldItem = field.descriptor.item;
    // Handle keyboard shortcut (Ctrl/Cmd + .) to trigger AI text edit
    const handleKeyDown = useCallback((e) => {
        // Check for Ctrl+. or Cmd+.
        if ((e.ctrlKey || e.metaKey) && e.key === ".") {
            // Allow triggering even without selection - just need to be in this field
            if (editContext?.focusedField?.fieldId === field.id) {
                e.preventDefault();
                e.stopPropagation();
                // Dispatch custom event to trigger AI dialog
                document.dispatchEvent(new CustomEvent("inline-ai-open"));
            }
        }
    }, [editContext, field.id]);
    return (_jsx(Textarea, { ref: inputRef, value: value ?? "", disabled: readOnly, className: "focus-shadow bg-neutral-grey-5 w-full p-2 text-xs", rows: 12, onChange: (e) => {
            setValue(e.target.value);
            // Capture the field descriptor at edit time to prevent saving to wrong language
            debouncedSetFieldvalue(e.target.value, field.descriptor);
            // field.value = e.target.value;
        }, onKeyDown: handleKeyDown, tabIndex: tabIndex }, fieldItem.id + field.id + fieldItem.language + fieldItem.version));
}
//# sourceMappingURL=RawEditor.js.map