import { create } from 'zustand'
import { devtools } from 'zustand/middleware'

export interface Krate {
  id: string
  type: string
  title: string
  x: number
  y: number
  width: number
  height: number
  color: string
  minimized: boolean
  windowLayout: WindowLayout
  windows: Map<string, KrateWindow>
}

export interface WindowLayout {
  cols: number
  rows: number
  cells: Map<string, { col: number; row: number; colSpan: number; rowSpan: number }>
}

export interface KrateWindow {
  id: string
  type: string
  title: string
  state: unknown
}

export interface KrateStore {
  krates: Map<string, Krate>
  selectedKrateId: string | null
}

const INITIAL_STATE: KrateStore = {
  krates: new Map(),
  selectedKrateId: null,
}

export const useKrateStore = create<KrateStore>()(
  devtools((set) => ({
    ...INITIAL_STATE,
    addKrate: (krate: Krate) =>
      set((state) => ({ krates: new Map(state.krates).set(krate.id, krate) })),
    removeKrate: (id: string) =>
      set((state) => {
        const newKrates = new Map(state.krates)
        newKrates.delete(id)
        return { krates: newKrates }
      }),
    selectKrate: (id: string | null) => set({ selectedKrateId: id }),
    updateKrate: (id: string, updates: Partial<Krate>) =>
      set((state) => {
        const existing = state.krates.get(id)
        if (!existing) return state
        return {
          krates: new Map(state.krates).set(id, { ...existing, ...updates }),
        }
      }),
  }))
)
