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

export interface Notification {
  id: string;
  type: 'audio_complete' | 'video_complete' | 'content_complete' | 'error';
  title: string;
  message: string;
  bookId?: string | number;
  timestamp: number;
  read: boolean;
}

const STORAGE_KEY = 'app_notifications';

function loadFromStorage(): Notification[] {
  try {
    const data = uni.getStorageSync(STORAGE_KEY);
    return data ? JSON.parse(data) : [];
  } catch {
    return [];
  }
}

function saveToStorage(notifications: Notification[]) {
  try {
    uni.setStorageSync(STORAGE_KEY, JSON.stringify(notifications));
  } catch (e) {
    console.error('[Notification] 保存失败:', e);
  }
}

export const useNotificationStore = defineStore('notification', () => {
  const notifications = ref<Notification[]>(loadFromStorage());

  const unreadCount = computed(() => notifications.value.filter(n => !n.read).length);

  function add(notif: Omit<Notification, 'id' | 'timestamp' | 'read'>) {
    const id = `notif_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`;
    const notification: Notification = {
      ...notif,
      id,
      timestamp: Date.now(),
      read: false,
    };
    notifications.value.unshift(notification);
    // 最多保留 50 条
    if (notifications.value.length > 50) {
      notifications.value = notifications.value.slice(0, 50);
    }
    saveToStorage(notifications.value);
  }

  function markRead(id: string) {
    const n = notifications.value.find(item => item.id === id);
    if (n) {
      n.read = true;
      saveToStorage(notifications.value);
    }
  }

  function markAllRead() {
    notifications.value.forEach(n => { n.read = true; });
    saveToStorage(notifications.value);
  }

  function remove(id: string) {
    notifications.value = notifications.value.filter(n => n.id !== id);
    saveToStorage(notifications.value);
  }

  function clear() {
    notifications.value = [];
    saveToStorage(notifications.value);
  }

  return {
    notifications,
    unreadCount,
    add,
    markRead,
    markAllRead,
    remove,
    clear,
  };
});
