import { atom, PrimitiveAtom } from 'jotai';
import { atomFamily } from 'jotai/utils';

const createActiveThreadIdAtom = () => atom<string | null>(null);
export type TActiveThreadIdAtom = PrimitiveAtom<string | null>;

/**
 * Per-room "which thread is open in the panel" state. Mirrors
 * `roomIdToReplyDraftAtomFamily` in `roomInputDrafts.ts` — the same atom
 * instance is returned for the same roomId, so a room's panel state survives
 * remounts.
 */
export const roomIdToActiveThreadIdAtomFamily = atomFamily<string, TActiveThreadIdAtom>(() =>
  createActiveThreadIdAtom(),
);

/**
 * Key used to scope a thread's composer drafts (message/reply/upload) away from
 * the main room composer, e.g. `"!room:server::$rootEventId"`.
 */
export const getThreadDraftKey = (roomId: string, threadRootId: string): string =>
  `${roomId}::${threadRootId}`;
