import { create } from 'zustand';

export interface StreamItem {
  id: string;
  url: string;
  title: string;
  type: 'tv' | 'movie' | 'series';
  posterUrl?: string; // Added to store content cover images for watch progress
}

interface MultiStreamState {
  isActive: boolean;
  layoutMode: 'mosaic' | 'pip';
  streams: StreamItem[];
  activeAudioIndex: number;
  // Temporary state to resume playback seamlessly when closing multi-screen
  pendingResume: { url: string; time: number; isPlaying: boolean } | null;
  
  startMultiStream: (initialStream: StreamItem) => void;
  addStream: (stream: StreamItem) => void;
  removeStream: (index: number) => void;
  setLayoutMode: (mode: 'mosaic' | 'pip') => void;
  setActiveAudio: (index: number) => void;
  resetMultiStream: () => void;
}

export const useMultiStreamStore = create<MultiStreamState>((set) => ({
  isActive: false,
  layoutMode: 'mosaic',
  streams: [],
  activeAudioIndex: 0,
  pendingResume: null,

  startMultiStream: (initialStream) => set({
    isActive: true,
    streams: [initialStream],
    activeAudioIndex: 0,
    pendingResume: null,
  }),

  addStream: (stream) => set((state) => {
    if (state.streams.length >= 4) return state; // Limit to 4 streams
    const exists = state.streams.some(s => s.url === stream.url);
    if (exists) return state;
    
    return {
      streams: [...state.streams, stream],
      activeAudioIndex: state.streams.length, // Switch audio to the new stream
    };
  }),

  removeStream: (index) => set((state) => {
    const updated = state.streams.filter((_, i) => i !== index);
    const newActiveAudio = state.activeAudioIndex >= updated.length ? 0 : state.activeAudioIndex;
    return {
      streams: updated,
      isActive: updated.length > 0,
      activeAudioIndex: newActiveAudio,
    };
  }),

  setLayoutMode: (mode) => set({ layoutMode: mode }),
  setActiveAudio: (index) => set({ activeAudioIndex: index }),
  resetMultiStream: () => set({ isActive: false, streams: [], activeAudioIndex: 0 }),
}));
