'use strict';

var react = require('react');
var jsxRuntime = require('react/jsx-runtime');
var patterns = require('@almadar/patterns');

var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);

// renderer/pattern-resolver.ts
var componentMapping = {};
var patternRegistry = {};
function initializePatternResolver(config) {
  componentMapping = config.componentMapping;
  patternRegistry = config.patternRegistry;
}
function setComponentMapping(mapping) {
  componentMapping = mapping;
}
function setPatternRegistry(registry) {
  patternRegistry = registry;
}
function resolvePattern(config) {
  const { type, ...props } = config;
  const mapping = componentMapping[type];
  if (!mapping) {
    if (Object.keys(componentMapping).length === 0) {
      console.warn(
        "[PatternResolver] Component mapping not initialized. Call initializePatternResolver() at app startup."
      );
    }
    throw new Error(`Unknown pattern type: ${type}`);
  }
  if (mapping.deprecated) {
    console.warn(
      `[PatternResolver] Pattern "${type}" is deprecated.` + (mapping.replacedBy ? ` Use "${mapping.replacedBy}" instead.` : "")
    );
  }
  const validatedProps = validatePatternProps(type, props);
  return {
    component: mapping.component,
    importPath: mapping.importPath,
    category: mapping.category,
    validatedProps
  };
}
function validatePatternProps(patternType, props) {
  const definition = patternRegistry[patternType];
  if (!definition || !definition.propsSchema) {
    return props;
  }
  const validated = { ...props };
  const schema = definition.propsSchema;
  for (const [propName, propDef] of Object.entries(schema)) {
    if (propDef.required && !(propName in validated)) {
      console.warn(
        `[PatternResolver] Missing required prop "${propName}" for pattern "${patternType}"`
      );
    }
  }
  return validated;
}
function isKnownPattern(type) {
  return type in componentMapping;
}
function getKnownPatterns() {
  return Object.keys(componentMapping);
}
function getPatternsByCategory(category) {
  return Object.entries(componentMapping).filter(([, mapping]) => mapping.category === category).map(([type]) => type);
}
function getPatternMapping(type) {
  return componentMapping[type];
}
function getPatternDefinition(type) {
  return patternRegistry[type];
}

// renderer/client-effect-executor.ts
function executeClientEffects(effects, config) {
  if (!effects || effects.length === 0) {
    return;
  }
  for (const effect of effects) {
    try {
      executeEffect(effect, config);
    } catch (error) {
      console.error(
        `[ClientEffectExecutor] Error executing effect:`,
        effect,
        error
      );
    }
  }
  config.onComplete?.();
}
function executeEffect(effect, config) {
  const [effectType, ...args] = effect;
  switch (effectType) {
    case "render-ui": {
      const [slot, patternConfig] = args;
      executeRenderUI(slot, patternConfig, config);
      break;
    }
    case "navigate": {
      const [path, params] = args;
      executeNavigate(path, params, config);
      break;
    }
    case "notify": {
      const [message, options] = args;
      executeNotify(message, options, config);
      break;
    }
    case "emit": {
      const [event, payload] = args;
      executeEmit(event, payload, config);
      break;
    }
    default:
      console.warn(`[ClientEffectExecutor] Unknown effect type: ${effectType}`);
  }
}
function executeRenderUI(slot, patternConfig, config) {
  config.renderToSlot(slot, patternConfig);
}
function executeNavigate(path, params, config) {
  config.navigate(path, params);
}
function executeNotify(message, options, config) {
  config.notify(message, options);
}
function executeEmit(event, payload, config) {
  config.eventBus.emit(event, payload);
}
function parseClientEffect(raw) {
  if (!Array.isArray(raw) || raw.length < 1) {
    console.warn("[ClientEffectExecutor] Invalid effect format:", raw);
    return null;
  }
  const [type, ...args] = raw;
  if (typeof type !== "string") {
    console.warn("[ClientEffectExecutor] Effect type must be string:", raw);
    return null;
  }
  switch (type) {
    case "render-ui":
      return ["render-ui", args[0], args[1]];
    case "navigate":
      return ["navigate", args[0], args[1]];
    case "notify":
      return ["notify", args[0], args[1]];
    case "emit":
      return ["emit", args[0], args[1]];
    default:
      console.warn(`[ClientEffectExecutor] Unknown effect type: ${type}`);
      return null;
  }
}
function parseClientEffects(raw) {
  if (!raw || !Array.isArray(raw)) {
    return [];
  }
  return raw.map((effect) => parseClientEffect(effect)).filter((effect) => effect !== null);
}
function filterEffectsByType(effects, type) {
  return effects.filter(
    (effect) => effect[0] === type
  );
}
function getRenderUIEffects(effects) {
  return filterEffectsByType(effects, "render-ui");
}
function getNavigateEffects(effects) {
  return filterEffectsByType(effects, "navigate");
}
function getNotifyEffects(effects) {
  return filterEffectsByType(effects, "notify");
}
function getEmitEffects(effects) {
  return filterEffectsByType(effects, "emit");
}
function useClientEffects(effects, options) {
  const {
    enabled = true,
    debug = false,
    onComplete,
    ...config
  } = options;
  const executedRef = react.useRef(/* @__PURE__ */ new Set());
  const executingRef = react.useRef(false);
  const executedCountRef = react.useRef(0);
  const getEffectKey = react.useCallback((effect) => {
    return JSON.stringify(effect);
  }, []);
  const execute = react.useCallback((effectsToExecute) => {
    if (executingRef.current || effectsToExecute.length === 0) {
      return;
    }
    executingRef.current = true;
    const newEffects = effectsToExecute.filter((effect) => {
      const key = getEffectKey(effect);
      if (executedRef.current.has(key)) {
        if (debug) {
          console.log("[useClientEffects] Skipping duplicate effect:", effect);
        }
        return false;
      }
      return true;
    });
    if (newEffects.length === 0) {
      executingRef.current = false;
      return;
    }
    if (debug) {
      console.log("[useClientEffects] Executing effects:", newEffects);
    }
    newEffects.forEach((effect) => {
      executedRef.current.add(getEffectKey(effect));
    });
    executeClientEffects(newEffects, {
      ...config,
      onComplete: () => {
        executedCountRef.current = newEffects.length;
        executingRef.current = false;
        onComplete?.();
      }
    });
  }, [config, debug, getEffectKey, onComplete]);
  react.useEffect(() => {
    if (!enabled || !effects || effects.length === 0) {
      return;
    }
    execute(effects);
  }, [effects, enabled, execute]);
  const prevEffectsRef = react.useRef(void 0);
  react.useEffect(() => {
    if (effects !== prevEffectsRef.current) {
      prevEffectsRef.current = effects;
    }
  }, [effects]);
  return {
    executedCount: executedCountRef.current,
    executing: executingRef.current,
    execute
  };
}
var ClientEffectConfigContext = react.createContext(null);
var ClientEffectConfigProvider = ClientEffectConfigContext.Provider;
function useClientEffectConfig() {
  const context = react.useContext(ClientEffectConfigContext);
  if (!context) {
    throw new Error(
      "useClientEffectConfig must be used within a ClientEffectConfigProvider. Make sure your component tree is wrapped with OrbitalProvider."
    );
  }
  return context;
}
function useClientEffectConfigOptional() {
  return react.useContext(ClientEffectConfigContext);
}

// renderer/data-resolver.ts
function resolveEntityData(entityName, context) {
  if (context.fetchedData && entityName in context.fetchedData) {
    const data = context.fetchedData[entityName];
    return {
      data: Array.isArray(data) ? data : [],
      loading: false
    };
  }
  if (context.entityStore) {
    try {
      const data = context.entityStore.getRecords(entityName);
      return {
        data: Array.isArray(data) ? data : [],
        loading: false
      };
    } catch (error) {
      console.warn(
        `[DataResolver] Error getting records from entity store for "${entityName}":`,
        error
      );
    }
  }
  const hasAnySources = context.fetchedData || context.entityStore;
  return {
    data: [],
    loading: !hasAnySources
    // Only loading if no sources configured
  };
}
function resolveEntityDataWithQuery(entityName, queryRef, context) {
  const resolution = resolveEntityData(entityName, context);
  if (!queryRef || !context.querySingleton) {
    return resolution;
  }
  try {
    const filters = context.querySingleton.getFilters(queryRef);
    const filteredData = applyFilters(resolution.data, filters);
    return {
      ...resolution,
      data: filteredData
    };
  } catch (error) {
    console.warn(
      `[DataResolver] Error applying query filters for "${queryRef}":`,
      error
    );
    return resolution;
  }
}
function applyFilters(data, filters) {
  if (!filters || Object.keys(filters).length === 0) {
    return data;
  }
  return data.filter((item) => {
    if (typeof item !== "object" || item === null) {
      return false;
    }
    const record = item;
    return Object.entries(filters).every(([key, value]) => {
      if (value === void 0 || value === null) {
        return true;
      }
      const recordValue = record[key];
      if (Array.isArray(value)) {
        return value.includes(recordValue);
      }
      if (typeof value === "string" && typeof recordValue === "string") {
        if (value.startsWith("*") && value.endsWith("*")) {
          const pattern = value.slice(1, -1);
          return recordValue.toLowerCase().includes(pattern.toLowerCase());
        }
      }
      return recordValue === value;
    });
  });
}
function resolveEntityById(entityName, id, context) {
  const { data } = resolveEntityData(entityName, context);
  return data.find((item) => {
    if (typeof item !== "object" || item === null) {
      return false;
    }
    const record = item;
    return record.id === id || record._id === id;
  }) ?? null;
}
function resolveEntityCount(entityName, context, filters) {
  const { data } = resolveEntityData(entityName, context);
  if (filters) {
    return applyFilters(data, filters).length;
  }
  return data.length;
}
function hasEntities(entityName, context) {
  const { data } = resolveEntityData(entityName, context);
  return data.length > 0;
}
function createFetchedDataContext(data) {
  return { fetchedData: data };
}
function mergeDataContexts(...contexts) {
  const merged = {};
  for (const context of contexts) {
    if (context.fetchedData) {
      merged.fetchedData = {
        ...merged.fetchedData,
        ...context.fetchedData
      };
    }
    if (context.entityStore) {
      merged.entityStore = context.entityStore;
    }
    if (context.querySingleton) {
      merged.querySingleton = context.querySingleton;
    }
  }
  return merged;
}

// renderer/slot-definitions.ts
var SLOT_DEFINITIONS = {
  // -------------------------------------------------------------------------
  // Inline Slots - Render in place within the component tree
  // -------------------------------------------------------------------------
  main: {
    name: "main",
    type: "inline"
  },
  sidebar: {
    name: "sidebar",
    type: "inline"
  },
  // -------------------------------------------------------------------------
  // Portal Slots - Render to document.body via React Portal
  // -------------------------------------------------------------------------
  modal: {
    name: "modal",
    type: "portal",
    portalTarget: "body",
    zIndex: 1e3
  },
  drawer: {
    name: "drawer",
    type: "portal",
    portalTarget: "body",
    zIndex: 900
  },
  overlay: {
    name: "overlay",
    type: "portal",
    portalTarget: "body",
    zIndex: 1100
  },
  center: {
    name: "center",
    type: "portal",
    portalTarget: "body",
    zIndex: 1e3
  },
  toast: {
    name: "toast",
    type: "portal",
    portalTarget: "body",
    zIndex: 1200
  },
  // -------------------------------------------------------------------------
  // Game HUD Slots - Portal for game overlay UI
  // -------------------------------------------------------------------------
  "hud-top": {
    name: "hud-top",
    type: "portal",
    portalTarget: "body",
    zIndex: 500
  },
  "hud-bottom": {
    name: "hud-bottom",
    type: "portal",
    portalTarget: "body",
    zIndex: 500
  },
  floating: {
    name: "floating",
    type: "portal",
    portalTarget: "body",
    zIndex: 800
  }
};
function getSlotDefinition(slot) {
  return SLOT_DEFINITIONS[slot];
}
function isPortalSlot(slot) {
  return SLOT_DEFINITIONS[slot]?.type === "portal";
}
function isInlineSlot(slot) {
  return SLOT_DEFINITIONS[slot]?.type === "inline";
}
function getSlotsByType(type) {
  return Object.entries(SLOT_DEFINITIONS).filter(([, def]) => def.type === type).map(([name]) => name);
}
function getInlineSlots() {
  return getSlotsByType("inline");
}
function getPortalSlots() {
  return getSlotsByType("portal");
}
var ALL_SLOTS = Object.keys(SLOT_DEFINITIONS);
var effectIdCounter = 0;
function generateEffectId() {
  return `offline-effect-${++effectIdCounter}-${Date.now()}`;
}
var OfflineExecutor = class {
  constructor(config) {
    __publicField(this, "config");
    __publicField(this, "state");
    __publicField(this, "storage");
    /**
     * Handle going online
     */
    __publicField(this, "handleOnline", () => {
      this.state.isOffline = false;
    });
    /**
     * Handle going offline
     */
    __publicField(this, "handleOffline", () => {
      this.state.isOffline = true;
    });
    this.config = {
      enableSyncQueue: true,
      maxQueueSize: 100,
      ...config
    };
    this.state = {
      isOffline: !this.checkOnline(),
      syncQueue: [],
      localEffectsProcessed: 0,
      effectsSynced: 0
    };
    this.storage = typeof localStorage !== "undefined" ? localStorage : null;
    this.loadSyncQueue();
    if (typeof window !== "undefined") {
      window.addEventListener("online", this.handleOnline);
      window.addEventListener("offline", this.handleOffline);
    }
  }
  /**
   * Check if we're online (browser API)
   */
  checkOnline() {
    return typeof navigator !== "undefined" ? navigator.onLine : true;
  }
  /**
   * Load sync queue from localStorage
   */
  loadSyncQueue() {
    if (!this.storage) return;
    try {
      const stored = this.storage.getItem("orbital-offline-queue");
      if (stored) {
        this.state.syncQueue = JSON.parse(stored);
      }
    } catch (error) {
      console.warn("[OfflineExecutor] Failed to load sync queue:", error);
    }
  }
  /**
   * Save sync queue to localStorage
   */
  saveSyncQueue() {
    if (!this.storage) return;
    try {
      this.storage.setItem("orbital-offline-queue", JSON.stringify(this.state.syncQueue));
    } catch (error) {
      console.warn("[OfflineExecutor] Failed to save sync queue:", error);
    }
  }
  /**
   * Add an effect to the sync queue
   */
  queueForSync(type, payload) {
    if (!this.config.enableSyncQueue) return;
    const effect = {
      id: generateEffectId(),
      timestamp: Date.now(),
      type,
      payload,
      retries: 0,
      maxRetries: 3
    };
    this.state.syncQueue.push(effect);
    if (this.state.syncQueue.length > (this.config.maxQueueSize ?? 100)) {
      this.state.syncQueue.shift();
    }
    this.saveSyncQueue();
    this.config.onEffectQueued?.(effect);
    this.config.onQueueChange?.(this.state.syncQueue);
  }
  /**
   * Execute client effects immediately.
   */
  executeClientEffects(effects) {
    if (effects.length === 0) return;
    executeClientEffects(effects, this.config);
    this.state.localEffectsProcessed += effects.length;
  }
  /**
   * Process an event in offline mode.
   *
   * Returns a simulated EventResponse with mock data.
   * Client effects are executed immediately.
   * Server effects are queued for sync.
   */
  processEventOffline(event, payload, effects) {
    const clientEffects = [];
    const fetchedData = {};
    if (effects) {
      for (const effect of effects) {
        if (!Array.isArray(effect) || effect.length < 1) continue;
        const [type, ...args] = effect;
        switch (type) {
          // Client effects - execute immediately
          case "render-ui":
          case "navigate":
          case "notify":
          case "emit":
            clientEffects.push(effect);
            break;
          // Fetch effect - use mock data
          case "fetch": {
            const [entityName, _query] = args;
            if (typeof entityName === "string" && this.config.mockDataProvider) {
              fetchedData[entityName] = this.config.mockDataProvider(entityName);
            }
            break;
          }
          // Server effects - queue for sync
          case "persist":
          case "call-service":
          case "spawn":
          case "despawn":
            this.queueForSync(type, { args, event, payload });
            break;
          default:
            console.warn(`[OfflineExecutor] Unknown effect type: ${type}`);
        }
      }
    }
    if (clientEffects.length > 0) {
      this.executeClientEffects(clientEffects);
    }
    return {
      success: true,
      data: Object.keys(fetchedData).length > 0 ? fetchedData : void 0,
      clientEffects: clientEffects.length > 0 ? clientEffects : void 0
    };
  }
  /**
   * Sync pending effects to server.
   *
   * @param serverUrl - Base URL for the orbital server
   * @param authToken - Optional auth token for requests
   * @returns Number of successfully synced effects
   */
  async syncPendingEffects(serverUrl, authToken) {
    if (this.state.syncQueue.length === 0) {
      return 0;
    }
    this.state.lastSyncAttempt = Date.now();
    let syncedCount = 0;
    const failedEffects = [];
    const headers = {
      "Content-Type": "application/json"
    };
    if (authToken) {
      headers["Authorization"] = `Bearer ${authToken}`;
    }
    for (const effect of this.state.syncQueue) {
      try {
        const response = await fetch(`${serverUrl}/sync-effect`, {
          method: "POST",
          headers,
          body: JSON.stringify({
            type: effect.type,
            payload: effect.payload,
            offlineId: effect.id,
            offlineTimestamp: effect.timestamp
          })
        });
        if (response.ok) {
          syncedCount++;
        } else {
          effect.retries++;
          if (effect.retries < effect.maxRetries) {
            failedEffects.push(effect);
          }
        }
      } catch (error) {
        effect.retries++;
        if (effect.retries < effect.maxRetries) {
          failedEffects.push(effect);
        }
      }
    }
    this.state.syncQueue = failedEffects;
    this.state.effectsSynced += syncedCount;
    if (syncedCount > 0) {
      this.state.lastSuccessfulSync = Date.now();
    }
    this.saveSyncQueue();
    this.config.onQueueChange?.(this.state.syncQueue);
    return syncedCount;
  }
  /**
   * Get current executor state
   */
  getState() {
    return { ...this.state };
  }
  /**
   * Get number of pending effects
   */
  getPendingCount() {
    return this.state.syncQueue.length;
  }
  /**
   * Clear the sync queue
   */
  clearQueue() {
    this.state.syncQueue = [];
    this.saveSyncQueue();
    this.config.onQueueChange?.(this.state.syncQueue);
  }
  /**
   * Dispose the executor and clean up listeners
   */
  dispose() {
    if (typeof window !== "undefined") {
      window.removeEventListener("online", this.handleOnline);
      window.removeEventListener("offline", this.handleOffline);
    }
  }
};
function createOfflineExecutor(config) {
  return new OfflineExecutor(config);
}
function useOfflineExecutor(options) {
  const executorRef = react.useRef(null);
  const [state, setState] = react.useState({
    isOffline: false,
    syncQueue: [],
    localEffectsProcessed: 0,
    effectsSynced: 0
  });
  react.useEffect(() => {
    const executor = new OfflineExecutor({
      ...options,
      onQueueChange: (queue) => {
        setState(executor.getState());
        options.onQueueChange?.(queue);
      }
    });
    executorRef.current = executor;
    setState(executor.getState());
    return () => {
      executor.dispose();
      executorRef.current = null;
    };
  }, []);
  react.useEffect(() => {
    if (!options.autoSync || !options.serverUrl) return;
    const handleOnline = async () => {
      if (executorRef.current) {
        await executorRef.current.syncPendingEffects(
          options.serverUrl,
          options.authToken
        );
        setState(executorRef.current.getState());
      }
    };
    window.addEventListener("online", handleOnline);
    return () => window.removeEventListener("online", handleOnline);
  }, [options.autoSync, options.serverUrl, options.authToken]);
  const executeEffects = react.useCallback((effects) => {
    executorRef.current?.executeClientEffects(effects);
    if (executorRef.current) {
      setState(executorRef.current.getState());
    }
  }, []);
  const processEventOffline = react.useCallback(
    (event, payload, effects) => {
      const result = executorRef.current?.processEventOffline(event, payload, effects);
      if (executorRef.current) {
        setState(executorRef.current.getState());
      }
      return result ?? { success: false, error: "Executor not initialized" };
    },
    []
  );
  const sync = react.useCallback(async () => {
    if (!executorRef.current || !options.serverUrl) return 0;
    const count = await executorRef.current.syncPendingEffects(
      options.serverUrl,
      options.authToken
    );
    setState(executorRef.current.getState());
    return count;
  }, [options.serverUrl, options.authToken]);
  const clearQueue = react.useCallback(() => {
    executorRef.current?.clearQueue();
    if (executorRef.current) {
      setState(executorRef.current.getState());
    }
  }, []);
  return {
    state,
    isOffline: state.isOffline,
    pendingCount: state.syncQueue.length,
    executeClientEffects: executeEffects,
    processEventOffline,
    sync,
    clearQueue
  };
}
function matchPath(pattern, path) {
  const normalizeSegment = (p) => {
    let normalized = p.trim();
    if (!normalized.startsWith("/")) normalized = "/" + normalized;
    if (normalized.length > 1 && normalized.endsWith("/")) {
      normalized = normalized.slice(0, -1);
    }
    return normalized;
  };
  const normalizedPattern = normalizeSegment(pattern);
  const normalizedPath = normalizeSegment(path);
  const patternParts = normalizedPattern.split("/").filter(Boolean);
  const pathParts = normalizedPath.split("/").filter(Boolean);
  if (patternParts.length !== pathParts.length) {
    return null;
  }
  const params = {};
  for (let i = 0; i < patternParts.length; i++) {
    const patternPart = patternParts[i];
    const pathPart = pathParts[i];
    if (patternPart.startsWith(":")) {
      const paramName = patternPart.slice(1);
      params[paramName] = decodeURIComponent(pathPart);
    } else if (patternPart !== pathPart) {
      return null;
    }
  }
  return params;
}
function extractRouteParams(pattern, path) {
  return matchPath(pattern, path) || {};
}
function pathMatches(pattern, path) {
  return matchPath(pattern, path) !== null;
}
function isInlineOrbital(orbital) {
  return "name" in orbital && typeof orbital.name === "string";
}
function isInlinePage(page) {
  return typeof page === "object" && page !== null && "name" in page && typeof page.name === "string";
}
function findPageByPath(schema, path) {
  if (!schema.orbitals) return null;
  for (const orbital of schema.orbitals) {
    if (!isInlineOrbital(orbital)) continue;
    if (!orbital.pages) continue;
    for (const pageRef of orbital.pages) {
      if (!isInlinePage(pageRef)) continue;
      const page = pageRef;
      const pagePath = page.path;
      if (!pagePath) continue;
      const params = matchPath(pagePath, path);
      if (params !== null) {
        return { page, params, orbitalName: orbital.name };
      }
    }
  }
  return null;
}
function findPageByName(schema, pageName) {
  if (!schema.orbitals) return null;
  for (const orbital of schema.orbitals) {
    if (!isInlineOrbital(orbital)) continue;
    if (!orbital.pages) continue;
    for (const pageRef of orbital.pages) {
      if (!isInlinePage(pageRef)) continue;
      const page = pageRef;
      if (page.name === pageName) {
        return { page, orbitalName: orbital.name };
      }
    }
  }
  return null;
}
function getDefaultPage(schema) {
  if (!schema.orbitals) return null;
  for (const orbital of schema.orbitals) {
    if (!isInlineOrbital(orbital)) continue;
    if (!orbital.pages) continue;
    for (const pageRef of orbital.pages) {
      if (isInlinePage(pageRef)) {
        return { page: pageRef, orbitalName: orbital.name };
      }
    }
  }
  return null;
}
function getAllPages(schema) {
  const pages = [];
  if (!schema.orbitals) return pages;
  for (const orbital of schema.orbitals) {
    if (!isInlineOrbital(orbital)) continue;
    if (!orbital.pages) continue;
    for (const pageRef of orbital.pages) {
      if (isInlinePage(pageRef)) {
        pages.push({ page: pageRef, orbitalName: orbital.name });
      }
    }
  }
  return pages;
}
var NavigationContext = react.createContext(null);
function NavigationProvider({
  schema,
  initialPage,
  updateUrl = true,
  onNavigate,
  children
}) {
  const initialState = react.useMemo(() => {
    let page = null;
    let path = "/";
    if (initialPage) {
      const found = findPageByName(schema, initialPage);
      if (found) {
        page = found.page;
        path = page.path || "/";
      }
    }
    if (!page) {
      const defaultPage = getDefaultPage(schema);
      if (defaultPage) {
        page = defaultPage.page;
        path = page.path || "/";
      }
    }
    return {
      activePage: page?.name || "",
      currentPath: path,
      initPayload: {},
      navigationId: 0
    };
  }, [schema, initialPage]);
  const [state, setState] = react.useState(initialState);
  const navigateTo = react.useCallback((path, payload) => {
    const result = findPageByPath(schema, path);
    if (!result) {
      console.error(`[Navigation] No page found for path: ${path}`);
      return;
    }
    const { page, params } = result;
    const finalPayload = { ...params, ...payload };
    console.log("[Navigation] Navigating to:", {
      path,
      page: page.name,
      params,
      payload,
      finalPayload
    });
    setState((prev) => ({
      activePage: page.name,
      currentPath: path,
      initPayload: finalPayload,
      navigationId: prev.navigationId + 1
    }));
    if (updateUrl && typeof window !== "undefined") {
      try {
        window.history.pushState(finalPayload, "", path);
      } catch (e) {
        console.warn("[Navigation] Could not update URL:", e);
      }
    }
    if (onNavigate) {
      onNavigate(page.name, path, finalPayload);
    }
  }, [schema, updateUrl, onNavigate]);
  const navigateToPage = react.useCallback((pageName, payload) => {
    const result = findPageByName(schema, pageName);
    if (!result) {
      console.error(`[Navigation] No page found with name: ${pageName}`);
      return;
    }
    const { page } = result;
    const path = page.path || `/${pageName.toLowerCase()}`;
    console.log("[Navigation] Navigating to page:", {
      pageName,
      path,
      payload
    });
    setState((prev) => ({
      activePage: page.name,
      currentPath: path,
      initPayload: payload || {},
      navigationId: prev.navigationId + 1
    }));
    if (updateUrl && typeof window !== "undefined") {
      try {
        window.history.pushState(payload || {}, "", path);
      } catch (e) {
        console.warn("[Navigation] Could not update URL:", e);
      }
    }
    if (onNavigate) {
      onNavigate(page.name, path, payload || {});
    }
  }, [schema, updateUrl, onNavigate]);
  const contextValue = react.useMemo(() => ({
    state,
    navigateTo,
    navigateToPage,
    schema,
    isReady: !!state.activePage
  }), [state, navigateTo, navigateToPage, schema]);
  return /* @__PURE__ */ jsxRuntime.jsx(NavigationContext.Provider, { value: contextValue, children });
}
function useNavigation() {
  return react.useContext(NavigationContext);
}
function useNavigateTo() {
  const context = react.useContext(NavigationContext);
  const noOp = react.useCallback((path, _payload) => {
    console.warn(`[Navigation] navigateTo called outside NavigationProvider. Path: ${path}`);
  }, []);
  return context?.navigateTo || noOp;
}
function useNavigationState() {
  const context = react.useContext(NavigationContext);
  return context?.state || null;
}
function useInitPayload() {
  const context = react.useContext(NavigationContext);
  return context?.state.initPayload || {};
}
function useActivePage() {
  const context = react.useContext(NavigationContext);
  return context?.state.activePage || null;
}
function useNavigationId() {
  const context = react.useContext(NavigationContext);
  return context?.state.navigationId || 0;
}
function initializePatterns() {
  console.log("[PatternResolver] initializePatterns called");
  console.log("[PatternResolver] componentMappingJson:", patterns.componentMapping);
  console.log("[PatternResolver] registryJson keys:", Object.keys(patterns.patternsRegistry));
  const componentMappingData = patterns.componentMapping;
  const componentMapping2 = componentMappingData.mappings || {};
  console.log("[PatternResolver] Extracted mappings count:", Object.keys(componentMapping2).length);
  console.log("[PatternResolver] Sample mappings:", Object.keys(componentMapping2).slice(0, 5));
  const registryData = patterns.patternsRegistry;
  const patternRegistry2 = registryData.patterns || {};
  console.log("[PatternResolver] Extracted patterns count:", Object.keys(patternRegistry2).length);
  initializePatternResolver({
    componentMapping: componentMapping2,
    patternRegistry: patternRegistry2
  });
  console.log(`[PatternResolver] Initialized with ${Object.keys(componentMapping2).length} component mappings and ${Object.keys(patternRegistry2).length} pattern definitions`);
  return Object.keys(componentMapping2).length;
}

exports.ALL_SLOTS = ALL_SLOTS;
exports.ClientEffectConfigContext = ClientEffectConfigContext;
exports.ClientEffectConfigProvider = ClientEffectConfigProvider;
exports.NavigationProvider = NavigationProvider;
exports.OfflineExecutor = OfflineExecutor;
exports.SLOT_DEFINITIONS = SLOT_DEFINITIONS;
exports.createFetchedDataContext = createFetchedDataContext;
exports.createOfflineExecutor = createOfflineExecutor;
exports.executeClientEffects = executeClientEffects;
exports.extractRouteParams = extractRouteParams;
exports.filterEffectsByType = filterEffectsByType;
exports.findPageByName = findPageByName;
exports.findPageByPath = findPageByPath;
exports.getAllPages = getAllPages;
exports.getDefaultPage = getDefaultPage;
exports.getEmitEffects = getEmitEffects;
exports.getInlineSlots = getInlineSlots;
exports.getKnownPatterns = getKnownPatterns;
exports.getNavigateEffects = getNavigateEffects;
exports.getNotifyEffects = getNotifyEffects;
exports.getPatternDefinition = getPatternDefinition;
exports.getPatternMapping = getPatternMapping;
exports.getPatternsByCategory = getPatternsByCategory;
exports.getPortalSlots = getPortalSlots;
exports.getRenderUIEffects = getRenderUIEffects;
exports.getSlotDefinition = getSlotDefinition;
exports.getSlotsByType = getSlotsByType;
exports.hasEntities = hasEntities;
exports.initializePatternResolver = initializePatternResolver;
exports.initializePatterns = initializePatterns;
exports.isInlineSlot = isInlineSlot;
exports.isKnownPattern = isKnownPattern;
exports.isPortalSlot = isPortalSlot;
exports.matchPath = matchPath;
exports.mergeDataContexts = mergeDataContexts;
exports.parseClientEffect = parseClientEffect;
exports.parseClientEffects = parseClientEffects;
exports.pathMatches = pathMatches;
exports.resolveEntityById = resolveEntityById;
exports.resolveEntityCount = resolveEntityCount;
exports.resolveEntityData = resolveEntityData;
exports.resolveEntityDataWithQuery = resolveEntityDataWithQuery;
exports.resolvePattern = resolvePattern;
exports.setComponentMapping = setComponentMapping;
exports.setPatternRegistry = setPatternRegistry;
exports.useActivePage = useActivePage;
exports.useClientEffectConfig = useClientEffectConfig;
exports.useClientEffectConfigOptional = useClientEffectConfigOptional;
exports.useClientEffects = useClientEffects;
exports.useInitPayload = useInitPayload;
exports.useNavigateTo = useNavigateTo;
exports.useNavigation = useNavigation;
exports.useNavigationId = useNavigationId;
exports.useNavigationState = useNavigationState;
exports.useOfflineExecutor = useOfflineExecutor;
