/**
 * Phase 2: 逐篇精读状态管理Hook
 */

import { useState, useCallback } from 'react'
import { Document } from '../types/index'
import { ChatMessage } from '../types/chat'

export function useDeepReadState(initialDocs: Document[]) {
  const [selectedDocs, setSelectedDocs] = useState<Document[]>(initialDocs)
  const [currentDocId, setCurrentDocId] = useState<string>(initialDocs[0]?.id || '')
  const [conversationMap, setConversationMap] = useState<Map<string, ChatMessage[]>>(
    new Map(initialDocs.map(doc => [doc.id, []]))
  )

  // 获取当前文献
  const currentDoc = selectedDocs.find(doc => doc.id === currentDocId)

  // 获取当前对话
  const currentConversation = conversationMap.get(currentDocId) || []

  // 切换文献
  const switchDocument = useCallback((newDocId: string) => {
    setCurrentDocId(newDocId)
  }, [])

  // 添加消息到当前文献
  const addMessage = useCallback((message: ChatMessage) => {
    setConversationMap(prev => {
      const newMap = new Map(prev)
      const messages = newMap.get(currentDocId) || []
      newMap.set(currentDocId, [...messages, message])
      return newMap
    })
  }, [currentDocId])

  // 清空当前文献对话
  const clearCurrentConversation = useCallback(() => {
    setConversationMap(prev => {
      const newMap = new Map(prev)
      newMap.set(currentDocId, [])
      return newMap
    })
  }, [currentDocId])

  // 更新选中的文献列表
  const updateSelectedDocs = useCallback((docs: Document[]) => {
    setSelectedDocs(docs)
    // 初始化新文献的对话历史
    setConversationMap(prev => {
      const newMap = new Map(prev)
      docs.forEach(doc => {
        if (!newMap.has(doc.id)) {
          newMap.set(doc.id, [])
        }
      })
      return newMap
    })
    // 如果当前文献不在新列表中，切换到第一个
    if (docs.length > 0 && !docs.some(d => d.id === currentDocId)) {
      setCurrentDocId(docs[0].id)
    }
  }, [currentDocId])

  return {
    selectedDocs,
    currentDoc,
    currentDocId,
    currentConversation,
    switchDocument,
    addMessage,
    clearCurrentConversation,
    updateSelectedDocs,
  }
}






