import { create } from 'zustand'

/**
 * In-memory state for the active SyncPlay group. Not persisted - rejoining
 * after a reload is an explicit user action since the server may have
 * pruned an idle group.
 */

export interface SyncPlayGroupState {
  groupId: string
  groupName: string
  memberCount: number
}

export interface RemoteQueueItem {
  itemId: string
  positionTicks: number
  isPlaying: boolean
}

interface State {
  active: SyncPlayGroupState | null
  /** Bumped any time the server pushes a remote command we should apply. */
  lastRemoteSeq: number
  lastRemoteCommand: { type: 'pause' | 'play' | 'seek'; positionTicks?: number } | null
  /** Last queue update from the server. PlayerPage watches this so a
   *  joiner can catch up to whatever the host is currently playing. */
  remoteQueueItem: RemoteQueueItem | null
  setActive: (next: SyncPlayGroupState | null) => void
  setMemberCount: (count: number) => void
  applyRemote: (cmd: { type: 'pause' | 'play' | 'seek'; positionTicks?: number }) => void
  setRemoteQueueItem: (q: RemoteQueueItem | null) => void
}

export const useSyncPlay = create<State>(set => ({
  active: null,
  lastRemoteSeq: 0,
  lastRemoteCommand: null,
  remoteQueueItem: null,
  setActive: next => set({ active: next, remoteQueueItem: null }),
  setMemberCount: count =>
    set(s => (s.active ? { active: { ...s.active, memberCount: count } } : s)),
  applyRemote: cmd => set(s => ({ lastRemoteSeq: s.lastRemoteSeq + 1, lastRemoteCommand: cmd })),
  setRemoteQueueItem: q => set({ remoteQueueItem: q }),
}))
