"use client";
import { useEffect, useRef } from "react";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { APPLY_VALUE_TAG } from "./constants.js";
import { hashSerializedState } from "./utils/hashSerializedState.js";
function ApplyValuePlugin({ value, incomingHash, lastEmittedHashRef, normalizedIncomingHashRef, hasNormalizedBaselineRef }) {
    const [editor] = useLexicalComposerContext();
    const lastAppliedHashRef = useRef(void 0);
    const cancelWaiterRef = useRef(void 0);
    useEffect(()=>{
        if (null == value) return;
        const nextRawHash = incomingHash;
        if (nextRawHash === lastEmittedHashRef.current) {
            if (true !== hasNormalizedBaselineRef.current) {
                hasNormalizedBaselineRef.current = true;
                if (cancelWaiterRef.current) {
                    cancelWaiterRef.current();
                    cancelWaiterRef.current = void 0;
                }
            }
            return;
        }
        if (nextRawHash === lastAppliedHashRef.current) return;
        if (cancelWaiterRef.current) {
            cancelWaiterRef.current();
            cancelWaiterRef.current = void 0;
        }
        hasNormalizedBaselineRef.current = false;
        const nextState = editor.parseEditorState(value);
        editor.update(()=>{
            editor.setEditorState(nextState);
        }, {
            tag: APPLY_VALUE_TAG
        });
        lastAppliedHashRef.current = nextRawHash;
        let cancelled = false;
        cancelWaiterRef.current = ()=>{
            cancelled = true;
        };
        queueMicrotask(()=>{
            requestAnimationFrame(()=>{
                requestAnimationFrame(()=>{
                    if (cancelled) return;
                    const settled = editor.getEditorState().toJSON();
                    normalizedIncomingHashRef.current = hashSerializedState(settled);
                    hasNormalizedBaselineRef.current = true;
                });
            });
        });
    }, [
        editor,
        value,
        incomingHash,
        lastEmittedHashRef,
        normalizedIncomingHashRef,
        hasNormalizedBaselineRef
    ]);
    return null;
}
export { ApplyValuePlugin };
