import assert from "node:assert/strict";
import { describe, it } from "node:test";

import type { Tier } from "../../access.ts";
import { CANONICAL_CAPABILITIES } from "../../devices/types.ts";
import type { DeviceDeclaration } from "../../devices/types.ts";
import type { ControlMode } from "../../play/controlMode.ts";
import { chromeState } from "../../ui/chromeState.ts";
import type { ChromeInputs, ChromeState } from "../../ui/chromeState.ts";

// ---- Fixtures -------------------------------------------------------------

const TIERS: readonly Tier[] = ["anon", "member", "god"];

const MODES: readonly ControlMode[] = [
  "overview",
  "drive",
  "actor",
  "aircraft",
  "office-overview",
  "office-walk",
];

const CITY_MODES: readonly ControlMode[] = ["overview", "drive", "actor", "aircraft"];
const OFFICE_MODES: readonly ControlMode[] = ["office-overview", "office-walk"];

const MIC: DeviceDeclaration = {
  id: "hq-mic-01",
  kind: "mic",
  label: "Desk mic",
  assetId: "tera:device.mic.desk",
  anchor: { levelId: "l1", propId: "desk-01" },
  capabilities: CANONICAL_CAPABILITIES.mic,
  provenance: "simulated",
  disclosure: "Simulated studio hardware. This is demonstration data, never presence data.",
};

function base(overrides: Partial<ChromeInputs> = {}): ChromeInputs {
  return {
    mode: "overview",
    available: ["overview", "drive", "actor", "aircraft"],
    access: { tier: "anon", signInUrl: "/login.html", subject: null },
    inside: false,
    officeDepth: null,
    viewport: { width: 1440, height: 900, coarsePointer: false },
    feeds: { markers: false, weather: true, flights: true },
    degraded: [],
    devices: [],
    firstVisit: false,
    panelOpen: true,
    planOpen: true,
    board: {
      cityId: "california",
      cityLabel: "California",
      officeId: "lumbridge-hq",
      officeLabel: "SF HQ",
      officeStatus: "active",
      isCalifornia: true,
    },
    ...overrides,
  };
}

/**
 * The properties that must hold in **every** state the product can be in.
 *
 * These are the assertions that would have caught the two live layout defects if
 * anything had been asserting anything at all: the desktop was being shoved
 * 160px for touch controls it does not draw, and a phone was being offered a
 * keyboard reference and no way to move.
 */
function invariants(state: ChromeState, inputs: ChromeInputs): void {
  // A touch surface is never drawn for a mouse. This is the one that was broken.
  if (!inputs.viewport.coarsePointer) {
    assert.equal(state.touchControlsVisible, false, "touch controls on a fine pointer");
    assert.equal(state.stickVisible, false, "a joystick on a fine pointer");
  }
  // Exactly one dock button is pressed, always — it is a radio group.
  const pressed = state.modeButtons.filter((button) => button.pressed);
  assert.equal(pressed.length, 1, "the dock must always show exactly one current mode");
  // ...and the pressed one is always visible, or the viewer cannot see where
  // they are.
  assert.equal(pressed[0]?.visible, true, "the current mode's dock button is hidden");
  // A dock with one button is a label pretending to be a control.
  const visible = state.modeButtons.filter((button) => button.visible);
  assert.equal(state.modeDockVisible, visible.length > 1);
  // The canvas always describes itself to a screen reader.
  assert.ok(state.canvasLabel.length > 20, "the canvas has no useful description");
  // Nothing office-shaped leaks into the city and vice versa.
  if (!inputs.inside) {
    assert.equal(state.officeInviteVisible, false);
    assert.equal(state.officeNoteVisible, false);
    assert.equal(state.devicePanelVisible, false);
  } else {
    assert.equal(state.flyVisible, false, "the aircraft route does not exist indoors");
  }
  // The tier badge is always on screen: every other difference between tiers is
  // a silence, and a silence you cannot attribute is indistinguishable from a
  // fault.
  assert.equal(state.tierVisible, true);
  assert.ok(state.tierLabel.length > 0);
}

// ---- The matrix -----------------------------------------------------------

describe("chromeState across the whole matrix", () => {
  it("holds its invariants in all 72 states: 3 tiers x 6 modes x in/out x coarse/fine", () => {
    let visited = 0;
    for (const tier of TIERS) {
      for (const mode of MODES) {
        for (const inside of [false, true]) {
          for (const coarsePointer of [false, true]) {
            // A mode is only reachable where it exists: the office has two, the
            // city has four, and `controlModeAvailable` already refuses the
            // crossings. Feeding a state the app cannot reach would be testing
            // a fiction.
            const available = inside ? OFFICE_MODES : CITY_MODES;
            const resolved = available.includes(mode) ? mode : available[0]!;
            const inputs = base({
              mode: resolved,
              available,
              inside,
              officeDepth: inside ? (tier === "anon" ? "public" : "full") : null,
              access: {
                tier,
                signInUrl: tier === "anon" ? "/login.html" : null,
                subject: tier === "anon" ? null : "someone@example.com",
              },
              viewport: coarsePointer
                ? { width: 390, height: 844, coarsePointer: true }
                : { width: 1440, height: 900, coarsePointer: false },
              devices: inside ? [MIC] : [],
            });
            invariants(chromeState(inputs), inputs);
            visited += 1;
          }
        }
      }
    }
    assert.equal(visited, TIERS.length * MODES.length * 2 * 2);
  });
});

// ---- The dock -------------------------------------------------------------

describe("the mode dock", () => {
  it("disappears when overview is the only thing available", () => {
    // On two of the three city boards it rendered as a lit pill holding one
    // already-pressed button that did nothing.
    assert.equal(chromeState(base({ available: ["overview"] })).modeDockVisible, false);
  });

  it("appears the moment there is a second mode", () => {
    assert.equal(chromeState(base({ available: ["overview", "drive"] })).modeDockVisible, true);
  });

  it("lets one View button stand for both orbit states", () => {
    // They are one idea — the camera is yours and nothing else is — and two
    // buttons for it would swap under the viewer as they walked through a door.
    const outside = chromeState(base({ mode: "overview" }));
    assert.equal(outside.modeButtons.find((b) => b.mode === "overview")?.pressed, true);

    const inside = chromeState(
      base({ mode: "office-overview", available: OFFICE_MODES, inside: true, officeDepth: "full" }),
    );
    assert.equal(inside.modeButtons.find((b) => b.mode === "overview")?.pressed, true);
    assert.equal(inside.modeButtons.find((b) => b.mode === "overview")?.visible, true);
  });

  it("hides a mode that is not available", () => {
    const state = chromeState(base({ available: ["overview", "aircraft"] }));
    assert.equal(state.modeButtons.find((b) => b.mode === "drive")?.visible, false);
    assert.equal(state.modeButtons.find((b) => b.mode === "actor")?.visible, false);
    assert.equal(state.modeButtons.find((b) => b.mode === "aircraft")?.visible, true);
  });
});

// ---- Layout ---------------------------------------------------------------

describe("layout", () => {
  it("splits at the two published breakpoints and nowhere else", () => {
    const at = (width: number) => chromeState(base({ viewport: { width, height: 800, coarsePointer: false } })).layout;
    assert.equal(at(390), "phone");
    assert.equal(at(600), "phone");
    assert.equal(at(601), "compact");
    assert.equal(at(900), "compact");
    assert.equal(at(901), "desktop");
    assert.equal(at(1440), "desktop");
  });

  it("assumes a desktop rather than a phone when the width is nonsense", () => {
    // A `NaN` width from a detached iframe must not collapse the layout to a
    // bottom sheet: wrong-and-usable beats wrong-and-unusable.
    const state = chromeState(base({ viewport: { width: Number.NaN, height: 0, coarsePointer: false } }));
    assert.equal(state.layout, "desktop");
  });

  it("keeps the panel toggle off the desktop, where the column is furniture", () => {
    assert.equal(chromeState(base()).panelToggleVisible, false);
    assert.equal(
      chromeState(base({ viewport: { width: 820, height: 1180, coarsePointer: true } }))
        .panelToggleVisible,
      true,
    );
  });

  it("only puts a scrim behind the panel where the panel is a sheet", () => {
    const phone = { width: 390, height: 844, coarsePointer: true };
    assert.equal(chromeState(base({ viewport: phone, panelOpen: true })).scrimVisible, true);
    assert.equal(chromeState(base({ viewport: phone, panelOpen: false })).scrimVisible, false);
    assert.equal(chromeState(base({ panelOpen: true })).scrimVisible, false);
  });

  it("publishes the body classes as one list rather than five toggles", () => {
    const state = chromeState(
      base({
        panelOpen: false,
        planOpen: false,
        presenceVisible: true,
        cameraLive: true,
        viewport: { width: 390, height: 844, coarsePointer: true },
      }),
    );
    for (const name of ["panel-closed", "minimap-off", "presence-on", "camera-live", "touch-first", "layout-phone"]) {
      assert.ok(state.bodyClasses.includes(name), `missing body class ${name}`);
    }
    assert.equal(state.bodyClasses.includes("inside"), false);
  });
});

// ---- The touch surface ----------------------------------------------------

describe("the touch surface", () => {
  const phone = { width: 390, height: 844, coarsePointer: true };

  it("is drawn in every play mode, and in no orbit mode", () => {
    for (const mode of ["drive", "actor", "aircraft"] as const) {
      const state = chromeState(base({ mode, viewport: phone }));
      assert.equal(state.touchControlsVisible, true, `${mode} has no touch surface`);
      assert.equal(state.stickVisible, true);
    }
    assert.equal(chromeState(base({ mode: "overview", viewport: phone })).stickVisible, false);
    assert.equal(
      chromeState(base({ mode: "office-overview", available: OFFICE_MODES, inside: true, viewport: phone }))
        .stickVisible,
      false,
    );
  });

  it("names what the stick moves rather than leaving a bare circle", () => {
    assert.equal(chromeState(base({ mode: "drive", viewport: phone })).stickLabel, "Steer");
    assert.equal(chromeState(base({ mode: "aircraft", viewport: phone })).stickLabel, "Fly");
    assert.equal(
      chromeState(base({ mode: "office-walk", available: OFFICE_MODES, inside: true, viewport: phone }))
        .stickLabel,
      "Walk",
    );
  });

  it("shows only the actions the current mode actually has", () => {
    const drive = chromeState(base({ mode: "drive", viewport: phone }));
    const shown = (state: ChromeState) =>
      state.touchActions.filter((action) => action.visible).map((action) => action.id);
    assert.deepEqual(shown(drive), [
      "touch-primary", "touch-assist", "touch-reset", "touch-camera", "touch-map",
    ]);
    assert.equal(drive.touchActions.find((a) => a.id === "touch-primary")?.label, "Handbrake");

    const fly = chromeState(base({ mode: "aircraft", viewport: phone }));
    assert.equal(fly.touchActions.find((a) => a.id === "touch-primary")?.label, "Throttle");
    assert.deepEqual(shown(fly), [
      "touch-primary", "touch-pitch-up", "touch-pitch-down", "touch-assist", "touch-reset", "touch-map",
    ]);

    const walk = chromeState(
      base({ mode: "office-walk", available: OFFICE_MODES, inside: true, viewport: phone }),
    );
    // On foot there is no handbrake, no throttle and nothing to reset.
    assert.deepEqual(shown(walk), ["touch-map"]);
  });

  it("gives a crow on the wing its own action pad", () => {
    const ground = chromeState(base({ mode: "actor", viewport: phone, actor: { kind: "crow", flying: false } }));
    assert.equal(ground.touchActions.find((a) => a.id === "touch-primary")?.label, "Sprint");
    assert.equal(ground.touchActions.find((a) => a.id === "touch-secondary")?.visible, false);

    const flying = chromeState(base({ mode: "actor", viewport: phone, actor: { kind: "crow", flying: true } }));
    assert.equal(flying.touchActions.find((a) => a.id === "touch-primary")?.label, "Climb");
    assert.equal(flying.touchActions.find((a) => a.id === "touch-primary")?.control, "ascend");
    assert.equal(flying.touchActions.find((a) => a.id === "touch-secondary")?.visible, true);
    assert.equal(flying.stickLabel, "Bank");
  });
});

// ---- The rail -------------------------------------------------------------

describe("the rail", () => {
  it("drops the keyboard hints on a device with no keyboard", () => {
    const phone = chromeState(base({ viewport: { width: 390, height: 844, coarsePointer: true } }));
    assert.equal(phone.railHintsVisible, false);
    assert.deepEqual(phone.railHints, []);
    // The `?` button stays: it is the only reference that layout has, since the
    // key strip is `display: none` there. What changes is what it opens.
    assert.equal(phone.helpVisible, true);
  });

  it("shows at most two hints, chosen for the mode", () => {
    const drive = chromeState(base({ mode: "drive" }));
    assert.equal(drive.railHintsVisible, true);
    assert.ok(drive.railHints.length <= 2);
    assert.deepEqual(drive.railHints.map((hint) => hint.id), ["primary", "assist"]);
  });

  it("only offers the plan button where a key cannot do the job", () => {
    assert.equal(chromeState(base()).planToggleVisible, false);
    assert.equal(
      chromeState(base({ viewport: { width: 1024, height: 768, coarsePointer: true } })).planToggleVisible,
      true,
    );
    assert.equal(
      chromeState(base({ viewport: { width: 390, height: 844, coarsePointer: false } })).planToggleVisible,
      true,
    );
  });

  it("ties the plan to the toggle and to the minimap, in one decision", () => {
    const on = chromeState(base({ planOpen: true }));
    assert.equal(on.minimapVisible, true);
    assert.equal(on.planTogglePressed, true);
    assert.equal(on.bodyClasses.includes("minimap-off"), false);

    const off = chromeState(base({ planOpen: false }));
    assert.equal(off.minimapVisible, false);
    assert.equal(off.planTogglePressed, false);
    assert.ok(off.bodyClasses.includes("minimap-off"));
  });

  it("drops the hover-only readout where there is no hover", () => {
    assert.equal(chromeState(base()).minimapReadoutVisible, true);
    assert.equal(
      chromeState(base({ viewport: { width: 390, height: 844, coarsePointer: true } }))
        .minimapReadoutVisible,
      false,
    );
  });
});

// ---- The tier badge -------------------------------------------------------

describe("the tier badge", () => {
  it("says what signing in adds, rather than labelling the visitor", () => {
    // "Public view" names the visitor rather than the offer, which on a product
    // designed anon-first is the wrong sentence in the most-read corner.
    const anon = chromeState(base());
    assert.equal(anon.tierLabel, "Open demo");
    assert.ok(anon.tierAdds !== null);
    assert.match(anon.tierAdds, /Sign in adds/);
    assert.match(anon.tierAdds, /character/);
    assert.equal(anon.signInVisible, true);
    assert.equal(anon.signInHref, "/login.html");
  });

  it("offers nothing to add when there is nothing to add", () => {
    // A clean self-hosted clone with no API resolves to `member` and has no door
    // to knock on. Telling that visitor to sign in to a server that does not
    // exist is the small dishonesty that makes the rest untrustworthy.
    const selfHosted = chromeState(
      base({ access: { tier: "member", signInUrl: null, subject: null } }),
    );
    assert.equal(selfHosted.tierLabel, "Full view");
    assert.equal(selfHosted.tierAdds, null);
    assert.equal(selfHosted.signInVisible, false);

    const anonNoDoor = chromeState(base({ access: { tier: "anon", signInUrl: null, subject: null } }));
    assert.equal(anonNoDoor.tierAdds, null);
    assert.equal(anonNoDoor.signInVisible, false);
  });

  it("prefers a chosen name over an auth subject, and offers Character only with a profile", () => {
    const withProfile = chromeState(
      base({
        access: {
          tier: "member",
          signInUrl: null,
          subject: "auth|1234",
          displayName: "Karti",
          hasProfile: true,
        },
      }),
    );
    assert.equal(withProfile.whoLabel, "Karti");
    assert.equal(withProfile.characterVisible, true);
    assert.equal(withProfile.signInVisible, false);

    const withoutProfile = chromeState(
      base({ access: { tier: "god", signInUrl: null, subject: "auth|1234" } }),
    );
    assert.equal(withoutProfile.whoLabel, "auth|1234");
    assert.equal(withoutProfile.characterVisible, false);
    assert.equal(withoutProfile.tierLabel, "Godmode");
    assert.equal(withoutProfile.tierTone, "god");
  });
});

// ---- Inside a studio ------------------------------------------------------

describe("inside a studio", () => {
  const insideBase = (overrides: Partial<ChromeInputs> = {}) =>
    base({
      inside: true,
      mode: "office-overview",
      available: OFFICE_MODES,
      officeDepth: "full",
      ...overrides,
    });

  it("puts the sign-in invitation on a surface that survives a closed panel", () => {
    // It used to be the last child of `#office-badge` inside `#panel`, and on a
    // phone `#panel` is a bottom sheet that starts closed — so the only in-office
    // call to sign in was behind a hamburger on the device least likely to open
    // one.
    const publicView = chromeState(insideBase({ officeDepth: "public" }));
    assert.equal(publicView.officeInviteVisible, true);
    assert.match(publicView.officeInviteText, /the building, not the people/);
    assert.equal(publicView.officeInviteLinkLabel, "Sign in for the live floor");

    const full = chromeState(insideBase({ officeDepth: "full" }));
    assert.equal(full.officeInviteVisible, false);
  });

  it("says something honest where there is no door at all", () => {
    const state = chromeState(
      insideBase({ officeDepth: "public", access: { tier: "anon", signInUrl: null, subject: null } }),
    );
    assert.equal(state.officeInviteVisible, true);
    assert.equal(state.officeInviteLinkLabel, null);
    assert.match(state.officeInviteText, /no sign-in/);
  });

  it("shows the screens button only where there are screens and the depth to drive them", () => {
    assert.equal(chromeState(insideBase({ office: { mediaSurfaceCount: 0 } })).screensVisible, false);
    assert.equal(chromeState(insideBase({ office: { mediaSurfaceCount: 3 } })).screensVisible, true);
    assert.equal(
      chromeState(insideBase({ officeDepth: "public", office: { mediaSurfaceCount: 3 } })).screensVisible,
      false,
    );
  });

  it("counts the screens in words a person would use", () => {
    assert.match(
      chromeState(insideBase({ office: { mediaSurfaceCount: 1 } })).officeNoteText,
      /1 screen ready · media stays off until you opt in\./,
    );
    assert.match(
      chromeState(insideBase({ office: { mediaSurfaceCount: 4, mediaSurfaceActiveCount: 2 } })).officeNoteText,
      /2 of 4 screens active/,
    );
  });

  it("carries the robot disclosure alongside, never instead", () => {
    const both = chromeState(
      insideBase({ office: { mediaSurfaceCount: 2, robotDisclosure: "Robot activity is simulated." } }),
    );
    assert.match(both.officeNoteText, /2 screens ready/);
    assert.match(both.officeNoteText, /Robot activity is simulated\./);
  });

  it("gives an anonymous visitor the hardware panel", () => {
    // The declarations are authored into the pack, so they are public by
    // construction — the hardware in the room is a description of the room. What
    // an account buys is the live readings.
    const anon = chromeState(
      insideBase({
        officeDepth: "public",
        access: { tier: "anon", signInUrl: "/login.html", subject: null },
        devices: [MIC],
      }),
    );
    assert.equal(anon.devicePanelVisible, true);
    assert.deepEqual(anon.deviceDeclarations, [MIC]);
    assert.equal(anon.devicePanelLabel, "Studio hardware →");
    assert.equal(chromeState(insideBase({ devices: [] })).devicePanelVisible, false);
  });

  it("refuses to offer a walk in a building with no walker", () => {
    assert.equal(chromeState(insideBase({ office: { walkable: false } })).walkVisible, false);
    assert.equal(chromeState(insideBase()).walkVisible, true);
  });

  it("names the building, not the board", () => {
    const state = chromeState(insideBase());
    assert.equal(state.panelTitle, "SF HQ");
    assert.equal(state.panelToggleLabel, "SF HQ");
    assert.equal(state.boardPicker, "office");
    assert.equal(state.enterLabel, "← Back to the city");
    assert.match(state.panelSubtitle, /active environment/);
  });

  it("says a building is still being built when it is", () => {
    const state = chromeState(base({ board: { officeLabel: "Frontier Valley", officeStatus: "building" } }));
    assert.equal(state.enterLabel, "Preview Frontier Valley · building →");
  });
});

// ---- The honesty line -----------------------------------------------------

describe("the honesty line", () => {
  it("says nothing at all when nothing is live", () => {
    const state = chromeState(base({ feeds: { markers: false, weather: false, flights: false } }));
    assert.equal(state.sourceVisible, false);
    assert.equal(state.sourceLabel, "");
    assert.equal(state.sourceLive, false);
  });

  it("names the parts rather than claiming the whole", () => {
    // "live data" printed over invented companies because a weather station
    // answered is exactly the claim this wording exists to prevent.
    assert.equal(
      chromeState(base({ feeds: { markers: false, weather: true, flights: false } })).sourceLabel,
      "live weather",
    );
    assert.equal(
      chromeState(base({ feeds: { markers: false, weather: true, flights: true } })).sourceLabel,
      "live weather · live traffic",
    );
    assert.equal(
      chromeState(base({ feeds: { markers: true, weather: true, flights: true } })).sourceLabel,
      "live data",
    );
  });

  it("retires the weather claim while somebody's invented sky is up", () => {
    const state = chromeState(
      base({ feeds: { markers: false, weather: true, flights: false, weatherOverridden: true } }),
    );
    assert.equal(state.sourceLabel, "");
    assert.equal(
      chromeState(base({ feeds: { markers: true, weather: true, flights: true, weatherOverridden: true } }))
        .sourceLabel,
      "live markers · live traffic",
    );
  });

  it("lets the office's occupancy disclosure outrank the board's liveness", () => {
    const state = chromeState(
      base({
        inside: true,
        mode: "office-overview",
        available: OFFICE_MODES,
        officeDepth: "full",
        feeds: { markers: true, weather: true, flights: true, sampleOccupancy: true },
      }),
    );
    assert.equal(state.sourceLabel, "sample occupancy · these people are invented");
    assert.equal(state.sourceLive, false, "an invented staff list is not a live-data green");
    assert.ok(state.bodyClasses.includes("sample-occupancy"));
  });

  it("carries the live sources' credit lines, deduplicated, to the ? card", () => {
    // A licence obligation that was plumbed to within one line of being met:
    // parsed into `WeatherFeed.attribution` and `FlightsBody.attribution`, then
    // read by nobody.
    const state = chromeState(
      base({
        feeds: {
          markers: false,
          weather: true,
          flights: true,
          credits: ["Data from MET Norway", "Data from MET Norway", "adsb.lol, ODbL", ""],
        },
      }),
    );
    assert.deepEqual(state.credits, ["Data from MET Norway", "adsb.lol, ODbL"]);
    assert.deepEqual(chromeState(base()).credits, []);
  });

  it("shows the deployment's demotions to an admin and to nobody else", () => {
    const degraded = ["No weather source is configured, so the sky is synthetic."];
    assert.equal(chromeState(base({ degraded })).degradedVisible, false);
    assert.equal(
      chromeState(base({ degraded, access: { tier: "member", signInUrl: null, subject: "x" } }))
        .degradedVisible,
      false,
    );
    const admin = chromeState(base({ degraded, access: { tier: "god", signInUrl: null, subject: "x" } }));
    assert.equal(admin.degradedVisible, true);
    assert.deepEqual(admin.degradedLines, degraded);
    // Nothing to report is not a reason to draw an empty card.
    assert.equal(
      chromeState(base({ degraded: [], access: { tier: "god", signInUrl: null, subject: "x" } }))
        .degradedVisible,
      false,
    );
  });
});

// ---- Lists, HUD and detail ------------------------------------------------

describe("the lists the applier draws", () => {
  it("marks exactly one board active, and carries the office status through", () => {
    const state = chromeState(
      base({
        inside: true,
        mode: "office-overview",
        available: OFFICE_MODES,
        officeDepth: "full",
        boards: [
          { id: "lumbridge-hq", label: "SF HQ", status: "active" },
          { id: "mateo-court", label: "LA Studio", status: "active" },
          { id: "frontier-valley", label: "Frontier", status: "building" },
        ],
      }),
    );
    assert.deepEqual(state.boards.map((board) => board.active), [true, false, false]);
    assert.equal(state.boards[2]?.status, "building");
  });

  it("numbers a view list that did not number itself", () => {
    const state = chromeState(
      base({
        views: [
          { id: "a", shortLabel: "Approach", description: "A long way out." },
          { id: "b", number: "07", shortLabel: "Paseo" },
        ],
        activeViewId: "b",
      }),
    );
    assert.deepEqual(state.views.map((view) => view.number), ["01", "07"]);
    assert.deepEqual(state.views.map((view) => view.active), [false, true]);
    assert.equal(state.chaptersVisible, true);
  });

  it("drops the blurb where there is nothing to say, and on a phone regardless", () => {
    const withText = chromeState(
      base({ views: [{ id: "a", shortLabel: "A", description: "Something." }], activeViewId: "a" }),
    );
    assert.equal(withText.blurbVisible, true);
    assert.equal(withText.blurbText, "Something.");

    const noText = chromeState(base({ views: [{ id: "a", shortLabel: "A" }], activeViewId: "a" }));
    assert.equal(noText.blurbVisible, false);

    const phone = chromeState(
      base({
        viewport: { width: 390, height: 844, coarsePointer: true },
        views: [{ id: "a", shortLabel: "A", description: "Something." }],
        activeViewId: "a",
      }),
    );
    assert.equal(phone.blurbVisible, false);
  });

  it("keeps the play HUD off in the orbit modes and on with real telemetry", () => {
    assert.equal(chromeState(base({ mode: "overview" })).playHudVisible, false);
    assert.equal(chromeState(base({ mode: "drive" })).playHud, null);

    const driving = chromeState(
      base({
        mode: "drive",
        telemetry: {
          kind: "drive",
          speedMps: 26.8,
          roadName: "US-101",
          driveMode: "assisted",
          progress: 0.42,
          camera: "chase",
          guardrailContact: false,
          collisionRisk: 0.1,
        },
      }),
    );
    assert.equal(driving.playHudVisible, true);
    assert.equal(driving.playHud?.mode, "Drive");
    assert.match(driving.playHud?.primary ?? "", /60 mph · US-101/);
    assert.equal(driving.playHud?.warning, false);
  });

  it("formats an aircraft pick into the card an anonymous visitor gets", () => {
    const state = chromeState(
      base({
        detail: {
          kind: "aircraft",
          aircraft: {
            id: "a1b2c3",
            callsign: "UAL 512",
            lat: 37.6188,
            lng: -122.3756,
            altitude: 3048,
            heading: 47,
            attribution: "Data from adsb.lol, ODbL",
          },
        },
      }),
    );
    assert.equal(state.detailVisible, true);
    assert.equal(state.detail?.kind, "aircraft");
    if (state.detail?.kind !== "aircraft") throw new Error("unreachable");
    assert.equal(state.detail.view.title, "UAL 512");
    assert.equal(state.detail.view.subtitle, "Mode S A1B2C3");
    assert.deepEqual(
      state.detail.view.rows.map((row) => row.label),
      ["Altitude", "Heading", "Position"],
    );
    assert.match(state.detail.view.rows[0]?.value ?? "", /10,000 ft · 3,048 m/);
    assert.match(state.detail.view.rows[1]?.value ?? "", /47° NE/);
    assert.match(state.detail.view.rows[2]?.value ?? "", /37\.619° N · 122\.376° W/);
    assert.equal(state.detail.view.attribution, "Data from adsb.lol, ODbL");
  });

  it("labels an invented track as invented", () => {
    const state = chromeState(
      base({
        detail: {
          kind: "aircraft",
          aircraft: { id: "sim-SIM 1", lat: 34, lng: -118, altitude: 900, heading: 180, synthetic: true },
        },
      }),
    );
    if (state.detail?.kind !== "aircraft") throw new Error("unreachable");
    assert.equal(state.detail.view.synthetic, true);
    assert.match(state.detail.view.subtitle, /Simulated track/);
  });

  it("still shows a plain marker string", () => {
    const state = chromeState(base({ detail: { kind: "text", text: "Something on the map." } }));
    assert.equal(state.detailVisible, true);
    assert.deepEqual(state.detail, { kind: "text", text: "Something on the map." });
    assert.equal(chromeState(base()).detailVisible, false);
    assert.equal(chromeState(base()).detail, null);
  });
});

// ---- Onboarding -----------------------------------------------------------

describe("onboarding's own visibility", () => {
  it("appears on a first visit to the board, and on no repeat visit", () => {
    assert.equal(chromeState(base({ firstVisit: true })).onboardingVisible, true);
    assert.equal(chromeState(base({ firstVisit: false })).onboardingVisible, false);
  });

  it("does not interrupt somebody who is already doing the thing it teaches", () => {
    assert.equal(chromeState(base({ firstVisit: true, mode: "drive" })).onboardingVisible, false);
    assert.equal(
      chromeState(
        base({ firstVisit: true, inside: true, mode: "office-overview", available: OFFICE_MODES }),
      ).onboardingVisible,
      false,
    );
  });
});

// ---- Purity ---------------------------------------------------------------

describe("purity", () => {
  it("returns the same answer for the same inputs, and mutates nothing", () => {
    // The whole reason this module exists. A decision that reads module state is
    // a decision you cannot enumerate.
    const inputs = base({ mode: "drive", firstVisit: true });
    const snapshot = JSON.parse(JSON.stringify(inputs)) as unknown;
    const first = chromeState(inputs);
    const second = chromeState(inputs);
    assert.deepEqual(first, second);
    assert.deepEqual(JSON.parse(JSON.stringify(inputs)), snapshot);
  });

  it("survives being given only the twelve documented keys", () => {
    // The contract with `integration`, which adopts this with stubs before the
    // optional refinements are wired.
    const minimal: ChromeInputs = {
      mode: "overview",
      available: ["overview"],
      access: { tier: "anon", signInUrl: null, subject: null },
      inside: false,
      officeDepth: null,
      viewport: { width: 1440, height: 900, coarsePointer: false },
      feeds: { markers: false, weather: false, flights: false },
      degraded: [],
      devices: [],
      firstVisit: false,
      panelOpen: true,
      planOpen: true,
    };
    const state = chromeState(minimal);
    assert.equal(state.modeDockVisible, false);
    assert.equal(state.boards.length, 0);
    assert.equal(state.views.length, 0);
    assert.equal(state.playHud, null);
    assert.equal(state.detail, null);
    assert.equal(state.tierVisible, true);
  });
});
