Back to Faultline
SOURCE / PINNED RELEASE

Made of little things.

Faultline

Release
da1ffaa5624c…
Author-recorded commit
60f5f03189db…
License
LICENSE
Author’s source reference
nostr://npub182jczunncwe0jn6frpqwq3e0qjws7yqqnc3auccqv9nte2dnd63scjm4rf/wss%3A%2F%2Fgit.napplet.soy%2F/n-6932b12c78c

Archive hash verified: 5a2e0492417ec4e7…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/main.ts
import { installController } from './gamepad';
import { PlayerSettings, cleanName, validKey } from './player-settings';
import { teams } from './simulation';
import './styles.css';
import { media, storageInstanceGetItem, storageInstanceRemoveItem } from '@napplet/sdk';
import { intentOnDelivery } from '@napplet/nap/intent';
import type { Entry } from './room-entry';
import { CoordinatedAudio } from '../docs/examples/coordinated-audio';
import { runtimeHasDomain } from './domain-availability.js';
import { arenas } from './maps';
import { guns, FIRST_SECONDARY, isPrimary, isSecondary } from './weapons';
import { mapPlate, gunArt } from './art';
import { Match, callsigns, type Seat } from './match';
import {
  Rooms,
  record,
  parseEntry,
  isDedicated,
  playerCapacity,
  playerCount,
  titleOf,
  type Packet,
  type Room,
} from './network';
import { combat } from './combat-tuning';
import { Controls } from './controls';

const el = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id)! as T;
const dialog = el<HTMLDialogElement>('dialog'),
  body = el('dialog-body'),
  note = el('dialog-note');
const createAudio = () =>
  new CoordinatedAudio(runtimeHasDomain('media') ? media : undefined, 'Faultline match audio');
let audio = createAudio();
let noise: AudioBuffer | undefined;
function sound(kind: 'shot' | 'blast' | 'hit', gun: number, level = 1, pan = 0) {
  const ctx = audio.context,
    out = audio.output;
  if (!ctx || !out || !audio.audible) return;
  const now = ctx.currentTime,
    osc = ctx.createOscillator(),
    gain = ctx.createGain(),
    balance = ctx.createStereoPanner();
  balance.pan.value = pan;
  balance.connect(out);
  const length =
    kind === 'blast'
      ? combat.feel.soundDuration
      : kind === 'hit'
        ? 0.06
        : 0.1 + (gun === 2 ? 0.07 : 0);
  osc.type = kind === 'hit' ? 'sine' : kind === 'blast' ? 'sawtooth' : 'triangle';
  osc.frequency.setValueAtTime(
    kind === 'hit' ? 760 : kind === 'blast' ? combat.feel.pitchStart : 210 + gun * 22,
    now,
  );
  osc.frequency.exponentialRampToValueAtTime(
    kind === 'hit' ? 510 : kind === 'blast' ? combat.feel.pitchEnd : 42,
    now + length,
  );
  gain.gain.setValueAtTime(
    (kind === 'blast' ? combat.feel.soundGain : kind === 'hit' ? 0.09 : 0.14) * level,
    now,
  );
  gain.gain.exponentialRampToValueAtTime(0.001, now + length);
  osc.connect(gain);
  gain.connect(balance);
  if (kind !== 'hit') {
    if (!noise) {
      noise = ctx.createBuffer(1, Math.ceil(ctx.sampleRate * 0.55), ctx.sampleRate);
      const data = noise.getChannelData(0);
      for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
    }
    const burst = ctx.createBufferSource(),
      filter = ctx.createBiquadFilter();
    burst.buffer = noise;
    filter.type = 'lowpass';
    filter.frequency.setValueAtTime(kind === 'blast' ? 3100 : 4700 + gun * 230, now);
    filter.frequency.exponentialRampToValueAtTime(kind === 'blast' ? 150 : 680, now + length);
    burst.connect(filter);
    filter.connect(gain);
    burst.onended = () => {
      burst.disconnect();
      filter.disconnect();
    };
    burst.start();
    burst.stop(now + length);
  }
  osc.onended = () => {
    osc.disconnect();
    gain.disconnect();
    balance.disconnect();
  };
  osc.start();
  osc.stop(now + length);
}
let arena = 0,
  gun = 0,
  secondary = FIRST_SECONDARY,
  inspected = 0,
  page = 'play',
  modal = '',
  busy = false,
  round = 0,
  lobbyMap = 0;
let nextRoundTimer = 0;
let lobbyView = '',
  lastAnnouncement = '';
let seats: Seat[] = [],
  listingGeneration = 0,
  listed: Room[] = [],
  roomListTimer = 0;
const networkAvailable = runtimeHasDomain('webrtc') && runtimeHasDomain('cvm');
let teamMode = true;
let publicListing = false,
  listingError = '';
async function shareRoom() {
  const r = rooms.room;
  if (!r || !rooms.host || !publicListing) return;
  try {
    await rooms.advertise({
      title: titleOf(r),
      phase: round ? 'playing' : 'lobby',
      accepting: true,
      badges: [
        arenas[lobbyMap].name,
        teamMode ? 'Team deathmatch' : 'Free-for-all',
        ...(isDedicated(r) ? ['Count includes server'] : []),
      ],
    });
    if (rooms.room?.room === r.room) listingError = '';
  } catch {
    if (rooms.room?.room !== r.room) return;
    listingError = 'Public listing unavailable. Friends can still find this room in Browse rooms.';
  }
}
let settingsBack = '';

const controls = new Controls(
  el<HTMLCanvasElement>('scene'),
  () => pauseGame(),
  () => prefs.toggleCrouch,
);
const rooms = new Rooms(onRoomChange, onPacket, (reason) => {
  reset();
  openDialog('message', 'Room closed');
  note.textContent = reason;
  addButton('Return to operations', closeDialog);
});
const game = new Match(el<HTMLCanvasElement>('scene'), controls, rooms, results, sound);
const prefs = new PlayerSettings(preferencesChanged, () => {
  audio.dispose();
  audio = createAudio();
  if (rooms.room) void leaveRoom();
});
function addButton(text: string, fn: () => void, primary = false, parent: HTMLElement = body) {
  const b = document.createElement('button');
  b.className = primary ? 'primary' : 'secondary';
  b.textContent = text;
  b.onclick = fn;
  parent.append(b);
  return b;
}
function message(text: string, cls = 'muted') {
  const p = document.createElement('p');
  p.className = cls;
  p.textContent = text;
  body.append(p);
  return p;
}
function closeDialog() {
  clearInterval(roomListTimer);
  listingGeneration++;
  if (dialog.open) dialog.close();
  modal = '';
}
function openDialog(type: string, title: string) {
  if (type !== 'browse') clearInterval(roomListTimer);
  modal = type;
  el('dialog-title').textContent = title;
  body.replaceChildren();
  note.textContent = '';
  if (!dialog.open) dialog.showModal();
  el('dismiss').hidden = type === 'lobby' || type === 'results' || busy;
}
function displayName(id: number) {
  return prefs.profile?.name || prefs.alias || callsigns[id];
}
function preferencesChanged() {
  const me = seats.find((s) => s.key === rooms.actor);
  if (me && rooms.host) {
    me.name = displayName(me.id);
    me.profile = prefs.profile?.key;
  }
  if (game.solo) {
    const local = game.seats.find((s) => s.id === game.mine);
    if (local) local.name = displayName(local.id);
  }
  if (rooms.room) {
    announce();
    if (modal === 'lobby') drawLobby();
  }
  if (modal === 'settings') {
    const stance = document.querySelector<HTMLSelectElement>('#crouch-mode');
    if (stance && !stance.dataset.edited) stance.value = prefs.toggleCrouch ? 'toggle' : 'hold';
    const status = document.getElementById('profile-status');
    if (status) status.textContent = prefs.message;
    const source = document.getElementById('name-source') as HTMLSelectElement | null;
    if (source) source.value = prefs.profileSelected ? 'nostr' : 'alias';
    const alias = document.getElementById('alias-field');
    if (alias) alias.hidden = !!prefs.profile || prefs.loading;
    if (!prefs.profile && !prefs.loading && document.activeElement?.id !== 'alias-name') {
      const field = document.getElementById('alias-name') as HTMLInputElement | null;
      if (field && !field.dataset.edited) field.value = prefs.alias;
    }
  }
}
function openSettings() {
  settingsBack = modal;
  openDialog('settings', 'Player settings');
  const field = (text: string, control: HTMLElement) => {
    const label = document.createElement('label');
    label.className = 'field';
    label.textContent = text;
    label.append(control);
    body.append(label);
    return label;
  };
  const source = document.createElement('select');
  source.id = 'name-source';
  source.add(new Option('Anonymous alias', 'alias'));
  source.add(new Option('Nostr profile', 'nostr'));
  source.options[1].disabled = !prefs.canProfile;
  field('Play as', source);
  const alias = document.createElement('input');
  alias.id = 'alias-name';
  alias.maxLength = 24;
  alias.autocomplete = 'off';
  alias.placeholder = 'Use assigned callsign';
  alias.value = prefs.alias;
  alias.oninput = () => {
    alias.dataset.edited = 'true';
  };
  field('Custom name', alias).id = 'alias-field';
  const status = message('', 'profile-status muted');
  status.id = 'profile-status';
  status.setAttribute('role', 'status');
  message(
    'Profile mode shares your display name and public key with the room.',
    'profile-status muted',
  );
  source.onchange = () => {
    if (source.value === 'alias') prefs.useAlias();
    else void prefs.useProfile();
  };
  const stance = document.createElement('select');
  stance.id = 'crouch-mode';
  stance.onchange = () => {
    stance.dataset.edited = 'true';
  };
  stance.add(new Option('Toggle', 'toggle'));
  stance.add(new Option('Hold', 'hold'));
  stance.value = prefs.toggleCrouch ? 'toggle' : 'hold';
  field('Crouch behavior', stance);
  addButton(
    'Done',
    () => {
      prefs.save(alias.value, stance.value === 'toggle');
      dismiss();
    },
    true,
  );
  preferencesChanged();
}
el('settings').onclick = openSettings;
function dismiss() {
  if (busy || modal === 'lobby') return;
  if (modal === 'settings') {
    const back = settingsBack;
    closeDialog();
    if (back === 'pause') pauseGame();
    else if (back === 'lobby') drawLobby();
    return;
  }
  if (modal === 'loadout') {
    closeDialog();
    pauseGame();
    return;
  }
  if (modal === 'pause') {
    closeDialog();
    game.menu(false);
    return;
  }
  if (modal === 'results') {
    returnFromRound();
    return;
  }
  closeDialog();
}
el('dismiss').onclick = dismiss;
dialog.addEventListener('cancel', (e) => {
  e.preventDefault();
  dismiss();
});
function showPage(next: string) {
  page = next;
  for (const n of ['play', 'armory', 'controls']) el(n + '-page').hidden = n !== next;
  for (const b of document.querySelectorAll<HTMLButtonElement>('[data-page]')) {
    const selected = b.dataset.page === next;
    b.classList.toggle('selected', selected);
    if (selected) b.setAttribute('aria-current', 'page');
    else b.removeAttribute('aria-current');
  }
  if (next === 'play') drawSelection();
  if (next === 'armory') {
    inspected = gun;
    drawArmory();
  }
}
for (const b of document.querySelectorAll<HTMLButtonElement>('[data-page]'))
  b.onclick = () => showPage(b.dataset.page!);
function drawSelection() {
  const map = arenas[arena];
  el('sector').textContent = map.sector;
  el('map-name').textContent = map.name;
  el('map-type').textContent = map.type;
  el('map-index').textContent =
    String(arena + 1).padStart(2, '0') + ' / ' + String(arenas.length).padStart(2, '0');
  el('equipped-name').textContent = guns[gun].name;
  el('equipped-type').textContent = '+ ' + guns[secondary].name;
  mapPlate(el('plate'), map);
  gunArt(el('equipped-art'), gun);
}
new ResizeObserver(() => {
  if (page === 'play') mapPlate(el('plate'), arenas[arena]);
}).observe(el('plate'));
el('next-map').onclick = () => {
  arena = (arena + 1) % arenas.length;
  drawSelection();
};
el('prev-map').onclick = () => {
  arena = (arena + arenas.length - 1) % arenas.length;
  drawSelection();
};
el('open-loadout').onclick = () => showPage('armory');
function drawArmory() {
  const list = el('weapon-list');
  list.replaceChildren();
  guns.forEach((w, i) => {
    const b = document.createElement('button');
    b.className = 'weapon-option' + (i === inspected ? ' active' : '');
    b.setAttribute('aria-pressed', String(i === inspected));
    const name = document.createElement('strong'),
      type = document.createElement('small');
    name.textContent = w.name;
    type.textContent = w.type + (i === gun || i === secondary ? ' · Equipped' : '');
    b.append(name, type);
    b.onclick = () => {
      inspected = i;
      drawArmory();
      (list.children[i] as HTMLElement).focus();
    };
    list.append(b);
  });
  const w = guns[inspected];
  gunArt(el('weapon-art'), inspected);
  el('weapon-class').textContent = w.type + ' / ' + w.mode;
  el('weapon-name').textContent = w.name;
  el('weapon-desc').textContent = w.blurb;
  const stats = el('stats');
  stats.replaceChildren();
  for (const [k, v] of [
    ['Magazine', w.mag],
    ['Damage per trigger', w.pellets > 1 ? w.damage + ' × ' + w.pellets : w.damage],
    ['Cycle time', Math.round((w.delay / 60) * 1000) + ' ms'],
    ['Reload', (w.reload / 60).toFixed(2) + ' s'],
    ['Sight magnification', w.zoom + '×'],
  ]) {
    const dt = document.createElement('dt'),
      dd = document.createElement('dd');
    dt.textContent = String(k);
    dd.textContent = String(v);
    stats.append(dt, dd);
  }
  el('equip').textContent =
    inspected === gun || inspected === secondary ? 'Return to operations' : 'Equip ' + w.name;
}
el('equip').onclick = () => {
  if (isPrimary(inspected)) gun = inspected;
  else secondary = inspected;
  showPage('play');
};
function practice() {
  closeDialog();
  audio.activate();
  const s = [0, 1, 2, 3].map((id) => ({
    id,
    key: 'bot-' + id,
    name: id === 0 ? displayName(id) : callsigns[id],
    gun: id === 0 ? gun : (id + arena) % FIRST_SECONDARY,
    secondary: id === 0 ? secondary : FIRST_SECONDARY,
    ready: true,
  }));
  game.start(1, arena, s, true);
}
el('practice').onclick = practice;
function pauseGame() {
  if (!game.round || game.ended || modal) return;
  showScoreboard(false);
  game.menu(true);
  openDialog('pause', game.solo ? 'Practice paused' : 'Match menu');
  message(
    game.solo ? arenas[game.arena].name : 'The multiplayer round continues.',
    'dialog-info muted',
  );
  addButton('Resume', dismiss, true);
  addButton('Change loadout', pauseLoadout);
  addButton('Player settings', openSettings);
  if (game.solo) addButton('Restart practice', practice);
  else if (!rooms.connected.size || rooms.notice)
    addButton(
      'Retry connection',
      () =>
        void rooms.retry().catch((e) => {
          note.textContent = String(e);
        }),
    );
  addButton(game.solo ? 'Leave practice' : 'Leave room', () => void leaveRoom());
}
function pauseLoadout() {
  openDialog('loadout', 'Change loadout');
  const selectSlot = (title: string, current: number, accept: (id: number) => boolean) => {
    const label = document.createElement('label'),
      select = document.createElement('select');
    label.textContent = title;
    guns.forEach((weapon, id) => {
      if (accept(id)) select.add(new Option(weapon.name, String(id), false, id === current));
    });
    label.append(select);
    body.append(label);
    return select;
  };
  const primaryField = selectSlot('Primary', gun, isPrimary),
    secondaryField = selectSlot('Secondary', secondary, isSecondary);
  addButton(
    'Equip and resume',
    () => {
      const a = Number(primaryField.value),
        b = Number(secondaryField.value);
      if (!game.changeLoadout(a, b)) {
        note.textContent = 'Reconnect to the host to change loadout.';
        return;
      }
      gun = a;
      secondary = b;
      closeDialog();
      game.menu(false);
    },
    true,
  );
  addButton('Back', () => {
    closeDialog();
    pauseGame();
  });
}
el('pause').onclick = pauseGame;
function reset() {
  lobbyView = lastAnnouncement = '';
  clearTimeout(nextRoundTimer);
  showScoreboard(false);
  game.stop();
  round = 0;
  seats = [];
  closeDialog();
  showPage('play');
  el('link-status').textContent = 'Standby';
}
async function leaveRoom() {
  if (rooms.host) rooms.send({ t: 'closed' });
  reset();
  await rooms.leave();
}
function results() {
  showScoreboard(false);
  const next = (lobbyMap + 1) % arenas.length;
  if (!game.solo && rooms.host && rooms.room) {
    const finishedRound = round, roomId = rooms.room.room;
    nextRoundTimer = window.setTimeout(() => {
      if (!rooms.host || rooms.room?.room !== roomId || round !== finishedRound) return;
      lobbyMap = next;
      startHostedRound();
      void shareRoom();
    }, 5000);
    if (isDedicated(rooms.room)) {
      el('game-message').textContent = 'Next arena · ' + arenas[next].name;
      if (modal === 'lobby') drawLobby();
      return;
    }
  }
  openDialog('results', 'Round complete');
  const rows = game.players().sort((a, b) => b.kills - a.kills || a.deaths - b.deaths);
  const winners = rows.filter((p) => p.kills === rows[0]?.kills).map((p) => game.name(p.id));
  message(
    game.teamMode
      ? (game.scores[0] === game.scores[1]
          ? 'Teams tied.'
          : teams[Number(game.scores[1] > game.scores[0])] + ' wins.') +
          ' Amber ' +
          game.scores[0] +
          ' / Slate ' +
          game.scores[1]
      : winners.join(' + ') + (winners.length > 1 ? ' tied for first.' : ' wins.'),
    'muted dialog-info',
  );
  for (const p of rows) {
    const r = document.createElement('div');
    r.className = 'roster-row';
    r.textContent =
      (game.teamMode ? teams[p.id % 2] + ' · ' : '') +
      game.name(p.id) +
      (p.id === game.mine ? ' (you)' : '');
    const s = document.createElement('small');
    s.textContent = p.kills + ' K / ' + p.deaths + ' D';
    r.append(s);
    body.append(r);
  }
  if (game.solo) addButton('Play again', practice, true);
  else if (rooms.host) message('Up next · ' + arenas[next].name + ' in five seconds.');
  if (game.solo || rooms.host)
    addButton(game.solo ? 'Operations' : 'Return to lobby', returnFromRound, !game.solo);
  else {
    message('Waiting for the next round.');
    addButton('Leave room', () => void leaveRoom());
  }
}
function returnFromRound() {
  if (game.solo) {
    reset();
    return;
  }
  if (!rooms.host) return;
  clearTimeout(nextRoundTimer);
  lobbyMap = (lobbyMap + 1) % arenas.length;
  game.stop();
  round = 0;
  void shareRoom();
  announce();
  drawLobby();
}
function hostForm() {
  openDialog('create', 'Create room');
  const label = document.createElement('label');
  label.htmlFor = 'room-name';
  label.textContent = 'Room name';
  const input = document.createElement('input');
  input.id = 'room-name';
  input.maxLength = 15;
  input.value = arenas[arena].name;
  input.autocomplete = 'off';
  body.append(label, input);
  const modes = document.createElement('select'),
    modeLabel = document.createElement('label');
  modeLabel.className = 'field';
  modeLabel.textContent = 'Game mode';
  modes.add(new Option('Team deathmatch', 'team'));
  modes.add(new Option('Free-for-all', 'ffa'));
  modes.value = teamMode ? 'team' : 'ffa';
  modes.onchange = () => {
    teamMode = modes.value === 'team';
  };
  modeLabel.append(modes);
  body.append(modeLabel);
  const access = document.createElement('select');
  access.add(new Option('Free to join', 'open'));
  access.add(new Option('Room code only', 'code'));
  const accessLabel = document.createElement('label');
  accessLabel.className = 'field';
  accessLabel.textContent = 'Room access';
  accessLabel.append(access);
  body.append(accessLabel);
  const hostRole = document.createElement('select');
  hostRole.add(new Option('Host and play', 'player'));
  hostRole.add(new Option('Dedicated host', 'server'));
  const roleLabel = document.createElement('label');
  roleLabel.className = 'field';
  roleLabel.textContent = 'This browser';
  roleLabel.append(hostRole);
  body.append(roleLabel);
  const share = document.createElement('label'),
    check = document.createElement('input');
  check.type = 'checkbox';
  check.checked = false;
  share.append(check, ' Show this lobby in Playing now across shells');
  body.append(share);
  const detail = message('', 'dialog-info muted');
  const describe = () => {
    const dedicated = hostRole.value === 'server';
    detail.textContent = dedicated
      ? 'Up to 7 players. Keep this window open and awake to run the server.'
      : arenas[arena].name + ' · Up to 8 players · Players can join during a match.';
    check.disabled = access.value === 'code';
    if (check.disabled) check.checked = false;
    b.textContent = dedicated ? 'Start server' : 'Open lobby';
  };
  access.onchange = hostRole.onchange = describe;
  const b = addButton(
    'Open lobby',
    () => {
      if (input.reportValidity())
        void enter(null, input.value.trim() || arenas[arena].name, undefined, {
          share: check.checked,
          dedicated: hostRole.value === 'server',
          listed: access.value === 'open',
        });
    },
    true,
  );
  input.onkeydown = (e) => {
    if (e.key === 'Enter') b.click();
  };
  describe();
  input.select();
}
function codeForm() {
  openDialog('code', 'Enter room code');
  const input = document.createElement('input');
  input.setAttribute('aria-label', 'Room code');
  input.maxLength = 36;
  body.append(input);
  input.required = true;
  input.pattern = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}';
  addButton(
    'Join room',
    () => {
      if (input.reportValidity()) void enter(input.value.trim().toLowerCase(), '');
    },
    true,
  );
  input.focus();
}
el('host').onclick = hostForm;
async function enter(
  id: string | null,
  name: string,
  entry?: Entry,
  options?: { share: boolean; dedicated: boolean; listed: boolean },
) {
  if (busy) return;
  if (!options?.dedicated) audio.activate();
  busy = true;
  el('dismiss').hidden = true;
  for (const b of body.querySelectorAll('button')) b.disabled = true;
  note.textContent = 'Contacting room service…';
  try {
    lobbyMap = arena;
    round = 0;
    seats = [];
    publicListing = !!options?.share;
    listingError = '';
    await rooms.enter(id, name, entry, options?.dedicated, options?.listed);
    if (rooms.host) syncSeats();
    if (options?.dedicated) startHostedRound();
    await shareRoom();
    if (!round || modal === 'lobby') drawLobby();
    announce();
  } catch (e) {
    note.textContent =
      (e instanceof Error ? e.message : String(e)) +
      (id ? '' : ' · Check Browse rooms before creating another lobby.');
    for (const b of body.querySelectorAll('button')) b.disabled = false;
  } finally {
    busy = false;
    el('dismiss').hidden = modal === 'lobby';
  }
}
async function refreshRooms() {
  const gen = ++listingGeneration;
  try {
    const list = await rooms.list();
    if (modal !== 'browse' || busy || listingGeneration !== gen) return;
    listed = list;
    listRooms();
  } catch (e) {
    if (modal === 'browse' && listingGeneration === gen) note.textContent = String(e);
  }
}
function listRooms() {
  openDialog('browse', 'Room browser');
  if (!listed.length)
    message('No open rooms. Create one to invite other players.', 'muted dialog-info');
  for (const r of listed) {
    const b = addButton(titleOf(r), () => void enter(r.room, ''));
    b.className = 'room-item';
    b.dataset.room = r.room;
    const count = document.createElement('small');
    count.textContent =
      playerCount(r) + ' / ' + playerCapacity(r) + (isDedicated(r) ? ' · Dedicated' : '') + '   →';
    b.append(count);
    b.disabled = r.peers.length >= r.capacity;
  }
  addButton('Refresh rooms', () => void refreshRooms());
  addButton('Create room', hostForm, !listed.length);
  addButton('Enter room code', codeForm);
}
el('browse').onclick = () => {
  listed = [];
  openDialog('browse', 'Room browser');
  message('Finding rooms…');
  addButton('Refresh rooms', () => void refreshRooms());
  void refreshRooms();
  clearInterval(roomListTimer);
  roomListTimer = window.setInterval(() => {
    if (!busy) void refreshRooms();
  }, 4200);
};
if (!networkAvailable) {
  for (const id of ['host', 'browse']) el<HTMLButtonElement>(id).disabled = true;
  document.querySelector('.action-panel p')!.textContent =
    'This host lacks room or peer support. Solo practice is available.';
}
function syncSeats() {
  const r = rooms.room;
  if (!r || !rooms.host) return;
  seats = seats.filter((s) => r.peers.includes(s.key));
  for (const key of r.peers) {
    if (key === rooms.actor ? isDedicated(r) : !rooms.connected.has(key)) continue;
    if (seats.some((s) => s.key === key)) continue;
    const free = Array.from({ length: 8 }, (_, id) => id).filter(
      (id) => !seats.some((s) => s.id === id),
    );
    const amber = seats.filter((s) => s.id % 2 === 0).length,
      preferred = Number(amber > seats.length - amber);
    const id = (teamMode ? free.find((id) => id % 2 === preferred) : undefined) ?? free[0];
    if (id === undefined) break;
    seats.push({
      key,
      id,
      name: key === rooms.actor ? displayName(id) : callsigns[id],
      profile: key === rooms.actor ? prefs.profile?.key : undefined,
      gun: key === rooms.actor ? gun : 0,
      secondary: key === rooms.actor ? secondary : FIRST_SECONDARY,
      ready: true,
    });
  }
  if (teamMode && !round) {
    // Departures can leave an otherwise ready lobby with every player on one side.
    const amber = seats.filter((s) => s.id % 2 === 0),
      slate = seats.filter((s) => s.id % 2 === 1);
    const crowded = amber.length > slate.length ? amber : slate,
      other = crowded === amber ? slate : amber;
    while (crowded.length > other.length + 1) {
      const member = crowded.pop()!;
      const next = Array.from({ length: 8 }, (_, id) => id).find(
        (id) => id % 2 !== member.id % 2 && !seats.some((s) => s.id === id),
      );
      if (next === undefined) break;
      member.id = next;
      other.push(member);
    }
  }
  if (round && game.round) game.updateSeats(seats);
}
function announce(force = false) {
  if (!rooms.room || !rooms.connected.size) return;
  const msg = rooms.host
    ? {
        t: 'lobby',
        transientInputs: true,
        r: round,
        map: lobbyMap,
        teamMode,
        s: seats.map((s) => ({ ...s, ping: rooms.pingFor(s.key) })),
      }
    : {
        t: 'hello',
        gun,
        secondary,
        ready: true,
        name: prefs.profile?.name || prefs.alias,
        profile: prefs.profile?.key,
      };
  const version = JSON.stringify([rooms.room.room, [...rooms.connected].sort(), msg]);
  if (force || version !== lastAnnouncement) {
    rooms.send(msg);
    lastAnnouncement = version;
  }
}
function onRoomChange() {
  if (!rooms.room) return;
  if (!rooms.connected.size) lastAnnouncement = '';
  if (rooms.host) syncSeats();
  announce(!rooms.host && !seats.length);
  if (modal === 'lobby') drawLobby();
}
function pingLabel(key: string) {
  if (game.solo) return key === 'bot-0' ? 'Local' : 'Bot';
  if (key === rooms.owner) return 'Host';
  if (!rooms.host && !rooms.connected.has(rooms.owner)) return '—';
  const ms = rooms.host
    ? rooms.pingFor(key)
    : (seats.find((s) => s.key === key)?.ping ??
      (key === rooms.actor && rooms.rtt > 0 ? rooms.rtt : undefined));
  return ms === undefined ? '—' : ms + ' ms';
}
function refreshPingCells(root: HTMLElement) {
  for (const cell of root.querySelectorAll<HTMLElement>('[data-peer-ping]')) {
    const key = cell.dataset.peerPing!;
    cell.textContent =
      rooms.host && key !== rooms.actor && !rooms.connected.has(key)
        ? 'Connecting…'
        : pingLabel(key);
  }
}
let scoreTimer = 0;
const scoreboard = el('scoreboard');
function drawScores() {
  const body = el('score-rows');
  const players = new Map(game.players().map((p) => [p.id, p]));
  const rows = [...game.seats].sort(
    (a, b) => (players.get(b.id)?.kills ?? 0) - (players.get(a.id)?.kills ?? 0) || a.id - b.id,
  );
  body.replaceChildren(
    ...rows.map((s) => {
      const p = players.get(s.id);
      const row = document.createElement('tr');
      for (const value of [
        s.name + (s.id === game.mine ? ' (you)' : ''),
        game.teamMode ? teams[s.id % 2] : '—',
        p?.kills ?? 0,
        p?.deaths ?? 0,
        pingLabel(s.key),
      ]) {
        const cell = document.createElement('td');
        cell.textContent = String(value);
        row.append(cell);
      }
      return row;
    }),
  );
}
function showScoreboard(open: boolean) {
  clearInterval(scoreTimer);
  scoreboard.hidden = !open;
  el('scores').setAttribute('aria-expanded', String(open));
  if (open) {
    drawScores();
    scoreTimer = window.setInterval(drawScores, 500);
  }
}
el('scores').onclick = () => showScoreboard(scoreboard.hidden);
window.addEventListener('keydown', (e) => {
  if (
    e.code !== 'Tab' ||
    e.ctrlKey ||
    e.altKey ||
    e.metaKey ||
    e.shiftKey ||
    !controls.active ||
    modal
  )
    return;
  e.preventDefault();
  if (!e.repeat) showScoreboard(true);
});
window.addEventListener('keyup', (e) => {
  if (e.code === 'Tab' && !scoreboard.hidden) showScoreboard(false);
});
window.addEventListener('blur', () => showScoreboard(false));
document.addEventListener('visibilitychange', () => {
  if (document.hidden) showScoreboard(false);
});
function drawLobby() {
  const r = rooms.room;
  if (!r) return;
  const view = JSON.stringify([
    r.room,
    r.peers,
    lobbyMap,
    teamMode,
    seats.map(({ ping, ...seat }) => seat),
    game.ended,
    listingError,
    [...rooms.connected].sort(),
    rooms.notice,
  ]);
  if (modal === 'lobby' && lobbyView === view) {
    refreshPingCells(body);
    return;
  }
  lobbyView = view;
  openDialog('lobby', titleOf(r));
  const server = rooms.host && isDedicated(r);
  el('link-status').textContent = server ? 'Hosting server' : 'In lobby';
  message(
    (rooms.host || seats.length ? arenas[lobbyMap].name : 'Receiving battlefield…') +
      ' · ' +
      playerCount(r) +
      ' / ' +
      playerCapacity(r) +
      ' players · ' +
      (teamMode ? 'Team deathmatch' : 'Free-for-all'),
    'muted dialog-info',
  );
  if (server)
    message(
      game.ended
        ? 'Round complete. The next round starts shortly.'
        : seats.length
          ? 'Dedicated server running.'
          : 'Dedicated server running with zero players.',
      'dialog-info',
    );
  if (listingError) message(listingError, 'dialog-info');
  if (rooms.host) message('Room code: ' + r.room, 'muted dialog-info');
  const roster = document.createElement('div');
  roster.className = 'roster';
  body.append(roster);
  for (const key of [rooms.owner, ...r.peers.filter((k) => k !== rooms.owner)]) {
    if (isDedicated(r) && key === rooms.owner) continue;
    const row = document.createElement('div');
    row.className = 'roster-row';
    const s = seats.find((s) => s.key === key);
    const member = document.createElement('span');
    member.textContent =
      (s ? s.name : 'Joining…') +
      (key === rooms.actor ? ' (you)' : '') +
      (s && teamMode ? ' · ' + teams[s.id % 2] : '');
    if (s?.profile) {
      member.textContent += ' · Nostr';
      member.title = s.profile;
    }
    row.append(member);
    const state = document.createElement('small');
    state.dataset.peerPing = key;
    row.append(state);
    roster.append(row);
  }
  refreshPingCells(roster);
  const actions = document.createElement('div');
  actions.className = 'room-actions';
  body.append(actions);
  if (rooms.host && !server) {
    addButton(
      'Start match',
      () => {
        audio.activate();
        startHostedRound();
        void shareRoom();
      },
      true,
      actions,
    );
  } else if (!rooms.host) {
    note.textContent = rooms.connected.has(rooms.owner)
      ? 'Waiting for the host to start.'
      : 'Connecting to the room host…';
  }
  if (rooms.notice) {
    note.textContent = rooms.notice;
    addButton(
      'Retry connection',
      () =>
        void rooms.retry().catch((e) => {
          note.textContent = String(e);
        }),
      false,
      actions,
    );
  }
  if (server) addButton('Back to overview', closeDialog, true, actions);
  else addButton('Player settings', openSettings, false, actions);
  addButton(server ? 'Stop server' : 'Leave room', () => void leaveRoom(), false, actions);
}
function startHostedRound() {
  if (!rooms.host || !rooms.room) return;
  round = Math.floor(performance.now() * 100) + 1;
  startRound();
  announce(true);
}
function startRound() {
  showScoreboard(false);
  closeDialog();
  game.start(round, lobbyMap, seats, false, teamMode);
}
el('server-menu').onclick = drawLobby;
function onPacket(from: string, msg: Packet) {
  if (rooms.host) {
    if (msg.t === 'hello') {
      syncSeats();
      const s = seats.find((s) => s.key === from);
      if (
        s &&
        typeof msg.gun === 'number' &&
        Number.isInteger(msg.gun) &&
        isPrimary(msg.gun) &&
        isSecondary(msg.secondary) &&
        typeof msg.name === 'string' &&
        msg.name === cleanName(msg.name) &&
        (msg.profile === undefined || validKey(msg.profile)) &&
        typeof msg.ready === 'boolean'
      ) {
        s.name = msg.name || callsigns[s.id];
        s.profile = msg.profile;
        if (!round) {
          s.gun = msg.gun;
          s.secondary = msg.secondary;
        }
        announce(true);
        if (game.ended) game.sendFinalState();
        if (modal === 'lobby') drawLobby();
      }
    } else game.packet(from, msg);
  } else if (from === rooms.owner) {
    if (msg.t === 'closed') {
      void rooms.leave();
      reset();
      openDialog('message', 'Room closed');
      message('The host left the room.');
      addButton('Operations', closeDialog, true);
      return;
    }
    if (msg.t === 'lobby') {
      if (
        !Number.isSafeInteger(msg.r) ||
        typeof msg.r !== 'number' ||
        msg.r < 0 ||
        typeof msg.map !== 'number' ||
        !Number.isInteger(msg.map) ||
        !arenas[msg.map] ||
        typeof msg.teamMode !== 'boolean' ||
        !Array.isArray(msg.s) ||
        msg.s.length > 8
      )
        return;
      const valid = msg.s.every(
        (s) =>
          record(s) &&
          typeof s.key === 'string' &&
          /^[a-f0-9]{64}$/.test(s.key) &&
          typeof s.id === 'number' &&
          Number.isInteger(s.id) &&
          s.id >= 0 &&
          s.id < 8 &&
          typeof s.gun === 'number' &&
          Number.isInteger(s.gun) &&
          isPrimary(s.gun) &&
          isSecondary(s.secondary) &&
          typeof s.name === 'string' &&
          s.name.length > 0 &&
          s.name === cleanName(s.name) &&
          (s.profile === undefined || validKey(s.profile)) &&
          (s.ping === undefined ||
            (Number.isInteger(s.ping) && Number(s.ping) >= 0 && Number(s.ping) <= 60000)) &&
          typeof s.ready === 'boolean',
      );
      if (
        !valid ||
        !msg.s.some((s) => s.key === rooms.actor) ||
        new Set(msg.s.map((s) => s.key)).size !== msg.s.length ||
        new Set(msg.s.map((s) => s.id)).size !== msg.s.length
      )
        return;
      rooms.transientInputs = msg.transientInputs === true;
      seats = msg.s as Seat[];
      lobbyMap = msg.map;
      teamMode = msg.teamMode;
      if (msg.r !== round) {
        const prior = round;
        round = msg.r;
        if (round) {
          startRound();
          const localSeat = seats.find((s) => s.key === rooms.actor)!;
          if (localSeat.gun !== gun || localSeat.secondary !== secondary)
            game.changeLoadout(gun, secondary);
        } else if (prior) {
          game.stop();
          announce();
          drawLobby();
        }
      } else if (!round && modal !== 'settings') drawLobby();
      else game.updateSeats(seats);
    } else game.packet(from, msg);
  }
}
window.addEventListener(
  'pagehide',
  () => {
    game.stop();
    audio.dispose();
    void rooms.leave();
  },
  { once: true },
);
installController(controls, dialog, {
  screen: () => modal ? 'dialog/' + modal : game.round ? (game.mine < 0 ? 'observing' : 'playing') : 'page/' + page,
  menu: () => game.mine < 0 ? drawLobby() : pauseGame(),
  scores: showScoreboard,
  back: () => {
    if (busy) return;
    if (modal === 'code') el('browse').click();
    else if (modal === 'lobby' && game.mine < 0 && game.round) closeDialog();
    else if (modal === 'lobby' || (modal === 'results' && !rooms.host && !game.solo)) {
      [...body.querySelectorAll('button')].find(b => b.textContent === 'Leave room')?.focus();
    } else if (modal) dismiss();
    else if (page !== 'play') showPage('play');
  },
});
showPage('play');

function offerRoom(value: unknown) {
  const entry = parseEntry(value);
  if (!entry || !networkAvailable || rooms.room || busy || game.world) return;
  openDialog('invite', 'Join a public room?');
  message('Join this Faultline lobby using its configured room service.', 'dialog-info');
  addButton('Join room', () => void enter(entry.room, '', entry), true);
  addButton('Not now', closeDialog);
}
if (runtimeHasDomain('intent')) {
  try {
    intentOnDelivery((d) => {
      if (d.convention === 'napplet:game/join') offerRoom(d.payload);
    });
  } catch {
    /* Older shells have no delivery receiver. */
  }
}
if (runtimeHasDomain('storage')) {
  void Promise.resolve()
    .then(() => storageInstanceGetItem('soy.room-entry.v1'))
    .then(async (raw) => {
      if (!raw) return;
      await storageInstanceRemoveItem('soy.room-entry.v1');
      offerRoom(JSON.parse(raw));
    })
    .catch(() => {});
}