import { defineStore } from 'pinia';
import { ref } from 'vue';

export interface Notification {
  id: string;
  message: string;
  type: 'success' | 'error' | 'warning' | 'info';
  duration?: number; // in milliseconds
  manualClose?: boolean; // If true, won't auto-close
}

export const useNotificationStore = defineStore('notifications', () => {
  const notifications = ref<Notification[]>([]);
  const defaultDuration = 5000; // 5 seconds

  // Helper to generate unique IDs
  const generateId = () => `notif_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;

  const addNotification = (notificationDetails: Omit<Notification, 'id'>) => {
    const id = generateId();
    const newNotification: Notification = {
      id,
      ...notificationDetails,
    };

    notifications.value.unshift(newNotification); // Add to the beginning for newest on top

    if (!newNotification.manualClose) {
      setTimeout(() => {
        removeNotification(id);
      }, newNotification.duration || defaultDuration);
    }
  };

  const removeNotification = (id: string) => {
    const index = notifications.value.findIndex(n => n.id === id);
    if (index !== -1) {
      notifications.value.splice(index, 1);
    }
  };

  const clearAllNotifications = () => {
    notifications.value = [];
  };

  return {
    notifications,
    addNotification,
    removeNotification,
    clearAllNotifications,
  };
});