import Taro from "@tarojs/taro";

const UNREAD_KEY = "xlh_unread_info";

interface UnreadMap {
  [conversationId: string]: number; // unreadCount
}

function loadUnread(): UnreadMap {
  try {
    const raw = Taro.getStorageSync(UNREAD_KEY);
    return raw ? JSON.parse(raw) : {};
  } catch {
    return {};
  }
}

function saveUnread(map: UnreadMap) {
  try {
    Taro.setStorageSync(UNREAD_KEY, JSON.stringify(map));
  } catch {
    // ignore storage quota errors
  }
}

/** Get total unread count across all conversations */
export function getTotalUnread(): number {
  const map = loadUnread();
  return Object.values(map).reduce((sum, c) => sum + c, 0);
}

/** Get unread count for a specific conversation */
export function getConversationUnread(conversationId: number): number {
  return loadUnread()[String(conversationId)] || 0;
}

/** Mark a conversation as read (clear unread count) */
export function markConversationRead(conversationId: number) {
  const map = loadUnread();
  delete map[String(conversationId)];
  saveUnread(map);
}

/** Increment unread for a conversation (called on new assistant message if not active) */
export function incrementUnread(conversationId: number, count = 1) {
  const map = loadUnread();
  const key = String(conversationId);
  map[key] = (map[key] || 0) + count;
  saveUnread(map);
}

/** Clean up stale conversation entries (ids not in the provided list) */
export function pruneUnread(activeIds: number[]) {
  const map = loadUnread();
  const idSet = new Set(activeIds.map(String));
  let changed = false;
  for (const key of Object.keys(map)) {
    if (!idSet.has(key)) {
      delete map[key];
      changed = true;
    }
  }
  if (changed) saveUnread(map);
}
