"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const React = require("react");
const index_browser = require("../_vendor/nanoid/index.browser.cjs");
const core = require("../types/core.cjs");
function useOpenRouterChat({
  config,
  onMessageUpdate,
  onMessageComplete,
  onError
}) {
  const [isStreaming, setIsStreaming] = React.useState(false);
  const [currentStreamingMessageId, setCurrentStreamingMessageId] = React.useState(null);
  const abortControllerRef = React.useRef(null);
  const sendMessage = React.useCallback(
    async (content, conversationHistory = []) => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
      abortControllerRef.current = new AbortController();
      const messageId = index_browser.nanoid();
      setCurrentStreamingMessageId(messageId);
      setIsStreaming(true);
      const aiMessage = {
        id: messageId,
        content: "",
        role: core.Role.Assistant,
        timestamp: (/* @__PURE__ */ new Date()).toISOString(),
        createdAt: (/* @__PURE__ */ new Date()).toISOString(),
        status: core.Status.Streaming,
        version: 1,
        isStreaming: true
      };
      try {
        const messages = [
          ...conversationHistory.map((msg) => ({
            role: msg.role,
            content: msg.content
          })),
          {
            role: core.Role.User,
            content
          }
        ];
        const response = await fetch(
          config.baseUrl || "https://openrouter.ai/api/v1/chat/completions",
          {
            method: "POST",
            headers: {
              Authorization: `Bearer ${config.apiKey}`,
              "Content-Type": "application/json",
              "HTTP-Referer": window.location.origin,
              "X-Title": "Design System AI Assistant Demo"
            },
            body: JSON.stringify({
              model: config.model || "openai/gpt-3.5-turbo",
              messages,
              stream: true,
              temperature: 0.7,
              max_tokens: 1e3
            }),
            signal: abortControllerRef.current.signal
          }
        );
        if (!response.ok) {
          throw new Error(`OpenRouter API error: ${response.status} ${response.statusText}`);
        }
        const reader = response.body?.getReader();
        const decoder = new TextDecoder();
        if (!reader) {
          throw new Error("No response body reader available");
        }
        let accumulatedContent = "";
        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            break;
          }
          const chunk = decoder.decode(value);
          const lines = chunk.split("\n");
          for (const line of lines) {
            if (line.startsWith("data: ")) {
              const data = line.slice(6).trim();
              if (data === "[DONE]") {
                const finalMessage2 = {
                  ...aiMessage,
                  content: accumulatedContent,
                  isStreaming: false,
                  status: core.Status.Completed
                };
                onMessageComplete?.(finalMessage2);
                setIsStreaming(false);
                setCurrentStreamingMessageId(null);
                return finalMessage2;
              }
              try {
                const parsed = JSON.parse(data);
                const deltaContent = parsed.choices?.[0]?.delta?.content;
                if (deltaContent) {
                  accumulatedContent += deltaContent;
                  const updatedMessage = {
                    ...aiMessage,
                    content: accumulatedContent,
                    isStreaming: true
                  };
                  onMessageUpdate?.(updatedMessage);
                }
                if (parsed.choices?.[0]?.finish_reason) {
                  const finalMessage2 = {
                    ...aiMessage,
                    content: accumulatedContent,
                    isStreaming: false,
                    status: core.Status.Completed
                  };
                  onMessageComplete?.(finalMessage2);
                  setIsStreaming(false);
                  setCurrentStreamingMessageId(null);
                  return finalMessage2;
                }
              } catch (parseError) {
                console.warn("Failed to parse streaming response:", parseError);
              }
            }
          }
        }
        const finalMessage = {
          ...aiMessage,
          content: accumulatedContent,
          isStreaming: false,
          status: core.Status.Completed
        };
        onMessageComplete?.(finalMessage);
        return finalMessage;
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
        const errorResponse = {
          id: messageId,
          content: `Error: ${errorMessage}`,
          role: core.Role.Assistant,
          timestamp: (/* @__PURE__ */ new Date()).toISOString(),
          createdAt: (/* @__PURE__ */ new Date()).toISOString(),
          status: core.Status.Failed,
          version: 1,
          isStreaming: false
        };
        onError?.(error instanceof Error ? error : new Error(errorMessage));
        setIsStreaming(false);
        setCurrentStreamingMessageId(null);
        return errorResponse;
      }
    },
    [config, onMessageUpdate, onMessageComplete, onError]
  );
  const stopStreaming = React.useCallback(() => {
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
      setIsStreaming(false);
      setCurrentStreamingMessageId(null);
    }
  }, []);
  return {
    sendMessage,
    stopStreaming,
    isStreaming,
    currentStreamingMessageId
  };
}
exports.useOpenRouterChat = useOpenRouterChat;
//# sourceMappingURL=use-openrouter-chat.cjs.map
