import { create } from 'zustand';
import type { Track, VibeSession } from '../types';

// V2 recommendation session state. The backend stores the plan in Redis
// (keyed by sessionId) and serves tracks one at a time via GET /v2/vibe/next.
// We keep a lookahead buffer of upcoming Track[] to feed playback.
interface VibeState {
  activeSessionId: string | null;
  seedTrackId: string | null;
  centerTrack: Track | null;
  buffer: Track[]; // lookahead buffer of upcoming recommended tracks

  setActiveSession: (session: VibeSession | null) => void;
  setSeedTrackId: (seedTrackId: string | null) => void;
  setCenterTrack: (track: Track | null) => void;
  setBuffer: (buffer: Track[]) => void;
  appendBuffer: (tracks: Track[]) => void;
  shiftBuffer: () => Track | undefined;
  reset: () => void;
}

const initialState = {
  activeSessionId: null as string | null,
  seedTrackId: null as string | null,
  centerTrack: null as Track | null,
  buffer: [] as Track[],
};

export const useVibeStore = create<VibeState>((set, get) => ({
  ...initialState,

  setActiveSession: (session) =>
    set(
      session
        ? { activeSessionId: session.sessionId, seedTrackId: session.seedTrackId }
        : { activeSessionId: null, seedTrackId: null }
    ),

  setSeedTrackId: (seedTrackId) => set({ seedTrackId }),
  setCenterTrack: (centerTrack) => set({ centerTrack }),
  setBuffer: (buffer) => set({ buffer }),
  appendBuffer: (tracks) => set((state) => ({ buffer: [...state.buffer, ...tracks] })),

  shiftBuffer: () => {
    const { buffer } = get();
    if (buffer.length === 0) return undefined;
    const [head, ...rest] = buffer;
    set({ buffer: rest });
    return head;
  },

  reset: () => set({ ...initialState }),
}));
