/**
 * 站内信动作总线
 * NoticeActionHost 挂载后注册 handler；铃铛/消息中心调用 openNoticeAction
 */
import type { NoticeItemLike } from './types';

type NoticeActionHandler = (item: NoticeItemLike) => void | Promise<void>;

let handler: NoticeActionHandler | null = null;
const refreshListeners = new Set<() => void>();

/** Host 注册：打开业务弹窗 / 详情抽屉 */
export function registerNoticeActionHandler(fn: NoticeActionHandler | null) {
  handler = fn;
}

/** 打开站内信动作（先已读由调用方或 Host 内处理） */
export async function openNoticeAction(item: NoticeItemLike) {
  if (!handler) {
    console.warn('[notice] NoticeActionHost 未挂载');
    return;
  }
  await handler(item);
}

/** 审核成功后刷新铃铛 */
export function onNoticeRefresh(fn: () => void) {
  refreshListeners.add(fn);
  return () => refreshListeners.delete(fn);
}

export function emitNoticeRefresh() {
  refreshListeners.forEach((fn) => {
    try {
      fn();
    } catch {
      /* ignore */
    }
  });
}
