// Attunement Store
// Handles attunements, XP, leveling, and related actions

import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { createSafeStorage } from '../utils/safe-persist';
import type { AttunementState } from '../types';
import { ATTUNEMENTS_DEF, getAttunementXPForLevel, MAX_ATTUNEMENT_LEVEL } from '../data/attunements';

export interface AttunementStoreState {
  attunements: Record<string, AttunementState>;
  
  // Actions
  addAttunementXP: (attunementId: string, amount: number) => void;
  debugUnlockAttunement: (attunementId: string) => void;
  setAttunements: (attunements: Record<string, AttunementState>) => void;
    
  // Reset
  resetAttunements: () => void;
}

const initialState = {
  attunements: {
    enchanter: { id: 'enchanter', active: true, level: 1, experience: 0 } as AttunementState,
  },
};

export const useAttunementStore = create<AttunementStoreState>()(
  persist(
    (set, get) => ({
      ...initialState,
      
      addAttunementXP: (attunementId: string, amount: number) => {
        set((state) => {
          const attState = state.attunements?.[attunementId];
          if (!attState) return state;
          
          let newXP = attState.experience + amount;
          let newLevel = attState.level;
          
          // Level up if enough XP
          while (newLevel < MAX_ATTUNEMENT_LEVEL) {
            const xpNeeded = getAttunementXPForLevel(newLevel + 1);
            if (newXP >= xpNeeded) {
              newXP -= xpNeeded;
              newLevel++;
            } else {
              break;
            }
          }
          
          return {
            attunements: {
              ...state.attunements,
              [attunementId]: {
                ...attState,
                level: newLevel,
                experience: newXP,
              },
            },
          };
        });
      },
      
      debugUnlockAttunement: (attunementId: string) => {
        set((state) => ({
          attunements: {
            ...state.attunements,
            [attunementId]: {
              id: attunementId,
              active: true,
              level: 1,
              experience: 0,
            } as AttunementState,
          },
        }));
      },
      
      setAttunements: (attunements: Record<string, AttunementState>) => {
        set({ attunements });
      },
      
      resetAttunements: () => {
        set(initialState);
      },
    }),
    {
      storage: createSafeStorage(),
      name: 'mana-loop-attunements',
      partialize: (state) => ({
        attunements: state.attunements,
      }),
    }
  )
);
