/**
 * 侧边栏与编辑区之间的轻量事件总线
 */
export const ASSETS_CHANGED_EVENT = "wolai:assets-changed";
export const DOCUMENTS_CHANGED_EVENT = "wolai:documents-changed";
export const ASSETS_RESTORED_EVENT = "wolai:assets-restored";

type AssetsChangedPayload = {
  docId?: string;
  asset?: unknown;
  assetIds?: string[];
  mindmapDeleted?: boolean;
  mindmapAssetIds?: string[];
};

type AssetsRestoredPayload =
  | { docId: string; kind: "media"; assetId: string; asset?: unknown }
  | { docId: string; kind: "mindmap"; mindmapId: string }
  | { docId: string; kind: "table"; tableId: string };

export function emitAssetsChanged(
  docId?: string,
  asset?: unknown,
  assetIds?: string[],
  mindmapDeleted?: boolean,
  mindmapAssetIds?: string[],
) {
  if (typeof window === "undefined") return;
  const detail: AssetsChangedPayload = { docId, asset, assetIds, mindmapDeleted, mindmapAssetIds };
  window.dispatchEvent(new CustomEvent(ASSETS_CHANGED_EVENT, { detail }));
}

export function emitAssetsRestored(payload: AssetsRestoredPayload) {
  if (typeof window === "undefined") return;
  window.dispatchEvent(new CustomEvent(ASSETS_RESTORED_EVENT, { detail: payload }));
}

export function emitDocumentsChanged(docId?: string) {
  if (typeof window === "undefined") return;
  window.dispatchEvent(new CustomEvent(DOCUMENTS_CHANGED_EVENT, { detail: { docId } }));
}
