import { create } from 'zustand'
import type { Project, Feature, JournalEntry } from '@/types'

interface ProjectStore {
  // Projekt-Daten
  project: Project | null
  features: Feature[] // Karten-Elemente (Symbole, Linien, Polygone)
  journalEntries: JournalEntry[]

  // Actions
  setProject: (project: Project | null) => void
  setFeatures: (features: Feature[]) => void
  addFeature: (feature: Feature) => void
  updateFeature: (id: string, updates: Partial<Feature>) => void
  removeFeature: (id: string) => void
  
  setJournalEntries: (entries: JournalEntry[]) => void
  addJournalEntry: (entry: JournalEntry) => void

  // Realtime-Sync Actions (werden von Socket.io getriggert)
  syncFeatures: (features: Feature[]) => void
  syncJournalEntry: (entry: JournalEntry) => void
}

export const useProjectStore = create<ProjectStore>((set) => ({
  project: null,
  features: [],
  journalEntries: [],

  setProject: (project) => set({ project }),
  
  setFeatures: (features) => set({ features }),
  
  addFeature: (feature) => set((state) => ({ 
    features: [...state.features, feature] 
  })),
  
  updateFeature: (id, updates) => set((state) => ({
    features: state.features.map(f => 
      f.id === id || f.properties?.id === id 
        ? { ...f, properties: { ...f.properties, ...updates } } 
        : f
    )
  })),
  
  removeFeature: (id) => set((state) => ({
    features: state.features.filter(f => f.id !== id && f.properties?.id !== id)
  })),

  setJournalEntries: (entries) => set({ journalEntries: entries }),
  
  addJournalEntry: (entry) => set((state) => ({
    journalEntries: [...state.journalEntries, entry]
  })),

  syncFeatures: (features) => set({ features }),
  
  syncJournalEntry: (entry) => set((state) => {
    // Avoid duplicates
    if (state.journalEntries.some(e => e.id === entry.id)) {
      return {
        journalEntries: state.journalEntries.map(e => e.id === entry.id ? entry : e)
      }
    }
    return {
      journalEntries: [...state.journalEntries, entry]
    }
  }),
}))
