import { useSyncExternalStore } from 'react';

export type ChatActionContextSnapshot = {
  sourceAppId: string | null;
  featureTitle: string | null;
  selectionSummary: string | null;
  selectionIds: string[];
};

let snapshot: ChatActionContextSnapshot = {
  sourceAppId: null,
  featureTitle: null,
  selectionSummary: null,
  selectionIds: [],
};

const listeners = new Set<() => void>();

function emit() {
  listeners.forEach((listener) => listener());
}

export function publishChatActionContext(next: Partial<ChatActionContextSnapshot>) {
  snapshot = {
    sourceAppId: typeof next.sourceAppId === 'string' ? next.sourceAppId.trim() || null : snapshot.sourceAppId,
    featureTitle: typeof next.featureTitle === 'string' ? next.featureTitle.trim() || null : snapshot.featureTitle,
    selectionSummary:
      typeof next.selectionSummary === 'string' ? next.selectionSummary.trim() || null : snapshot.selectionSummary,
    selectionIds: Array.isArray(next.selectionIds)
      ? next.selectionIds.map((item) => String(item).trim()).filter(Boolean)
      : snapshot.selectionIds,
  };
  emit();
}

export function clearChatActionContext(sourceAppId?: string | null) {
  if (sourceAppId && snapshot.sourceAppId && snapshot.sourceAppId !== sourceAppId) {
    return;
  }

  snapshot = {
    sourceAppId: null,
    featureTitle: null,
    selectionSummary: null,
    selectionIds: [],
  };
  emit();
}

export function getChatActionContextSnapshot() {
  return snapshot;
}

export function useChatActionContextSnapshot() {
  return useSyncExternalStore(
    (listener) => {
      listeners.add(listener);
      return () => {
        listeners.delete(listener);
      };
    },
    () => snapshot,
    () => snapshot,
  );
}
