import { create } from "zustand";
import type { StreamParticle } from "@/api/types";

type PlaybackStatus = "idle" | "playing" | "ended";

interface PlaybackState {
  streamId: string | null;
  particles: StreamParticle[];
  currentIndex: number;
  status: PlaybackStatus;
  paused: boolean;
  downloadUrlCache: Record<string, string>;

  initStream: (
    streamId: string,
    particles: StreamParticle[],
    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<PlaybackState>((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: {},
    });
  },
}));
