"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PCEditorStoreProvider = void 0;
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const React = tslib_1.__importStar(require("react"));
const postMessage_1 = require("../../common/postMessage.js");
const store_1 = require("../../common/store.js");
const usePostMessageAPI_1 = require("../../hooks/usePostMessageAPI.js");
const PCEditorStoreContext_1 = require("./PCEditorStoreContext.js");
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 (!(0, postMessage_1.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) {
                (0, usePostMessageAPI_1.sendEventPostMessage)('ON_EDITOR_REDO', {});
            }
            else {
                (0, usePostMessageAPI_1.sendEventPostMessage)('ON_EDITOR_UNDO', {});
            }
        };
        window.addEventListener('keydown', onKeyDown, true);
        return () => window.removeEventListener('keydown', onKeyDown, true);
    }, []);
    if (!storeRef.current) {
        storeRef.current = (0, store_1.createPCEditorStore)();
    }
    return ((0, jsx_runtime_1.jsx)(PCEditorStoreContext_1.PCEditorStoreContext.Provider, { value: {
            state: storeRef.current,
        }, children: children }));
};
exports.PCEditorStoreProvider = PCEditorStoreProvider;
//# sourceMappingURL=PCEditorStoreProvider.js.map
