"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/hooks/useChatbot.ts
var useChatbot_exports = {};
__export(useChatbot_exports, {
  createUseChatbot: () => createUseChatbot
});
module.exports = __toCommonJS(useChatbot_exports);
var import_react = require("react");

// src/types/chatbot.ts
var CHATBOT_MESSAGE_ROLES = {
  USER: "user",
  ASSISTANT: "assistant"
};

// src/hooks/useChatbot.ts
var DEFAULT_CONVERSATIONS_PAGE_SIZE = 20;
var DEFAULT_MESSAGES_PAGE_SIZE = 50;
var placeholderCounter = 0;
function generatePlaceholderId() {
  const globalCrypto = globalThis.crypto;
  if (globalCrypto && typeof globalCrypto.randomUUID === "function") {
    return `pending-${globalCrypto.randomUUID()}`;
  }
  placeholderCounter += 1;
  return `pending-${Date.now()}-${placeholderCounter}`;
}
function replacePlaceholder(prev, placeholderId, result) {
  return [
    ...prev.filter((m) => m.id !== placeholderId),
    result.userMessage,
    result.assistantMessage
  ];
}
function removePlaceholder(prev, placeholderId) {
  return prev.filter((m) => m.id !== placeholderId);
}
function removeById(items, id) {
  return items.filter((item) => item.id !== id);
}
function toUserErrorMessage(_err, fallback) {
  return fallback;
}
function createUseChatbot(resolver) {
  const resolveClient = typeof resolver === "function" ? resolver : () => resolver;
  return function useChatbot() {
    const [isOpen, setIsOpen] = (0, import_react.useState)(false);
    const [isSending, setIsSending] = (0, import_react.useState)(false);
    const [isLoadingHistory, setIsLoadingHistory] = (0, import_react.useState)(false);
    const [isLoadingMessages, setIsLoadingMessages] = (0, import_react.useState)(false);
    const [errorMessage, setErrorMessage] = (0, import_react.useState)(null);
    const [conversations, setConversations] = (0, import_react.useState)(
      []
    );
    const [activeConversationId, setActiveConversationId] = (0, import_react.useState)(null);
    const [messages, setMessages] = (0, import_react.useState)([]);
    const apiClientRef = (0, import_react.useRef)(resolveClient());
    apiClientRef.current = resolveClient();
    const mountedRef = (0, import_react.useRef)(false);
    (0, import_react.useEffect)(() => {
      mountedRef.current = true;
      return () => {
        mountedRef.current = false;
      };
    }, []);
    const conversationsSeqRef = (0, import_react.useRef)(0);
    const messagesSeqRef = (0, import_react.useRef)(0);
    const isSendingRef = (0, import_react.useRef)(false);
    const invalidateMessagesLoad = () => {
      messagesSeqRef.current += 1;
      setIsLoadingMessages(false);
    };
    const loadConversations = (0, import_react.useCallback)(async () => {
      const seq = ++conversationsSeqRef.current;
      setIsLoadingHistory(true);
      setErrorMessage(null);
      try {
        const result = await apiClientRef.current.listConversations({
          page: 1,
          limit: DEFAULT_CONVERSATIONS_PAGE_SIZE
        });
        if (!mountedRef.current || seq !== conversationsSeqRef.current) return;
        setConversations(result.conversations);
      } catch (err) {
        if (!mountedRef.current || seq !== conversationsSeqRef.current) return;
        setErrorMessage(toUserErrorMessage(err, "Falha ao carregar conversas"));
      } finally {
        if (mountedRef.current && seq === conversationsSeqRef.current) {
          setIsLoadingHistory(false);
        }
      }
    }, []);
    const loadMessages = (0, import_react.useCallback)(async (conversationId) => {
      const seq = ++messagesSeqRef.current;
      setIsLoadingMessages(true);
      setErrorMessage(null);
      try {
        const result = await apiClientRef.current.getMessages(conversationId, {
          page: 1,
          limit: DEFAULT_MESSAGES_PAGE_SIZE
        });
        if (!mountedRef.current || seq !== messagesSeqRef.current) return;
        setMessages(result.messages);
      } catch (err) {
        if (!mountedRef.current || seq !== messagesSeqRef.current) return;
        setErrorMessage(toUserErrorMessage(err, "Falha ao carregar mensagens"));
      } finally {
        if (mountedRef.current && seq === messagesSeqRef.current) {
          setIsLoadingMessages(false);
        }
      }
    }, []);
    const openPanel = (0, import_react.useCallback)(() => {
      setIsOpen(true);
      void loadConversations();
    }, [loadConversations]);
    const closePanel = (0, import_react.useCallback)(() => {
      setIsOpen(false);
    }, []);
    const togglePanel = (0, import_react.useCallback)(() => {
      setIsOpen((prev) => {
        if (!prev) void loadConversations();
        return !prev;
      });
    }, [loadConversations]);
    const selectConversation = (0, import_react.useCallback)(
      (id) => {
        setActiveConversationId(id);
        if (id) {
          void loadMessages(id);
        } else {
          invalidateMessagesLoad();
          setMessages([]);
        }
      },
      [loadMessages]
    );
    const startNewConversation = (0, import_react.useCallback)(() => {
      invalidateMessagesLoad();
      setActiveConversationId(null);
      setMessages([]);
    }, []);
    const sendMessage = (0, import_react.useCallback)(
      async (text, currentContext) => {
        const trimmed = text.trim();
        if (!trimmed || isSendingRef.current) return;
        isSendingRef.current = true;
        const sendSeq = messagesSeqRef.current;
        const placeholderId = generatePlaceholderId();
        const placeholder = {
          id: placeholderId,
          conversationId: activeConversationId ?? "",
          role: CHATBOT_MESSAGE_ROLES.USER,
          content: trimmed,
          createdAt: /* @__PURE__ */ new Date()
        };
        setMessages((prev) => [...prev, placeholder]);
        setIsSending(true);
        setErrorMessage(null);
        try {
          const result = await apiClientRef.current.sendMessage({
            message: trimmed,
            conversationId: activeConversationId ?? void 0,
            currentContext
          });
          if (!mountedRef.current) return;
          if (sendSeq !== messagesSeqRef.current) {
            void loadConversations();
            return;
          }
          setMessages(
            (prev) => replacePlaceholder(prev, placeholderId, result)
          );
          setActiveConversationId(result.conversationId);
          void loadConversations();
        } catch (err) {
          if (!mountedRef.current) return;
          if (sendSeq !== messagesSeqRef.current) return;
          setMessages((prev) => removePlaceholder(prev, placeholderId));
          setErrorMessage(toUserErrorMessage(err, "Falha ao enviar mensagem"));
        } finally {
          isSendingRef.current = false;
          if (mountedRef.current) setIsSending(false);
        }
      },
      [activeConversationId, loadConversations]
    );
    const deleteConversation = (0, import_react.useCallback)(
      async (id) => {
        setErrorMessage(null);
        try {
          await apiClientRef.current.deleteConversation(id);
          if (!mountedRef.current) return;
          setConversations((prev) => removeById(prev, id));
          if (activeConversationId === id) {
            invalidateMessagesLoad();
            setActiveConversationId(null);
            setMessages([]);
          }
        } catch (err) {
          if (!mountedRef.current) return;
          setErrorMessage(toUserErrorMessage(err, "Falha ao excluir conversa"));
        }
      },
      [activeConversationId]
    );
    return {
      isOpen,
      isSending,
      isLoadingHistory,
      isLoadingMessages,
      errorMessage,
      conversations,
      activeConversationId,
      messages,
      openPanel,
      closePanel,
      togglePanel,
      selectConversation,
      startNewConversation,
      sendMessage,
      deleteConversation,
      reloadConversations: loadConversations
    };
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  createUseChatbot
});
//# sourceMappingURL=index.js.map