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