import { create } from 'zustand'

function computeUnread(conversations) {
  return conversations.reduce((sum, c) => sum + (c.unread_count || 0), 0)
}

const useChatStore = create((set, get) => ({
  conversations: [],
  totalUnread: 0,
  // Messages cache: { [convId]: MessageOut[] } — newest first (API order)
  messages: {},

  setConversations(list) {
    set({ conversations: list, totalUnread: computeUnread(list) })
  },

  upsertConversation(conv) {
    set(state => {
      const exists = state.conversations.find(c => c.id === conv.id)
      const next = exists
        ? state.conversations.map(c => c.id === conv.id ? { ...c, ...conv } : c)
        : [conv, ...state.conversations]
      return { conversations: next, totalUnread: computeUnread(next) }
    })
  },

  updateLastRead(convId, userId, readAt) {
    set(state => {
      const next = state.conversations.map(c => {
        if (c.id !== convId) return c
        const participants = (c.participants || []).map(p =>
          p.user_id === userId ? { ...p, last_read_at: readAt } : p
        )
        return { ...c, participants }
      })
      return { conversations: next, totalUnread: computeUnread(next) }
    })
  },

  addMessage(convId, msg) {
    set(state => {
      const existing = state.messages[convId] || []
      // Prepend (newest-first to match API order), deduplicate by id
      const deduplicated = existing.some(m => m.id === msg.id)
        ? existing
        : [msg, ...existing]
      return { messages: { ...state.messages, [convId]: deduplicated } }
    })
  },

  setMessages(convId, msgs) {
    set(state => ({
      messages: { ...state.messages, [convId]: msgs },
    }))
  },

  prependMessages(convId, olderMsgs) {
    // Prepend older messages at the end (they're older so go to the "bottom" of the newest-first list)
    set(state => {
      const existing = state.messages[convId] || []
      const existingIds = new Set(existing.map(m => m.id))
      const newOnes = olderMsgs.filter(m => !existingIds.has(m.id))
      return { messages: { ...state.messages, [convId]: [...existing, ...newOnes] } }
    })
  },

  incrementUnread(convId) {
    set(state => {
      const next = state.conversations.map(c =>
        c.id === convId ? { ...c, unread_count: (c.unread_count || 0) + 1 } : c
      )
      return { conversations: next, totalUnread: computeUnread(next) }
    })
  },

  markConvRead(convId) {
    set(state => {
      const next = state.conversations.map(c =>
        c.id === convId ? { ...c, unread_count: 0 } : c
      )
      return { conversations: next, totalUnread: computeUnread(next) }
    })
  },
}))

export default useChatStore
