// 每个页面独立的对话存储工具
class PageConversationStore {
  constructor(pageName) {
    this.pageName = pageName
    this.storageKey = `page_conversations_${pageName}`
    console.log('Initializing store for page:', this.storageKey)
    this.conversations = this.loadFromStorage()
    this.currentConversationId = this.conversations.length > 0 ? this.conversations[0].id : null
    this.subscribers = []

    // 如果没有对话，创建默认对话
    if (this.conversations.length === 0) {
      this.createNewConversation()
    }
  }

  // 从本地存储加载对话
  loadFromStorage() {
    try {
      const stored = localStorage.getItem(this.storageKey)
      if (stored) {
        const parsed = JSON.parse(stored)
        // 恢复日期对象
        return parsed.map(conv => ({
          ...conv,
          lastUpdate: new Date(conv.lastUpdate),
          messages: conv.messages.map(msg => ({
            ...msg,
            timestamp: new Date(msg.timestamp)
          }))
        }))
      }
    } catch (error) {
      console.error(`Error loading conversations for ${this.pageName}:`, error)
    }
    return []
  }

  // 保存到本地存储
  saveToStorage() {
    try {
      localStorage.setItem(this.storageKey, JSON.stringify(this.conversations))
    } catch (error) {
      console.error(`Error saving conversations for ${this.pageName}:`, error)
    }
  }

  // 获取所有对话
  getConversations() {
    return this.conversations
  }

  // 获取当前对话ID
  getCurrentConversationId() {
    return this.currentConversationId
  }

  // 获取当前对话
  getCurrentConversation() {
    return this.conversations.find(conv => conv.id === this.currentConversationId)
  }

  // 创建新对话
  createNewConversation() {
    const newConversation = {
      id: `${this.pageName}_${Date.now()}`,
      title: `新对话 ${this.conversations.length + 1}`,
      messages: [
        {
          role: 'assistant',
          content: `欢迎使用${this.pageName}！我是您的AI助手，有什么可以帮助您的吗？`,
          timestamp: new Date()
        }
      ],
      lastUpdate: new Date(),
      isActive: true
    }

    // 将之前的对话设为非活跃
    this.conversations.forEach(conv => conv.isActive = false)

    this.conversations.unshift(newConversation)
    this.currentConversationId = newConversation.id
    this.saveToStorage()
    this.notifySubscribers()
  }

  // 切换对话
  switchConversation(conversationId) {
    this.conversations.forEach(conv => conv.isActive = false)
    const targetConversation = this.conversations.find(conv => conv.id === conversationId)
    if (targetConversation) {
      targetConversation.isActive = true
      this.currentConversationId = conversationId
      this.saveToStorage()
      this.notifySubscribers()
    }
  }

  // 添加消息
  addMessage(role, content) {
    const currentConversation = this.getCurrentConversation()
    if (currentConversation) {
      const newMessage = {
        id: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
        role,
        content,
        timestamp: new Date()
      }

      currentConversation.messages.push(newMessage)
      currentConversation.lastUpdate = new Date()

      // 如果是用户消息，更新标题
      if (role === 'user') {
        const words = content.split(' ').slice(0, 5)
        currentConversation.title = words.join(' ') + (content.length > 30 ? '...' : '')
      }

      this.saveToStorage()
      this.notifySubscribers()
      return newMessage.id
    }
    return null
  }

  // 更新指定消息的内容
  updateMessage(messageId, newContent) {
    console.log('updateMessage 调用:', { messageId, newContent: newContent.substring(0, 50) + '...', length: newContent.length })
    const currentConversation = this.getCurrentConversation()
    if (currentConversation) {
      const message = currentConversation.messages.find(msg => msg.id === messageId)
      if (message) {
        console.log('找到消息，更新内容:', { oldContent: message.content.substring(0, 50) + '...', newContent: newContent.substring(0, 50) + '...' })
        message.content = newContent
        currentConversation.lastUpdate = new Date()
        this.saveToStorage()
        this.notifySubscribers()
      } else {
        console.log('未找到消息:', messageId)
      }
    } else {
      console.log('未找到当前对话')
    }
  }

  // 更新对话标题
  updateConversationTitle(conversationId, newTitle) {
    const conversation = this.conversations.find(conv => conv.id === conversationId)
    if (conversation) {
      conversation.title = newTitle
      this.saveToStorage()
      this.notifySubscribers()
    }

  }

  // 删除对话
  deleteConversation(conversationId) {
    const index = this.conversations.findIndex(conv => conv.id === conversationId)
    if (index !== -1) {
      this.conversations.splice(index, 1)

      // 如果删除的是当前对话，切换到第一个对话
      if (conversationId === this.currentConversationId) {
        if (this.conversations.length > 0) {
          this.currentConversationId = this.conversations[0].id
          this.conversations[0].isActive = true
        } else {
          this.currentConversationId = null
        }
      }

      this.saveToStorage()
      this.notifySubscribers()
    }
  }

  // 清空当前对话
  clearCurrentConversation() {
    const currentConversation = this.getCurrentConversation()
    if (currentConversation) {
      currentConversation.messages = [
        {
          role: 'assistant',
          content: `对话已清空，有什么可以帮助您的吗？`,
          timestamp: new Date()
        }
      ]
      currentConversation.lastUpdate = new Date()
      this.saveToStorage()
      this.notifySubscribers()
    }
  }

  // 订阅状态变化
  subscribe(callback) {
    this.subscribers.push(callback)
    return () => {
      const index = this.subscribers.indexOf(callback)
      if (index !== -1) {
        this.subscribers.splice(index, 1)
      }
    }
  }

  // 通知订阅者
  notifySubscribers() {
    this.subscribers.forEach(callback => {
      callback({
        conversations: this.conversations,
        currentConversationId: this.currentConversationId
      })
    })
  }
}

// 为每个页面创建独立的存储实例
export const dataAnalysisStore = new PageConversationStore('数据分析')
export const conversationStore = new PageConversationStore('智能对话')
export const writingStore = new PageConversationStore('智能写作')
export const mobileStore = new PageConversationStore('问答移动端')
export const assistantStore = new PageConversationStore('智能助理')

export default PageConversationStore
