// 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 { getAttunementXPForLevel, MAX_ATTUNEMENT_LEVEL, ATTUNEMENTS_DEF } from '../data/attunements';
import { useCombatStore } from './combatStore';

export interface AttunementStoreState {
  attunements: Record<string, AttunementState>;

  // Actions
  addAttunementXP: (attunementId: string, amount: number) => void;
  unlockAttunement: (attunementId: string, defeatedGuardians: number[]) => boolean;
  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;
            }
          }

          // Log level-up (outside set to avoid nested state updates)
          if (newLevel > attState.level) {
            const def = ATTUNEMENTS_DEF[attunementId];
            const name = def?.name || attunementId;
            // Use setTimeout to log after state update completes
            setTimeout(() => {
              useCombatStore.getState().addActivityLog(
                'attunement',
                `${name} reached level ${newLevel}!`
              );
            }, 0);
          }
          
          return {
            attunements: {
              ...state.attunements,
              [attunementId]: {
                ...attState,
                level: newLevel,
                experience: newXP,
              },
            },
          };
        });
      },
      
      unlockAttunement: (attunementId: string, defeatedGuardians: number[]) => {
        const def = ATTUNEMENTS_DEF[attunementId];
        if (!def) return false;
        const currentState = _get();
        if (currentState.attunements[attunementId]?.active) return false;

        // Check unlock conditions
        if (attunementId === 'invoker') {
          // Invoker requires defeating the first guardian (floor 10)
          if (!defeatedGuardians.includes(10)) return false;
        } else if (attunementId === 'fabricator') {
          // Fabricator requires defeating the second guardian (floor 20)
          if (!defeatedGuardians.includes(20)) return false;
        } else {
          // Unknown attunement — don't unlock
          return false;
        }

        set((s) => ({
          attunements: {
            ...s.attunements,
            [attunementId]: {
              id: attunementId,
              active: true,
              level: 1,
              experience: 0,
            } as AttunementState,
          },
        }));
        return true;
      },

      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',
      version: 1,
      partialize: (state) => ({
        attunements: state.attunements,
      }),
    }
  )
);
