import type { AnimName, Bubble, CharacterState, Facing, Pose, Status, VehicleState } from '@pixeloffice/protocol';
import type { CharactersDef } from '../catalog.ts';
import { animFor } from '../characters.ts';
import { zoneContains, type Zone } from '../office.ts';
import { findPath, type Cell } from '../path/astar.ts';
import { fnv1a } from '../random.ts';
import type { RuleTarget, Rules } from '../rules.ts';
import { byCodePoint, type DockSpot, type Spot, type WorldMap } from '../world-map.ts';
import { MeetingRooms } from './meetings.ts';
import { commuteFor, portalOf } from './portals.ts';
import { resolveTargets, type ResolveContext } from './targets.ts';
import { Traffic } from './traffic.ts';
import { BUS_STOP_MS, CAR_LEAVE_MS, personBox, type SpotPlan } from './transport.ts';
import type { SimEntity } from './types.ts';

export type WorldOptions = {
  map: WorldMap;
  rules: Rules;
  poses: CharactersDef['poses'];
  speedCellsPerSec?: number;
  spawnIntervalMs?: number;
  dockCycleMs?: number; // цикл капсулы; тестам нужен длинный
  onWarn?: (msg: string) => void;
};

type StatusRec = { status: Status; meetingId?: string };
// Цель ухода (спека маршрутов 4.3, 4.8, спека транспорта 4.5): cell — конец пути по клеткам, point — точка портала (у
// места-портала — клетка плюс сдвиг места), via — точка между ними (у машины — точка у двери перед шагом под кузов),
// spotId — забронированное место-портал, busWait — стоять на точке до автобуса (остановка), board — идёт к двери
// автобуса, facing — взгляд на точке, dockWait — ждёт, пока освободится капсула, sleep — лечь на спальное место
// парка и остаться (спека сна 5.3).
type ExitGoal = {
  kind: 'exit';
  cell: Cell;
  point: Cell;
  via?: Cell;
  spotId: string | null;
  busWait: boolean;
  board?: true;
  facing: Facing | null;
  dockWait?: boolean;
  sleep?: true;
};
type Goal = { kind: 'spot'; spotId: string } | { kind: 'cell'; x: number; y: number } | ExitGoal | { kind: 'stay' };
type Char = {
  e: SimEntity;
  latest: StatusRec & { since: number }; // последний сырой статус
  committed: StatusRec; // принятый (прошёл dwell)
  visible: boolean;
  queue: string | null; // ключ очереди появления, в которой стоит
  busWaitSince: number | null; // с какого момента стоит на остановке до автобуса (спека транспорта 4.5.4)
  carLeaveAt: number | null; // когда стоящей машине без хозяина у двери трогаться (спека транспорта 4.5.2)
  entered: boolean; // начал вход в капсулу цели (событие цикла уже было)
  holding: boolean; // ждёт конца цикла перед капсулой
  yielding: boolean; // ждёт, пока едущий транспорт освободит следующую клетку (спека транспорта 4.4)
  x: number;
  y: number;
  facing: Facing;
  pose: Pose | 'walk';
  anim: AnimName;
  offset: [number, number];
  labelAbove: boolean; // место с label: above — подпись над головой
  fidgets: AnimName[]; // бытовые анимации места; вне места — пусто
  seatSpot: string | null; // место, на котором сидит (у автомата — играет); в пути и вне места — null
  path: Cell[];
  goal: Goal | null;
  reserved: string | null;
  workSeat: string | null;
  lastSeat: string | null;
  bubble: { text: string; kind: Bubble['kind']; expiresAt: number; to?: BubbleTo } | null;
  bubbleDirty: boolean;
  fallback: boolean; // цель — запасная (ни одна цель правил не подошла), пересматривается раз в FALLBACK_RECHECK_MS
};

const FALLBACK_RECHECK_MS = 5000;
// Облачко ждущего ответа, когда текста запроса нет (перезапуск без снимка, статус без облачка).
export const WAITING_TEXT = 'Ждёт ответа';

// Адресаты облачка (спека адресных сообщений 2.1): 'all' — объявление, видно каждому зрителю, включая общие
// токены; список id людей — личное сообщение, его видит только адресат; undefined — адресата нет: текст хранится
// у персонажа, но в кадры не попадает. Кадры по адресатам фильтрует сервер (frames.ts), мир только хранит их
// рядом с облачком и снимает вместе с ним (TTL, ответ на needs_input, исчезновение сущности).
export type BubbleTo = 'all' | string[];
// Сохранённый вопрос ждущего (спека адресных сообщений 2.1.7): текст и адресаты облачка-запроса; to нет —
// безадресное. Снимки старого формата — только строка текста, восстанавливаются как «всем» (до этой спеки
// публичны были все облачка).
export type StoredQuestion = { text: string; to?: BubbleTo };
// Результат World.setBubble (спека написания сообщения 2.1.10).
export type SetBubbleResult = 'ok' | 'absent' | 'asleep';
// Кадр персонажа для сервера (спека адресных сообщений 2.4): bubbleTo — адресаты облачка, внутреннее поле;
// фильтр по зрителю срезает его до сериализации, в протокол оно не попадает.
export type FrameCharacter = CharacterState & { bubbleTo?: BubbleTo };

const DIRS: Cell[] = [[0, -1], [1, 0], [0, 1], [-1, 0]];
const ALONG_FIRST: Cell[] = [[-1, 0], [1, 0], [0, -1], [0, 1]]; // сначала вдоль ряда
const sameStatus = (a: StatusRec, b: StatusRec) => a.status === b.status && (a.meetingId ?? null) === (b.meetingId ?? null);
const round3 = (v: number) => Math.round(v * 1000) / 1000;
const facingOf = (dx: number, dy: number): Facing => (Math.abs(dx) >= Math.abs(dy) ? (dx > 0 ? 'right' : 'left') : dy > 0 ? 'down' : 'up');
// Цель ухода на спальное место s (спека сна 5.3): клетка и точка — клетка места, с бронью.
const sleepGoal = (s: Spot): ExitGoal => ({ kind: 'exit', cell: [s.x, s.y], point: [s.x, s.y], spotId: s.id, busWait: false, facing: s.facing, sleep: true });

// Во столько раз быстрее ходьба по скрытым клеткам, где вьюер персонажа не показывает (спека маршрутов 4.4);
// после спеки двери скрытая клетка одна — нижняя ступень метро (спека двери 4.2).
const HIDDEN_SPEEDUP = 2;
// Цикл капсулы (спека маршрутов 4.5): после события капсулы (появление агента, начало входа) следующее — не раньше.
export const DOCK_CYCLE_MS = 2000;

export class World {
  private readonly map: WorldMap;
  private rules: Rules;
  private readonly poses: CharactersDef['poses'];
  private readonly speed: number;
  private readonly spawnInterval: number;
  private readonly dockCycle: number;
  private readonly warn: (msg: string) => void;
  private readonly chars = new Map<string, Char>();
  private readonly reservations = new Map<string, string>();
  private readonly meetings: MeetingRooms;
  // Очереди появления по порталам (спека маршрутов 4.5): люди из метро и с парковки друг друга не ждут.
  private readonly queues = new Map<string, { ids: string[]; nextAt: number }>();
  private readonly dockFree = new Map<string, number>(); // id места капсулы → когда кончается её цикл
  private readonly traffic: Traffic | null; // транспорт участка (спека транспорта 4.2); без участка — null
  private readonly gaps = new Map<string, number>(); // клетка крайнего столбца места парковки → сдвиг узла пути к щели
  private busAt: number | null = null; // когда автобус встал в карман
  private busIdleAt: number | null = null; // начало второй паузы
  private nextFallbackCheck = FALLBACK_RECHECK_MS;
  private despawned: string[] = [];
  private readonly lastSent = new Map<string, string>();
  private t = 0;

  constructor(o: WorldOptions) {
    this.map = o.map;
    this.rules = o.rules;
    this.poses = o.poses;
    this.speed = o.speedCellsPerSec ?? 3;
    this.spawnInterval = o.spawnIntervalMs ?? 400;
    this.dockCycle = o.dockCycleMs ?? DOCK_CYCLE_MS;
    this.warn = o.onWarn ?? (() => {});
    this.meetings = new MeetingRooms(o.map);
    this.traffic = o.map.transport ? new Traffic(o.map.transport) : null;
    // Щели между машинами (спека транспорта 3.3): левый столбец места — к щели слева, правый — к щели справа.
    for (const s of o.map.transport?.spots ?? []) {
      for (let j = 0; j < 5; j++) {
        this.gaps.set(`${s.spot[0]},${s.spot[1] + j}`, -0.5);
        this.gaps.set(`${s.spot[0] + 2},${s.spot[1] + j}`, 0.5);
      }
    }
  }

  now(): number {
    return this.t;
  }

  upsertEntity(e: SimEntity): void {
    const existing = this.chars.get(e.id);
    if (existing) {
      existing.e = e;
      return;
    }
    const [ex, ey] = this.portalStart(e);
    this.chars.set(e.id, {
      e,
      latest: { status: 'offline', since: this.t },
      committed: { status: 'offline' },
      visible: false,
      queue: null,
      busWaitSince: null,
      carLeaveAt: null,
      entered: false,
      holding: false,
      yielding: false,
      x: ex,
      y: ey,
      facing: 'up',
      pose: 'stand',
      anim: 'idle',
      offset: [0, 0],
      labelAbove: false,
      fidgets: [],
      seatSpot: null,
      path: [],
      goal: null,
      reserved: null,
      workSeat: null,
      lastSeat: null,
      bubble: null,
      bubbleDirty: false,
      fallback: false,
    });
  }

  removeEntity(id: string): void {
    const c = this.chars.get(id);
    if (!c) return;
    if (c.reserved) this.reservations.delete(c.reserved);
    if (c.visible) this.despawned.push(id);
    this.dequeue(c);
    this.lastSent.delete(id);
    this.chars.delete(id);
  }

  status(id: string): StatusRec | undefined {
    return this.chars.get(id)?.committed;
  }

  setStatus(id: string, status: Status, meetingId?: string): void {
    const c = this.chars.get(id);
    if (!c) return;
    const next: StatusRec = { status, meetingId };
    if (sameStatus(c.latest, next)) return;
    c.latest = { ...next, since: this.t };
    // Ответ на запрос: облачко «?» гаснет сразу по сырому статусу, цель меняется по dwell (уточнение решения 12).
    if (status !== 'needs_input' && c.bubble?.kind === 'needs_input') {
      c.bubble = null;
      c.bubbleDirty = true;
    }
    if (sameStatus(c.latest, c.committed)) return; // вернулся к принятому — ждать нечего
    if (status === 'needs_input') this.commit(c); // без dwell (спека 4.4)
  }

  // Результат установки облачка (спека написания сообщения 2.1.10): 'ok' — поставлено видимому; 'absent' —
  // персонажа нет в мире или он не виден (событию адаптера облачок всё равно ставится и приходит с появлением
  // персонажа — для события это только возврат); 'asleep' — спит в парке.
  setBubble(id: string, text: string, ttlSec: number, to?: BubbleTo): SetBubbleResult {
    const c = this.chars.get(id);
    if (!c) return 'absent';
    // Спящий в парке не говорит (спека сна 5.6): облачко offline-человека раньше не было видно — он был невидим, а
    // «невидимка» (человек без статуса от источника, шлющий облачка) не должна выдавать себя над спальником.
    if (c.pose === 'sleep') return 'asleep';
    // needs_input принимается без dwell, так что сырой статус точен; после ответа облачко — обычное.
    const kind = c.latest.status === 'needs_input' ? 'needs_input' : 'info';
    // Новое сообщение заменяет прежнее вместе с его адресатами (спека адресных сообщений 2.1.5).
    c.bubble = { text, kind, expiresAt: this.t + ttlSec * 1000, to };
    c.bubbleDirty = true;
    return c.visible ? 'ok' : 'absent';
  }

  // Старт сервера: статусы без dwell, онлайн-сущности сразу на местах (спека 4.7, 5.4); offline-люди парка —
  // на спальных местах (спека сна 5.5).
  // sleepSpot — спальное место из снимка (sleepSpots): лежал на нём или шёл к нему до перезапуска.
  bootstrap(list: { id: string; status: Status; meetingId?: string; question?: StoredQuestion; sleepSpot?: string }[]): void {
    // Проход 1: статусы всех сразу, чтобы потребность встречи (meetingNeed) видела всех участников.
    const online: Char[] = [];
    const sleepers: Char[] = [];
    for (const s of list) {
      const c = this.chars.get(s.id);
      if (!c) continue;
      c.latest = { status: s.status, meetingId: s.meetingId, since: this.t };
      c.committed = { status: s.status, meetingId: s.meetingId };
      c.visible = false;
      c.path = [];
      this.dequeue(c);
      if (s.status === 'offline') {
        if (c.reserved) this.reservations.delete(c.reserved);
        c.reserved = null;
        c.goal = null;
        if (this.parkSleeper(c)) sleepers.push(c);
        continue;
      }
      if (s.status === 'needs_input') this.ensureQuestion(c, s.question);
      // Машина присутствующего — сразу на месте (спека транспорта 4.6).
      const car = this.carPlan(c);
      if (car) this.traffic!.placeParked(this.carId(c), c.e.carModel ?? 1, car.key);
      online.push(c);
    }
    // Проход 2: цели и мгновенная расстановка.
    for (const c of online) {
      this.retarget(c); // невидимый: цель назначена и поставлен в очередь
      this.dequeue(c);
      if (c.goal && (c.goal.kind === 'spot' || c.goal.kind === 'cell')) {
        const [x, y] = this.goalCell(c.goal);
        c.x = x;
        c.y = y;
        c.visible = true;
        this.arrive(c);
        c.bubbleDirty = c.bubble !== null;
      }
    }
    // Проход 3 (спека сна 5.5): offline-люди парка сразу лежат — видимые, с бронью. Сначала записанные в снимке — на
    // своё место из снимка: раздача в живом мире зависит от порядка ухода, и без записи после перезапуска на скамейках
    // при совпадениях и нехватке мест лежали бы другие люди. Потом остальные (снимок старый или ушли после него) — в
    // порядке id на свободное место по sleepSpot. Мест не хватило — невидим, как остальные offline; придя в online,
    // появится на портале.
    const bedOf = new Map(list.map((s) => [s.id, s.sleepSpot]));
    sleepers.sort((a, b) => byCodePoint(a.e.id, b.e.id));
    const rest: Char[] = [];
    for (const c of sleepers) {
      const id = bedOf.get(c.e.id);
      if (id && this.map.portals.parkSleep.includes(id) && !this.reservations.has(id)) this.lieDown(c, this.map.spot(id)!);
      else rest.push(c);
    }
    for (const c of rest) {
      const s = this.sleepSpot(c);
      if (s) this.lieDown(c, s);
    }
  }

  // Старт сервера: человек парка сразу лежит на месте s. Цель ухода ставит обычный setGoal: путь из клетки места в неё
  // же сразу даёт arrive.
  private lieDown(c: Char, s: Spot): void {
    c.x = s.x;
    c.y = s.y;
    c.visible = true;
    this.setGoal(c, sleepGoal(s));
    c.bubbleDirty = c.bubble !== null;
  }

  setRules(rules: Rules): void {
    this.rules = rules;
    for (const c of this.chars.values()) if (c.committed.status !== 'offline') this.retarget(c);
  }

  // Тексты облачков-запросов ждущих: сервер сохраняет их, чтобы после перезапуска вопрос не пропал; вместе с
  // текстом — адресаты (спека адресных сообщений 2.1.7).
  questions(): Record<string, StoredQuestion> {
    const out: Record<string, StoredQuestion> = {};
    for (const c of this.chars.values()) if (c.bubble?.kind === 'needs_input') out[c.e.id] = { text: c.bubble.text, to: c.bubble.to };
    return out;
  }

  // Кто на каком спальном месте парка (лежит или идёт к нему): сервер сохраняет в снимок, чтобы после перезапуска на
  // скамейках лежали те же люди (спека сна 5.5).
  sleepSpots(): Record<string, string> {
    const out: Record<string, string> = {};
    for (const c of this.chars.values()) if (c.visible && c.goal?.kind === 'exit' && c.goal.sleep && c.goal.spotId) out[c.e.id] = c.goal.spotId;
    return out;
  }

  lastSeats(): Record<string, string> {
    const out: Record<string, string> = {};
    for (const c of this.chars.values()) if (c.lastSeat) out[c.e.id] = c.lastSeat;
    return out;
  }

  restoreLastSeats(rec: Record<string, string>): void {
    for (const [id, spotId] of Object.entries(rec)) {
      const c = this.chars.get(id);
      if (c && this.map.spot(spotId)) c.lastSeat = spotId;
    }
  }

  debugInfo(): {
    paths: Record<string, [number, number][]>;
    reservations: Record<string, string>;
    meetings: Record<string, string[]>;
    vehicles?: Record<string, [number, number][]>;
    mouthLock?: string | null;
    lotLock?: string[];
  } {
    const paths: Record<string, [number, number][]> = {};
    for (const c of this.chars.values()) if (c.visible && c.path.length > 0) paths[c.e.id] = c.path.map(([x, y]) => [x, y]);
    return { paths, reservations: Object.fromEntries(this.reservations), meetings: this.meetings.allocations(), ...(this.traffic?.debugInfo() ?? {}) };
  }

  vehicles(): VehicleState[] {
    return this.traffic?.vehicles() ?? [];
  }

  tick(dtMs: number): void {
    this.t += dtMs;
    for (const c of this.chars.values()) {
      // Облачко-запрос живёт, пока агент ждёт ответа: гаснет только со сменой статуса, не по ttl.
      if (c.bubble && c.bubble.kind !== 'needs_input' && c.bubble.expiresAt <= this.t) {
        c.bubble = null;
        c.bubbleDirty = true;
      }
    }
    const due = [...this.chars.values()].filter((c) => !sameStatus(c.latest, c.committed) && this.t - c.latest.since >= this.dwell(c));
    due.sort(
      (a, b) =>
        a.latest.since - b.latest.since ||
        byCodePoint(a.latest.meetingId ?? '', b.latest.meetingId ?? '') ||
        byCodePoint(a.e.id, b.e.id),
    );
    for (const c of due) this.commit(c);
    this.releaseMeetings();
    // Место или переговорка могли освободиться: стоящие в запасной клетке пробуют цели правил снова.
    if (this.t >= this.nextFallbackCheck) {
      this.nextFallbackCheck = this.t + FALLBACK_RECHECK_MS;
      for (const c of this.chars.values()) if (c.fallback && c.committed.status !== 'offline') this.recheckFallback(c);
    }
    this.processSpawns();
    // Ждущие брони капсулы пробуют снова, как только одна освободилась (спека маршрутов 4.6.4).
    if (this.map.portals.docks.some((d) => !this.reservations.has(d.spotId))) {
      for (const c of this.chars.values()) {
        if (!c.visible || c.goal?.kind !== 'exit' || !c.goal.dockWait) continue;
        const g = this.exitGoal(c);
        if (!g.dockWait) this.setGoal(c, g);
      }
    }
    // Транспорт уступает видимым людям (спека транспорта 4.4): клетки — по позициям до их шага в этом тике.
    this.traffic?.tick(dtMs, [...this.chars.values()].filter((c) => c.visible).map((c) => personBox(c.x, c.y)));
    // Машина встала (спека транспорта 4.7.3): идущие, чей оставшийся путь проходит по её клеткам, — заново к той же цели
    // от текущей клетки, тем же механизмом, что смена цели на ходу.
    if (this.traffic) {
      const t = this.traffic;
      const cells = new Set(t.drainParked().flatMap((id) => t.parkedCells(id)).map(([x, y]) => `${x},${y}`));
      if (cells.size) for (const c of this.chars.values()) if (c.visible && c.goal && c.path.some(([x, y]) => cells.has(`${x},${y}`))) this.setGoal(c, c.goal);
    }
    this.busStep(); // встал в этом тике — отсчёт паузы с этого тика
    for (const c of this.chars.values()) this.move(c, dtMs);
    this.carsStep(); // после шагов: сел в машину в этом тике — отсчёт с этого тика
  }

  characters(): FrameCharacter[] {
    return [...this.chars.values()]
      .filter((c) => c.visible)
      .map((c) => (c.bubble ? { ...this.stateOf(c), bubble: this.bubbleOf(c), bubbleTo: c.bubble.to } : this.stateOf(c)));
  }

  drainEvents(): { changed: FrameCharacter[]; despawned: string[] } {
    const changed: FrameCharacter[] = [];
    for (const c of this.chars.values()) {
      if (!c.visible) continue;
      const s = this.stateOf(c);
      const key = JSON.stringify(s);
      if (this.lastSent.get(c.e.id) === key && !c.bubbleDirty) continue;
      this.lastSent.set(c.e.id, key);
      changed.push(c.bubbleDirty ? { ...s, bubble: this.bubbleOf(c), bubbleTo: c.bubble?.to } : s);
      c.bubbleDirty = false;
    }
    const despawned = this.despawned.filter((id) => !this.chars.get(id)?.visible);
    this.despawned = [];
    return { changed, despawned };
  }

  // ---- внутреннее ----

  // Ждущий ответа никогда не остаётся без пометки: облачко становится запросом, а если облачка нет —
  // показывается сохранённый вопрос или «Ждёт ответа» — «всем» (состояние персонажа, а не сообщение, спека
  // адресных сообщений 2.1.7). Облачко-запрос с текстом от события хранит адресатов этого события.
  // Облачко-запрос живёт без срока (гаснет со сменой статуса).
  private ensureQuestion(c: Char, q?: StoredQuestion): void {
    if (c.bubble && c.bubble.kind === 'needs_input') return;
    if (c.bubble) c.bubble.kind = 'needs_input'; // существующее облачко сохраняет адресатов своего события
    else c.bubble = { text: q?.text ?? WAITING_TEXT, kind: 'needs_input', expiresAt: Infinity, to: q === undefined ? 'all' : q.to };
    c.bubbleDirty = true;
  }

  private dwell(c: Char): number {
    return c.e.kind === 'agent' ? this.rules.dwellMs.agent : this.rules.dwellMs.human;
  }

  private commit(c: Char): void {
    const was = c.committed.status;
    c.committed = { status: c.latest.status, meetingId: c.latest.meetingId };
    // Решение 12: ответ на запрос — облачко запроса гаснет.
    if (was === 'needs_input' && c.committed.status !== 'needs_input' && c.bubble?.kind === 'needs_input') {
      c.bubble = null;
      c.bubbleDirty = true;
    }
    if (c.committed.status === 'needs_input') this.ensureQuestion(c);
    // Комната ушедшей встречи освобождается до разбора целей: иначе встреча, созревшая в том же тике, её не получит.
    this.releaseMeetings();
    this.retarget(c);
  }

  private targetsFor(c: Char): RuleTarget[] | undefined {
    const table = (c.e.kind === 'human' ? this.rules.human : this.rules.agent) as Record<string, RuleTarget[] | undefined>;
    return table[c.committed.status];
  }

  private ctx(c: Char): ResolveContext {
    return {
      map: this.map,
      reservations: this.reservations,
      entity: c.e,
      podOf: (id) => this.chars.get(id)?.e.podZoneId,
      lastSeat: c.lastSeat,
      currentSpot: c.reserved,
      currentIsWorkSeat: c.reserved !== null && c.reserved === c.workSeat,
      meetingId: c.committed.meetingId,
      meetings: this.meetings,
      meetingNeed: (mid) =>
        [...this.chars.values()].filter((x) => [x.latest, x.committed].some((s) => s.status === 'meeting' && s.meetingId === mid)).length,
    };
  }

  private retarget(c: Char): void {
    c.fallback = false;
    const list = this.targetsFor(c);
    if (!list) {
      this.warn(`${c.e.id}: нет правил для ${c.e.kind}:${c.committed.status}`);
      return;
    }
    const { resolved, lastZoneId } = resolveTargets(list, this.ctx(c));
    if (resolved) return this.setGoal(c, resolved.kind === 'exit' ? this.exitGoal(c) : resolved);
    this.warn(`${c.e.id}: ни одна цель для «${c.committed.status}» недоступна`);
    c.fallback = true;
    const cell = this.fallbackCell(c, lastZoneId);
    this.setGoal(c, cell ? { kind: 'cell', x: cell[0], y: cell[1] } : { kind: 'stay' });
  }

  // Плановый пересмотр запасной цели: меняем её, только если цель правил стала доступна.
  // Иначе персонаж не трогается (без перепланирования на ходу) и warn не повторяется.
  private recheckFallback(c: Char): void {
    const list = this.targetsFor(c);
    const resolved = list ? resolveTargets(list, this.ctx(c)).resolved : null;
    if (!resolved) return;
    c.fallback = false;
    this.setGoal(c, resolved.kind === 'exit' ? this.exitGoal(c) : resolved);
  }

  private setGoal(c: Char, goal: Goal): void {
    // Смена цели прерывает ожидание автобуса и капсулы (спека маршрутов 4.8.2, спека транспорта 4.5.4), в том числе
    // stay: иначе подошедший автобус увезёт человека, который снова в сети.
    c.busWaitSince = null;
    c.entered = false;
    c.holding = false;
    if (goal.kind === 'stay') return this.stay(c);
    if (goal.kind === 'exit' && !c.visible) {
      // Невидимый уходит сразу: ни брони, ни пути.
      if (c.reserved) this.reservations.delete(c.reserved);
      c.reserved = null;
      c.workSeat = null;
      c.goal = goal;
      this.dequeue(c);
      c.path = [];
      return;
    }
    const spotId = goal.kind === 'spot' || goal.kind === 'exit' ? goal.spotId : null;
    if (c.reserved && c.reserved !== spotId) this.reservations.delete(c.reserved);
    c.reserved = spotId;
    if (spotId) this.reservations.set(spotId, c.e.id);
    // Рабочий статус для памяти места (спека 17.11.2026): у агента working, у человека online — иначе
    // current_work_seat у человека никогда не разрешается. needs_input нового места не запоминает:
    // цель — вернуться туда, где застал запрос; при переседании память обновит следующий рабочий статус.
    const workStatus = c.e.kind === 'agent' ? c.committed.status === 'working' : c.committed.status === 'online';
    if (spotId && goal.kind === 'spot' && workStatus) c.workSeat = spotId;
    else if (spotId !== c.workSeat) c.workSeat = null;
    c.goal = goal;
    if (goal.kind === 'exit') return this.plan(c, goal.cell, undefined, goal.via ? [goal.via, goal.point] : [goal.point]);
    if (!c.visible) return this.enqueue(c);
    this.plan(c, this.goalCell(goal));
  }

  // stay — остаться где есть (спека 5.3): сидящий остаётся на месте с бронью, идущий встаёт
  // в ближайшей (округлённой) клетке и отпускает бронь места, к которому шёл. Хозяин на шаге под кузов своей машины —
  // в клетке у двери (startCell): выходит обратно в щель, а не стоит под машиной за кузовом (спека транспорта 4.5.2).
  // Лежащий на спальном месте парка (или дошедший до его клетки) встаёт и отходит на соседнюю свободную клетку, бронь
  // места снимает (спека сна 5.4): лежать можно только offline, а stay — цель другого статуса.
  private stay(c: Char): void {
    c.goal = { kind: 'stay' };
    const here = this.startCell(c);
    const at = c.visible ? this.map.spotAt(here[0], here[1]) : undefined;
    const bed = at?.tags.includes('park_sleep') ? at : undefined;
    if (c.visible && c.path.length === 0 && !bed) return;
    const keep = bed ? undefined : at?.id;
    if (c.reserved && c.reserved !== keep) {
      this.reservations.delete(c.reserved);
      if (c.workSeat === c.reserved) c.workSeat = null;
      c.reserved = null;
    }
    if (!c.visible) {
      this.dequeue(c);
      c.path = [];
      return;
    }
    this.plan(c, bed ? (this.freeTransit(here, c) ?? here) : here);
  }

  // Ближайшая к from транзитная клетка, не цель другого персонажа (поиск в ширину по транзитным клеткам); нет — null.
  private freeTransit(from: Cell, c: Char): Cell | null {
    const taken = this.takenCells(c);
    const seen = new Uint8Array(this.map.size);
    const queue: Cell[] = [from];
    seen[this.map.index(from[0], from[1])] = 1;
    for (let i = 0; i < queue.length; i++) {
      const [x, y] = queue[i]!;
      if (i > 0 && !taken.has(`${x},${y}`)) return [x, y];
      for (const [dx, dy] of DIRS) {
        const nx = x + dx;
        const ny = y + dy;
        if (this.map.isTransit(nx, ny) && !seen[this.map.index(nx, ny)]) {
          seen[this.map.index(nx, ny)] = 1;
          queue.push([nx, ny]);
        }
      }
    }
    return null;
  }

  private goalCell(g: Goal): Cell {
    if (g.kind === 'spot') {
      const s = this.map.spot(g.spotId)!;
      return [s.x, s.y];
    }
    if (g.kind === 'cell') return [g.x, g.y];
    if (g.kind === 'exit') return g.cell;
    return this.map.doorPoint;
  }

  // Начальная клетка новой сущности (до появления) — её портал (спека маршрутов 4.3).
  private portalStart(e: SimEntity): Cell {
    const p = portalOf(this.map, e);
    if (p.kind === 'cell') return p.cell;
    const s = this.map.spot(p.spots[0]!);
    return s ? [s.x, s.y] : this.map.doorPoint;
  }

  // Цель ухода — портал персонажа. Остановка — свободное место с бронью или запасная клетка; капсула — ближайшая
  // без чужой брони (dockExit).
  private exitGoal(c: Char): ExitGoal {
    // Уход на машине (спека транспорта 3.3, 4.5.2): путь до клетки у двери, отрезок до точки у двери и последний шаг —
    // под кузов, к точке посадки. Шаг добавляется после поиска пути: клетки под машиной для поиска непроходимы и для
    // хозяина, исключение — только этот шаг к своей машине.
    const car = this.carPlan(c);
    if (car) return { kind: 'exit', cell: car.cell, point: car.seat, via: car.door, spotId: null, busWait: false, facing: null };
    // Уход человека парка (спека сна 5.3): на своё спальное место, с бронью; свободных нет — общий путь портала. Спят
    // только offline: exit по правилам другого статуса — уход в метро (спека сна 5.4).
    if (c.visible && c.committed.status === 'offline' && this.parkSleeper(c)) {
      const s = this.sleepSpot(c);
      if (s) return sleepGoal(s);
    }
    const p = portalOf(this.map, c.e);
    if (p.kind === 'spots' && p.key === 'bus' && c.visible) return this.busExit(c, p.spots);
    if (p.kind === 'spots' && c.visible) return this.dockExit(c, p.spots);
    const cell: Cell = p.kind === 'cell' ? p.cell : this.portalStart(c.e);
    return { kind: 'exit', cell, point: cell, spotId: null, busWait: false, facing: null };
  }

  // Клетки-цели других персонажей: запасные клетки (cell) и цели ухода без места (спека маршрутов 4.6.3).
  private takenCells(c: Char): Set<string> {
    const taken = new Set<string>();
    for (const o of this.chars.values()) {
      if (o === c || !o.goal) continue;
      if (o.goal.kind === 'cell') taken.add(`${o.goal.x},${o.goal.y}`);
      else if (o.goal.kind === 'exit' && !o.goal.spotId) taken.add(`${o.goal.cell[0]},${o.goal.cell[1]}`);
    }
    return taken;
  }

  // Первое место набора без чужой брони.
  private freeSpot(ids: string[], c: Char): Spot | undefined {
    for (const id of ids) {
      const r = this.reservations.get(id);
      if (!r || r === c.e.id) return this.map.spot(id);
    }
    return undefined;
  }

  // Человек парка (спека сна): его способ после запасного пути — park, то есть на участке есть спальные места.
  private parkSleeper(c: Char): boolean {
    return c.e.kind === 'human' && commuteFor(this.map, c.e.commute ?? 'metro') === 'park';
  }

  // Спальное место человека парка (спека сна 2.2, 5.2): по parkSleep начиная с fnv1a(id) % n — первое без чужой брони.
  // Так он каждую ночь ложится на одну и ту же скамейку, пока она свободна. Свободных нет — undefined.
  private sleepSpot(c: Char): Spot | undefined {
    const ids = this.map.portals.parkSleep;
    const k = ids.length ? fnv1a(c.e.id) % ids.length : 0;
    return this.freeSpot([...ids.slice(k), ...ids.slice(0, k)], c);
  }

  // Запасная клетка остановки (спека маршрутов 4.6.3): поиск в ширину от мест остановки по проходимым клеткам
  // (тротуар, газон, зебра), сначала вдоль ряда; подходит клетка тротуара, которая не место и не цель другого
  // персонажа. Первая такая в ряду мест (рядом с остановкой, лицом к дороге), иначе первая любая: ряды над остановкой
  // закрыты её задней стенкой и козырьком (решение 8). Не нашлась — первое место.
  private busFallback(ids: string[], c: Char): Cell {
    const spots = ids.map((id) => this.map.spot(id)!);
    const row = spots[0]!.y;
    const taken = this.takenCells(c);
    const seen = new Uint8Array(this.map.size);
    const queue: Cell[] = spots.map((s) => [s.x, s.y]);
    for (const [x, y] of queue) seen[this.map.index(x, y)] = 1;
    let other: Cell | null = null;
    for (let i = 0; i < queue.length; i++) {
      const [x, y] = queue[i]!;
      if (this.map.terrainAt(x, y) === 'sidewalk' && !this.map.spotAt(x, y) && !taken.has(`${x},${y}`) && !this.isBusDoor(x, y)) {
        if (y === row) return [x, y];
        other ??= [x, y];
      }
      for (const [dx, dy] of ALONG_FIRST) {
        const nx = x + dx;
        const ny = y + dy;
        if (this.map.isTransit(nx, ny) && !seen[this.map.index(nx, ny)]) {
          seen[this.map.index(nx, ny)] = 1;
          queue.push([nx, ny]);
        }
      }
    }
    return other ?? [spots[0]!.x, spots[0]!.y];
  }

  // Точка у двери автобуса (спека транспорта 3.8): запасная клетка ждущего её не берёт — там выходят приехавшие.
  private isBusDoor(x: number, y: number): boolean {
    const d = this.map.transport?.bus?.door;
    return d !== undefined && d[0] === x && d[1] === y;
  }

  // Уход на остановку: свободное место с бронью, иначе запасная клетка; там — лицом к дороге до автобуса.
  private busExit(c: Char, ids: string[]): ExitGoal {
    const s = this.freeSpot(ids, c);
    if (s) return { kind: 'exit', cell: [s.x, s.y], point: this.map.spotPoint(s), spotId: s.id, busWait: true, facing: s.facing };
    const f = this.busFallback(ids, c);
    return { kind: 'exit', cell: f, point: f, spotId: null, busWait: true, facing: 'down' };
  }

  // Клетка ряда места капсулы и длина пути (спека маршрутов 4.7): из двух столбцов — тот, где путь короче (from — от
  // персонажа к клетке, иначе от клетки к to); при равной длине — ближний к точке места. Так путь в капсуле идёт по
  // одному столбцу, а между ним и точкой места — короткий сдвиг без шага назад. Пути нет ни к одному — null.
  private dockSide(d: DockSpot, way: { from: Cell } | { to: Cell }): { side: Cell; len: number } | null {
    const row = this.map.spot(d.spotId)!.y;
    const cols = [...new Set(d.cells.map(([cx]) => cx))].sort((a, b) => Math.abs(a - d.point[0]) - Math.abs(b - d.point[0]) || a - b);
    let best: { side: Cell; len: number } | null = null;
    for (const x of cols) {
      const side: Cell = [x, row];
      const len = ('from' in way ? this.path(way.from, side) : this.path(side, way.to))?.length;
      if (len !== undefined && (!best || len < best.len)) best = { side, len };
    }
    return best;
  }

  // Капсула, которая раньше всех выходит из цикла (при равенстве — первая); все в цикле — null. Капсулу, перед которой
  // уже стоит уходящий с её бронью, появление не занимает: он входит первым (спека маршрутов 4.6.4), иначе поток
  // появлений держал бы его у капсулы, пока не кончится очередь.
  private freeDock(): DockSpot | null {
    let best: DockSpot | null = null;
    for (const d of this.map.portals.docks) {
      const r = this.reservations.get(d.spotId);
      if (r !== undefined && this.chars.get(r)?.holding) continue;
      if (!best || (this.dockFree.get(d.spotId) ?? 0) < (this.dockFree.get(best.spotId) ?? 0)) best = d;
    }
    return best && (this.dockFree.get(best.spotId) ?? 0) <= this.t ? best : null;
  }

  // Уход агента (спека маршрутов 4.6.4): ближайшая по длине пути капсула без чужой брони, цель — клетка ряда места
  // со стороны прихода, последний отрезок — до точки места. Забронированы все — ждать у ближайшей.
  private dockExit(c: Char, ids: string[]): ExitGoal {
    const from: Cell = [Math.round(c.x), Math.round(c.y)];
    let best: { d: DockSpot; side: Cell; len: number } | null = null;
    let near: { d: DockSpot; side: Cell; len: number } | null = null;
    for (const id of ids) {
      const d = this.map.dock(id)!;
      const s = this.dockSide(d, { from });
      if (!s) continue;
      if (!near || s.len < near.len) near = { d, ...s };
      const r = this.reservations.get(id);
      if ((!r || r === c.e.id) && (!best || s.len < best.len)) best = { d, ...s };
    }
    if (best) return { kind: 'exit', cell: best.side, point: best.d.point, spotId: best.d.spotId, busWait: false, facing: this.map.spot(best.d.spotId)!.facing };
    const front = near ? (near.d.front.find(([x]) => x === near.side[0]) ?? near.d.front[0]!) : from;
    const wait = this.freeNear(front, c) ?? from;
    return { kind: 'exit', cell: wait, point: wait, spotId: null, busWait: false, facing: 'up', dockWait: true };
  }

  // Свободная клетка пола у клетки перед капсулой (спека маршрутов 4.6.4): поиск в ширину, сначала вдоль ряда, не
  // сквозь капсулы и тумбы; подходит клетка не из капсул, тумб и рядов перед ними и не цель другого персонажа.
  private freeNear(start: Cell, c: Char): Cell | null {
    const taken = this.takenCells(c);
    const seen = new Uint8Array(this.map.size);
    const queue: Cell[] = [start];
    seen[this.map.index(start[0], start[1])] = 1;
    for (let i = 0; i < queue.length; i++) {
      const [x, y] = queue[i]!;
      if (!this.map.inDockArea(x, y) && !taken.has(`${x},${y}`)) return [x, y];
      for (const [dx, dy] of ALONG_FIRST) {
        const nx = x + dx;
        const ny = y + dy;
        if (this.map.isTransit(nx, ny) && !seen[this.map.index(nx, ny)] && !this.map.inDockBody(nx, ny)) {
          seen[this.map.index(nx, ny)] = 1;
          queue.push([nx, ny]);
        }
      }
    }
    return null;
  }

  private enqueue(c: Char): void {
    if (c.queue) return;
    const key = portalOf(this.map, c.e).key;
    const q = this.queues.get(key) ?? { ids: [], nextAt: 0 };
    q.ids.push(c.e.id);
    this.queues.set(key, q);
    c.queue = key;
  }

  private dequeue(c: Char): void {
    if (!c.queue) return;
    const q = this.queues.get(c.queue);
    if (q) q.ids = q.ids.filter((id) => id !== c.e.id);
    c.queue = null;
  }

  // Путь с учётом стоящих машин (спека транспорта 4.7.2, 4.7.4): их клетки непроходимы; с ними цель недостижима — путь
  // без них, человек пройдёт сквозь машину, офис не застревает.
  private path(from: Cell, to: Cell): Cell[] | null {
    const t = this.traffic;
    if (!t) return findPath(this.map, from, to);
    return findPath(this.map, from, to, (x, y) => t.occupied(x, y)) ?? findPath(this.map, from, to);
  }

  // Откуда (по умолчанию — клетка персонажа, startCell) и до какой клетки; tail — точки после клетки (точка портала-места,
  // у машины — точка у двери и точка посадки).
  private plan(c: Char, target: Cell, from: Cell = this.startCell(c), tail: Cell[] = []): void {
    const path = this.path(from, target);
    if (!path) {
      this.warn(`${c.e.id}: нет пути из (${from.join(',')}) в (${target.join(',')})`);
      c.path = [];
      // Хозяин на шаге под кузов (в том числе только что появившийся на точке посадки) встаёт у двери в щели: иначе он
      // так и стоял бы под машиной, невидимый, а машина, пока он виден, не уезжает (спека транспорта 4.5.1).
      const car = this.underBody(c);
      if (car) [c.x, c.y] = car.door;
      return;
    }
    // В капсуле и на тумбе — по центру капсулы, по x точки места (спека маршрутов 4.7): сдвиг с клетки столбца на
    // центр уходит в шаг между полом перед капсулой и тумбой, в стекле агент не идёт сбоку.
    for (const node of path) {
      const d = this.map.dockAt(node[0], node[1]);
      if (d) node[0] = d.point[0];
    }
    // Узлы в крайних столбцах мест парковки — к середине ближней щели (спека транспорта 3.3): человек по пути к двери
    // не идёт сквозь кузов соседней машины. Подряд одинаковые узлы склеиваются.
    for (const node of path) node[0] += this.gaps.get(`${node[0]},${node[1]}`) ?? 0;
    for (let i = path.length - 1; i > 0; i--) if (path[i]![0] === path[i - 1]![0] && path[i]![1] === path[i - 1]![1]) path.splice(i, 1);
    for (const p of tail) if (p[0] !== path.at(-1)![0] || p[1] !== path.at(-1)![1]) path.push(p); // последние отрезки — до точек
    const end = path.at(-1)!;
    if (path.length === 1 && c.x === end[0] && c.y === end[1]) {
      c.path = [];
      this.arrive(c);
      return;
    }
    c.path = path;
    c.pose = 'walk';
    c.anim = 'walk';
    c.yielding = false;
    c.offset = [0, 0];
    c.labelAbove = false;
    c.fidgets = [];
    c.seatSpot = null;
  }

  // Клетка, от которой строится путь: округлённая позиция. Хозяин на шаге между точкой у двери и точкой посадки (под
  // кузовом своей машины) — от клетки у двери: выходит обратно в щель, а не через пассажирскую сторону.
  private startCell(c: Char): Cell {
    const car = this.underBody(c);
    return car ? [car.cell[0], car.cell[1]] : [Math.round(c.x), Math.round(c.y)];
  }

  // Место машины, если хозяин на шаге между точкой у двери (не включая её) и точкой посадки; иначе null.
  private underBody(c: Char): SpotPlan | null {
    const car = c.visible ? this.carPlan(c) : null;
    if (!car) return null;
    const [dx, sx] = [car.door[0], car.seat[0]];
    return c.y === car.seat[1] && c.x !== dx && Math.min(dx, sx) <= c.x && c.x <= Math.max(dx, sx) ? car : null;
  }

  // По одному у каждого портала раз в spawnInterval (спека 5.4, спека маршрутов 4.5); порталы — в порядке ключей.
  // Капсулы выпускают сразу всех, для кого есть капсула вне цикла: у них вместо интервала — цикл каждой.
  private processSpawns(): void {
    for (const key of [...this.queues.keys()].sort(byCodePoint)) {
      const q = this.queues.get(key)!;
      while (q.ids.length > 0 && this.t >= q.nextAt) {
        const c = this.chars.get(q.ids[0]!);
        if (!c || c.visible || !c.goal || c.goal.kind === 'exit' || c.goal.kind === 'stay') {
          q.ids.shift();
          if (c) c.queue = null;
          continue;
        }
        if (!this.spawn(c)) break; // все капсулы в цикле — ждёт в очереди
        q.ids.shift();
        c.queue = null;
        if (key === 'dock') continue;
        q.nextAt = this.t + this.spawnInterval;
        break;
      }
    }
  }

  // Появление на портале (спека маршрутов 4.8.1): позиция — точка портала, путь к цели — в том же тике.
  private spawn(c: Char): boolean {
    const p = portalOf(this.map, c.e);
    if (p.kind === 'spots' && p.key === 'dock') {
      const d = this.freeDock();
      if (!d) return false;
      this.dockFree.set(d.spotId, this.t + this.dockCycle); // событие «появление» начинает цикл
      const target = this.goalCell(c.goal!);
      c.x = d.point[0];
      c.y = d.point[1];
      c.facing = 'down';
      c.visible = true;
      c.bubbleDirty = c.bubble !== null;
      // Путь — от клетки ряда места в столбце, откуда короче до цели: первый отрезок от точки места без шага назад
      // (спека маршрутов 4.7). Цели не достичь — от клетки места: plan предупредит.
      const s = this.map.spot(d.spotId)!;
      this.plan(c, target, this.dockSide(d, { to: target })?.side ?? [s.x, s.y]);
      return true;
    }
    const car = this.carPlan(c);
    if (car) {
      // Приезд на машине (спека транспорта 4.5.1): выходит, когда его машина встала на место; машины нет — рейс. Машина
      // ещё уезжает — ждать её удаления, потом рейс: двух машин с одним id не бывает.
      const id = this.carId(c);
      const phase = this.traffic!.phase(id);
      if (phase === undefined) this.traffic!.orderCar(id, c.e.carModel ?? 1, car.key);
      if (phase !== 'parked') return false;
      // Появляется под кузовом, на точке посадки: первый отрезок пути — к точке у двери (узел клетки у двери, сдвинутый в
      // щель), так что человек выходит из машины в щель и только потом идёт к цели.
      c.carLeaveAt = null;
      c.x = car.seat[0];
      c.y = car.seat[1];
      c.facing = 'down';
      c.visible = true;
      c.bubbleDirty = c.bubble !== null;
      this.plan(c, this.goalCell(c.goal!), car.cell);
      return true;
    }
    let at: Cell = this.portalStart(c.e);
    let facing: Facing = 'up';
    if (p.kind === 'spots' && p.key === 'bus') {
      const bus = this.map.transport?.bus;
      if (bus) {
        // Приезд на автобусе (спека транспорта 4.5.3): выходят у двери автобуса, когда он постоял BUS_STOP_MS.
        if (!this.busOpen()) return false;
        at = [bus.door[0], bus.door[1]];
        facing = 'up';
      } else {
        // Без кармана — как на этапе 2: незабронированное место остановки, иначе запасная клетка; взгляд — к дороге.
        const s = this.freeSpot(p.spots, c);
        at = s ? this.map.spotPoint(s) : this.busFallback(p.spots, c);
        facing = 'down';
      }
    }
    c.x = at[0];
    c.y = at[1];
    c.facing = facing;
    c.visible = true;
    c.bubbleDirty = c.bubble !== null;
    this.plan(c, this.goalCell(c.goal!));
    return true;
  }

  // Место парковки человека (спека транспорта 3.3): по клетке портала car:<x,y>. Не на машине, нет транспорта или
  // места с такой клеткой — null (тогда портал — просто клетка, как на этапе 2).
  private carPlan(c: Char): SpotPlan | null {
    const p = portalOf(this.map, c.e);
    if (!this.traffic || p.kind !== 'cell' || !p.key.startsWith('car:')) return null;
    return this.map.transport!.spots.find((s) => s.cell[0] === p.cell[0] && s.cell[1] === p.cell[1]) ?? null;
  }

  private carId(c: Char): string {
    return `car:${c.e.id}`;
  }

  // Отъезд машины без хозяина (спека транспорта 4.5.2): стоящая машина, чей хозяин не виден и не ждёт появления (сел в
  // неё или ушёл в offline, пока она ехала), трогается через CAR_LEAVE_MS; хозяин появился раньше — отсчёт снят.
  private carsStep(): void {
    if (!this.traffic) return;
    for (const c of this.chars.values()) {
      if (!this.carPlan(c)) continue;
      const id = this.carId(c);
      if (c.visible || c.queue !== null || this.traffic.phase(id) !== 'parked') {
        c.carLeaveAt = null;
        continue;
      }
      c.carLeaveAt ??= this.t + CAR_LEAVE_MS;
      if (this.t >= c.carLeaveAt) {
        this.traffic.depart(id);
        c.carLeaveAt = null;
      }
    }
  }

  private busOpen(): boolean {
    return this.traffic?.phase('bus') === 'boarding' && this.busAt !== null && this.t - this.busAt >= BUS_STOP_MS;
  }

  // Автобус по требованию (спека транспорта 4.5.3–4.5.5). Нет автобуса — заказ, если кто-то в очереди на появление или
  // первый ждущий простоял bus.wait. Встал в карман — пауза BUS_STOP_MS, затем выходят приехавшие (spawn) и ждущие идут к
  // двери; никого — ещё пауза и отъезд; новый ждущий во второй паузе начинает её заново.
  private busStep(): void {
    const plan = this.map.transport?.bus;
    if (!this.traffic || !plan) return;
    const phase = this.traffic.phase('bus');
    const queued = (this.queues.get('bus')?.ids.length ?? 0) > 0;
    const waiting = [...this.chars.values()].filter((c) => c.visible && c.busWaitSince !== null);
    if (phase === undefined) {
      this.busAt = null;
      this.busIdleAt = null;
      if (queued || waiting.some((c) => this.t - c.busWaitSince! >= this.rules.busWaitMs)) this.traffic.orderBus();
      return;
    }
    if (phase !== 'boarding') return;
    this.busAt ??= this.t;
    if (!this.busOpen()) return;
    const door: Cell = [plan.door[0], plan.door[1]];
    for (const c of waiting) this.setGoal(c, { kind: 'exit', cell: door, point: door, spotId: null, busWait: false, board: true, facing: 'up' });
    const boarding = [...this.chars.values()].some((c) => c.visible && c.goal?.kind === 'exit' && c.goal.board === true);
    if (queued || waiting.length > 0 || boarding) {
      this.busIdleAt = null;
      return;
    }
    this.busIdleAt ??= this.t;
    if (this.t - this.busIdleAt >= BUS_STOP_MS) this.traffic.busDepart();
  }

  // Персонаж ушёл: снять бронь, спрятать, сообщить зрителям (спека маршрутов 4.6.5, 4.8.2).
  private despawn(c: Char): void {
    if (c.reserved) this.reservations.delete(c.reserved);
    c.reserved = null;
    c.workSeat = null;
    c.visible = false;
    c.path = [];
    c.goal = null;
    c.pose = 'stand';
    c.anim = 'idle';
    c.seatSpot = null;
    c.busWaitSince = null;
    this.despawned.push(c.e.id);
    this.lastSent.delete(c.e.id);
  }

  private move(c: Char, dtMs: number): void {
    if (!c.visible || c.path.length === 0) return;
    // На скрытых клетках (нижняя ступень метро), где вьюер персонажа не показывает, — в HIDDEN_SPEEDUP раз быстрее
    // (спека маршрутов 4.4); проход входной двери не скрытый — обычная скорость (спека двери 4.2).
    // Скорость — по положению в начале тика.
    const k = this.map.isHidden(Math.round(c.x), Math.round(c.y)) ? HIDDEN_SPEEDUP : 1;
    let budget = (k * this.speed * dtMs) / 1000;
    while (budget > 1e-9 && c.path.length > 0) {
      if (this.holdAtDock(c) || this.yieldToTraffic(c)) break;
      const [nx, ny] = c.path[0]!;
      const dx = nx - c.x;
      const dy = ny - c.y;
      const dist = Math.abs(dx) + Math.abs(dy);
      if (dist <= budget + 1e-9) {
        c.x = nx;
        c.y = ny;
        budget -= dist;
        c.path.shift();
        if (dist > 0) c.facing = facingOf(dx, dy);
      } else {
        c.x += (dx / dist) * budget;
        c.y += (dy / dist) * budget;
        c.facing = facingOf(dx, dy);
        budget = 0;
      }
    }
    if (c.path.length === 0) this.arrive(c);
  }

  // Вход в капсулу (спека маршрутов 4.5): перед шагом с клетки перед капсулой на её тумбу. Капсула в цикле — стоять
  // лицом вверх; свободна — событие «вход» начинает цикл, агент идёт дальше.
  private holdAtDock(c: Char): boolean {
    const g = c.goal;
    if (c.entered || g?.kind !== 'exit' || !g.spotId) return false;
    const d = this.map.dock(g.spotId);
    const [nx, ny] = c.path[0]!;
    // Шаг на тумбу — в её ряд, x уже по центру капсулы (plan): столбец не сравнивается.
    if (!d || !d.front.some(([x, y]) => x === c.x && y === c.y) || !d.plinth.some(([, y]) => y === ny) || Math.abs(nx - d.point[0]) > 1e-9) return false;
    if ((this.dockFree.get(d.spotId) ?? 0) > this.t) {
      if (!c.holding) {
        c.holding = true;
        c.facing = 'up';
        c.pose = 'stand';
        c.anim = animFor(this.poses, 'stand', 'up');
      }
      return true;
    }
    this.dockFree.set(d.spotId, this.t + this.dockCycle);
    c.entered = true;
    if (c.holding) {
      c.holding = false;
      c.pose = 'walk';
      c.anim = 'walk';
    }
    return false;
  }

  // Шаг к следующей точке пути, которую задевает контур едущего транспорта (спека транспорта 4.4), ждёт стоя: транспорт
  // смотрит только полосу перед бампером, и вошедший сбоку под проезжающий кузов шёл бы сквозь него.
  private yieldToTraffic(c: Char): boolean {
    const [nx, ny] = c.path[0]!;
    const wait = this.traffic?.movingOver([Math.min(c.x, nx), Math.min(c.y, ny), Math.max(c.x, nx) + 1, Math.max(c.y, ny) + 1]) ?? false;
    if (wait !== c.yielding) {
      c.yielding = wait;
      c.pose = wait ? 'stand' : 'walk';
      c.anim = wait ? animFor(this.poses, 'stand', c.facing) : 'walk';
    }
    return wait;
  }

  private arrive(c: Char): void {
    const g = c.goal;
    if (!g) return;
    if (g.kind === 'exit') {
      // Лёг на спальное место (спека сна 5.3): как приход на обычное место — клетка места (не точка портала), взгляд,
      // поза и сдвиг места; не исчезает и держит бронь, пока offline. Встаёт обычной сменой цели (спека сна 5.4).
      if (g.sleep) {
        // Спящий не говорит (спека сна 5.6): облачко, начатое по пути, гаснет.
        if (c.bubble) {
          c.bubble = null;
          c.bubbleDirty = true;
        }
        return this.settle(c, this.map.spot(g.spotId!)!);
      }
      // Приход к порталу (спека маршрутов 4.8.2): позиция — точка портала, у места-портала — взгляд и поза места.
      c.x = g.point[0];
      c.y = g.point[1];
      if (g.facing) c.facing = g.facing;
      const s = g.spotId ? this.map.spot(g.spotId) : undefined;
      c.pose = s?.pose ?? 'stand';
      c.anim = animFor(this.poses, c.pose, c.facing);
      c.offset = [0, 0];
      c.labelAbove = false;
      c.fidgets = [];
      c.seatSpot = null;
      if (g.dockWait) return; // ждёт брони капсулы: стоит, а не исчезает
      // Ждущий автобус стоит лицом к дороге без таймера (спека транспорта 4.5.4); без кармана ждать некого — уходит сразу.
      if (g.busWait && this.map.transport?.bus) {
        c.busWaitSince = this.t;
        return;
      }
      this.despawn(c);
      return;
    }
    // stay посреди пути, оборвавшийся на клетке своего места, — как приход на место.
    const spotId = g.kind === 'spot' ? g.spotId : g.kind === 'stay' ? c.reserved : null;
    const s = spotId ? this.map.spot(spotId) : undefined;
    if (s && (g.kind === 'spot' || (s.x === c.x && s.y === c.y))) return this.settle(c, s);
    // cell, stay и любой другой приход: персонаж не остаётся в позе ходьбы.
    c.pose = 'stand';
    c.anim = animFor(this.poses, 'stand', c.facing);
    c.offset = [0, 0];
    c.labelAbove = false;
    c.fidgets = [];
    c.seatSpot = null;
  }

  // Персонаж на месте s: клетка места, взгляд, поза, сдвиг, подпись и бытовые анимации места; агент в кабинке хозяина
  // запоминает последнее место.
  private settle(c: Char, s: Spot): void {
    c.x = s.x;
    c.y = s.y;
    c.facing = s.facing;
    c.pose = s.pose;
    c.anim = animFor(this.poses, s.pose, s.facing);
    c.offset = s.offset;
    c.labelAbove = s.label === 'above';
    c.fidgets = s.fidgets;
    c.seatSpot = s.id;
    const ownerPod = c.e.ownerId ? this.chars.get(c.e.ownerId)?.e.podZoneId : undefined;
    if (c.e.kind === 'agent' && s.pose === 'sit' && ownerPod && s.zoneId === ownerPod) c.lastSeat = s.id;
  }

  private releaseMeetings(): void {
    // Активна встреча, у которой остался участник с принятым (после dwell) статусом meeting.
    const active = new Set<string>();
    for (const c of this.chars.values()) if (c.committed.status === 'meeting' && c.committed.meetingId) active.add(c.committed.meetingId);
    this.meetings.release(active);
  }

  // Ближайшая свободная транзитная клетка зоны (BFS от персонажа); нет — в рамке зоны +1.
  private fallbackCell(c: Char, zoneId: string | null): Cell | null {
    const zone = zoneId ? this.map.zones.find((z) => z.id === zoneId) : undefined;
    if (!zone) return null;
    const taken = this.takenCells(c);
    const start: Cell = c.visible ? [Math.round(c.x), Math.round(c.y)] : this.map.entrance();
    const grown: Zone = { ...zone, rect: [zone.rect[0] - 1, zone.rect[1] - 1, zone.rect[2] + 2, zone.rect[3] + 2] };
    for (const z of [zone, grown]) {
      const seen = new Uint8Array(this.map.size);
      const queue: Cell[] = [start];
      seen[this.map.index(start[0], start[1])] = 1;
      for (let i = 0; i < queue.length; i++) {
        const [x, y] = queue[i]!;
        if (zoneContains(z, x, y) && this.map.isTransit(x, y) && !taken.has(`${x},${y}`)) return [x, y];
        for (const [dx, dy] of DIRS) {
          const nx = x + dx;
          const ny = y + dy;
          if (this.map.isTransit(nx, ny) && !seen[this.map.index(nx, ny)]) {
            seen[this.map.index(nx, ny)] = 1;
            queue.push([nx, ny]);
          }
        }
      }
    }
    return null;
  }

  private stateOf(c: Char): CharacterState {
    const s: CharacterState = { id: c.e.id, x: round3(c.x), y: round3(c.y), facing: c.facing, pose: c.pose, anim: c.anim, offset: c.offset };
    if (c.labelAbove) s.label = 'above';
    if (c.fidgets.length) s.fidgets = c.fidgets;
    // Экраны места горят, пока сидит и не ждёт ответа. Статус — принятый и проверяется здесь: смену статуса делает
    // commit, и персонаж после неё не обязательно снова проходит через arrive.
    // Лежащий в парке не сидит: его место — не рабочее, screenSpot ему не нужен (спека сна 5.6).
    if (c.seatSpot && c.pose !== 'sleep' && c.committed.status !== 'needs_input') s.screenSpot = c.seatSpot;
    const talk = this.talkGroup(c);
    if (talk) s.talk = talk;
    return s;
  }

  // Группа разговора — первая переговорка встречи (общая для всех её комнат, meetingId зрителю не уходит):
  // у участника встречи, который дошёл до места в одной из её переговорок.
  private talkGroup(c: Char): string | null {
    const mid = c.committed.meetingId;
    if (c.committed.status !== 'meeting' || !mid || c.pose === 'walk' || !c.reserved) return null;
    const rooms = this.meetings.roomsOf(mid);
    const zoneId = this.map.spot(c.reserved)?.zoneId;
    return zoneId && rooms.includes(zoneId) ? rooms[0]! : null;
  }

  private bubbleOf(c: Char): Bubble | null {
    return c.bubble ? { text: c.bubble.text, kind: c.bubble.kind } : null;
  }
}
