import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import type { AnimDef, AvatarParts, FidgetTiming, TalkLayout } from '@pixeloffice/protocol';
import * as charactersModule from '../src/characters.ts';
import * as renderMapModule from '../src/render-map.ts';
import {
  agentAvatar,
  agentPropKey,
  animAt,
  animFor,
  animFrameAt,
  avatarFromKey,
  avatarLayerPaths,
  avatarPropPaths,
  bounceAt,
  characterLayout,
  defaultAssetUrl,
  defaultProjectAvatar,
  emoteFrameAt,
  fidgetAt,
  fidgetFrameAt,
  fillTemplate,
  fnv1a,
  frameRect,
  loadCatalog,
  mulberry32,
  parseProjectAvatarKey,
  projectAvatarKey,
  talkersAt,
  validateAvatar,
  type FidgetWindow,
} from '../src/index.ts';
import { MINI_CATALOG, miniCatalog, mutateYaml } from './fixtures.ts';

const chars = () => miniCatalog().characters;

describe('персонажи', () => {
  it('fillTemplate: ведущий ноль, строки как есть, нет ключа — ошибка', () => {
    expect(fillTemplate('Outfit_{model}_{color}.png', { model: 3, color: 12 })).toBe('Outfit_03_12.png');
    expect(fillTemplate('A_{name}.png', { name: 'Bee' })).toBe('A_Bee.png');
    expect(() => fillTemplate('{body}', {})).toThrow();
  });

  it('fillTemplate: модификатор :0 — число без ведущего нуля (спека диалоговых окон 2.2)', () => {
    expect(fillTemplate('PG_Skin_{body:0}.png', { body: 3 })).toBe('PG_Skin_3.png');
    expect(fillTemplate('PG_Hairstyle_{model}_{color:0}.png', { model: 1, color: 3 })).toBe('PG_Hairstyle_01_3.png');
    expect(fillTemplate('{body:0}/{body}', { body: 12 })).toBe('12/12');
    expect(() => fillTemplate('{body:0}', {})).toThrow();
  });

  it('слои аватара в порядке наложения, с аксессуаром', () => {
    expect(avatarLayerPaths(chars(), { body: 3, eyes: 2, outfit: [41, 2], hair: [17, 5], accessory: [1, 3] })).toEqual([
      'gen/Body_03.png',
      'gen/Eyes_02.png',
      'gen/Outfit_41_02.png',
      'gen/Hairstyle_17_05.png',
      'gen/Accessory_01_Ladybug_03.png',
    ]);
  });

  it('аватар по ключу: детерминирован и в пределах пула', () => {
    const pool = chars().pool;
    const a = avatarFromKey('agent:stas:PixelOffice:%17', pool);
    expect(avatarFromKey('agent:stas:PixelOffice:%17', pool)).toEqual(a);
    expect(pool.bodies).toContain(a.body);
    expect(pool.eyes).toContain(a.eyes);
    expect(a.outfit[1]).toBeLessThanOrEqual(pool.outfits[String(a.outfit[0])]!);
    const distinct = new Set(Array.from({ length: 20 }, (_, i) => JSON.stringify(avatarFromKey(`k${i}`, pool))));
    expect(distinct.size).toBeGreaterThan(1);
  });

  it('fnv1a и mulberry32 стабильны', () => {
    expect(fnv1a('a')).toBe(0xe40c292c);
    const r1 = mulberry32(42);
    const r2 = mulberry32(42);
    expect([r1(), r1()]).toEqual([r2(), r2()]);
  });

  it('поза → анимация: сидение вверх/вниз — кадр walk, игра со спины — play (спека 5.2)', () => {
    const poses = chars().poses;
    expect(animFor(poses, 'sit', 'up')).toBe('sitFront');
    expect(animFor(poses, 'sit', 'left')).toBe('sit');
    expect(animFor(poses, 'play', 'up')).toBe('play');
    expect(animFor(poses, 'play', 'down')).toBe('idle');
    expect(animFor(poses, 'walk', 'right')).toBe('walk');
    expect(animFor(poses, 'sleep', 'down')).toBe('sleep');
    expect(animFor(poses, 'sleep', 'left')).toBe('sleep'); // у лежащего направления нет (спека сна 3.2)
    const l = characterLayout(chars());
    expect(frameRect(l, 'sitFront', 'up', 0)).toEqual(frameRect(l, 'walk', 'up', 0)); // тот же кадр, но без цикла
  });

  it('кадр цикла по времени: fps, сдвиг фазы по id, статичные анимации', () => {
    const a = { row: 1, frames: 6, fps: 5, dirs: {} };
    // Фаза по id: у разных ключей сдвиг разный, но кадр меняется ровно раз в 1000/fps мс.
    const seq = (key: string) => Array.from({ length: 13 }, (_, i) => animFrameAt(a, i * 100, key));
    for (const key of ['a', 'agent:1', 'human:stas']) {
      const s = seq(key);
      expect(s.every((f) => f >= 0 && f < 6)).toBe(true);
      const changes = s.slice(1).filter((f, i) => f !== s[i]).length;
      expect(changes).toBeGreaterThanOrEqual(5);
      expect(changes).toBeLessThanOrEqual(6);
      expect(seq(key)).toEqual(s); // детерминирована
    }
    const phases = new Set(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].map((k) => animFrameAt(a, 0, k)));
    expect(phases.size).toBeGreaterThan(1); // не хором
    // Полный цикл — frames кадров за frames/fps секунд.
    expect(animFrameAt(a, 1200, 'a')).toBe(animFrameAt(a, 0, 'a'));
    expect(animFrameAt({ row: 2, frames: 1, dirs: {} }, 12345, 'a')).toBe(0);
    expect(animFrameAt({ row: 2, frames: 6, dirs: {} }, 12345, 'a')).toBe(0); // без fps
    expect(animFrameAt(undefined, 12345, 'a')).toBe(0);
  });

  it('кадр по анимации и направлению', () => {
    const l = characterLayout(chars());
    expect(frameRect(l, 'walk', 'down', 0)).toEqual({ x: 288, y: 64, w: 16, h: 32 });
    expect(frameRect(l, 'walk', 'down', 7)).toEqual({ x: 304, y: 64, w: 16, h: 32 }); // 7 % 6 = 1
    expect(frameRect(l, 'sit', 'left', 0)).toEqual({ x: 96, y: 128, w: 16, h: 32 });
    expect(frameRect(l, 'sit', 'up', 0).x).toBe(0); // нет колонки up/down у sit → right
  });
});

const TIMING: FidgetTiming = { everyMs: [180_000, 300_000], durationMs: [5000, 10_000] };
const NAMES = ['phone', 'reading'];

// Все окна персонажа на отрезке [0, untilMs): обход с шагом 1 с (окно не короче 5 с — не пропустить).
function windows(key: string, untilMs: number, t = TIMING): FidgetWindow[] {
  const out: FidgetWindow[] = [];
  for (let ms = 0; ms < untilMs; ms += 1000) {
    const w = fidgetAt(key, ms, t, NAMES);
    if (w && out.at(-1)?.startMs !== w.startMs) out.push(w);
  }
  return out;
}

describe('бытовые анимации (fidgets)', () => {
  it('окна: между началами 3–5 минут, длительность 5–10 с, анимация из списка', () => {
    for (const key of ['human:vera', 'agent:stas:PixelOffice:%3', 'x']) {
      const ws = windows(key, 3 * 3_600_000);
      expect(ws.length).toBeGreaterThanOrEqual(3 * 12 - 1); // 3 часа: от 36 до 60 окон
      expect(ws.length).toBeLessThanOrEqual(3 * 20 + 1);
      for (const w of ws) {
        expect(w.durationMs).toBeGreaterThanOrEqual(5000);
        expect(w.durationMs).toBeLessThanOrEqual(10_000);
        expect(NAMES).toContain(w.anim);
      }
      ws.slice(1).forEach((w, i) => {
        const gap = w.startMs - ws[i]!.startMs;
        expect(gap).toBeGreaterThanOrEqual(180_000);
        expect(gap).toBeLessThanOrEqual(300_000);
      });
      expect(new Set(ws.map((w) => w.anim)).size).toBe(2); // за 3 часа встречаются обе
    }
  });

  it('детерминированы по id и времени; у разных id окна в разное время', () => {
    const at = 1_760_000_000_000; // реальные часы: ~2025 год в мс
    expect(fidgetAt('human:vera', at, TIMING, NAMES)).toEqual(fidgetAt('human:vera', at, TIMING, NAMES));
    const starts = ['a', 'b', 'c', 'd', 'e'].map((k) => windows(k, 600_000)[0]?.startMs);
    expect(new Set(starts).size).toBe(5);
    // Окно на больших временах тоже находится, и текущий момент внутри него.
    let ms = at;
    while (!fidgetAt('human:vera', ms, TIMING, NAMES)) ms += 1000;
    const w = fidgetAt('human:vera', ms, TIMING, NAMES)!;
    expect(ms - w.startMs).toBeLessThan(w.durationMs);
    expect(ms - at).toBeLessThanOrEqual(300_000 + 10_000);
  });

  it('без списка анимаций — никогда', () => {
    expect(windows('x', 1_000_000).length).toBeGreaterThan(0);
    for (let ms = 0; ms < 1_000_000; ms += 1000) expect(fidgetAt('x', ms, TIMING, [])).toBeNull();
  });

  it('кадры: вступление один раз, цикл, в конце окна — завершение', () => {
    const phone: AnimDef = { row: 6, frames: 12, fps: 6, dirs: { down: 0 }, loop: [3, 8] };
    const seq = (durationMs: number) => Array.from({ length: Math.floor((durationMs * 6) / 1000) }, (_, f) => fidgetFrameAt(phone, (f * 1000) / 6 + 1, durationMs));
    const s = seq(5000); // 30 кадров
    expect(s.slice(0, 3)).toEqual([0, 1, 2]);
    expect(s.slice(3, 9)).toEqual([3, 4, 5, 6, 7, 8]);
    expect(s.slice(9, 15)).toEqual([3, 4, 5, 6, 7, 8]);
    expect(s.slice(-3)).toEqual([9, 10, 11]);
    expect(s.slice(3, -3).every((f) => f >= 3 && f <= 8)).toBe(true);
    // Без loop — цикл всех кадров; без fps — кадр 0.
    expect(fidgetFrameAt({ row: 7, frames: 4, fps: 2, dirs: {} }, 2600, 10_000)).toBe(1);
    expect(fidgetFrameAt({ row: 7, frames: 4, dirs: {} }, 2600, 10_000)).toBe(0);
  });

  it('animAt: в окне — бытовая анимация, иначе anim места с циклом', () => {
    const l = { ...characterLayout(chars()), fidget: TIMING };
    l.animations = { ...l.animations, phone: { row: 6, frames: 12, fps: 6, dirs: { down: 0 }, loop: [3, 8] } };
    const c = { id: 'human:vera', anim: 'sitFront', fidgets: ['phone'] };
    let ms = 0;
    while (!fidgetAt(c.id, ms, TIMING, c.fidgets)) ms += 1000;
    const w = fidgetAt(c.id, ms, TIMING, c.fidgets)!;
    expect(animAt(c, l, 0, w.startMs + 100)).toEqual({ anim: 'phone', frame: 0 });
    expect(animAt(c, l, 0, w.startMs - 100).anim).toBe('sitFront');
    expect(animAt({ id: c.id, anim: 'sitFront' }, l, 0, w.startMs + 100).anim).toBe('sitFront');
    expect(animAt(c, { ...l, animations: { ...l.animations, phone: undefined! } }, 0, w.startMs + 100).anim).toBe('sitFront'); // анимации нет в раскладке
  });

  it('предметы в руках: вариант по id, путь без ведущего нуля; в раскладке ряд и колонки заполнены', () => {
    const r = loadCatalog(
      mutateYaml(MINI_CATALOG, (d) => {
        d.characters.props = { phone: { path: 'gen/Phone_{n}.png', variants: ['1', '2', '3'] } };
        d.characters.animations.phone = { row: 6, frames: 3, fps: 6, dirs: { down: 0 }, prop: { name: 'phone' } };
        d.characters.animations.phone2 = { row: 6, frames: 3, dirs: { down: 0 }, prop: { name: 'phone', row: 4, cols: [null, 1, 2] } };
      }),
    );
    if (!r.ok) throw new Error(JSON.stringify(r.errors));
    const p = avatarPropPaths(r.value.characters, 'human:vera');
    expect(p.phone).toMatch(/^gen\/Phone_[123]\.png$/);
    expect(avatarPropPaths(r.value.characters, 'human:vera')).toEqual(p);
    expect(new Set(['a', 'b', 'c', 'd', 'e', 'f', 'g'].map((k) => avatarPropPaths(r.value.characters, k).phone)).size).toBeGreaterThan(1);
    expect(avatarPropPaths(chars(), 'x')).toEqual({});
    const l = characterLayout(r.value.characters);
    expect(l.animations.phone!.prop).toEqual({ name: 'phone', row: 6, cols: [0, 1, 2] });
    expect(l.animations.phone2!.prop).toEqual({ name: 'phone', row: 4, cols: [null, 1, 2] });
    expect(characterLayout(chars()).fidget).toBeUndefined();
  });

  it('разговор: в раскладке кадры эмоций прямоугольниками и URL листа', () => {
    const r = loadCatalog(mutateYaml(MINI_CATALOG, (d) => (d.characters.talk = TALK_YAML)));
    if (!r.ok) throw new Error(JSON.stringify(r.errors));
    const t = characterLayout(r.value.characters, (p) => `/assets/${p}`).talk!;
    expect(t).toMatchObject({ speakers: 2, turnMs: [4000, 8000], emoteMs: 2000, bounce: { fps: 8, dy: [0, -1] } });
    expect(t.emotes.sheet).toBe('/assets/ui/emotes.png');
    expect(t.emotes.appear[1]).toEqual({ x: 16, y: 0, w: 16, h: 32 }); // облачко и хвостик — две клетки
    expect(t.emotes.tail).toEqual({ x: 64, y: 16, w: 16, h: 16 });
    expect(t.emotes.icons).toEqual([[{ x: 32, y: 64, w: 16, h: 16 }, { x: 48, y: 64, w: 16, h: 16 }]]); // только из set
    expect(characterLayout(chars()).talk).toBeUndefined();
  });

  it('talkersAt: говорят до speakers участников, реплика 4–8 с, слово переходит, у всех зрителей одинаково', () => {
    const ids = ['a', 'b', 'c', 'd', 'e'];
    const starts: number[] = [];
    const speakers = new Set<string>();
    for (let ms = 1_700_000_000_000; ms < 1_700_000_600_000; ms += 100) {
      const m = talkersAt('meeting:m1', ids, ms, TALK);
      expect(m.size).toBeGreaterThanOrEqual(1);
      expect(m.size).toBeLessThanOrEqual(2);
      expect(talkersAt('meeting:m1', ids, ms, TALK)).toEqual(m);
      for (const [id, t] of m) {
        expect(ids).toContain(id);
        expect(t.startMs).toBeLessThanOrEqual(ms);
        expect(t.emote).toBeGreaterThanOrEqual(0);
        expect(t.emote).toBeLessThan(TALK.emotes.icons.length);
        if (t.voice === 0) {
          if (starts.at(-1) !== t.startMs) starts.push(t.startMs);
          speakers.add(id);
        }
      }
    }
    const lens = starts.slice(1).map((s, i) => s - starts[i]!).slice(1, -1);
    expect(lens.length).toBeGreaterThan(50);
    expect(Math.min(...lens)).toBeGreaterThanOrEqual(4000);
    expect(Math.max(...lens)).toBeLessThanOrEqual(8000);
    expect(speakers.size).toBe(5);
    // Один участник — один голос; без участников — никого. У другой группы — свой ритм.
    expect(talkersAt('g', ['a'], 1_700_000_000_000, TALK).size).toBe(1);
    expect(talkersAt('g', [], 1_700_000_000_000, TALK).size).toBe(0);
    const other = [0, 1, 2, 3, 4, 5].map((i) => talkersAt('meeting:m2', ids, 1_700_000_000_000 + i * 3000, TALK).get('a')?.startMs);
    const own = [0, 1, 2, 3, 4, 5].map((i) => talkersAt('meeting:m1', ids, 1_700_000_000_000 + i * 3000, TALK).get('a')?.startMs);
    expect(other).not.toEqual(own);
  });

  it('emoteFrameAt и bounceAt: появление, иконка вдвое медленнее, после emoteMs нет ни облачка, ни подпрыгивания', () => {
    expect(emoteFrameAt(TALK, -1)).toBeNull();
    expect(emoteFrameAt(TALK, 0)).toEqual({ appear: 0 });
    expect(emoteFrameAt(TALK, 130)).toEqual({ appear: 1 });
    expect(emoteFrameAt(TALK, 260)).toEqual({ icon: 0 }); // 2 кадра появления при 8 fps
    expect(emoteFrameAt(TALK, 510)).toEqual({ icon: 1 });
    expect(emoteFrameAt(TALK, 760)).toEqual({ icon: 0 });
    expect(emoteFrameAt(TALK, 1999)).not.toBeNull();
    expect(emoteFrameAt(TALK, 2000)).toBeNull();
    expect([0, 130, 260, 380].map((ms) => bounceAt(TALK, ms))).toEqual([0, -1, 0, -1]);
    expect([2000, 2130, 5000].map((ms) => bounceAt(TALK, ms))).toEqual([0, 0, 0]); // облачко погасло — не подпрыгивает
  });
});

const TALK_YAML = {
  speakers: 2,
  turn: ['4s', '8s'],
  emote: '2s',
  bounce: { fps: 8, dy: [0, -1] },
  emotes: { path: 'ui/emotes.png', cell: 16, fps: 8, appear: [[0, 0], [1, 0]], tail: [4, 1], icons: { bang: [2, 4], zzz: [6, 5] }, set: ['bang'] },
};
const R = (x: number, y: number) => ({ x, y, w: 16, h: 16 });
const TALK: TalkLayout = {
  speakers: 2,
  turnMs: [4000, 8000],
  emoteMs: 2000,
  bounce: { fps: 8, dy: [0, -1] },
  emotes: { sheet: '/assets/ui/emotes.png', fps: 8, appear: [R(0, 0), R(16, 0)], tail: R(64, 16), icons: [[R(0, 64), R(16, 64)], [R(32, 64), R(48, 64)], [R(64, 64), R(80, 64)]] },
};

describe('validateAvatar', () => {
  // Мини-каталог: тела 1–3, глаза 1–2, одежда {1: 3, 2: 2}, причёска {1: 4}, аксессуар {1: 3}.
  const pool = () => chars().pool;
  const good: AvatarParts = { body: 1, eyes: 2, outfit: [2, 2], hair: [1, 4], accessory: [1, 3] };

  it('годный облик — пустой список', () => {
    expect(validateAvatar(good, pool())).toEqual([]);
  });

  it('тело и глаза вне pool', () => {
    expect(validateAvatar({ ...good, body: 4, eyes: 3 }, pool())).toEqual(['тело 4: нет в каталоге', 'глаза 3: нет в каталоге']);
  });

  it('модель или цвет одежды и причёски вне диапазона', () => {
    expect(validateAvatar({ ...good, outfit: [3, 1] }, pool())).toEqual(['одежда: модели 3 нет в каталоге']);
    expect(validateAvatar({ ...good, outfit: [2, 3] }, pool())).toEqual(['одежда 2: цвета 3 нет, есть 1–2']);
    expect(validateAvatar({ ...good, hair: [2, 1] }, pool())).toEqual(['причёска: модели 2 нет в каталоге']);
    expect(validateAvatar({ ...good, hair: [1, 5] }, pool())).toEqual(['причёска 1: цвета 5 нет, есть 1–4']);
  });

  it('аксессуар: модель вне pool.accessories, цвет вне диапазона; без аксессуара — годен', () => {
    expect(validateAvatar({ ...good, accessory: [2, 1] }, pool())).toEqual(['аксессуар: модели 2 нет в каталоге']);
    expect(validateAvatar({ ...good, accessory: [1, 4] }, pool())).toEqual(['аксессуар 1: цвета 4 нет, есть 1–3']);
    const { accessory: _accessory, ...plain } = good;
    expect(validateAvatar(plain, pool())).toEqual([]);
  });

  it('облик по хешу всегда проходит проверку — мини-каталог и LimeZu', () => {
    const limezu = loadCatalog(readFileSync(new URL('../../../catalog/limezu/catalog.yaml', import.meta.url), 'utf8'));
    if (!limezu.ok) throw new Error('каталог');
    for (const p of [pool(), limezu.value.characters.pool]) {
      for (let i = 0; i < 500; i++) expect(validateAvatar(avatarFromKey(`k${i}`, p), p)).toEqual([]);
    }
  });
});

describe('URL слоёв для вьюера', () => {
  it('defaultAssetUrl живёт в characters.ts (подпуть вьюера); render-map и корень реэкспортируют её же', () => {
    expect(renderMapModule.defaultAssetUrl).toBe(charactersModule.defaultAssetUrl);
    expect(defaultAssetUrl).toBe(charactersModule.defaultAssetUrl);
    expect(charactersModule.defaultAssetUrl('Modern Office/a b.png')).toBe('/sprites/Modern%20Office/a%20b.png');
  });

  it('avatarLayerPaths хватает layers и accessoryNames (avatarKit вьюера)', () => {
    const { layers, accessoryNames } = chars();
    const a: AvatarParts = { body: 3, eyes: 2, outfit: [2, 1], hair: [1, 2], accessory: [1, 3] };
    expect(avatarLayerPaths({ layers, accessoryNames }, a)).toEqual(avatarLayerPaths(chars(), a));
  });
});

describe('облик агентов (спека агентов §3)', () => {
  const pool = () => chars().pool; // MINI_CATALOG: outfits { "1": 3, "2": 2 }, hairs { "1": 4 }, accessories { "1": 3 }
  const LOOK: AvatarParts = { body: 2, eyes: 1, outfit: [1, 2], hair: [1, 3], accessory: [1, 2] };

  it('agentAvatar: номер 1 — облик проекта; n — цвет одежды сдвинут на n − 1 по кругу; N + 1 — исходный цвет', () => {
    expect(agentAvatar(LOOK, 1, pool())).toEqual(LOOK);
    expect(agentAvatar(LOOK, 2, pool())).toEqual({ ...LOOK, outfit: [1, 3] });
    expect(agentAvatar(LOOK, 3, pool())).toEqual({ ...LOOK, outfit: [1, 1] });
    expect(agentAvatar(LOOK, 4, pool())).toEqual(LOOK); // N = 3: четвёртый — цвет первого
    expect(agentAvatar({ ...LOOK, outfit: [2, 2] }, 2, pool())).toEqual({ ...LOOK, outfit: [2, 1] });
  });

  it('agentAvatar: у модели один цвет — цвет не меняется; прочие детали не трогаются, облик в пределах каталога', () => {
    expect(agentAvatar({ ...LOOK, outfit: [7, 1] }, 5, { outfits: { '7': 1 } })).toEqual({ ...LOOK, outfit: [7, 1] });
    const shifted = agentAvatar(LOOK, 2, pool());
    expect([shifted.body, shifted.eyes, shifted.hair, shifted.accessory]).toEqual([LOOK.body, LOOK.eyes, LOOK.hair, LOOK.accessory]);
    expect(validateAvatar(shifted, pool())).toEqual([]);
  });

  it('agentAvatar: модели одежды нет в каталоге — облик проекта без сдвига', () => {
    const unknown: AvatarParts = { ...LOOK, outfit: [99, 2] };
    expect(agentAvatar(unknown, 3, pool())).toEqual(unknown);
  });

  it('облик проекта по умолчанию — по «хозяин:проект», без слота и префикса agent:', () => {
    expect(defaultProjectAvatar('p1', 'demo', pool())).toEqual(avatarFromKey('p1:demo', pool()));
    expect(validateAvatar(defaultProjectAvatar('p1', 'demo', pool()), pool())).toEqual([]);
  });

  it('ключ облика проекта: построение и разбор; «:» и «/» в проекте допустимы', () => {
    expect(projectAvatarKey('p1', 'pixeloffice')).toBe('agent:p1:pixeloffice');
    for (const project of ['pixeloffice', 'a:b', 'org/repo:main', ':', 'x:']) {
      expect(parseProjectAvatarKey(projectAvatarKey('p1', project))).toEqual({ owner: 'p1', project });
    }
    for (const bad of ['p1', 'agent:', 'agent:p1', 'agent:p1:', 'agent::x', 'human:p1:x']) expect(parseProjectAvatarKey(bad)).toBeNull();
  });

  it('ключ предметов в руках агента — хозяин, проект и номер', () => {
    expect(agentPropKey('p1', 'demo', 2)).toBe('p1:demo:2');
  });
});

describe('сон в парке (спека сна 3.2, 4)', () => {
  it('раскладка: under только у предмета под телом; иконка спящего — пара кадров', () => {
    const r = loadCatalog(
      mutateYaml(MINI_CATALOG, (d) => {
        d.characters.props = { bag: { path: 'gen/Bag_{n}.png', variants: ['1'], under: true }, phone: { path: 'gen/Phone_{n}.png', variants: ['1'] } };
        d.characters.animations.sleep.prop = { name: 'bag', row: 0, cols: [0, 0, 0, 0, 0, 0] };
        d.characters.animations.phone = { row: 6, frames: 2, dirs: { down: 0 }, prop: { name: 'phone' } };
        d.characters.talk = { ...TALK_YAML, emotes: { ...TALK_YAML.emotes, sleep: 'zzz' } };
      }),
    );
    if (!r.ok) throw new Error(JSON.stringify(r.errors));
    const l = characterLayout(r.value.characters);
    expect(l.animations['sleep']!.prop).toEqual({ name: 'bag', row: 0, cols: [0, 0, 0, 0, 0, 0], under: true });
    expect(l.animations['phone']!.prop).toEqual({ name: 'phone', row: 6, cols: [0, 1] }); // поверх — поля under нет
    expect(l.talk!.emotes.sleep).toEqual([{ x: 96, y: 80, w: 16, h: 16 }, { x: 112, y: 80, w: 16, h: 16 }]); // zzz [6, 5]
    expect(characterLayout(r.value.characters).talk!.emotes.icons).toHaveLength(1); // set не меняется
    const noSleep = loadCatalog(mutateYaml(MINI_CATALOG, (d) => (d.characters.talk = TALK_YAML)));
    if (!noSleep.ok) throw new Error(JSON.stringify(noSleep.errors));
    expect(characterLayout(noSleep.value.characters).talk!.emotes.sleep).toBeUndefined();
  });

  it('каталог LimeZu: sleep — ряд 3 со спальником под телом, поза sleep, иконка zzz', () => {
    const r = loadCatalog(readFileSync(new URL('../../../catalog/limezu/catalog.yaml', import.meta.url), 'utf8'));
    if (!r.ok) throw new Error(JSON.stringify(r.errors));
    const c = r.value.characters;
    expect(animFor(c.poses, 'sleep', 'down')).toBe('sleep');
    expect(c.props['sleeping_bag']).toMatchObject({ under: true, variants: ['1', '2', '3', '4', '5'] });
    expect(c.props['smartphone']!.under).toBe(false);
    const l = characterLayout(c);
    expect(l.animations['sleep']).toMatchObject({ row: 3, frames: 6, prop: { name: 'sleeping_bag', row: 0, cols: [0, 0, 0, 0, 0, 0], under: true } });
    expect(l.talk!.emotes.sleep).toEqual([{ x: 96, y: 80, w: 16, h: 16 }, { x: 112, y: 80, w: 16, h: 16 }]);
  });
});
