/** Unsent composer text per group — CometChat has no built-in draft persistence. */
export const COMPOSER_DRAFT_PREFIX = 'cc_composer_draft_';

export const composerDraftKey = (guid?: string | null) =>
  guid ? `${COMPOSER_DRAFT_PREFIX}${String(guid).replace(/^group_/, '')}` : '';

export const loadComposerDraft = (guid?: string | null): string => {
  if (typeof window === 'undefined' || !guid) return '';
  try {
    return localStorage.getItem(composerDraftKey(guid)) || '';
  } catch {
    return '';
  }
};

export const saveComposerDraft = (guid: string | null | undefined, text: string) => {
  if (typeof window === 'undefined' || !guid) return;
  try {
    const key = composerDraftKey(guid);
    const trimmed = String(text || '').trim();
    if (!trimmed) localStorage.removeItem(key);
    else localStorage.setItem(key, String(text));
  } catch {
    /* ignore quota / private mode */
  }
};

export const clearComposerDraft = (guid?: string | null) => {
  if (typeof window === 'undefined' || !guid) return;
  try {
    localStorage.removeItem(composerDraftKey(guid));
  } catch {
    /* ignore */
  }
};

/** Flush whatever is currently in the visible composer into localStorage before switching surfaces. */
export const flushActiveComposerDraft = (guid?: string | null) => {
  if (typeof window === 'undefined' || !guid) return;
  try {
    const el = document.querySelector('.cometchat-message-composer__input') as HTMLElement | null;
    if (el) saveComposerDraft(guid, el.innerText || '');
  } catch {
    /* ignore */
  }
};
