import { useCallback, useEffect, useRef } from "react";
import { useEditContextRef, useFieldsEditContextRef, } from "../client/editContext";
import { getComponentById } from "../componentTreeHelper";
import { getBridgeFieldPatchValue, isBridgePatchableTextField, } from "../page-viewer/bridgeFieldPatch";
import { useSlotContext } from "../views/editorSlotContext";
import { logFieldValueDiagnostic, summarizeField, summarizeFieldDescriptor, summarizeFieldValue, } from "../fieldValueDiagnostics";
import { normalizeMarkerId } from "../utils";
export function useBridgeInlineEditing({ pageViewContextRef, activeBridgeInlineEditRef, blockIframeBlurUntil, sendBeginInlineEdit, sendCancelInlineEdit, sendApplyFieldPatch, }) {
    const editContextRef = useEditContextRef();
    const fieldsContextRef = useFieldsEditContextRef();
    const slotContext = useSlotContext();
    const slotIdRef = useRef(slotContext?.slotId);
    const lastBridgeInlineValueRef = useRef(new Map());
    const deniedInlineCancelKeysRef = useRef(new Set());
    useEffect(() => {
        slotIdRef.current = slotContext?.slotId;
    }, [slotContext?.slotId]);
    const rejectInlineEdit = useCallback((payload, field, currentField) => {
        if (!payload.elementKey)
            return;
        const denyKey = getInlineEditKey(payload.elementKey, field.fieldId);
        logFieldValueDiagnostic("bridge-inline", "rejecting inline edit", {
            elementKey: payload.elementKey,
            denyKey,
            field: summarizeFieldDescriptor(field),
            currentField: summarizeField(currentField),
            resetValue: currentField
                ? summarizeFieldValue(getBridgeFieldPatchValue(currentField))
                : undefined,
        });
        deniedInlineCancelKeysRef.current.add(denyKey);
        activeBridgeInlineEditRef.current = null;
        if (currentField) {
            sendApplyFieldPatch({
                elementKey: payload.elementKey,
                fieldId: field.fieldId,
                isRichText: payload.isRichText,
                source: "reset",
                value: getBridgeFieldPatchValue(currentField),
            });
        }
        sendCancelInlineEdit({
            elementKey: payload.elementKey,
            fieldId: field.fieldId,
            forceReadOnly: true,
        });
    }, [activeBridgeInlineEditRef, sendApplyFieldPatch, sendCancelInlineEdit]);
    const ensureBridgeFieldLock = useCallback(async (field) => {
        const editor = editContextRef.current;
        if (!editor || editor.mode === "suggestions")
            return true;
        if (fieldDescriptorsMatch(editor.lockedField, field))
            return true;
        if (getForeignFieldLockSession(editor, field))
            return false;
        return (await editor.operations.ensureLock(field)) || false;
    }, [editContextRef]);
    const resolveFieldDescriptor = useCallback((fieldId, item, elementKey) => {
        if (!fieldId)
            return undefined;
        const pageView = pageViewContextRef.current;
        const structureField = pageView?.bridgeStructure?.fields.find((field) => (elementKey && field.elementKey === elementKey) ||
            (field.fieldId === fieldId &&
                (!item?.id || field.item?.id === item.id)));
        const fallbackItem = pageView?.page?.item ?? pageView?.pageItemDescriptor;
        const sourceItem = item?.id
            ? item
            : (structureField?.item ?? fallbackItem);
        const id = sourceItem?.id ?? fallbackItem?.id;
        const language = sourceItem?.language ?? fallbackItem?.language;
        const versionValue = sourceItem?.version ?? fallbackItem?.version;
        const version = typeof versionValue === "number" && Number.isFinite(versionValue)
            ? versionValue
            : undefined;
        if (!id || !language || version === undefined)
            return undefined;
        return {
            fieldId,
            item: {
                id,
                language,
                version,
                name: sourceItem?.name ?? fallbackItem?.name,
                displayName: sourceItem?.displayName ?? fallbackItem?.displayName,
                path: sourceItem?.path ?? fallbackItem?.path,
                database: sourceItem?.database ?? fallbackItem?.database,
            },
        };
    }, [pageViewContextRef]);
    const handleFieldValueChanged = useCallback(async (payload) => {
        const editor = editContextRef.current;
        logFieldValueDiagnostic("bridge-inline", "fieldValueChanged received", {
            elementKey: payload.elementKey,
            fieldId: payload.fieldId,
            item: payload.item,
            isRichText: payload.isRichText,
            value: summarizeFieldValue(payload.value),
            editorMode: editor?.mode,
            activeInlineEdit: activeBridgeInlineEditRef.current,
        });
        if (!editor || editor.mode === "preview") {
            logFieldValueDiagnostic("bridge-inline", "fieldValueChanged skipped", {
                reason: !editor ? "missing editor" : "preview mode",
                fieldId: payload.fieldId,
                elementKey: payload.elementKey,
            });
            return;
        }
        const field = resolveFieldDescriptor(payload.fieldId, payload.item, payload.elementKey);
        if (!field) {
            logFieldValueDiagnostic("bridge-inline", "fieldValueChanged skipped", {
                reason: "unresolved field descriptor",
                fieldId: payload.fieldId,
                item: payload.item,
                elementKey: payload.elementKey,
            });
            return;
        }
        const value = (payload.value ?? "").replaceAll("\u200B", "");
        const valueKey = `${field.item.id}:${field.item.language}:${field.item.version}:${field.fieldId}`;
        const previousValue = lastBridgeInlineValueRef.current.get(valueKey);
        if (payload.elementKey) {
            const activeEdit = activeBridgeInlineEditRef.current;
            activeBridgeInlineEditRef.current = {
                elementKey: payload.elementKey,
                fieldId: field.fieldId,
                item: field.item,
                modeAtStart: activeEdit &&
                    activeEdit.elementKey === payload.elementKey &&
                    activeEdit.fieldId === field.fieldId
                    ? activeEdit.modeAtStart
                    : editor.mode,
                value,
            };
            logFieldValueDiagnostic("bridge-inline", "active edit updated", {
                previousActiveEdit: activeEdit,
                nextActiveEdit: activeBridgeInlineEditRef.current,
            });
        }
        if (previousValue === value) {
            logFieldValueDiagnostic("bridge-inline", "deduped unchanged value", {
                valueKey,
                field: summarizeFieldDescriptor(field),
                value: summarizeFieldValue(value),
            });
            return;
        }
        const currentField = await editor.itemsRepository.getField(field);
        if (!currentField ||
            !isBridgePatchableTextField(currentField, payload.isRichText)) {
            logFieldValueDiagnostic("bridge-inline", "fieldValueChanged skipped", {
                reason: !currentField ? "field not found" : "field not patchable",
                field: summarizeFieldDescriptor(field),
                currentField: summarizeField(currentField),
                isRichText: payload.isRichText,
            });
            return;
        }
        const hasLock = await ensureBridgeFieldLock(field);
        if (!hasLock) {
            logBridgeInlineEditDiagnostic("blocked: field locked by another user", {
                fieldId: field.fieldId,
                itemId: field.item.id,
            });
            rejectInlineEdit(payload, field, currentField);
            return;
        }
        lastBridgeInlineValueRef.current.set(valueKey, value);
        const activeEdit = activeBridgeInlineEditRef.current;
        const modeAtStart = activeEdit &&
            activeEdit.elementKey === payload.elementKey &&
            activeEdit.fieldId === field.fieldId
            ? activeEdit.modeAtStart
            : undefined;
        logFieldValueDiagnostic("bridge-inline", "dispatching editField", {
            valueKey,
            field: summarizeFieldDescriptor(field),
            previousValue: summarizeFieldValue(previousValue),
            nextValue: summarizeFieldValue(value),
            currentField: summarizeField(currentField),
            modeAtStart,
            editorMode: editor.mode,
            forceMode: modeAtStart === "suggestions" || editor.mode === "suggestions"
                ? "suggestions"
                : undefined,
            originatingSlotId: slotIdRef.current,
        });
        editor.operations.editField({
            field,
            forceMode: modeAtStart === "suggestions" || editor.mode === "suggestions"
                ? "suggestions"
                : undefined,
            originatingSlotId: slotIdRef.current,
            refresh: "none",
            value,
        });
    }, [
        activeBridgeInlineEditRef,
        editContextRef,
        ensureBridgeFieldLock,
        rejectInlineEdit,
        resolveFieldDescriptor,
    ]);
    const endFieldFocus = useCallback(() => {
        editContextRef.current?.operations.onFieldBlur?.();
        fieldsContextRef.current?.setFocusedField(undefined, false);
    }, [editContextRef, fieldsContextRef]);
    const handleInlineEditEnded = useCallback((payload) => {
        logFieldValueDiagnostic("bridge-inline", "inlineEditEnded received", {
            reason: payload.reason,
            elementKey: payload.elementKey,
            fieldId: payload.fieldId,
            item: payload.item,
            isRichText: payload.isRichText,
            value: summarizeFieldValue(payload.value),
            activeInlineEdit: activeBridgeInlineEditRef.current,
        });
        const denyKey = getInlineEditKey(payload.elementKey, payload.fieldId);
        if (payload.reason === "cancel" &&
            deniedInlineCancelKeysRef.current.delete(denyKey)) {
            logFieldValueDiagnostic("bridge-inline", "inlineEditEnded consumed denied cancel", {
                denyKey,
                fieldId: payload.fieldId,
                elementKey: payload.elementKey,
            });
            endFieldFocus();
            return;
        }
        handleFieldValueChanged(payload);
        endFieldFocus();
    }, [activeBridgeInlineEditRef, endFieldFocus, handleFieldValueChanged]);
    const beginInlineEdit = useCallback(async (interaction) => {
        const editor = editContextRef.current;
        logFieldValueDiagnostic("bridge-inline", "begin interaction received", {
            kind: interaction.kind,
            elementKey: interaction.elementKey,
            fieldId: interaction.fieldId,
            item: interaction.item,
            editorMode: editor?.mode,
            selectedText: summarizeFieldValue(interaction.selectedText),
            selectionStartOffset: interaction.selectionStartOffset,
            selectionEndOffset: interaction.selectionEndOffset,
            modifiers: {
                ctrlKey: interaction.ctrlKey,
                shiftKey: interaction.shiftKey,
                altKey: interaction.altKey,
                metaKey: interaction.metaKey,
            },
        });
        if (!editor || !interaction.fieldId || !interaction.elementKey) {
            logBridgeInlineEditDiagnostic("skipped: missing context", {
                hasEditor: !!editor,
                fieldId: interaction.fieldId,
                elementKey: interaction.elementKey,
                kind: interaction.kind,
            });
            return false;
        }
        if (interaction.ctrlKey || interaction.shiftKey || interaction.metaKey) {
            logBridgeInlineEditDiagnostic("skipped: modifier click", {
                fieldId: interaction.fieldId,
                ctrlKey: interaction.ctrlKey,
                shiftKey: interaction.shiftKey,
                metaKey: interaction.metaKey,
            });
            return false;
        }
        if (editor.mode !== "edit" && editor.mode !== "suggestions") {
            logBridgeInlineEditDiagnostic("skipped: mode", {
                mode: editor.mode,
                fieldId: interaction.fieldId,
            });
            return false;
        }
        const page = pageViewContextRef.current?.page;
        if (editor.mode === "edit" && page && !page.item.canWriteItem) {
            logBridgeInlineEditDiagnostic("skipped: item is not writable", {
                fieldId: interaction.fieldId,
                itemId: page.item.id,
            });
            return false;
        }
        const resolvedField = resolveFieldDescriptor(interaction.fieldId, interaction.item, interaction.elementKey);
        if (!resolvedField) {
            logBridgeInlineEditDiagnostic("skipped: unresolved field", {
                fieldId: interaction.fieldId,
                elementKey: interaction.elementKey,
                itemId: interaction.item?.id,
            });
            return false;
        }
        if (editor.showLayoutComponents === false && page) {
            const owner = getComponentById(resolvedField.item.id, page);
            if (owner?.layoutId) {
                logBridgeInlineEditDiagnostic("skipped: layout component hidden", {
                    fieldId: resolvedField.fieldId,
                    itemId: resolvedField.item.id,
                });
                return false;
            }
        }
        if (editor.mode !== "suggestions" &&
            getForeignFieldLockSession(editor, resolvedField)) {
            logBridgeInlineEditDiagnostic("skipped: field locked by another user", {
                fieldId: resolvedField.fieldId,
                itemId: resolvedField.item.id,
            });
            rejectInlineEdit(interaction, resolvedField);
            return false;
        }
        blockIframeBlurUntil(Date.now() + 500);
        const shouldRequestLock = editor.mode !== "suggestions";
        logBridgeInlineEditDiagnostic("requesting lock", {
            fieldId: resolvedField.fieldId,
            itemId: resolvedField.item.id,
            language: resolvedField.item.language,
            version: resolvedField.item.version,
            shouldRequestLock,
        });
        const hasLock = shouldRequestLock &&
            fieldDescriptorsMatch(editor.lockedField, resolvedField)
            ? ((await fieldsContextRef.current?.setFocusedField(resolvedField, false)) ?? false)
            : ((await fieldsContextRef.current?.setFocusedField(resolvedField, shouldRequestLock)) ?? false);
        if (!hasLock) {
            logBridgeInlineEditDiagnostic("skipped: lock failed", {
                fieldId: resolvedField.fieldId,
                itemId: resolvedField.item.id,
            });
            rejectInlineEdit(interaction, resolvedField);
            return false;
        }
        const beginPayload = {
            elementKey: interaction.elementKey,
            fieldId: resolvedField.fieldId,
            clientX: interaction.clientX,
            clientY: interaction.clientY,
        };
        if (typeof interaction.selectionStartOffset === "number" &&
            typeof interaction.selectionEndOffset === "number") {
            beginPayload.selectedText = interaction.selectedText;
            beginPayload.selectionStartOffset = interaction.selectionStartOffset;
            beginPayload.selectionEndOffset = interaction.selectionEndOffset;
        }
        const sent = sendBeginInlineEdit(beginPayload);
        logBridgeInlineEditDiagnostic(sent ? "started" : "command not sent", {
            fieldId: resolvedField.fieldId,
            itemId: resolvedField.item.id,
            elementKey: interaction.elementKey,
            beginPayload,
        });
        return sent;
    }, [
        blockIframeBlurUntil,
        editContextRef,
        fieldsContextRef,
        pageViewContextRef,
        rejectInlineEdit,
        resolveFieldDescriptor,
        sendBeginInlineEdit,
    ]);
    return {
        beginInlineEdit,
        clearInlineDedupe: () => {
            logFieldValueDiagnostic("bridge-inline", "clearing inline dedupe", {
                entries: lastBridgeInlineValueRef.current.size,
            });
            lastBridgeInlineValueRef.current.clear();
        },
        endFieldFocus,
        handleFieldValueChanged,
        handleInlineEditEnded,
    };
}
function getInlineEditKey(elementKey, fieldId) {
    return `${elementKey ?? ""}:${normalizeMarkerId(fieldId)}`;
}
function fieldDescriptorsMatch(left, right) {
    if (!left || !right)
        return false;
    return (normalizeMarkerId(left.fieldId) === normalizeMarkerId(right.fieldId) &&
        fieldItemsMatch(left.item, right.item));
}
function fieldItemsMatch(left, right) {
    if (!left || !right)
        return false;
    if (normalizeMarkerId(left.id) !== normalizeMarkerId(right.id))
        return false;
    if (left.language &&
        right.language &&
        left.language.toLowerCase() !== right.language.toLowerCase()) {
        return false;
    }
    if (left.version !== undefined &&
        right.version !== undefined &&
        left.version !== right.version) {
        return false;
    }
    return true;
}
function getForeignFieldLockSession(editor, field) {
    return editor.activeSessions.find((session) => session.sessionId !== editor.sessionId &&
        fieldDescriptorsMatch(session.fieldLock, field));
}
function logBridgeInlineEditDiagnostic(message, details) {
    logFieldValueDiagnostic("bridge-inline", message, details);
}
//# sourceMappingURL=useBridgeInlineEditing.js.map