import { create } from "zustand";

const MAX_LOGS = 50;
const AUTO_HIDE_DELAY = 5000; // 5 secondes après la dernière activité

const useCommandLogStore = create((set, get) => ({
  logs: [],
  visible: false,
  autoHideTimer: null,

  // Ajouter un log
  addLog: (message, type = "info") => {
    const timestamp = new Date().toLocaleTimeString("fr-FR", {
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    });

    set((state) => {
      // Annuler le timer existant
      if (state.autoHideTimer) {
        clearTimeout(state.autoHideTimer);
      }

      // Nouveau timer pour auto-hide
      const newTimer = setTimeout(() => {
        set({ visible: false });
      }, AUTO_HIDE_DELAY);

      const newLogs = [
        { id: Date.now(), timestamp, message, type },
        ...state.logs,
      ].slice(0, MAX_LOGS);

      return {
        logs: newLogs,
        visible: true,
        autoHideTimer: newTimer,
      };
    });
  },

  // Types de logs spécifiques
  logInfo: (message) => get().addLog(message, "info"),
  logSuccess: (message) => get().addLog(message, "success"),
  logError: (message) => get().addLog(message, "error"),
  logWarning: (message) => get().addLog(message, "warning"),

  // Masquer le popup
  hide: () => {
    const state = get();
    if (state.autoHideTimer) {
      clearTimeout(state.autoHideTimer);
    }
    set({ visible: false, autoHideTimer: null });
  },

  // Afficher le popup
  show: () => set({ visible: true }),

  // Vider les logs
  clear: () => set({ logs: [], visible: false }),
}));

export default useCommandLogStore;
