import { jsx as _jsx } from "react/jsx-runtime";
import * as React from 'react';
import { isValidPostMessage } from "../../common/postMessage.js";
import { createPCEditorStore } from "../../common/store.js";
import { sendEventPostMessage } from "../../hooks/usePostMessageAPI.js";
import { PCEditorStoreContext } from "./PCEditorStoreContext.js";
export const PCEditorStoreProvider = ({ children }) => {
    const storeRef = React.useRef();
    const syncStore = React.useCallback((message) => {
        if (storeRef.current && message.state) {
            storeRef.current.setState(message.state);
        }
    }, []);
    React.useEffect(() => {
        const onMessage = (e) => {
            if (!isValidPostMessage(e.data)) {
                return;
            }
            const message = e.data;
            syncStore(message);
        };
        window.addEventListener('message', onMessage);
        return () => window.removeEventListener('message', onMessage);
    }, [syncStore]);
    // When Page Constructor runs inside the editor preview iframe, keyboard focus stays in the iframe
    // after clicking the canvas — parent window never receives Cmd+Z. Forward to parent via postMessage.
    React.useEffect(() => {
        if (typeof window === 'undefined' || window.parent === window) {
            return undefined;
        }
        const onKeyDown = (e) => {
            if (!(e.metaKey || e.ctrlKey) || e.key.toLowerCase() !== 'z') {
                return;
            }
            const target = e.target;
            if (target?.closest('input, textarea, select, [contenteditable="true"]')) {
                return;
            }
            e.preventDefault();
            if (e.shiftKey) {
                sendEventPostMessage('ON_EDITOR_REDO', {});
            }
            else {
                sendEventPostMessage('ON_EDITOR_UNDO', {});
            }
        };
        window.addEventListener('keydown', onKeyDown, true);
        return () => window.removeEventListener('keydown', onKeyDown, true);
    }, []);
    if (!storeRef.current) {
        storeRef.current = createPCEditorStore();
    }
    return (_jsx(PCEditorStoreContext.Provider, { value: {
            state: storeRef.current,
        }, children: children }));
};
//# sourceMappingURL=PCEditorStoreProvider.js.map
