import { create } from "zustand"; import type { Particle } from "@/api/types"; type PlaybackStatus = "idle" | "playing" | "ended"; interface PlaybackState { streamId: string | null; particles: Particle[]; currentIndex: number; status: PlaybackStatus; paused: boolean; downloadUrlCache: Record; initStream: ( streamId: string, particles: Particle[], startIndex: number, ) => void; next: () => void; prev: () => void; goTo: (index: number) => void; pause: () => void; resume: () => void; cacheDownloadUrl: (particleId: string, url: string) => void; reset: () => void; } export const usePlaybackStore = create((set, get) => ({ streamId: null, particles: [], currentIndex: 0, status: "idle", paused: false, downloadUrlCache: {}, initStream: (streamId, particles, startIndex) => { set({ streamId, particles, currentIndex: startIndex, status: particles.length > 0 ? "playing" : "ended", downloadUrlCache: {}, }); }, next: () => { const { currentIndex, particles } = get(); if (currentIndex < particles.length - 1) { set({ currentIndex: currentIndex + 1, paused: false }); } else { set({ status: "ended", paused: false }); } }, prev: () => { const { currentIndex } = get(); if (currentIndex > 0) { set({ currentIndex: currentIndex - 1, status: "playing", paused: false }); } }, goTo: (index) => { const { particles } = get(); if (index >= 0 && index < particles.length) { set({ currentIndex: index, status: "playing", paused: false }); } }, pause: () => set({ paused: true }), resume: () => set({ paused: false }), cacheDownloadUrl: (particleId, url) => { set({ downloadUrlCache: { ...get().downloadUrlCache, [particleId]: url }, }); }, reset: () => { set({ streamId: null, particles: [], currentIndex: 0, status: "idle", paused: false, downloadUrlCache: {}, }); }, }));