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

export type RecentSticker = {
  /** mxc:// url of the sticker image. */
  url: string;
  shortcode: string;
  body?: string;
};

const STORAGE_KEY = 'cinny_recent_stickers_v1';
const MAX_RECENT_STICKERS = 16;

// getOnInit reads localStorage synchronously so the Recent group is present on the
// first render of the sticker picker (no flash of the empty default).
const internalAtom = atomWithStorage<RecentSticker[]>(
  STORAGE_KEY,
  [],
  createJSONStorage(() => localStorage),
  { getOnInit: true },
);

/**
 * Global atom: the most recently sent stickers, newest first, deduped by url,
 * capped at MAX_RECENT_STICKERS. Backed by localStorage (device-local
 * convenience), mirroring `recentGifsAtom`.
 */
export const recentStickersAtom = atom(
  (get): RecentSticker[] => get(internalAtom),
  (_get, set, updater: RecentSticker[] | ((prev: RecentSticker[]) => RecentSticker[])) => {
    set(internalAtom, (prev) => {
      const prevList = Array.isArray(prev) ? prev : [];
      return typeof updater === 'function' ? updater(prevList) : updater;
    });
  },
);

/**
 * Prepend a sticker: ignores an empty url, de-dupes by url (moving an existing
 * entry to the front), and caps the list at `max`. Pure — returns a new array.
 */
export const addRecentSticker = (
  prev: RecentSticker[],
  sticker: RecentSticker,
  max = MAX_RECENT_STICKERS,
): RecentSticker[] => {
  if (!sticker.url) return prev;
  const withoutDupe = prev.filter((s) => s.url !== sticker.url);
  return [sticker, ...withoutDupe].slice(0, max);
};

/**
 * Wipe persisted recent stickers. Called on logout — these are stickers the
 * user sent (mxc + label text) and must not surface under "Recent" to the next
 * person on a shared device.
 */
export const clearRecentStickers = (): void => {
  try {
    localStorage.removeItem(STORAGE_KEY);
  } catch {
    /* localStorage unavailable — nothing to clear */
  }
};
