import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { newId } from '@/lib/ids';

export interface Macro {
  id: string;
  label: string;
  expression: string;
}

interface MacroState {
  /** macros keyed by campaign id ('' for the no-campaign scratch list) */
  byCampaign: Record<string, Macro[]>;
  add: (campaignId: string, label: string, expression: string) => void;
  remove: (campaignId: string, id: string) => void;
}

export const useMacroStore = create<MacroState>()(
  persist(
    (set) => ({
      byCampaign: {},
      add: (campaignId, label, expression) =>
        set((s) => ({
          byCampaign: {
            ...s.byCampaign,
            [campaignId]: [...(s.byCampaign[campaignId] ?? []), { id: newId(), label, expression }],
          },
        })),
      remove: (campaignId, id) =>
        set((s) => ({
          byCampaign: {
            ...s.byCampaign,
            [campaignId]: (s.byCampaign[campaignId] ?? []).filter((m) => m.id !== id),
          },
        })),
    }),
    { name: 'ttrpg-macros' },
  ),
);
