import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { ArrowUp } from "lucide-react";
import FieldListField from "./FieldListField";
import { useEditContext, useOperationsContext, useFieldsEditContext, } from "./client/editContext";
import { Checkbox } from "../components/ui/checkbox";
import { MANUAL_FIELD_ACTION_VISIBILITY_EVENT, } from "./manualActionEvents";
export function FieldListFieldWithFallbacks({ fieldDescriptor, validators, simplified, title, compareToField, readonly, tabIndex, }) {
    const [showFallback, setShowFallback] = useState(false);
    const [fallbackChain, setFallbackChain] = useState();
    const ref = useRef(null);
    const [hover, setHover] = useState(false);
    const [manualActionRunIds, setManualActionRunIds] = useState([]);
    const [field, setField] = useState();
    const editContext = useEditContext();
    const fieldsContext = useFieldsEditContext();
    if (!editContext)
        return;
    const operationsContext = useOperationsContext();
    useEffect(() => {
        const loadField = async () => {
            const field = await editContext.itemsRepository.getField(fieldDescriptor);
            setField(field);
        };
        loadField();
    }, [editContext.itemsRepository.revision, fieldDescriptor]);
    //const liveField = editContext.getLiveField(field);
    // function isEditFieldOp(op?: EditOperation): op is EditFieldOperation {
    //   return op?.type === "edit-field";
    // }
    async function loadFallback() {
        if (!field?.fallbackChain || !editContext)
            return;
        await editContext.itemsRepository.getItems(field.fallbackChain?.map((x) => x.item));
        setFallbackChain((await Promise.all(field.fallbackChain.map((x) => editContext.itemsRepository.getField(x)))).filter((x) => x));
        //const chain = await loadFallbackChain(field.descriptor);
        // if(currentEditOp.item.language !== field._editor!.descriptor.item.language) {
        //   chain.forEach((x, i) => {
        //     if (i > 0) {
        //       x._editor!.isFallback = true;
        //     }
        //   });
        // }
        // // chain.forEach((x, i) => {
        // //   if (
        // //     init ||
        // //     !isEditFieldOp(currentEditOp) ||
        // //     currentEditOp.fieldId !== x.id ||
        // //     currentEditOp.item.id !== x._editor!.descriptor.item.id ||
        // //     currentEditOp.item.language !== x._editor!.descriptor.item.language
        // //   ) {
        // //     console.log("apply change", i, x);
        // //     x._editor! = chain[i]._editor!;
        // //     x.value = chain[i].value;
        // //     x.jsonValue = chain[i].jsonValue;
        // //   }
        // // });
        //setFallbackChain(chain);
    }
    const fieldItem = field?.descriptor.item;
    const isFocusedField = fieldsContext?.focusedField?.fieldId === field?.id &&
        fieldsContext?.focusedField?.item?.id === fieldItem?.id &&
        fieldsContext?.focusedField?.item?.language === fieldItem?.language;
    useEffect(() => {
        const handleEnter = () => {
            setHover(true);
        };
        const handleLeave = () => {
            setHover(false);
        };
        const element = ref.current;
        if (element && field) {
            element.addEventListener("mouseenter", handleEnter);
            element.addEventListener("mouseleave", handleLeave);
        }
        return () => {
            if (element) {
                element.removeEventListener("mouseenter", handleEnter);
                element.removeEventListener("mouseleave", handleLeave);
            }
        };
    }, [field]);
    useEffect(() => {
        const handler = (event) => {
            const detail = event.detail;
            if (!field?.id || !detail.fieldIds.includes(field.id)) {
                return;
            }
            setManualActionRunIds((prev) => {
                if (detail.mode === "show") {
                    return prev.includes(detail.runId) ? prev : [...prev, detail.runId];
                }
                return prev.filter((runId) => runId !== detail.runId);
            });
        };
        window.addEventListener(MANUAL_FIELD_ACTION_VISIBILITY_EVENT, handler);
        return () => {
            window.removeEventListener(MANUAL_FIELD_ACTION_VISIBILITY_EVENT, handler);
        };
    }, [field?.id]);
    useEffect(() => {
        if (ref.current && isFocusedField) {
            // only scroll if the field is completely outside the viewport
            const rect = ref.current.getBoundingClientRect();
            if (rect.bottom < 0 || rect.top > window.innerHeight) {
                ref.current.scrollIntoView({
                    behavior: "smooth",
                    block: "center",
                    inline: "center",
                });
            }
        }
    }, [fieldsContext?.focusedField?.fieldId]);
    useEffect(() => {
        if (ref.current && (isFocusedField || hover) && field?.isFallback) {
            loadFallback();
        }
    }, [fieldsContext?.focusedField, hover]);
    useEffect(() => {
        if (field?.isFallback && isFocusedField) {
            loadFallback();
        }
    }, [
        operationsContext?.editOperationExecuted,
        editContext.refreshCompletedFlag,
        editContext.itemsRepository.revision,
    ]);
    const showFallbackButton = field?.isFallback && (_jsxs("div", { className: "flex items-center gap-1.5 text-xs", children: [_jsx(Checkbox, { className: "size-3.5", checked: showFallback, onCheckedChange: (checked) => setShowFallback(!!checked) }), _jsx("label", { className: "cursor-pointer", onClick: () => setShowFallback(!showFallback), children: "Fallback" })] }));
    if (!field) {
        return;
    }
    const isManuallyVisible = manualActionRunIds.length > 0;
    return (_jsxs("div", { "data-field-id": field.id, "data-fieldname": field.name, ref: ref, className: "not-first:mt-4 px-2", onClickCapture: () => {
            fieldsContext?.setFocusedField(field.descriptor, field.canWrite || false);
        }, onFocusCapture: () => {
            // Handle Tab navigation: update focused field when any input within this field gets focus
            fieldsContext?.setFocusedField(field.descriptor, field.canWrite || false);
        }, children: [_jsx(FieldListField, { field: field, validators: validators, simplified: simplified, title: title, isFocusedField: isFocusedField, showFallbackButton: showFallbackButton, compareToField: compareToField, readonly: readonly, isHoveringField: hover || isManuallyVisible, tabIndex: tabIndex }), field.isFallback && isFocusedField && showFallback && (_jsx(_Fragment, { children: fallbackChain &&
                    fallbackChain.map((x, i) => (_jsxs("div", { className: "ml-3", children: [_jsx("div", { className: "mb-4 text-center", children: _jsx(ArrowUp, { className: "fallback-arrow-animation relative top-3 inline-block h-5 w-5 font-bold text-blue-300" }) }), _jsx(FieldListField, { field: x, validators: validators, simplified: true, isFocusedField: true, readonly: readonly, isHoveringField: hover, title: _jsxs("div", { className: "text-xs", children: [x.displayName || x.name, " (", x.descriptor.item.language, ")", x.descriptor.item.id != field.descriptor.item.id && (_jsxs("span", { className: "text-gray-400", children: ["- Item: ", x.descriptor.item.id] }))] }) }, i)] }, i))) }))] }, field.id));
}
//# sourceMappingURL=FieldListFieldWithFallbacks.js.map