import { create } from 'zustand';
import type { Annotation } from '@abcvideo/shared';

interface AnnotationStore {
  annotations: Annotation[];
  setAnnotations: (a: Annotation[]) => void;
  addAnnotation: (a: Annotation) => void;
  updateAnnotation: (id: string, a: Partial<Annotation>) => void;
  removeAnnotation: (id: string) => void;
}

export const useAnnotationStore = create<AnnotationStore>((set) => ({
  annotations: [],
  setAnnotations: (annotations) => set({ annotations }),
  addAnnotation: (annotation) =>
    set((s) => ({
      annotations: [...s.annotations, annotation].sort((a, b) => a.timeStart - b.timeStart),
    })),
  updateAnnotation: (id, update) =>
    set((s) => ({
      annotations: s.annotations.map((a) => (a.id === id ? { ...a, ...update } : a)),
    })),
  removeAnnotation: (id) =>
    set((s) => ({ annotations: s.annotations.filter((a) => a.id !== id) })),
}));
