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

export interface ColorHistoryEntry {
  color: string;
  timestamp: number;
}

interface ColorHistoryState {
  history: ColorHistoryEntry[];
  addColor: (color: string) => void;
  removeColor: (color: string) => void;
  clearHistory: () => void;
  getRecent: (limit?: number) => ColorHistoryEntry[];
}

/**
 * Color history store with localStorage persistence
 *
 * Tracks up to 50 most recent colors with timestamps
 * Automatically removes duplicates (keeps most recent)
 * Persists across browser sessions
 */
export const useColorHistory = create<ColorHistoryState>()(
  persist(
    (set, get) => ({
      history: [],

      addColor: (color) => {
        const normalizedColor = color.toLowerCase();
        set((state) => {
          // Remove existing entry if present
          const filtered = state.history.filter(
            (entry) => entry.color.toLowerCase() !== normalizedColor
          );

          // Add new entry at the beginning
          const newHistory = [
            { color: normalizedColor, timestamp: Date.now() },
            ...filtered,
          ].slice(0, 50); // Keep only 50 most recent

          return { history: newHistory };
        });
      },

      removeColor: (color) => {
        const normalizedColor = color.toLowerCase();
        set((state) => ({
          history: state.history.filter(
            (entry) => entry.color.toLowerCase() !== normalizedColor
          ),
        }));
      },

      clearHistory: () => set({ history: [] }),

      getRecent: (limit = 10) => {
        const { history } = get();
        return history.slice(0, limit);
      },
    }),
    {
      name: 'pastel-color-history',
      storage: createJSONStorage(() => localStorage),
    }
  )
);
