"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Input } from "../../components/ui/input";
import { useEditContext, useEditContextRef, useFieldsEditContextRef, } from "../client/editContext";
import { useFieldModification } from "../client/fieldModificationStore";
import { extractPlainTextContext } from "../utils/selectionContext";
import { useEffect, useRef, useState, useCallback } from "react";
import { RefreshCw } from "lucide-react";
export function SingleLineText({ field, readOnly, updateFieldValue, tabIndex, }) {
    const editContextRef = useEditContextRef();
    const editContext = useEditContext();
    const fieldsContextRef = useFieldsEditContextRef();
    const inputRef = useRef(null);
    // const [selectionStart, setSelectionStart] = useState(0);
    // const [selectionEnd, setSelectionEnd] = useState(0);
    if (!editContextRef.current)
        return;
    const fieldItem = field.descriptor.item;
    const [value, setValue] = useState(undefined);
    // Field-specific subscription - only rerenders when THIS field changes
    const { modifiedField } = useFieldModification(field.id, fieldItem.id, fieldItem.language, fieldItem.version);
    useEffect(() => {
        if (inputRef.current !== document.activeElement) {
            if (field.isHistoric)
                setValue(field.value);
            else {
                setValue(modifiedField?.value ?? field.value);
            }
        }
    }, [field.value, field.isHistoric, modifiedField?.value]);
    if (!fieldItem)
        return;
    const handleChange = (e) => {
        if (editContextRef.current?.operations.undoing) {
            return;
        }
        const newValue = e.target.value;
        if (newValue !== value) {
            setValue(newValue);
            updateFieldValue(newValue);
        }
    };
    // Create a stable callback for replacing selected text or inserting at cursor
    const createReplaceTextCallback = useCallback((currentValue, startOffset, endOffset) => {
        return (newText) => {
            // If startOffset === endOffset, there's no selection - insert at cursor
            const newValue = currentValue.slice(0, startOffset) +
                newText +
                currentValue.slice(endOffset);
            setValue(newValue);
            updateFieldValue(newValue);
        };
    }, [updateFieldValue]);
    const handleSelect = (e) => {
        const target = e.target;
        const startOffset = target.selectionStart || 0;
        const endOffset = target.selectionEnd || 0;
        const selectedText = target.value.slice(startOffset, endOffset);
        // Extract context around the cursor/selection position
        const { contextBefore, contextAfter } = extractPlainTextContext(target.value, startOffset, endOffset);
        // Always set selection range, even if empty (for cursor position tracking)
        const range = {
            itemId: fieldItem.id,
            fieldId: field.id,
            language: fieldItem.language,
            version: fieldItem.version,
            startOffset,
            endOffset,
            text: selectedText, // Empty string if no selection
            element: target, // Include element reference for AI trigger positioning
            contextBefore,
            contextAfter,
            replaceText: createReplaceTextCallback(target.value, startOffset, endOffset),
        };
        // Update if cursor position changed or selection changed
        const currentRange = editContext?.selectedRange;
        if (range.text !== currentRange?.text ||
            range.startOffset !== currentRange?.startOffset ||
            range.endOffset !== currentRange?.endOffset ||
            range.fieldId !== currentRange?.fieldId ||
            range.itemId !== currentRange?.itemId) {
            editContextRef.current?.setSelectedRange(range);
        }
    };
    // 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]);
    useEffect(() => {
        const focusedField = fieldsContextRef.current?.focusedField;
        if (focusedField?.fieldId === field.id &&
            focusedField?.item.id === fieldItem.id &&
            focusedField?.item.language === fieldItem.language &&
            focusedField?.item.version === fieldItem.version) {
            const range = editContextRef.current?.selectedRange;
            if (range && inputRef.current) {
                inputRef.current.setSelectionRange(range.startOffset, range.endOffset);
                // setSelectionStart(range.startOffset);
                // setSelectionEnd(range.endOffset);
            }
        }
    }, [editContext?.selectedRange]);
    // // Calculate the position of the highlight
    // const getHighlightStyle = () => {
    //   if (!inputRef.current || selectionStart === selectionEnd) return {};
    //   const text = value || "";
    //   const beforeSelection = text.slice(0, selectionStart);
    //   const selection = text.slice(selectionStart, selectionEnd);
    //   // Use a temporary span to measure text width
    //   const temp = document.createElement("span");
    //   temp.style.font = window.getComputedStyle(inputRef.current).font;
    //   temp.style.visibility = "hidden";
    //   temp.style.position = "absolute";
    //   document.body.appendChild(temp);
    //   temp.textContent = beforeSelection;
    //   const startPos = temp.getBoundingClientRect().width + 5; // padding
    //   temp.textContent = selection;
    //   const width = temp.getBoundingClientRect().width;
    //   document.body.removeChild(temp);
    //   return {
    //     left: `${startPos}px`,
    //     width: `${width}px`,
    //   };
    // };
    useEffect(() => {
        setTimeout(() => {
            const focusedField = fieldsContextRef.current?.focusedField;
            if (!fieldsContextRef.current?.inlineEditingFieldElement &&
                focusedField?.fieldId === field.id &&
                focusedField?.item.id === fieldItem.id &&
                focusedField?.item.language === fieldItem.language &&
                focusedField?.item.version === fieldItem.version) {
                // Only focus if no other element currently has focus (e.g., popover buttons)
                if (inputRef.current &&
                    (!document.activeElement || document.activeElement === document.body)) {
                    inputRef.current.focus();
                }
            }
        }, 500);
    }, [fieldsContextRef.current?.focusedField]);
    const customSource = field?.customProperties?.source;
    const isManualRefreshEnabled = typeof customSource === "string" && customSource.includes("manual-refresh");
    return (_jsxs("div", { className: "relative", children: [_jsx(Input, { ref: inputRef, value: value ?? "", disabled: readOnly, className: "focus-shadow bg-gray-5 w-full p-1.5 pr-7 text-xs", onChange: handleChange, onSelect: handleSelect, onKeyDown: handleKeyDown, tabIndex: tabIndex }, fieldItem.id + field.id + fieldItem.language + fieldItem.version), isManualRefreshEnabled && (_jsx("button", { type: "button", title: "Re-render", className: "absolute top-1/2 right-1 -translate-y-1/2 rounded p-1 text-gray-600 hover:text-gray-900", onClick: () => editContext?.requestRefresh("immediate"), children: _jsx(RefreshCw, { className: "h-4 w-4", strokeWidth: 1 }) }))] }));
}
//# sourceMappingURL=SingleLineText.js.map