import { test } from 'node:test';
import assert from 'node:assert/strict';

// The module evaluates atomWithStorage(..., { getOnInit: true }), which reads
// localStorage at load time. node has none, so install a no-op mock, then import
// dynamically (a static import would hoist above the mock and evaluate too early).
(globalThis as { localStorage?: unknown }).localStorage = {
  getItem: () => null,
  setItem: () => undefined,
  removeItem: () => undefined,
};

const { addRecentSticker } = await import('./recentStickers');

const st = (url: string, shortcode = url, body = url) => ({ url, shortcode, body });

test('addRecentSticker prepends a new sticker', () => {
  const out = addRecentSticker([st('a'), st('b')], st('c'));
  assert.deepEqual(
    out.map((s) => s.url),
    ['c', 'a', 'b'],
  );
});

test('addRecentSticker de-dupes by url, moving the existing one to the front', () => {
  const out = addRecentSticker([st('a'), st('b'), st('c')], st('c'));
  assert.deepEqual(
    out.map((s) => s.url),
    ['c', 'a', 'b'],
  );
  assert.equal(out.length, 3);
});

test('addRecentSticker caps the list at max (newest kept)', () => {
  const start = [st('a'), st('b'), st('c')];
  const out = addRecentSticker(start, st('d'), 3);
  assert.deepEqual(
    out.map((s) => s.url),
    ['d', 'a', 'b'],
  );
});

test('addRecentSticker ignores an empty url', () => {
  const start = [st('a')];
  const out = addRecentSticker(start, st(''));
  assert.equal(out, start); // returns the same array unchanged
});
