import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { Term } from '../types/term';

export interface SentenceToken {
  id: string;
  termId: string;
  term: Term;
  displayText: string;
  isPunctuation: boolean;
}

interface SentenceState {
  // Current working sentence (tokens being built)
  currentTokens: SentenceToken[];
  
  // Actions
  addToken: (term: Term) => void;
  removeToken: (tokenId: string) => void;
  reorderTokens: (tokens: SentenceToken[]) => void;
  clearTokens: () => void;
  setTokens: (tokens: SentenceToken[]) => void;
}

export const useSentenceStore = create<SentenceState>()(
  persist(
    (set) => ({
      currentTokens: [],

      addToken: (term: Term) => {
        set((state) => {
          const newToken: SentenceToken = {
            id: `token-${Date.now()}-${Math.random()}`,
            termId: term.id,
            term,
            displayText: term.wordText,
            isPunctuation: false,
          };
          return {
            currentTokens: [...state.currentTokens, newToken],
          };
        });
      },

      removeToken: (tokenId: string) => {
        set((state) => ({
          currentTokens: state.currentTokens.filter((token) => token.id !== tokenId),
        }));
      },

      reorderTokens: (tokens: SentenceToken[]) => {
        set({ currentTokens: tokens });
      },

      clearTokens: () => {
        set({ currentTokens: [] });
      },

      setTokens: (tokens: SentenceToken[]) => {
        set({ currentTokens: tokens });
      },
    }),
    {
      name: 'sentence-storage',
    }
  )
);

