/**
 * Extension registry for Pro and third-party UI slots.
 */

import type { ComponentType } from "react";

export type ExtensionSlotName = "canvas-toolbar" | "settings-ai-section" | "animation-countup-settings";

type ExtensionSlot = ExtensionSlotName;

const EMPTY_EXTENSIONS: ComponentType<unknown>[] = [];

const extensions = new Map<ExtensionSlot, ComponentType<unknown>[]>();
const listeners = new Set<() => void>();
let snapshotVersion = 0;

function notifyListeners(): void {
  snapshotVersion += 1;
  listeners.forEach((listener) => listener());
}

export function registerExtension(slot: ExtensionSlotName, component: ComponentType<unknown>): void {
  const existing = extensions.get(slot) ?? EMPTY_EXTENSIONS;
  extensions.set(slot, [...existing, component]);
  notifyListeners();
}

export function getExtensions(slot: ExtensionSlotName): readonly ComponentType<unknown>[] {
  return extensions.get(slot) ?? EMPTY_EXTENSIONS;
}

export function getExtensionsSnapshotVersion(): number {
  return snapshotVersion;
}

export function subscribeExtensions(listener: () => void): () => void {
  listeners.add(listener);
  return () => {
    listeners.delete(listener);
  };
}

declare global {
  interface Window {
    oppbExtensions?: {
      register: typeof registerExtension;
    };
  }
}

if (typeof window !== "undefined") {
  window.oppbExtensions = {
    register: registerExtension,
  };
}
