"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const react = require("../../../_vendor/@legendapp/state/react.cjs");
const index_browser = require("../../../_vendor/nanoid/index.browser.cjs");
const React = require("react");
const paginationStore = require("../../../stores/pagination-store.cjs");
const messageStore = require("../../../stores/message-store.cjs");
const core = require("../../../types/core.cjs");
function usePagination({
  chatId,
  onLoadMessages,
  scrollContainerRef,
  pageSize = 10
}) {
  const hasMore = react.use$(paginationStore.paginationStore$.hasMore);
  const isLoading = react.use$(paginationStore.paginationStore$.isLoading);
  react.use$(paginationStore.paginationStore$.currentPage);
  const loadMessagesRef = React.useRef(onLoadMessages);
  loadMessagesRef.current = onLoadMessages;
  const loadInitialMessages = React.useCallback(async () => {
    if (!chatId) return;
    try {
      paginationStore.paginationActions.setPaginationLoading(true);
      const result = await loadMessagesRef.current({
        chatId,
        page: 1,
        pageSize
      });
      messageStore.messageActions.loadMessages(result.messages || result.items || [], false);
      const currentMessages = messageStore.messageComputed$.currentMessages();
      const actualTotalCount = Math.max(result.totalCount || 0, currentMessages.length);
      const actualHasMore = result.hasMore || actualTotalCount > pageSize && currentMessages.length < actualTotalCount;
      paginationStore.paginationActions.updatePagination(actualHasMore, actualTotalCount, result.nextCursor, true);
    } catch (error) {
      console.error("Failed to load initial messages:", error);
      paginationStore.paginationActions.loadError();
    } finally {
      paginationStore.paginationActions.setPaginationLoading(false);
    }
  }, [chatId, pageSize]);
  const loadMoreMessages = React.useCallback(async () => {
    if (!chatId || isLoading || !hasMore) return;
    try {
      paginationStore.paginationActions.setPaginationLoading(true);
      const latestMessages = messageStore.messageComputed$.currentMessages();
      const earliestMessage = latestMessages[0];
      const before = earliestMessage?.id;
      const currentPageNumber = paginationStore.paginationStore$.currentPage.peek();
      const result = await loadMessagesRef.current({
        chatId,
        page: currentPageNumber + 1,
        pageSize,
        before
        // 用于确保连续性
      });
      messageStore.messageActions.appendMessages(result.messages || result.items || [], "start");
      const actualTotalCount = Math.max(result.totalCount || 0, paginationStore.paginationStore$.totalCount.peek());
      paginationStore.paginationActions.updatePagination(result.hasMore, actualTotalCount, result.nextCursor, false);
    } catch (error) {
      console.error("Failed to load more messages:", error);
      paginationStore.paginationActions.loadError();
    } finally {
      paginationStore.paginationActions.setPaginationLoading(false);
    }
  }, [chatId, isLoading, hasMore, pageSize]);
  const scrollToNewMessages = React.useCallback(
    (newCount) => {
      if (!scrollContainerRef.current || newCount === 0) return;
      requestAnimationFrame(() => {
        const container = scrollContainerRef.current;
        if (!container) return;
        const estimatedHeight = newCount * 120;
        container.scrollTop = estimatedHeight;
      });
    },
    [scrollContainerRef]
  );
  const handleNewMessage = React.useCallback(
    async (messageContent) => {
      if (!chatId) return;
      const newMessage = {
        id: index_browser.nanoid(),
        content: messageContent,
        role: core.Role.User,
        timestamp: (/* @__PURE__ */ new Date()).toISOString(),
        isStreaming: false,
        status: core.Status.Pending,
        createdAt: (/* @__PURE__ */ new Date()).toISOString(),
        version: 1
      };
      messageStore.messageActions.addMessage(newMessage);
      const currentMessageCount = messageStore.messageComputed$.currentMessages().length;
      if (currentMessageCount > pageSize * 3) {
        console.info(`当前已加载 ${currentMessageCount} 条消息，建议重置到最新消息以优化性能`);
      }
    },
    [chatId, pageSize]
  );
  React.useEffect(() => {
    if (chatId) {
      messageStore.messageActions.resetMessages();
      paginationStore.paginationActions.resetPagination();
      loadInitialMessages();
    }
  }, [chatId, loadInitialMessages]);
  return {
    loadMoreMessages,
    loadInitialMessages,
    scrollToNewMessages,
    isLoading,
    hasMore,
    handleNewMessage
  };
}
exports.usePagination = usePagination;
//# sourceMappingURL=use-pagination.cjs.map
