Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

127 KB
Raw Blame
#nullable enable
using System.Collections;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Statecraft.Game.Map;
using Statecraft.Game.UI;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.TestTools.Constraints;
using UnityEngine.UIElements;
using Is = UnityEngine.TestTools.Constraints.Is;

/// <summary>Plan Task 9: settlement labels as UI Toolkit pills in EB Garamond, decluttered and on their markers.</summary>
public class MapLabelTests
{
    MapScene map = null!;
    Camera cam = null!;
    CameraRig rig = null!;

    [SetUp]
    public void Open()
    {
        EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
        map = Object.FindFirstObjectByType<MapScene>(); map.Build();
        cam = Camera.main; rig = cam.GetComponent<CameraRig>();
        Pose(34.85, 32.0, 90000f);
    }

    [TearDown]
    public void Close() { cam.targetTexture = null; EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); VisualToggles.Clear(); }

    void Pose(double lon, double lat, float distance)
    {
        rig.LookAt = map.Frame.ToWorld(lon, lat, 0); rig.Distance = distance; rig.Yaw = 0; rig.TopInset = 0; rig.Apply();
    }

    static bool Shown(VisualElement slot) => slot.style.visibility.value == Visibility.Visible;

    /// <summary>A UIDocument with Game.uxml on a panel of its own size (scale-with-screen-size against 1920x1080, so a
    /// 2880x1620 target is a scale of 1.5), the camera drawing to a texture of the same size, "loading" removed.</summary>
    sealed class HdPanel : System.IDisposable
    {
        public readonly int Width, Height; public readonly VisualElement Root;
        readonly RenderTexture rt, camRt; readonly PanelSettings ps; readonly GameObject go; readonly Camera cam;

        public HdPanel(Camera cam, int width = 1920, int height = 1080, bool loading = false)
        {
            this.cam = cam; Width = width; Height = height;
            rt = new RenderTexture(width, height, 0); camRt = new RenderTexture(width, height, 24);
            ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel)); ps.targetTexture = rt;
            go = new GameObject("LabelPanel"); go.SetActive(false);
            var doc = go.AddComponent<UIDocument>(); doc.panelSettings = ps; doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml);
            go.SetActive(true);
            cam.targetTexture = camRt;
            Root = doc.rootVisualElement;
            if (!loading) Root.Q("root")?.RemoveFromClassList("loading");
        }

        /// <summary>A world point in panel coordinates, independently of the presenter: the camera's pixels, y flipped, times
        /// the panel's scale.</summary>
        public Vector2 ToPanel(Vector3 world, out bool inFront)
        {
            var p = cam.WorldToScreenPoint(world); inFront = p.z > 0;
            float scale = Root.worldBound.width / Width;
            return new Vector2(p.x * scale, (Height - p.y) * scale);
        }

        public void Dispose()
        {
            Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt);
            cam.targetTexture = null; camRt.Release(); Object.DestroyImmediate(camRt);
        }
    }

    static Vector3 MarkerTopOf(string id)
    {
        var box = GameObject.Find("Settlements").transform.Find(id);
        return box.position + Vector3.up * box.lossyScale.y / 2;
    }

    /// <summary>A settlement's kit (its drawn buildings) as a panel rectangle, independently of the presenter: the hull of
    /// every vertex of its mesh through the camera's pixels.</summary>
    static Rect KitRectOf(HdPanel hd, string id)
    {
        var kit = GameObject.Find(Statecraft.Game.Map.Kits.KitLayer.RootName).transform.Find(id);
        Assert.IsNotNull(kit, id + " has a kit");
        float x0 = float.MaxValue, y0 = float.MaxValue, x1 = float.MinValue, y1 = float.MinValue;
        foreach (var v in kit.GetComponent<MeshFilter>().sharedMesh.vertices)
        {
            var p = hd.ToPanel(kit.localToWorldMatrix.MultiplyPoint3x4(v), out _);
            x0 = Mathf.Min(x0, p.x); y0 = Mathf.Min(y0, p.y); x1 = Mathf.Max(x1, p.x); y1 = Mathf.Max(y1, p.y);
        }
        return Rect.MinMaxRect(x0, y0, x1, y1);
    }

    static float Cover(Rect pill, Rect kit)
    {
        float w = Mathf.Min(pill.xMax, kit.xMax) - Mathf.Max(pill.xMin, kit.xMin), h = Mathf.Min(pill.yMax, kit.yMax) - Mathf.Max(pill.yMin, kit.yMin);
        return w <= 0 || h <= 0 ? 0f : w * h / (kit.width * kit.height);
    }

    /// <summary>Issue #214: a kit's columns hold every vertex, stand on the kit's lowest point, and keep a tall landmark's
    /// height to its own cell (a low house beside a tall tower gets a low column).</summary>
    [Test]
    public void KitColumnsHoldTheKitAndKeepATowerToItsCell()
    {
        var pts = new[] { new Vector3(0, 0, 0), new Vector3(10, 8, 10), new Vector3(90, 0, 90), new Vector3(100, 60, 100) };   // a house, a tower
        var cols = Statecraft.Game.Map.Kits.KitMesh.Columns(pts);
        Assert.AreEqual(2, cols.Length, "two occupied cells");
        foreach (var p in pts) Assert.IsTrue(cols.Any(c => c.min.x <= p.x && p.x <= c.max.x && c.min.y <= p.y && p.y <= c.max.y && c.min.z <= p.z && p.z <= c.max.z), p.ToString());
        foreach (var c in cols) Assert.AreEqual(0f, c.min.y, "from the ground");
        Assert.AreEqual(8f, cols.Min(c => c.max.y), "the house's column is as tall as the house");
        // The built map's columns come from the kit build, not from the uploaded mesh: the player has no CPU copy to read
        // (a WebGL boot read mesh.vertices and failed).
        var tlv = GameObject.Find(Statecraft.Game.Map.Kits.KitLayer.RootName).transform.Find("tel_aviv").GetComponent<MeshFilter>().sharedMesh;
        Assert.IsFalse(tlv.isReadable, "the kit meshes keep no CPU copy");
        foreach (var s in map.Settlements) Assert.IsTrue(map.TryKitColumns(s.Id, out var c) && c.Length > 0, s.Id + " has kit columns");
    }

    /// <summary>Review C-m3: with the "kits" toggle off the marker boxes are drawn, and a pill sits just above its box, not
    /// above the hidden kit; turning the kits back on moves it back above the kit.</summary>
    [UnityTest]
    public IEnumerator WithTheKitsOffAPillSitsAboveItsMarker()
    {
        var hd = new HdPanel(cam);
        var labels = new MapLabelsPresenter(hd.Root, map, cam);
        try
        {
            var deg = map.Settlements.Single(s => s.Id == "degania_alef");
            Pose(deg.Lon, deg.Lat, 10000f);
            var pill = labels.Labels.Single(l => l.name == "label-degania_alef");
            Assert.IsTrue(map.KitsShown);
            yield return Settle(labels);
            var withKit = pill.worldBound;
            VisualToggles.Set("kits", false);
            Assert.IsFalse(map.KitsShown);
            labels.Refresh(); yield return null;
            var box = GameObject.Find("Settlements").transform.Find("degania_alef");
            float top = float.MaxValue;
            for (int c = 0; c < 8; c++)
            {
                var corner = box.position + Vector3.Scale(box.lossyScale, new Vector3((c & 1) - 0.5f, ((c >> 1) & 1) - 0.5f, ((c >> 2) & 1) - 0.5f));
                top = Mathf.Min(top, hd.ToPanel(corner, out _).y);
            }
            var withMarker = pill.worldBound;
            TestContext.WriteLine($"Degania pill with the kit {withKit}, with the marker {withMarker}, marker top {top:F0}");
            Assert.AreEqual(top - MapLabelsPresenter.LiftPx, withMarker.yMax, 2f, "LiftPx above the marker box");
            Assert.Greater(withMarker.yMax, withKit.yMax + 2f, "lower than above the (hidden) kit");
            VisualToggles.Set("kits", true);
            labels.Refresh(); yield return null;
            Assert.AreEqual(withKit.yMax, pill.worldBound.yMax, 0.5f, "back above the kit");
        }
        finally { labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>Issue #214: the spots a pill may take against its kit's screen rectangle, LiftPx clear of it.</summary>
    [Test]
    public void SpotsSitClearOfTheKit()
    {
        var kit = new Rect(100, 200, 60, 40); var size = new Vector2(30, 10); var point = new Vector2(130, 215);
        float lift = MapLabelsPresenter.LiftPx;
        Assert.AreEqual(new Rect(115, 200 - lift - 10, 30, 10), MapLabelsPresenter.SpotRect(MapLabelsPresenter.Spot.AboveCentre, kit, point, size));
        Assert.AreEqual(new Rect(130, 200 - lift - 10, 30, 10), MapLabelsPresenter.SpotRect(MapLabelsPresenter.Spot.AboveLeft, kit, point, size));
        Assert.AreEqual(new Rect(100, 200 - lift - 10, 30, 10), MapLabelsPresenter.SpotRect(MapLabelsPresenter.Spot.AboveRight, kit, point, size));
        Assert.AreEqual(new Rect(160 + lift, 215, 30, 10), MapLabelsPresenter.SpotRect(MapLabelsPresenter.Spot.BesideRight, kit, point, size));
        Assert.AreEqual(new Rect(100 - lift - 30, 215, 30, 10), MapLabelsPresenter.SpotRect(MapLabelsPresenter.Spot.BesideLeft, kit, point, size));
        Assert.AreEqual(new Rect(115, 240 + lift, 30, 10), MapLabelsPresenter.SpotRect(MapLabelsPresenter.Spot.Below, kit, point, size));
        foreach (var spot in new[] { MapLabelsPresenter.Spot.AboveCentre, MapLabelsPresenter.Spot.AboveLeft, MapLabelsPresenter.Spot.AboveRight,
                     MapLabelsPresenter.Spot.BesideRight, MapLabelsPresenter.Spot.BesideLeft, MapLabelsPresenter.Spot.Below })
            Assert.AreEqual(0f, MapLabelsPresenter.Cover(MapLabelsPresenter.SpotRect(spot, kit, point, size), kit), spot.ToString());
        var over = MapLabelsPresenter.SpotRect(MapLabelsPresenter.Spot.Over, kit, point, size);
        Assert.AreEqual(new Rect(115, 215 - lift - 10, 30, 10), over);
        Assert.AreEqual(30f * 9f / (60f * 40f), MapLabelsPresenter.Cover(over, kit), 1e-4f, "over the kit: its bottom 9 rows, 270 of its 2400 px");
        Assert.AreEqual(0f, MapLabelsPresenter.Cover(over, new Rect(0, 0, 0, 0)), "an empty kit is never covered");
        Assert.AreEqual(new Rect(115, 215 + lift, 30, 10), MapLabelsPresenter.SpotRect(MapLabelsPresenter.Spot.Under, kit, point, size), "under the point (#599)");
    }
    [Test]
    public void EverySettlementHasOneGaramondPillThatIgnoresThePointer()
    {
        using var ui = new UiTestKit();
        using var labels = new MapLabelsPresenter(ui.Root, map, cam);
        var names = map.Settlements.Select(s => s.Name).ToArray();
        CollectionAssert.AreEqual(names, labels.Labels.Select(l => l.text).ToArray());
        var container = ui.Q<VisualElement>(MapLabelsPresenter.ContainerName);
        // The game settlements' pills, the 1948 localities' pills and the one tooltip.
        Assert.AreEqual(names.Length + map.Localities.Count + 1, container.childCount);
        CollectionAssert.AreEqual(map.Localities.Select(p => p.Settlement.Name).ToArray(), labels.LocalityLabels.Select(l => l.text).ToArray());
        foreach (var l in labels.LocalityLabels) { Assert.IsTrue(l.ClassListContains(MapLabelsPresenter.LocalityClass), l.text); Assert.AreEqual(PickingMode.Ignore, l.pickingMode, l.text); }
        Assert.AreEqual(PickingMode.Ignore, labels.Tooltip.pickingMode);
        foreach (var slot in labels.Slots) Assert.AreEqual(PickingMode.Ignore, slot.pickingMode);
        foreach (var l in labels.Labels)
        {
            Assert.IsTrue(l.ClassListContains(MapLabelsPresenter.LabelClass), l.text);
            Assert.AreEqual(PickingMode.Ignore, l.pickingMode, l.text + " must not catch map clicks");
        }
        Assert.AreEqual(PickingMode.Ignore, container.pickingMode);
        VisualToggles.Set("labels", false);
        Assert.AreEqual(DisplayStyle.None, container.style.display.value, "the labels toggle hides the layer");
        VisualToggles.Set("labels", true);
        Assert.AreEqual(StyleKeyword.Null, container.style.display.keyword, "on clears the inline display, so the loading rule still wins (review M1)");
    }

    static System.Collections.Generic.List<Statecraft.Sim.MapLocation> Locations() => Statecraft.Sim.ContentLoader.Load(Statecraft.Game.Paths.Content).MapLocations;

    /// <summary>Issues #1008, #1007 and #2113: the ten required GDD v0.2 map locations, the optional outpost and optional Nirim
    /// are named in English and in Hebrew. The one that reuses a game settlement's id (jerusalem) renames that settlement's
    /// pill, so Jerusalem reads "West Jerusalem" with no second pill; each other location has exactly one pill of its own,
    /// which ignores the pointer.</summary>
    [Test]
    public void EveryMapLocationIsNamedOnceInEnglishAndHebrew()
    {
        var locations = Locations();
        var settlementIds = map.Settlements.Select(s => s.Id).ToHashSet();
        var own = locations.Where(l => !settlementIds.Contains(l.Id)).ToList();
        CollectionAssert.AreEquivalent(new[] { "negba", "hulda", "nir_am", "latrun_fort", "iraq_suwaydan_fort",
            "shaar_hagai", "ad_halom_bridge", "shaar_haaliyah", "jerusalem", "east_jerusalem_old_city" },
            locations.Where(l => l.Priority == "must_have").Select(l => l.Id).ToArray(), "the ten required #1008 locations stay intact");
        Assert.AreEqual(18, locations.Count, "the ten required locations, the optional #1007 outpost, optional nirim (#2113) and the six optional #1719 camps");
        CollectionAssert.AreEqual(new[] { "umm_rashrash", "nirim", "military_tzrifin", "military_tel_litvinsky", "military_schneller", "military_camp_80", "reception_atlit", "reception_beit_lid" }, locations.Where(l => l.Priority == "optional").Select(l => l.Id).ToArray(), "the optional rows, in file order");
        var outpost = locations.Single(l => l.Id == "umm_rashrash");
        Assert.AreEqual("outpost", outpost.Kind);
        Assert.IsFalse(outpost.ManagedCity || outpost.DesignatedSite || outpost.SettlementControlTarget, "an optional map record grants no gameplay role");
        Assert.IsFalse(map.Settlements.Any(s => s.Id == outpost.Id), "the outpost has no population-managed settlement");
        Assert.AreEqual(new[] { "jerusalem" }, locations.Where(l => settlementIds.Contains(l.Id)).Select(l => l.Id).ToArray());
        foreach (var hebrew in new[] { false, true })
        {
            using var ui = new UiTestKit();
            using var labels = new MapLabelsPresenter(ui.Root, map, cam, hebrew: hebrew, locations: locations);
            var container = ui.Q<VisualElement>(MapLabelsPresenter.ContainerName);
            CollectionAssert.AreEqual(own.Select(l => hebrew ? l.NameHe : l.Name).ToArray(), labels.LocationLabels.Select(l => l.text).ToArray(), hebrew ? "he" : "en");
            foreach (var l in own)
            {
                Assert.AreEqual(1, container.Query<VisualElement>("slot-" + l.Id).ToList().Count, l.Id + ": one pill");
                Assert.IsFalse(string.IsNullOrWhiteSpace(hebrew ? l.NameHe : l.Name), l.Id);
            }
            foreach (var l in labels.LocationLabels)
            {
                Assert.IsTrue(l.ClassListContains(MapLabelsPresenter.LabelClass) && l.ClassListContains(MapLabelsPresenter.LocationClass), l.text);
                Assert.AreEqual(PickingMode.Ignore, l.pickingMode, l.text + " must not catch map clicks");
            }
            var outpostPill = labels.LocationLabels.Single(l => l.name == "label-umm_rashrash");
            Assert.AreEqual(hebrew ? outpost.NameHe : outpost.Name, outpostPill.text, "the optional outpost has its own translated pill");
            var outpostSlot = container.Q<VisualElement>("slot-umm_rashrash");
            Assert.IsNull(outpostSlot.Q<Label>(className: MapLabelsPresenter.TierClass), "no invented 1948 population tier");
            Assert.IsFalse(outpostPill.ClassListContains(MapLabelsPresenter.WithTierClass));
            Assert.AreEqual(1, container.Query<VisualElement>("slot-jerusalem").ToList().Count, "Jerusalem keeps one pill");
            Assert.AreEqual(hebrew ? "מערב ירושלים" : "West Jerusalem", labels.Labels[map.Settlements.ToList().FindIndex(s => s.Id == "jerusalem")].text);
            Assert.AreEqual(map.Settlements.Count + own.Count + map.Localities.Count + 1, container.childCount, "settlements, locations, localities and the tooltip");
        }
        Assert.AreEqual("village", MapLabelsPresenter.LabelType("fort"));
        Assert.AreEqual("kibbutz", MapLabelsPresenter.LabelType("kibbutz"));
        Assert.AreEqual("city", MapLabelsPresenter.LabelType("city"));
    }

    /// <summary>Issue #1008: two locations in one hex stay two readable pills. Negba and the Iraq Suwaydan police fort share
    /// hex (-8, 28), and West Jerusalem (the jerusalem settlement's pill) and East Jerusalem / Old City share (0, 26). Close up,
    /// in English and in Hebrew, both pills of each pair are shown, and no two shown pills overlap.</summary>
    [UnityTest]
    public IEnumerator LocationsSharingAHexAreBothNamedAndNeverOverlap()
    {
        var locations = Locations();
        var failures = new System.Collections.Generic.List<string>();
        foreach (var hebrew in new[] { false, true })
        {
            var hd = new HdPanel(cam);
            if (hebrew) (hd.Root.Q("root") ?? hd.Root).AddToClassList(UiLanguage.HebrewClass);
            var labels = new MapLabelsPresenter(hd.Root, map, cam, hebrew: hebrew, locations: locations);
            try
            {
                foreach (var (a, b, lon, lat) in new[] { ("negba", "iraq_suwaydan_fort", 34.6825, 31.6545), ("jerusalem", "east_jerusalem_old_city", 35.23, 31.778) })
                {
                    Pose(lon, lat, 20000f);
                    for (int i = 0; i < 20 && labels.LocationLabels.Concat(labels.Labels).Any(l => float.IsNaN(l.resolvedStyle.width) || l.resolvedStyle.width <= 0); i++) yield return null;
                    labels.Refresh(force: true); yield return null;
                    labels.Refresh(force: true); yield return null;
                    var all = labels.Slots.Concat(labels.LocationSlots).Concat(labels.LocalitySlots).ToList();
                    string lang = hebrew ? "he" : "en";
                    foreach (var id in new[] { a, b })
                        if (!Shown(all.Single(s => s.name == "slot-" + id))) failures.Add($"{lang} at {lon},{lat}: {id} is not shown");
                    var shown = all.Where(Shown).Select(x => (id: x.name, rect: x.Q<Label>().worldBound)).ToList();
                    TestContext.WriteLine($"{lang} 20 km over {a}/{b}: {string.Join(" ", shown.Select(x => x.id + "@" + x.rect))}");
                    for (int i = 0; i < shown.Count; i++)
                        for (int j = i + 1; j < shown.Count; j++)
                            if (shown[i].rect.Overlaps(shown[j].rect)) failures.Add($"{lang}: {shown[i].id} overlaps {shown[j].id}");
                }
            }
            finally { labels.Dispose(); hd.Dispose(); }
        }
        Assert.IsEmpty(failures, string.Join("\n", failures));
    }

    /// <summary>#1701 slice F: Tal Heuberger's workshop model (b21) at an arms workshop built on Rehovot's own hex (gdd-0.3) and
    /// the map's names do not cover each other. With the real prefab placed and the camera at 30 km over the model (inside its
    /// close zoom), no shown settlement, locality or location pill overlaps the model's projected bounds.</summary>
    [UnityTest] public IEnumerator NoNamePillCoversAWorkshopModel() { yield return NoPillCovers("rehovot"); }
    /// <summary>The same at a major city's edge (owner, 6 November 2026, verbatim: "make the workshop at the edge of the city",
    /// which replaces "Among the houses" of 2 November 2026 there): Tel Aviv and Jerusalem.</summary>
    [UnityTest] public IEnumerator NoNamePillCoversAWorkshopModelInTelAviv() { yield return NoPillCovers("tel_aviv"); }
    /// <summary>Jerusalem, every pill through the close zoom (15 to 45 km) but one: the "East Jerusalem / Old City"
    /// location's pill is checked up to the close zoom's entry (40 km) only. At its exit (45 km, reached only on the way out)
    /// that pill (263 px wide, about 7.6 km there, set above the Old City's kit) covers the b21: an open item on #2281.
    /// The plan models the place names' bands (SpecialBuildingModels.ClearOfName), not a location pill at that zoom.</summary>
    [UnityTest] public IEnumerator NoNamePillCoversAWorkshopModelInJerusalem() { yield return NoPillCovers("jerusalem"); }

    /// <summary>Review of #2281 on main: every city's workshop model, not only these three, clear of every name pill through the
    /// close zoom (15 to 45 km), so keeping off the map locations' pills moved no overlap elsewhere.</summary>
    [UnityTest]
    public IEnumerator NoNamePillCoversAnyCitysWorkshopModel()
    {
        var cities = Statecraft.Sim.ContentLoader.Load(Statecraft.Game.Paths.Content).Cities.Select(c => c.Id).OrderBy(x => x, System.StringComparer.Ordinal).ToList();
        Assert.Greater(cities.Count, 5);
        foreach (var city in cities) yield return NoPillCovers(city);
    }

    /// <summary>The one pill, and the distances, the owner's ruling of 3 November 2026 accepts over the Jerusalem b21; that pill
    /// is not checked beyond the close zoom's entry (40 km).</summary>
    static readonly string OldCityPill = "slot-east_jerusalem_old_city";
    static readonly float[] OldCityPillAcceptedM = { 25000f, 30000f, 40000f };
    const float OldCityPillFarthestM = 40000f;

    IEnumerator NoPillCovers(string city)
    {
        var saved = Statecraft.Game.Map.Collection.SpecialBuildingModels.Request;
        Statecraft.Game.Map.Collection.SpecialBuildingModels.Request = (id, detail, done) =>
            done(AssetDatabase.LoadAssetAtPath<GameObject>(Statecraft.Game.Map.Collection.CollectionCatalog.PrefabPath(id, detail)));
        var hd = new HdPanel(cam);
        MapLabelsPresenter? labels = null;
        try
        {
            var content = Statecraft.Sim.ContentLoader.Load(Statecraft.Game.Paths.Content);
            foreach (var era in content.Eras) { era.Systems.Ruleset = Statecraft.Sim.SaveGame.Gdd03Ruleset; era.Systems.Loop = Statecraft.Sim.EraSystems.Gdd; }
            var home = content.SettlementHexes.Single(h => h.Id == city);
            var built = new System.DateTime(1949, 3, 1);
            var layer = CollectionGeometryFixture.Special(map, built, content,
                new[] { new Statecraft.Sim.CityProject(9, Statecraft.Sim.Workshops.ArmsWorkshop, city, home.Q, home.R, 0, built) })!;
            var model = layer.transform.Find(Statecraft.Game.Map.Collection.SpecialBuildingModels.WorkshopKey(9));
            Assert.IsNotNull(model, "the workshop model stands at " + city);
            // As GameRoot wires it (#1701 slice F, option 3): the names keep clear of the drawn b21 (SpecialBuildingModels.KeepClear).
            labels = new MapLabelsPresenter(hd.Root, map, cam, keepClear: () => layer.KeepClearFor(cam), locations: Locations());
            var all = labels.Labels.Concat(labels.LocalityLabels).Concat(labels.LocationLabels).ToList();
            var slots = labels.Slots.Concat(labels.LocalitySlots).Concat(labels.LocationSlots).ToList();
            var failures = new System.Collections.Generic.List<string>();
            // Review of #2281 (N1): not one framing only. The camera over the model, and 2.5 km to either side of it (the model
            // off the frame's centre), at 15 km, 25 km, 30 km, at 40 km (the close zoom's entry) and at 45 km (its exit: the model
            // is still drawn there on the way out). Not at the 6 km minimum (CameraController.MinDistance): owner, 3 November 2026,
            // verbatim: "Fine at 6 km (Recommended)": at the minimum zoom a city's own name may not be shown.
            foreach (var distance in new[] { 15000f, 25000f, 30000f, 40000f, 45000f })
                foreach (var offset in new[] { 0f, -2500f, 2500f })
                {
                    rig.LookAt = model!.position + new Vector3(offset, 0f, 0f); rig.Distance = distance; rig.Yaw = 0; rig.TopInset = 0; rig.Apply();
                    layer.Choose(default, cam);   // the render callback's close-zoom switch, as a camera rendering would run it
                    // Beyond the close zoom (the view ray's ground distance, TownModelLayer.ViewDistance) the b21 is not drawn.
                    if (!layer.LastClose) { TestContext.WriteLine($"{distance:0} m, {offset:0} m: the b21 is not drawn here"); continue; }
                    for (int i = 0; i < 20 && all.Any(l => float.IsNaN(l.resolvedStyle.width) || l.resolvedStyle.width <= 0); i++) yield return null;
                    labels.Refresh(force: true); yield return null;
                    labels.Refresh(force: true); yield return null;
                    float x0 = float.MaxValue, y0 = float.MaxValue, x1 = float.MinValue, y1 = float.MinValue;
                    foreach (var r in model.GetComponentsInChildren<Renderer>(true))
                    {
                        var b = r.bounds;
                        for (int c = 0; c < 8; c++)
                        {
                            var corner = new Vector3((c & 1) == 0 ? b.min.x : b.max.x, (c & 2) == 0 ? b.min.y : b.max.y, (c & 4) == 0 ? b.min.z : b.max.z);
                            var q = hd.ToPanel(corner, out bool front); Assert.IsTrue(front, city + "'s workshop model is in front of the camera");
                            x0 = Mathf.Min(x0, q.x); y0 = Mathf.Min(y0, q.y); x1 = Mathf.Max(x1, q.x); y1 = Mathf.Max(y1, q.y);
                        }
                    }
                    var rect = Rect.MinMaxRect(x0, y0, x1, y1);
                    var shown = slots.Where(Shown).ToList();
                    if (shown.Count == 0) failures.Add($"{distance:0} m, {offset:0} m: no name shown over {city}");
                    foreach (var slot in shown)
                    {
                        var pill = slot.Q<Label>().worldBound;
                        TestContext.WriteLine($"{distance:0} m, {offset:0} m: {slot.name} pill {pill}; workshop model {rect}");
                        // Owner, 3 November 2026 (~07:02), verbatim: "Accept it at 30-40 km (Recommended)", and later that day, verbatim:
                        // "Accept at 25 km too (Recommended)": the "East Jerusalem / Old City" city pill may sit over the Jerusalem b21
                        // at 25, 30 and 40 km (as at 45 km: "Accept it (Recommended)", 2 November 2026). Exactly that pill, at exactly
                        // those distances; every other pill and distance is checked.
                        if (city == "jerusalem" && slot.name == OldCityPill && distance > OldCityPillFarthestM)
                        {
                            TestContext.WriteLine($"{distance:0} m, {offset:0} m: {slot.name} not checked beyond {OldCityPillFarthestM:0} m (open item on #2281)");
                            continue;
                        }
                        if (city == "jerusalem" && slot.name == OldCityPill && System.Array.IndexOf(OldCityPillAcceptedM, distance) >= 0)
                        {
                            if (pill.Overlaps(rect)) TestContext.WriteLine($"{distance:0} m, {offset:0} m: {slot.name} over the b21, accepted by the owner's ruling");
                            continue;
                        }
                        if (pill.Overlaps(rect)) failures.Add($"{distance:0} m, {offset:0} m: {slot.name}'s pill {pill} covers the workshop model {rect}");
                    }
                }
            Assert.IsEmpty(failures, city + ": " + string.Join("\n" + city + ": ", failures));
        }
        finally
        {
            labels?.Dispose(); hd.Dispose();
            Statecraft.Game.Map.Collection.SpecialBuildingModels.Request = saved;
        }
    }

    /// <summary>Issue #1008 beside #707: the Latrun police fort's pill and Tal Heuberger's Tegart fort model (SpecialBuildingModels,
    /// streamed close up from 15 May 1948) do not cover each other. With the real prefab placed and the camera at 30 km over
    /// Latrun (inside the model's close zoom), the pill is shown and its rectangle clears the model's projected bounds.</summary>
    [UnityTest]
    public IEnumerator TheLatrunFortsPillClearsTheTegartFortModel()
    {
        var saved = Statecraft.Game.Map.Collection.SpecialBuildingModels.Request;
        Statecraft.Game.Map.Collection.SpecialBuildingModels.Request = (id, detail, done) =>
            done(AssetDatabase.LoadAssetAtPath<GameObject>(Statecraft.Game.Map.Collection.CollectionCatalog.PrefabPath(id, detail)));
        var hd = new HdPanel(cam);
        MapLabelsPresenter? labels = null;
        try
        {
            var layer = CollectionGeometryFixture.Special(map, new System.DateTime(1948, 5, 15))!;
            var fort = layer.transform.Find("latrun_tegart");
            Assert.IsNotNull(fort, "the Tegart fort model stands at Latrun on 15 May 1948");
            labels = new MapLabelsPresenter(hd.Root, map, cam, locations: Locations());
            Pose(34.98, 31.835, 30000f);
            for (int i = 0; i < 20 && labels.LocationLabels.Any(l => float.IsNaN(l.resolvedStyle.width) || l.resolvedStyle.width <= 0); i++) yield return null;
            labels.Refresh(force: true); yield return null;
            labels.Refresh(force: true); yield return null;
            var slot = labels.LocationSlots.Single(s => s.name == "slot-latrun_fort");
            Assert.IsTrue(Shown(slot), "the Latrun police fort is named at 30 km");
            var pill = slot.Q<Label>().worldBound;
            float x0 = float.MaxValue, y0 = float.MaxValue, x1 = float.MinValue, y1 = float.MinValue;
            foreach (var r in fort!.GetComponentsInChildren<Renderer>(true))
            {
                var b = r.bounds;
                for (int c = 0; c < 8; c++)
                {
                    var corner = new Vector3((c & 1) == 0 ? b.min.x : b.max.x, (c & 2) == 0 ? b.min.y : b.max.y, (c & 4) == 0 ? b.min.z : b.max.z);
                    var q = hd.ToPanel(corner, out bool front); Assert.IsTrue(front);
                    x0 = Mathf.Min(x0, q.x); y0 = Mathf.Min(y0, q.y); x1 = Mathf.Max(x1, q.x); y1 = Mathf.Max(y1, q.y);
                }
            }
            var model = Rect.MinMaxRect(x0, y0, x1, y1);
            TestContext.WriteLine($"latrun_fort pill {pill}; Tegart model {model}");
            Assert.IsFalse(pill.Overlaps(model), $"the pill {pill} covers the fort model {model}");
        }
        finally
        {
            labels?.Dispose(); hd.Dispose();
            Statecraft.Game.Map.Collection.SpecialBuildingModels.Request = saved;
        }
    }

    [Test]
    public void LabelsOffScreenAreHiddenAndComeBack()
    {
        using var ui = new UiTestKit();
        using var labels = new MapLabelsPresenter(ui.Root, map, cam);
        var tlv = labels.Slots.Single(s => s.name == "slot-tel_aviv");
        Pose(35.5, 33.2, CameraController.MinDistance);   // the far north, close up
        labels.Refresh(force: true);
        Assert.IsFalse(Shown(tlv), "Tel Aviv is off screen");
        Pose(34.85, 32.0, 90000f);
        labels.Refresh(force: true);
        Assert.IsTrue(Shown(tlv));
    }

    [Test]
    public void TheDenseClusterKeepsItsAnchorsAndMinorPlacesGiveWayAtTheOverview()
    {
        using var ui = new UiTestKit();
        using var labels = new MapLabelsPresenter(ui.Root, map, cam);
        string AnchorOf(string id) => labels.Labels.Single(l => l.name == "label-" + id).GetClasses().Single(c => c.StartsWith("anchor-"));
        Assert.AreEqual("anchor-lower-right", AnchorOf("jaffa")); Assert.AreEqual("anchor-lower-right", AnchorOf("rishon_lezion"));
        Assert.AreEqual("anchor-lower-left", AnchorOf("lod")); Assert.AreEqual("anchor-lower-left", AnchorOf("petah_tikva"));
        Assert.AreEqual("anchor-lower-centre", AnchorOf("tel_aviv"));
        Assert.Less(MapLabelsPresenter.Priority("city"), MapLabelsPresenter.Priority("town"));
        Assert.AreEqual(MapLabelsPresenter.Priority("town"), MapLabelsPresenter.Priority("arab_town"));
        Assert.Less(MapLabelsPresenter.Priority("arab_town"), MapLabelsPresenter.Priority("kibbutz"));
        foreach (var minor in new[] { "village", "kibbutz", "moshav" })
        {
            Assert.IsFalse(MapLabelsPresenter.HiddenByZoom(minor, 90000f), minor + " at 90 km");
            Assert.IsTrue(MapLabelsPresenter.HiddenByZoom(minor, CameraController.MaxDistance), minor + " at the overview");
        }
        Assert.IsFalse(MapLabelsPresenter.HiddenByZoom("town", CameraController.MaxDistance));
        Assert.AreEqual(new Rect(90, 70, 20, 10), MapLabelsPresenter.PillRect(new Vector2(100, 80), new Vector2(20, 10), "anchor-lower-centre"));
        Assert.AreEqual(new Rect(100, 70, 20, 10), MapLabelsPresenter.PillRect(new Vector2(100, 80), new Vector2(20, 10), "anchor-lower-left"));
        Assert.AreEqual(new Rect(80, 70, 20, 10), MapLabelsPresenter.PillRect(new Vector2(100, 80), new Vector2(20, 10), "anchor-lower-right"));
    }

    [Test]
    public void RebuildingKeepsOneLabelPerSettlement()
    {
        using var ui = new UiTestKit();
        var first = new MapLabelsPresenter(ui.Root, map, cam);
        first.Dispose();
        Assert.AreEqual(0, ui.Q<VisualElement>(MapLabelsPresenter.ContainerName).childCount, "dispose clears");
        map.Build();
        using var second = new MapLabelsPresenter(ui.Root, map, cam);
        using var third = new MapLabelsPresenter(ui.Root, map, cam);
        Assert.AreEqual(map.Settlements.Count + map.Localities.Count + 1, ui.Q<VisualElement>(MapLabelsPresenter.ContainerName).childCount);
    }

    /// <summary>Review M2: an older presenter disposed after a newer one was made removes only its own pills.</summary>
    [Test]
    public void DisposingAnOlderPresenterLeavesTheNewerOnesPills()
    {
        using var ui = new UiTestKit();
        var older = new MapLabelsPresenter(ui.Root, map, cam);
        using var newer = new MapLabelsPresenter(ui.Root, map, cam);
        older.Dispose();
        var container = ui.Q<VisualElement>(MapLabelsPresenter.ContainerName);
        Assert.AreEqual(map.Settlements.Count + map.Localities.Count + 1, container.childCount);
        foreach (var slot in newer.Slots.Concat(newer.LocalitySlots)) Assert.AreSame(container, slot.parent, slot.name);
    }

    /// <summary>Behavioural, not text (review N4/N6): with the real theme, a laid-out pill resolves to EB Garamond SemiBold on
    /// the navy fill with the gold edge, and the whole layer is display:none while the root carries "loading" (neither the
    /// slots' inline visibility nor the labels switch turned on can override that, review M1), and back once it is
    /// removed. A 1920x1080 panel (scale 1), as in the game: UiTestKit's panel follows the batch-mode screen (about 0.39
    /// points per pixel there), and UI Toolkit rounds a 1 px border up to one physical pixel, 2.57 points.</summary>
    [UnityTest]
    public IEnumerator ThePillIsEbGaramondOnNavyWithAGoldEdgeAndHiddenWhileLoading()
    {
        var hd = new HdPanel(cam, loading: true);
        var labels = new MapLabelsPresenter(hd.Root, map, cam);
        try
        {
            var root = hd.Root.Q<VisualElement>("root");
            var container = hd.Root.Q<VisualElement>(MapLabelsPresenter.ContainerName);
            Assert.IsTrue(root.ClassListContains("loading"), "Game.uxml starts loading");
            VisualToggles.Set("labels", true);
            for (int i = 0; i < 10; i++) yield return null;
            Assert.AreEqual(DisplayStyle.None, container.resolvedStyle.display, "hidden while the game loads, the switch on or not");
            root.RemoveFromClassList("loading");
            for (int i = 0; i < 10; i++) yield return null;
            Assert.AreEqual(DisplayStyle.Flex, container.resolvedStyle.display, "shown once ready");
            var pill = labels.Labels.Single(l => l.name == "label-tel_aviv");
            var font = pill.resolvedStyle.unityFontDefinition;
            var fontName = font.font != null ? font.font.name : font.fontAsset != null ? font.fontAsset.name : "";
            StringAssert.Contains("EBGaramond-SemiBold", fontName);
            var bg = pill.resolvedStyle.backgroundColor;
            Assert.AreEqual(14f / 255f, bg.r, 0.01f); Assert.AreEqual(22f / 255f, bg.g, 0.01f); Assert.AreEqual(38f / 255f, bg.b, 0.01f);
            Assert.AreEqual(0.82f, bg.a, 0.01f);
            var gold = pill.resolvedStyle.borderTopColor;
            Assert.AreEqual(196f / 255f, gold.r, 0.01f); Assert.AreEqual(160f / 255f, gold.g, 0.01f); Assert.AreEqual(92f / 255f, gold.b, 0.01f);
            Assert.AreEqual(1f, pill.resolvedStyle.borderTopWidth, 0.01f);
            Assert.GreaterOrEqual(pill.resolvedStyle.fontSize, labels.Labels.Single(l => l.name == "label-petah_tikva").resolvedStyle.fontSize + 2f,
                "a city's name is visibly larger than a town's (review M5)");
            Assert.IsNull(GameObject.Find("tel_aviv_label"), "no world-space TextMesh labels remain");
        }
        finally { labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>#1527's follow-up: a go-to route's turn numbers are drawn at a city name's size (they were smaller than a
    /// town's), and the disc holds a two-digit turn.</summary>
    [UnityTest]
    public IEnumerator RouteTurnNumbersReadAtACitysNameSize()
    {
        var hd = new HdPanel(cam);
        var labels = new MapLabelsPresenter(hd.Root, map, cam);
        try
        {
            var hexes = map.Hexes.hexes.Where(h => h.land).Take(12).ToList();
            map.ShowRoute(hexes.Select((h, i) => (h.q, h.r, i + 1)).ToList());
            labels.Refresh(force: true);
            yield return Settle(labels);
            var city = labels.Labels.Single(l => l.name == "label-tel_aviv");
            var turn = hd.Root.Query<Label>(className: MapLabelsPresenter.RouteTurnClass).ToList().Single(l => l.text == "12");
            Assert.GreaterOrEqual(turn.resolvedStyle.fontSize, city.resolvedStyle.fontSize, "a turn number reads like a city's name");
            var two = turn.MeasureTextSize("12", 0, VisualElement.MeasureMode.Undefined, 0, VisualElement.MeasureMode.Undefined);
            Assert.GreaterOrEqual(turn.resolvedStyle.width - turn.resolvedStyle.borderLeftWidth - turn.resolvedStyle.borderRightWidth, two.x,
                "two digits fit the disc");
        }
        finally { map.ShowRoute(System.Array.Empty<(int, int, int)>()); labels.Dispose(); hd.Dispose(); }
    }

    static IEnumerator Settle(MapLabelsPresenter labels)
    {
        for (int i = 0; i < 20 && labels.Labels.Concat(labels.LocalityLabels).Any(l => float.IsNaN(l.resolvedStyle.width) || l.resolvedStyle.width <= 0); i++) yield return null;
        labels.Refresh(force: true); yield return null;   // the first refresh with sizes declutters
        labels.Refresh(force: true); yield return null;
    }

    /// <summary>#2572: the camera inset includes the safe area above the top bar, while a zero inset keeps the top bar's
    /// old share of the window. Built in GameRoot's order (TopBarInset, then SafeAreaFit) and never told to update: the
    /// padding SafeAreaFit puts on the root must reach the camera through the layout's own events.</summary>
    [UnityTest]
    public IEnumerator TheCameraInsetIncludesTheSafeAreaAboveTheTopBar()
    {
        var hd = new HdPanel(cam);
        var safeInsets = (l: 0f, r: 0f, t: 0f, b: 0f);
        var inset = new TopBarInset(hd.Root, rig);
        var safeArea = new SafeAreaFit(hd.Root, () => safeInsets);
        try
        {
            var bar = hd.Root.Q<VisualElement>("top-bar");
            for (int i = 0; i < 20 && (float.IsNaN(bar.worldBound.height) || bar.worldBound.height <= 0); i++) yield return null;
            yield return null; yield return null;
            var panelBounds = hd.Root.panel.visualTree.worldBound;
            var window = panelBounds.height;
            Assert.AreEqual(panelBounds.yMin, bar.worldBound.yMin, 1e-3f, "with no safe area the bar starts at the panel top");
            Assert.AreEqual(bar.worldBound.height / window, rig.TopInset, 1e-3f,
                "with no safe-area inset the bar starts at the panel top, so its bottom edge is its height");

            const float safeTop = 47f;
            safeInsets = (0f, 0f, safeTop, 0f);   // what SafeAreaFit's per-frame poll reads next
            safeArea.Apply(0f, 0f, safeTop, 0f);   // and what it then writes: the root's padding, as on a notched phone
            var expected = 0f;
            for (int i = 0; i < 20; i++)
            {
                EditorApplication.QueuePlayerLoopUpdate();
                yield return null;
                expected = (bar.worldBound.yMax - panelBounds.yMin) / window;
                if (bar.worldBound.yMin - panelBounds.yMin >= safeTop - 1f && Mathf.Abs(rig.TopInset - expected) < 1e-3f) break;
            }
            Assert.AreEqual(safeTop, bar.worldBound.yMin - panelBounds.yMin, 1f, "precondition: the padding moved the bar down");
            Assert.AreEqual((safeTop + bar.worldBound.height) / window, rig.TopInset, 1e-3f,
                "the camera leaves room for the safe area and the top bar, with no call to Update");
        }
        finally { safeArea.Dispose(); inset.Dispose(); hd.Dispose(); }
    }

    /// <summary>Independent of the presenter's own projection call: the Tel Aviv pill sits centred over its kit and just
    /// above it (issue #214): its bottom at least LiftPx and at most 30 px above the top of the kit's drawn buildings (every
    /// vertex projected with Camera.WorldToScreenPoint and the panel's scale; the presenter's columns are a little looser). Also on a 2880x1620 target (panel scale 1.5, Retina-like) with the game's top-bar
    /// inset (review I5).</summary>
    [UnityTest]
    public IEnumerator APillSitsJustAboveItsKit() => PillOnMarker(1920, 1080, 0f);

    [UnityTest]
    public IEnumerator APillSitsJustAboveItsKitAtScaleOneAndAHalfWithTheTopInset() => PillOnMarker(2880, 1620, 0.088f);

    IEnumerator PillOnMarker(int width, int height, float topInset)
    {
        var hd = new HdPanel(cam, width, height);
        rig.TopInset = topInset; rig.ApplyProjection();
        var labels = new MapLabelsPresenter(hd.Root, map, cam);
        try
        {
            yield return Settle(labels);
            var kit = KitRectOf(hd, "tel_aviv");
            var wb = labels.Labels.Single(l => l.name == "label-tel_aviv").worldBound;
            TestContext.WriteLine($"{width}x{height} inset {topInset}: Tel Aviv pill {wb}, kit {kit}, panel {hd.Root.worldBound.size}");
            Assert.AreEqual(1920f, hd.Root.worldBound.width, 1f, $"the panel is 1920 points wide: a scale of {width / 1920f}");
            Assert.AreEqual(kit.center.x, wb.center.x, 0.05f * kit.width + 2f, "centred on the kit");
            Assert.LessOrEqual(wb.yMax, kit.yMin - MapLabelsPresenter.LiftPx + 1f, "clear of the kit, LiftPx above it");
            Assert.GreaterOrEqual(wb.yMax, kit.yMin - 30f, "just above the kit, not floating");
        }
        finally { labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>Owner, 18 October 2026, on #710 ("Accept as shipped"): tiers 1 to 9, doubling from 1,000 people. 999 is
    /// tier 1, 1,000 tier 2, 128,000 and up tier 9.</summary>
    [Test]
    public void PopulationTierBoundariesDoubleFromOneThousandAndCapAtNine()
    {
        Assert.AreEqual(1, MapLabelsPresenter.Tier(999)); Assert.AreEqual(2, MapLabelsPresenter.Tier(1000));
        Assert.AreEqual(2, MapLabelsPresenter.Tier(1999)); Assert.AreEqual(3, MapLabelsPresenter.Tier(2000));
        Assert.AreEqual(8, MapLabelsPresenter.Tier(127999)); Assert.AreEqual(9, MapLabelsPresenter.Tier(128000));
        Assert.AreEqual(9, MapLabelsPresenter.Tier(248459));
    }

    /// <summary>Owner, 18 October 2026, on #710 ("Keep tier 1 from 350"): Rosh Pinna's badge comes from its May 1948 figure
    /// of 350, which is Hebrew Wikipedia only (CBS lists no population), so the data marks it wikipedia-only.</summary>
    [Test]
    public void RoshPinnaKeepsTierOneFromItsWikipediaOnlyFigure()
    {
        var roshPinna = Statecraft.Sim.ContentLoader.Load(Statecraft.Game.Paths.Content).Cities.Single(c => c.Id == "rosh_pinna");
        var people = roshPinna.People ?? throw new AssertionException("Rosh Pinna has no population figure");
        Assert.AreEqual("wikipedia-only", people.Status);
        Assert.AreEqual(350m, people.Value); Assert.AreEqual("1948-05", people.Date);
        Assert.AreEqual(1, MapLabelsPresenter.Tier(people.Value));
    }

    /// <summary>Issue #710 (owner, 15 October 2026): a city's or town's pill starts with its static 1948 population tier, from
    /// cities.yaml's people; a pill with no 1948 figure (an Arab town, a kibbutz, a locality) has no badge. The tiers double
    /// from 1,000 (owner-approved, 18 October 2026), which gives eight distinct tiers across the twelve rows. The badge sits
    /// inside its pill, at the left, before the name; with the pointer over Haifa's pill the tooltip explains the number.</summary>
    [UnityTest]
    public IEnumerator CitiesWearTheirStatic1948PopulationTier()
    {
        // The game's tooltip comes from map.tier (GameRoot); both languages format it with the tier, the count and the people.
        var en = UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
        var he = UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text, "strings.he.yaml");
        Assert.AreEqual(MapLabelsPresenter.DefaultTierTip(8, 98618m), en.Format("map.tier", 8, MapLabelsPresenter.TierCount, "98,618"));
        var heTip = he.Format("map.tier", 8, MapLabelsPresenter.TierCount, "98,618");
        StringAssert.Contains("98,618", heTip); StringAssert.Contains("8", heTip); StringAssert.Contains("9", heTip);
        Assert.IsTrue(UiDirection.RightToLeft(heTip), heTip + " reads right to left");
        var cities = Statecraft.Sim.ContentLoader.Load(Statecraft.Game.Paths.Content).Cities;
        var people = cities.Where(c => c.People != null).ToDictionary(c => c.Id, c => c.People!.Value);
        Assert.AreEqual(12, people.Count, "the twelve city and town rows of cities.yaml");
        Assert.AreEqual(8, people.Values.Select(MapLabelsPresenter.Tier).Distinct().Count(), "eight distinct tiers (#710)");
        var hd = new HdPanel(cam);
        var labels = new MapLabelsPresenter(hd.Root, map, cam, population: people);
        try
        {
            Label? BadgeOf(string id) => labels.Slots.Single(x => x.name == "slot-" + id).Q<Label>(className: MapLabelsPresenter.TierClass);
            string? Badge(string id) => BadgeOf(id)?.text;
            Assert.AreEqual("9", Badge("tel_aviv")); Assert.AreEqual("8", Badge("haifa")); Assert.AreEqual("8", Badge("jerusalem"));
            Assert.AreEqual("6", Badge("petah_tikva")); Assert.AreEqual("4", Badge("tiberias")); Assert.AreEqual("1", Badge("rosh_pinna"));
            foreach (var s in map.Settlements.Where(s => !people.ContainsKey(s.Id))) Assert.IsNull(Badge(s.Id), s.Id + " has no 1948 figure: no badge");
            foreach (var x in labels.LocalitySlots) Assert.IsNull(x.Q<Label>(className: MapLabelsPresenter.TierClass), x.name);
            Assert.AreEqual("Haifa", labels.Labels.Single(l => l.name == "label-haifa").text, "the name itself is unchanged");

            Pose(34.99, 32.80, 40000f);
            yield return Settle(labels);
            var haifa = labels.Labels.Single(l => l.name == "label-haifa");
            Assert.IsTrue(Shown(labels.Slots.Single(x => x.name == "slot-haifa")), "Haifa is named at 40 km");
            var pill = haifa.worldBound; var badge = BadgeOf("haifa")!.worldBound;
            Assert.IsTrue(pill.Contains(badge.min) && pill.Contains(badge.max - Vector2.one * 0.01f), $"the badge {badge} lies inside its pill {pill}");
            Assert.Less(badge.center.x, pill.center.x, "at the start of the name");
            Assert.LessOrEqual(badge.xMax, pill.xMin + haifa.resolvedStyle.paddingLeft, "clear of the name's text");
            var container = hd.Root.Q<VisualElement>(MapLabelsPresenter.ContainerName).worldBound.position;
            labels.HoverAt(pill.center - container); yield return null;
            Assert.AreEqual(Visibility.Visible, labels.Tooltip.style.visibility.value, "the pointer over Haifa's pill shows its tooltip");
            Assert.AreEqual("Population tier 8 of 9: 98,618 people in 1948", labels.Tooltip.text);
        }
        finally { labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>#1063 (player report: cities are hard to pick on the map): a city's name pill is a click target. PillAtLayer
    /// finds the shown game settlement's pill under a point, and none off every pill or where a pill is hidden; Highlight
    /// lights that one pill (HoverClass, a lighter fill) and puts it out again. English and Hebrew alike.</summary>
    [UnityTest]
    public IEnumerator ThePillUnderThePointerIsFoundAndLit()
    {
        foreach (var hebrew in new[] { false, true })
        {
            var hd = new HdPanel(cam);
            if (hebrew) (hd.Root.Q("root") ?? hd.Root).AddToClassList(UiLanguage.HebrewClass);
            var labels = new MapLabelsPresenter(hd.Root, map, cam, hebrew: hebrew);
            string lang = hebrew ? "he" : "en";
            try
            {
                Pose(34.99, 32.80, 40000f);
                yield return Settle(labels);
                var haifa = labels.Labels.Single(l => l.name == "label-haifa");
                Assert.IsTrue(Shown(labels.Slots.Single(x => x.name == "slot-haifa")), lang + ": Haifa is named at 40 km");
                var container = hd.Root.Q<VisualElement>(MapLabelsPresenter.ContainerName).worldBound.position;
                var centre = haifa.worldBound.center - container;
                Assert.AreEqual("haifa", labels.PillAtLayer(centre), lang + ": the pointer over Haifa's pill");
                Assert.IsNull(labels.PillAtLayer(new Vector2(-50f, -50f)), lang + ": off every pill");
                var fill = haifa.resolvedStyle.backgroundColor;
                labels.Highlight("haifa"); yield return null;
                Assert.IsTrue(haifa.ClassListContains(MapLabelsPresenter.HoverClass), lang + ": Haifa's pill is lit");
                Assert.AreEqual(1, labels.Labels.Count(l => l.ClassListContains(MapLabelsPresenter.HoverClass)), lang + ": that pill alone");
                Assert.AreNotEqual(fill, haifa.resolvedStyle.backgroundColor, lang + ": the lit pill has another fill");
                labels.Highlight(null); yield return null;
                Assert.IsFalse(labels.Labels.Any(l => l.ClassListContains(MapLabelsPresenter.HoverClass)), lang + ": put out");
                Assert.AreEqual(fill, haifa.resolvedStyle.backgroundColor, lang + ": its own fill again");

                Pose(34.78, 31.25, 40000f);   // Beersheba: Haifa is off screen
                yield return Settle(labels);
                Assert.IsFalse(Shown(labels.Slots.Single(x => x.name == "slot-haifa")), lang + ": precondition, Haifa's pill is hidden");
                Assert.AreNotEqual("haifa", labels.PillAtLayer(centre), lang + ": a hidden pill is no target");
            }
            finally { labels.Dispose(); hd.Dispose(); }
        }
    }

    /// <summary>Owner decision on #897 (17 October 2026, "Yes, mirror it"): in the Hebrew UI the tier badge sits at the start of
    /// the Hebrew name, which is the pill's right; inside the pill and clear of the name. The English pill keeps it on the left.
    /// Pinned at every window size of InfoPanelLayoutTests and on one pill per anchor (Haifa centre, Safed right, Petah Tikva
    /// left; owner review on #940): the badge's start edge sits 7 px (to within one screen pixel) inside the pill's start edge in both languages.</summary>
    [UnityTest]
    public IEnumerator InHebrewTheTierBadgeSitsOnTheRightOfThePill()
    {
        const float Inset = 7f;   // MapLabelsPresenter.TierInsetPx, the room Statecraft.uss ".map-label-with-tier" leaves
        var people = Statecraft.Sim.ContentLoader.Load(Statecraft.Game.Paths.Content).Cities
            .Where(c => c.People != null).ToDictionary(c => c.Id, c => c.People!.Value);
        var failures = new System.Collections.Generic.List<string>();
        var anchorsAt = new System.Collections.Generic.List<(string window, System.Collections.Generic.HashSet<string> anchors)>();   // one entry per window and language
        int total = 0;
        foreach (var (w, h) in InfoPanelLayoutTests.Windows)
            foreach (var hebrew in new[] { true, false })
            {
                var hd = new HdPanel(cam, w, h);
                if (hebrew) (hd.Root.Q("root") ?? hd.Root).AddToClassList(UiLanguage.HebrewClass);
                var labels = new MapLabelsPresenter(hd.Root, map, cam, population: people, hebrew: hebrew);
                string lang = hebrew ? "he" : "en"; int seen = 0;
                var anchors = new System.Collections.Generic.HashSet<string>();
                anchorsAt.Add(($"{w}x{h} {lang}", anchors));
                try
                {
                    foreach (var (lon, lat) in new[] { (34.99, 32.80), (35.50, 32.96), (34.89, 32.09) })   // Haifa, Safed, Petah Tikva
                    {
                        Pose(lon, lat, 40000f);
                        yield return Settle(labels);
                        float screenPx = hd.Root.worldBound.width / w;   // one screen pixel in panel units
                        foreach (var slot in labels.Slots.Where(Shown))
                        {
                            var b = slot.Q<Label>(className: MapLabelsPresenter.TierClass); if (b == null) continue;
                            var name = slot.Q<Label>("label-" + slot.name.Substring("slot-".Length));
                            Rect pill = name.worldBound, badge = b.worldBound; seen++;
                            anchors.Add(name.GetClasses().Single(c => c.StartsWith("anchor-")));
                            string at = $"{w}x{h} {lang} {slot.name}: pill {pill}, badge {badge}";
                            if (!(pill.Contains(badge.min) && pill.Contains(badge.max - Vector2.one * 0.01f))) failures.Add(at + ": the badge leaves its pill");
                            // worldBound snaps to the screen's pixels, so the inset is 7 px give or take one screen pixel (in panel units).
                            float inset = hebrew ? pill.xMax - badge.xMax : badge.xMin - pill.xMin;
                            if (Mathf.Abs(inset - Inset) > screenPx)
                                failures.Add(at + $": the badge's {(hebrew ? "right" : "left")} edge is {inset:0.##} px inside the pill's, not {Inset} (+-{screenPx:0.##})");
                            if (hebrew ? badge.xMin < pill.xMax - name.resolvedStyle.paddingRight : badge.xMax > pill.xMin + name.resolvedStyle.paddingLeft)
                                failures.Add(at + ": the badge overlaps the name's text");
                        }
                    }
                    total += seen;
                    if (seen == 0) failures.Add($"{w}x{h} {lang}: no tier badge shown at all");
                }
                finally { labels.Dispose(); hd.Dispose(); }
            }
        TestContext.WriteLine($"{total} badges checked; anchors per window: {string.Join("; ", anchorsAt.Select(a => a.window + " = " + string.Join("/", a.anchors.OrderBy(x => x))))}");
        Assert.IsEmpty(failures, string.Join("\n", failures));
        // Each window and language must show a centre, a right and a left anchored pill (Haifa, Safed, Petah Tikva); a set pooled
        // across windows would pass with one anchor missing at some window. No window is exempt: at today's window sizes declutter hides none of the three.
        foreach (var (window, seenAnchors) in anchorsAt)
            Assert.AreEqual(3, seenAnchors.Count, $"{window}: a centre, a right and a left anchored pill, saw {string.Join(", ", seenAnchors.OrderBy(x => x))}");
    }

    /// <summary>Owner rulings 2026-10-11 and 2026-10-12: the 1948 localities are named by their 1948 names only at close zoom,
    /// with today's name in a tooltip only where a living place carries on. At 30 km over Beisan its pill reads "Beisan"
    /// and, with the pointer over it (the hit test Hover runs, in the layer's coordinates), the tooltip "Today: Beit She'an"
    /// sits under it; off every pill it hides; no two shown pills overlap; at the gameplay zoom (60 km) no locality pill is
    /// shown. A place that did not carry on (Isdud), or whose name is today's (Nablus), has no tooltip; Nesher's says it was
    /// a mixed locality.</summary>
    [UnityTest]
    public IEnumerator LocalitiesAreNamedOnlyCloseUpWithTodaysNameOnHover()
    {
        var hd = new HdPanel(cam);
        var labels = new MapLabelsPresenter(hd.Root, map, cam);
        try
        {
            Assert.Greater(map.Localities.Count, 250);
            Pose(35.50, 32.49, 30000f);
            yield return Settle(labels);
            var beisan = labels.LocalitySlots.Single(x => x.name == "slot-beit_shean");
            Assert.AreEqual("Beisan", beisan.Q<Label>().text);
            Assert.IsTrue(Shown(beisan), "Beisan is named at 30 km");
            var shown = labels.Slots.Concat(labels.LocalitySlots).Where(Shown).Select(x => (id: x.name, rect: x.Q<Label>().worldBound)).ToList();
            TestContext.WriteLine($"30 km over Beisan: {shown.Count} pills shown: {string.Join(" ", shown.Select(x => x.id))}");
            for (int i = 0; i < shown.Count; i++)
                for (int j = i + 1; j < shown.Count; j++)
                    Assert.IsFalse(shown[i].rect.Overlaps(shown[j].rect), $"{shown[i].id} overlaps {shown[j].id}");
            var container = hd.Root.Q<VisualElement>(MapLabelsPresenter.ContainerName).worldBound.position;
            labels.HoverAt(beisan.Q<Label>().worldBound.center - container); yield return null;
            Assert.AreEqual(Visibility.Visible, labels.Tooltip.style.visibility.value, "the pointer over Beisan's pill shows its tooltip");
            Assert.AreEqual("Today: Beit She'an", labels.Tooltip.text);
            var pill = beisan.Q<Label>().worldBound; var tip = labels.Tooltip.worldBound;
            Assert.AreEqual(pill.center.x, tip.center.x, 2f, "the tooltip is centred under its pill");
            Assert.Greater(tip.yMin, pill.yMax - 1f, "and below it");
            labels.HoverAt(new Vector2(-50f, -50f));
            Assert.AreEqual(Visibility.Hidden, labels.Tooltip.style.visibility.value, "off every pill, no tooltip");
            var by = map.Localities.ToDictionary(p => p.Settlement.Id);
            Assert.IsNull(MapLabelsPresenter.DefaultTip(by["isdud"]), "no today name for a place that did not carry on");
            Assert.IsNull(MapLabelsPresenter.DefaultTip(by["nablus"]), "Nablus is Nablus: nothing to say");
            Assert.AreEqual("Mixed locality", MapLabelsPresenter.DefaultTip(by["nesher"]));
            labels.HoverLocality("isdud");
            Assert.AreEqual(Visibility.Hidden, labels.Tooltip.style.visibility.value, "Isdud's pill never shows a tooltip");

            Pose(PromoPose.Gameplay03.Lon, PromoPose.Gameplay03.Lat, PromoPose.Gameplay03.Distance);
            yield return Settle(labels);
            Assert.IsFalse(labels.LocalitySlots.Any(Shown), "no locality is named at the gameplay zoom");
        }
        finally { labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>Issue #245: on a touchscreen a tap on a locality pill toggles its tooltip (a second tap hides it), and a tap
    /// elsewhere, or on a pill with nothing to say, hides it. The touch's own Hover(null) each frame leaves a tapped
    /// tooltip up. A mouse hover still shows and hides it as before, and a mouse in use takes a tapped tooltip away.</summary>
    [UnityTest]
    public IEnumerator ATapTogglesTheTooltipAndATapElsewhereHidesIt()
    {
        var hd = new HdPanel(cam);
        var labels = new MapLabelsPresenter(hd.Root, map, cam);
        try
        {
            Pose(35.50, 32.49, 30000f);
            yield return Settle(labels);
            var container = hd.Root.Q<VisualElement>(MapLabelsPresenter.ContainerName).worldBound.position;
            Vector2 Centre(string id) => labels.LocalitySlots.Single(x => x.name == "slot-" + id).Q<Label>().worldBound.center - container;
            bool Up() => labels.Tooltip.style.visibility.value == Visibility.Visible;
            Assert.IsTrue(Shown(labels.LocalitySlots.Single(x => x.name == "slot-beit_shean")));

            labels.TapAt(Centre("beit_shean"));
            Assert.IsTrue(Up(), "a tap on Beisan's pill shows its tooltip");
            Assert.AreEqual("Today: Beit She'an", labels.Tooltip.text);
            labels.Hover(null);   // the frames after the tap: a touchscreen has no hover position
            Assert.IsTrue(Up(), "and it stays up across frames");
            labels.TapAt(Centre("beit_shean"));
            Assert.IsFalse(Up(), "a second tap on the pill hides it");
            labels.TapAt(Centre("beit_shean"));
            labels.TapAt(new Vector2(-50f, -50f));
            Assert.IsFalse(Up(), "a tap elsewhere hides it");

            labels.HoverAt(Centre("beit_shean"));
            Assert.IsTrue(Up(), "a mouse hover still shows it");
            Assert.AreEqual("Today: Beit She'an", labels.Tooltip.text);
            labels.HoverAt(new Vector2(-50f, -50f));
            Assert.IsFalse(Up(), "and off the pill hides it");

            labels.TapAt(Centre("beit_shean"));
            Assert.IsTrue(Up());
            labels.Hover(new Vector2(-500f, -500f));   // a mouse position well off every pill
            Assert.IsFalse(Up(), "a mouse in use takes a tapped tooltip away");

            labels.TapAt(Centre("beit_shean"));
            Pose(PromoPose.Gameplay03.Lon, PromoPose.Gameplay03.Lat, PromoPose.Gameplay03.Distance);
            yield return Settle(labels);
            labels.Hover(null);
            Assert.IsFalse(Up(), "zooming out hides the pill and the tooltip with it");
        }
        finally { labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>Issue #245: the device type decides. A touchscreen has no hover position (the Input System keeps its last
    /// touch after the finger lifts); a mouse and a pen do.</summary>
    [Test]
    public void OnlyANonTouchPointerHovers()
    {
        Assert.IsNull(MapLabelsPresenter.HoverPosition(null));
        var touch = UnityEngine.InputSystem.InputSystem.AddDevice<UnityEngine.InputSystem.Touchscreen>();
        var mouse = UnityEngine.InputSystem.InputSystem.AddDevice<UnityEngine.InputSystem.Mouse>();
        var pen = UnityEngine.InputSystem.InputSystem.AddDevice<UnityEngine.InputSystem.Pen>();
        try
        {
            Assert.IsNull(MapLabelsPresenter.HoverPosition(touch), "a touchscreen does not hover");
            Assert.IsNotNull(MapLabelsPresenter.HoverPosition(mouse), "a mouse hovers");
            Assert.IsNotNull(MapLabelsPresenter.HoverPosition(pen), "a pen hovers");
        }
        finally
        {
            UnityEngine.InputSystem.InputSystem.RemoveDevice(touch); UnityEngine.InputSystem.InputSystem.RemoveDevice(mouse); UnityEngine.InputSystem.InputSystem.RemoveDevice(pen);
        }
    }

    static float Gap(Rect r, Vector2 p) => new Vector2(Mathf.Max(0, Mathf.Max(r.xMin - p.x, p.x - r.xMax)), Mathf.Max(0, Mathf.Max(r.yMin - p.y, p.y - r.yMax))).magnitude;
    static float RectGap(Rect a, Rect b) => new Vector2(Mathf.Max(0, Mathf.Max(a.xMin - b.xMax, b.xMin - a.xMax)), Mathf.Max(0, Mathf.Max(a.yMin - b.yMax, b.yMin - a.yMax))).magnitude;

    /// <summary>Issue #214 (integration B16): at the gameplay03 promo pose (with the game's top-bar inset), and close over
    /// Degania Alef (10 km) and Zikhron Ya'akov (25 km), no shown pill covers more than MaxKitCover of its own kit's screen
    /// rectangle or of any other visible kit's, and no two shown pills overlap; both small places are labelled close up.</summary>
    [UnityTest]
    public IEnumerator NoPillHidesAKit()
    {
        var hd = new HdPanel(cam);
        var labels = new MapLabelsPresenter(hd.Root, map, cam);
        var inset = new TopBarInset(hd.Root, rig);
        try
        {
            var degania = map.Settlements.Single(s => s.Id == "degania_alef");
            var zikhron = map.Settlements.Single(s => s.Id == "zikhron_yaakov");
            foreach (var (name, lon, lat, distance, yaw, must) in new[]
            {
                ("gameplay03", PromoPose.Gameplay03.Lon, PromoPose.Gameplay03.Lat, PromoPose.Gameplay03.Distance, PromoPose.Gameplay03.Yaw, ""),
                ("degania 10 km", degania.Lon, degania.Lat, 10000f, 0f, "degania_alef"),
                ("zikhron 25 km", zikhron.Lon, zikhron.Lat, 25000f, 0f, "zikhron_yaakov"),
            })
            {
                rig.LookAt = map.Frame.ToWorld(lon, lat, 0); rig.Distance = distance; rig.Yaw = yaw; rig.Apply();
                yield return null;
                inset.Update();
                yield return Settle(labels);
                var tops = VisibleMarkerTops(hd, map);
                var shown = labels.Slots.Where(Shown).Select(s => (id: s.name.Substring("slot-".Length), rect: s.Q<Label>().worldBound)).ToList();
                TestContext.WriteLine($"{name}: {shown.Count} shown: {string.Join(" ", shown.Select(x => $"{x.id}{x.rect} kit {KitRectOf(hd, x.id)}"))}");
                Assert.Greater(shown.Count, 0, $"{name}: pills are shown");
                if (must != "") Assert.IsTrue(shown.Any(x => x.id == must), $"{name}: {must} is labelled");
                foreach (var (id, rect) in shown)
                {
                    float own = Cover(rect, KitRectOf(hd, id));
                    Assert.LessOrEqual(own, MapLabelsPresenter.MaxKitCover + 0.01f, $"{name}: {id}'s pill {rect} covers {own:P0} of its kit {KitRectOf(hd, id)}");
                    foreach (var other in tops.Keys.Where(o => o != id))
                    {
                        float c = Cover(rect, KitRectOf(hd, other));
                        Assert.LessOrEqual(c, MapLabelsPresenter.MaxKitCover + 0.01f, $"{name}: {id}'s pill {rect} covers {c:P0} of {other}'s kit");
                    }
                }
                for (int i = 0; i < shown.Count; i++)
                    for (int j = i + 1; j < shown.Count; j++)
                        Assert.IsFalse(shown[i].rect.Overlaps(shown[j].rect), $"{name}: {shown[i].id} {shown[i].rect} overlaps {shown[j].id} {shown[j].rect}");
            }
        }
        finally { inset.Dispose(); labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>Issue #197 (audit 2026-10-13, webunits-gameplay03): in normal play at the gameplay03 pose (its yaw, with
    /// the game's top-bar inset) the Tel Aviv pill keeps clear of the Kiryati Brigade standing in Tel Aviv: it overlaps
    /// neither the brigade's badge nor its figures, and it still hangs above the town (over its kit's width, not beside
    /// it); no shown pill overlaps any token's badge. The rectangles are measured
    /// independently of the presenter: the badge plate's corners as it faces the camera, the figures' renderer bounds,
    /// both through the camera's pixels.</summary>
    [UnityTest]
    public IEnumerator PillsKeepClearOfTheUnitTokens()
    {
        var layer = StartUnits();
        HdPanel hd = new HdPanel(cam);   // typed, not var: the local functions below capture it
        var labels = new MapLabelsPresenter(hd.Root, map, cam, keepClear: () => layer.KeepClear);
        var inset = new TopBarInset(hd.Root, rig);
        try
        {
            var pose = PromoPose.Gameplay03;
            rig.LookAt = map.Frame.ToWorld(pose.Lon, pose.Lat, 0); rig.Distance = pose.Distance; rig.Yaw = pose.Yaw; rig.Apply();
            yield return null;
            inset.Update();
            yield return Settle(labels);
            var tokens = GameObject.Find(Statecraft.Game.Map.Units.UnitLayer.RootName).transform.Find("Tokens");
            Rect Hull(System.Collections.Generic.IEnumerable<Vector3> points)
            {
                float x0 = float.MaxValue, y0 = float.MaxValue, x1 = float.MinValue, y1 = float.MinValue;
                foreach (var w in points)
                {
                    var p = hd.ToPanel(w, out bool inFront); Assert.IsTrue(inFront);
                    x0 = Mathf.Min(x0, p.x); y0 = Mathf.Min(y0, p.y); x1 = Mathf.Max(x1, p.x); y1 = Mathf.Max(y1, p.y);
                }
                return Rect.MinMaxRect(x0, y0, x1, y1);
            }
            Rect BadgeRect(Transform token)
            {
                var badge = token.Find("Badge"); var turn = cam.transform.rotation;   // the plate faces the camera as it renders
                float half = Statecraft.Game.Map.Units.UnitBadge.SizeM / 2f;
                return Hull(new[] { new Vector3(-half, -half, 0), new Vector3(half, -half, 0), new Vector3(-half, half, 0), new Vector3(half, half, 0) }
                    .Select(c => badge.position + turn * c));
            }
            Rect FiguresRect(Transform token) => Hull(token.GetComponentsInChildren<Renderer>().Where(r => r.name.StartsWith("Rifleman"))
                .SelectMany(r => { var b = r.bounds; return Enumerable.Range(0, 8).Select(c => new Vector3((c & 1) == 0 ? b.min.x : b.max.x, (c & 2) == 0 ? b.min.y : b.max.y, (c & 4) == 0 ? b.min.z : b.max.z)); }));

            var kiryati = layer.Tokens.Single(t => t.Token.Unit.Id == "kiryati");
            Assert.AreEqual("Tel Aviv", kiryati.Token.Anchor.Place, "the brigade stands in Tel Aviv on the first turn");
            var token = tokens.Find("kiryati");
            Rect badgeRect = BadgeRect(token), figuresRect = FiguresRect(token);
            var tlv = labels.Slots.Single(s => s.name == "slot-tel_aviv");
            Assert.IsTrue(Shown(tlv), "Tel Aviv is named at gameplay03");
            var pill = tlv.Q<Label>().worldBound;
            TestContext.WriteLine($"gameplay03: Tel Aviv pill {pill}, Kiryati badge {badgeRect}, figures {figuresRect}");
            Assert.IsFalse(pill.Overlaps(badgeRect), $"the Tel Aviv pill {pill} overlaps the Kiryati badge {badgeRect}");
            Assert.IsFalse(pill.Overlaps(figuresRect), $"the Tel Aviv pill {pill} overlaps the Kiryati figures {figuresRect}");
            var kit = KitRectOf(hd, "tel_aviv");
            Assert.LessOrEqual(pill.yMax, kit.yMin + 1f, $"the pill {pill} still hangs above Tel Aviv's kit {kit}");
            Assert.IsTrue(pill.center.x >= kit.xMin && pill.center.x <= kit.xMax, $"over the town, not beside it: pill {pill}, kit {kit}");
            var badges = layer.Tokens.Select(t => (id: t.Token.Unit.Id, rect: BadgeRect(tokens.Find(t.Token.Unit.Id)))).ToList();
            foreach (var slot in labels.Slots.Concat(labels.LocalitySlots).Where(Shown))
                foreach (var (id, rect) in badges)
                    Assert.IsFalse(slot.Q<Label>().worldBound.Overlaps(rect), $"{slot.name} {slot.Q<Label>().worldBound} overlaps {id}'s badge {rect}");

            // The units off: with no camera move, the plain refresh re-places Tel Aviv's pill at its home above the kit.
            VisualToggles.Set(Statecraft.Game.Map.Units.UnitLayer.ToggleName, false);
            Assert.AreEqual(0, layer.KeepClear.Count, "a hidden layer asks no pill to keep clear");
            labels.Refresh(); yield return null;
            var home = tlv.Q<Label>().worldBound;
            TestContext.WriteLine($"units off: Tel Aviv pill {home}, kit {kit}");
            // #1183: 4.4 km hexes, values scale with HexM: the denser grid leaves Tel Aviv's pill clear of Kiryati without a lift (0 px measured), so it only
            // must not stand higher than it did with the units on.
            Assert.GreaterOrEqual(home.yMax, pill.yMax, $"the pill {home} came back down from {pill}");
            Assert.That(kit.yMin - home.yMax, Is.InRange(MapLabelsPresenter.LiftPx - 1f, 30f), $"back just above its kit: pill {home}, kit {kit}");
            // And on again: it goes back above the brigade.
            VisualToggles.Set(Statecraft.Game.Map.Units.UnitLayer.ToggleName, true);
            labels.Refresh(); yield return null;
            Assert.AreEqual(pill.yMax, tlv.Q<Label>().worldBound.yMax, 0.5f, "the units on again: above the brigade again");
        }
        finally { inset.Dispose(); labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>Review of #2176, item 1: a moved unit's token slides to its new spot (#1866), and with no camera move the
    /// names keep clear of the token where it is drawn, during the slide and after it. At gameplay03 the Tel Aviv pill
    /// stands clear of the Kiryati Brigade (PillsKeepClearOfTheUnitTokens). The brigade's token then starts a slide from
    /// the far part of Tel Aviv's kit, right under the pill, and the labels' pass at the rebuild sees it there, so the pill
    /// goes up past it. Near the slide's end, and once it has arrived, a plain refresh (GameRoot's every LateUpdate, the
    /// boxes faced to the camera first) puts the pill clear of the brigade in Tel Aviv again. Before the fix the slide moved
    /// the boxes inside the same list, the labels re-place only for a new list, and the pill stayed where the token had been
    /// drawn at the start.</summary>
    [UnityTest]
    public IEnumerator PillsKeepClearOfASlidingTokenWithoutACameraMove()
    {
        var layer = StartUnits(animateMoves: true);
        HdPanel hd = new HdPanel(cam);
        var labels = new MapLabelsPresenter(hd.Root, map, cam, keepClear: () => { layer.FaceCamera(cam); return layer.KeepClear; });   // as GameRoot
        var inset = new TopBarInset(hd.Root, rig);
        try
        {
            var pose = PromoPose.Gameplay03;
            rig.LookAt = map.Frame.ToWorld(pose.Lon, pose.Lat, 0); rig.Distance = pose.Distance; rig.Yaw = pose.Yaw; rig.Apply();
            yield return null;
            inset.Update();
            // An Arab force's token is drawn only once its figure has loaded or failed (UnitLayer.Show), and each such
            // arrival (UnitFigures.AvailabilityVersion) makes the next FaceCamera redraw every token (Rebuild), which can
            // move the names and replaces the brigade's token. Only figures near the camera load, so wait until no
            // arrival has come for 3 s (at most 60 s) before the names are measured.
            var clock = System.Diagnostics.Stopwatch.StartNew();
            int version = Statecraft.Game.Map.Units.UnitFigures.AvailabilityVersion; double quietSince = 0;
            while (clock.Elapsed.TotalSeconds - quietSince < 3 && clock.Elapsed.TotalSeconds < 60)
            {
                yield return null;
                layer.FaceCamera(cam);   // as a render would: an arrival redraws the tokens now
                if (Statecraft.Game.Map.Units.UnitFigures.AvailabilityVersion != version)
                { version = Statecraft.Game.Map.Units.UnitFigures.AvailabilityVersion; quietSince = clock.Elapsed.TotalSeconds; }
            }
            TestContext.WriteLine($"figures quiet after {quietSince:F1} s (availability version {version})");
            layer.FaceCamera(cam);   // the redraw for them, before the names are placed
            yield return Settle(labels);
            var tlv = labels.Slots.Single(s => s.name == "slot-tel_aviv");
            Assert.IsTrue(Shown(tlv), "Tel Aviv is named at gameplay03");
            var clear = tlv.Q<Label>().worldBound;   // clear of the brigade standing in Tel Aviv
            // Found again after every frame: a redraw replaces the token, and its new motion goes on with the slide.
            Statecraft.Game.Map.Units.UnitTokenMotion Motion() =>
                GameObject.Find(Statecraft.Game.Map.Units.UnitLayer.RootName).transform.Find("Tokens").Find("kiryati")
                    .GetComponent<Statecraft.Game.Map.Units.UnitTokenMotion>();
            Assert.IsNotNull(Motion(), "a play build moves the brigade's token");

            // The slide's start (#1183): on 4.4 km hexes the brigade in Tel Aviv stands low in the kit at gameplay03, so the pill
            // needs no lift (PillsKeepClearOfTheUnitTokens) and a token drawn far away would move nothing. So the token starts
            // where it overlaps the kit and reaches above it, as the brigade in Tel Aviv did on 5 km hexes: its boxes (the ones
            // the names keep clear of, UnitLayer.KeepClear) moved level on the ground until their foot stands, as the camera
            // sees it, under the pill's centre and half their own screen height below the kit's top edge.
            int index = layer.Tokens.Select((t, n) => (t, n)).Single(x => x.t.Token.Unit.Id == "kiryati").n;
            var boxes = layer.KeepClear[index];
            var world = boxes[0]; foreach (var b in boxes) world.Encapsulate(b);
            float x0 = float.MaxValue, y0 = float.MaxValue, x1 = float.MinValue, y1 = float.MinValue;
            for (int c = 0; c < 8; c++)
            {
                var p = hd.ToPanel(new Vector3((c & 1) == 0 ? world.min.x : world.max.x, (c & 2) == 0 ? world.min.y : world.max.y,
                    (c & 4) == 0 ? world.min.z : world.max.z), out _);
                x0 = Mathf.Min(x0, p.x); y0 = Mathf.Min(y0, p.y); x1 = Mathf.Max(x1, p.x); y1 = Mathf.Max(y1, p.y);
            }
            var drawn = Rect.MinMaxRect(x0, y0, x1, y1);
            var kit = KitRectOf(hd, "tel_aviv");
            var foot = new Vector3(world.center.x, world.min.y, world.center.z);
            float scale = hd.Root.worldBound.width / hd.Width;
            var ray = cam.ScreenPointToRay(new Vector3(clear.center.x / scale, hd.Height - (kit.yMin + drawn.height / 2f) / scale, 0f));
            Assert.IsTrue(new Plane(Vector3.up, foot).Raycast(ray, out float enter), "the spot under the pill is on the ground ahead");
            var start = ray.GetPoint(enter) - foot;
            TestContext.WriteLine($"the brigade drawn {drawn} in Tel Aviv's kit {kit}; the slide starts {start.magnitude:F0} m away");
            Motion().Begin(start);
            labels.Refresh(force: true); yield return null;   // the labels' pass at the rebuild sees the slide's start
            // and the frames after it, while the token has barely moved: a placement that shows or hides a pill changes the
            // pills' sizes, which re-places them once more (MapLabelsPresenter.Refresh), so let that settle at the start.
            for (int i = 0; i < 3; i++) { labels.Refresh(); yield return null; }
            var away = tlv.Q<Label>().worldBound;
            TestContext.WriteLine($"slide start: Tel Aviv pill {away}, clear of the brigade {clear}");
            Assert.Less(away.yMax, clear.yMax - 1f, $"with the brigade drawn under it the pill {away} goes up from {clear}");

            var motion = Motion();
            motion.Tick(Statecraft.Game.Map.Units.UnitTokenMotion.Duration * 0.9999f);   // a ten-thousandth of the slide short of Tel Aviv
            Assert.IsTrue(motion.Moving, "still sliding");
            labels.Refresh(); yield return null;
            var during = tlv.Q<Label>().worldBound;
            TestContext.WriteLine($"near the end: Tel Aviv pill {during}");
            Assert.AreEqual(clear.yMax, during.yMax, 1f, $"mid-slide the pill {during} keeps clear of the token as drawn, not of its start {away}");

            motion = Motion();
            motion.Tick(Statecraft.Game.Map.Units.UnitTokenMotion.Duration);
            Assert.IsFalse(motion.Moving, "arrived");
            labels.Refresh(); yield return null;
            Assert.AreEqual(clear.yMax, tlv.Q<Label>().worldBound.yMax, 0.5f, "arrived, the pill keeps clear of the brigade in Tel Aviv");
        }
        finally { inset.Dispose(); labels.Dispose(); hd.Dispose(); }
    }

    static readonly string[] Occluders = { "top-bar", "info-panel", "minimap" };

    /// <summary>The units in play as a new game starts (golden seed, historical mode), as the game draws them; with
    /// <paramref name="animateMoves"/> as in play, where a moved unit's token slides (#1866).</summary>
    Statecraft.Game.Map.Units.UnitLayer StartUnits(bool animateMoves = false)
    {
        var content = Statecraft.Sim.ContentLoader.Load(Statecraft.Game.Paths.Content);
        var units = Statecraft.Game.Map.Units.UnitData.Parse(File.ReadAllText(Path.Combine(Statecraft.Game.Paths.Content, "map", Statecraft.Game.Map.Units.UnitData.DefaultFileName)));
        var layer = Statecraft.Game.Map.Units.UnitLayer.Create(map, units, content.Hexes, still: true);
        layer.AnimateMoves = animateMoves;
        layer.Show(content, Statecraft.Sim.Simulation.NewGame(content, Statecraft.Sim.GoldenRun.Seed, Statecraft.Sim.Mode.Historical));
        return layer;
    }

    /// <summary>The presenter, keeping clear of the units in play as the game does (GameRoot), or without them.</summary>
    MapLabelsPresenter Labels(HdPanel hd, bool units)
    {
        if (!units) return new MapLabelsPresenter(hd.Root, map, cam);
        var layer = StartUnits();
        return new MapLabelsPresenter(hd.Root, map, cam, keepClear: () => layer.KeepClear);
    }

    /// <summary>Marker tops on screen and not under a panel, in panel coordinates (independent of the presenter).</summary>
    static System.Collections.Generic.Dictionary<string, Vector2> VisibleMarkerTops(HdPanel hd, MapScene map)
    {
        var panels = Occluders.Select(n => hd.Root.Q<VisualElement>(n).worldBound).ToList();
        var size = hd.Root.worldBound.size;
        var tops = new System.Collections.Generic.Dictionary<string, Vector2>();
        foreach (var s in map.Settlements)
        {
            var p = hd.ToPanel(MarkerTopOf(s.Id), out bool inFront);
            if (inFront && p.x >= 0 && p.x <= size.x && p.y >= 0 && p.y <= size.y && !panels.Any(r => r.Contains(p))) tops[s.Id] = p;
        }
        return tops;
    }

    /// <summary>M2's cluster test, on layout bounds (review I5), widened by reviews I2/I4 and made robust to terrain changes
    /// (re-review, task 3). At 90 km (the flythrough's frame 120) and at the overview: no two shown pills overlap; every
    /// shown pill's marker is visible and the pill is more than twice as far (plus 4 px) from every other visible marker's
    /// top as from its own, so none reads as a neighbour's; completeness: every visible marker of a place not decluttered
    /// by zoom with no other visible marker within 2 pill heights + MarginPx is shown; only unambiguous names are pinned
    /// (well apart from any other marker), with a lower bound on the count; and at the overview a coastal town between
    /// Haifa and Tel Aviv is labelled. The full shown set is logged, for a new baseline.</summary>
    [UnityTest]
    public IEnumerator ShownPillsNeverOverlapAndEachReadsAsItsOwn() => NeverOverlapAndOwn(false);

    /// <summary>The same with the units in play on the map (review of #518): the tokens move pills, and a city with tokens
    /// on it (Tel Aviv, Jerusalem) keeps its name; each pill still reads as its own town's, measured from the kit.</summary>
    [UnityTest]
    public IEnumerator ShownPillsNeverOverlapAndEachReadsAsItsOwnWithTheUnits() => NeverOverlapAndOwn(true);

    IEnumerator NeverOverlapAndOwn(bool units)
    {
        var hd = new HdPanel(cam);
        var labels = Labels(hd, units);
        try
        {
            foreach (var (name, lon, lat, distance, pinned, atLeast) in new[]
            {
                ("90 km", 34.95, 31.3 + (32.9 - 31.3) * 120 / 239.0, 90000f, new[] { "tel_aviv", "petah_tikva" }, 8),
                ("overview", PromoPose.Diorama02.Lon, PromoPose.Diorama02.Lat, CameraController.MaxDistance, new[] { "tel_aviv", "jerusalem", "gaza", "beersheba" }, 7),
            })
            {
                Pose(lon, lat, distance);
                yield return Settle(labels);
                var tops = VisibleMarkerTops(hd, map);
                var shown = labels.Slots.Where(Shown).Select(s => (id: s.name.Substring("slot-".Length), rect: s.Q<Label>().worldBound)).ToList();
                TestContext.WriteLine($"{name}: {shown.Count} of {labels.Slots.Count} pills shown: {string.Join(" ", shown.Select(s => s.id))}");
                TestContext.WriteLine($"{name}: visible markers {string.Join(" ", tops.Select(t => $"{t.Key}@{t.Value.x:F0},{t.Value.y:F0}"))}");
                foreach (var id in pinned) Assert.IsTrue(shown.Any(s => s.id == id), $"{name}: {id} is shown");
                Assert.GreaterOrEqual(shown.Count, atLeast, $"{name}: shown pills");
                if (name == "overview") Assert.IsTrue(shown.Any(s => s.id == "hadera" || s.id == "netanya"), "overview: a coastal town between Haifa and Tel Aviv is labelled");
                for (int i = 0; i < shown.Count; i++)
                    for (int j = i + 1; j < shown.Count; j++)
                        Assert.IsFalse(shown[i].rect.Overlaps(shown[j].rect), $"{name}: {shown[i].id} {shown[i].rect} overlaps {shown[j].id} {shown[j].rect}");
                foreach (var (id, rect) in shown)
                {
                    Assert.IsTrue(tops.ContainsKey(id), $"{name}: {id} is shown but its marker is not visible");
                    // The pill's gap to its own kit (issue #214), as the presenter measures it: at most LiftPx, since its
                    // kit columns may reach a few px past the drawn vertices this test projects.
                    float own = Mathf.Min(RectGap(rect, KitRectOf(hd, id)), MapLabelsPresenter.LiftPx);
                    foreach (var other in tops.Where(o => o.Key != id))
                        Assert.Greater(Gap(rect, other.Value), 2f * own + 4f, $"{name}: {id} pill is {own:F0} px from its kit but closer to {other.Key}'s marker");
                }
                foreach (var s in map.Settlements.Where(s => tops.ContainsKey(s.Id) && !MapLabelsPresenter.HiddenByZoom(s.Type, distance)))
                {
                    float clear = 2f * labels.Labels.Single(l => l.name == "label-" + s.Id).worldBound.height + MapLabelsPresenter.MarginPx;
                    if (tops.Any(o => o.Key != s.Id && Vector2.Distance(o.Value, tops[s.Id]) <= clear)) continue;
                    Assert.IsTrue(shown.Any(x => x.id == s.Id), $"{name}: {s.Id} has no visible marker within {clear:F0} px, so it must be labelled");
                }
                if (distance > MapLabelsPresenter.DeclutterDistanceM)
                    foreach (var s in map.Settlements.Where(s => MapLabelsPresenter.HiddenByZoom(s.Type, distance)))
                        Assert.IsFalse(Shown(labels.Slots.Single(x => x.name == "slot-" + s.Id)), $"{name}: {s.Id} ({s.Type}) is decluttered");
            }
        }
        finally { labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>Issue #599: close over Jaffa's harbour (gameplay03's yaw at 30, 40 and 50% of its distance, with the game's
    /// top-bar inset), Tel Aviv's and Jaffa's kit rectangles are hundreds of pixels across and overlap, and each holds or
    /// touches the other's marker. Every shown pill must still be nearer its own settlement's marker than any other
    /// visible marker, so "Tel Aviv" never hangs by Jaffa's harbour and "Jaffa" never sits on the pier by Tel Aviv. The
    /// markers are measured independently of the presenter. Jaffa is named at every pose, and Tel Aviv wherever its
    /// marker is visible (a city keeps its name). gameplay03 itself is checked the same way.</summary>
    [UnityTest]
    public IEnumerator EachPillIsNearerItsOwnMarkerByJaffasHarbour() => NearerOwnMarker(false);

    /// <summary>The same with the units in play (#518's keep-clear moves the spots round the Kiryati Brigade).</summary>
    [UnityTest]
    public IEnumerator EachPillIsNearerItsOwnMarkerByJaffasHarbourWithTheUnits() => NearerOwnMarker(true);

    IEnumerator NearerOwnMarker(bool units)
    {
        var hd = new HdPanel(cam);
        var labels = Labels(hd, units);
        var inset = new TopBarInset(hd.Root, rig);
        try
        {
            var g03 = PromoPose.Gameplay03;
            foreach (var pose in new[] { g03, new PromoPose("jaffa30", 34.76, 32.05, 0.3f * g03.Distance, g03.Yaw),
                         new PromoPose("jaffa40", 34.76, 32.05, 0.4f * g03.Distance, g03.Yaw), new PromoPose("jaffa50", 34.76, 32.05, 0.5f * g03.Distance, g03.Yaw) })
            {
                pose.Apply(rig, map.Frame);
                yield return null;
                inset.Update();
                yield return Settle(labels);
                var tops = VisibleMarkerTops(hd, map);
                var shown = labels.Slots.Where(Shown).Select(s => (id: s.name.Substring("slot-".Length), rect: s.Q<Label>().worldBound)).ToList();
                foreach (var id in new[] { "tel_aviv", "jaffa" })
                {
                    var p = shown.FirstOrDefault(x => x.id == id);
                    string Gaps() => string.Join(" ", new[] { "tel_aviv", "jaffa" }.Where(tops.ContainsKey).Select(o => $"{o} {Gap(p.rect, tops[o]):F0}"));
                    TestContext.WriteLine($"{pose.Name} units={units}: {id} marker {(tops.TryGetValue(id, out var t) ? t.ToString() : "not visible")} " +
                        (p.id == null ? "hidden" : $"pill {p.rect}, gap to {Gaps()}"));
                }
                Assert.IsTrue(shown.Any(x => x.id == "jaffa"), $"{pose.Name}: Jaffa is named");
                if (tops.ContainsKey("tel_aviv")) Assert.IsTrue(shown.Any(x => x.id == "tel_aviv"), $"{pose.Name}: Tel Aviv's marker is visible, so it is named");
                foreach (var (id, rect) in shown)
                {
                    Assert.IsTrue(tops.ContainsKey(id), $"{pose.Name}: {id} is shown but its marker is not visible");
                    float own = Gap(rect, tops[id]);
                    foreach (var other in tops.Where(o => o.Key != id))
                        Assert.Less(own, Gap(rect, other.Value), $"{pose.Name}: the {id} pill {rect} is {own:F0} px from its own marker but {Gap(rect, other.Value):F0} px from {other.Key}'s");
                }
            }
        }
        finally { inset.Dispose(); labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>Second review of #599: a city keeps its name. At gameplay03, at jaffa30, and over each city
    /// (from the closest zoom out to 40 km, at five yaws, with the top-bar inset), every city whose marker is visible is named, with the units off and on, and
    /// its pill is nearer its own marker than any other visible settlement's. Within LocalityDistanceM the 1948 localities'
    /// markers are on the map too (Silwan is 1.5 km from Jerusalem), and they must not take a city's name away. The towns
    /// the review named are logged (a town may give way, as before). No other settlement's pill hangs under its marker:
    /// Spot.Under is a city's last resort.</summary>
    [UnityTest]
    public IEnumerator EveryCityKeepsItsNameCloseUp() => CitiesKeepTheirNames(false);

    [UnityTest]
    public IEnumerator EveryCityKeepsItsNameCloseUpWithTheUnits() => CitiesKeepTheirNames(true);

    IEnumerator CitiesKeepTheirNames(bool units)
    {
        var hd = new HdPanel(cam);
        var labels = Labels(hd, units);
        var inset = new TopBarInset(hd.Root, rig);
        try
        {
            var g03 = PromoPose.Gameplay03;
            var cities = map.Settlements.Where(s => s.Type == "city").ToList();
            Assert.GreaterOrEqual(cities.Count, 3, "Jerusalem, Tel Aviv and Haifa");
            var poses = new System.Collections.Generic.List<(PromoPose pose, string? over)> { (g03, null), (new PromoPose("jaffa30", 34.76, 32.05, 0.3f * g03.Distance, g03.Yaw), null) };
            foreach (var c in cities)
                foreach (var d in new[] { CameraController.MinDistance, 10000f, 14000f, 18000f, 24000f, 30000f, 40000f })
                    foreach (var yaw in new[] { 0f, g03.Yaw, 90f, 180f, 270f })
                        poses.Add((new PromoPose($"{c.Id}{d / 1000f:F0}y{yaw:F0}", c.Lon, c.Lat, d, yaw), c.Id));
            string[] towns = { "acre", "rosh_pinna", "rishon_lezion", "petah_tikva" };
            foreach (var (pose, over) in poses)
            {
                pose.Apply(rig, map.Frame);
                if (over != null)   // over a city the look point is on the ground, as the game's pan keeps it (CameraController)
                {
                    var at = rig.LookAt; at.y = map.Terrain.SampleHeight(at) + map.Terrain.transform.position.y;
                    rig.LookAt = at; rig.Apply();
                }
                yield return null;
                inset.Update();
                yield return Settle(labels);
                var tops = VisibleMarkerTops(hd, map);
                var shown = labels.Slots.Where(Shown).Select(s => (id: s.name.Substring("slot-".Length), rect: s.Q<Label>().worldBound)).ToList();
                if (over != null) Assert.IsTrue(tops.ContainsKey(over), $"{pose.Name}: {over}'s marker is on screen, so this pose checks it");
                TestContext.WriteLine($"{pose.Name} units={units}: " + string.Join(" ", cities.Select(c => c.Id).Concat(towns).Where(tops.ContainsKey)
                    .Select(id => $"{id}={(shown.Any(x => x.id == id) ? "named" : "HIDDEN")}")));
                // Only a city hangs its pill under its marker (Spot.Under: top LiftPx below the marker top, centred on it).
                foreach (var (id, rect) in shown.Where(x => tops.ContainsKey(x.id) && map.Settlements.First(s => s.Id == x.id).Type != "city"))
                    Assert.IsFalse(Mathf.Abs(rect.yMin - (tops[id].y + MapLabelsPresenter.LiftPx)) < 1f && Mathf.Abs(rect.center.x - tops[id].x) < 1f,
                        $"{pose.Name}: {id} is no city but its pill {rect} hangs under its marker {tops[id]}");
                foreach (var c in cities.Where(c => tops.ContainsKey(c.Id)))
                {
                    var p = shown.FirstOrDefault(x => x.id == c.Id);
                    Assert.IsNotNull(p.id, $"{pose.Name}: {c.Id}'s marker {tops[c.Id]} is visible, so it is named");
                    float own = Gap(p.rect, tops[c.Id]);
                    foreach (var other in tops.Where(o => o.Key != c.Id))
                        Assert.Less(own, Gap(p.rect, other.Value), $"{pose.Name}: the {c.Id} pill {p.rect} is {own:F0} px from its own marker but {Gap(p.rect, other.Value):F0} px from {other.Key}'s");
                }
            }
        }
        finally { inset.Dispose(); labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>Re-review N1: a panel that appears (the event card) hides the pill it covers when its layout lands, from the
    /// geometry event itself, with no other refresh (in the game that is before the frame is drawn, not one frame later).</summary>
    [UnityTest]
    public IEnumerator TheEventCardAppearingHidesAnOverlappedPillAtOnce()
    {
        var hd = new HdPanel(cam);
        var labels = new MapLabelsPresenter(hd.Root, map, cam);
        try
        {
            Pose(34.78, 32.08, 90000f);   // Tel Aviv in the middle, where the decision card opens
            yield return Settle(labels);
            var tlv = labels.Slots.Single(s => s.name == "slot-tel_aviv");
            var before = tlv.Q<Label>().worldBound;
            Assert.IsTrue(Shown(tlv), "Tel Aviv is shown before the card opens");
            var card = hd.Root.Q<VisualElement>("event-card");
            card.style.minHeight = 500; card.style.display = DisplayStyle.Flex;
            for (int i = 0; i < 10 && (float.IsNaN(card.worldBound.width) || card.worldBound.width <= 0); i++) yield return null;
            TestContext.WriteLine($"Tel Aviv {before}, the card {card.worldBound}");
            Assert.IsTrue(card.worldBound.Overlaps(before), "precondition: the card covers Tel Aviv's pill");
            var after = tlv.Q<Label>().worldBound;
            Assert.IsTrue(!Shown(tlv) || !after.Overlaps(card.worldBound), $"Tel Aviv's pill {after} is still under the card {card.worldBound}");
        }
        finally { labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>Re-review N2: a pill that changes size with the camera still (a late font, a new text) is re-placed by the
    /// next plain refresh: label sizes are part of what Refresh checks before returning early.</summary>
    [UnityTest]
    public IEnumerator APillThatGrowsIsRePlacedWithoutACameraChange()
    {
        var hd = new HdPanel(cam);
        var labels = new MapLabelsPresenter(hd.Root, map, cam);
        try
        {
            Pose(34.95, 31.3 + (32.9 - 31.3) * 120 / 239.0, 90000f);
            yield return Settle(labels);
            var tlv = labels.Labels.Single(l => l.name == "label-tel_aviv");
            float width = tlv.resolvedStyle.width;
            tlv.text = "Tel Aviv, the first Hebrew city, with Jaffa to the south";
            for (int i = 0; i < 10 && tlv.resolvedStyle.width <= width + 1f; i++) yield return null;
            Assert.Greater(tlv.resolvedStyle.width, width + 200f, "the pill grew");
            labels.Refresh();
            var shown = labels.Slots.Where(Shown).Select(s => (id: s.name, rect: s.Q<Label>().worldBound)).ToList();
            for (int i = 0; i < shown.Count; i++)
                for (int j = i + 1; j < shown.Count; j++)
                    Assert.IsFalse(shown[i].rect.Overlaps(shown[j].rect), $"{shown[i].id} {shown[i].rect} overlaps {shown[j].id} {shown[j].rect}");
        }
        finally { labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>Review I1: with the game's top-bar inset, no shown pill reaches under the top bar, the info panel or the
    /// minimap, at both promo poses.</summary>
    [UnityTest]
    public IEnumerator NoPillSitsUnderAPanel()
    {
        var hd = new HdPanel(cam);
        var labels = new MapLabelsPresenter(hd.Root, map, cam);
        var inset = new TopBarInset(hd.Root, rig);
        try
        {
            foreach (var pose in new[] { PromoPose.Diorama02, PromoPose.Gameplay03 })
            {
                pose.Apply(rig, map.Frame);
                yield return null;
                inset.Update();
                Assert.Greater(rig.TopInset, 0.05f, "the top bar's inset applies");
                yield return Settle(labels);
                var bar = hd.Root.Q<VisualElement>("top-bar").worldBound;
                var info = hd.Root.Q<VisualElement>("info-panel").worldBound;
                var mini = hd.Root.Q<VisualElement>("minimap").worldBound;
                var layer = hd.Root.Q<VisualElement>("map-layer").worldBound;   // the minimap's caption (#234)
                int count = 0;
                foreach (var slot in labels.Slots.Where(Shown))
                {
                    var r = slot.Q<Label>().worldBound; count++;
                    Assert.GreaterOrEqual(r.yMin, bar.yMax - 0.5f, $"{pose.Name}: {slot.name} {r} reaches under the top bar {bar}");
                    Assert.IsFalse(r.Overlaps(info), $"{pose.Name}: {slot.name} {r} under the info panel {info}");
                    Assert.IsFalse(r.Overlaps(mini), $"{pose.Name}: {slot.name} {r} under the minimap {mini}");
                    Assert.IsFalse(layer.width > 0 && r.Overlaps(layer), $"{pose.Name}: {slot.name} {r} under the map-layer caption {layer}");
                }
                var zikhron = labels.Slots.Single(s => s.name == "slot-zikhron_yaakov");
                TestContext.WriteLine($"{pose.Name}: {count} shown; Zikhron Ya'akov shown={Shown(zikhron)} {zikhron.Q<Label>().worldBound}; bar {bar}");
                Assert.Greater(count, 4, $"{pose.Name}: pills are still shown");
            }
        }
        finally { inset.Dispose(); labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>Review of #624: the date plate hangs below the 70 px bar, so the bar's box no longer covers it, and a pill
    /// under the plate must hide as under any panel. The plate is made larger here so that towns certainly lie under it
    /// (checked first, so the test is not vacuous); no shown pill may overlap it.</summary>
    [UnityTest]
    public IEnumerator APillUnderTheHangingPlateIsHidden()
    {
        var hd = new HdPanel(cam);
        var labels = new MapLabelsPresenter(hd.Root, map, cam);
        try
        {
            PromoPose.Gameplay03.Apply(rig, map.Frame);
            var plateEl = hd.Root.Q<VisualElement>("date-plate");
            Assert.IsNotNull(plateEl, "the plate is named date-plate");
            plateEl.style.height = 700f; plateEl.style.width = 900f;   // over the coast and Tel Aviv's district at gameplay03
            for (int i = 0; i < 4; i++) yield return null;
            yield return Settle(labels);
            var plate = plateEl.worldBound;
            var bar = hd.Root.Q<VisualElement>("top-bar").worldBound;
            var under = map.Settlements.Where(t => { var p = hd.ToPanel(MarkerTopOf(t.Id), out bool front); return front && plate.Contains(p) && p.y > bar.yMax; }).Select(t => t.Id).ToList();
            TestContext.WriteLine($"plate {plate}; towns under it: {string.Join(", ", under)}");
            Assert.IsNotEmpty(under, "precondition: some towns lie under the plate");
            foreach (var slot in labels.Slots.Where(Shown))
            {
                var r = slot.Q<Label>().worldBound;
                Assert.IsFalse(r.Overlaps(plate), $"{slot.name} {r} is shown under the hanging plate {plate}");
            }
        }
        finally { labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>One step of the camera sweep the refresh tests share: a turn of 1.5 degrees and a zoom from 60 km out to
    /// the farthest, over 240 steps, so that every refresh sees a new view.</summary>
    void SweepStep(int i)
    {
        rig.Yaw += 1.5f; rig.Distance = Mathf.Lerp(60000f, CameraController.MaxDistance, i / 239f); rig.Apply();
    }

    /// <summary>Review I3: a refresh allocates nothing, forced or while the camera turns and zooms (240 refreshes, each with
    /// a new view, after one sweep that lets the presenter's lists reach their size). Counted by the profiler, so it does
    /// not depend on the machine's load (#322).</summary>
    [UnityTest]
    public IEnumerator RefreshWhileTheCameraMovesAllocatesNothing() => AllocatesNothing(false);

    /// <summary>The same with the unit tokens to keep clear of (the game's path).</summary>
    [UnityTest]
    public IEnumerator RefreshWhileTheCameraMovesAllocatesNothingWithTheUnits() => AllocatesNothing(true);

    IEnumerator AllocatesNothing(bool units)
    {
        var hd = new HdPanel(cam);
        var labels = Labels(hd, units);
        try
        {
            yield return Settle(labels);
            Assert.That(() => labels.Refresh(force: true), Is.Not.AllocatingGCMemory());
            for (int i = 0; i < 240; i++) { SweepStep(i); labels.Refresh(); }   // warm-up: the lists grow to their size
            for (int i = 0; i < 240; i++)
            {
                SweepStep(i);
                Assert.That(() => labels.Refresh(), Is.Not.AllocatingGCMemory(), $"refresh {i} of the sweep");
            }
        }
        finally { labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>#1680 / #322: moving the camera projects each active marker once and transforms each box corner at most
    /// once, plus one marker-box fallback. Count real work instead of scheduler-dependent microseconds; the existing
    /// profiler tests above still enforce zero allocations. This is an operation bound, not an absolute timing claim.</summary>
    [UnityTest]
    public IEnumerator RefreshWhileTheCameraMovesIsCheap()
    {
        const int Sweeps = 5, Steps = 240;
        var hd = new HdPanel(cam);
        var labels = new MapLabelsPresenter(hd.Root, map, cam);
        try
        {
            yield return Settle(labels);
            // This fixture has no site/location/route additions or keep-clear tokens. Localities are below 40 km only;
            // SweepStep starts at 60 km, so only the game settlements' markers are projected throughout the sweep.
            Assert.Greater(labels.Slots.Count, 0);
            Assert.AreEqual(map.Settlements.Count, labels.Slots.Count);
            Assert.IsEmpty(labels.LocationSlots);
            Assert.IsEmpty(map.ShownRoute);
            Assert.IsTrue(labels.Labels.All(l => l.resolvedStyle.width > 0f && l.resolvedStyle.height > 0f),
                "precondition: real label geometry has settled before testing the unchanged-view cache");
            long kitCornerLimit = 0;
            foreach (var place in map.Settlements)
                kitCornerLimit += 8L * (MapLabelsPresenter.KitBounds(map, place, MapLabelsPresenter.MarkerTop(map, place)).Length + 1);
            long markerCornerLimit = 8L * labels.Slots.Count;
            var tlv = labels.Slots.Single(s => s.name == "slot-tel_aviv");
            int moved = 0; var last = tlv.style.translate.value;
            for (int sweep = 0; sweep < Sweeps; sweep++)
                for (int i = 0; i < Steps; i++)
                {
                    SweepStep(i);
                    Assert.Greater(rig.Distance, MapLabelsPresenter.LocalityDistanceM, "localities are outside this fixture's projection work");
                    long markerBefore = labels.ProjectedMarkersForTests;
                    long placementBefore = labels.PlacementVisitsForTests;
                    long cornerBefore = MapLabelsPresenter.ProjectedCornersForTests;
                    labels.Refresh();   // no yield: snapshots surround only this synchronous main-thread call
                    long markers = labels.ProjectedMarkersForTests - markerBefore;
                    long corners = MapLabelsPresenter.ProjectedCornersForTests - cornerBefore;
                    long cornerLimit = map.KitsShown ? kitCornerLimit : markerCornerLimit;
                    string at = $"sweep {sweep}, step {i}";
                    Assert.AreEqual((long)labels.Slots.Count, markers, at + ": one marker projection per changed view, no duplicate pass");
                    Assert.AreEqual((long)labels.Slots.Count + labels.LocalitySlots.Count, labels.PlacementVisitsForTests - placementBefore,
                        at + ": one placement visit per slot, including hidden localities, no duplicate pass");
                    Assert.Greater(corners, 0L, at + ": actual corner transforms ran, not only the marker/cache check");
                    Assert.LessOrEqual(corners, cornerLimit, at + ": each kit corner plus at most one marker fallback");
                    var now = tlv.style.translate.value;
                    if (now.x != last.x || now.y != last.y) moved++;
                    last = now;
                    markerBefore = labels.ProjectedMarkersForTests;
                    placementBefore = labels.PlacementVisitsForTests;
                    cornerBefore = MapLabelsPresenter.ProjectedCornersForTests;
                    labels.Refresh();
                    Assert.AreEqual(markerBefore, labels.ProjectedMarkersForTests, at + ": unchanged view reuses marker projections");
                    Assert.AreEqual(cornerBefore, MapLabelsPresenter.ProjectedCornersForTests, at + ": unchanged view reuses box projections");
                    Assert.AreEqual(placementBefore, labels.PlacementVisitsForTests, at + ": unchanged view reuses placement");
                }
            Assert.Greater(moved, Sweeps * Steps / 2, "the refreshes did work: Tel Aviv's pill moved");
            // Isolate a fully front-facing box as well: a 24-corner loop produces the SAME hull, but must fail this count.
            // Reflection keeps the existing projection primitive private; no new public/test replacement implementation.
            var project = typeof(MapLabelsPresenter).GetMethod("ProjectBoxes",
                System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
            Assert.IsNotNull(project, "the real box-projection primitive is present");
            var args = new object[] { new[] { new Bounds(Vector3.zero, Vector3.one) }, Matrix4x4.identity,
                new Rect(0, 0, 1, 1), new Vector2(100, 100), Vector2.zero, default(Rect) };
            long beforeBox = MapLabelsPresenter.ProjectedCornersForTests;
            Assert.AreEqual(true, project!.Invoke(null, args), "the box is entirely in front of the identity projection");
            Assert.AreEqual(new Rect(25, 25, 50, 50), (Rect)args[5], "all eight corners produce the expected hull");
            Assert.AreEqual(8L, MapLabelsPresenter.ProjectedCornersForTests - beforeBox,
                "one box requires eight transforms; repeating the same corners 3x does not get a free pass");
        }
        finally { labels.Dispose(); hd.Dispose(); }
    }

    [UnityTest]
    public IEnumerator ASettledRefreshDoesNotReadEveryLabelSize()
    {
        var hd = new HdPanel(cam); var labels = new MapLabelsPresenter(hd.Root, map, cam);
        try
        {
            yield return Settle(labels);
            long reads = labels.LabelSizeReadsForTests, placements = labels.PlacementVisitsForTests;
            // This fixture owns a bare presenter, not a GameRoot component; Refresh is the production operation that
            // GameRoot.LateUpdate calls, without booting an unrelated scene-wide presenter into these counters.
            for (int i = 0; i < 5; i++) labels.Refresh();
            Assert.AreEqual(reads, labels.LabelSizeReadsForTests, "settled refreshes do not poll every label's resolved size");
            Assert.AreEqual(placements, labels.PlacementVisitsForTests, "settled refreshes do no placement work");

            labels.Labels[0].text += " wider";
            yield return null;   // UI Toolkit delivers the label's real GeometryChangedEvent.
            labels.Refresh();
            Assert.Greater(labels.PlacementVisitsForTests, placements, "changed text invalidates real placement");
            Assert.Greater(labels.LabelSizeReadsForTests, reads, "sizes are read while that placement work runs");
        }
        finally { labels.Dispose(); hd.Dispose(); }
    }

    [UnityTest]
    public IEnumerator HoverAndPillHitsAreCachedUntilPointerOrPlacementChanges()
    {
        var hd = new HdPanel(cam); var labels = new MapLabelsPresenter(hd.Root, map, cam);
        try
        {
            Pose(35.50, 32.49, 30000f); yield return Settle(labels);
            var origin = hd.Root.Q<VisualElement>(MapLabelsPresenter.ContainerName).worldBound.position;
            var locality = labels.LocalitySlots.Single(x => x.name == "slot-beit_shean");
            var hover = locality.Q<Label>().worldBound.center - origin;
            var city = labels.Slots.First(Shown).Q<Label>().worldBound.center - origin;
            var panel = hd.Root.panel;
            Assert.IsNotNull(panel, "the labels have a live panel");
            Vector2 panelZero = UiPointer.ToPanel(panel, Vector2.zero, Screen.height);
            Vector2 panelX = UiPointer.ToPanel(panel, Vector2.right * 100f, Screen.height) - panelZero;
            Vector2 panelY = UiPointer.ToPanel(panel, Vector2.up * 100f, Screen.height) - panelZero;
            Vector2 ScreenPoint(Vector2 layerPoint)
            {
                var wanted = layerPoint + origin - panelZero;
                return new Vector2(wanted.x / panelX.x * 100f, wanted.y / panelY.y * 100f);
            }
            var hoverScreen = ScreenPoint(hover); var cityScreen = ScreenPoint(city);

            labels.Hover(hoverScreen); long hoverVisits = labels.HoverVisitsForTests;
            labels.Hover(hoverScreen);
            Assert.AreEqual(hoverVisits, labels.HoverVisitsForTests, "the unchanged hover reuses its hit");
            labels.Hover(ScreenPoint(hover + Vector2.right));
            Assert.Greater(labels.HoverVisitsForTests, hoverVisits, "a moved hover recomputes");

            labels.PillAt(cityScreen); long pillVisits = labels.PillVisitsForTests;
            labels.PillAt(cityScreen);
            Assert.AreEqual(pillVisits, labels.PillVisitsForTests, "the unchanged city-pill hit is reused");
            labels.PillAt(ScreenPoint(city + Vector2.right));
            Assert.Greater(labels.PillVisitsForTests, pillVisits, "a moved pill probe recomputes");

            // As above, the bare presenter has no player-loop method of its own; GameRoot owns this Refresh call in play.
            labels.Refresh(force: true);
            hoverVisits = labels.HoverVisitsForTests; pillVisits = labels.PillVisitsForTests;
            labels.Hover(hoverScreen); labels.PillAt(cityScreen);
            Assert.Greater(labels.HoverVisitsForTests, hoverVisits, "new placement invalidates hover hits");
            Assert.Greater(labels.PillVisitsForTests, pillVisits, "new placement invalidates pill hits");
        }
        finally { labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>Keeping clear of the unit tokens (#197) costs little next to placing the pills: one presenter, whose
    /// keep-clear list is switched between the units in play and none, runs interleaved sweeps (off, on, off, on, ...) of
    /// 240 refreshes along the same camera path; the median refresh with the units is at most 1.25 times the median without,
    /// both taken from the same run. This separate relative timing check is unchanged by #1680; the test above bounds work, not time.</summary>
    [UnityTest]
    public IEnumerator KeepingClearOfTheUnitsIsCheap()
    {
        const int Pairs = 5, Steps = 240;
        const double MaxRatio = 1.25;
        var layer = StartUnits();
        bool on = false;
        var hd = new HdPanel(cam);
        var labels = new MapLabelsPresenter(hd.Root, map, cam, keepClear: () => on ? layer.KeepClear : System.Array.Empty<Bounds[]>());
        try
        {
            yield return Settle(labels);
            var times = new double[Steps];
            var off = new System.Collections.Generic.List<double>(); var with = new System.Collections.Generic.List<double>();
            var watch = new System.Diagnostics.Stopwatch();
            for (int s = 0; s < 2 * Pairs; s++)
            {
                on = s % 2 == 1;
                for (int i = 0; i < Steps; i++)
                {
                    SweepStep(i);
                    watch.Restart(); labels.Refresh(); watch.Stop();
                    times[i] = watch.Elapsed.TotalMilliseconds * 1000.0;
                }
                System.Array.Sort(times);
                (on ? with : off).Add((times[Steps / 2 - 1] + times[Steps / 2]) / 2.0);
            }
            Assert.Greater(layer.KeepClear.Count, 0, "the units were on the map");
            double Median(System.Collections.Generic.List<double> xs) { xs.Sort(); return xs.Count % 2 == 1 ? xs[xs.Count / 2] : (xs[xs.Count / 2 - 1] + xs[xs.Count / 2]) / 2.0; }
            double mOff = Median(off), mOn = Median(with);
            var inv = System.Globalization.CultureInfo.InvariantCulture;
            TestContext.WriteLine(System.FormattableString.Invariant(
                $"LABELS keep-clear cost off_us={mOff:0} on_us={mOn:0} ratio={mOn / mOff:0.00} off={string.Join(",", off.Select(m => m.ToString("0", inv)))} on={string.Join(",", with.Select(m => m.ToString("0", inv)))}"));
            Assert.LessOrEqual(mOn, MaxRatio * mOff, $"keeping clear of the units: {mOn:0} us against {mOff:0} us without them");
        }
        finally { labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>Issue #669: the 1948 Collection's craft stay off the labels. At the 60 km gameplay view over Tel Aviv and Jaffa,
    /// Haifa and Acre, and Lod, on the Altalena's turn (15 June 1948) and in Magic Carpet's main wave (15 August 1949), no
    /// shown pill meets a drawn craft (its renderers' world box, every corner through the camera's pixels): the pills keep
    /// clear of the craft's boxes as GameRoot passes them (SeaAirCollection.KeepClear).</summary>
    [UnityTest]
    public IEnumerator TheCollectionCraftStayOffEveryShownPill()
    {
        var c = Statecraft.Sim.ContentLoader.Load(Statecraft.Game.Paths.Content);
        var saved = Statecraft.Game.Map.Collection.SeaAirCollection.Request;
        Statecraft.Game.Map.Collection.SeaAirCollection.Request = (id, d, done) => done(AssetDatabase.LoadAssetAtPath<GameObject>(
            Statecraft.Game.Map.Collection.CollectionCatalog.PrefabPath(id, d)));
        var hd = new HdPanel(cam);
        Statecraft.Game.Map.Collection.SeaAirCollection? craftLayer = null;
        // As GameRoot wires it: the names keep clear of the craft's boxes (SeaAirCollection.KeepClear), as of the unit tokens.
        var labels = new MapLabelsPresenter(hd.Root, map, cam, keepClear: () => craftLayer != null ? craftLayer.KeepClear : null);
        int checkedCraft = 0;
        try
        {
            foreach (var date in new[] { new System.DateTime(1948, 6, 15), new System.DateTime(1949, 8, 15) })
            {
                var layer = craftLayer = Statecraft.Game.Map.Collection.SeaAirCollection.ShowAt(map, date, System.Array.Empty<Statecraft.Sim.Placement>(), c)!;
                Assert.AreEqual(date.Year == 1948 ? 5 : 4, layer.Placed.Count, "every craft drawn on " + date.ToString("d MMM yyyy"));
                foreach (var (lon, lat) in new[] { (34.76, 32.07), (35.03, 32.86), (34.88, 32.0) })
                {
                    Pose(lon, lat, 60000f);
                    yield return Settle(labels);
                    var pills = labels.Labels.Where(l => Shown(l.parent)).Concat(labels.LocalityLabels.Where(l => Shown(l.parent))).Select(l => l.worldBound).ToList();
                    Assert.Greater(pills.Count, 0, $"pills shown over {lon}, {lat}");
                    foreach (Transform craft in layer.transform)
                    {
                        var b = craft.GetComponentsInChildren<Renderer>(true).Select(r => r.bounds).Aggregate((a, x) => { a.Encapsulate(x); return a; });
                        float x0 = float.MaxValue, y0 = float.MaxValue, x1 = float.MinValue, y1 = float.MinValue; bool front = true;
                        for (int k = 0; k < 8; k++)
                        {
                            var corner = new Vector3((k & 1) == 0 ? b.min.x : b.max.x, (k & 2) == 0 ? b.min.y : b.max.y, (k & 4) == 0 ? b.min.z : b.max.z);
                            var q = hd.ToPanel(corner, out var inFront); front &= inFront;
                            x0 = Mathf.Min(x0, q.x); y0 = Mathf.Min(y0, q.y); x1 = Mathf.Max(x1, q.x); y1 = Mathf.Max(y1, q.y);
                        }
                        var rect = Rect.MinMaxRect(x0, y0, x1, y1);
                        if (!front || !rect.Overlaps(hd.Root.worldBound)) continue;   // off this view
                        checkedCraft++;
                        foreach (var pill in pills)
                            Assert.IsFalse(pill.Overlaps(rect), $"{craft.name} {rect} under a pill {pill} at {lon}, {lat} on {date:d MMM yyyy}");
                    }
                }
            }
            Assert.GreaterOrEqual(checkedCraft, 5, "the craft were in view");
        }
        finally { labels.Dispose(); hd.Dispose(); Statecraft.Game.Map.Collection.SeaAirCollection.Request = saved; }
    }

    // --- #803: settlement-control states on the map ----------------------------------------------------------------

    static UiText En803 => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
    static UiText He803 => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text, "strings.he.yaml");

    /// <summary>The map tag's words for a record, as GameRoot gives them (SettlementControlView.MapText).</summary>
    static System.Func<Statecraft.Sim.SettlementControl, string?> ControlText(UiText text) => r => SettlementControlView.MapText(text, r);

    static Label ControlBadge(MapLabelsPresenter labels, string id) =>
        labels.Slots.Single(x => x.name == "slot-" + id).Q<Label>(className: MapLabelsPresenter.ControlBadgeClass);

    /// <summary>#803 Task 3 (owner, 24 October 2026, "1521: 1. a 2.a"): each state on main shows as a short word tag under the
    /// town's name, in one quiet colour for every state; the name stays, and a place with no record has no tag.</summary>
    [UnityTest]
    public IEnumerator EachStateHasOneBadgeAndTheNameStays()
    {
        var hd = new HdPanel(cam);
        var text = En803;
        var labels = new MapLabelsPresenter(hd.Root, map, cam, controlText: ControlText(text));
        try
        {
            var names = labels.Labels.ToDictionary(x => x.name, x => x.text);
            var badges = new System.Collections.Generic.List<Label>();
            labels.SetSettlementControl(new System.Collections.Generic.Dictionary<string, Statecraft.Sim.SettlementControl>
            {
                ["acre"] = new Statecraft.Sim.SettlementControl("israel", Statecraft.Sim.SettlementControl.AwaitingChoice),
                ["nazareth"] = new Statecraft.Sim.SettlementControl("israel", Statecraft.Sim.SettlementControl.Occupied, turns: 4),
                ["lod"] = new Statecraft.Sim.SettlementControl("israel", Statecraft.Sim.SettlementControl.AwaitingEnd),
                ["ramla"] = new Statecraft.Sim.SettlementControl(depopulated: true),
                ["beersheba"] = new Statecraft.Sim.SettlementControl("israel", Statecraft.Sim.SettlementControl.Annexed),
            });
            for (int i = 0; i < 3; i++) yield return null;
            foreach (var (id, key) in new[] { ("acre", "awaiting_choice"), ("nazareth", "occupied"), ("lod", "awaiting_end"), ("ramla", "depopulated"), ("beersheba", "annexed") })
            {
                var slot = labels.Slots.Single(x => x.name == "slot-" + id);
                Assert.AreEqual(names["label-" + id], slot.Q<Label>("label-" + id).text, id + ": the name is kept");
                var badge = ControlBadge(labels, id);
                Assert.IsNotNull(badge, id + " has a badge");
                Assert.AreEqual(text["map.control." + key], badge.text, id);
                Assert.AreEqual(DisplayStyle.Flex, badge.resolvedStyle.display, id + ": shown");
                StringAssert.DoesNotMatch(@"\d", badge.text, id + ": the map tag carries no number (Question 2 (a))");
                badges.Add(badge);
            }
            Assert.AreEqual(1, badges.Select(x => x.resolvedStyle.color).Distinct().Count(), "one quiet colour for every state");
            Assert.AreEqual(1, badges.Select(x => x.resolvedStyle.backgroundColor).Distinct().Count(), "one background for every state");
            Assert.AreEqual(DisplayStyle.None, ControlBadge(labels, "jaffa").resolvedStyle.display, "no record, no badge");
            foreach (var x in labels.LocalitySlots.Concat(labels.LocationSlots))
                Assert.IsNull(x.Q<Label>(className: MapLabelsPresenter.ControlBadgeClass), x.name + ": only game settlements have a badge");
        }
        finally { labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>#803 Task 3: clearing a record hides its badge and keeps the very same name label (no rebuild).</summary>
    [UnityTest]
    public IEnumerator ClearingARecordHidesItsBadgeAndKeepsTheSameNameLabel()
    {
        var hd = new HdPanel(cam);
        var text = En803;
        var labels = new MapLabelsPresenter(hd.Root, map, cam, controlText: ControlText(text));
        try
        {
            var name = labels.Labels.Single(l => l.name == "label-nazareth");
            var badge = ControlBadge(labels, "nazareth");
            var occupied = new System.Collections.Generic.Dictionary<string, Statecraft.Sim.SettlementControl>
                { ["nazareth"] = new Statecraft.Sim.SettlementControl("israel", Statecraft.Sim.SettlementControl.Occupied, turns: 4) };
            labels.SetSettlementControl(occupied);
            yield return null;
            Assert.AreEqual(DisplayStyle.Flex, badge.resolvedStyle.display);
            Assert.AreEqual(text["map.control.occupied"], badge.text);
            labels.SetSettlementControl(new System.Collections.Generic.Dictionary<string, Statecraft.Sim.SettlementControl>());
            yield return null;
            Assert.AreEqual(DisplayStyle.None, badge.resolvedStyle.display, "the record is gone: the badge hides");
            Assert.AreSame(name, labels.Labels.Single(l => l.name == "label-nazareth"), "the same name label");
            Assert.AreSame(name, labels.Slots.Single(x => x.name == "slot-nazareth").Q<Label>("label-nazareth"), "still in its slot");
            Assert.AreSame(badge, ControlBadge(labels, "nazareth"), "the same badge, hidden, not rebuilt");
        }
        finally { labels.Dispose(); hd.Dispose(); }
    }

    /// <summary>#803 Task 3: at 1920x1080, 1280x720 and 390x844, in English and Hebrew, each shown badge sits under its own
    /// name (its top at the name's bottom, across the name), stays inside the window, and overlaps no other shown name or
    /// badge: Lod and Ramla share a hex, and Jaffa sits by Tel Aviv.</summary>
    [UnityTest]
    public IEnumerator EveryShownBadgeSitsUnderItsNameAndClearOfTheOtherNames()
    {
        var problems = new System.Collections.Generic.List<string>();
        var records = new System.Collections.Generic.Dictionary<string, Statecraft.Sim.SettlementControl>
        {
            ["jaffa"] = new Statecraft.Sim.SettlementControl("israel", Statecraft.Sim.SettlementControl.AwaitingEnd),
            ["lod"] = new Statecraft.Sim.SettlementControl("israel", Statecraft.Sim.SettlementControl.Occupied, turns: 3),
            ["ramla"] = new Statecraft.Sim.SettlementControl(depopulated: true),
        };
        foreach (var hebrew in new[] { false, true })
            foreach (var (w, h) in new[] { (1920, 1080), (1280, 720), (390, 844) })
                foreach (var distance in new[] { 30000f, 90000f })
                {
                    string at = $"{(hebrew ? "he" : "en")} {w}x{h} {distance / 1000f:0} km";
                    var hd = new HdPanel(cam, w, h);
                    if (hebrew) (hd.Root.Q("root") ?? hd.Root).AddToClassList(UiLanguage.HebrewClass);
                    var labels = new MapLabelsPresenter(hd.Root, map, cam, hebrew: hebrew, controlText: ControlText(hebrew ? He803 : En803));
                    try
                    {
                        Pose(34.85, 31.98, distance);
                        labels.SetSettlementControl(records);
                        for (int i = 0; i < 20 && labels.Labels.Any(l => float.IsNaN(l.resolvedStyle.width) || l.resolvedStyle.width <= 0); i++) yield return null;
                        yield return null;
                        labels.Refresh(force: true); yield return null;
                        labels.Refresh(force: true); yield return null;
                        var win = hd.Root.worldBound;
                        var shown = labels.Slots.Where(Shown).ToList();
                        var rects = new System.Collections.Generic.List<(string what, Rect rect)>();
                        foreach (var slot in shown)
                        {
                            rects.Add((slot.name + " name", slot.Q<Label>().worldBound));
                            var b = slot.Q<Label>(className: MapLabelsPresenter.ControlBadgeClass);
                            if (b != null && b.resolvedStyle.display == DisplayStyle.Flex) rects.Add((slot.name + " badge", b.worldBound));
                        }
                        int seen = 0;
                        foreach (var id in records.Keys)
                        {
                            var slot = labels.Slots.Single(x => x.name == "slot-" + id);
                            if (!Shown(slot)) continue;
                            seen++;
                            Rect name = slot.Q<Label>("label-" + id).worldBound, badge = ControlBadge(labels, id).worldBound;
                            if (Mathf.Abs(badge.yMin - name.yMax) > 1f) problems.Add($"{at} {id}: the badge {badge} is not right under its name {name}");
                            if (badge.xMax < name.xMin || badge.xMin > name.xMax) problems.Add($"{at} {id}: the badge {badge} is not under its name {name}");
                            if (badge.xMin < win.xMin - 0.5f || badge.xMax > win.xMax + 0.5f || badge.yMin < win.yMin - 0.5f || badge.yMax > win.yMax + 0.5f)
                                problems.Add($"{at} {id}: the badge {badge} leaves the window {win}");
                        }
                        for (int i = 0; i < rects.Count; i++)
                            for (int j = i + 1; j < rects.Count; j++)
                                if (rects[i].what.Split(' ')[0] != rects[j].what.Split(' ')[0] && rects[i].rect.Overlaps(rects[j].rect))
                                    problems.Add($"{at}: {rects[i].what} {rects[i].rect} overlaps {rects[j].what} {rects[j].rect}");
                        TestContext.WriteLine($"{at}: {seen} of {records.Count} places with a record shown");
                        if (w >= 1280 && seen == 0) problems.Add($"{at}: precondition: no place with a record is shown");
                    }
                    finally { labels.Dispose(); hd.Dispose(); }
                }
        Assert.IsEmpty(problems, string.Join("\n", problems));
    }
}