function _class_call_check(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
    }
}
function _defineProperties(target, props) {
    for(var i = 0; i < props.length; i++){
        var descriptor = props[i];
        descriptor.enumerable = descriptor.enumerable || false;
        descriptor.configurable = true;
        if ("value" in descriptor) descriptor.writable = true;
        Object.defineProperty(target, descriptor.key, descriptor);
    }
}
function _create_class(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    return Constructor;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
import { createSchemaElementEditorBridge } from "@schema-element-editor/host-sdk/core";
import React from "react";
import ReactDOM from "react-dom/client";
import { MarkdownEditor } from "../../MarkdownEditor";
/**
 * Schema Editor Bridge 单例管理器
 * @description 全局唯一的监听器管理，避免多个 Bubble 组件冲突
 *
 * @remarks
 * 推荐使用 `useSchemaEditorBridge` Hook，它会自动管理启用状态和注册/注销流程。
 * Schema Editor 在开发环境下自动启用（process.env.NODE_ENV === 'development'）。
 * 如需直接使用 Manager，需手动调用 `setEnabled(true)` 启动 Bridge。
 *
 * @example
 * ```tsx
 * // 推荐方式：使用 useSchemaEditorBridge Hook（开发环境自动启用）
 * const { content, setContent } = useSchemaEditorBridge(id, initialContent);
 *
 * // 直接使用 Manager（需手动管理启用状态）
 * useEffect(() => {
 *   const manager = SchemaEditorBridgeManager.getInstance();
 *   manager.setEnabled(true); // 必须：启用 Bridge
 *   manager.register(id, {
 *     getContent: () => contentRef.current,
 *     setContent: (c) => setContent(c)
 *   });
 *   return () => manager.unregister(id);
 * }, [id]);
 * ```
 */ export var SchemaEditorBridgeManager = /*#__PURE__*/ function() {
    "use strict";
    function SchemaEditorBridgeManager() {
        _class_call_check(this, SchemaEditorBridgeManager);
        /** Bubble 处理器注册表：id -> handler */ _define_property(this, "registry", new Map());
        /** Bridge 实例 */ _define_property(this, "bridge", null);
        /** 是否启用 */ _define_property(this, "enabled", false);
        /** 预览 Root */ _define_property(this, "previewRoot", null);
        /** 当前正在编辑的 Bubble id */ _define_property(this, "currentEditingId", null);
    }
    _create_class(SchemaEditorBridgeManager, [
        {
            /**
   * 设置启用状态
   * @param enabled - 是否启用
   */ key: "setEnabled",
            value: function setEnabled(enabled) {
                var wasEnabled = this.enabled;
                this.enabled = enabled;
                if (enabled && !wasEnabled && this.registry.size > 0) {
                    this.startBridge();
                } else if (!enabled && wasEnabled) {
                    this.stopBridge();
                }
            }
        },
        {
            /**
   * 检查是否启用
   */ key: "isEnabled",
            value: function isEnabled() {
                return this.enabled;
            }
        },
        {
            /**
   * 注册 Bubble 处理器
   * @param id - Bubble 的唯一标识（data-id）
   * @param handler - 处理器对象
   */ key: "register",
            value: function register(id, handler) {
                this.registry.set(id, handler);
                if (this.enabled) {
                    this.startBridge();
                }
            }
        },
        {
            /**
   * 注销 Bubble 处理器
   * @param id - Bubble 的唯一标识
   */ key: "unregister",
            value: function unregister(id) {
                this.registry.delete(id);
                if (this.registry.size === 0) {
                    this.stopBridge();
                }
            }
        },
        {
            /**
   * 获取注册的 Bubble 数量
   */ key: "getRegistrySize",
            value: function getRegistrySize() {
                return this.registry.size;
            }
        },
        {
            /**
   * 检查某个 ID 是否已注册
   */ key: "has",
            value: function has(id) {
                return this.registry.has(id);
            }
        },
        {
            key: "startBridge",
            value: /**
   * 启动 Bridge（幂等，已启动时直接返回）
   */ function startBridge() {
                var _this = this;
                if (this.bridge) return;
                this.bridge = createSchemaElementEditorBridge({
                    getSchema: function(params) {
                        var handler = _this.registry.get(params);
                        if (!handler) {
                            // 返回 undefined 表示该元素不可编辑，插件将无法打开编辑器
                            _this.currentEditingId = null;
                            return undefined;
                        }
                        // 记录当前编辑的 Bubble id,供 renderPreview 使用
                        _this.currentEditingId = params;
                        return handler.getContent();
                    },
                    updateSchema: function(schema, params) {
                        var handler = _this.registry.get(params);
                        if (!handler) {
                            return false;
                        }
                        try {
                            var content = typeof schema === 'string' ? schema : JSON.stringify(schema, null, 2);
                            handler.setContent(content);
                            return true;
                        } catch (error) {
                            console.error('[SchemaEditorBridge] updateSchema failed:', error);
                            return false;
                        }
                    },
                    renderPreview: function(schema, containerId) {
                        /** 使用当前编辑 Bubble 的自定义预览 */ if (_this.currentEditingId) {
                            var handler = _this.registry.get(_this.currentEditingId);
                            if (handler === null || handler === void 0 ? void 0 : handler.renderPreview) {
                                return handler.renderPreview(schema, containerId);
                            }
                        }
                        /** 兜底：内置 Markdown 预览 */ return _this.createDefaultPreview(schema, containerId);
                    }
                });
            }
        },
        {
            key: "stopBridge",
            value: /**
   * 停止 Bridge
   */ function stopBridge() {
                if (!this.bridge) return;
                try {
                    if (typeof this.bridge.cleanup === 'function') {
                        this.bridge.cleanup();
                    }
                } catch (error) {
                    console.warn('[SchemaEditorBridge] cleanup failed during stopBridge:', error);
                } finally{
                    this.bridge = null;
                }
            }
        },
        {
            key: "createDefaultPreview",
            value: /**
   * 创建默认预览
   * @description 使用 MarkdownEditor 渲染 Markdown 预览
   */ function createDefaultPreview(schema, containerId) {
                var _this = this;
                var container = document.getElementById(containerId);
                if (!container) return;
                var content = typeof schema === 'string' ? schema : JSON.stringify(schema, null, 2);
                /** 复用或创建 Root */ if (!this.previewRoot) {
                    this.previewRoot = ReactDOM.createRoot(container);
                }
                this.previewRoot.render(React.createElement(MarkdownEditor, {
                    initValue: content,
                    readonly: true,
                    style: {
                        padding: 16
                    },
                    height: 'auto',
                    width: '100%'
                }));
                return function() {
                    var _this_previewRoot_unmount, _this_previewRoot;
                    (_this_previewRoot = _this.previewRoot) === null || _this_previewRoot === void 0 ? void 0 : (_this_previewRoot_unmount = _this_previewRoot.unmount) === null || _this_previewRoot_unmount === void 0 ? void 0 : _this_previewRoot_unmount.call(_this_previewRoot);
                    _this.previewRoot = null;
                };
            }
        }
    ], [
        {
            key: "getInstance",
            value: /**
   * 获取单例实例
   * @returns SchemaEditorBridgeManager 实例
   */ function getInstance() {
                if (!SchemaEditorBridgeManager.instance) {
                    SchemaEditorBridgeManager.instance = new SchemaEditorBridgeManager();
                }
                return SchemaEditorBridgeManager.instance;
            }
        },
        {
            key: "destroy",
            value: /**
   * 销毁单例（主要用于测试）
   */ function destroy() {
                var _instance_previewRoot;
                if (!SchemaEditorBridgeManager.instance) return;
                var instance = SchemaEditorBridgeManager.instance;
                instance.stopBridge();
                (_instance_previewRoot = instance.previewRoot) === null || _instance_previewRoot === void 0 ? void 0 : _instance_previewRoot.unmount();
                instance.previewRoot = null;
                instance.registry.clear();
                SchemaEditorBridgeManager.instance = null;
            }
        }
    ]);
    return SchemaEditorBridgeManager;
}();
/** 单例实例 */ _define_property(SchemaEditorBridgeManager, "instance", null);
export default SchemaEditorBridgeManager;
