import { atom } from 'jotai';
import { atomWithStorage, createJSONStorage } from 'jotai/utils';

const STORAGE_KEY = 'cinny_recent_forward_targets_v1';
const MAX_RECENT_FORWARD_TARGETS = 8;

// Internal atom persists as a plain string[] of roomIds (JSON-serializable).
// getOnInit reads localStorage synchronously so the Recent row is present on the
// first render of the Forward dialog (no flash of the empty default).
const internalAtom = atomWithStorage<string[]>(
  STORAGE_KEY,
  [],
  createJSONStorage(() => localStorage),
  { getOnInit: true },
);

/**
 * Global atom: string[] of the most recent distinct roomIds forwarded to.
 * Most-recent first, deduped, capped at MAX_RECENT_FORWARD_TARGETS.
 * Backed by localStorage (device-local convenience — not synced across devices).
 */
export const recentForwardTargetsAtom = atom(
  (get): string[] => get(internalAtom),
  (_get, set, updater: string[] | ((prev: string[]) => string[])) => {
    set(internalAtom, (prev) => {
      const prevList = Array.isArray(prev) ? prev : [];
      const next = typeof updater === 'function' ? updater(prevList) : updater;
      return next;
    });
  },
);

/**
 * Prepend a roomId: dedupes, drops empties, moves an existing id to the front,
 * caps at MAX_RECENT_FORWARD_TARGETS.
 */
export const addRecentForwardTarget = (prev: string[], roomId: string): string[] => {
  if (!roomId) return prev;
  const withoutDupe = prev.filter((id) => id !== roomId);
  return [roomId, ...withoutDupe].slice(0, MAX_RECENT_FORWARD_TARGETS);
};

/**
 * Wipe persisted recent forward targets. Called on logout — the list is the
 * user's recent messaging contact/room graph (PII) and must not survive a
 * session on a shared device.
 */
export const clearRecentForwardTargets = (): void => {
  try {
    localStorage.removeItem(STORAGE_KEY);
  } catch {
    /* localStorage unavailable — nothing to clear */
  }
};
