import { createContext, useCallback, useState, useEffect, useMemo, useContext, useRef, useSyncExternalStore } from 'react';
import { EventBusContext, useTraitScope } from '@almadar/ui/providers';
import { useQuery, useQueryClient, useMutation } from '@tanstack/react-query';

function useOrbitalHistory(options) {
  const { appId, authToken, userId, onHistoryChange, onRevertSuccess } = options;
  const getHeaders = useCallback(() => {
    const headers = {
      "Content-Type": "application/json"
    };
    if (authToken) {
      headers["Authorization"] = `Bearer ${authToken}`;
    }
    if (userId) {
      headers["x-user-id"] = userId;
    }
    return headers;
  }, [authToken, userId]);
  const [timeline, setTimeline] = useState([]);
  const [currentVersion, setCurrentVersion] = useState(1);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const refresh = useCallback(async () => {
    if (!appId) return;
    setIsLoading(true);
    setError(null);
    try {
      const headers = getHeaders();
      const [changesetsRes, snapshotsRes] = await Promise.all([
        fetch(`/api/graphs/${appId}/history/changesets`, { headers }),
        fetch(`/api/graphs/${appId}/history/snapshots`, { headers })
      ]);
      if (!changesetsRes.ok) {
        throw new Error(`Failed to fetch changesets: ${changesetsRes.status}`);
      }
      if (!snapshotsRes.ok) {
        throw new Error(`Failed to fetch snapshots: ${snapshotsRes.status}`);
      }
      const changesetsData = await changesetsRes.json();
      const snapshotsData = await snapshotsRes.json();
      const changesetItems = (changesetsData.changesets || []).map((cs) => ({
        id: cs.id,
        type: "changeset",
        version: cs.version,
        timestamp: cs.timestamp,
        description: `Version ${cs.version}`,
        source: cs.source,
        summary: cs.summary
      }));
      const snapshotItems = (snapshotsData.snapshots || []).map((snap) => ({
        id: snap.id,
        type: "snapshot",
        version: snap.version,
        timestamp: snap.timestamp,
        description: snap.reason || `Snapshot v${snap.version}`,
        reason: snap.reason
      }));
      const mergedTimeline = [...changesetItems, ...snapshotItems].sort(
        (a, b) => b.timestamp - a.timestamp
      );
      setTimeline(mergedTimeline);
      if (mergedTimeline.length > 0) {
        setCurrentVersion(mergedTimeline[0].version);
      }
    } catch (err) {
      console.error("[useOrbitalHistory] Failed to load history:", err);
      setError(err instanceof Error ? err.message : "Failed to load history");
    } finally {
      setIsLoading(false);
    }
  }, [appId, getHeaders]);
  const revertToSnapshot = useCallback(async (snapshotId) => {
    if (!appId) {
      return { success: false, error: "No app ID provided" };
    }
    try {
      const response = await fetch(`/api/graphs/${appId}/history/revert/${snapshotId}`, {
        method: "POST",
        headers: getHeaders()
      });
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.error || `Failed to revert: ${response.status}`);
      }
      const data = await response.json();
      if (data.success && data.schema) {
        await refresh();
        onRevertSuccess?.(data.schema);
        return {
          success: true,
          restoredSchema: data.schema
        };
      }
      return {
        success: false,
        error: data.error || "Unknown error during revert"
      };
    } catch (err) {
      console.error("[useOrbitalHistory] Failed to revert:", err);
      return {
        success: false,
        error: err instanceof Error ? err.message : "Failed to revert"
      };
    }
  }, [appId, getHeaders, refresh, onRevertSuccess]);
  useEffect(() => {
    if (appId && authToken && userId) {
      refresh();
    }
  }, [appId, authToken, userId]);
  useEffect(() => {
    onHistoryChange?.(timeline);
  }, [timeline]);
  return {
    timeline,
    currentVersion,
    isLoading,
    error,
    revertToSnapshot,
    refresh
  };
}
function useFileSystem() {
  const [status, setStatus] = useState("idle");
  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [files, setFiles] = useState([]);
  const [selectedFile, setSelectedFile] = useState(null);
  const [selectedPath, setSelectedPath] = useState(null);
  const [previewUrl, setPreviewUrl] = useState(null);
  const [fileContents, setFileContents] = useState(/* @__PURE__ */ new Map());
  const boot = useCallback(async () => {
    setStatus("booting");
    setError(null);
    setIsLoading(true);
    try {
      console.log("[useFileSystem] Booting WebContainer...");
      await new Promise((resolve) => setTimeout(resolve, 100));
      setStatus("ready");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to boot");
      setStatus("error");
    } finally {
      setIsLoading(false);
    }
  }, []);
  const mountFiles = useCallback(async (filesToMount) => {
    setIsLoading(true);
    try {
      let filesArray;
      if (Array.isArray(filesToMount)) {
        filesArray = filesToMount;
      } else {
        filesArray = [];
        const flattenTree = (obj, basePath = "") => {
          for (const [key, value] of Object.entries(obj)) {
            const path = basePath ? `${basePath}/${key}` : key;
            if (value && typeof value === "object" && "file" in value) {
              const fileObj = value;
              filesArray.push({ path, content: fileObj.file.contents || "" });
            } else if (value && typeof value === "object" && "directory" in value) {
              const dirObj = value;
              flattenTree(dirObj.directory, path);
            }
          }
        };
        flattenTree(filesToMount);
      }
      const newContents = /* @__PURE__ */ new Map();
      for (const file of filesArray) {
        newContents.set(file.path, file.content);
      }
      setFileContents(newContents);
      const newTree = [];
      for (const file of filesArray) {
        const parts = file.path.split("/").filter(Boolean);
        let current = newTree;
        for (let i = 0; i < parts.length; i++) {
          const part = parts[i];
          const isFile = i === parts.length - 1;
          const currentPath = "/" + parts.slice(0, i + 1).join("/");
          let node = current.find((n) => n.name === part);
          if (!node) {
            node = {
              path: currentPath,
              name: part,
              type: isFile ? "file" : "directory",
              children: isFile ? void 0 : []
            };
            current.push(node);
          }
          if (!isFile && node && node.children) {
            current = node.children;
          }
        }
      }
      setFiles(newTree);
      setStatus("running");
    } catch (err) {
      console.error("[useFileSystem] Failed to mount files:", err);
    } finally {
      setIsLoading(false);
    }
  }, []);
  const readFile = useCallback(async (path) => {
    return fileContents.get(path) || "";
  }, [fileContents]);
  const writeFile = useCallback(async (path, content) => {
    setFileContents((prev) => {
      const next = new Map(prev);
      next.set(path, content);
      return next;
    });
  }, []);
  const selectFile = useCallback(async (path) => {
    const content = fileContents.get(path) || "";
    const ext = path.split(".").pop()?.toLowerCase() || "";
    const languageMap = {
      ts: "typescript",
      tsx: "typescript",
      js: "javascript",
      jsx: "javascript",
      json: "json",
      md: "markdown",
      css: "css",
      html: "html",
      orb: "json"
    };
    setSelectedPath(path);
    setSelectedFile({
      path,
      content,
      language: languageMap[ext] || "plaintext",
      isDirty: false
    });
  }, [fileContents]);
  const updateContent = useCallback((pathOrContent, contentArg) => {
    const path = contentArg !== void 0 ? pathOrContent : selectedPath;
    const content = contentArg !== void 0 ? contentArg : pathOrContent;
    if (!path) {
      console.warn("[useFileSystem] updateContent called without path and no file selected");
      return;
    }
    setFileContents((prev) => {
      const next = new Map(prev);
      next.set(path, content);
      return next;
    });
    if (selectedPath === path) {
      setSelectedFile((prev) => prev ? { ...prev, content, isDirty: true } : null);
    }
  }, [selectedPath]);
  const updateSelectedContent = useCallback((content) => {
    setSelectedFile((prev) => prev ? { ...prev, content, isDirty: true } : null);
  }, []);
  const refreshTree = useCallback(async () => {
    console.log("[useFileSystem] Refreshing tree");
  }, []);
  const runCommand = useCallback(async (command) => {
    console.log("[useFileSystem] Running command:", command);
    return { exitCode: 0, output: "" };
  }, []);
  const startDevServer = useCallback(async () => {
    console.log("[useFileSystem] Starting dev server");
    setPreviewUrl("http://localhost:5173");
  }, []);
  return {
    status,
    error,
    isLoading,
    files,
    selectedFile,
    selectedPath,
    previewUrl,
    boot,
    mountFiles,
    readFile,
    writeFile,
    selectFile,
    updateContent,
    updateSelectedContent,
    refreshTree,
    runCommand,
    startDevServer
  };
}
var defaultManifest = {
  languages: {
    typescript: { extensions: [".ts", ".tsx"], icon: "ts", color: "#3178c6" },
    javascript: { extensions: [".js", ".jsx"], icon: "js", color: "#f7df1e" },
    json: { extensions: [".json", ".orb"], icon: "json", color: "#000000" },
    css: { extensions: [".css"], icon: "css", color: "#264de4" },
    html: { extensions: [".html"], icon: "html", color: "#e34c26" },
    markdown: { extensions: [".md", ".mdx"], icon: "md", color: "#083fa1" }
  },
  extensions: []
};
function useExtensions(options) {
  const { appId, loadOnMount = true } = options;
  const [extensions, setExtensions] = useState([]);
  const [manifest] = useState(defaultManifest);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const loadExtension = useCallback(async (extensionId) => {
    console.log("[useExtensions] Loading extension:", extensionId);
  }, []);
  const loadExtensions = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const defaultExtensions = [
        { id: "typescript", name: "TypeScript", language: "typescript", loaded: true },
        { id: "javascript", name: "JavaScript", language: "javascript", loaded: true },
        { id: "json", name: "JSON", language: "json", loaded: true },
        { id: "css", name: "CSS", language: "css", loaded: true },
        { id: "html", name: "HTML", language: "html", loaded: true },
        { id: "markdown", name: "Markdown", language: "markdown", loaded: true }
      ];
      setExtensions(defaultExtensions);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load extensions");
    } finally {
      setIsLoading(false);
    }
  }, []);
  const getExtensionForFile = useCallback((filename) => {
    const ext = filename.split(".").pop()?.toLowerCase();
    if (!ext) return null;
    const languageMap = {
      ts: "typescript",
      tsx: "typescript",
      js: "javascript",
      jsx: "javascript",
      json: "json",
      md: "markdown",
      css: "css",
      html: "html",
      orb: "json"
    };
    const language = languageMap[ext];
    if (!language) return null;
    return extensions.find((e) => e.language === language) || null;
  }, [extensions]);
  useEffect(() => {
    if (!appId || !loadOnMount) return;
    const loadExtensions2 = async () => {
      setIsLoading(true);
      setError(null);
      try {
        const defaultExtensions = [
          { id: "typescript", name: "TypeScript", language: "typescript", loaded: true },
          { id: "javascript", name: "JavaScript", language: "javascript", loaded: true },
          { id: "json", name: "JSON", language: "json", loaded: true },
          { id: "css", name: "CSS", language: "css", loaded: true },
          { id: "html", name: "HTML", language: "html", loaded: true },
          { id: "markdown", name: "Markdown", language: "markdown", loaded: true }
        ];
        setExtensions(defaultExtensions);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Failed to load extensions");
      } finally {
        setIsLoading(false);
      }
    };
    loadExtensions2();
  }, [appId, loadOnMount]);
  return {
    extensions,
    manifest,
    isLoading,
    error,
    loadExtension,
    loadExtensions,
    getExtensionForFile
  };
}
function useFileEditor(options) {
  const { extensions, fileSystem, onSchemaUpdate } = options;
  const [openFiles, setOpenFiles] = useState([]);
  const [activeFilePath, setActiveFilePath] = useState(null);
  const [isSaving, setIsSaving] = useState(false);
  const activeFile = openFiles.find((f) => f.path === activeFilePath) || null;
  const openFile = useCallback(async (path) => {
    const existing = openFiles.find((f) => f.path === path);
    if (existing) {
      setActiveFilePath(path);
      return;
    }
    try {
      const content = await fileSystem.readFile(path);
      const ext = extensions.getExtensionForFile(path);
      const newFile = {
        path,
        content,
        isDirty: false,
        language: ext?.language
      };
      setOpenFiles((prev) => [...prev, newFile]);
      setActiveFilePath(path);
    } catch (err) {
      console.error("[useFileEditor] Failed to open file:", err);
    }
  }, [openFiles, fileSystem, extensions]);
  const closeFile = useCallback((path) => {
    setOpenFiles((prev) => prev.filter((f) => f.path !== path));
    if (activeFilePath === path) {
      const remaining = openFiles.filter((f) => f.path !== path);
      setActiveFilePath(remaining.length > 0 ? remaining[0].path : null);
    }
  }, [activeFilePath, openFiles]);
  const setActiveFile = useCallback((path) => {
    setActiveFilePath(path);
  }, []);
  const updateFileContent = useCallback((path, content) => {
    setOpenFiles(
      (prev) => prev.map(
        (f) => f.path === path ? { ...f, content, isDirty: true } : f
      )
    );
  }, []);
  const handleFileEdit = useCallback(async (path, content) => {
    try {
      await fileSystem.writeFile(path, content);
      let action = "saved";
      if (path.endsWith(".orb") || path.endsWith("schema.json")) {
        try {
          const schema = JSON.parse(content);
          await onSchemaUpdate?.(schema);
          action = "updated_schema";
        } catch {
        }
      } else if (path.includes("/extensions/")) {
        action = path.endsWith(".new") ? "converted_extension" : "saved_extension";
      }
      return { success: true, action };
    } catch (err) {
      return {
        success: false,
        error: err instanceof Error ? err.message : "Failed to save file"
      };
    }
  }, [fileSystem, onSchemaUpdate]);
  const saveFile = useCallback(async (path) => {
    const file = openFiles.find((f) => f.path === path);
    if (!file) return;
    setIsSaving(true);
    try {
      await fileSystem.writeFile(path, file.content);
      setOpenFiles(
        (prev) => prev.map(
          (f) => f.path === path ? { ...f, isDirty: false } : f
        )
      );
      if (path.endsWith(".orb") || path.endsWith("schema.json")) {
        try {
          const schema = JSON.parse(file.content);
          await onSchemaUpdate?.(schema);
        } catch {
        }
      }
    } catch (err) {
      console.error("[useFileEditor] Failed to save file:", err);
    } finally {
      setIsSaving(false);
    }
  }, [openFiles, fileSystem, onSchemaUpdate]);
  const saveAllFiles = useCallback(async () => {
    setIsSaving(true);
    try {
      const dirtyFiles = openFiles.filter((f) => f.isDirty);
      for (const file of dirtyFiles) {
        await saveFile(file.path);
      }
    } finally {
      setIsSaving(false);
    }
  }, [openFiles, saveFile]);
  return {
    openFiles,
    activeFile,
    isSaving,
    openFile,
    closeFile,
    setActiveFile,
    updateFileContent,
    handleFileEdit,
    saveFile,
    saveAllFiles
  };
}
function useCompile() {
  const [isCompiling, setIsCompiling] = useState(false);
  const [stage, setStage] = useState("idle");
  const [lastResult, setLastResult] = useState(null);
  const [error, setError] = useState(null);
  const compileSchema = useCallback(async (schema) => {
    setIsCompiling(true);
    setStage("compiling");
    setError(null);
    try {
      console.log("[useCompile] Compiling schema:", schema.name);
      const result = {
        success: true,
        files: []
      };
      setLastResult(result);
      setStage("done");
      return result;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : "Compilation failed";
      setError(errorMessage);
      setStage("error");
      setLastResult({ success: false, errors: [errorMessage] });
      return null;
    } finally {
      setIsCompiling(false);
    }
  }, []);
  return {
    isCompiling,
    stage,
    lastResult,
    error,
    compileSchema
  };
}
function usePreview(options) {
  const [previewUrl, setPreviewUrl] = useState(null);
  const [isLoading, setIsLoading] = useState(!!options?.appId);
  const [error, setError] = useState(null);
  const [loadError, setLoadError] = useState(null);
  const [app, setApp] = useState(null);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [isExecutingEvent, setIsExecutingEvent] = useState(false);
  const [errorToast, setErrorToast] = useState(null);
  const [currentStateName, setCurrentStateName] = useState(null);
  const [notificationsList, setNotificationsList] = useState([]);
  const [isPanelOpen, setIsPanelOpen] = useState(false);
  const notifications = useMemo(() => ({
    notifications: notificationsList,
    isPanelOpen,
    closePanel: () => setIsPanelOpen(false),
    dismissNotification: (id) => {
      setNotificationsList((prev) => prev.filter((n) => n.id !== id));
    },
    markAsRead: (id) => {
      setNotificationsList(
        (prev) => prev.map((n) => n.id === id ? { ...n, read: true } : n)
      );
    },
    clearAll: () => setNotificationsList([])
  }), [notificationsList, isPanelOpen]);
  useEffect(() => {
    const appId = options?.appId;
    if (!appId) {
      setApp(null);
      setIsLoading(false);
      return;
    }
    console.log("[usePreview] Setting up preview for app:", appId);
    setPreviewUrl(`/api/orbitals/${appId}`);
    setIsLoading(false);
  }, [options?.appId]);
  const startPreview = useCallback(async () => {
    console.log("[usePreview] startPreview called");
  }, []);
  const stopPreview = useCallback(async () => {
    setIsLoading(true);
    try {
      console.log("[usePreview] Stopping preview server...");
      setPreviewUrl(null);
      setApp(null);
    } finally {
      setIsLoading(false);
    }
  }, []);
  const refresh = useCallback(async () => {
    if (!previewUrl) return;
    console.log("[usePreview] Refreshing preview...");
    setPreviewUrl(`${previewUrl.split("?")[0]}?t=${Date.now()}`);
  }, [previewUrl]);
  const handleRefresh = useCallback(async () => {
    console.log("[usePreview] Handle refresh...");
    await refresh();
  }, [refresh]);
  const handleReset = useCallback(async () => {
    console.log("[usePreview] Resetting preview...");
    setError(null);
    setLoadError(null);
    setErrorToast(null);
    setIsExecutingEvent(false);
    setCurrentStateName(null);
  }, []);
  const toggleFullscreen = useCallback(() => {
    setIsFullscreen((prev) => !prev);
  }, []);
  const dismissErrorToast = useCallback(() => {
    setErrorToast(null);
  }, []);
  return {
    previewUrl,
    isLoading,
    error,
    loadError,
    app,
    isFullscreen,
    isExecutingEvent,
    errorToast,
    currentStateName,
    notifications,
    startPreview,
    stopPreview,
    refresh,
    handleRefresh,
    handleReset,
    toggleFullscreen,
    setErrorToast,
    dismissErrorToast
  };
}
function useAgentChat(options) {
  const [messages, setMessages] = useState([]);
  const [status, setStatus] = useState("idle");
  const [activities, setActivities] = useState([]);
  const [todos, setTodos] = useState([]);
  const [schemaDiffs, setSchemaDiffs] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const [threadId] = useState(null);
  const [interrupt, setInterrupt] = useState(null);
  const sendMessage = useCallback(async (content) => {
    setIsLoading(true);
    setStatus("running");
    setError(null);
    try {
      const userMessage = {
        id: Date.now().toString(),
        role: "user",
        content,
        timestamp: Date.now()
      };
      setMessages((prev) => [...prev, userMessage]);
      console.log("[useAgentChat] Sending message:", content);
      const assistantMessage = {
        id: (Date.now() + 1).toString(),
        role: "assistant",
        content: "Agent chat is not yet implemented.",
        timestamp: Date.now()
      };
      setMessages((prev) => [...prev, assistantMessage]);
      setStatus("idle");
      options?.onComplete?.();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to send message");
      setStatus("error");
    } finally {
      setIsLoading(false);
    }
  }, [options]);
  const startGeneration = useCallback(async (skill, prompt, genOptions) => {
    setStatus("running");
    setIsLoading(true);
    setError(null);
    const skillName = Array.isArray(skill) ? skill[0] : skill;
    try {
      console.log("[useAgentChat] Starting generation:", skillName, prompt, genOptions);
      await new Promise((resolve) => setTimeout(resolve, 100));
      setStatus("complete");
      options?.onComplete?.();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Generation failed");
      setStatus("error");
    } finally {
      setIsLoading(false);
    }
  }, [options]);
  const continueConversation = useCallback(async (message) => {
    console.log("[useAgentChat] Continue conversation", message);
  }, []);
  const resumeWithDecision = useCallback(async (decisions) => {
    console.log("[useAgentChat] Resume with decision:", decisions);
    setInterrupt(null);
  }, []);
  const cancel = useCallback(() => {
    setStatus("idle");
    setIsLoading(false);
    setInterrupt(null);
  }, []);
  const clearMessages = useCallback(() => {
    setMessages([]);
  }, []);
  const clearHistory = useCallback(() => {
    setMessages([]);
    setActivities([]);
    setTodos([]);
    setSchemaDiffs([]);
    setError(null);
  }, []);
  return {
    messages,
    status,
    activities,
    todos,
    schemaDiffs,
    isLoading,
    error,
    threadId,
    interrupt,
    sendMessage,
    startGeneration,
    continueConversation,
    resumeWithDecision,
    cancel,
    clearMessages,
    clearHistory
  };
}
function useValidation() {
  const [result, setResult] = useState(null);
  const [isValidating, setIsValidating] = useState(false);
  const [error, setError] = useState(null);
  const [stage, setStage] = useState("idle");
  const [isFixing, setIsFixing] = useState(false);
  const [progressMessage, setProgressMessage] = useState(null);
  const validate = useCallback(async (appId) => {
    setIsValidating(true);
    setError(null);
    setStage("validating");
    setProgressMessage("Validating schema...");
    try {
      console.log("[useValidation] Validating app:", appId);
      const validationResult = {
        valid: true,
        errors: [],
        warnings: []
      };
      setResult(validationResult);
      setStage("complete");
      setProgressMessage(null);
      return validationResult;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : "Validation failed";
      setError(errorMessage);
      const failedResult = {
        valid: false,
        errors: [{ code: "VALIDATION_ERROR", message: errorMessage, severity: "error" }],
        warnings: []
      };
      setResult(failedResult);
      setStage("complete");
      setProgressMessage(null);
      return failedResult;
    } finally {
      setIsValidating(false);
    }
  }, []);
  const clearResult = useCallback(() => {
    setResult(null);
    setError(null);
  }, []);
  const reset = useCallback(() => {
    setResult(null);
    setError(null);
    setStage("idle");
    setIsFixing(false);
    setProgressMessage(null);
    setIsValidating(false);
  }, []);
  return {
    result,
    isValidating,
    error,
    stage,
    isFixing,
    progressMessage,
    errors: result?.errors ?? [],
    warnings: result?.warnings ?? [],
    isValid: result?.valid ?? false,
    validate,
    clearResult,
    reset
  };
}
function useDeepAgentGeneration() {
  const [requests, setRequests] = useState([]);
  const [currentRequest, setCurrentRequest] = useState(null);
  const [isGenerating, setIsGenerating] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isComplete, setIsComplete] = useState(false);
  const [progress, setProgress] = useState({ stage: "idle", percent: 0, message: "" });
  const [error, setError] = useState(null);
  const [interrupt, setInterrupt] = useState(null);
  const generate = useCallback(async (prompt) => {
    setIsGenerating(true);
    setIsLoading(true);
    setIsComplete(false);
    setError(null);
    setProgress({ stage: "starting", percent: 0, message: "Starting generation..." });
    const request = {
      id: Date.now().toString(),
      prompt,
      status: "running"
    };
    setCurrentRequest(request);
    setRequests((prev) => [...prev, request]);
    try {
      console.log("[useDeepAgentGeneration] Generating from prompt:", prompt);
      await new Promise((resolve) => setTimeout(resolve, 100));
      request.status = "completed";
      setCurrentRequest(request);
      setIsComplete(true);
      setProgress({ stage: "complete", percent: 100, message: "Generation complete" });
      return null;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : "Generation failed";
      setError(errorMessage);
      request.status = "failed";
      request.error = errorMessage;
      setCurrentRequest(request);
      return null;
    } finally {
      setIsGenerating(false);
      setIsLoading(false);
    }
  }, []);
  const startGeneration = useCallback(async (skill, prompt, _options) => {
    console.log("[useDeepAgentGeneration] Starting generation with skill:", skill);
    await generate(prompt);
  }, [generate]);
  const cancelGeneration = useCallback(() => {
    if (currentRequest) {
      currentRequest.status = "failed";
      currentRequest.error = "Cancelled by user";
      setCurrentRequest(null);
    }
    setIsGenerating(false);
    setIsLoading(false);
    setIsComplete(false);
    setProgress({ stage: "idle", percent: 0, message: "" });
  }, [currentRequest]);
  const clearRequests = useCallback(() => {
    setRequests([]);
    setCurrentRequest(null);
    setError(null);
    setProgress({ stage: "idle", percent: 0, message: "" });
    setIsComplete(false);
  }, []);
  const submitInterruptDecisions = useCallback((decisions) => {
    console.log("[useDeepAgentGeneration] Submitting interrupt decisions:", decisions);
    setInterrupt(null);
  }, []);
  return {
    requests,
    currentRequest,
    isGenerating,
    isLoading,
    isComplete,
    progress,
    error,
    interrupt,
    generate,
    startGeneration,
    cancelGeneration,
    clearRequests,
    submitInterruptDecisions
  };
}

// lib/logger.ts
var LEVEL_PRIORITY = { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3 };
var ENV = typeof process !== "undefined" && process.env ? process.env : {};
function envGet(key) {
  return ENV[key] ?? ENV[`VITE_${key}`];
}
var NODE_ENV = envGet("NODE_ENV") ?? "development";
var CONFIGURED_LEVEL = (envGet("LOG_LEVEL") ?? (NODE_ENV === "production" ? "info" : "debug")).toUpperCase();
var MIN_PRIORITY = LEVEL_PRIORITY[CONFIGURED_LEVEL] ?? 0;
var DEBUG_FILTER = (envGet("ALMADAR_DEBUG") ?? "").split(",").map((s) => s.trim()).filter(Boolean);
function matchesNamespace(namespace) {
  if (DEBUG_FILTER.length === 0) return true;
  return DEBUG_FILTER.some((pattern) => {
    if (pattern === "*" || pattern === "almadar:*") return true;
    if (pattern.endsWith(":*")) return namespace.startsWith(pattern.slice(0, -1));
    return namespace === pattern;
  });
}
function createLogger(namespace) {
  const nsAllowed = matchesNamespace(namespace);
  const log2 = (level, message, data, correlationId) => {
    if (LEVEL_PRIORITY[level] < MIN_PRIORITY) return;
    if (level === "DEBUG" && !nsAllowed) return;
    const prefix = `[${namespace}]`;
    const logData = correlationId ? { ...data, cid: correlationId } : data;
    switch (level) {
      case "DEBUG":
        console.debug(prefix, message, logData ?? "");
        break;
      case "INFO":
        console.info(prefix, message, logData ?? "");
        break;
      case "WARN":
        console.warn(prefix, message, logData ?? "");
        break;
      case "ERROR":
        console.error(prefix, message, logData ?? "");
        break;
    }
  };
  return {
    debug: (msg, data, cid) => log2("DEBUG", msg, data, cid),
    info: (msg, data, cid) => log2("INFO", msg, data, cid),
    warn: (msg, data, cid) => log2("WARN", msg, data, cid),
    error: (msg, data, cid) => log2("ERROR", msg, data, cid)
  };
}

// hooks/useEventBus.ts
var log = createLogger("almadar:eventbus");
var subLog = createLogger("almadar:eventbus:subscribe");
var scopeLog = createLogger("almadar:ui:trait-scope");
function getGlobalEventBus() {
  if (typeof window !== "undefined") {
    return window.__kflowEventBus ?? null;
  }
  return null;
}
var fallbackListeners = /* @__PURE__ */ new Map();
var fallbackAnyListeners = /* @__PURE__ */ new Set();
var fallbackEventBus = {
  emit: (type, payload, source) => {
    const event = {
      type,
      payload,
      timestamp: Date.now(),
      source
    };
    const handlers = fallbackListeners.get(type);
    log.debug("emit", { type, payloadKeys: payload ? Object.keys(payload).length : 0, listenerCount: (handlers?.size ?? 0) + fallbackAnyListeners.size });
    if (handlers) {
      handlers.forEach((handler) => {
        try {
          handler(event);
        } catch (error) {
          console.error(`[EventBus] Error in listener for '${type}':`, error);
        }
      });
    }
    fallbackAnyListeners.forEach((handler) => {
      try {
        handler(event);
      } catch (error) {
        console.error(`[EventBus] Error in onAny listener for '${type}':`, error);
      }
    });
  },
  on: (type, listener) => {
    if (!fallbackListeners.has(type)) {
      fallbackListeners.set(type, /* @__PURE__ */ new Set());
    }
    fallbackListeners.get(type).add(listener);
    subLog.debug("subscribe", { type, totalListeners: fallbackListeners.get(type).size });
    return () => {
      const handlers = fallbackListeners.get(type);
      if (handlers) {
        handlers.delete(listener);
        if (handlers.size === 0) {
          fallbackListeners.delete(type);
        }
      }
    };
  },
  once: (type, listener) => {
    const wrappedListener = (event) => {
      fallbackListeners.get(type)?.delete(wrappedListener);
      listener(event);
    };
    return fallbackEventBus.on(type, wrappedListener);
  },
  hasListeners: (type) => {
    const handlers = fallbackListeners.get(type);
    return handlers !== void 0 && handlers.size > 0;
  },
  onAny: (listener) => {
    fallbackAnyListeners.add(listener);
    subLog.debug("subscribe:any", { totalAnyListeners: fallbackAnyListeners.size });
    return () => {
      fallbackAnyListeners.delete(listener);
    };
  }
};
function useEventBus() {
  const context = useContext(EventBusContext);
  const baseBus = context ?? getGlobalEventBus() ?? fallbackEventBus;
  const scope = useTraitScope();
  return useMemo(() => {
    if (!scope) {
      return {
        ...baseBus,
        emit: (type, payload, source) => {
          if (typeof type === "string" && type.startsWith("UI:") && !type.slice(3).includes(".")) {
            scopeLog.warn("emit:bare-key-no-scope", { type });
          }
          baseBus.emit(type, payload, source);
        }
      };
    }
    return {
      ...baseBus,
      emit: (type, payload, source) => {
        if (typeof type === "string" && type.startsWith("UI:")) {
          const tail = type.slice(3);
          const qualified = tail.includes(".") ? type : `UI:${scope.orbital}.${scope.trait}.${tail}`;
          if (qualified !== type) {
            scopeLog.info("emit:qualified", { from: type, to: qualified, scope });
          }
          baseBus.emit(qualified, payload, source);
          return;
        }
        baseBus.emit(type, payload, source);
      }
    };
  }, [baseBus, scope]);
}
function useEventListener(event, handler) {
  const eventBus = useEventBus();
  const handlerRef = useRef(handler);
  handlerRef.current = handler;
  useEffect(() => {
    const wrappedHandler = (evt) => {
      handlerRef.current(evt);
    };
    const unsub = eventBus.on(event, wrappedHandler);
    return () => {
      if (typeof unsub === "function") unsub();
    };
  }, [event, eventBus]);
}
function useEmitEvent() {
  const eventBus = useEventBus();
  return useCallback(
    (type, payload, source) => {
      eventBus.emit(type, payload, source);
    },
    [eventBus]
  );
}
var slotLog = createLogger("almadar:ui:useUISlots");
var DEFAULT_SOURCE_KEY = "__default__";
var MULTI_SOURCE_STACK_TRAIT = "__multi_source_stack__";
var ALL_SLOTS = [
  "main",
  "sidebar",
  "modal",
  "drawer",
  "overlay",
  "center",
  "toast",
  "hud-top",
  "hud-bottom",
  "hud-left",
  "hud-right",
  "floating"
];
var DEFAULT_SLOTS = ALL_SLOTS.reduce(
  (acc, slot) => {
    acc[slot] = null;
    return acc;
  },
  {}
);
var DEFAULT_SOURCES = ALL_SLOTS.reduce(
  (acc, slot) => {
    acc[slot] = {};
    return acc;
  },
  {}
);
var idCounter = 0;
function generateId() {
  return `slot-content-${++idCounter}-${Date.now()}`;
}
function aggregateSlot(sources) {
  if (!sources) return null;
  const entries = Object.entries(sources);
  if (entries.length === 0) return null;
  if (entries.length === 1) return entries[0][1];
  const children = entries.map(([, entry]) => ({
    type: entry.pattern,
    ...entry.props
  }));
  const stackId = `slot-content-stack-${entries.map(([k]) => k).join("-")}`;
  return {
    id: stackId,
    pattern: "stack",
    props: {
      direction: "vertical",
      gap: "lg",
      children
    },
    priority: 0,
    animation: "fade",
    sourceTrait: MULTI_SOURCE_STACK_TRAIT
  };
}
function useUISlotManager() {
  const [sources, setSources] = useState(DEFAULT_SOURCES);
  const subscribersRef = useRef(/* @__PURE__ */ new Set());
  const timersRef = useRef(/* @__PURE__ */ new Map());
  const traitIndexRef = useRef(/* @__PURE__ */ new Map());
  const traitSubscribersRef = useRef(/* @__PURE__ */ new Map());
  const slots = useMemo(() => {
    const out = { ...DEFAULT_SLOTS };
    for (const slot of ALL_SLOTS) {
      out[slot] = aggregateSlot(sources[slot]);
    }
    return out;
  }, [sources]);
  useEffect(() => {
    return () => {
      timersRef.current.forEach((timer) => clearTimeout(timer));
      timersRef.current.clear();
    };
  }, []);
  const notifySubscribers = useCallback((slot, content) => {
    subscribersRef.current.forEach((callback) => {
      try {
        callback(slot, content);
      } catch (error) {
        console.error("[UISlots] Subscriber error:", error);
      }
    });
  }, []);
  const notifyTraitSubscribers = useCallback(
    (traitName, content) => {
      const subs = traitSubscribersRef.current.get(traitName);
      if (!subs) return;
      subs.forEach((callback) => {
        try {
          callback(content);
        } catch (error) {
          console.error(`[UISlots] Trait subscriber error (${traitName}):`, error);
        }
      });
    },
    []
  );
  const indexTraitRender = useCallback(
    (traitName, content) => {
      traitIndexRef.current.set(traitName, content);
    },
    []
  );
  const unindexTrait = useCallback((traitName) => {
    traitIndexRef.current.delete(traitName);
  }, []);
  const render = useCallback(
    (config) => {
      const id = generateId();
      const sourceKey = config.sourceTrait ?? DEFAULT_SOURCE_KEY;
      const content = {
        id,
        pattern: config.pattern,
        props: config.props ?? {},
        priority: config.priority ?? 0,
        animation: config.animation ?? "fade",
        onDismiss: config.onDismiss,
        sourceTrait: config.sourceTrait
      };
      if (config.autoDismissMs && config.autoDismissMs > 0) {
        content.autoDismissAt = Date.now() + config.autoDismissMs;
        const timer = setTimeout(() => {
          setSources((prev) => {
            const slotSources = prev[config.target];
            if (slotSources && slotSources[sourceKey]?.id === id) {
              content.onDismiss?.();
              const next = { ...slotSources };
              delete next[sourceKey];
              const updated = { ...prev, [config.target]: next };
              notifySubscribers(config.target, aggregateSlot(next));
              return updated;
            }
            return prev;
          });
          timersRef.current.delete(id);
        }, config.autoDismissMs);
        timersRef.current.set(id, timer);
      }
      setSources((prev) => {
        const slotSources = prev[config.target] ?? {};
        const existing = slotSources[sourceKey];
        if (existing && existing.priority > content.priority) {
          console.warn(
            `[UISlots] Slot "${config.target}" source "${sourceKey}" already has higher priority content (${existing.priority} > ${content.priority})`
          );
          return prev;
        }
        const nextSources = {
          ...slotSources,
          [sourceKey]: content
        };
        const nextAll = { ...prev, [config.target]: nextSources };
        if (content.sourceTrait) {
          indexTraitRender(content.sourceTrait, content);
          notifyTraitSubscribers(content.sourceTrait, content);
        }
        slotLog.info("slot:written", {
          slot: config.target,
          sourceKey,
          sourceTrait: content.sourceTrait,
          patternType: content.pattern,
          priority: content.priority
        });
        notifySubscribers(config.target, aggregateSlot(nextSources));
        return nextAll;
      });
      return id;
    },
    [notifySubscribers, notifyTraitSubscribers, indexTraitRender]
  );
  const clear = useCallback(
    (slot) => {
      setSources((prev) => {
        const slotSources = prev[slot];
        if (!slotSources || Object.keys(slotSources).length === 0) {
          return prev;
        }
        for (const content of Object.values(slotSources)) {
          const timer = timersRef.current.get(content.id);
          if (timer) {
            clearTimeout(timer);
            timersRef.current.delete(content.id);
          }
          content.onDismiss?.();
          if (content.sourceTrait) {
            unindexTrait(content.sourceTrait);
            notifyTraitSubscribers(content.sourceTrait, null);
          }
        }
        notifySubscribers(slot, null);
        return { ...prev, [slot]: {} };
      });
    },
    [notifySubscribers, notifyTraitSubscribers, unindexTrait]
  );
  const clearBySource = useCallback(
    (slot, sourceTrait) => {
      const sourceKey = sourceTrait;
      setSources((prev) => {
        const slotSources = prev[slot];
        if (!slotSources || !(sourceKey in slotSources)) {
          slotLog.debug("slot:clear-noop", { slot, sourceTrait, reason: !slotSources ? "no-slot" : "no-source" });
          return prev;
        }
        const content = slotSources[sourceKey];
        const timer = timersRef.current.get(content.id);
        if (timer) {
          clearTimeout(timer);
          timersRef.current.delete(content.id);
        }
        content.onDismiss?.();
        if (content.sourceTrait) {
          unindexTrait(content.sourceTrait);
          notifyTraitSubscribers(content.sourceTrait, null);
        }
        const nextSources = { ...slotSources };
        delete nextSources[sourceKey];
        slotLog.info("slot:cleared", { slot, sourceTrait, lastPatternType: content.pattern });
        notifySubscribers(slot, aggregateSlot(nextSources));
        return { ...prev, [slot]: nextSources };
      });
    },
    [notifySubscribers, notifyTraitSubscribers, unindexTrait]
  );
  const clearById = useCallback(
    (id) => {
      setSources((prev) => {
        for (const slot of ALL_SLOTS) {
          const slotSources = prev[slot];
          if (!slotSources) continue;
          const matchKey = Object.keys(slotSources).find(
            (k) => slotSources[k].id === id
          );
          if (!matchKey) continue;
          const content = slotSources[matchKey];
          const timer = timersRef.current.get(id);
          if (timer) {
            clearTimeout(timer);
            timersRef.current.delete(id);
          }
          content.onDismiss?.();
          if (content.sourceTrait) {
            unindexTrait(content.sourceTrait);
            notifyTraitSubscribers(content.sourceTrait, null);
          }
          const nextSources = { ...slotSources };
          delete nextSources[matchKey];
          notifySubscribers(slot, aggregateSlot(nextSources));
          return { ...prev, [slot]: nextSources };
        }
        return prev;
      });
    },
    [notifySubscribers, notifyTraitSubscribers, unindexTrait]
  );
  const clearAll = useCallback(() => {
    timersRef.current.forEach((timer) => clearTimeout(timer));
    timersRef.current.clear();
    setSources((prev) => {
      for (const slot of ALL_SLOTS) {
        const slotSources = prev[slot];
        if (!slotSources) continue;
        for (const content of Object.values(slotSources)) {
          content.onDismiss?.();
          if (content.sourceTrait) {
            notifyTraitSubscribers(content.sourceTrait, null);
          }
        }
        notifySubscribers(slot, null);
      }
      return DEFAULT_SOURCES;
    });
    traitIndexRef.current.clear();
  }, [notifySubscribers, notifyTraitSubscribers]);
  const subscribe2 = useCallback((callback) => {
    subscribersRef.current.add(callback);
    return () => {
      subscribersRef.current.delete(callback);
    };
  }, []);
  const hasContent = useCallback(
    (slot) => slots[slot] !== null,
    [slots]
  );
  const getContent = useCallback(
    (slot) => slots[slot],
    [slots]
  );
  const getTraitContent = useCallback(
    (traitName) => traitIndexRef.current.get(traitName) ?? null,
    []
  );
  const subscribeTrait = useCallback(
    (traitName, callback) => {
      let set = traitSubscribersRef.current.get(traitName);
      if (!set) {
        set = /* @__PURE__ */ new Set();
        traitSubscribersRef.current.set(traitName, set);
      }
      set.add(callback);
      return () => {
        const s = traitSubscribersRef.current.get(traitName);
        if (!s) return;
        s.delete(callback);
        if (s.size === 0) {
          traitSubscribersRef.current.delete(traitName);
        }
      };
    },
    []
  );
  const updateTraitContent = useCallback(
    (traitName, content) => {
      const id = generateId();
      const fullContent = { ...content, id, sourceTrait: traitName };
      indexTraitRender(traitName, fullContent);
      notifyTraitSubscribers(traitName, fullContent);
      return id;
    },
    [indexTraitRender, notifyTraitSubscribers]
  );
  return {
    slots,
    render,
    clear,
    clearBySource,
    clearById,
    clearAll,
    subscribe: subscribe2,
    hasContent,
    getContent,
    getTraitContent,
    subscribeTrait,
    updateTraitContent
  };
}
var UI_PREFIX = "UI:";
function useUIEvents(dispatch, traitName, validEvents, eventBusInstance) {
  const defaultEventBus = useEventBus();
  const eventBus = eventBusInstance ?? defaultEventBus;
  const validEventsKey = validEvents.slice().sort().join(",");
  const stableValidEvents = useMemo(
    () => validEvents,
    [validEventsKey]
    // intentional — validEventsKey is the stable dep
  );
  useEffect(() => {
    const unsubscribes = [];
    for (const smEvent of stableValidEvents) {
      const handler = (event) => {
        if (event.source && event.source.dispatched) {
          return;
        }
        dispatch(smEvent, event.payload);
      };
      unsubscribes.push(
        eventBus.on(`${UI_PREFIX}${traitName}.${smEvent}`, handler)
      );
    }
    return () => {
      for (const unsub of unsubscribes) {
        if (typeof unsub === "function") unsub();
      }
    };
  }, [eventBus, dispatch, traitName, stableValidEvents]);
}
function useTraitListens(dispatch, listens, eventBusInstance) {
  const defaultEventBus = useEventBus();
  const eventBus = eventBusInstance ?? defaultEventBus;
  const stableKey = listens.map((l) => `${l.sourceKey}->${l.trigger}`).sort().join("|");
  const stableListens = useMemo(
    () => listens,
    [stableKey]
    // intentional
  );
  useEffect(() => {
    const unsubscribes = [];
    for (const spec of stableListens) {
      const handler = (event) => {
        dispatch(spec.trigger, event.payload);
      };
      unsubscribes.push(eventBus.on(`${UI_PREFIX}${spec.sourceKey}`, handler));
    }
    return () => {
      for (const unsub of unsubscribes) {
        if (typeof unsub === "function") unsub();
      }
    };
  }, [eventBus, dispatch, stableListens]);
}
var queryStores = /* @__PURE__ */ new Map();
function getOrCreateStore(query) {
  if (!queryStores.has(query)) {
    queryStores.set(query, {
      search: "",
      filters: {},
      sortField: void 0,
      sortDirection: void 0,
      listeners: /* @__PURE__ */ new Set()
    });
  }
  return queryStores.get(query);
}
function useQuerySingleton(query) {
  const [, forceUpdate] = useState({});
  if (!query) {
    return null;
  }
  const store = useMemo(() => getOrCreateStore(query), [query]);
  useMemo(() => {
    const listener = () => forceUpdate({});
    store.listeners.add(listener);
    return () => {
      store.listeners.delete(listener);
    };
  }, [store]);
  const notifyListeners = useCallback(() => {
    store.listeners.forEach((listener) => listener());
  }, [store]);
  const setSearch = useCallback((value) => {
    store.search = value;
    notifyListeners();
  }, [store, notifyListeners]);
  const setFilter = useCallback((key, value) => {
    store.filters = { ...store.filters, [key]: value };
    notifyListeners();
  }, [store, notifyListeners]);
  const clearFilters = useCallback(() => {
    store.filters = {};
    store.search = "";
    notifyListeners();
  }, [store, notifyListeners]);
  const setSort = useCallback((field, direction) => {
    store.sortField = field;
    store.sortDirection = direction;
    notifyListeners();
  }, [store, notifyListeners]);
  return {
    search: store.search,
    setSearch,
    filters: store.filters,
    setFilter,
    clearFilters,
    sortField: store.sortField,
    sortDirection: store.sortDirection,
    setSort
  };
}
function parseQueryBinding(binding) {
  const cleaned = binding.startsWith("@") ? binding.slice(1) : binding;
  const parts = cleaned.split(".");
  return {
    query: parts[0],
    field: parts.length > 1 ? parts.slice(1).join(".") : void 0
  };
}

// stores/entityStore.ts
var entities = /* @__PURE__ */ new Map();
var listeners = /* @__PURE__ */ new Set();
var idCounter2 = 0;
function subscribe(listener) {
  listeners.add(listener);
  return () => listeners.delete(listener);
}
function notify() {
  listeners.forEach((listener) => listener());
}
function getEntity(id) {
  return entities.get(id);
}
function getByType(type) {
  const types = Array.isArray(type) ? type : [type];
  return [...entities.values()].filter((e) => types.includes(e.type));
}
function getAllEntities() {
  return [...entities.values()];
}
function getSingleton(type) {
  return [...entities.values()].find((e) => e.type === type);
}
function spawnEntity(config) {
  const id = config.id ?? `entity_${++idCounter2}`;
  const entity = { ...config, id };
  entities = new Map(entities);
  entities.set(id, entity);
  notify();
  return id;
}
function updateEntity(id, updates) {
  const entity = entities.get(id);
  if (entity) {
    entities = new Map(entities);
    entities.set(id, { ...entity, ...updates });
    notify();
  }
}
function updateSingleton(type, updates) {
  const entity = getSingleton(type);
  if (entity) {
    updateEntity(entity.id, updates);
  }
}
function removeEntity(id) {
  if (entities.has(id)) {
    entities = new Map(entities);
    entities.delete(id);
    notify();
  }
}
function clearEntities() {
  entities = /* @__PURE__ */ new Map();
  notify();
}
function getSnapshot() {
  return entities;
}

// hooks/useEntities.ts
function useEntities() {
  const entities2 = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
  return {
    entities: entities2,
    getEntity,
    getByType,
    getAllEntities,
    getSingleton,
    spawnEntity,
    updateEntity,
    updateSingleton,
    removeEntity,
    clearEntities
  };
}
function useEntity(id) {
  const entities2 = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
  return entities2.get(id);
}
function useEntitiesByType(type) {
  const entities2 = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
  return [...entities2.values()].filter((e) => e.type === type);
}
function useSingletonEntity(type) {
  const entities2 = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
  return [...entities2.values()].find((e) => e.type === type);
}
function usePlayer() {
  const player = useSingletonEntity("Player");
  const update = useCallback((updates) => {
    if (player) updateEntity(player.id, updates);
  }, [player?.id]);
  return { player, updatePlayer: update };
}
function usePhysics() {
  const physics = useSingletonEntity("Physics");
  const update = useCallback((updates) => {
    if (physics) updateEntity(physics.id, updates);
  }, [physics?.id]);
  return { physics, updatePhysics: update };
}
function useInput() {
  const input = useSingletonEntity("Input");
  const update = useCallback((updates) => {
    if (input) updateEntity(input.id, updates);
  }, [input?.id]);
  return { input, updateInput: update };
}

// locales/en.json
var en_default = {
  $meta: { locale: "en", direction: "ltr" },
  "common.save": "Save",
  "common.cancel": "Cancel",
  "common.delete": "Delete",
  "common.close": "Close",
  "common.confirm": "Are you sure?",
  "common.create": "Create",
  "common.edit": "Edit",
  "common.view": "View",
  "common.add": "Add",
  "common.remove": "Remove",
  "common.search": "Search...",
  "common.filter": "Filter",
  "common.actions": "Actions",
  "common.yes": "Yes",
  "common.no": "No",
  "common.selected": "selected",
  "common.ok": "OK",
  "common.done": "Done",
  "common.apply": "Apply",
  "common.reset": "Reset",
  "common.refresh": "Refresh",
  "common.export": "Export",
  "common.import": "Import",
  "common.copy": "Copy",
  "common.settings": "Settings",
  "nav.previous": "Previous",
  "nav.next": "Next",
  "nav.back": "Back",
  "nav.home": "Home",
  "form.submit": "Submit",
  "form.saving": "Saving...",
  "form.required": "This field is required",
  "form.invalidEmail": "Enter a valid email address",
  "form.selectPlaceholder": "Select {{label}}...",
  "form.searchPlaceholder": "Search {{entity}}...",
  "table.empty.title": "No items found",
  "table.empty.description": "No items to display.",
  "table.search.placeholder": "Search...",
  "table.pagination.showing": "Showing {{start}} to {{end}} of {{total}} results",
  "table.pagination.page": "Page {{page}} of {{totalPages}}",
  "table.bulk.selected": "{{count}} selected",
  "table.loading": "Loading...",
  "status.loading": "Loading...",
  "status.scheduled": "Scheduled",
  "status.inProgress": "In Progress",
  "status.completed": "Completed",
  "status.cancelled": "Cancelled",
  "status.pending": "Pending",
  "status.active": "Active",
  "status.inactive": "Inactive",
  "status.draft": "Draft",
  "status.archived": "Archived",
  "error.generic": "Something went wrong",
  "error.retry": "Try again",
  "error.notFound": "Not found",
  "error.loadFailed": "Failed to load: {{message}}",
  "error.configMissing": "Configuration not found for: {{id}}",
  "common.loading": "Loading...",
  "common.showMore": "Show More",
  "common.showLess": "Show Less",
  "common.noResults": "No results found",
  "common.saveChanges": "Save Changes",
  "common.retry": "Retry",
  "common.open": "Open",
  "common.back": "Back",
  "empty.noItems": "No items",
  "empty.noData": "No data available",
  "empty.noItemsYet": "No items yet",
  "empty.noItemsAdded": "No items added yet",
  "empty.noOptionsFound": "No options found",
  "list.addItemPlaceholder": "Add new item...",
  "error.occurred": "An error occurred",
  "error.failedToLoad": "Failed to load data",
  "wizard.back": "Back",
  "wizard.next": "Next",
  "wizard.complete": "Complete",
  "wizard.stepOf": "Step {{current}} of {{total}}",
  "pagination.previous": "Previous",
  "pagination.next": "Next",
  "pagination.total": "Total:",
  "pagination.show": "Show:",
  "pagination.goTo": "Go to:",
  "pagination.go": "Go",
  "auth.signIn": "Sign in",
  "auth.signOut": "Sign out",
  "dialog.confirm": "Confirm",
  "dialog.cancel": "Cancel",
  "dialog.loading": "Loading...",
  "dialog.delete.title": "Delete {{item}}?",
  "dialog.delete.message": "This action cannot be undone.",
  "trait.availableActions": "Available Actions",
  "trait.transitions": "Transitions",
  "trait.availableNow": "Available now",
  "book.startReading": "Start Reading",
  "book.tableOfContents": "Table of Contents",
  "book.partNumber": "Part {{number}}",
  "book.print": "Print",
  "book.previousPage": "Previous page",
  "book.nextPage": "Next page",
  "quiz.showAnswer": "Show answer",
  "quiz.hideAnswer": "Hide answer"
};

// hooks/useTranslate.ts
var { $meta: _meta, ...coreMessages } = en_default;
var coreLocale = coreMessages;
var I18nContext = createContext({
  locale: "en",
  direction: "ltr",
  t: (key) => coreLocale[key] ?? key
  // core locale fallback
});
I18nContext.displayName = "I18nContext";
var I18nProvider = I18nContext.Provider;
function useTranslate() {
  return useContext(I18nContext);
}
function createTranslate(messages) {
  return (key, params) => {
    let msg = messages[key] ?? coreLocale[key] ?? key;
    if (params) {
      for (const [k, v] of Object.entries(params)) {
        msg = msg.split(`{{${k}}}`).join(String(v));
      }
    }
    return msg;
  };
}

// hooks/useAuthContext.ts
function useAuthContext() {
  return {
    user: null,
    loading: false,
    signIn: void 0,
    signOut: void 0
  };
}
function useSwipeGesture(callbacks, options = {}) {
  const { threshold = 50, velocityThreshold = 0.3, preventDefault = false } = options;
  const startX = useRef(0);
  const startY = useRef(0);
  const startTime = useRef(0);
  const currentX = useRef(0);
  const tracking = useRef(false);
  const offsetXRef = useRef(0);
  const isSwipingRef = useRef(false);
  const onPointerDown = useCallback((e) => {
    startX.current = e.clientX;
    startY.current = e.clientY;
    currentX.current = e.clientX;
    startTime.current = Date.now();
    tracking.current = true;
    isSwipingRef.current = false;
    offsetXRef.current = 0;
    e.target.setPointerCapture?.(e.pointerId);
  }, []);
  const onPointerMove = useCallback((e) => {
    if (!tracking.current) return;
    if (preventDefault) e.preventDefault();
    currentX.current = e.clientX;
    const dx = e.clientX - startX.current;
    const dy = e.clientY - startY.current;
    if (Math.abs(dx) > 10 && Math.abs(dx) > Math.abs(dy)) {
      isSwipingRef.current = true;
      offsetXRef.current = dx;
    }
  }, [preventDefault]);
  const onPointerUp = useCallback((e) => {
    if (!tracking.current) return;
    tracking.current = false;
    const dx = e.clientX - startX.current;
    const dy = e.clientY - startY.current;
    const elapsed = Date.now() - startTime.current;
    const velocity = Math.abs(dx) / Math.max(elapsed, 1);
    offsetXRef.current = 0;
    isSwipingRef.current = false;
    if (Math.abs(dx) < threshold && velocity < velocityThreshold) return;
    if (Math.abs(dx) > Math.abs(dy)) {
      if (dx < -threshold) callbacks.onSwipeLeft?.();
      else if (dx > threshold) callbacks.onSwipeRight?.();
    } else {
      if (dy < -threshold) callbacks.onSwipeUp?.();
      else if (dy > threshold) callbacks.onSwipeDown?.();
    }
  }, [threshold, velocityThreshold, callbacks]);
  const onPointerCancel = useCallback(() => {
    tracking.current = false;
    offsetXRef.current = 0;
    isSwipingRef.current = false;
  }, []);
  return {
    onPointerDown,
    onPointerMove,
    onPointerUp,
    onPointerCancel,
    offsetX: offsetXRef.current,
    isSwiping: isSwipingRef.current
  };
}
function useLongPress(onLongPress, options = {}) {
  const { duration = 500, moveThreshold = 10 } = options;
  const timerRef = useRef(null);
  const startPos = useRef({ x: 0, y: 0 });
  const isPressedRef = useRef(false);
  const firedRef = useRef(false);
  const cancel = useCallback(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
    isPressedRef.current = false;
  }, []);
  const onPointerDown = useCallback((e) => {
    firedRef.current = false;
    startPos.current = { x: e.clientX, y: e.clientY };
    isPressedRef.current = true;
    timerRef.current = setTimeout(() => {
      firedRef.current = true;
      isPressedRef.current = false;
      onLongPress();
    }, duration);
  }, [duration, onLongPress]);
  const onPointerMove = useCallback((e) => {
    if (!isPressedRef.current) return;
    const dx = e.clientX - startPos.current.x;
    const dy = e.clientY - startPos.current.y;
    if (Math.sqrt(dx * dx + dy * dy) > moveThreshold) {
      cancel();
    }
  }, [moveThreshold, cancel]);
  const onPointerUp = useCallback(() => {
    cancel();
  }, [cancel]);
  const onPointerCancel = useCallback(() => {
    cancel();
  }, [cancel]);
  return {
    onPointerDown,
    onPointerMove,
    onPointerUp,
    onPointerCancel,
    isPressed: isPressedRef.current
  };
}
function useDragReorder(initialItems, onReorder) {
  const [items, setItems] = useState(initialItems);
  const [dragIndex, setDragIndex] = useState(-1);
  const [dragOverIndex, setDragOverIndex] = useState(-1);
  const itemsRef = useRef(initialItems);
  if (initialItems !== itemsRef.current) {
    itemsRef.current = initialItems;
    setItems(initialItems);
  }
  const isDragging = dragIndex >= 0;
  const handleDragStart = useCallback((index) => (e) => {
    e.preventDefault();
    setDragIndex(index);
    setDragOverIndex(index);
    e.target.setPointerCapture?.(e.pointerId);
  }, []);
  const handleDragMove = useCallback((index) => (e) => {
    if (dragIndex < 0) return;
    const target = document.elementFromPoint(e.clientX, e.clientY);
    if (!target) return;
    let el = target;
    while (el && !el.dataset.dragIndex) {
      el = el.parentElement;
    }
    if (el?.dataset.dragIndex) {
      const overIndex = parseInt(el.dataset.dragIndex, 10);
      if (!isNaN(overIndex) && overIndex !== dragOverIndex) {
        setDragOverIndex(overIndex);
      }
    }
  }, [dragIndex, dragOverIndex]);
  const handleDragEnd = useCallback(() => {
    if (dragIndex >= 0 && dragOverIndex >= 0 && dragIndex !== dragOverIndex) {
      const newItems = [...items];
      const [movedItem] = newItems.splice(dragIndex, 1);
      newItems.splice(dragOverIndex, 0, movedItem);
      setItems(newItems);
      onReorder(dragIndex, dragOverIndex, items[dragIndex]);
    }
    setDragIndex(-1);
    setDragOverIndex(-1);
  }, [dragIndex, dragOverIndex, items, onReorder]);
  const getDragHandleProps = useCallback((index) => ({
    onPointerDown: handleDragStart(index),
    style: { cursor: "grab", touchAction: "none" },
    "aria-grabbed": dragIndex === index,
    role: "button"
  }), [handleDragStart, dragIndex]);
  const getItemProps = useCallback((index) => ({
    onPointerMove: handleDragMove(index),
    onPointerUp: handleDragEnd,
    "aria-dropeffect": "move",
    "data-drag-index": String(index),
    style: {
      opacity: dragIndex === index ? 0.5 : 1,
      transition: isDragging ? "transform 150ms ease" : void 0,
      transform: isDragging && dragOverIndex >= 0 ? index === dragIndex ? "scale(1.02)" : index > dragIndex && index <= dragOverIndex ? "translateY(-100%)" : index < dragIndex && index >= dragOverIndex ? "translateY(100%)" : void 0 : void 0
    }
  }), [handleDragMove, handleDragEnd, dragIndex, dragOverIndex, isDragging]);
  return {
    items,
    dragIndex,
    dragOverIndex,
    isDragging,
    getDragHandleProps,
    getItemProps
  };
}
function useInfiniteScroll(onLoadMore, options = {}) {
  const { rootMargin = "200px", hasMore = true, isLoading = false } = options;
  const observerRef = useRef(null);
  const callbackRef = useRef(onLoadMore);
  callbackRef.current = onLoadMore;
  const hasMoreRef = useRef(hasMore);
  hasMoreRef.current = hasMore;
  const isLoadingRef = useRef(isLoading);
  isLoadingRef.current = isLoading;
  useEffect(() => {
    return () => {
      observerRef.current?.disconnect();
    };
  }, []);
  const sentinelRef = useCallback((node) => {
    observerRef.current?.disconnect();
    if (!node) return;
    observerRef.current = new IntersectionObserver(
      (entries) => {
        const entry = entries[0];
        if (entry.isIntersecting && hasMoreRef.current && !isLoadingRef.current) {
          callbackRef.current();
        }
      },
      { rootMargin }
    );
    observerRef.current.observe(node);
  }, [rootMargin]);
  return { sentinelRef };
}
function usePullToRefresh(onRefresh, options = {}) {
  const { threshold = 60, maxPull = 120 } = options;
  const [pullDistance, setPullDistance] = useState(0);
  const [isPulling, setIsPulling] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const startY = useRef(0);
  const scrollTopRef = useRef(0);
  const onTouchStart = useCallback((e) => {
    const container = e.currentTarget;
    scrollTopRef.current = container.scrollTop;
    if (scrollTopRef.current <= 0) {
      startY.current = e.touches[0].clientY;
      setIsPulling(true);
    }
  }, []);
  const onTouchMove = useCallback((e) => {
    if (!isPulling || isRefreshing) return;
    const container = e.currentTarget;
    if (container.scrollTop > 0) {
      setPullDistance(0);
      return;
    }
    const dy = e.touches[0].clientY - startY.current;
    if (dy > 0) {
      const distance = Math.min(dy * 0.5, maxPull);
      setPullDistance(distance);
    }
  }, [isPulling, isRefreshing, maxPull]);
  const onTouchEnd = useCallback(() => {
    if (!isPulling) return;
    setIsPulling(false);
    if (pullDistance >= threshold && !isRefreshing) {
      setIsRefreshing(true);
      setPullDistance(threshold);
      onRefresh();
    } else {
      setPullDistance(0);
    }
  }, [isPulling, pullDistance, threshold, isRefreshing, onRefresh]);
  const endRefresh = useCallback(() => {
    setIsRefreshing(false);
    setPullDistance(0);
  }, []);
  const containerProps = {
    onTouchStart,
    onTouchMove,
    onTouchEnd,
    style: {
      transform: pullDistance > 0 ? `translateY(${pullDistance}px)` : void 0,
      transition: isPulling ? "none" : "transform 300ms ease-out"
    }
  };
  return {
    pullDistance,
    isPulling,
    isRefreshing,
    containerProps,
    endRefresh
  };
}
function getDistance(touches) {
  const dx = touches[0].clientX - touches[1].clientX;
  const dy = touches[0].clientY - touches[1].clientY;
  return Math.sqrt(dx * dx + dy * dy);
}
function usePinchZoom(options = {}) {
  const { minScale = 0.5, maxScale = 4 } = options;
  const [scale, setScale] = useState(1);
  const [isPinching, setIsPinching] = useState(false);
  const initialDistance = useRef(0);
  const initialScale = useRef(1);
  const onTouchStart = useCallback((e) => {
    if (e.touches.length === 2) {
      initialDistance.current = getDistance(e.touches);
      initialScale.current = scale;
      setIsPinching(true);
    }
  }, [scale]);
  const onTouchMove = useCallback((e) => {
    if (e.touches.length !== 2 || !isPinching) return;
    e.preventDefault();
    const currentDistance = getDistance(e.touches);
    const ratio = currentDistance / initialDistance.current;
    const newScale = Math.min(maxScale, Math.max(minScale, initialScale.current * ratio));
    setScale(newScale);
  }, [isPinching, minScale, maxScale]);
  const onTouchEnd = useCallback(() => {
    setIsPinching(false);
  }, []);
  const resetZoom = useCallback(() => {
    setScale(1);
  }, []);
  return {
    scale,
    isPinching,
    gestureProps: {
      onTouchStart,
      onTouchMove,
      onTouchEnd
    },
    resetZoom
  };
}
var ALMADAR_DND_MIME = "application/x-almadar-dnd";
function useDraggable({ payload, disabled = false }) {
  const [isDragging, setIsDragging] = useState(false);
  const eventBus = useEventBus();
  const handleDragStart = useCallback(
    (e) => {
      if (disabled) {
        e.preventDefault();
        return;
      }
      e.dataTransfer.setData(ALMADAR_DND_MIME, JSON.stringify(payload));
      e.dataTransfer.effectAllowed = "copy";
      setIsDragging(true);
      eventBus.emit("UI:DRAG_START", { kind: payload.kind, data: payload.data });
    },
    [disabled, payload, eventBus]
  );
  const handleDragEnd = useCallback(
    (e) => {
      setIsDragging(false);
      eventBus.emit("UI:DRAG_END", { kind: payload.kind, data: payload.data });
    },
    [payload, eventBus]
  );
  const dragProps = useMemo(
    () => ({
      draggable: !disabled,
      onDragStart: handleDragStart,
      onDragEnd: handleDragEnd,
      "aria-grabbed": isDragging
    }),
    [disabled, handleDragStart, handleDragEnd, isDragging]
  );
  return { dragProps, isDragging };
}
function parsePayload(e) {
  try {
    const raw = e.dataTransfer.getData(ALMADAR_DND_MIME);
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    if (typeof parsed.kind !== "string" || !parsed.data) return null;
    return parsed;
  } catch {
    return null;
  }
}
function hasAlmadarPayload(e) {
  return e.dataTransfer.types.includes(ALMADAR_DND_MIME);
}
function useDropZone({ accepts, onDrop, disabled = false }) {
  const [isOver, setIsOver] = useState(false);
  const eventBus = useEventBus();
  const handleDragOver = useCallback(
    (e) => {
      if (disabled) return;
      if (!hasAlmadarPayload(e)) return;
      e.preventDefault();
      e.dataTransfer.dropEffect = "copy";
      setIsOver(true);
    },
    [disabled]
  );
  const handleDragLeave = useCallback(
    (e) => {
      setIsOver(false);
    },
    []
  );
  const handleDrop = useCallback(
    (e) => {
      e.preventDefault();
      setIsOver(false);
      if (disabled) return;
      const payload = parsePayload(e);
      if (!payload) return;
      if (!accepts.includes(payload.kind)) return;
      const position = { x: e.clientX, y: e.clientY };
      onDrop(payload, position);
      eventBus.emit("UI:DROP", { kind: payload.kind, data: payload.data, ...position });
    },
    [disabled, accepts, onDrop, eventBus]
  );
  const dropProps = useMemo(
    () => ({
      onDragOver: handleDragOver,
      onDragLeave: handleDragLeave,
      onDrop: handleDrop
    }),
    [handleDragOver, handleDragLeave, handleDrop]
  );
  return { dropProps, isOver };
}
var API_BASE = typeof process !== "undefined" && process.env?.VITE_API_URL ? process.env.VITE_API_URL : "http://localhost:3000";
function getUserId() {
  return localStorage.getItem("userId") || "anonymous";
}
async function fetchWithAuth(endpoint, options) {
  const userId = getUserId();
  const response = await fetch(`${API_BASE}${endpoint}`, {
    ...options,
    headers: {
      "Content-Type": "application/json",
      "x-user-id": userId,
      ...options?.headers
    }
  });
  if (!response.ok) {
    const error = await response.json().catch(() => ({ error: response.statusText }));
    throw new Error(error.error || error.message || "Request failed");
  }
  return response.json();
}
function useGitHubStatus() {
  return useQuery({
    queryKey: ["github", "status"],
    queryFn: () => fetchWithAuth("/api/github/status"),
    staleTime: 6e4,
    // 1 minute
    retry: false
  });
}
function useConnectGitHub() {
  const connectGitHub = useCallback(() => {
    const userId = getUserId();
    const state = btoa(JSON.stringify({ userId, returnUrl: window.location.href }));
    window.location.href = `${API_BASE}/api/github/oauth/authorize?state=${state}`;
  }, []);
  return { connectGitHub };
}
function useDisconnectGitHub() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: () => fetchWithAuth("/api/github/disconnect", { method: "POST" }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["github", "status"] });
      queryClient.removeQueries({ queryKey: ["github", "repos"] });
    }
  });
}
function useGitHubRepos(page = 1, perPage = 30) {
  return useQuery({
    queryKey: ["github", "repos", page, perPage],
    queryFn: () => fetchWithAuth(`/api/github/repos?page=${page}&per_page=${perPage}`),
    enabled: true,
    // Only fetch if user is connected
    staleTime: 3e5
    // 5 minutes
  });
}
function useGitHubRepo(owner, repo, enabled = true) {
  return useQuery({
    queryKey: ["github", "repo", owner, repo],
    queryFn: () => fetchWithAuth(`/api/github/repos/${owner}/${repo}`),
    enabled: enabled && !!owner && !!repo,
    staleTime: 3e5
    // 5 minutes
  });
}
function useGitHubBranches(owner, repo, enabled = true) {
  return useQuery({
    queryKey: ["github", "branches", owner, repo],
    queryFn: () => fetchWithAuth(`/api/github/repos/${owner}/${repo}/branches`),
    enabled: enabled && !!owner && !!repo,
    staleTime: 6e4
    // 1 minute
  });
}

export { ALMADAR_DND_MIME, DEFAULT_SLOTS, I18nProvider, clearEntities, createTranslate, getAllEntities, getByType, getEntity, getSingleton, parseQueryBinding, removeEntity, spawnEntity, updateEntity, updateSingleton, useAgentChat, useAuthContext, useCompile, useConnectGitHub, useDeepAgentGeneration, useDisconnectGitHub, useDragReorder, useDraggable, useDropZone, useEmitEvent, useEntities, useEntitiesByType, useEntity as useEntityById, useEventBus, useEventListener, useExtensions, useFileEditor, useFileSystem, useGitHubBranches, useGitHubRepo, useGitHubRepos, useGitHubStatus, useInfiniteScroll, useInput, useLongPress, useOrbitalHistory, usePhysics, usePinchZoom, usePlayer, usePreview, usePullToRefresh, useQuerySingleton, useSingletonEntity, useSwipeGesture, useTraitListens, useTranslate, useUIEvents, useUISlotManager, useValidation };
