import { describe, expect, it } from 'vitest';
import { World, WorldMap, type FrameCharacter, type Rules, type Spot, type Zone } from '../src/index.ts';
import { ROUTES_OFFICE, bundle, mutateYaml, routesBundle } from './fixtures.ts';

const b = bundle();
const FAST: Partial<Rules> = { dwellMs: { agent: 0, human: 0 } };

function world(over: Partial<Rules> = {}, warns: string[] = []) {
  const w = new World({ map: b.map, rules: { ...b.rules, ...over }, poses: b.catalog.characters.poses, onWarn: (m) => warns.push(m) });
  w.upsertEntity({ id: 'a', kind: 'human', podZoneId: 'pod:a' });
  return w;
}
const agent = (n: number) => ({ id: `agent:a:p:%${n}`, kind: 'agent' as const, ownerId: 'a' });
function run(w: World, ms: number, each?: () => void) {
  for (let t = 0; t < ms; t += 50) {
    w.tick(50);
    each?.();
  }
}
const ch = (w: World, id: string) => w.characters().find((c) => c.id === id);
const at = (w: World, id: string) => {
  const c = ch(w, id);
  return c ? [c.x, c.y] : null;
};

describe('World', () => {
  it('человек online: после dwell появляется у входа и садится на своё место', () => {
    const w = world();
    w.setStatus('a', 'online');
    run(w, 59_950);
    expect(ch(w, 'a')).toBeUndefined();
    run(w, 100);
    const c = ch(w, 'a')!;
    expect(c.x).toBe(6);
    expect(c.y).toBeLessThan(6);
    expect(c.pose).toBe('walk');
    run(w, 5000);
    expect(ch(w, 'a')).toMatchObject({ x: 1, y: 2, pose: 'sit', facing: 'up', anim: 'sitFront', offset: [0, -4] });
  });

  it('дребезг: статус, не продержавшийся dwell, не меняет цель', () => {
    const w = world();
    const A = agent(1);
    w.upsertEntity(A);
    w.setStatus(A.id, 'working');
    run(w, 10_000);
    w.setStatus(A.id, 'idle');
    run(w, 15_000);
    expect(ch(w, A.id)).toBeUndefined(); // working не созрел, idle ещё не созрел
    run(w, 10_000);
    expect(w.status(A.id)?.status).toBe('idle');
    run(w, 10_000);
    expect(ch(w, A.id)).toMatchObject({ x: 1, y: 5, pose: 'play' });
  });

  it('needs_input без dwell: из лаунжа сразу идёт в угол хозяина', () => {
    const w = world();
    const A = agent(1);
    w.upsertEntity(A);
    w.setStatus(A.id, 'idle');
    run(w, 30_000);
    expect(at(w, A.id)).toEqual([1, 5]);
    w.setStatus(A.id, 'needs_input');
    expect(w.status(A.id)?.status).toBe('needs_input');
    run(w, 6000);
    expect(ch(w, A.id)).toMatchObject({ x: 2, y: 2, pose: 'sit' });
  });

  it('needs_input за рабочим столом — остаётся на месте (current_work_seat)', () => {
    const w = world();
    const A = agent(1);
    w.upsertEntity(A);
    w.setStatus(A.id, 'working');
    run(w, 30_000);
    expect(at(w, A.id)).toEqual([2, 2]);
    w.setStatus(A.id, 'needs_input');
    run(w, 1000);
    expect(ch(w, A.id)).toMatchObject({ x: 2, y: 2, pose: 'sit' });
  });

  it('человек idle: после dwell — перерыв в лаунже (спека 17.11.2026)', () => {
    const w = world({ ...FAST, human: { ...b.rules.human, idle: [{ kind: 'zone', zoneId: 'lounge', pose: 'play' }, { kind: 'zone', zoneId: 'lounge' }] } });
    w.setStatus('a', 'online');
    run(w, 5000);
    expect(at(w, 'a')).toEqual([1, 2]);
    w.setStatus('a', 'idle');
    run(w, 10_000);
    expect(ch(w, 'a')).toMatchObject({ x: 1, y: 5, pose: 'play' });
  });

  it('человек needs_input без dwell: с лаунжа — на своё место, экран гаснет, облачко «?» (спека 17.11.2026)', () => {
    const w = world({
      ...FAST,
      human: { ...b.rules.human, idle: [{ kind: 'zone', zoneId: 'lounge', pose: 'play' }], needs_input: [{ kind: 'current_work_seat' }, { kind: 'own_seat' }] },
    });
    w.setStatus('a', 'idle');
    run(w, 10_000);
    expect(at(w, 'a')).toEqual([1, 5]);
    w.setStatus('a', 'needs_input');
    run(w, 6000);
    const c = ch(w, 'a')!;
    expect(c).toMatchObject({ x: 1, y: 2, pose: 'sit' });
    expect(c.screenSpot).toBeUndefined(); // экраны места гаснут у ждущего
    expect(w.questions()['a']).toBeTruthy(); // «?» без срока
    w.setStatus('a', 'online');
    run(w, 500);
    expect(ch(w, 'a')!.screenSpot).toBeTruthy(); // ответ — экраны снова горят
    expect(w.questions()['a']).toBeUndefined();
  });

  it('адресаты облачка: кадр несёт bubbleTo, новое сообщение заменяет прежнее вместе с адресатами (спека адресных сообщений 2.1.5, 2.4.4)', () => {
    const w = world(FAST);
    w.setStatus('a', 'online');
    run(w, 6000);
    const frame = () => w.characters().find((c) => c.id === 'a') as FrameCharacter;
    w.setBubble('a', 'личное', 60, ['p2']);
    expect(frame().bubble).toEqual({ text: 'личное', kind: 'info' });
    expect(frame().bubbleTo).toEqual(['p2']);
    const d = w.drainEvents().changed.find((c) => c.id === 'a') as FrameCharacter;
    expect([d.bubble?.text, d.bubbleTo]).toEqual(['личное', ['p2']]);
    w.setBubble('a', 'всем', 60, 'all');
    expect(frame().bubbleTo).toBe('all');
    w.setBubble('a', 'без адресата', 60);
    expect(frame().bubbleTo).toBeUndefined(); // уведомление без получателя (спека 2.1.1)
    run(w, 61_000); // ttl истёк — облачко снято вместе с адресатами
    expect(frame().bubble).toBeUndefined();
    expect(w.drainEvents().changed.find((c) => c.id === 'a')?.bubble).toBeNull();
  });

  it('current_work_seat у человека: рабочий статус online запоминает место — needs_input сидит где сидел', () => {
    const warns: string[] = [];
    const w = new World({ map: b.map, rules: { ...b.rules, ...FAST, human: { ...b.rules.human, online: [{ kind: 'zone', zoneId: 'coworking', pose: 'sit' }], needs_input: [{ kind: 'current_work_seat' }] } }, poses: b.catalog.characters.poses, onWarn: (m) => warns.push(m) });
    w.upsertEntity({ id: 'a', kind: 'human', podZoneId: 'pod:a' });
    w.setStatus('a', 'online');
    run(w, 10_000);
    const seat = at(w, 'a');
    expect(seat).toBeTruthy(); // сел в коворкинг — не на своё место
    expect(seat).not.toEqual([1, 2]);
    w.setStatus('a', 'needs_input');
    run(w, 10_000);
    expect(at(w, 'a')).toEqual(seat); // остался там же: current_work_seat разрешается и без фолбэка
    expect(warns).toEqual([]); // мёртвая цель не должна отправлять в запасную клетку с warn
  });

  it('offline: идёт к выходу и исчезает', () => {
    const w = world(FAST);
    w.setStatus('a', 'online');
    run(w, 6000);
    w.drainEvents();
    w.setStatus('a', 'offline');
    run(w, 6000);
    expect(ch(w, 'a')).toBeUndefined();
    expect(w.drainEvents().despawned).toEqual(['a']);
  });

  it('с участком: агент без капсул появляется у двери на тротуаре, проходит сквозь дверь по столбцу E; проход двери — обычная скорость (спека маршрутов 4.1, спека двери 4.2)', () => {
    const rb = routesBundle({ office: mutateYaml(ROUTES_OFFICE, (d) => (d.grid = d.grid.replaceAll('KKKKKK', '......'))) });
    const w = new World({ map: rb.map, rules: { ...rb.rules, ...FAST }, poses: rb.catalog.characters.poses });
    w.upsertEntity({ id: 'a', kind: 'human', podZoneId: 'pod:a' });
    w.upsertEntity({ id: 'g', kind: 'agent', ownerId: 'a' });
    w.setStatus('g', 'working');
    const seen: [number, number][] = [];
    run(w, 10_000, () => {
      const c = ch(w, 'g');
      if (c) seen.push([c.x, c.y]);
    });
    expect(seen[0]![0]).toBe(6);
    expect(seen[0]![1]).toBeGreaterThan(16.5); // появился у двери (и шагнул)
    expect(seen.filter(([, y]) => y > 13).every(([x]) => x === 6)).toBe(true); // ниже здания — только столбец двери
    expect(ch(w, 'g')).toMatchObject({ x: 2, y: 9, pose: 'sit' });
    const ticks = (lo: number, hi: number) => seen.filter(([x, y]) => x === 6 && y >= lo && y < hi).length;
    // Клетки проёма не скрытые — скорость ×1 (спека двери 4.2): 2 клетки проёма не быстрее 1,5 обычной
    // (при ускорении ×2, как раньше, было бы вдвое меньше тиков).
    expect(ticks(13.5, 15.5)).toBeGreaterThanOrEqual(ticks(15.5, 17.5));
    w.drainEvents();
    w.setStatus('g', 'offline');
    let last: [number, number] | null = null;
    run(w, 10_000, () => {
      const c = ch(w, 'g');
      if (c) last = [c.x, c.y];
    });
    expect(ch(w, 'g')).toBeUndefined();
    expect(last).not.toBeNull();
    expect(last![0]).toBe(6);
    expect(last![1]).toBeGreaterThan(16.5);
    expect(w.drainEvents().despawned).toEqual(['g']);
  });

  it('с участком: agents.arrival: metro — агент выходит из спуска метро и уходит в него, даже когда капсулы есть', () => {
    const rb = routesBundle({ office: mutateYaml(ROUTES_OFFICE, (d) => (d.agents = { arrival: 'metro' })) });
    const w = new World({ map: rb.map, rules: { ...rb.rules, ...FAST }, poses: rb.catalog.characters.poses });
    w.upsertEntity({ id: 'a', kind: 'human', podZoneId: 'pod:a' });
    w.upsertEntity({ id: 'g', kind: 'agent', ownerId: 'a' });
    w.setStatus('g', 'working');
    const seen: [number, number][] = [];
    run(w, 10_000, () => {
      const c = ch(w, 'g');
      if (c) seen.push([c.x, c.y]);
    });
    expect(seen[0]![0]).toBe(8); // из спуска метро (и шагнул): как у человека с commute: metro
    expect(seen[0]![1]).toBeLessThanOrEqual(25);
    expect(seen[0]![1]).toBeGreaterThan(23);
    expect(ch(w, 'g')).toMatchObject({ x: 2, y: 9, pose: 'sit' });
    w.drainEvents();
    w.setStatus('g', 'offline');
    let last: [number, number] | null = null;
    run(w, 10_000, () => {
      const c = ch(w, 'g');
      if (c) last = [c.x, c.y];
    });
    expect(ch(w, 'g')).toBeUndefined();
    expect(last![0]).toBe(8); // ушёл в метро, а не к капсулам
    expect(last![1]).toBeGreaterThanOrEqual(24);
    expect(w.drainEvents().despawned).toEqual(['g']);
  });

  it('очередь появления: по одному каждые 0,4 с', () => {
    const w = world(FAST);
    const [A, B] = [agent(1), agent(2)];
    w.upsertEntity(A);
    w.upsertEntity(B);
    w.setStatus(A.id, 'working');
    w.setStatus(B.id, 'working');
    w.tick(50);
    expect([!!ch(w, A.id), !!ch(w, B.id)]).toEqual([true, false]);
    run(w, 350);
    expect(ch(w, B.id)).toBeUndefined();
    run(w, 50);
    expect(ch(w, B.id)).toBeDefined();
  });

  it('смена цели посреди пути — перепланирование, блокирующие клетки не посещаются', () => {
    const w = world(FAST);
    const A = agent(1);
    w.upsertEntity(A);
    w.setStatus(A.id, 'working');
    run(w, 1000);
    w.setStatus(A.id, 'idle');
    const visited: string[] = [];
    run(w, 8000, () => {
      const c = ch(w, A.id);
      if (c) visited.push(`${Math.round(c.x)},${Math.round(c.y)}`);
    });
    expect(ch(w, A.id)).toMatchObject({ x: 1, y: 5, pose: 'play' });
    expect(visited.filter((k) => { const [x, y] = k.split(',').map(Number); return b.map.isBlocked(x!, y!); })).toEqual([]);
  });

  it('брони: места не дублируются; нехватка — коворкинг, затем запасная клетка с warn', () => {
    const warns: string[] = [];
    const w = world(FAST, warns);
    const agents = [1, 2, 3, 4, 5, 6].map(agent);
    for (const A of agents) {
      w.upsertEntity(A);
      w.setStatus(A.id, 'working');
    }
    run(w, 15_000);
    const pos = agents.map((A) => at(w, A.id)!.join(','));
    expect(new Set(pos).size).toBe(6);
    expect(pos.slice(0, 5).sort()).toEqual(['10,2', '11,2', '2,2', '3,2', '4,2']);
    const [fx, fy] = at(w, agents[5]!.id)!;
    expect(fx).toBeGreaterThanOrEqual(9);
    expect(fx).toBeLessThanOrEqual(12);
    expect(fy).toBeLessThanOrEqual(3);
    expect(warns.some((m) => m.includes('недоступна'))).toBe(true);
  });

  it('owner_pod_seat предпочитает место, где агент сидел в прошлый раз', () => {
    const w = world(FAST);
    const [X, W] = [agent(1), agent(2)];
    w.upsertEntity(W);
    w.upsertEntity(X);
    w.setStatus(W.id, 'working');
    run(w, 500);
    w.setStatus(X.id, 'working');
    run(w, 10_000);
    expect(at(w, X.id)).toEqual([3, 2]);
    w.setStatus(W.id, 'offline');
    w.setStatus(X.id, 'idle');
    run(w, 10_000);
    w.setStatus(X.id, 'working');
    run(w, 10_000);
    expect(at(w, X.id)).toEqual([3, 2]); // без предпочтения сел бы на свободное (2,2)
  });

  it('stay — остаётся где есть', () => {
    const w = world({ ...FAST, agent: { ...b.rules.agent, needs_input: [{ kind: 'stay' }] } });
    const A = agent(1);
    w.upsertEntity(A);
    w.setStatus(A.id, 'idle');
    run(w, 10_000);
    w.setStatus(A.id, 'needs_input');
    run(w, 3000);
    expect(at(w, A.id)).toEqual([1, 5]);
  });

  it('drainEvents отдаёт изменения один раз', () => {
    const w = world(FAST);
    w.setStatus('a', 'online');
    w.tick(50);
    expect(w.drainEvents().changed.map((c) => c.id)).toEqual(['a']);
    expect(w.drainEvents().changed).toEqual([]);
  });

  it('встречи, конкурирующие в одном тике: сначала по meetingId; проигравшая получает warn', () => {
    const warns: string[] = [];
    const w = world(FAST, warns);
    w.upsertEntity({ id: 'b', kind: 'human' });
    w.setStatus('a', 'meeting', 'zz');
    w.setStatus('b', 'meeting', 'aa');
    run(w, 6000);
    expect(at(w, 'b')).not.toBeNull();
    expect(ch(w, 'b')).toMatchObject({ pose: 'sit' });
    expect(warns.some((m) => m.startsWith('a:') && m.includes('недоступна'))).toBe(true);
    expect(warns.some((m) => m.startsWith('b:') && m.includes('недоступна'))).toBe(false);
  });

  it('переговорка освобождается после того, как meeting покинут (после dwell), и достаётся следующей встрече', () => {
    const w = world({ dwellMs: { agent: 0, human: 1000 } });
    w.upsertEntity({ id: 'b', kind: 'human' });
    w.setStatus('a', 'meeting', 'm1');
    run(w, 1050);
    w.setStatus('a', 'online');
    run(w, 400);
    w.setStatus('b', 'meeting', 'm2');
    run(w, 500); // t=1950: online у a ещё не принят, встреча m1 держит комнату
    expect(w.status('a')?.status).toBe('meeting');
    run(w, 1500); // a принят как online, комната освобождена; b созрел позже и получил её
    expect(w.status('a')?.status).toBe('online');
    expect(w.status('b')?.status).toBe('meeting');
    run(w, 6000);
    expect(ch(w, 'b')).toMatchObject({ pose: 'sit' });
  });

  it('разговор: у участника встречи на месте — группа talk (первая переговорка встречи), в пути и вне встречи — нет', () => {
    const w = world(FAST);
    w.upsertEntity({ id: 'b', kind: 'human' });
    w.setStatus('a', 'meeting', 'm1');
    w.setStatus('b', 'meeting', 'm1');
    run(w, 200);
    expect(ch(w, 'a')).toMatchObject({ pose: 'walk' });
    expect(ch(w, 'a')!.talk).toBeUndefined();
    run(w, 8000);
    expect(ch(w, 'a')).toMatchObject({ pose: 'sit', talk: 'meeting:m1' });
    expect(ch(w, 'b')).toMatchObject({ pose: 'sit', talk: 'meeting:m1' });
    w.setStatus('a', 'online');
    w.tick(50);
    expect(ch(w, 'a')!.talk).toBeUndefined();
  });

  it('комната уходящей встречи достаётся встрече, созревшей в том же тике', () => {
    const w = world(FAST);
    w.upsertEntity({ id: 'b', kind: 'human' });
    w.setStatus('a', 'meeting', 'm1');
    run(w, 6000);
    expect(ch(w, 'a')).toMatchObject({ pose: 'sit' });
    expect(w.debugInfo().meetings).toEqual({ m1: ['meeting:m1'] });
    w.setStatus('a', 'online'); // тот же since, что и у b
    w.setStatus('b', 'meeting', 'm2');
    w.tick(50);
    expect(w.debugInfo().meetings).toEqual({ m2: ['meeting:m1'] });
    run(w, 6000);
    expect(ch(w, 'b')).toMatchObject({ pose: 'sit' });
  });

  it('ещё не принятый статус meeting не удерживает комнату: её получает созревшая раньше встреча', () => {
    const w = world({ dwellMs: { agent: 0, human: 1000 } });
    w.upsertEntity({ id: 'c', kind: 'human' });
    w.upsertEntity({ id: 'd', kind: 'human' });
    w.setStatus('a', 'meeting', 'm1');
    run(w, 1050); // a принят в m1, комната закреплена
    w.setStatus('a', 'online'); // принят на t=2050
    run(w, 50);
    w.setStatus('d', 'meeting', 'm2'); // созреет на t=2100
    run(w, 100);
    w.setStatus('c', 'meeting', 'm1'); // созреет на t=2200, позже d
    run(w, 1200);
    expect(w.status('c')?.status).toBe('meeting');
    expect(w.debugInfo().meetings).toEqual({ m2: ['meeting:m1'] });
    run(w, 6000);
    expect(ch(w, 'd')).toMatchObject({ pose: 'sit' });
    expect(ch(w, 'c')).toBeUndefined();
  });

  it('потребность встречи считает всех участников: трое выбирают комнату на 4, а не на 2', () => {
    const spots: Spot[] = [];
    const add = (zoneId: string, x: number, y: number) =>
      spots.push({ id: `${zoneId}#${x},${y}`, x, y, facing: 'up', pose: 'sit', offset: [0, 0], label: 'below', fidgets: [], tags: [], itemUid: 'x', zoneId });
    [1, 2].forEach((x) => add('meeting:small', x, 1));
    [1, 2, 3, 4].forEach((x) => add('meeting:big', x, 3));
    const zones: Zone[] = [
      { id: 'meeting:small', kind: 'meeting', rect: [0, 0, 10, 2] },
      { id: 'meeting:big', kind: 'meeting', rect: [0, 2, 10, 2] },
    ];
    const map = new WorldMap({ width: 10, height: 6, blocked: new Uint8Array(60), spots, zones, entrances: [[0, 5]] });
    const w = new World({ map, rules: { ...b.rules, ...FAST }, poses: b.catalog.characters.poses });
    for (const id of ['h1', 'h2', 'h3']) {
      w.upsertEntity({ id, kind: 'human' });
      w.setStatus(id, 'meeting', 'm1');
    }
    run(w, 10_000);
    const pos = ['h1', 'h2', 'h3'].map((id) => at(w, id)!);
    expect(pos.map((p) => p[1])).toEqual([3, 3, 3]);
    expect(new Set(pos.map((p) => p.join(','))).size).toBe(3);
  });

  it('бытовые анимации места (fidgets) уходят зрителю, пока сидит на месте; на ходу их нет', () => {
    const spots: Spot[] = [
      { id: 'u#0', x: 2, y: 1, facing: 'down', pose: 'sit', offset: [0, 14], label: 'above', fidgets: ['phone', 'reading'], tags: [], itemUid: 'u', zoneId: 'pod:a' },
    ];
    const zones: Zone[] = [{ id: 'pod:a', kind: 'pod', rect: [0, 0, 5, 3] }];
    const map = new WorldMap({ width: 5, height: 5, blocked: new Uint8Array(25), spots, zones, entrances: [[0, 4]] });
    const rules: Rules = { ...b.rules, ...FAST, human: { ...b.rules.human, online: [{ kind: 'zone', zoneId: 'pod:a' }] } };
    const w = new World({ map, rules, poses: b.catalog.characters.poses });
    w.upsertEntity({ id: 'h', kind: 'human' });
    w.setStatus('h', 'online');
    run(w, 200);
    expect(ch(w, 'h')).toMatchObject({ pose: 'walk' });
    expect(ch(w, 'h')!.fidgets).toBeUndefined();
    run(w, 5000);
    expect(ch(w, 'h')).toMatchObject({ x: 2, y: 1, pose: 'sit', label: 'above', fidgets: ['phone', 'reading'] });
    w.setStatus('h', 'offline');
    run(w, 200);
    expect(ch(w, 'h')).toMatchObject({ pose: 'walk' });
    expect(ch(w, 'h')!.fidgets).toBeUndefined();
  });
});

describe('World: экраны места (screenSpot, спека экранов 4.2)', () => {
  it('сидящий человек online и агент working включают экраны своего места; в пути — нет', () => {
    const w = world(FAST);
    const A = agent(1);
    w.upsertEntity(A);
    w.setStatus('a', 'online');
    w.setStatus(A.id, 'working');
    run(w, 200);
    expect(ch(w, 'a')).toMatchObject({ pose: 'walk' });
    expect(ch(w, 'a')!.screenSpot).toBeUndefined();
    run(w, 8000);
    expect(ch(w, 'a')).toMatchObject({ x: 1, y: 2, pose: 'sit', screenSpot: 'chair@1,2#0' });
    expect(ch(w, A.id)).toMatchObject({ x: 2, y: 2, pose: 'sit', screenSpot: 'chair@2,2#0' });
  });

  it('агент idle за автоматом включает экраны автомата', () => {
    const w = world(FAST);
    const A = agent(1);
    w.upsertEntity(A);
    w.setStatus(A.id, 'idle');
    run(w, 8000);
    expect(ch(w, A.id)).toMatchObject({ x: 1, y: 5, pose: 'play', screenSpot: 'arcade@1,4#0' });
  });

  it('needs_input на том же месте — экраны гаснут сразу (в delta); ответ — горят снова; ушёл — гаснут', () => {
    const w = world(FAST);
    const A = agent(1);
    w.upsertEntity(A);
    w.setStatus(A.id, 'working');
    run(w, 8000);
    expect(ch(w, A.id)).toMatchObject({ x: 2, y: 2, screenSpot: 'chair@2,2#0' });
    w.drainEvents();
    w.setStatus(A.id, 'needs_input');
    w.tick(50);
    const changed = w.drainEvents().changed.find((c) => c.id === A.id);
    expect(changed).toMatchObject({ x: 2, y: 2, pose: 'sit' });
    expect(changed!.screenSpot).toBeUndefined();
    w.setStatus(A.id, 'working');
    run(w, 100);
    expect(ch(w, A.id)).toMatchObject({ x: 2, y: 2, screenSpot: 'chair@2,2#0' });
    w.setStatus(A.id, 'offline');
    run(w, 200);
    expect(ch(w, A.id)).toMatchObject({ pose: 'walk' });
    expect(ch(w, A.id)!.screenSpot).toBeUndefined();
  });

  it('запасная клетка (мест не хватило) — стоит, экраны не горят', () => {
    const w = world(FAST);
    const agents = [1, 2, 3, 4, 5, 6].map(agent);
    for (const A of agents) {
      w.upsertEntity(A);
      w.setStatus(A.id, 'working');
    }
    run(w, 15_000);
    expect(ch(w, agents[4]!.id)!.screenSpot).toMatch(/^chair@/);
    expect(ch(w, agents[5]!.id)).toMatchObject({ pose: 'stand' }); // шестому места нет — запасная клетка
    expect(ch(w, agents[5]!.id)!.screenSpot).toBeUndefined();
  });

  it('stay на месте автомата: остаётся играть — экраны горят', () => {
    const w = world({ ...FAST, agent: { ...b.rules.agent, working: [{ kind: 'stay' }] } });
    const A = agent(1);
    w.upsertEntity(A);
    w.setStatus(A.id, 'idle');
    run(w, 8000);
    expect(ch(w, A.id)).toMatchObject({ x: 1, y: 5, pose: 'play', screenSpot: 'arcade@1,4#0' });
    w.setStatus(A.id, 'working');
    run(w, 1000);
    expect(ch(w, A.id)).toMatchObject({ x: 1, y: 5, pose: 'play', screenSpot: 'arcade@1,4#0' });
  });

  it('bootstrap: севший сразу с экранами; ждущий ответа — без', () => {
    const w = world();
    const A = agent(1);
    const B = agent(2);
    w.upsertEntity(A);
    w.upsertEntity(B);
    w.bootstrap([{ id: 'a', status: 'online' }, { id: A.id, status: 'working' }, { id: B.id, status: 'needs_input' }]);
    expect(ch(w, 'a')!.screenSpot).toBe('chair@1,2#0');
    expect(ch(w, A.id)!.screenSpot).toMatch(/^chair@\d+,2#0$/);
    expect(ch(w, B.id)).toMatchObject({ pose: 'sit' });
    expect(ch(w, B.id)!.screenSpot).toBeUndefined();
  });
});
