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.

61.5 KB
Raw Blame
#nullable enable
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Statecraft.Game;
using Statecraft.Game.UI;
using Statecraft.Sim;
using UnityEditor;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.UIElements;

public class HudTests
{
    static readonly Content C = ContentLoader.Load(Paths.Content);
    static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
    static SimBridge NewBridge() => new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);

    /// <summary>#2199: the Money meter's causes are the sim's Money lines (EconomySystem.MovesMoney): a city's job income
    /// is one, though its Target is the city; a borrowing line (Target debt) is not, as it moves the Treasury and the Debt
    /// alike. The largest first, at most MaxCauses (#1037). After the real opening turn, job income is among them.</summary>
    [Test]
    public void MoneyCausesIncludeJobIncomeAndLeaveOutBorrowing()
    {
        var why = new List<Cause>
        {
            new Cause("economy", "treasury", -0.4, "Money IL\u00A0-0.4m (military upkeep)", key: CauseKeys.MilitaryUpkeep),
            new Cause("city", "tel_aviv", 0.53, "Tel Aviv: jobs paid IL\u00A0+0.5m", key: CauseKeys.WagesPaid),
            new Cause("economy", "debt", 9, "Borrowed IL\u00A09.0m to cover the deficit", key: CauseKeys.Borrowed, args: new[] { CauseKeys.Purpose.Deficit }),
        };
        var turn = new StepResult(new GameState(), why, new Rejection[0]);
        CollectionAssert.AreEqual(new[] { "Tel Aviv: jobs paid IL\u00A0+0.5m", "Money IL\u00A0-0.4m (military upkeep)" },
            HudModel.Causes(turn, "treasury", C, w => w.Message));

        var b = NewBridge();
        b.EndTurn();
        CollectionAssert.Contains(HudModel.Causes(b.Session.Last, "treasury", C, w => w.Key), CauseKeys.WagesPaid, "the opening turn's job income");
    }

    /// <summary>#2212: Money shows its two largest causes (MaxCauses) and one Other line for the rest, summed by the sim
    /// (EconomySystem.OtherMoney), so the lines add up to the Money (net) change. No Other line with two causes or fewer,
    /// or when the rest shows as IL 0.0m; no other meter gets one. After the real opening turn the lines add up.</summary>
    [Test]
    public void MoneyShowsTheTwoLargestCausesAndOneOtherLineForTheRest()
    {
        Cause Money(double d, string what) => new Cause("economy", "treasury", d, PlayerText.Change(C, "treasury", d) + " (" + what + ")", key: CauseKeys.MilitaryUpkeep);
        var borrowing = new Cause("economy", "debt", 9, "Borrowed IL\u00A09.0m to cover the deficit", key: CauseKeys.Borrowed, args: new[] { CauseKeys.Purpose.Deficit });
        IReadOnlyList<string> Lines(string meter, params Cause[] why) =>
            HudModel.Causes(new StepResult(new GameState(), why.Append(borrowing).ToList(), new Rejection[0]), meter, C, w => w.Message);

        var a = Money(-3, "a"); var b = Money(2, "b");
        CollectionAssert.AreEqual(new[] { "Money IL\u00A0-3.0m (a)", "Money IL\u00A0+2.0m (b)", "Money IL\u00A0-0.3m (other causes)" },
            Lines("treasury", Money(0.1, "d"), a, Money(-0.4, "c"), b), "three or more causes: the two largest, then the rest");
        CollectionAssert.AreEqual(new[] { "Money IL\u00A0-3.0m (a)", "Money IL\u00A0+2.0m (b)" }, Lines("treasury", a, b), "two causes: no Other line");
        CollectionAssert.AreEqual(new[] { "Money IL\u00A0-3.0m (a)" }, Lines("treasury", a), "one cause: no Other line");
        CollectionAssert.AreEqual(new[] { "Money IL\u00A0-3.0m (a)", "Money IL\u00A0+2.0m (b)" }, Lines("treasury", a, b, Money(0.04, "c")),
            "the rest shows as IL\u00A00.0m: no Other line");
        CollectionAssert.AreEqual(new[] { "Money IL\u00A0-3.0m (a)", "Money IL\u00A0+2.0m (b)" }, Lines("treasury", a, b, Money(1, "c"), Money(-1, "d")),
            "the rest cancels out: no Other line");
        Cause Security(double d) => new Cause("events", "security", d, PlayerText.Change(C, "security", d));
        Assert.AreEqual(HudModel.MaxCauses, Lines("security", Security(0.03), Security(0.02), Security(0.01)).Count, "only Money gets an Other line");

        var bridge = NewBridge();
        bridge.EndTurn();
        var shown = new List<Cause>();
        HudModel.Causes(bridge.Session.Last, "treasury", C, w => { shown.Add(w); return w.Message; });
        Assert.AreEqual(HudModel.MaxCauses + 1, shown.Count, "the opening turn has more Money causes than MaxCauses");
        Assert.AreEqual(CauseKeys.MoneyOther, shown[shown.Count - 1].Key);
        var s = bridge.State; var prev = bridge.Session.Previous!;
        Assert.AreEqual((s.Treasury - s.Debt) - (prev.Treasury - prev.Debt), shown.Sum(w => w.Delta), 1e-9, "the lines add up to the Money (net) change");
    }

    [Test]
    public void TheTopBarShowsTheOpeningOfTheGame()
    {
        var m = HudModel.From(NewBridge(), Text);
        Assert.AreEqual("1948", m.Year);
        Assert.AreEqual(Text.Format("hud.turn", 0), m.Turn);
        Assert.AreEqual("15 May 1948", m.Date);
        Assert.AreEqual("IL\u00A020.0m", m.Treasury.Value);          // Israeli pounds (playtest 1, item 7)
        Assert.AreEqual("$40.0m", m.Fx.Value);
        Assert.AreEqual("30%", m.Security.Value);                    // the 0-100 scale, with its unit (fix round 1, I2)
        Assert.AreEqual("50%", m.Standing.Value);
        StringAssert.EndsWith("%", m.Support.Value);
        Assert.AreEqual(Text.Format("hud.level", 5), m.SecurityLevel);
        Assert.AreEqual(Text.Format("hud.attention", 4.0, 4.0), m.Attention);
        Assert.AreEqual("", m.Treasury.Delta);                       // no previous turn yet
    }

    /// <summary>#687: the plate's date is in the UI's language, through the date.* strings as the map's front-line date
    /// (Control1948.LineDateText): "15 במאי 1948" in Hebrew, every month with its Hebrew name and no Latin letter.</summary>
    [Test]
    public void TheDatePlateIsInHebrewInTheHebrewUi()
    {
        var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), He);
        Assert.AreEqual("15 במאי 1948", HudModel.From(bridge, He).Date);
        var months = new[] { "ינואר", "פברואר", "מרץ", "אפריל", "מאי", "יוני", "יולי", "אוגוסט", "ספטמבר", "אוקטובר", "נובמבר", "דצמבר" };
        for (int m = 1; m <= 12; m++)
        {
            bridge.State.Date = new System.DateTime(1950, m, 1);
            var date = HudModel.From(bridge, He).Date;
            Assert.AreEqual($"1 ב{months[m - 1]} 1950", date);
            Assert.IsFalse(System.Text.RegularExpressions.Regex.IsMatch(date, "[A-Za-z]"), date);
        }
    }

    /// <summary>#687: English is unchanged, PlayerText.Date's "15 May 1948" on every day of a leap year (every month, every
    /// day number).</summary>
    [Test]
    public void TheDatePlateInEnglishIsUnchanged()
    {
        var bridge = NewBridge();
        for (var d = new System.DateTime(1948, 1, 1); d.Year == 1948; d = d.AddDays(1))
        {
            bridge.State.Date = d;
            Assert.AreEqual(PlayerText.Date(d), HudModel.From(bridge, Text).Date);
        }
    }

    /// <summary>#687, fail-open check: a Hebrew strings file without a month's name does not fall back to English or show
    /// nothing; the lookup throws naming the file and the key.</summary>
    [Test]
    public void AMissingMonthNameThrowsRatherThanShowingEnglish()
    {
        var yaml = AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text;
        var noMay = UiText.Parse(string.Join("\n", yaml.Split('\n').Where(l => !l.StartsWith("date.month_5:"))), "strings.he.yaml");
        var e = Assert.Throws<System.Collections.Generic.KeyNotFoundException>(() =>
            HudModel.From(new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), He), noMay));
        StringAssert.Contains("date.month_5", e!.Message);
    }

    /// <summary>T71: the top bar's Treasury is the net position, cash minus debt (HudModel.From; M3 plan: "with deficits
    /// borrowed, cash alone is always 0"). The sim keeps cash at 0 or above (R-MONEY-003), so a negative reading is debt,
    /// not a negative Treasury: after five monthly turns with no orders, 0 cash and the debt read as minus the debt (four
    /// before the GDD loop sent the reserves home with the first truce's rung, R-WAR-002, #750).</summary>
    [Test]
    public void TheTreasuryShowsCashMinusDebtSoBorrowingReadsNegative()
    {
        var bridge = NewBridge();
        for (var i = 0; i < 5; i++) bridge.EndTurn();
        Assert.AreEqual(0.0, bridge.State.Treasury);   // R-MONEY-003: cash stops at 0
        Assert.Greater(bridge.State.Debt, 0.0);
        var m = HudModel.From(bridge, Text);
        Assert.AreEqual(PlayerText.Money(C, "treasury", -bridge.State.Debt), m.Treasury.Value);
        Assert.That(m.Treasury.Value.IndexOf("IL\u00A0-", System.StringComparison.Ordinal) >= 0);
    }

    /// <summary>#681 (owner, 16 October 2026: "keep one top-bar figure and label it as net (cash minus debt)"): the Money
    /// caption, and the tooltip that says it, read net in both languages; the value stays cash minus debt, so with debt
    /// it reads negative.</summary>
    [TestCase(false, "Money (net)")]
    [TestCase(true, "כסף (נטו)")]
    public void TheMoneyFigureIsLabelledNet(bool hebrew, string caption)
    {
        var text = hebrew ? He : Text;
        var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text);
        for (var i = 0; i < 5; i++) bridge.EndTurn();
        Assert.Greater(bridge.State.Debt, 0.0, "precondition: something is borrowed");
        using var ui = new UiTestKit();
        new HudPresenter(ui.Root, bridge, text);
        var meter = ui.Q<VisualElement>("meter-treasury");
        Assert.AreEqual(caption, meter.Q<Label>(className: "meter-name").text);
        StringAssert.StartsWith(caption + ":", meter.tooltip);
        Assert.AreEqual(PlayerText.Money(C, "treasury", bridge.State.Treasury - bridge.State.Debt), ui.Q<Label>("treasury-value").text);
        Assert.That(ui.Q<Label>("treasury-value").text.IndexOf("IL\u00A0-", System.StringComparison.Ordinal) >= 0);
    }

    // ---- The score (#380): only in the GDD loop, from GameState.Score ----

    /// <summary>The real game: the GDD loop since the cutover (the ?mvp=1 slice is gone with MvpSlice).</summary>
    static SimBridge GddBridge() => new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);

    [Test]
    public void EndTurnWaitsWhileAUnitNeedsOrders()
    {
        using var ui = new UiTestKit();
        var bridge = GddBridge();
        var selected = new List<int>();
        using var hud = new HudPresenter(ui.Root, bridge, Text, selectUnit: selected.Add);
        var endTurn = ui.Q<Button>("end-turn");
        var turn = bridge.TurnStart.Turn;
        Assert.AreEqual(Text["hud.end_turn_needs_orders"], endTurn.text);
        UiTestKit.Press(endTurn);
        Assert.AreEqual(turn, bridge.TurnStart.Turn, "the turn did not end");
        Assert.AreEqual(bridge.NeedsOrders[0], selected.Single());
        foreach (var id in bridge.NeedsOrders.ToList()) bridge.Skip(id);
        Assert.AreEqual(Text["hud.end_turn"], endTurn.text);
        UiTestKit.Press(endTurn);
        Assert.AreEqual(turn + 1, bridge.TurnStart.Turn);
    }

    /// <summary>Review Focus 4: a unit with Send home queued is not selected.</summary>
    [Test]
    public void TheCycleSkipsUnitsGoingHome()
    {
        using var ui = new UiTestKit();
        var bridge = GddBridge();
        var selected = new List<int>();
        using var hud = new HudPresenter(ui.Root, bridge, Text, selectUnit: selected.Add);
        var first = bridge.NeedsOrders[0];
        Assert.IsNull(bridge.Queue(new UnitOrder(first, Demobilization.SendHome)));
        UiTestKit.Press(ui.Q<Button>("end-turn"));
        Assert.AreNotEqual(first, selected.Single());
        Assert.AreEqual(bridge.NeedsOrders[0], selected.Single());
    }

    [Test]
    public void TheLegacyLoopShowsNoScore()
    {
        // The legacy loop survives only as content without the loop switch (SimBridgeGddTests.Legacy) since the cutover.
        SimBridge LegacyBridge() => new SimBridge(GameSession.New(SimBridgeGddTests.Legacy, GoldenRun.Seed, Mode.Historical), Text);
        Assert.AreEqual("", HudModel.From(LegacyBridge(), Text).Score);
        using var ui = new UiTestKit();
        using var hud = new HudPresenter(ui.Root, LegacyBridge(), Text);
        Assert.AreEqual(DisplayStyle.None, ui.Q<Label>("score").style.display.value);
    }

    [Test]
    public void TheGddGameShowsItsScore()
    {
        var bridge = GddBridge();
        Assert.AreEqual(Text.Format("hud.score", 0), HudModel.From(bridge, Text).Score);
        bridge.State.Score = 150;
        Assert.AreEqual(Text.Format("hud.score", 150), HudModel.From(bridge, Text).Score);
        // The value carries left-to-right marks in a Hebrew line (U+200E, #543), as every Hebrew value does.
        var he = HudModel.From(bridge, He).Score;
        Assert.AreEqual("ניקוד \u200E150\u200E", he);
        Assert.AreEqual("ניקוד 150", he.Replace("\u200E", ""));
    }

    [Test]
    public void TheBarShowsTheGddGamesScore()
    {
        using var ui = new UiTestKit();
        var bridge = GddBridge();
        using var hud = new HudPresenter(ui.Root, bridge, Text);
        var label = ui.Q<Label>("score");
        Assert.AreEqual(Text.Format("hud.score", 0), label.text);
        Assert.AreEqual(DisplayStyle.Flex, label.style.display.value);
        bridge.State.Score = 150;
        hud.Render();
        Assert.AreEqual(Text.Format("hud.score", 150), label.text);
    }

    // ---- The exhausted-turn count (#812, R-END-002): "1 of 3" under the date while Money and Food are both out ----

    [Test]
    public void TheBarCountsTheExhaustedTurnsAgainstTheDefeatLimit()
    {
        using var ui = new UiTestKit();
        var bridge = GddBridge();
        using var hud = new HudPresenter(ui.Root, bridge, Text);
        var label = ui.Q<Label>("exhausted");
        // Nothing is shown at 0: one exhausted resource alone ends nothing, so there is no count to warn about.
        Assert.AreEqual("", HudModel.From(bridge, Text).Exhausted);
        Assert.AreEqual(DisplayStyle.None, label.style.display.value);
        var limit = bridge.Content.RulesAt(bridge.State.Date).Mvp!.DefeatTurns!.Value;
        bridge.State.ExhaustedTurns = 1;
        hud.Render();
        Assert.AreEqual(Text.Format("hud.exhausted", 1, limit), label.text);
        Assert.AreEqual(DisplayStyle.Flex, label.style.display.value);
        // The value carries left-to-right marks in a Hebrew line (U+200E, #543), as every Hebrew value does.
        var he = HudModel.From(bridge, He).Exhausted;
        Assert.AreEqual($"הכסף והמזון אזלו: תור 1 מתוך {limit}", he.Replace("\u200E", ""));
    }

    // ---- Social cohesion (#380): a resource meter, only in the GDD loop, from the morale indicator ----

    /// <summary>The owner's ruling of 15 October 2026 (#380): Social cohesion on the top bar as a resource meter, in the GDD
    /// loop. Its value is the morale indicator (R-NAT-001) on the 0-100 scale, as the other 0..1 meters; after a turn it
    /// shows the change, and its tooltip says both, under the caption the bar shows (Hebrew: לכידות חברתית).</summary>
    [Test]
    public void TheGddGameShowsSocialCohesion()
    {
        using var ui = new UiTestKit();
        var bridge = GddBridge();
        using var hud = new HudPresenter(ui.Root, bridge, Text);
        var meter = ui.Q<VisualElement>("meter-cohesion");
        Assert.AreEqual(DisplayStyle.Flex, meter.style.display.value, "shown in the GDD loop");
        Assert.AreEqual(Text["hud.caption.cohesion"], meter.Q<Label>(className: "meter-name").text);
        Assert.AreEqual("rings", meter.Q<UiIcon>().Glyph);
        Assert.Greater(bridge.State.Indicators["morale"], 0.0, "precondition: the indicator starts at its base");
        Assert.AreEqual(PlayerText.Percent(bridge.State.Indicators["morale"]), ui.Q<Label>("cohesion-value").text);
        Assert.AreEqual("", ui.Q<Label>("cohesion-delta").text, "no change before the first turn");
        Assert.AreEqual($"Social cohesion: {PlayerText.Percent(bridge.State.Indicators["morale"])}", meter.tooltip);
        bridge.EndTurn();
        var prev = bridge.Session.Previous!; var now = bridge.State;
        now.Indicators["morale"] = 0.634; prev.Indicators["morale"] = 0.584;         // 58% -> 63%: up 5 points
        hud.Render();
        Assert.AreEqual("63%", ui.Q<Label>("cohesion-value").text);
        Assert.AreEqual("+5%", ui.Q<Label>("cohesion-delta").text);
        Assert.IsTrue(ui.Q<Label>("cohesion-delta").ClassListContains("delta-up"));
        Assert.AreEqual(Text.Format("hud.say_up", Text["hud.caption.cohesion"], "63%", Text.Format("hud.say_points", 5)), meter.tooltip);
        now.Indicators["morale"] = 0.574;                                     // 58% -> 57%: down 1 point
        hud.Render();
        Assert.AreEqual("-1%", ui.Q<Label>("cohesion-delta").text);
        Assert.IsTrue(ui.Q<Label>("cohesion-delta").ClassListContains("delta-down"));
        Assert.AreEqual(Text.Format("hud.say_down", Text["hud.caption.cohesion"], "57%", Text.Format("hud.say_point", 1)), meter.tooltip);
        using var heUi = new UiTestKit();
        using var heHud = new HudPresenter(heUi.Root, GddBridge(), He);
        Assert.AreEqual("לכידות חברתית", heUi.Q<VisualElement>("meter-cohesion").Q<Label>(className: "meter-name").text);
        StringAssert.StartsWith("לכידות חברתית: ", heUi.Q<VisualElement>("meter-cohesion").tooltip);
    }

    /// <summary>The legacy loop has no Social cohesion (its cities do not exist): the meter is hidden, as the score is.</summary>
    [Test]
    public void TheLegacyLoopShowsNoSocialCohesion()
    {
        SimBridge LegacyBridge() => new SimBridge(GameSession.New(SimBridgeGddTests.Legacy, GoldenRun.Seed, Mode.Historical), Text);
        using var ui = new UiTestKit();
        using var hud = new HudPresenter(ui.Root, LegacyBridge(), Text);
        Assert.AreEqual(DisplayStyle.None, ui.Q<VisualElement>("meter-cohesion").style.display.value);
        Assert.AreEqual("", ui.Q<Label>("cohesion-value").text);
    }

    [Test]
    public void EndTurnAdvancesTheGameAndShowsChanges()
    {
        using var ui = new UiTestKit();
        var bridge = NewBridge();
        new HudPresenter(ui.Root, bridge, Text);
        foreach (var id in bridge.NeedsOrders.ToList()) bridge.Skip(id);
        ui.Press("end-turn");
        Assert.AreEqual(1, bridge.State.Turn);
        Assert.AreEqual(Text.Format("hud.turn", 1), ui.Q<Label>("turn").text);
        Assert.AreEqual("15 June 1948", ui.Q<Label>("date").text);   // monthly turns since the GDD cutover
        var arrivals = bridge.Session.Last!.Why.Where(w => w.System == "population").Sum(w => w.Delta);
        Assert.AreEqual(arrivals.ToString("N0", System.Globalization.CultureInfo.InvariantCulture), ui.Q<Label>("immigration-value").text);
        var s0 = bridge.Session.Previous!; var s1 = bridge.State;
        var d = System.Math.Round((s1.Treasury - s1.Debt) - (s0.Treasury - s0.Debt), 1, System.MidpointRounding.AwayFromZero);
        Assert.AreNotEqual(0.0, d, "the test needs a turn with a treasury change");
        Assert.AreEqual(PlayerText.MoneyChange(C, "treasury", d), ui.Q<Label>("treasury-delta").text);
        Assert.AreEqual(d < 0, ui.Q<Label>("treasury-delta").ClassListContains("delta-down"));
        Assert.AreEqual(d > 0, ui.Q<Label>("treasury-delta").ClassListContains("delta-up"));
    }

    [Test]
    public void QueuedOrdersSpendAttentionUpFront()
    {
        var bridge = NewBridge();
        Assert.IsNull(bridge.Queue(new SetMobilization(1.0)));      // at war each order costs 2
        Assert.AreEqual(2.0, bridge.AttentionLeft, 1e-9);
        Assert.IsNull(bridge.Queue(new SetMobilization(0.9)));      // replaces the first: still one order
        Assert.AreEqual(1, bridge.Queued.Count);
        Assert.IsNull(bridge.Queue(new SecurityOrder(-1)));
        Assert.AreEqual(Text.Format("order.no_attention", 2.0, 0.0), bridge.Queue(new SetPolicy("rationing", 1)));
    }

    [Test]
    public void RefusedOrdersAreShownWithTheirReason()
    {
        using var ui = new UiTestKit();
        var bridge = NewBridge();
        var text = Text;
        new HudPresenter(ui.Root, bridge, text);
        new ToastPresenter(ui.Root, bridge, text);
        Assert.AreEqual(DisplayStyle.None, ui.Q<Label>("toast").style.display.value);
        bridge.Queue(new SetPolicy(C.At(bridge.State.Date).Policies[0].Id, 2));     // a policy in force now at an impossible level: the sim refuses it
        foreach (var id in bridge.NeedsOrders.ToList()) bridge.Skip(id);
        ui.Press("end-turn");
        Assert.AreEqual("Not done: Policy level must be between 0 and 1", ui.Q<Label>("toast").text);
        Assert.AreEqual(DisplayStyle.Flex, ui.Q<Label>("toast").style.display.value);
    }

    /// <summary>ScreenNav's motion as the test run found it (off in edit mode), put back after every test: an assertion
    /// inside a nested coroutine skips the outer one's finally.</summary>
    static readonly System.Func<bool> PlayModeMotion = ScreenNav.Moves;
    [TearDown] public void StillWindows() => ScreenNav.Moves = PlayModeMotion;

    /// <summary>Yields until <paramref name="done"/> holds, at most 3 s: an edit-mode panel updates its styles and layout
    /// only now and then, not on every yield.</summary>
    static IEnumerator Until(System.Func<bool> done)
    {
        var t0 = Time.realtimeSinceStartup;
        while (!done() && Time.realtimeSinceStartup - t0 < 3f) yield return null;
    }

    /// <summary>#1106: a window (a side-menu screen, the decision card) opens in ScreenNav.OpeningClass, small and
    /// transparent, for one layout, then grows and fades in over 0.5 s; on close it shrinks over 0.3 s (ClosingClass), out
    /// of reach, and leaves the layout when that transition ends. An EditMode panel does not run the transitions' clock,
    /// so the test checks the classes, the resolved transitions, and sends the transitions' ends itself.</summary>
    static IEnumerator OpensAndCloses(VisualElement window, System.Action open, System.Action close, string what)
    {
        open();
        Assert.AreEqual(DisplayStyle.Flex, window.style.display.value, what + " shows at once");
        Assert.IsTrue(window.ClassListContains(ScreenNav.OpeningClass), what + " starts small and transparent");
        Assert.IsTrue(ScreenNav.IsOpen(window), what + " is open");
        yield return Until(() => !window.ClassListContains(ScreenNav.OpeningClass));
        Assert.IsFalse(window.ClassListContains(ScreenNav.OpeningClass), what + ": the start state lasts one layout, then it grows");
        yield return Until(() => window.resolvedStyle.transitionDuration.First().value > 0.4f);
        Assert.AreEqual(0.5f, window.resolvedStyle.transitionDuration.First().value, 1e-4, what + ": scale-up and fade-in, 0.5 s");
        CollectionAssert.AreEquivalent(new[] { "scale", "opacity" }, window.resolvedStyle.transitionProperty.Select(p => p.ToString()), what);
        close();
        Assert.IsTrue(window.ClassListContains(ScreenNav.ClosingClass), what + " shrinks");
        Assert.IsFalse(ScreenNav.IsOpen(window), what + " counts as closed while it shrinks");
        Assert.IsFalse(window.enabledSelf, what + ": out of reach while it shrinks (#400)");
        Assert.AreEqual(DisplayStyle.Flex, window.style.display.value, what + " stays in view while it shrinks");
        yield return Until(() => window.resolvedStyle.transitionDuration.First().value < 0.4f);
        Assert.AreEqual(0.3f, window.resolvedStyle.transitionDuration.First().value, 1e-4, what + ": scale-down, 0.3 s");
        Assert.AreEqual("scale", window.resolvedStyle.transitionProperty.Single().ToString(), what + ": a scale-down, no fade");
        End(window, "opacity");                                   // the grow's fade, when it closes within 0.5 s of opening
        Assert.AreEqual(DisplayStyle.Flex, window.style.display.value, what + ": only the end of the shrink hides it");
        open();                                                   // opened again while it shrinks: it grows back from there
        Assert.IsFalse(window.ClassListContains(ScreenNav.ClosingClass), what + " grows back");
        Assert.IsFalse(window.ClassListContains(ScreenNav.OpeningClass), what + ": from where it is, not from the start state");
        Assert.IsTrue(window.enabledSelf && ScreenNav.IsOpen(window), what + " is open and in reach again");
        End(window, "scale");                                     // the interrupted shrink's end, late: ignored
        Assert.AreEqual(DisplayStyle.Flex, window.style.display.value, what + " stays open");
        close();
        End(window, "scale");
        Assert.AreEqual(DisplayStyle.None, window.style.display.value, what + " leaves the layout when the shrink ends");
        Assert.IsFalse(window.ClassListContains(ScreenNav.ClosingClass), what);
        open(); close();                                          // closed before its first layout (two presses in one frame)
        Assert.AreEqual(DisplayStyle.None, window.style.display.value, what + ": nothing to shrink from, it hides at once");
        Assert.IsFalse(window.ClassListContains(ScreenNav.OpeningClass) || window.ClassListContains(ScreenNav.ClosingClass), what);
    }

    /// <summary>Sends the end of a transition of <paramref name="property"/> on <paramref name="window"/>, as the panel does.</summary>
    static void End(VisualElement window, string property)
    {
        using var e = TransitionEndEvent.GetPooled(new StylePropertyName(property), 0.3);
        e.target = window; window.SendEvent(e);
    }

    [UnityTest]
    public IEnumerator WindowsScaleUpAndFadeInWhenTheyOpenAndScaleDownWhenTheyClose()
    {
        ScreenNav.Moves = () => true;   // play mode's motion; StillWindows puts it back (an EditMode panel ticks only now and then: Until)
        using var ui = new UiTestKit();
        using var nav = new ScreenNav(ui.Root);
        foreach (var s in ScreenNav.Screens)
            yield return OpensAndCloses(ui.Q<VisualElement>("screen-" + s), () => ui.Press("nav-" + s), () => ui.Press("nav-" + s), s);
        using var card = new EventCardPresenter(ui.Root, NewBridge(), Text, null);   // a new game opens on a decision
        var element = ui.Q<VisualElement>("event-card");
        card.Collapse();
        yield return Until(() => element.style.display.value == DisplayStyle.None);
        yield return OpensAndCloses(element, card.Reopen, card.Collapse, "the decision card");
    }

    /// <summary>#1175 review: a window closed while it still grows (within 0.5 s of opening) retargets the scale
    /// transition, and the panel sends a TransitionCancelEvent for the grow. That must not hide it: it shrinks, and only the
    /// shrink's end or ScreenNav's safety net (ClosingNetMs) takes it out of the layout.</summary>
    [UnityTest]
    public IEnumerator AWindowClosedWhileItGrowsStillShrinks()
    {
        ScreenNav.Moves = () => true;   // StillWindows puts it back
        using var ui = new UiTestKit();
        using var nav = new ScreenNav(ui.Root);
        var screen = ScreenNav.Screens.First();
        var window = ui.Q<VisualElement>("screen-" + screen);
        ui.Press("nav-" + screen);
        yield return Until(() => !window.ClassListContains(ScreenNav.OpeningClass));
        ui.Press("nav-" + screen);                                // closed mid-grow
        var closedAt = Time.realtimeSinceStartup;
        using (var e = TransitionCancelEvent.GetPooled(new StylePropertyName("scale"), 0.2))
        {
            e.target = window; window.SendEvent(e);               // the grow, cancelled by the shrink
        }
        Assert.AreEqual(DisplayStyle.Flex, window.style.display.value, "the cancelled grow does not hide it: it shrinks");
        Assert.IsTrue(window.ClassListContains(ScreenNav.ClosingClass), "still shrinking");
        // a quiet EditMode panel runs its scheduler (the safety net) only on player-loop requests (SafeAreaTests)
        while (window.style.display.value != DisplayStyle.None && Time.realtimeSinceStartup - closedAt < 3f)
        {
            EditorApplication.QueuePlayerLoopUpdate();
            yield return null;
        }
        // a scale TransitionEndEvent from the panel (EndClosing) or the safety net (ClosingNetMs), whichever comes first:
        // on a busy machine the panel's end can come well before ClosingNetMs (0.30 s in #1216, 0.06 s in a rerun under
        // load), so only the end state is asserted, not the elapsed time
        Assert.AreEqual(DisplayStyle.None, window.style.display.value, "a transition end or the safety net hides it");
        Assert.IsFalse(window.ClassListContains(ScreenNav.ClosingClass) || window.ClassListContains(ScreenNav.OpeningClass),
            "it leaves the layout through Hide");
    }

    [Test]
    public void NavigationOpensOneScreenAtATime()
    {
        using var ui = new UiTestKit();
        var nav = new ScreenNav(ui.Root);
        Assert.IsNull(nav.Current);
        ui.Press("nav-budget");
        Assert.AreEqual("budget", nav.Current);
        Assert.AreEqual(DisplayStyle.Flex, ui.Q<VisualElement>("screen-budget").style.display.value);
        Assert.AreEqual(DisplayStyle.None, ui.Q<VisualElement>("screen-cabinet").style.display.value);
        ui.Press("nav-cabinet");
        Assert.AreEqual(DisplayStyle.None, ui.Q<VisualElement>("screen-budget").style.display.value);
        ui.Press("nav-cabinet");
        Assert.IsNull(nav.Current);
    }

    [UnityTest]
    public IEnumerator AtStartNoScreenIsShownAndTheMiddleOfTheScreenIsNotUi()
    {
        using var ui = new UiTestKit();
        var bridge = NewBridge();
        new ScreenNav(ui.Root);
        new ToastPresenter(ui.Root, bridge, Text);
        foreach (var name in new[] { "screen-cabinet", "screen-budget", "screen-defence", "screen-why", "toast" })
            Assert.AreEqual(DisplayStyle.None, ui.Q<VisualElement>(name).style.display.value, name);
        for (int i = 0; i < 10 && float.IsNaN(ui.Root.worldBound.width); i++) yield return null;
        var panel = ui.Root.panel;
        var middle = ui.Root.worldBound.center;
        Assert.IsNull(panel.Pick(middle), "the middle of the screen must reach the map");
        // screen coordinates are y-up; UiPointer flips them
        var screenH = (float)Screen.height;
        var asScreen = new Vector2(middle.x, screenH - middle.y);
        Assert.IsFalse(UiPointer.IsOverUi(panel, asScreen, screenH));
    }

    [Test]
    public void BadIdsAreRefusedNotThrownAndTheNextTurnRuns()
    {
        var bridge = NewBridge();
        var refusals = new System.Collections.Generic.List<string>();
        bridge.Refused += refusals.Add;
        Assert.IsNotNull(bridge.Queue(new SetPolicy(null!, 1)));
        Assert.IsNotNull(bridge.Queue(new SetPolicy("", 1)));
        Assert.IsNotNull(bridge.Queue(new SetPolicy("curfew", 1)));
        Assert.IsNotNull(bridge.Queue(new Appoint("pm", "free text")));
        Assert.IsNotNull(bridge.Queue(new Appoint(null!, null!)));
        Assert.IsNotNull(bridge.Queue(new ChooseEventOption("nope", "nope")));
        Assert.IsNotNull(bridge.Queue(new ChooseEventOption(C.Events[0].Id, "nope")));
        Assert.IsNotNull(bridge.Queue(new MapAction("moat", 0, 0)));
        Assert.IsNotNull(bridge.Queue(new AllocateBudget(new System.Collections.Generic.Dictionary<string, double> { ["nowhere"] = 1 })));
        Assert.IsNotNull(bridge.Queue(new AllocateBudget(null!)));
        Assert.AreEqual(0, bridge.Queued.Count);
        Assert.AreEqual(10, refusals.Count);
        Assert.DoesNotThrow(() => bridge.EndTurn());
        Assert.AreEqual(1, bridge.State.Turn);
    }

    [Test]
    public void AQueuedBudgetIsACopy()
    {
        var bridge = NewBridge();
        var shares = new System.Collections.Generic.Dictionary<string, double>(C.Rules.BudgetStart);
        Assert.IsNull(bridge.Queue(new AllocateBudget(shares)));
        var key = shares.Keys.First();
        shares[key] = 99;
        shares["nowhere"] = 1;
        var queued = (AllocateBudget)bridge.Queued[0];
        Assert.AreEqual(C.Rules.BudgetStart[key], queued.Shares[key], 1e-12);
        Assert.IsFalse(queued.Shares.ContainsKey("nowhere"));
    }

    [Test]
    public void ADisposedPresenterHearsNothing()
    {
        using var ui = new UiTestKit();
        var bridge = NewBridge();
        var hud = new HudPresenter(ui.Root, bridge, Text);
        var toast = new ToastPresenter(ui.Root, bridge, Text);
        var nav = new ScreenNav(ui.Root);
        hud.Dispose(); toast.Dispose(); nav.Dispose();
        ui.Q<Label>("turn").text = "untouched";
        ui.Q<Label>("toast").text = "untouched";
        bridge.Queue(new SetPolicy("curfew", 1));
        bridge.EndTurn();
        ui.Press("end-turn");
        ui.Press("nav-budget");
        Assert.AreEqual("untouched", ui.Q<Label>("turn").text);
        Assert.AreEqual("untouched", ui.Q<Label>("toast").text);
        Assert.AreEqual(1, bridge.State.Turn, "End Turn button no longer wired (only the direct call ran)");
        Assert.IsNull(nav.Current);
        Assert.AreEqual(DisplayStyle.None, ui.Q<VisualElement>("screen-budget").style.display.value);
    }

    [Test]
    public void ToastShowsQueueRefusalsAndClearsOnTheNextChange()
    {
        using var ui = new UiTestKit();
        var bridge = NewBridge();
        new ToastPresenter(ui.Root, bridge, Text);
        LogAssert.Expect(LogType.Log, new System.Text.RegularExpressions.Regex("unknown policy 'curfew'"));   // the id: log only (#622)
        Assert.IsNotNull(bridge.Queue(new SetPolicy("curfew", 1)));
        Assert.AreEqual(Text.Format("toast.refused", Text.Format("order.unknown", Text["order.kind.policy"])), ui.Q<Label>("toast").text);
        Assert.AreEqual(DisplayStyle.Flex, ui.Q<Label>("toast").style.display.value);
        Assert.IsNull(bridge.Queue(new SecurityOrder(-1)));
        Assert.AreEqual(DisplayStyle.None, ui.Q<Label>("toast").style.display.value);
    }

    [Test]
    public void ChangesShowSignsAndZeroDeltasAreEmpty()
    {
        using var ui = new UiTestKit();
        var bridge = NewBridge();
        bridge.EndTurn();
        var hud = new HudPresenter(ui.Root, bridge, Text);
        var prev = bridge.Session.Previous!;
        var now = bridge.State;
        prev.Treasury = now.Treasury - now.Debt + prev.Debt - 5;          // up by 5
        hud.Render();
        Assert.AreEqual("IL\u00A0+5.0m", ui.Q<Label>("treasury-delta").text);
        Assert.IsTrue(ui.Q<Label>("treasury-delta").ClassListContains("delta-up"));
        Assert.IsFalse(ui.Q<Label>("treasury-delta").ClassListContains("delta-down"));
        prev.Treasury = now.Treasury - now.Debt + prev.Debt + 0.04;       // down by 0.04: rounds to zero, never "-0.0"
        hud.Render();
        Assert.AreEqual("", ui.Q<Label>("treasury-delta").text);
        Assert.IsFalse(ui.Q<Label>("treasury-delta").ClassListContains("delta-down"));
        prev.Treasury = now.Treasury - now.Debt + prev.Debt - 0.04;
        hud.Render();
        Assert.AreEqual("", ui.Q<Label>("treasury-delta").text);
    }

    [Test]
    public void TheHudIsTheSameUnderAGermanCulture()
    {
        var bridge = NewBridge();
        bridge.EndTurn();
        var inv = HudModel.From(bridge, Text);
        var old = System.Globalization.CultureInfo.CurrentCulture;
        try
        {
            System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo("de-DE");
            var de = HudModel.From(bridge, Text);
            Assert.AreEqual(JsonUtility.ToJson(Flat(inv)), JsonUtility.ToJson(Flat(de)));
        }
        finally { System.Globalization.CultureInfo.CurrentCulture = old; }
    }

    [System.Serializable] class FlatHud { public string[] V = new string[0]; }
    static FlatHud Flat(HudModel m) => new FlatHud
    {
        V = new[] { m.Year, m.Turn, m.Date, m.Attention, m.SecurityLevel,
            m.Treasury.Value, m.Treasury.Delta, m.Immigration.Value, m.Immigration.Delta, m.Security.Value, m.Security.Delta,
            m.Support.Value, m.Support.Delta, m.Standing.Value, m.Standing.Delta, m.Fx.Value, m.Fx.Delta },
    };

    [Test]
    public void ReplaceDropsOrdersAndBeforeLastSpansTwoTurns()
    {
        var bridge = NewBridge();
        Assert.IsNull(bridge.BeforeLast);
        bridge.EndTurn();
        Assert.IsNull(bridge.BeforeLast);                        // only one step has run
        var first = bridge.Session.Last;
        bridge.EndTurn();
        Assert.AreSame(first, bridge.BeforeLast);
        Assert.AreNotSame(first, bridge.Session.Last);
        bridge.Queue(new SecurityOrder(-1));
        int changed = 0; bridge.Changed += () => changed++;
        bridge.Replace(GameSession.New(C, GoldenRun.Seed, Mode.Historical));
        Assert.AreEqual(1, changed);
        Assert.AreEqual(0, bridge.Queued.Count);
        Assert.IsNull(bridge.BeforeLast);
        Assert.AreEqual(0, bridge.State.Turn);
    }

    /// <summary>#622: a refusal names the kind of thing and never shows the content id or the exception's message, in
    /// either language; both stay in the log for a bug report.</summary>
    [TestCase(false)]
    [TestCase(true)]
    public void ARefusalShowsNoIdOrExceptionTextInEitherLanguage(bool hebrew)
    {
        var text = hebrew ? UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text, "strings.he.yaml") : Text;
        LogAssert.Expect(LogType.Log, new System.Text.RegularExpressions.Regex("unknown policy 'curfew'"));
        var unknown = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text).Queue(new SetPolicy("curfew", 1));
        Assert.AreEqual(text.Format("order.unknown", text["order.kind.policy"]), unknown);   // the kind in the UI's language (#595)
        StringAssert.DoesNotContain("curfew", unknown);

        LogAssert.Expect(LogType.Exception, new System.Text.RegularExpressions.Regex("stack detail 42"));
        var failing = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text,
            (s, cmds) => throw new System.InvalidOperationException("stack detail 42"));
        Assert.IsNull(failing.Queue(new SecurityOrder(-1)));
        var reason = failing.EndTurn().Rejected.Single().Reason;
        Assert.AreEqual(text["order.failed"], reason);
        StringAssert.DoesNotContain("stack detail", reason);
    }

    /// <summary>Any exception from the sim (not only ArgumentException; final review M7) keeps the state, clears the queue
    /// and shows the reason: End Turn can never soft-lock. An unexpected kind is also logged in full.</summary>
    [TestCase(typeof(System.ArgumentException))]
    [TestCase(typeof(System.InvalidOperationException))]
    [TestCase(typeof(System.NullReferenceException))]
    public void ABatchTheSimRefusesOutrightKeepsTheStateAndShowsTheReason(System.Type kind)
    {
        using var ui = new UiTestKit();
        // Every kind leaves a console trace (rereview): a refusal as a warning, anything else as the full exception.
        if (kind == typeof(System.ArgumentException)) LogAssert.Expect(LogType.Warning, new System.Text.RegularExpressions.Regex("End Turn refused.*boom"));
        else LogAssert.Expect(LogType.Exception, new System.Text.RegularExpressions.Regex("boom"));
        var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text,
            (s, cmds) => throw (System.Exception)System.Activator.CreateInstance(kind, "boom")!);
        new ToastPresenter(ui.Root, bridge, Text);
        var order = new SecurityOrder(-1);
        Assert.IsNull(bridge.Queue(order));
        System.Collections.Generic.IReadOnlyList<Rejection>? seen = null;
        bridge.TurnEnded += r => seen = r;
        var hash = bridge.State.Hash();
        Assert.DoesNotThrow(() => bridge.EndTurn());
        Assert.AreEqual(hash, bridge.State.Hash());
        Assert.AreEqual(0, bridge.Queued.Count);
        Assert.IsNull(bridge.BeforeLast);
        Assert.AreSame(order, seen![0].Command);
        Assert.AreEqual(Text.Format("toast.refused", Text["order.failed"]), ui.Q<Label>("toast").text);   // "boom": the log only (#622)
    }

    /// <summary>#912: the sim and autosave have advanced before End Turn notifies presenters. A broken presenter is
    /// logged, but cannot leave every subscriber registered after it showing the previous turn.</summary>
    [Test]
    public void AThrowingEndTurnSubscriberDoesNotStopTheOthers()
    {
        var bridge = NewBridge();
        var changed = 0;
        var ended = 0;
        bridge.Changed += () => throw new System.InvalidOperationException("changed presenter failed");
        bridge.Changed += () => changed++;
        bridge.TurnEnded += _ => throw new System.InvalidOperationException("turn-ended presenter failed");
        bridge.TurnEnded += _ => ended++;
        LogAssert.Expect(LogType.Exception, new System.Text.RegularExpressions.Regex("changed presenter failed"));
        LogAssert.Expect(LogType.Exception, new System.Text.RegularExpressions.Regex("turn-ended presenter failed"));

        Assert.DoesNotThrow(() => bridge.EndTurn());

        Assert.AreEqual(1, bridge.State.Turn, "the simulation stepped exactly once");
        Assert.AreEqual(1, changed, "later Changed subscribers still refresh");
        Assert.AreEqual(1, ended, "later TurnEnded subscribers still run");
    }

    /// <summary>Playtest 1, item 11: pressing the open screen's button closes it, every time, with every presenter
    /// GameRoot creates listening, with the button focused (as after a mouse click), and across End Turn.</summary>
    [Test]
    public void PressingTheOpenScreensButtonClosesItAcrossTurns()
    {
        using var ui = new UiTestKit();
        var bridge = NewBridge();
        var portraits = ScriptableObject.CreateInstance<PortraitCatalog>();
        var owned = new System.Collections.Generic.List<System.IDisposable>();   // fix round 1: nothing outlives the test
        T Own<T>(T d) where T : System.IDisposable { owned.Add(d); return d; }
        try
        {
            Own(new HudPresenter(ui.Root, bridge, Text));
            var nav = Own(new ScreenNav(ui.Root));
            Own(new EventCardPresenter(ui.Root, bridge, Text, portraits));
            Own(new DefencePresenter(ui.Root, bridge, Text));
            Own(new BudgetPresenter(ui.Root, bridge, Text));
            Own(new WhyPresenter(ui.Root, bridge, Text));
            Own(new CabinetPresenter(ui.Root, bridge, Text, portraits));
            DisplayStyle Shown(string screen) => ui.Q<VisualElement>("screen-" + screen).style.display.value;
            for (int turn = 0; turn < 4; turn++)
            {
                foreach (var screen in ScreenNav.Screens)
                {
                    ui.Press("nav-" + screen);
                    Assert.AreEqual(DisplayStyle.Flex, Shown(screen), $"turn {turn}: {screen} did not open");
                    ui.Q<Button>("nav-" + screen).Focus();
                    ui.Press("nav-" + screen);
                    Assert.AreEqual(DisplayStyle.None, Shown(screen), $"turn {turn}: {screen} did not close");
                    Assert.IsNull(nav.Current);
                }
                var open = ScreenNav.Screens[turn % ScreenNav.Screens.Length];
                ui.Press("nav-" + open);
                foreach (var id in bridge.NeedsOrders.ToList()) bridge.Skip(id);
                ui.Press("end-turn");
                Assert.AreEqual(turn + 1, bridge.State.Turn, $"turn {turn}: End Turn did not run");
                Assert.AreEqual(DisplayStyle.Flex, Shown(open), $"turn {turn}: End Turn closed {open}");
                ui.Press("nav-" + open);
                Assert.AreEqual(DisplayStyle.None, Shown(open), $"turn {turn}: {open} did not close after End Turn");
            }
        }
        finally
        {
            DisposeAll(owned);
            Object.DestroyImmediate(portraits);
        }
        // Every presenter let go of the bridge and the buttons: a later turn writes nothing and End Turn does nothing.
        ui.Q<Label>("turn").text = "untouched";
        ui.Q<Label>("cabinet-coalition").text = "untouched";
        bridge.EndTurn();
        var turnAfter = bridge.State.Turn;
        ui.Press("end-turn");
        Assert.AreEqual("untouched", ui.Q<Label>("turn").text, "HudPresenter still listens");
        Assert.AreEqual("untouched", ui.Q<Label>("cabinet-coalition").text, "CabinetPresenter still listens");
        Assert.AreEqual(turnAfter, bridge.State.Turn, "End Turn is still wired");
    }

    /// <summary>Disposes test-owned presenters newest first, as GameRoot does.</summary>
    static void DisposeAll(System.Collections.Generic.List<System.IDisposable> owned)
    {
        for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();
        owned.Clear();
    }

    /// <summary>Fix round 1, I2: the top-bar changes carry their unit: IL for the treasury, $ for foreign currency, % for
    /// the 0-100 meters.</summary>
    [Test]
    public void EveryTopBarChangeCarriesItsUnit()
    {
        var bridge = NewBridge();
        bridge.EndTurn();
        var prev = bridge.Session.Previous!;
        var now = bridge.State;
        prev.FxReserves = now.FxReserves + 2;                                // down by 2
        prev.Indicators["security"] = now.Indicators["security"] - 0.05;    // up 5 points
        prev.Treasury = now.Treasury - now.Debt + prev.Debt + 3;            // down by 3
        var m = HudModel.From(bridge, Text);
        Assert.AreEqual("$-2.0m", m.Fx.Delta);
        Assert.AreEqual("+5%", m.Security.Delta);
        Assert.AreEqual("IL\u00A0-3.0m", m.Treasury.Delta);
    }

    /// <summary>Fix round 2 (N4, N5): no script rescales a sim number for display itself: 0..1 values go through
    /// PlayerText.Scale / Percent / PercentChange. Scans all of Assets/Scripts for "* 100", "100f", "/ 0.01" and "100.0".
    /// Allowed, each for a reason that is not a displayed number:</summary>
    static readonly (string file, string contains, string why)[] AllowedScale =
    {
        ("MinimapPresenter.cs", "Length.Percent(", "the view frame's position and size in percent of the picture (layout, not text)"),
        ("PortraitFraming.cs", "offset / (h - boxH) * 100f", "a portrait's background-position-y in percent (layout, not text)"),
        ("UiBar.cs", "Length.Percent(", "a bar's fill width and tick position in percent of its track (layout, not text)"),
        ("MapShaderGlobals.cs", "RiftHazeTopM = -100f", "a real elevation in metres for the rift haze (shader input, not a displayed number)"),
        ("SettlementKits.cs", "DefaultHouses = 100f", "the owner's symbolic scale for houses and trees (100x real size), not a displayed number"),
        ("RouteLayer.cs", "CorridorMarginM = 100f", "a clearance in map metres that kit buildings and trees keep from a route (geometry, not a displayed number)"),
        ("CameraController.cs", "PixelsPerNotch = 100f", "wheel pixels in one mouse notch, to scale the browser's wheel events (input, not a displayed number)"),
        ("WildlifeLayer.cs", "MinimumCliffElevationM = 100f", "a real elevation in metres an ibex hex must reach (placement, not a displayed number)"),
        ("SettingsPresenter.cs", "Level(int percent) => percent / 100.0", "the UI scale's stored percents (#40) to the level PlayerText.Percent formats (1.25 for 125%); it never formats text itself"),
        ("VillageMill.cs", "vy + 100f", "a bearing in degrees round the hex tile, where the village mill's well stands (placement, not a displayed number)"),
    };

    [Test]
    public void NoScriptRescalesADisplayedNumberItself()
    {
        var pattern = new System.Text.RegularExpressions.Regex(@"\*\s*100\b|\b100f\b|/\s*0\.01\b|\b100\.0\b|\*\s*100f");
        foreach (var f in System.IO.Directory.GetFiles("Assets/Scripts", "*.cs", System.IO.SearchOption.AllDirectories))
            foreach (var line in System.IO.File.ReadAllLines(f))
                if (pattern.IsMatch(line) && !System.Array.Exists(AllowedScale, a => System.IO.Path.GetFileName(f) == a.file && line.Contains(a.contains)))
                    Assert.Fail($"{System.IO.Path.GetFileName(f)}: {line.Trim()}");
        foreach (var a in AllowedScale) Assert.IsNotEmpty(a.why);
    }

    /// <summary>Fix round 2 (N4): percentages have one formatter, PlayerText; no UI string formats a number as "%" itself.</summary>
    [Test]
    public void NoUiStringFormatsAPercentItself()
    {
        var yaml = AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text;
        foreach (var line in yaml.Split('\n'))
            Assert.IsFalse(System.Text.RegularExpressions.Regex.IsMatch(line, @"\{\d+:[^}]*\}%"), "percent format in strings.en.yaml: " + line);
    }

    /// <summary>Fix round 1, M3: the top-bar captions are the content names. Since #622 they are in the sentence case the
    /// content and the rest of the strings use, so a caption is the content name as written (it was Title Case before);
    /// Immigration and Public support are UI quantities with no content name. Money carries "(net)" after its name: the top
    /// bar shows cash minus debt (#681, owner, 16 October 2026), where the content name, as the causes use it, is cash.</summary>
    [Test]
    public void TopBarCaptionsAreTheContentNames()
    {
        using var ui = new UiTestKit();
        string Caption(string meter) => ui.Q<VisualElement>(meter).Q<Label>(className: "meter-name").text;
        Assert.AreEqual(PlayerText.Target(C, "treasury") + " (net)", Caption("meter-treasury"));
        Assert.AreEqual(PlayerText.Target(C, "security"), Caption("meter-security"));
        Assert.AreEqual(PlayerText.Target(C, "intl_standing"), Caption("meter-standing"));
        Assert.AreEqual(PlayerText.Target(C, "fx_reserves"), Caption("meter-fx"));
    }

    /// <summary>Fix round 2 (R2-3, playtest 1 item 11): two Submit events on the Defence button within one frame (a
    /// double click, or a click plus Enter) each toggle the screen, as ScreenNav documents: no debounce. From closed the
    /// result is closed, from open it is open; the same input always gives the same state.</summary>
    [Test]
    public void TwoPressesInOneFrameToggleTwice()
    {
        using var ui = new UiTestKit();
        var nav = new ScreenNav(ui.Root);
        try
        {
            var defence = ui.Q<Button>("nav-defence");
            var frame = Time.frameCount;
            UiTestKit.Press(defence); UiTestKit.Press(defence);
            Assert.AreEqual(frame, Time.frameCount, "both presses in the same frame");
            Assert.IsNull(nav.Current, "closed -> open -> closed");
            Assert.AreEqual(DisplayStyle.None, ui.Q<VisualElement>("screen-defence").style.display.value);
            UiTestKit.Press(defence);                                   // open it
            UiTestKit.Press(defence); UiTestKit.Press(defence);
            Assert.AreEqual("defence", nav.Current, "open -> closed -> open");
            Assert.AreEqual(DisplayStyle.Flex, ui.Q<VisualElement>("screen-defence").style.display.value);
        }
        finally { nav.Dispose(); }
    }

    /// <summary>Fix round 3 (m-1): the top bar's change agrees with the two values it shows.</summary>
    [Test]
    public void TheShownChangeAgreesWithTheShownValues()
    {
        var bridge = NewBridge();
        bridge.EndTurn();
        var prev = bridge.Session.Previous!;
        var now = bridge.State;
        now.Indicators["security"] = 0.634; prev.Indicators["security"] = 0.626;     // "63%" -> "63%"
        var m = HudModel.From(bridge, Text);
        Assert.AreEqual("63%", m.Security.Value);
        Assert.AreEqual("", m.Security.Delta, "no change shown between two equal shown values");
        Assert.AreEqual(0, m.Security.Sign);
        now.Indicators["security"] = 0.626; prev.Indicators["security"] = 0.624;     // "62%" -> "63%"
        m = HudModel.From(bridge, Text);
        Assert.AreEqual("63%", m.Security.Value);
        Assert.AreEqual("+1%", m.Security.Delta);
        Assert.AreEqual(1, m.Security.Sign);
    }

    static readonly string[] MeterIds = { "treasury", "immigration", "security", "support", "cohesion", "standing", "fx" };
    static UiText He => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings.Replace("strings.en.yaml", "strings.he.yaml")).text, "strings.he.yaml");

    /// <summary>Ends turns until Immigration shows a change (it compares two turns' arrivals), so every meter can show one.
    /// Fails if none comes within 30 turns, so a test built on it never passes by checking nothing.</summary>
    static void PlayUntilImmigrationChanges(SimBridge bridge)
    {
        for (int i = 0; i < 30 && HudModel.From(bridge, Text).Immigration.Sign == 0; i++) bridge.EndTurn();
        Assert.AreNotEqual(0, HudModel.From(bridge, Text).Immigration.Sign, "no Immigration change within 30 turns");
    }

    /// <summary>#398: each meter's tooltip says its value and the change since last turn in words: money in millions
    /// with its currency, the 0-100 meters in points, a count as shown; with no change (turn 0, or one that rounds to
    /// zero) only the caption and the value. The caption is the strings file's (the UI's language).</summary>
    [Test]
    public void EachMeterSaysItsValueAndTheChangeSinceLastTurn()
    {
        using var ui = new UiTestKit();
        var bridge = NewBridge();
        var hud = new HudPresenter(ui.Root, bridge, Text);
        Assert.AreEqual(Text.Format("hud.say", Text["hud.caption.treasury"], Text.Format("hud.say_million", "IL\u00A0", "20.0")), ui.Q<VisualElement>("meter-treasury").tooltip);           // turn 0: no change
        Assert.AreEqual(Text.Format("hud.say", Text["hud.caption.fx"], Text.Format("hud.say_million", "$", "40.0")), ui.Q<VisualElement>("meter-fx").tooltip);
        Assert.AreEqual("Security: 30%", ui.Q<VisualElement>("meter-security").tooltip);
        bridge.EndTurn();
        var prev = bridge.Session.Previous!; var now = bridge.State;
        prev.Treasury = now.Treasury - now.Debt + prev.Debt + 1.4;            // down by 1.4
        prev.FxReserves = now.FxReserves - 2;                                // up by 2
        prev.Indicators["security"] = now.Indicators["security"] - 0.05;    // up 5 points
        prev.Indicators["intl_standing"] = now.Indicators["intl_standing"] + 0.01;   // down 1 point
        hud.Render();
        var net = System.Math.Round(now.Treasury - now.Debt, 1, System.MidpointRounding.AwayFromZero);
        Assert.Greater(net, 0, "the test expects a positive net position after one turn");
        Assert.AreEqual(Text.Format("hud.say_down", Text["hud.caption.treasury"], Text.Format("hud.say_million", "IL\u00A0", net.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture)), Text.Format("hud.say_million", "IL\u00A0", "1.4")), ui.Q<VisualElement>("meter-treasury").tooltip);
        Assert.AreEqual(Text.Format("hud.say_up", Text["hud.caption.fx"], Text.Format("hud.say_million", "$", now.FxReserves.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture)), Text.Format("hud.say_million", "$", "2.0")), ui.Q<VisualElement>("meter-fx").tooltip);
        Assert.AreEqual($"Security: {ui.Q<Label>("security-value").text}, up 5 points since last turn", ui.Q<VisualElement>("meter-security").tooltip);
        Assert.AreEqual($"International support: {ui.Q<Label>("standing-value").text}, down 1 point since last turn", ui.Q<VisualElement>("meter-standing").tooltip);
        // Immigration after one turn has no change yet (it needs two turns of arrivals): the caption and the count only.
        Assert.AreEqual($"Immigration: {ui.Q<Label>("immigration-value").text}", ui.Q<VisualElement>("meter-immigration").tooltip);
        // Every tooltip agrees with the meter's shown change: "up" with a gain, "down" with a loss, neither without one.
        foreach (var id in MeterIds)
        {
            var tip = ui.Q<VisualElement>("meter-" + id).tooltip; var delta = ui.Q<Label>(id + "-delta");
            StringAssert.StartsWith(Text["hud.caption." + id] + ": ", tip, id);
            Assert.AreEqual(delta.ClassListContains("delta-up"), tip.Contains(", up "), id + ": " + tip);
            Assert.AreEqual(delta.ClassListContains("delta-down"), tip.Contains(", down "), id + ": " + tip);
        }
    }

    /// <summary>#398 review S3: the spoken captions are strings (so a Hebrew UI says Hebrew captions), and the English ones
    /// are the captions the bar shows, so the two cannot drift apart. #193: in each language the bar's visible caption is
    /// the caption its tooltip says (HudPresenter sets both from hud.caption.*), so a Hebrew bar no longer shows "Treasury"
    /// over a tooltip that says "אוצר".</summary>
    [Test]
    public void TheSpokenCaptionsAreTheBarsCaptions()
    {
        using var ui = new UiTestKit();
        foreach (var id in MeterIds)
            Assert.AreEqual(ui.Q<VisualElement>("meter-" + id).Q<Label>(className: "meter-name").text, Text["hud.caption." + id], id);
        foreach (var (language, text) in new[] { ("he", He), ("en", Text) })
        {
            using var hud = new HudPresenter(ui.Root, new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text), text);
            foreach (var id in MeterIds)
            {
                var meter = ui.Q<VisualElement>("meter-" + id);
                var shown = meter.Q<Label>(className: "meter-name").text;
                Assert.AreEqual(text["hud.caption." + id], shown, $"{language}: {id}");
                StringAssert.StartsWith(shown + ":", meter.tooltip, $"{language}: {id}'s tooltip says the caption it shows");
            }
        }
    }

    /// <summary>#398: a negative net position, a people count and a Hebrew UI, each through the real path (the
    /// presenter with the UI's own strings). Hebrew uses neutral words for a rise and a fall: on Immigration "עלייה"
    /// and "ירידה" would read as aliyah and emigration (review S2).</summary>
    [Test]
    public void TheSpokenTextCoversNegativeMoneyCountsAndHebrew()
    {
        var bridge = NewBridge();
        PlayUntilImmigrationChanges(bridge);
        var m = HudModel.From(bridge, Text);
        Assert.AreEqual(m.Immigration.Value, m.Immigration.SayValue, "a count is said as shown");
        Assert.AreEqual(m.Immigration.Delta.Substring(1), m.Immigration.SayChange, "a count's change is said without its sign");
        var prev = bridge.Session.Previous!; var now = bridge.State;
        now.Debt = now.Treasury + 3;                                         // net -3.0
        prev.Debt = prev.Treasury - 1;                                       // net +1.0 before: down by 4
        m = HudModel.From(bridge, Text);
        Assert.AreEqual(Text.Format("hud.say_down", "Money", Text.Format("hud.say_million", "IL\u00A0-", "3.0"), Text.Format("hud.say_million", "IL\u00A0", "4.0")), HudModel.Spoken(Text, "Money", m.Treasury));
        using var ui = new UiTestKit();
        var he = He;
        new HudPresenter(ui.Root, bridge, he);
        var said = ui.Q<VisualElement>("meter-treasury").tooltip;
        // The values carry left-to-right marks (U+200E, #543), so the value stays one left-to-right run - "IL -3.0" with the minus next to the number - in a right-to-left line.
        Assert.AreEqual("כסף (נטו): \u200EIL\u00A0-\u200E\u200E3.0\u200E מיליון, קיטון של \u200EIL\u00A0\u200E\u200E4.0\u200E מיליון מאז התור הקודם", said);
        Assert.AreEqual("כסף (נטו): IL\u00A0-3.0 מיליון, קיטון של IL\u00A04.0 מיליון מאז התור הקודם", said.Replace("\u200E", ""));
        foreach (var id in MeterIds)
        {
            var tip = ui.Q<VisualElement>("meter-" + id).tooltip;
            StringAssert.StartsWith(he["hud.caption." + id] + ": ", tip, id);
            Assert.IsFalse(System.Text.RegularExpressions.Regex.IsMatch(tip, "[A-Za-z]{3,}"), $"{id}: English words in the Hebrew text: {tip}");
            Assert.IsFalse(tip.Contains("עלייה של") || tip.Contains("ירידה של"), $"{id}: {tip}");
        }
    }

    /// <summary>#398 review S1: a resumed game shows the changes the player saw before the reload, on all six meters.
    /// GameSession.Load replays the save's own commands and checks the hash, so the replay's last two steps are the
    /// player's; Immigration needs the step before the last, which the session now keeps. Both ways a save arrives: at
    /// start (a new bridge) and through Replace.</summary>
    [Test]
    public void AResumedGameShowsTheChangesOfTheSessionThatSavedIt()
    {
        var played = NewBridge();
        PlayUntilImmigrationChanges(played);
        using var saved = new UiTestKit();
        new HudPresenter(saved.Root, played, Text);
        var saveText = played.Session.Save.Write();
        foreach (var how in new[] { "start", "replace" })
        {
            using var ui = new UiTestKit();
            var loaded = GameSession.Load(C, saveText, out var warnings);
            Assert.IsEmpty(warnings, how);
            SimBridge bridge;
            if (how == "start") bridge = new SimBridge(loaded, Text);
            else { bridge = NewBridge(); bridge.EndTurn(); bridge.EndTurn(); bridge.Replace(loaded); }
            new HudPresenter(ui.Root, bridge, Text);
            Assert.AreEqual(played.State.Turn, bridge.State.Turn, how);
            foreach (var id in MeterIds)
            {
                var before = saved.Q<Label>(id + "-delta"); var after = ui.Q<Label>(id + "-delta");
                Assert.AreEqual(before.text, after.text, $"{how}: {id}");
                Assert.AreEqual(before.ClassListContains("delta-up"), after.ClassListContains("delta-up"), $"{how}: {id}");
                Assert.AreEqual(before.ClassListContains("delta-down"), after.ClassListContains("delta-down"), $"{how}: {id}");
                Assert.AreEqual(saved.Q<VisualElement>("meter-" + id).tooltip, ui.Q<VisualElement>("meter-" + id).tooltip, $"{how}: {id}");
            }
            Assert.AreNotEqual("", ui.Q<Label>("immigration-delta").text, how + ": Immigration's change survives the reload");
        }
    }
}