import {
  Suggestions
} from "./chunk-226ZMOE3.mjs";
import {
  ImageUploadQueue
} from "./chunk-PLHTVHUW.mjs";
import {
  Input
} from "./chunk-DTRPPNSA.mjs";
import {
  Messages
} from "./chunk-NGA4T3VT.mjs";
import {
  RenderMessage
} from "./chunk-WRQST6DJ.mjs";
import {
  UserMessage
} from "./chunk-VVL6JFCJ.mjs";
import {
  AssistantMessage
} from "./chunk-X477GDGZ.mjs";
import {
  ImageRenderer
} from "./chunk-DBKRAOH7.mjs";
import {
  ChatContext,
  ChatContextProvider
} from "./chunk-IEMQ2SQW.mjs";
import {
  __async,
  __spreadProps,
  __spreadValues
} from "./chunk-MRXNTQOX.mjs";

// src/components/chat/Chat.tsx
import React, { useEffect, useRef, useState, useCallback, useMemo } from "react";
import {
  useCopilotChatInternal as useCopilotChat,
  useCopilotContext,
  useCopilotMessagesContext
} from "@copilotkit/react-core";
import {
  CopilotKitError,
  CopilotKitErrorCode,
  Severity,
  ErrorVisibility,
  styledConsole
} from "@copilotkit/shared";
import { randomId } from "@copilotkit/shared";
import { runAgent, stopAgent } from "@copilotkit/react-core";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
function CopilotChat({
  instructions,
  suggestions = "auto",
  onSubmitMessage,
  makeSystemMessage,
  disableSystemMessage,
  onInProgress,
  onStopGeneration,
  onReloadMessages,
  onRegenerate,
  onCopy,
  onThumbsUp,
  onThumbsDown,
  markdownTagRenderers,
  Messages: Messages2 = Messages,
  RenderMessage: RenderMessage2 = RenderMessage,
  RenderSuggestionsList = Suggestions,
  Input: Input2 = Input,
  className,
  icons,
  labels,
  AssistantMessage: AssistantMessage2 = AssistantMessage,
  UserMessage: UserMessage2 = UserMessage,
  ImageRenderer: ImageRenderer2 = ImageRenderer,
  ErrorMessage,
  imageUploadsEnabled,
  inputFileAccept = "image/*",
  hideStopButton,
  observabilityHooks,
  renderError,
  onError,
  // Legacy props - deprecated
  RenderTextMessage,
  RenderActionExecutionMessage,
  RenderAgentStateMessage,
  RenderResultMessage,
  RenderImageMessage
}) {
  const {
    additionalInstructions,
    setChatInstructions,
    copilotApiConfig,
    setBannerError,
    setInternalErrorHandler,
    removeInternalErrorHandler
  } = useCopilotContext();
  const { publicApiKey, chatApiEndpoint } = copilotApiConfig;
  const [selectedImages, setSelectedImages] = useState([]);
  const [chatError, setChatError] = useState(null);
  const fileInputRef = useRef(null);
  const triggerObservabilityHook = useCallback(
    (hookName, ...args) => {
      if (publicApiKey && (observabilityHooks == null ? void 0 : observabilityHooks[hookName])) {
        observabilityHooks[hookName](...args);
      }
      if ((observabilityHooks == null ? void 0 : observabilityHooks[hookName]) && !publicApiKey) {
        setBannerError(
          new CopilotKitError({
            message: "observabilityHooks requires a publicApiKey to function.",
            code: CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,
            severity: Severity.CRITICAL,
            visibility: ErrorVisibility.BANNER
          })
        );
        styledConsole.publicApiKeyRequired("observabilityHooks");
      }
    },
    [publicApiKey, observabilityHooks, setBannerError]
  );
  const triggerChatError = useCallback(
    (error, operation, originalError) => {
      const errorMessage = (error == null ? void 0 : error.message) || (error == null ? void 0 : error.toString()) || "An error occurred";
      setChatError({
        message: errorMessage,
        operation,
        timestamp: Date.now()
      });
      const errorEvent = {
        type: "error",
        timestamp: Date.now(),
        context: {
          source: "ui",
          request: {
            operation,
            url: chatApiEndpoint,
            startTime: Date.now()
          },
          technical: {
            environment: "browser",
            userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
            stackTrace: originalError instanceof Error ? originalError.stack : void 0
          }
        },
        error
      };
      if (onError) {
        onError(errorEvent);
      }
      if (publicApiKey && (observabilityHooks == null ? void 0 : observabilityHooks.onError)) {
        observabilityHooks.onError(errorEvent);
      }
      if ((observabilityHooks == null ? void 0 : observabilityHooks.onError) && !publicApiKey) {
        setBannerError(
          new CopilotKitError({
            message: "observabilityHooks.onError requires a publicApiKey to function.",
            code: CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,
            severity: Severity.CRITICAL,
            visibility: ErrorVisibility.BANNER
          })
        );
        styledConsole.publicApiKeyRequired("observabilityHooks.onError");
      }
    },
    [publicApiKey, chatApiEndpoint, observabilityHooks, setBannerError]
  );
  useEffect(() => {
    const id = "chat-component";
    setInternalErrorHandler({
      [id]: (error) => {
        if (!error)
          return;
        triggerChatError(error.error, "sendMessage");
      }
    });
    return () => {
      removeInternalErrorHandler == null ? void 0 : removeInternalErrorHandler(id);
    };
  }, [triggerChatError, setInternalErrorHandler, removeInternalErrorHandler]);
  useEffect(() => {
    if (!imageUploadsEnabled)
      return;
    const handlePaste = (e) => __async(this, null, function* () {
      var _a, _b;
      const target = e.target;
      if (!((_a = target.parentElement) == null ? void 0 : _a.classList.contains("copilotKitInput")))
        return;
      const items = Array.from(((_b = e.clipboardData) == null ? void 0 : _b.items) || []);
      const imageItems = items.filter((item) => item.type.startsWith("image/"));
      if (imageItems.length === 0)
        return;
      e.preventDefault();
      const imagePromises = imageItems.map((item) => {
        const file = item.getAsFile();
        if (!file)
          return Promise.resolve(null);
        return new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.onload = (e2) => {
            var _a2, _b2;
            const base64String = (_b2 = (_a2 = e2.target) == null ? void 0 : _a2.result) == null ? void 0 : _b2.split(",")[1];
            if (base64String) {
              resolve({
                contentType: file.type,
                bytes: base64String
              });
            } else {
              resolve(null);
            }
          };
          reader.onerror = reject;
          reader.readAsDataURL(file);
        });
      });
      try {
        const loadedImages = (yield Promise.all(imagePromises)).filter((img) => img !== null);
        setSelectedImages((prev) => [...prev, ...loadedImages]);
      } catch (error) {
        triggerChatError(error, "processClipboardImages", error);
        console.error("Error processing pasted images:", error);
      }
    });
    document.addEventListener("paste", handlePaste);
    return () => document.removeEventListener("paste", handlePaste);
  }, [imageUploadsEnabled, triggerChatError]);
  useEffect(() => {
    if (!(additionalInstructions == null ? void 0 : additionalInstructions.length)) {
      setChatInstructions(instructions || "");
      return;
    }
    const combinedAdditionalInstructions = [
      instructions,
      "Additionally, follow these instructions:",
      ...additionalInstructions.map((instruction) => `- ${instruction}`)
    ];
    setChatInstructions(combinedAdditionalInstructions.join("\n") || "");
  }, [instructions, additionalInstructions]);
  const {
    messages,
    isLoading,
    sendMessage,
    stopGeneration,
    reloadMessages,
    suggestions: currentSuggestions
  } = useCopilotChatLogic(
    suggestions,
    makeSystemMessage,
    disableSystemMessage,
    onInProgress,
    onSubmitMessage,
    onStopGeneration,
    onReloadMessages
  );
  const prevIsLoading = useRef(isLoading);
  useEffect(() => {
    if (prevIsLoading.current !== isLoading) {
      if (isLoading) {
        triggerObservabilityHook("onChatStarted");
      } else {
        triggerObservabilityHook("onChatStopped");
      }
      prevIsLoading.current = isLoading;
    }
  }, [isLoading, triggerObservabilityHook]);
  const handleSendMessage = (text) => {
    const images = selectedImages;
    setSelectedImages([]);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
    triggerObservabilityHook("onMessageSent", text);
    return sendMessage(text, images);
  };
  const chatContext = React.useContext(ChatContext);
  const isVisible = chatContext ? chatContext.open : true;
  const handleRegenerate = (messageId) => {
    if (onRegenerate) {
      onRegenerate(messageId);
    }
    triggerObservabilityHook("onMessageRegenerated", messageId);
    reloadMessages(messageId);
  };
  const handleCopy = (message) => {
    if (onCopy) {
      onCopy(message);
    }
    triggerObservabilityHook("onMessageCopied", message);
  };
  const handleImageUpload = (event) => __async(this, null, function* () {
    if (!event.target.files || event.target.files.length === 0) {
      return;
    }
    const files = Array.from(event.target.files).filter((file) => file.type.startsWith("image/"));
    if (files.length === 0)
      return;
    const fileReadPromises = files.map((file) => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
          var _a, _b;
          const base64String = ((_b = (_a = e.target) == null ? void 0 : _a.result) == null ? void 0 : _b.split(",")[1]) || "";
          if (base64String) {
            resolve({
              contentType: file.type,
              bytes: base64String
            });
          }
        };
        reader.onerror = reject;
        reader.readAsDataURL(file);
      });
    });
    try {
      const loadedImages = yield Promise.all(fileReadPromises);
      setSelectedImages((prev) => [...prev, ...loadedImages]);
    } catch (error) {
      triggerChatError(error, "processUploadedImages", error);
      console.error("Error reading files:", error);
    }
  });
  const removeSelectedImage = (index) => {
    setSelectedImages((prev) => prev.filter((_, i) => i !== index));
  };
  const handleThumbsUp = (message) => {
    if (onThumbsUp) {
      onThumbsUp(message);
    }
    triggerObservabilityHook("onFeedbackGiven", message.id, "thumbsUp");
  };
  const handleThumbsDown = (message) => {
    if (onThumbsDown) {
      onThumbsDown(message);
    }
    triggerObservabilityHook("onFeedbackGiven", message.id, "thumbsDown");
  };
  return /* @__PURE__ */ jsxs(WrappedCopilotChat, { icons, labels, className, children: [
    chatError && renderError && renderError(__spreadProps(__spreadValues({}, chatError), {
      onDismiss: () => setChatError(null),
      onRetry: () => {
        setChatError(null);
      }
    })),
    /* @__PURE__ */ jsx(
      Messages2,
      {
        AssistantMessage: AssistantMessage2,
        UserMessage: UserMessage2,
        RenderMessage: RenderMessage2,
        messages,
        inProgress: isLoading,
        onRegenerate: handleRegenerate,
        onCopy: handleCopy,
        onThumbsUp: handleThumbsUp,
        onThumbsDown: handleThumbsDown,
        markdownTagRenderers,
        ImageRenderer: ImageRenderer2,
        ErrorMessage,
        chatError,
        RenderTextMessage,
        RenderActionExecutionMessage,
        RenderAgentStateMessage,
        RenderResultMessage,
        RenderImageMessage,
        children: currentSuggestions.length > 0 && /* @__PURE__ */ jsx(
          RenderSuggestionsList,
          {
            onSuggestionClick: handleSendMessage,
            suggestions: currentSuggestions
          }
        )
      }
    ),
    imageUploadsEnabled && /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(ImageUploadQueue, { images: selectedImages, onRemoveImage: removeSelectedImage }),
      /* @__PURE__ */ jsx(
        "input",
        {
          type: "file",
          multiple: true,
          ref: fileInputRef,
          onChange: handleImageUpload,
          accept: inputFileAccept,
          style: { display: "none" }
        }
      )
    ] }),
    /* @__PURE__ */ jsx(
      Input2,
      {
        inProgress: isLoading,
        onSend: handleSendMessage,
        isVisible,
        onStop: stopGeneration,
        onUpload: imageUploadsEnabled ? () => {
          var _a;
          return (_a = fileInputRef.current) == null ? void 0 : _a.click();
        } : void 0,
        hideStopButton
      }
    )
  ] });
}
function WrappedCopilotChat({
  children,
  icons,
  labels,
  className
}) {
  const chatContext = React.useContext(ChatContext);
  if (!chatContext) {
    return /* @__PURE__ */ jsx(ChatContextProvider, { icons, labels, open: true, setOpen: () => {
    }, children: /* @__PURE__ */ jsx("div", { className: `copilotKitChat ${className != null ? className : ""}`, children }) });
  }
  return /* @__PURE__ */ jsx(Fragment, { children });
}
var useCopilotChatLogic = (chatSuggestions, makeSystemMessage, disableSystemMessage, onInProgress, onSubmitMessage, onStopGeneration, onReloadMessages) => {
  var _a;
  const {
    messages,
    sendMessage,
    setMessages,
    reloadMessages: defaultReloadMessages,
    stopGeneration: defaultStopGeneration,
    runChatCompletion,
    isLoading,
    suggestions,
    setSuggestions,
    generateSuggestions,
    resetSuggestions: resetSuggestionsFromHook,
    isLoadingSuggestions
  } = useCopilotChat({
    makeSystemMessage,
    disableSystemMessage
  });
  const generalContext = useCopilotContext();
  const messagesContext = useCopilotMessagesContext();
  const { actions } = generalContext;
  const [suggestionsFailed, setSuggestionsFailed] = useState(false);
  const hasGeneratedInitialSuggestions = useRef(false);
  useEffect(() => {
    if (Array.isArray(chatSuggestions)) {
      setSuggestions(chatSuggestions);
      hasGeneratedInitialSuggestions.current = true;
    }
  }, [JSON.stringify(chatSuggestions), setSuggestions]);
  const generateSuggestionsWithErrorHandling = useCallback(
    (context) => __async(void 0, null, function* () {
      try {
        yield generateSuggestions();
      } catch (error) {
        console.error("Failed to generate suggestions:", error);
        setSuggestionsFailed(true);
      }
    }),
    [generateSuggestions]
  );
  useEffect(() => {
    if (chatSuggestions !== "auto" || isLoadingSuggestions || suggestionsFailed) {
      return;
    }
    if (isLoading) {
      return;
    }
    if (Object.keys(generalContext.chatSuggestionConfiguration).length === 0) {
      return;
    }
    if (messages.length === 0 && !hasGeneratedInitialSuggestions.current) {
      hasGeneratedInitialSuggestions.current = true;
      generateSuggestionsWithErrorHandling("initial");
      return;
    }
    if (messages.length > 0 && suggestions.length === 0) {
      generateSuggestionsWithErrorHandling("post-message");
      return;
    }
  }, [
    chatSuggestions,
    isLoadingSuggestions,
    suggestionsFailed,
    messages.length,
    isLoading,
    suggestions.length,
    Object.keys(generalContext.chatSuggestionConfiguration).join(","),
    // Use stable string instead of object reference
    generateSuggestionsWithErrorHandling
  ]);
  useEffect(() => {
    if (chatSuggestions !== "auto") {
      hasGeneratedInitialSuggestions.current = false;
      setSuggestionsFailed(false);
    }
  }, [chatSuggestions]);
  const stableContext = useMemo(
    () => __spreadValues(__spreadValues({}, generalContext), messagesContext),
    [
      // Only include stable dependencies
      generalContext.actions,
      messagesContext.messages.length,
      generalContext.isLoading
    ]
  );
  const resetSuggestions = useCallback(() => {
    resetSuggestionsFromHook();
    setSuggestionsFailed(false);
    hasGeneratedInitialSuggestions.current = false;
  }, [resetSuggestionsFromHook]);
  useEffect(() => {
    onInProgress == null ? void 0 : onInProgress(isLoading);
  }, [onInProgress, isLoading]);
  const safelySendMessage = (messageContent, imagesToUse) => __async(void 0, null, function* () {
    const images = imagesToUse || [];
    if (chatSuggestions === "auto" || chatSuggestions === "manual") {
      setSuggestions([]);
    }
    let firstMessage = null;
    if (messageContent.trim().length > 0) {
      const textMessage = {
        id: randomId(),
        role: "user",
        content: messageContent
      };
      if (onSubmitMessage) {
        try {
          yield onSubmitMessage(messageContent);
        } catch (error) {
          console.error("Error in onSubmitMessage:", error);
        }
      }
      yield sendMessage(textMessage, {
        followUp: images.length === 0,
        clearSuggestions: chatSuggestions === "auto" || chatSuggestions === "manual"
      });
      if (!firstMessage) {
        firstMessage = textMessage;
      }
    }
    if (images.length > 0) {
      for (let i = 0; i < images.length; i++) {
        const imageMessage = {
          id: randomId(),
          role: "user",
          image: {
            format: images[i].contentType.replace("image/", ""),
            bytes: images[i].bytes
          }
        };
        yield sendMessage(imageMessage, { followUp: i === images.length - 1 });
        if (!firstMessage) {
          firstMessage = imageMessage;
        }
      }
    }
    if (!firstMessage) {
      return { role: "user", content: "", id: randomId() };
    }
    return firstMessage;
  });
  const currentAgentName = (_a = generalContext.agentSession) == null ? void 0 : _a.agentName;
  const restartCurrentAgent = (hint) => __async(void 0, null, function* () {
    if (generalContext.agentSession) {
      generalContext.setAgentSession(__spreadProps(__spreadValues({}, generalContext.agentSession), {
        nodeName: void 0,
        threadId: void 0
      }));
      generalContext.setCoagentStates((prevAgentStates) => {
        return __spreadProps(__spreadValues({}, prevAgentStates), {
          [generalContext.agentSession.agentName]: __spreadProps(__spreadValues({}, prevAgentStates[generalContext.agentSession.agentName]), {
            threadId: void 0,
            nodeName: void 0,
            runId: void 0
          })
        });
      });
    }
  });
  const runCurrentAgent = (hint) => __async(void 0, null, function* () {
    if (generalContext.agentSession) {
      yield runAgent(
        generalContext.agentSession.agentName,
        stableContext,
        messagesContext.messages,
        sendMessage,
        runChatCompletion
      );
    }
  });
  const stopCurrentAgent = () => {
    if (generalContext.agentSession) {
      stopAgent(generalContext.agentSession.agentName, stableContext);
    }
  };
  const setCurrentAgentState = (state) => {
    if (generalContext.agentSession) {
      generalContext.setCoagentStates((prevAgentStates) => {
        return __spreadProps(__spreadValues({}, prevAgentStates), {
          [generalContext.agentSession.agentName]: {
            state
          }
        });
      });
    }
  };
  function stopGeneration() {
    setSuggestions([]);
    if (onStopGeneration) {
      onStopGeneration({
        messages,
        setMessages,
        stopGeneration: defaultStopGeneration,
        currentAgentName,
        restartCurrentAgent,
        stopCurrentAgent,
        runCurrentAgent,
        setCurrentAgentState
      });
    } else {
      defaultStopGeneration();
    }
  }
  function reloadMessages(messageId) {
    if (onReloadMessages) {
      onReloadMessages({
        messages,
        setMessages,
        stopGeneration: defaultStopGeneration,
        currentAgentName,
        restartCurrentAgent,
        stopCurrentAgent,
        runCurrentAgent,
        setCurrentAgentState,
        messageId
      });
    } else {
      defaultReloadMessages(messageId);
    }
  }
  return {
    messages,
    isLoading,
    suggestions,
    sendMessage: safelySendMessage,
    stopGeneration,
    reloadMessages,
    resetSuggestions,
    context: stableContext,
    actions
  };
};

export {
  CopilotChat,
  WrappedCopilotChat,
  useCopilotChatLogic
};
//# sourceMappingURL=chunk-NJY6RHHQ.mjs.map