import { create } from 'zustand';
import { persist } from 'zustand/middleware';

interface CommandPaletteState {
  isOpen: boolean;
  recentItems: string[];
}

interface CommandPaletteActions {
  open: () => void;
  close: () => void;
  toggle: () => void;
  addRecent: (id: string) => void;
}

export const useCommandPaletteStore = create<CommandPaletteState & CommandPaletteActions>()(
  persist(
    (set) => ({
      isOpen: false,
      recentItems: [],

      open: () => set({ isOpen: true }),
      close: () => set({ isOpen: false }),
      toggle: () => set((s) => ({ isOpen: !s.isOpen })),

      addRecent: (id) =>
        set((s) => ({
          recentItems: [id, ...s.recentItems.filter((i) => i !== id)].slice(0, 10),
        })),
    }),
    {
      name: 'cml-command-palette',
      partialize: (state) => ({
        recentItems: state.recentItems,
      }),
    },
  ),
);
