// ─── UI Store ────────────────────────────────────────────────────────────────
// Handles logs, pause state, and UI-specific state

import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { createSafeStorage } from '../utils/safe-persist';

export interface LogEntry {
  message: string;
  timestamp: number;
}

export interface UIState {
  logs: string[];
  paused: boolean;
  gameOver: boolean;
  victory: boolean;

  // Actions
  addLog: (message: string) => void;
  clearLogs: () => void;
  togglePause: () => void;
  setPaused: (paused: boolean) => void;
  setGameOver: (gameOver: boolean, victory?: boolean) => void;
  reset: () => void;
}

const MAX_LOGS = 50;

export const useUIStore = create<UIState>()(
  persist(
    (set) => ({
      logs: ['✨ The loop begins. You start with Mana Bolt. Gather your strength, mage.'],
      paused: false,
      gameOver: false,
      victory: false,

      addLog: (message: string) => {
        set((state) => ({
          logs: [message, ...state.logs.slice(0, MAX_LOGS - 1)],
        }));
      },

      clearLogs: () => {
        set({ logs: [] });
      },

      togglePause: () => {
        set((state) => ({ paused: !state.paused }));
      },

      setPaused: (paused: boolean) => {
        set({ paused });
      },

      setGameOver: (gameOver: boolean, victory: boolean = false) => {
        set({ gameOver, victory });
      },

      reset: () => {
        set({
          logs: ['✨ The loop begins. You start with Mana Bolt. Gather your strength, mage.'],
          paused: false,
          gameOver: false,
          victory: false,
        });
      },
    }),
    { storage: createSafeStorage(), name: 'mana-loop-ui-storage', version: 1, partialize: (state) => ({ logs: state.logs, paused: state.paused, gameOver: state.gameOver, victory: state.victory }) }
  )
);
