import { create } from 'zustand'
import { devtools } from 'zustand/middleware'

export interface User {
  id: string
  name: string
  avatar?: string
}

export interface UserPresence {
  userId: string
  name: string
  color: string
  cursorPosition?: { x: number; y: number }
  activeKrateId?: string
  spotlightQuery?: string
  timestamp: number
}

export interface UserStore {
  currentUser: User
  presence: Map<string, UserPresence>
}

const INITIAL_STATE: UserStore = {
  currentUser: {
    id: 'local-user',
    name: 'User',
  },
  presence: new Map(),
}

export const useUserStore = create<UserStore>()(
  devtools((set) => ({
    ...INITIAL_STATE,
    setCurrentUser: (user: User) => set({ currentUser: user }),
    addPresence: (presence: UserPresence) =>
      set((state) => ({
        presence: new Map(state.presence).set(presence.userId, presence),
      })),
    removePresence: (userId: string) =>
      set((state) => {
        const newPresence = new Map(state.presence)
        newPresence.delete(userId)
        return { presence: newPresence }
      }),
    updatePresence: (userId: string, updates: Partial<UserPresence>) =>
      set((state) => {
        const existing = state.presence.get(userId)
        if (!existing) return state
        return {
          presence: new Map(state.presence).set(userId, { ...existing, ...updates }),
        }
      }),
  }))
)
