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.

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

/// <summary>The end screen (#812; D-H4): once the game is over it shows the sim's end report (EndReport.For, #810), formatted
/// only, over the real final state; closing, rebuilding (the language switch) and New Game's first press keep that state and
/// the saved bytes, and only New Game's second press starts over.</summary>
public class EndScreenTests
{
    static readonly Content C = ContentLoader.Load(Paths.Content);
    static UiText En => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
    static UiText He => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text, "strings.he.yaml");

    /// <summary>The HUD, the toast, New Game, the autosave and the end screen on Game.uxml, over a fresh Historical game.</summary>
    sealed class Kit : System.IDisposable
    {
        public readonly UiTestKit Ui = new UiTestKit();
        public readonly SimBridge Bridge; public readonly SaveStore Store; public readonly NewGamePresenter NewGame; public readonly TurnReportPresenter Report;
        public EndScreenPresenter End;
        readonly List<System.IDisposable> owned = new List<System.IDisposable>();
        readonly string dir = Path.Combine(Path.GetTempPath(), "statecraft-end-" + System.Guid.NewGuid().ToString("N"));

        public Kit(UiText text, System.Action<GameState>? setUp = null)
        {
            var session = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
            setUp?.Invoke(session.State);
            Bridge = new SimBridge(session, text);
            Store = new SaveStore(dir);
            owned.Add(new HudPresenter(Ui.Root, Bridge, text));
            var nav = new ScreenNav(Ui.Root); owned.Add(nav);
            owned.Add(Report = new TurnReportPresenter(Ui.Root, Bridge, text, nav));
            var toast = new ToastPresenter(Ui.Root, Bridge, text); owned.Add(toast);
            owned.Add(NewGame = new NewGamePresenter(Ui.Root, Bridge, Store, toast, text, () => GoldenRun.Seed));
            owned.Add(GameStart.Autosave(Bridge, Store, text));
            End = new EndScreenPresenter(Ui.Root, Bridge, text, NewGame.Press);
        }

        /// <summary>The end screen built again over the same game, as Settings' language switch does (GameRoot.SwitchLanguage):
        /// open again only if it was open.</summary>
        public void Rebuild(UiText text)
        {
            bool open = End.IsOpen;
            End.Dispose();
            End = new EndScreenPresenter(Ui.Root, Bridge, text, NewGame.Press, show: open);
        }

        /// <summary>The end screen made again as a load or a restart makes it (GameRoot.Begin with no keep).</summary>
        public void Dispose_End_Reload(UiText text)
        {
            End.Dispose();
            End = new EndScreenPresenter(Ui.Root, Bridge, text, NewGame.Press);
        }

        public VisualElement Q(string name) => Ui.Q<VisualElement>(name);
        public string Line(string name) => Ui.Q<Label>("end-screen-" + name).text;

        public void Dispose()
        {
            End.Dispose();
            for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();
            Ui.Dispose();
            try { if (Directory.Exists(dir)) Directory.Delete(dir, true); } catch (IOException) { }
        }
    }

    /// <summary>Money and Food exhausted and kept so (as the sim's DefeatTests): the debt far over the ceiling, an empty stock
    /// and a foreign currency crisis deep enough to last, so nothing is imported (R-END-001).</summary>
    static void Exhausted(GameState s)
    {
        s.Debt = 1e12;
        s.Food = 0;
        s.FxReserves = -1e12;
        s.ActiveSituations.Add(EconomySystem.FxCrisis);
    }

    /// <summary>A game on its last day, ended as the MVP ends, with the first objective completed a month early.</summary>
    static void Ended(GameState s)
    {
        var first = C.Objectives.Single(o => o.Id == "absorb_immigrants");   // by id: the first in id order, as before R-OBJ-007
        Objectives.Record(C, s, C.RulesAt(s.Date).Mvp!, first.Id, first.ReferenceDate.AddMonths(-1), new List<Cause>());
        s.Date = C.End;
        s.GameOver = GameOverCodes.MvpEnded;
    }

    /// <summary>The state the turn that ends the game leaves when it completes an objective (#2536; the sim's
    /// LastTurnObjectiveCardTests): on the last day, the railway recorded that day and its card waiting, nothing else waiting.</summary>
    static void EndedWithACard(GameState s)
    {
        var r = C.RulesAt(s.Date).Mvp!;
        s.PendingEvents.Clear();
        s.Date = C.End;
        Objectives.Record(C, s, r, "railway", s.Date, new List<Cause>());
        s.FiredEvents.Add("railway_complete");
        s.PendingEvents.Add("railway_complete");
        s.GameOver = GameOverCodes.MvpEnded;
    }

    // R-OBJ-003, R-LOOP-004 (#2536; the owner's choice "Show the card (Recommended)", 4 November 2026): the card of an
    // objective completed on the turn that ended the game shows before the end screen. Its one option is no order and changes
    // nothing; answering it opens the end screen, and the card does not come back when the screens are built again.
    [Test]
    public void AnObjectiveCardOfTheEndingTurnShowsBeforeTheEndScreen()
    {
        using var k = new Kit(En, EndedWithACard);
        using var card = new EventCardPresenter(k.Ui.Root, k.Bridge, En, null);
        Assert.IsTrue(k.Bridge.EndingCardWaiting);
        Assert.IsFalse(k.End.IsOpen, "the card comes first");
        Assert.AreEqual("railway_complete", card.Shown?.Id);
        var option = k.Ui.Q<Button>("option-continue");
        Assert.IsTrue(option.enabledSelf, "its one option can be pressed");
        Assert.AreEqual(C.Events.Single(e => e.Id == "railway_complete").Options.Single().Text, option.text, "with no Attention price");
        var hash = k.Bridge.State.Hash(); var score = k.Bridge.State.Score;

        UiTestKit.Press(option);
        Assert.IsNull(card.Shown, "answered, the card goes");
        Assert.IsFalse(k.Bridge.EndingCardWaiting);
        Assert.IsTrue(k.End.IsOpen, "and the end screen follows");
        Assert.IsEmpty(k.Bridge.Queued, "the answer is no order");
        Assert.AreEqual(hash, k.Bridge.State.Hash(), "and changes nothing in the game");
        Assert.AreEqual(score, k.Bridge.State.Score, "the score is the one the turn recorded");

        k.Rebuild(He);   // the language switch: the same bridge, so the answered card stays answered
        Assert.IsTrue(k.End.IsOpen);
        card.Render();
        Assert.IsNull(card.Shown);
    }

    // R-OBJ-003, R-LOOP-004 (#2536): the real autosave/load path replays an ending objective card into a new bridge.
    // The loaded card still precedes the end screen and its UI answer opens the screen, in both shipped languages.
    [TestCase(false, TestName = "AnEndingObjectiveCardSurvivesAutosaveAndLoad_English")]
    [TestCase(true, TestName = "AnEndingObjectiveCardSurvivesAutosaveAndLoad_Hebrew")]
    public void AnEndingObjectiveCardSurvivesAutosaveAndLoad(bool hebrew)
    {
        var text = hebrew ? He : En;
        var c = ContentLoader.Load(Paths.Content);   // a fresh copy: the fixture below rewrites it in memory, never C

        // A one-turn fixture over a fresh copy of the real content. The objective condition is already true, while its
        // card cannot fire until step 11 records it; ending the game at that turn's boundary makes it an ending card.
        var probe = Simulation.NewGame(c, GoldenRun.Seed, Mode.Historical);
        c.Rules.Mvp!.End = Simulation.TurnEnd(c, probe);
        var objective = c.Objectives.Single(o => o.Id == "railway");
        objective.CompletesWhen = new ObjectiveCondition
        {
            Absorbed = new AbsorbCondition
            {
                PopulationAtLeast = 0,
                OverflowAtMost = 1m,
                EmployedAtLeast = 0m,
            },
        };
        var objectiveCard = c.Events.Single(e => e.Id == objective.Card);
        objectiveCard.From = probe.Date;
        objectiveCard.To = null;
        objectiveCard.Requires.Clear();
        objectiveCard.Conditions.Clear();

        var dir = Path.Combine(Path.GetTempPath(), "statecraft-ending-load-" + System.Guid.NewGuid().ToString("N"));
        try
        {
            var store = new SaveStore(dir);
            var firstBridge = new SimBridge(GameSession.New(c, GoldenRun.Seed, Mode.Historical), text);
            using (GameStart.Autosave(firstBridge, store, text))
            {
                firstBridge.EndTurn();
                Assert.AreEqual(GameOverCodes.MvpEnded, firstBridge.State.GameOver);
                Assert.AreEqual(firstBridge.State.Date, firstBridge.State.Objectives[objective.Id],
                    "step 11 recorded the objective on the ending date");
                CollectionAssert.AreEqual(new[] { objectiveCard.Id }, firstBridge.State.PendingEvents,
                    "the autosaved final state leaves its ending card pending");
            }

            var savedHash = firstBridge.State.Hash();
            Assert.IsTrue(File.Exists(store.AutosavePath), "the real autosave path wrote the ending turn");

            var notes = new List<string>();
            var loadedSession = GameStart.Begin(c, store, () => 1UL, notes, text, out var resumed);
            Assert.IsTrue(resumed, "launch resumed the autosave");
            CollectionAssert.IsEmpty(notes);
            Assert.AreEqual(savedHash, loadedSession.State.Hash(), "the command log replayed the saved final state");

            var loadedBridge = new SimBridge(loadedSession, text);
            using var ui = new UiTestKit();
            using var card = new EventCardPresenter(ui.Root, loadedBridge, text, null);
            using var end = new EndScreenPresenter(ui.Root, loadedBridge, text, null);

            Assert.IsTrue(loadedBridge.EndingCardWaiting);
            Assert.AreEqual(objectiveCard.Id, card.Shown?.Id);
            Assert.IsFalse(end.IsOpen, "the loaded ending card comes before the end screen");

            var option = ui.Q<Button>("option-" + objectiveCard.Options.Single().Id);
            Assert.IsTrue(option.enabledSelf);
            Assert.IsNotEmpty(option.text);
            UiTestKit.Press(option);

            Assert.IsNull(card.Shown);
            Assert.IsFalse(loadedBridge.EndingCardWaiting);
            Assert.IsTrue(end.IsOpen, "answering the loaded card through its UI button opens the end screen");
            Assert.AreEqual(text["end.title"], ui.Q<Label>("end-screen-title").text);
            Assert.AreEqual(savedHash, loadedBridge.State.Hash(), "seeing the card changes no saved simulation state");
        }
        finally
        {
            try { if (Directory.Exists(dir)) Directory.Delete(dir, true); }
            catch (IOException) { }
        }
    }

    // #2536: SeeEndingCard answers only a waiting card of the ending turn; any other event stays as it was.
    [Test]
    public void OnlyAnEndingTurnCardCanBeAnsweredThatWay()
    {
        using var k = new Kit(En, Ended);   // the absorb objective recorded a month early, not on the last day
        var waiting = k.Bridge.State.PendingEvents.ToList();
        Assert.IsFalse(k.Bridge.EndingCardWaiting);
        Assert.IsTrue(k.End.IsOpen, "an ended game with no card of its ending turn opens on its end screen");
        k.Bridge.SeeEndingCard("absorb_immigrants");
        foreach (var id in waiting) k.Bridge.SeeEndingCard(id);
        CollectionAssert.IsEmpty(k.Bridge.EndingCardsAnswered);
    }

    [Test]
    public void OpensOnGameOverAndADefeatShowsItsCause()
    {
        using var k = new Kit(En, Exhausted);
        Assert.IsFalse(k.End.IsOpen, "no end screen while the game is on");
        for (int turn = 0; turn < 3 && k.Bridge.State.GameOver == null; turn++) k.Bridge.EndTurn();
        Assert.AreEqual(GameOverCodes.DefeatEconomy, k.Bridge.State.GameOver, "three exhausted turn ends are the economic defeat");
        Assert.IsTrue(k.End.IsOpen, "the turn that ends the game opens the end screen");
        Assert.AreEqual(DisplayStyle.Flex, k.Q("end-screen").style.display.value);
        Assert.AreEqual(En["end.outcome.defeat_economy"], k.Line("outcome"));
        Assert.IsFalse(k.Q("top-bar").enabledSelf, "the screen covers the HUD");
        Assert.IsTrue(k.Q("end-screen").enabledSelf, "and takes input itself");
    }

    [Test]
    public void ShowsEveryPartOfTheReportAndNothingElse()
    {
        using var k = new Kit(En, Ended);
        Assert.IsTrue(k.End.IsOpen, "a loaded ended game opens on its end screen");
        var s = k.Bridge.State; var r = EndReport.For(C, s);
        var names = k.Ui.Q<ScrollView>("end-screen-rows").Children().Select(x => x.name).ToList();
        var expected = new[] { "outcome", "date", "score", "score-objectives", "score-timing", "score-reference" }.Concat(r.Objectives.Select(o => "objective-" + o.Id))
            .Concat(new[] { "cohesion", "standing", "population", "population-sources" }).Select(n => "end-screen-" + n);
        CollectionAssert.AreEqual(expected, names, "the report's parts, in order");
        Assert.AreEqual(En["end.outcome.mvp_ended"], k.Line("outcome"));
        string Date(System.DateTime d) => En.Format("date.day_month_year", d.Day, En["date.month_" + d.Month], d.Year);
        Assert.AreEqual(En.Format("end.date", Date(r.Date)), k.Line("date"), "the end date (R-END-005, #2545)");
        Assert.AreEqual(En.Format("hud.score", s.Score), k.Line("score"));
        Assert.Greater(s.Score, 0);
        Assert.AreEqual(200, r.ReferenceScore, "the reference is the sim's number (Q-SCORE-2)");
        Assert.AreEqual(En.Format("end.reference_score", r.ReferenceScore), k.Line("score-reference"));
        StringAssert.Contains("200", k.Line("score-reference"));
        // The first objective: the card's title, the player's date and the historical date (Q-END-1).
        var first = C.Objectives.Single(o => o.Id == "absorb_immigrants");   // by id: the first in id order, as before R-OBJ-007
        var title = EventSystem.Title(C, s, C.Events.First(e => e.Id == first.Card));
        Assert.AreEqual(En.Format("end.objective_done", title, Date(first.ReferenceDate.AddMonths(-1)), Date(first.ReferenceDate)), k.Line("objective-" + first.Id));
        foreach (var o in C.Objectives.Where(o => o.Id != first.Id))
            StringAssert.Contains(Date(o.ReferenceDate), k.Line("objective-" + o.Id), "an open objective still shows its historical date");
        Assert.AreEqual(En.Format("end.parameter", En["hud.caption.cohesion"], PlayerText.Percent(r.SocialCohesion)), k.Line("cohesion"));
        Assert.AreEqual(En.Format("end.parameter", En["hud.caption.standing"], PlayerText.Percent(r.InternationalSupport)), k.Line("standing"));
        // The one comparison with history: the population beside its CBS anchor (Q-END-2, R-END-006).
        var anchor = r.PopulationHistory!;
        Assert.AreEqual(En.Format("end.population_history", r.Population.ToString("N0", System.Globalization.CultureInfo.InvariantCulture),
            Date(anchor.Date), anchor.Jews.ToString("N0", System.Globalization.CultureInfo.InvariantCulture)), k.Line("population"));
        // ...and the anchor's sources (R-END-006, #2545), by host as the unit card gives its sources.
        Assert.AreEqual(En.Format("unit.sources", "www.cbs.gov.il"), k.Line("population-sources"));
    }

    /// <summary>#812 (GDD Phase 7 PR 9: "the score and its parts"; R-SCORE-001): right after the score, one row per part of
    /// it as the sim recorded it (EndReport.ScoreParts): objective points, the early-completion bonuses and the prisoner
    /// points, so the rows add up to the score. Ended completes one objective a month early (100 + 5, rules.yaml
    /// objective_points, objective_bonus_per_month); 1,200 prisoner points are set directly with the score kept equal to the
    /// parts, since the screen formats the recorded parts and computes nothing. A part over 999 takes the invariant group
    /// separator in both languages (the Mac runs he_IL).</summary>
    [Test]
    public void ShowsEveryPartOfTheScore()
    {
        using var k = new Kit(En, s => { Ended(s); s.ScorePrisonerPoints += 1200; s.Score += 1200; });
        var st = k.Bridge.State; var parts = EndReport.For(C, st).ScoreParts;
        Assert.AreEqual(100, parts.ObjectivePoints, "precondition: one objective's points");
        Assert.AreEqual(5, parts.TimingBonuses, "precondition: one month early");
        Assert.AreEqual(1200, parts.PrisonerPoints, "precondition: the prisoner points set");
        Assert.AreEqual(st.Score, parts.ObjectivePoints + parts.TimingBonuses + parts.PrisonerPoints, "precondition: the parts sum to the score");
        var names = k.Ui.Q<ScrollView>("end-screen-rows").Children().Select(x => x.name).ToList();
        var at = names.IndexOf("end-screen-score");
        Assert.GreaterOrEqual(at, 0, "the score row: " + string.Join(", ", names));
        CollectionAssert.AreEqual(new[] { "end-screen-score", "end-screen-score-objectives", "end-screen-score-timing", "end-screen-score-prisoners" },
            names.Skip(at).Take(4), "the parts follow the score");
        Assert.AreEqual("Score from objectives: 100", k.Line("score-objectives"));
        Assert.AreEqual("Score from early completion: 5", k.Line("score-timing"));
        Assert.AreEqual("Score from prisoners returned: 1,200", k.Line("score-prisoners"));
        var he = EndScreenPresenter.Lines(C, st, He);
        Assert.AreEqual("ניקוד מיעדים: \u200e100\u200e", he.Single(l => l.Name == "score-objectives").Text);
        Assert.AreEqual("ניקוד מהשלמה מוקדמת: \u200e5\u200e", he.Single(l => l.Name == "score-timing").Text);
        Assert.AreEqual("ניקוד משבויים שהוחזרו: \u200e1,200\u200e", he.Single(l => l.Name == "score-prisoners").Text);
    }

    /// <summary>#812: the prisoner points show only when some were scored. The #812 notice: "Do not invent zero/placeholder
    /// prisoner or war rows". Objectives and timing still show, the zero one included: the objective is completed on its
    /// historical date, so it earns no timing bonus (R-SCORE-001, HistoricalDatesScoreNoBonus), and no prisoners went home.</summary>
    [Test]
    public void ShowsThePrisonerPointsOnlyWhenSomeWereScored()
    {
        using var k = new Kit(En, s =>
        {
            var first = C.Objectives.Single(o => o.Id == "absorb_immigrants");   // on its historical date: no timing bonus
            Objectives.Record(C, s, C.RulesAt(s.Date).Mvp!, first.Id, first.ReferenceDate, new List<Cause>());
            s.Date = C.End;
            s.GameOver = GameOverCodes.MvpEnded;
        });
        var parts = EndReport.For(C, k.Bridge.State).ScoreParts;
        Assert.AreEqual(0, parts.PrisonerPoints, "precondition: no prisoners returned");
        Assert.AreEqual(0, parts.TimingBonuses, "precondition: no timing bonus");
        var names = k.Ui.Q<ScrollView>("end-screen-rows").Children().Select(x => x.name).ToList();
        CollectionAssert.DoesNotContain(names, "end-screen-score-prisoners", "no prisoner row at 0");
        var at = names.IndexOf("end-screen-score");
        Assert.GreaterOrEqual(at, 0, "the score row: " + string.Join(", ", names));
        CollectionAssert.AreEqual(new[] { "end-screen-score", "end-screen-score-objectives", "end-screen-score-timing" },
            names.Skip(at).Take(3), "objectives and timing follow the score, a zero part included");
        Assert.AreEqual("Score from early completion: 0", k.Line("score-timing"));
        var he = EndScreenPresenter.Lines(C, k.Bridge.State, He);
        Assert.IsFalse(he.Any(l => l.Name == "score-prisoners"), "nor in Hebrew");
        Assert.AreEqual("ניקוד מהשלמה מוקדמת: \u200e0\u200e", he.Single(l => l.Name == "score-timing").Text);
    }

    /// <summary>#2545 (R-END-006): the sources row follows the anchor. A game that ends before the first anchor has no
    /// comparison and so no sources row, and an anchor with no readable source URL gets no bare "Sources:" row either.</summary>
    [Test]
    public void ThePopulationSourcesRowShowsOnlyAnAnchorsReadableSources()
    {
        using (var early = new Kit(En, s => { s.Date = C.PopulationAnchors.Min(a => a.Date).AddDays(-1); s.GameOver = GameOverCodes.DefeatEconomy; }))
        {
            Assert.IsNull(EndReport.For(C, early.Bridge.State).PopulationHistory, "precondition: before the first anchor");
            CollectionAssert.DoesNotContain(early.Ui.Q<ScrollView>("end-screen-rows").Children().Select(x => x.name), "end-screen-population-sources");
        }
        var unsourced = ContentLoader.Load(Paths.Content);
        foreach (var a in unsourced.PopulationAnchors) { a.Sources.Clear(); a.Sources.Add(new Source { Url = "" }); }
        using var k = new Kit(En, Ended);
        var names = EndScreenPresenter.Lines(unsourced, k.Bridge.State, En).Select(l => l.Name).ToList();
        Assert.IsNotNull(EndReport.For(unsourced, k.Bridge.State).PopulationHistory, "precondition: an anchor applies, so only its sources are dropped");
        CollectionAssert.DoesNotContain(names, "population-sources");
    }

    /// <summary>A cause's history note (Q-DEF-4 (b)) sits right under its line when the strings carry one, and nowhere else.
    /// The armistice note is held out of the strings until the person's check is recorded, so a fixture string stands in.</summary>
    [Test]
    public void AWarLossShowsItsHistoryNoteUnderItsLineAndOtherOutcomesShowNone()
    {
        var withNote = UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text + "\nend.note.defeat_war: \"Fixture note.\"\n");
        using var k = new Kit(withNote, s => { s.Date = C.End; s.GameOver = GameOverCodes.DefeatWar; });
        var names = k.Ui.Q<ScrollView>("end-screen-rows").Children().Select(x => x.name).ToList();
        CollectionAssert.AreEqual(new[] { "end-screen-outcome", "end-screen-note", "end-screen-date", "end-screen-score" }, names.Take(4), "the note follows the outcome line");
        Assert.AreEqual("Fixture note.", k.Line("note"));
        Assert.IsTrue(k.Ui.Q<Label>("end-screen-note").ClassListContains("end-screen-note"));
        using var ended = new Kit(withNote, Ended);
        Assert.IsFalse(ended.Ui.Q<ScrollView>("end-screen-rows").Children().Any(x => x.name == "end-screen-note"), "no note for the MVP end");
    }

    /// <summary>A regression guard (it passes without the note change too): with no note in the strings (the shipped EN and HE
    /// files, until the person's check), a war loss goes straight from its line to the score: no note row, no empty gap.
    /// Adding the note string back means updating this test too.</summary>
    [Test]
    public void AWarLossWithNoNoteStringGoesStraightFromItsLineToTheScore()
    {
        foreach (var text in new[] { En, He })
        {
            using var k = new Kit(text, s => { s.Date = C.End; s.GameOver = GameOverCodes.DefeatWar; });
            var names = k.Ui.Q<ScrollView>("end-screen-rows").Children().Select(x => x.name).ToList();
            CollectionAssert.AreEqual(new[] { "end-screen-outcome", "end-screen-date", "end-screen-score" }, names.Take(3), "the end date follows the outcome line, then the score");
            CollectionAssert.DoesNotContain(names, "end-screen-note");
        }
    }

    /// <summary>A note follows only its own cause's line: an outcome with no line of its own (a legacy code, shown as the
    /// generic game-over line) gets no note even when the strings carry one for it.</summary>
    [Test]
    public void ANoteNeverFollowsTheGenericGameOverLine()
    {
        var withNote = UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text + "\nend.note.coalition_collapse: \"Fixture note.\"\n");
        Assert.IsFalse(withNote.Has("end.outcome." + GameOverCodes.CoalitionCollapse), "precondition: the legacy code has no outcome line");
        using var k = new Kit(withNote, s => { s.Date = C.End; s.GameOver = GameOverCodes.CoalitionCollapse; });
        Assert.AreEqual(withNote["order.game_over"], k.Line("outcome"), "precondition: the generic line shows");
        var names = k.Ui.Q<ScrollView>("end-screen-rows").Children().Select(x => x.name).ToList();
        CollectionAssert.AreEqual(new[] { "end-screen-outcome", "end-screen-date", "end-screen-score" }, names.Take(3), "the end date follows the generic line, then the score");
        CollectionAssert.DoesNotContain(names, "end-screen-note");
    }

    // Q-END-3: the prisoners returned, worded as Defence words them, only when some went home (no zero row).
    [Test]
    public void ShowsThePrisonersReturnedOnlyWhenSomeWentHome()
    {
        using (var none = new Kit(En, Ended))
            CollectionAssert.DoesNotContain(none.Ui.Q<ScrollView>("end-screen-rows").Children().Select(x => x.name), "end-screen-prisoners");
        using var k = new Kit(En, s => { Ended(s); s.PrisonersReturned["lebanon"] = 4; });
        Assert.AreEqual("Prisoners returned: 4,000", k.Line("prisoners"));
        Assert.AreEqual("שבויים שהוחזרו: \u200e4,000\u200e", EndScreenPresenter.Lines(C, k.Bridge.State, He).Single(l => l.Name == "prisoners").Text);
        // The same count as the Defence screen shows over the same state.
        k.Q("screen-defence").style.display = DisplayStyle.Flex;   // open, as ScreenNav opens it (a hidden screen does not re-render)
        using (new DefencePresenter(k.Ui.Root, k.Bridge, En))
            Assert.AreEqual(k.Ui.Q<Label>("prisoners-returned").text, k.Line("prisoners"));
    }

    [Test]
    public void CloseRebuildAndTheFirstNewGamePressKeepTheStateAndTheSave()
    {
        using var k = new Kit(En, Exhausted);
        for (int turn = 0; turn < 3 && k.Bridge.State.GameOver == null; turn++) k.Bridge.EndTurn();
        Assert.IsTrue(k.End.IsOpen);
        var hash = k.Bridge.State.Hash();
        var saved = File.ReadAllBytes(k.Store.AutosavePath);

        k.Report.Close();   // the last turn's report, under the end screen
        UiTestKit.Press(k.Ui.Q<Button>("end-screen-close"));
        Assert.IsFalse(k.End.IsOpen, "Close leaves the map to inspect");
        Assert.IsTrue(k.Q("top-bar").enabledSelf, "the HUD is back");
        Assert.AreEqual(hash, k.Bridge.State.Hash(), "closing changes nothing");
        CollectionAssert.AreEqual(saved, File.ReadAllBytes(k.Store.AutosavePath), "nor the saved game");
        Assert.IsFalse(k.Ui.Q<Button>("end-turn").enabledSelf, "End Turn stays disabled after the end");
        Assert.AreEqual(En["order.game_over"], k.Bridge.Queue(new BuyArms(1)), "the map is read-only: an order is refused");

        k.Rebuild(He);   // the language switch builds the screens again over the same game
        Assert.IsFalse(k.End.IsOpen, "a screen the player closed stays closed in the other language");
        Assert.IsTrue(k.Q("top-bar").enabledSelf);
        k.Dispose_End_Reload(He);
        Assert.IsTrue(k.End.IsOpen, "a loaded ended game opens on its end screen again");
        Assert.AreEqual(He["end.title"], k.Ui.Q<Label>("end-screen-title").text);
        Assert.AreEqual(He["end.outcome.defeat_economy"], k.Line("outcome"));

        UiTestKit.Press(k.Ui.Q<Button>("end-screen-new-game"));
        Assert.IsTrue(k.NewGame.Armed, "the first press only asks");
        Assert.IsTrue(k.End.IsOpen);
        Assert.AreEqual(hash, k.Bridge.State.Hash(), "showing, closing and rebuilding the screen change nothing");
        CollectionAssert.AreEqual(saved, File.ReadAllBytes(k.Store.AutosavePath), "nor the saved game");

        UiTestKit.Press(k.Ui.Q<Button>("end-screen-new-game"));
        Assert.IsNull(k.Bridge.State.GameOver, "the second press starts a new game");
        Assert.IsFalse(k.End.IsOpen, "which has no end screen");
        Assert.IsTrue(File.Exists(k.Store.AutosavePath), "New Game saves its replacement immediately");
        var resumed = GameStart.Begin(C, k.Store, () => 1UL, new List<string>(), En);
        Assert.AreEqual(k.Bridge.State.Hash(), resumed.State.Hash());
        Assert.IsNull(resumed.State.GameOver);
    }

    /// <summary>#2669: the end screen can start New Game while the final turn's report waits underneath it. Red first:
    /// before TurnReportPresenter listened to Changed, the second press replaced the session but left that report open.</summary>
    [Test]
    public void NewGameFromTheEndScreenClosesTheLastTurnsReport()
    {
        using var k = new Kit(En, Exhausted);
        for (int turn = 0; turn < 3 && k.Bridge.State.GameOver == null; turn++) k.Bridge.EndTurn();
        Assert.IsTrue(k.End.IsOpen && k.Report.IsOpen, "precondition: the end screen covers the final turn's report");

        UiTestKit.Press(k.Ui.Q<Button>("end-screen-new-game"));
        Assert.IsTrue(k.NewGame.Armed);
        Assert.IsTrue(k.End.IsOpen && k.Report.IsOpen, "the confirmation press changes no session");

        UiTestKit.Press(k.Ui.Q<Button>("end-screen-new-game"));
        Assert.IsNull(k.Bridge.State.GameOver, "the second press starts the new game");
        Assert.IsFalse(k.End.IsOpen);
        Assert.IsFalse(k.Report.IsOpen, "the old game's report is closed");
        Assert.IsTrue(k.Q("top-bar").enabledSelf, "the old report does not cover the new game");
    }

    /// <summary>#2669 with #2536 (Codex review of 17c491b3d): answering the ending turn's card changes nothing in the game, so
    /// the final turn's report stays open under the end screen; only a replaced session closes it. Red at 17c491b3d: the
    /// report listened to every Changed, which SeeEndingCard raises.</summary>
    [Test]
    public void AnsweringTheEndingTurnsCardKeepsTheLastTurnsReport()
    {
        using var k = new Kit(En, Exhausted);
        for (int turn = 0; turn < 3 && k.Bridge.State.GameOver == null; turn++) k.Bridge.EndTurn();
        Assert.IsTrue(k.Report.IsOpen, "precondition: the final turn's report is open");
        EndedWithACard(k.Bridge.State);   // the ending turn also left an objective's card waiting
        Assert.IsTrue(k.Bridge.EndingCardWaiting, "precondition: a card of the ending turn waits");
        var session = k.Bridge.Session;

        k.Bridge.SeeEndingCard("railway_complete");
        Assert.AreSame(session, k.Bridge.Session, "the answer replaces nothing");
        Assert.IsFalse(k.Bridge.EndingCardWaiting);
        Assert.IsTrue(k.Report.IsOpen, "the report stays, under the end screen");
    }

    [Test]
    public void CancelClosesItAndClosedItTakesNoInput()
    {
        using var k = new Kit(En, Ended);
        var close = k.Ui.Q<Button>("end-screen-close");
        using (var e = NavigationCancelEvent.GetPooled()) { e.target = close; close.SendEvent(e); }
        Assert.IsFalse(k.End.IsOpen, "Esc or a gamepad's Cancel closes it");
        Assert.IsFalse(k.Q("end-screen").enabledSelf, "a closed screen takes no input");
        Assert.IsFalse(k.End.Close(), "closing it again does nothing");
    }

    [Test]
    public void TheLastTurnsReportWaitsUnderTheEndScreenAndADisposedScreenStaysShut()
    {
        using var k = new Kit(En, Exhausted);
        for (int turn = 0; turn < 3 && k.Bridge.State.GameOver == null; turn++) k.Bridge.EndTurn();
        Assert.IsTrue(k.End.IsOpen && k.Report.IsOpen, "the last turn brings both");
        Assert.IsFalse(k.Q("turn-report").enabledSelf, "the report takes no input under the end screen");
        Assert.IsTrue(k.Q("end-screen").enabledSelf);
        UiTestKit.Press(k.Ui.Q<Button>("end-screen-close"));
        Assert.IsTrue(k.Q("turn-report").enabledSelf, "and takes it again when the end screen closes");
        Assert.IsFalse(k.Q("top-bar").enabledSelf, "the report still covers the HUD");
        k.Report.Close();
        k.End.Dispose();
        var again = GameSession.New(C, GoldenRun.Seed, Mode.Historical); Exhausted(again.State);
        k.Bridge.Replace(again);
        for (int turn = 0; turn < 3 && k.Bridge.State.GameOver == null; turn++) k.Bridge.EndTurn();
        Assert.IsNotNull(k.Bridge.State.GameOver);
        Assert.AreEqual(DisplayStyle.None, k.Q("end-screen").style.display.value, "a disposed end screen listens to no turn");
        k.Dispose_End_Reload(En);   // the kit disposes it once more at the end
    }

    /// <summary>#2041: in Hebrew an objective's line titles it as its decision card does - the Hebrew title_he where
    /// there is no variant title, the English otherwise (EventCardPresenter's pick). English is unchanged, pinned by
    /// ShowsEveryPartOfTheReportAndNothingElse. Red-first: Lines used the English EventSystem.Title in every language.
    /// </summary>
    [Test]
    public void HebrewTitlesTheObjectivesAsTheirCardsDo()
    {
        using var k = new Kit(He, Ended);
        var s = k.Bridge.State;
        var lines = EndScreenPresenter.Lines(C, s, He);
        foreach (var o in C.Objectives)
        {
            var card = C.Events.First(e => e.Id == o.Card);
            var variant = Timeline.Variant(C, s, card);
            Assert.IsTrue(variant == null || variant.Title == "", o.Id + " precondition: no variant title");
            Assert.AreNotEqual("", card.TitleHe, o.Id + " precondition: the card has a Hebrew title");
            var line = lines.Single(l => l.Name == "objective-" + o.Id).Text;
            StringAssert.Contains(card.TitleHe, line, o.Id + ": the Hebrew line shows the card's Hebrew title");
            StringAssert.DoesNotContain(EventSystem.Title(C, s, card), line, o.Id + ": not the English title");
        }
    }

    /// <summary>R-EVT-007 (owner, 2 November 2026, #2197: "Show on the end screen (Recommended)"): a Deport card that never
    /// fired, because its Deport came on the turn that ended the game (EndReport.DeportCards), shows on the end screen after
    /// the objectives: its title, then its text, as its card shows them, in the UI's language. A card that fired was shown on
    /// its turn and is not shown again. Red first, reasoned (Unity runs only through the gate): before this change Lines had
    /// no Deport rows, so the ordered names lack "end-screen-deport-deport_acre" and the Line lookups find no label.</summary>
    [Test]
    public void ADeportCardThatNeverFiredShowsOnTheEndScreen()
    {
        var card = C.Events.Single(e => e.Deported == "acre");
        void Deported(GameState s) { Ended(s); s.Settlements["acre"] = new SettlementControl(since: s.Date, depopulated: true); }
        using (var k = new Kit(En, Deported))
        {
            var s = k.Bridge.State;
            var names = k.Ui.Q<ScrollView>("end-screen-rows").Children().Select(x => x.name).ToList();
            var at = names.IndexOf("end-screen-deport-" + card.Id);
            Assert.GreaterOrEqual(at, 0, "the card's row: " + string.Join(", ", names));
            Assert.AreEqual("end-screen-objective-" + C.Objectives[C.Objectives.Count - 1].Id, names[at - 1], "after the objectives");
            CollectionAssert.AreEqual(new[] { "end-screen-deport-" + card.Id, "end-screen-deport-" + card.Id + "-text", "end-screen-cohesion" },
                names.Skip(at).Take(3), "the title, the text, then the parameters");
            Assert.AreEqual(EventSystem.Title(C, s, card), k.Line("deport-" + card.Id));
            Assert.AreEqual(EventSystem.Render(C, s, card), k.Line("deport-" + card.Id + "-text"));
            var he = EndScreenPresenter.Lines(C, s, He);
            Assert.AreEqual(card.TitleHe, he.Single(l => l.Name == "deport-" + card.Id).Text, "in Hebrew, the card's Hebrew");
            Assert.AreEqual(card.TextHe, he.Single(l => l.Name == "deport-" + card.Id + "-text").Text);
        }
        using var fired = new Kit(En, s => { Deported(s); s.FiredEvents.Add(card.Id); });
        CollectionAssert.DoesNotContain(fired.Ui.Q<ScrollView>("end-screen-rows").Children().Select(x => x.name), "end-screen-deport-" + card.Id,
            "a card that fired is not shown again");
    }

    [Test]
    public void HebrewShowsTheHebrewWords()
    {
        using var k = new Kit(He, Ended);
        Assert.AreEqual(He["end.title"], k.Ui.Q<Label>("end-screen-title").text);
        Assert.AreEqual(He["end.outcome.mvp_ended"], k.Line("outcome"));
        Assert.AreEqual(He["report.close"], k.Ui.Q<Button>("end-screen-close").text);
        Assert.AreEqual(He["hud.new_game"], k.Ui.Q<Button>("end-screen-new-game").text);
        StringAssert.StartsWith(He["hud.caption.cohesion"] + ":", k.Line("cohesion"));
        Assert.AreEqual(He.Format("unit.sources", "www.cbs.gov.il"), k.Line("population-sources"));
    }

    /// <summary>#2060: in Hebrew each date an end-screen line inserts sits between RLE and PDF (U+202B, U+202C), so it
    /// reads as one unit right after "ב־" ("20 בספטמבר 1949") even in a line laid out left to right, instead of the bidi
    /// rules pulling its day onto the next word and its year to the line's far end. The lines are compared ordinally, so
    /// every direction mark counts. The titles are read back from the lines: #2041 decides which title shows, this test
    /// pins the dates around it.</summary>
    [Test]
    public void HebrewIsolatesEachDateItInserts()
    {
        using var k = new Kit(He, Ended);
        var first = C.Objectives.Single(o => o.Id == "absorb_immigrants");
        const char Lrm = '\u200E', Rle = '\u202B', Pdf = '\u202C';
        string Date(System.DateTime d) => $"{Rle}{Lrm}{d.Day}{Lrm} ב{He["date.month_" + d.Month]} {Lrm}{d.Year}{Lrm}{Pdf}";
        var line = k.Line("objective-" + first.Id);
        var title = line.Substring("יעד ".Length, line.IndexOf(": הושלם", System.StringComparison.Ordinal) - "יעד ".Length);
        var expected = "יעד " + title + ": הושלם ב־" + Date(first.ReferenceDate.AddMonths(-1)) + "; בהיסטוריה ב־" + Date(first.ReferenceDate);
        Assert.IsTrue(string.Equals(expected, line, System.StringComparison.Ordinal), "expected\n" + Escape(expected) + "\nbut was\n" + Escape(line));
        var open = C.Objectives.First(o => o.Id != first.Id);   // Ended completes only the first
        var openLine = k.Line("objective-" + open.Id);
        var openTitle = openLine.Substring("יעד ".Length, openLine.IndexOf(": לא הושלם", System.StringComparison.Ordinal) - "יעד ".Length);
        var openExpected = "יעד " + openTitle + ": לא הושלם; בהיסטוריה ב־" + Date(open.ReferenceDate);
        Assert.IsTrue(string.Equals(openExpected, openLine, System.StringComparison.Ordinal), "expected\n" + Escape(openExpected) + "\nbut was\n" + Escape(openLine));
        var anchor = EndReport.For(C, k.Bridge.State).PopulationHistory!;
        Assert.GreaterOrEqual(k.Line("population").IndexOf(Date(anchor.Date), System.StringComparison.Ordinal), 0, "the population line's date too: " + Escape(k.Line("population")));
        var endDate = He.Format("end.date", Date(EndReport.For(C, k.Bridge.State).Date));
        Assert.IsTrue(string.Equals(endDate, k.Line("date"), System.StringComparison.Ordinal), "the end date too: expected\n" + Escape(endDate) + "\nbut was\n" + Escape(k.Line("date")));
    }

    /// <summary>The line with its invisible marks spelled out, for a failure message.</summary>
    static string Escape(string s) => string.Concat(s.Select(c => c < 0x2000 || c > 0x206F ? c.ToString() : $"<U+{(int)c:X4}>"));
}