import { create } from 'zustand';
import type { CyreneForm, Mood } from '@/types/persona';
import { DEFAULT_PERSONA_STATE, MOOD_EMOJI } from '@/types/persona';

interface PersonaStore {
  currentForm: CyreneForm;
  mood: Mood;
  affectionScore: number;
  affectionLevel: number;

  setForm: (form: CyreneForm) => void;
  setMood: (mood: Mood) => void;
  addAffectionScore: (score: number) => void;
  resetPersona: () => void;
}

export const usePersonaStore = create<PersonaStore>((set) => ({
  currentForm: DEFAULT_PERSONA_STATE.currentForm,
  mood: DEFAULT_PERSONA_STATE.mood,
  affectionScore: DEFAULT_PERSONA_STATE.affectionScore,
  affectionLevel: DEFAULT_PERSONA_STATE.affectionLevel,

  setForm: (form) => set({ currentForm: form }),
  setMood: (mood) => set({ mood }),

  addAffectionScore: (score) =>
    set((state) => {
      const newScore = state.affectionScore + score;
      // 根据分数计算等级
      let newLevel = 1;
      for (const level of DEFAULT_PERSONA_STATE.affectionLevels) {
        if (newScore >= level.threshold) {
          newLevel = level.level;
        }
      }
      return {
        affectionScore: newScore,
        affectionLevel: newLevel,
      };
    }),

  resetPersona: () =>
    set({
      currentForm: DEFAULT_PERSONA_STATE.currentForm,
      mood: DEFAULT_PERSONA_STATE.mood,
      affectionScore: DEFAULT_PERSONA_STATE.affectionScore,
      affectionLevel: DEFAULT_PERSONA_STATE.affectionLevel,
    }),
}));

/** 获取心情对应的 Emoji */
export function getMoodEmoji(mood: Mood): string {
  return MOOD_EMOJI[mood] || '🌸';
}
