import '../chunk-2QM732NQ.js';
import { registerTrait, unregisterTrait, updateTraitState } from '../chunk-42YQ6JVR.js';
import '../chunk-3HJHHULT.js';
import { useFetchedDataContext } from '../chunk-42AVZIGQ.js';
import '../chunk-IP2FYX3M.js';
import '../chunk-WGJIL4YR.js';
import { useEventBus } from '../chunk-YXZM3WCF.js';
import '../chunk-DKQN5FVU.js';
import '../chunk-3JGAROCW.js';
import { recordTransition } from '../chunk-WCTZ7WZX.js';
import '../chunk-TSETXL2E.js';
import '../chunk-K2D5D3WK.js';
import '../chunk-N7MVUW4R.js';
import '../chunk-PKBMQBKP.js';
import { createContext, useMemo, useContext, useState, useRef, useEffect, useCallback } from 'react';
import { isCircuitEvent, schemaToIR, getPage, clearSchemaCache as clearSchemaCache$1 } from '@almadar/core';
import { StateMachineManager, createContextFromBindings, interpolateValue, EffectExecutor } from '@almadar/runtime';
import { isEntityAwarePattern } from '@almadar/patterns';
import { jsx } from 'react/jsx-runtime';

// runtime/createClientEffectHandlers.ts
function createClientEffectHandlers(options) {
  const { eventBus, slotSetter, navigate, notify, enrichPattern } = options;
  return {
    emit: (event, payload) => {
      const prefixedEvent = event.startsWith("UI:") ? event : `UI:${event}`;
      eventBus.emit(prefixedEvent, { payload });
    },
    persist: async () => {
      console.warn("[ClientEffectHandlers] persist is server-side only, ignored on client");
    },
    set: () => {
      console.warn("[ClientEffectHandlers] set is server-side only, ignored on client");
    },
    callService: async () => {
      console.warn("[ClientEffectHandlers] callService is server-side only, ignored on client");
      return {};
    },
    renderUI: (slot, pattern, props) => {
      if (pattern === null) {
        slotSetter.clearSlot(slot);
        return;
      }
      const enriched = enrichPattern ? enrichPattern(pattern) : pattern;
      slotSetter.addPattern(slot, enriched, props);
    },
    navigate: navigate ?? ((path) => {
      console.warn("[ClientEffectHandlers] No navigate handler, ignoring:", path);
    }),
    notify: notify ?? ((msg, type) => {
      console.log(`[ClientEffectHandlers] notify (${type}):`, msg);
    })
  };
}
var EntitySchemaContext = createContext(null);
function EntitySchemaProvider({
  entities,
  children
}) {
  const entitiesMap = useMemo(() => {
    const map = /* @__PURE__ */ new Map();
    for (const entity of entities) {
      map.set(entity.name, entity);
    }
    return map;
  }, [entities]);
  const contextValue = useMemo(
    () => ({
      entities: entitiesMap
    }),
    [entitiesMap]
  );
  return /* @__PURE__ */ jsx(EntitySchemaContext.Provider, { value: contextValue, children });
}
function useEntitySchema() {
  const context = useContext(EntitySchemaContext);
  if (!context) {
    throw new Error("useEntitySchema must be used within an EntitySchemaProvider");
  }
  return context;
}
function useEntityDefinition(entityName) {
  const { entities } = useEntitySchema();
  return entities.get(entityName);
}

// runtime/useTraitStateMachine.ts
function toTraitDefinition(binding) {
  return {
    name: binding.trait.name,
    states: binding.trait.states,
    transitions: binding.trait.transitions,
    listens: binding.trait.listens
  };
}
function normalizeEventKey(eventKey) {
  return eventKey.startsWith("UI:") ? eventKey.slice(3) : eventKey;
}
function useTraitStateMachine(traitBindings, slotsActions, options) {
  const eventBus = useEventBus();
  const { entities } = useEntitySchema();
  const fetchedDataContext = useFetchedDataContext();
  const manager = useMemo(() => {
    const traitDefs = traitBindings.map(toTraitDefinition);
    return new StateMachineManager(traitDefs);
  }, [traitBindings]);
  const [traitStates, setTraitStates] = useState(() => {
    return manager.getAllStates();
  });
  const traitBindingsRef = useRef(traitBindings);
  const managerRef = useRef(manager);
  const slotsActionsRef = useRef(slotsActions);
  const optionsRef = useRef(options);
  useEffect(() => {
    traitBindingsRef.current = traitBindings;
  }, [traitBindings]);
  useEffect(() => {
    managerRef.current = manager;
    setTraitStates(manager.getAllStates());
  }, [manager]);
  useEffect(() => {
    slotsActionsRef.current = slotsActions;
  }, [slotsActions]);
  useEffect(() => {
    optionsRef.current = options;
  }, [options]);
  const traitStatesRef = useRef(traitStates);
  const fetchedDataContextRef = useRef(fetchedDataContext);
  useEffect(() => {
    traitStatesRef.current = traitStates;
  }, [traitStates]);
  useEffect(() => {
    fetchedDataContextRef.current = fetchedDataContext;
  }, [fetchedDataContext]);
  useEffect(() => {
    const mgr = managerRef.current;
    const bindings = traitBindingsRef.current;
    const ids = [];
    for (const binding of bindings) {
      const trait = binding.trait;
      const state = mgr.getState(trait.name);
      const info = {
        id: trait.name,
        name: trait.name,
        currentState: state?.currentState ?? trait.states[0]?.name ?? "unknown",
        states: trait.states.map((s) => s.name),
        transitions: trait.transitions.flatMap((t) => {
          const froms = Array.isArray(t.from) ? t.from : [t.from];
          return froms.map((f) => ({
            from: f,
            to: t.to,
            event: t.event,
            guard: t.guard ? String(t.guard) : void 0
          }));
        }),
        guards: trait.transitions.filter((t) => t.guard).map((t) => ({ name: String(t.guard) })),
        transitionCount: 0
      };
      registerTrait(info);
      ids.push(trait.name);
    }
    return () => {
      for (const id of ids) {
        unregisterTrait(id);
      }
    };
  }, [traitBindings]);
  useEffect(() => {
    const newManager = managerRef.current;
    newManager.resetAll();
    setTraitStates(newManager.getAllStates());
    console.log(
      "[TraitStateMachine] Reset states for page navigation:",
      Array.from(newManager.getAllStates().keys()).join(", ")
    );
  }, [traitBindings]);
  const runTickEffects = useCallback((tick, binding) => {
    const fdc = fetchedDataContextRef.current;
    const actions = slotsActionsRef.current;
    const linkedEntity = binding.linkedEntity ?? "";
    const currentState = traitStatesRef.current.get(binding.trait.name)?.currentState ?? "";
    if (tick.appliesTo.length > 0 && !tick.appliesTo.includes(currentState)) return;
    const records = linkedEntity && fdc ? fdc.getData(linkedEntity) : [];
    const entityData = records.length > 0 ? Object.assign([...records], records[0]) : {};
    const bindingCtx = { entity: entityData, payload: {}, state: currentState };
    const evalCtx = createContextFromBindings(bindingCtx);
    if (tick.guard !== void 0) {
      const passed = interpolateValue(tick.guard, evalCtx);
      if (!passed) return;
    }
    const entityMutations = /* @__PURE__ */ new Map();
    const pendingSlots = /* @__PURE__ */ new Map();
    const slotSource = {
      trait: binding.trait.name,
      state: currentState,
      transition: `${currentState}->tick:${tick.name}`,
      effects: tick.effects,
      traitDefinition: binding.trait
    };
    const enrichTickNode = (node) => {
      if (!node || typeof node !== "object") return node;
      const rec = node;
      const nodeType = rec.type;
      let enriched = rec;
      if (Array.isArray(rec.children)) {
        enriched = { ...rec, children: rec.children.map(enrichTickNode) };
      }
      if (nodeType && isEntityAwarePattern(nodeType) && fdc) {
        let injected = false;
        if (typeof enriched.entity === "string") {
          const entityRecords = fdc.getData(enriched.entity);
          if (entityRecords.length > 0) {
            enriched = { ...enriched, entity: entityRecords };
            injected = true;
          }
        } else if (!enriched.entity && linkedEntity) {
          const entityRecords = fdc.getData(linkedEntity);
          if (entityRecords.length > 0) {
            enriched = { ...enriched, entity: entityRecords };
            injected = true;
          }
        }
        if (injected && !enriched.fields && !enriched.columns) {
          const sample = enriched.entity[0];
          if (sample && typeof sample === "object") {
            const keys = Object.keys(sample).filter((k) => k !== "id" && k !== "_id");
            enriched = { ...enriched, fields: keys.map((k, i) => ({ name: k, variant: i === 0 ? "h4" : "body" })), children: void 0 };
          }
        }
      }
      return enriched;
    };
    for (const effect of tick.effects) {
      if (!Array.isArray(effect)) continue;
      const op = effect[0];
      if (op === "set") {
        const path = effect[1];
        if (typeof path !== "string" || !path.startsWith("@entity.")) continue;
        const field = path.slice("@entity.".length);
        const updatedCtx = createContextFromBindings(bindingCtx);
        const value = interpolateValue(effect[2], updatedCtx);
        bindingCtx.entity[field] = value;
        entityMutations.set(field, value);
      } else if (op === "render-ui" || op === "render") {
        const slot = effect[1];
        const rawPattern = effect[2];
        if (rawPattern === null || rawPattern === void 0) {
          pendingSlots.set(slot, []);
          continue;
        }
        const updatedCtx = createContextFromBindings(bindingCtx);
        const resolved = interpolateValue(rawPattern, updatedCtx);
        const enriched = enrichTickNode(resolved);
        const existing = pendingSlots.get(slot) ?? [];
        existing.push({ pattern: enriched, props: {} });
        pendingSlots.set(slot, existing);
      }
    }
    for (const [slot, patterns] of pendingSlots) {
      if (patterns.length === 0) {
        actions.clearSlot(slot);
      } else {
        actions.setSlotPatterns(slot, patterns, slotSource);
      }
    }
    if (linkedEntity && entityMutations.size > 0 && fdc) {
      const latestRecords = fdc.getData(linkedEntity);
      if (latestRecords.length > 0) {
        const updated = latestRecords.map(
          (r, i) => i === 0 ? { ...r, ...Object.fromEntries(entityMutations) } : r
        );
        fdc.setData({ [linkedEntity]: updated });
      }
    }
  }, []);
  useEffect(() => {
    const hasFrameTicks = traitBindingsRef.current.some(
      (b) => b.trait.ticks?.some((t) => t.interval === "frame")
    );
    if (!hasFrameTicks) return;
    let running = true;
    let rafId = 0;
    const frame = () => {
      if (!running) return;
      for (const binding of traitBindingsRef.current) {
        for (const tick of binding.trait.ticks ?? []) {
          if (tick.interval !== "frame") continue;
          runTickEffects(tick, binding);
        }
      }
      rafId = requestAnimationFrame(frame);
    };
    rafId = requestAnimationFrame(frame);
    return () => {
      running = false;
      cancelAnimationFrame(rafId);
    };
  }, [traitBindings, runTickEffects]);
  useEffect(() => {
    const intervals = [];
    for (const binding of traitBindings) {
      for (const tick of binding.trait.ticks ?? []) {
        if (tick.interval === "frame") continue;
        const ms = tick.interval;
        intervals.push(setInterval(() => {
          runTickEffects(tick, binding);
        }, ms));
      }
    }
    return () => {
      for (const id of intervals) clearInterval(id);
    };
  }, [traitBindings, runTickEffects]);
  const processEvent = useCallback((eventKey, payload) => {
    const normalizedEvent = normalizeEventKey(eventKey);
    const bindings = traitBindingsRef.current;
    const currentManager = managerRef.current;
    const actions = slotsActionsRef.current;
    console.log("[TraitStateMachine] Processing event:", normalizedEvent, "payload:", payload);
    const bindingMap = new Map(bindings.map((b) => [b.trait.name, b]));
    const results = currentManager.sendEvent(normalizedEvent, payload);
    for (const { traitName, result } of results) {
      const binding = bindingMap.get(traitName);
      const traitState = currentManager.getState(traitName);
      if (!binding || !traitState) continue;
      if (result.executed && result.effects.length > 0) {
        console.log(
          "[TraitStateMachine] Executing",
          result.effects.length,
          "effects for",
          traitName,
          "| linkedEntity:",
          binding.linkedEntity,
          "| transition:",
          `${result.previousState} -> ${result.newState}`,
          "| effects:",
          JSON.stringify(result.effects)
        );
        const linkedEntity = binding.linkedEntity || "";
        const entityId = payload?.entityId;
        const entityData = (() => {
          if (!linkedEntity || !fetchedDataContext) return payload || {};
          if (entityId) {
            return fetchedDataContext.getById(linkedEntity, entityId) || {};
          }
          const records = fetchedDataContext.getData(linkedEntity);
          if (records.length === 0) return payload || {};
          const firstRecord = records[0];
          return Object.assign([...records], firstRecord);
        })();
        const pendingSlots = /* @__PURE__ */ new Map();
        const slotSource = {
          trait: binding.trait.name,
          state: result.previousState,
          transition: `${result.previousState}->${result.newState}`,
          effects: result.effects,
          traitDefinition: binding.trait
        };
        const handlers = createClientEffectHandlers({
          eventBus,
          slotSetter: {
            addPattern: (slot, pattern, props) => {
              const existing = pendingSlots.get(slot) || [];
              existing.push({ pattern, props: props || {} });
              pendingSlots.set(slot, existing);
            },
            clearSlot: (slot) => {
              pendingSlots.set(slot, []);
            }
          },
          navigate: optionsRef.current?.navigate,
          notify: optionsRef.current?.notify,
          enrichPattern: (pattern) => {
            const enrichNode = (node) => {
              if (!node || typeof node !== "object") return node;
              const rec = node;
              const nodeType = rec.type;
              let enriched = rec;
              if (Array.isArray(rec.children)) {
                const enrichedChildren = rec.children.map(enrichNode);
                enriched = { ...rec, children: enrichedChildren };
              }
              if (nodeType && isEntityAwarePattern(nodeType) && fetchedDataContext) {
                let injected = false;
                if (typeof enriched.entity === "string") {
                  const records = fetchedDataContext.getData(enriched.entity);
                  if (records.length > 0) {
                    enriched = { ...enriched, entity: records };
                    injected = true;
                  }
                } else if (!enriched.entity && linkedEntity) {
                  const records = fetchedDataContext.getData(linkedEntity);
                  if (records.length > 0) {
                    enriched = { ...enriched, entity: records };
                    injected = true;
                  }
                }
                if (injected && !enriched.fields && !enriched.columns) {
                  const sample = enriched.entity[0];
                  if (sample && typeof sample === "object") {
                    const keys = Object.keys(sample).filter((k) => k !== "id" && k !== "_id");
                    enriched = {
                      ...enriched,
                      fields: keys.map((k, i) => ({
                        name: k,
                        variant: i === 0 ? "h4" : "body"
                      })),
                      // Remove pattern-config children that components
                      // can't render (they expect a function or nothing)
                      children: void 0
                    };
                  }
                }
              }
              return enriched;
            };
            return enrichNode(pattern);
          }
        });
        const bindingCtx = {
          entity: entityData,
          payload: payload || {},
          state: result.previousState
        };
        const entityMutations = /* @__PURE__ */ new Map();
        for (const effect of result.effects) {
          if (!Array.isArray(effect) || effect[0] !== "set") continue;
          const path = effect[1];
          if (typeof path !== "string" || !path.startsWith("@entity.")) continue;
          const field = path.slice("@entity.".length);
          const evalCtx = createContextFromBindings(bindingCtx);
          const value = interpolateValue(effect[2], evalCtx);
          if (bindingCtx.entity !== null && typeof bindingCtx.entity === "object") {
            bindingCtx.entity[field] = value;
          }
          entityMutations.set(field, value);
        }
        const effectContext = {
          traitName: binding.trait.name,
          state: result.previousState,
          transition: `${result.previousState}->${result.newState}`,
          linkedEntity,
          entityId
        };
        const executor = new EffectExecutor({ handlers, bindings: bindingCtx, context: effectContext });
        executor.executeAll(result.effects).then(() => {
          console.log(
            "[TraitStateMachine] After executeAll, pendingSlots:",
            Object.fromEntries(pendingSlots.entries())
          );
          for (const [slot, patterns] of pendingSlots) {
            if (patterns.length === 0) {
              actions.clearSlot(slot);
            } else {
              actions.setSlotPatterns(slot, patterns, slotSource);
            }
          }
          if (linkedEntity && entityMutations.size > 0 && fetchedDataContext) {
            const records = fetchedDataContext.getData(linkedEntity);
            if (records.length > 0) {
              const updated = records.map(
                (r, i) => i === 0 ? { ...r, ...Object.fromEntries(entityMutations) } : r
              );
              fetchedDataContext.setData({ [linkedEntity]: updated });
            }
          }
        }).catch((error) => {
          console.error(
            "[TraitStateMachine] Effect execution error:",
            error,
            "| effects:",
            JSON.stringify(result.effects)
          );
        });
      } else if (!result.executed) {
        if (result.guardResult === false) {
          console.log(
            "[TraitStateMachine] Guard blocked transition:",
            traitName,
            result.previousState,
            "->",
            result.transition?.to
          );
        } else if (!result.transition) {
          if (isCircuitEvent(normalizedEvent)) {
            console.warn(
              `[CLOSED CIRCUIT VIOLATION] Trait "${traitName}" in state "${traitState.currentState}" received event "${normalizedEvent}" but has no transition to handle it.
   This is likely a schema issue. To fix, add a transition:
   { from: "${traitState.currentState}", to: "<target_state>", event: "${normalizedEvent}", effects: [...] }
   Or ensure the previous action (that opened this UI) properly transitions back before emitting this event.`
            );
          } else {
            console.log(
              "[TraitStateMachine] No transition for",
              traitName,
              "from state:",
              traitState.currentState,
              "on event:",
              normalizedEvent
            );
          }
        }
      }
    }
    for (const { traitName, result } of results) {
      if (result.executed) {
        updateTraitState(traitName, result.newState);
        const effectTraces = result.effects.map(
          (e) => {
            const eff = e;
            return {
              type: String(eff.type ?? "unknown"),
              args: Array.isArray(eff.args) ? eff.args : [],
              status: "executed"
            };
          }
        );
        recordTransition({
          traitName,
          from: result.previousState,
          to: result.newState,
          event: normalizedEvent,
          effects: effectTraces,
          timestamp: Date.now()
        });
      }
    }
    if (results.length > 0) {
      setTraitStates(currentManager.getAllStates());
    }
    const onEventProcessed = optionsRef.current?.onEventProcessed;
    if (onEventProcessed) {
      onEventProcessed(normalizedEvent, payload);
    }
  }, [entities, fetchedDataContext, eventBus]);
  const sendEvent = useCallback((eventKey, payload) => {
    processEvent(eventKey, payload);
  }, [processEvent]);
  const getTraitState = useCallback((traitName) => {
    return managerRef.current.getState(traitName);
  }, []);
  const canHandleEvent = useCallback((traitName, eventKey) => {
    const normalizedEvent = normalizeEventKey(eventKey);
    return managerRef.current.canHandleEvent(traitName, normalizedEvent);
  }, []);
  useEffect(() => {
    const allEvents = /* @__PURE__ */ new Set();
    for (const binding of traitBindings) {
      for (const event of binding.trait.events) {
        allEvents.add(event.key);
      }
      for (const transition of binding.trait.transitions) {
        allEvents.add(transition.event);
      }
    }
    console.log("[TraitStateMachine] Subscribing to events:", Array.from(allEvents));
    const unsubscribes = [];
    for (const eventKey of allEvents) {
      if (eventKey === "INIT" || eventKey === "LOAD" || eventKey === "$MOUNT") {
        continue;
      }
      const unsub = eventBus.on(`UI:${eventKey}`, (event) => {
        console.log("[TraitStateMachine] Received event:", `UI:${eventKey}`, event);
        processEvent(eventKey, event.payload);
      });
      unsubscribes.push(unsub);
    }
    return () => {
      for (const unsub of unsubscribes) {
        unsub();
      }
    };
  }, [traitBindings, eventBus, processEvent]);
  return {
    traitStates,
    sendEvent,
    getTraitState,
    canHandleEvent
  };
}
function useResolvedSchema(schema, pageName) {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const ir = useMemo(() => {
    if (!schema) return null;
    try {
      return schemaToIR(schema);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Schema resolution failed");
      return null;
    }
  }, [schema]);
  useEffect(() => {
    setLoading(false);
  }, [ir]);
  const result = useMemo(() => {
    if (!ir) {
      return {
        page: void 0,
        traits: [],
        entities: /* @__PURE__ */ new Map(),
        allEntities: /* @__PURE__ */ new Map(),
        allTraits: /* @__PURE__ */ new Map(),
        loading,
        error: error || (schema ? null : "No schema provided"),
        ir: null
      };
    }
    const page = getPage(ir, pageName);
    console.log("[useResolvedSchema] Resolved page:", page?.name, "| path:", page?.path, "| traits:", page?.traits.length);
    const traits = page?.traits || [];
    const entities = /* @__PURE__ */ new Map();
    if (page) {
      for (const binding of page.entityBindings) {
        entities.set(binding.entity.name, binding.entity);
      }
    }
    return {
      page,
      traits,
      entities,
      allEntities: ir.entities,
      allTraits: ir.traits,
      loading,
      error,
      ir
    };
  }, [ir, pageName, loading, error, schema]);
  return result;
}
function clearSchemaCache() {
  clearSchemaCache$1();
}
var TraitContext = createContext(null);
function TraitProvider({
  traits: traitBindings,
  children
}) {
  const traitInstances = useMemo(() => {
    const map = /* @__PURE__ */ new Map();
    for (const binding of traitBindings) {
      const trait = binding.trait;
      const initialState = trait.states.find((s) => s.isInitial);
      const stateName = initialState?.name || trait.states[0]?.name || "idle";
      const instance = {
        name: trait.name,
        currentState: stateName,
        availableEvents: trait.transitions.filter((t) => t.from === stateName).map((t) => t.event),
        dispatch: (eventKey, payload) => {
          console.log(`[TraitProvider] Dispatch to ${trait.name}: ${eventKey}`, payload);
        },
        canDispatch: (eventKey) => {
          return trait.transitions.some(
            (t) => t.from === stateName && t.event === eventKey
          );
        },
        trait
      };
      map.set(trait.name, instance);
    }
    return map;
  }, [traitBindings]);
  const contextValue = useMemo(() => {
    return {
      traits: traitInstances,
      getTrait: (name) => traitInstances.get(name),
      dispatchToTrait: (traitName, eventKey, payload) => {
        const instance = traitInstances.get(traitName);
        if (instance) {
          instance.dispatch(eventKey, payload);
        }
      },
      canDispatch: (traitName, eventKey) => {
        const instance = traitInstances.get(traitName);
        return instance?.canDispatch(eventKey) || false;
      }
    };
  }, [traitInstances]);
  return /* @__PURE__ */ jsx(TraitContext.Provider, { value: contextValue, children });
}
function useTraitContext() {
  const context = useContext(TraitContext);
  if (!context) {
    throw new Error("useTraitContext must be used within a TraitProvider");
  }
  return context;
}
function useTrait(traitName) {
  const context = useTraitContext();
  return context.getTrait(traitName);
}
var SlotsStateContext = createContext({});
var SlotsActionsContext = createContext(null);
function SlotsProvider({ children }) {
  const [slots, setSlots] = useState({});
  const setSlotPatterns = useCallback((slot, patterns, source) => {
    setSlots((prev) => ({
      ...prev,
      [slot]: { patterns, source }
    }));
  }, []);
  const clearSlot = useCallback((slot) => {
    setSlots((prev) => {
      if (!(slot in prev)) return prev;
      const next = { ...prev };
      delete next[slot];
      return next;
    });
  }, []);
  const clearAllSlots = useCallback(() => {
    setSlots({});
  }, []);
  const actionsRef = useRef({ setSlotPatterns, clearSlot, clearAllSlots });
  actionsRef.current = { setSlotPatterns, clearSlot, clearAllSlots };
  const [stableActions] = useState(() => ({
    setSlotPatterns: (...args) => actionsRef.current.setSlotPatterns(...args),
    clearSlot: (...args) => actionsRef.current.clearSlot(...args),
    clearAllSlots: () => actionsRef.current.clearAllSlots()
  }));
  return /* @__PURE__ */ jsx(SlotsActionsContext.Provider, { value: stableActions, children: /* @__PURE__ */ jsx(SlotsStateContext.Provider, { value: slots, children }) });
}
function useSlots() {
  return useContext(SlotsStateContext);
}
function useSlotContent(slotName) {
  const slots = useContext(SlotsStateContext);
  return slots[slotName] || null;
}
function useSlotsActions() {
  const actions = useContext(SlotsActionsContext);
  if (!actions) {
    throw new Error("useSlotsActions must be used within a SlotsProvider");
  }
  return actions;
}

export { EntitySchemaProvider, SlotsProvider, TraitContext, TraitProvider, clearSchemaCache, createClientEffectHandlers, useEntityDefinition, useEntitySchema, useResolvedSchema, useSlotContent, useSlots, useSlotsActions, useTrait, useTraitContext, useTraitStateMachine };
