"use strict";
const common_vendor = require("../../../../common/vendor.js");
const uni_modules_uviewPro_libs_util_logger = require("../util/logger.js");
const PARENT_CONTEXT_SYMBOL = Symbol("parent_context");
function generateInstanceId(componentName) {
  return `${componentName}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
function findParentInstance(name, instance) {
  var _a, _b;
  if (!instance)
    return null;
  let parent = instance.parent;
  while (parent) {
    const parentName = ((_a = parent.type) == null ? void 0 : _a.name) || ((_b = parent.type) == null ? void 0 : _b.__name);
    if (parentName === name) {
      return parent;
    }
    parent = parent.parent;
  }
  return null;
}
function getParentContext(name, instance) {
  var _a;
  const parentInstance = findParentInstance(name, instance);
  return ((_a = parentInstance == null ? void 0 : parentInstance.proxy) == null ? void 0 : _a[PARENT_CONTEXT_SYMBOL]) || null;
}
function findAllChildComponents(componentName, instance) {
  const components = [];
  function traverse(currentInstance) {
    var _a;
    if (!(currentInstance == null ? void 0 : currentInstance.subTree))
      return;
    const subTree = ((_a = currentInstance.subTree) == null ? void 0 : _a.children) || [];
    const children = Array.isArray(subTree) ? subTree : [subTree];
    children.forEach((vnode) => {
      var _a2, _b;
      const child = vnode.component;
      if (!child)
        return;
      const name = ((_a2 = child.type) == null ? void 0 : _a2.name) || ((_b = child.type) == null ? void 0 : _b.__name);
      if (name === componentName) {
        components.push(child);
      }
      traverse(child);
    });
  }
  traverse(instance);
  uni_modules_uviewPro_libs_util_logger.logger.log(`Found ${components.length} ${componentName} components`);
  return components;
}
function useParent(componentName) {
  const instance = common_vendor.getCurrentInstance();
  if (!instance) {
    throw new Error("useParent must be called within setup function");
  }
  const name = componentName || instance.type.name || instance.type.__name;
  if (!name) {
    throw new Error("Component name is required for useParent");
  }
  const children = common_vendor.reactive([]);
  const childrenMap = /* @__PURE__ */ new Map();
  const broadcast = (event, data, childIds) => {
    const targetChildren = childIds ? (Array.isArray(childIds) ? childIds : [childIds]).map((id) => childrenMap.get(id)).filter(Boolean) : Array.from(childrenMap.values());
    uni_modules_uviewPro_libs_util_logger.logger.log(`Parent ${name} broadcasting event: ${event} to ${targetChildren.length} children`);
    targetChildren.forEach((child) => {
      const exposed = child.getExposed();
      if (exposed && typeof exposed[event] === "function") {
        try {
          exposed[event](data);
        } catch (error) {
          uni_modules_uviewPro_libs_util_logger.logger.warn(`Error calling child method ${event}:`, error);
        }
      }
    });
  };
  const broadcastToChildren = (componentName2, event, data) => {
    uni_modules_uviewPro_libs_util_logger.logger.log(`Parent ${name} broadcasting event: ${event} to all ${componentName2} components`);
    const childComponents = findAllChildComponents(componentName2, instance);
    let successCount = 0;
    childComponents.forEach((childComponent) => {
      const exposed = childComponent.exposed || childComponent.proxy;
      if (exposed && typeof exposed[event] === "function") {
        try {
          exposed[event](data);
          successCount++;
        } catch (error) {
          uni_modules_uviewPro_libs_util_logger.logger.warn(`Error calling ${componentName2} method ${event}:`, error);
        }
      }
    });
    uni_modules_uviewPro_libs_util_logger.logger.log(
      `Parent ${name} successfully called ${successCount} of ${childComponents.length} ${componentName2} components`
    );
  };
  const parentContext = {
    name,
    addChild(child) {
      if (!childrenMap.has(child.id)) {
        childrenMap.set(child.id, child);
        children.push(child);
        uni_modules_uviewPro_libs_util_logger.logger.log(`Parent ${name} added child: ${child.name}`);
      }
    },
    removeChild(childId) {
      if (childrenMap.has(childId)) {
        childrenMap.get(childId);
        childrenMap.delete(childId);
        const index = children.findIndex((c) => c.id === childId);
        if (index > -1)
          children.splice(index, 1);
        uni_modules_uviewPro_libs_util_logger.logger.log(`Parent ${name} removed child: ${childId}`);
      }
    },
    broadcast,
    broadcastToChildren,
    getChildren: () => Array.from(childrenMap.values()),
    getExposed: () => instance.exposed || {},
    getChildExposed(childId) {
      var _a;
      const child = childrenMap.get(childId);
      return ((_a = child == null ? void 0 : child.getExposed) == null ? void 0 : _a.call(child)) || {};
    },
    getChildrenExposed() {
      return Array.from(childrenMap.values()).filter((child) => child.getExposed).map((child) => ({
        id: child.id,
        name: child.name,
        exposed: child.getExposed()
      })).filter((item) => Object.keys(item.exposed).length > 0);
    },
    getInstance: () => instance
  };
  if (instance.proxy) {
    instance.proxy[PARENT_CONTEXT_SYMBOL] = parentContext;
  }
  common_vendor.onUnmounted(() => {
    childrenMap.forEach((_, childId) => parentContext.removeChild(childId));
    if (instance.proxy) {
      delete instance.proxy[PARENT_CONTEXT_SYMBOL];
    }
    uni_modules_uviewPro_libs_util_logger.logger.log(`Parent ${name} unmounted and cleaned up`);
  });
  return {
    parentName: name,
    children,
    broadcast,
    broadcastToChildren,
    getChildren: parentContext.getChildren,
    getChildExposed: parentContext.getChildExposed,
    getChildrenExposed: parentContext.getChildrenExposed,
    getExposed: parentContext.getExposed,
    getInstance: parentContext.getInstance
  };
}
function useChildren(componentName, parentName) {
  const instance = common_vendor.getCurrentInstance();
  if (!instance) {
    throw new Error("useChildren must be called within setup function");
  }
  const name = componentName || instance.type.name || instance.type.__name;
  const instanceId = generateInstanceId(name || "anonymous");
  const parentRef = common_vendor.ref(null);
  const parentExposed = common_vendor.ref({});
  const createSimulatedParentContext = (parentInstance) => {
    var _a, _b;
    return {
      name: ((_a = parentInstance == null ? void 0 : parentInstance.type) == null ? void 0 : _a.name) || ((_b = parentInstance == null ? void 0 : parentInstance.type) == null ? void 0 : _b.__name) || "unknown",
      addChild: () => uni_modules_uviewPro_libs_util_logger.logger.log("Simulated parent added child"),
      removeChild: () => uni_modules_uviewPro_libs_util_logger.logger.log("Simulated parent removed child"),
      broadcast: () => uni_modules_uviewPro_libs_util_logger.logger.log("Simulated parent broadcasting"),
      broadcastToChildren: () => uni_modules_uviewPro_libs_util_logger.logger.log("Simulated parent broadcasting to children"),
      getChildren: () => [],
      getExposed: () => (parentInstance == null ? void 0 : parentInstance.exposed) || {},
      getChildExposed: () => ({}),
      getChildrenExposed: () => [],
      getInstance: () => parentInstance
    };
  };
  const getParentExposed = () => {
    if (parentRef.value) {
      const exposed = parentRef.value.getExposed();
      parentExposed.value = exposed;
      return exposed;
    }
    return {};
  };
  const getExposed = () => instance.exposed || {};
  const findParent = () => {
    var _a;
    if (parentName) {
      const parentContext = getParentContext(parentName, instance);
      if (parentContext) {
        if (!parentContext.getInstance) {
          parentContext.getInstance = () => findParentInstance(parentName, instance);
        }
        return parentContext;
      }
      const parentInstance = findParentInstance(parentName, instance);
      if (parentInstance) {
        return createSimulatedParentContext(parentInstance);
      }
    }
    let current = instance.parent;
    while (current) {
      const context = (_a = current.proxy) == null ? void 0 : _a[PARENT_CONTEXT_SYMBOL];
      if (context) {
        if (!context.getInstance) {
          context.getInstance = () => current;
        }
        return context;
      }
      current = current.parent;
    }
    return instance.parent ? createSimulatedParentContext(instance.parent) : null;
  };
  const linkParent = () => {
    const parent = findParent();
    if (parent) {
      parentRef.value = parent;
      if (parent.addChild && childContext) {
        parent.addChild(childContext);
      }
      getParentExposed();
      uni_modules_uviewPro_libs_util_logger.logger.log(`Child ${name || "anonymous"} linked to parent ${parent.name}`);
      return true;
    }
    uni_modules_uviewPro_libs_util_logger.logger.log(`Child ${name || "anonymous"} no parent found, working in standalone mode`);
    return false;
  };
  const emitToParent = (event, data) => {
    if (parentRef.value) {
      const exposed = getParentExposed();
      if (exposed && typeof exposed[event] === "function") {
        try {
          exposed[event](data, instanceId, name);
        } catch (error) {
          uni_modules_uviewPro_libs_util_logger.logger.warn(`Error calling parent method ${event}:`, error);
        }
      }
    }
  };
  const getChildIndex = () => {
    if (!parentRef.value)
      return -1;
    try {
      const children = parentRef.value.getChildren();
      return children.findIndex((child) => child.id === instanceId);
    } catch (error) {
      return -1;
    }
  };
  const childContext = {
    id: instanceId,
    name: name || "anonymous",
    getChildIndex,
    emitToParent,
    getParentExposed,
    getInstance: () => instance,
    getExposed
  };
  uni_modules_uviewPro_libs_util_logger.logger.log(`Child ${name || "anonymous"} registered, looking for parent`);
  common_vendor.onMounted(() => {
    let connected = linkParent();
    common_vendor.nextTick$1(() => {
      connected = linkParent();
      if (!connected) {
        setTimeout(linkParent, 500);
      }
    });
  });
  common_vendor.onUnmounted(() => {
    var _a;
    if ((_a = parentRef.value) == null ? void 0 : _a.removeChild) {
      parentRef.value.removeChild(instanceId);
    }
    uni_modules_uviewPro_libs_util_logger.logger.log(`Child ${name || "anonymous"} unmounted`);
  });
  return {
    childId: instanceId,
    childName: name || "anonymous",
    childIndex: common_vendor.computed(getChildIndex),
    parent: parentRef,
    emitToParent,
    getParentExposed,
    parentExposed: common_vendor.computed(() => parentExposed.value),
    getExposed
  };
}
exports.useChildren = useChildren;
exports.useParent = useParent;
//# sourceMappingURL=../../../../../.sourcemap/mp-weixin/uni_modules/uview-pro/libs/hooks/useCompRelation.js.map
