import * as React from "react";
import { hasAllFeatures } from "../../security/features.js";
const GLOBAL_COMPONENT_REGISTRY_KEY = "__openMercatoComponentRegistry__";
function isComponentOverride(value) {
  if (!value || typeof value !== "object") {
    return false;
  }
  const target = value.target;
  if (!target || typeof target !== "object") {
    return false;
  }
  return typeof target.componentId === "string" && target.componentId.length > 0;
}
function getState() {
  const globalValue = globalThis[GLOBAL_COMPONENT_REGISTRY_KEY];
  if (globalValue && typeof globalValue === "object") {
    const typed = globalValue;
    if (typed.components instanceof Map && Array.isArray(typed.overrides)) {
      return typed;
    }
  }
  const initial = {
    components: /* @__PURE__ */ new Map(),
    overrides: []
  };
  globalThis[GLOBAL_COMPONENT_REGISTRY_KEY] = initial;
  return initial;
}
function registerComponent(entry) {
  const state = getState();
  state.components.set(entry.id, entry);
}
function registerComponentOverrides(overrides) {
  const state = getState();
  state.overrides = overrides.filter(isComponentOverride);
}
function getComponentEntry(componentId) {
  const state = getState();
  return state.components.get(componentId) ?? null;
}
function getComponentOverrides(componentId, userFeatures) {
  const state = getState();
  const relevant = state.overrides.filter((override) => {
    if (!isComponentOverride(override)) return false;
    if (override.target.componentId !== componentId) return false;
    if (override.features && override.features.length > 0) {
      if (!hasAllFeatures(userFeatures, override.features)) return false;
    }
    return true;
  });
  return relevant.sort((a, b) => a.priority - b.priority);
}
function resolveRegisteredComponent(componentId, fallback, userFeatures) {
  const overrides = getComponentOverrides(componentId, userFeatures);
  let resolved = fallback;
  for (const override of overrides) {
    if ("replacement" in override) {
      resolved = override.replacement;
      continue;
    }
    if ("wrapper" in override) {
      resolved = override.wrapper(resolved);
      continue;
    }
    if ("propsTransform" in override) {
      const transform = override.propsTransform;
      const Current = resolved;
      resolved = ((props) => {
        const transformed = transform(props);
        return React.createElement(Current, transformed);
      });
    }
  }
  return resolved;
}
const ComponentReplacementHandles = {
  page: (path) => `page:${path}`,
  dataTable: (tableId) => `data-table:${tableId}`,
  crudForm: (entityId) => `crud-form:${entityId}`,
  section: (scope, sectionId) => `section:${scope}.${sectionId}`
};
export {
  ComponentReplacementHandles,
  getComponentEntry,
  getComponentOverrides,
  registerComponent,
  registerComponentOverrides,
  resolveRegisteredComponent
};
//# sourceMappingURL=component-registry.js.map
