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.

64.6 KB
Raw Blame
#nullable enable
using System;
using System.Globalization;
using System.Linq;
using Statecraft.Sim;
using UnityEngine.UIElements;

namespace Statecraft.Game.UI
{
    /// <summary>GDD Phase 1 PR 8 (#381): the info panel's part for the GDD loop (Content.IsGdd), built into the
    /// <see cref="HostName"/> element on every render.
    /// <para>On a city hex (State.Cities), its counts (housing, overflow, jobs, craftsmen, refugees waiting, recruits) and training cohorts with
    /// their turns left, the Assign stepper (R-CITY-001), Train for each facility the city has (R-TRAIN-001, R-CAMP-001) and Cancel
    /// (R-TRAIN-002). On a site's hex (sites.yaml: a yishuv, camp, field or swamp site, #1124), its state, and Build with each idle pioneer
    /// group (Projects.IsPioneer: a halutz or a veteran one), with the rules' cost and the unit's own turns (Projects.TurnsToBuild;
    /// R-SITE-001, R-VET-002), or Stop while it is built (R-SITE-002). The same for each corridor segment through the hex: Build
    /// road or Build railway (R-COR-001 to R-COR-003, #792).</para>
    /// <para>On any hex a city can build on (Projects.CitiesFor, #1122): the city that builds (the player picks when several
    /// can), and Build for each content project kind with its cost and turns (Projects.CityTurnsToBuild), disabled with the sim's own refusal
    /// (Projects.CheckCityReason) worded in the UI's language; or the project there, with its turns left and Cancel, or the
    /// day it was finished (R-PROJ-001 to R-PROJ-003); under gdd-0.3, on a built arms workshop, its staffing and cycle (#1722,
    /// R-ARMS-005 to R-ARMS-007). Under gdd-0.3 the city's block also has its housing readout (Cities.HousingOutlook,
    /// R-HOUSE-005) and the list of all its projects with their work done, cost, builder and Cancel (#1722).</para>
    /// <para>Every number is the sim's, and every order goes through the bridge's queue: the sim rules on it when the turn
    /// runs. No rule lives here: the limits are the sim's public helpers (Cities.MaxWorkers, Training.Available, Workshops.Check) and
    /// Simulation.Preview, asked with the exact queue a press would leave; a button is disabled only where the sim would refuse that
    /// order, or another one in the queue, anyway.</para></summary>
    public static class GddHexPanel
    {
        public const string HostName = "info-gdd";
        /// <summary>The city-project part's host (#1122), in the hex's facts column: the GDD column beside it is already full on a city's
        /// own hex, and the facts column has room (InfoPanelLayoutTests).</summary>
        public const string ProjectsHostName = "info-projects";
        /// <summary>On the city's own hex, on a stacked bar or a short window, the project part folds behind this toggle
        /// ("City projects (N)") and the list it opens (owner ruling on #1150, 21 Oct 2026; Statecraft.uss .city-projects-list).</summary>
        public const string ToggleName = "city-projects-toggle", ListName = "city-projects-list", OpenClass = "info-projects-open";
        /// <summary>The name over each city's block on a hex that holds two (Statecraft.uss).</summary>
        public const string CityNameClass = "city-part-name";
        const string LineClass = "info-gdd-line", RowClass = "info-gdd-row", PairsClass = "info-gdd-pairs";

        public static void Hide(VisualElement host) { host.Clear(); host.style.display = DisplayStyle.None; }

        /// <summary>Builds the hex's GDD part into <paramref name="host"/> and its city projects into <paramref name="projects"/>
        /// (each hidden when there is none) and returns the designated site's name in the UI's language when the hex holds one,
        /// else null. <paramref name="townName"/> names a city in the UI's language (InfoPanelPresenter's town names).</summary>
        public static string? Render(VisualElement host, VisualElement projects, SimBridge bridge, UiText text, int q, int r, Func<string, string> townName, Action<int>? selectPioneer = null)
        {
            host.Clear(); projects.Clear();
            var c = bridge.Content; var s = bridge.State;
            string? title = null;
            if (c.IsGdd)
            {
                // A hex with two cities (Rishon LeZion and Rehovot) shows two stat blocks: each gets its own part, named, so the
                // player can tell whose jobs stepper is whose (playtest B6). One city's block needs no name: the title has it.
                var cities = c.SettlementHexes.Where(x => x.Q == q && x.R == r && s.Cities.ContainsKey(x.Id)).ToList();
                foreach (var at in cities)
                {
                    var part = new VisualElement { name = "city-part-" + at.Id };
                    host.Add(part);
                    if (cities.Count > 1) Line(part, "city-name", townName(at.Id)).AddToClassList(CityNameClass);
                    City(part, bridge, text, at.Id);
                }
                var cityHere = host.childCount > 0;
                // A hex may hold two sites, a yishuv or the Hula swamp and the field it readies (R-FIELD-001, R-SWAMP-001): each
                // gets its own part, the one to finish first on top, and its name is the title (#1124).
                foreach (var site in c.Sites.Where(x => x.Q == q && x.R == r && Work(x) != null).OrderBy(x => x.Kinds.Contains(Projects.FieldKind)))
                {
                    title ??= Name(text, site);
                    var part = new VisualElement { name = "site-part-" + site.Id };
                    host.Add(part);
                    Site(part, bridge, text, site, Work(site)!.Value, selectPioneer);
                }
                // #792: each corridor segment through the hex (corridors.yaml; a hex where two segments meet is in both). Not on a
                // city's own hex, whose column is full (InfoPanelLayoutTests), for a segment that has another hex; a segment whose
                // every hex is a city's (the Yarkon rail link, Petah Tikva to Tel Aviv, on 4.4 km hexes) shows on its first hex
                // only, so it can still be built where it ran and Tel Aviv's column stays as it was (owner, 26 October 2026, #1183).
                foreach (var d in c.Corridors)
                    for (int i = 0; i < d.Segments.Count; i++)
                        if (d.Segments[i].Hexes.Any(h => h[0] == q && h[1] == r) && (!cityHere
                            || (d.Segments[i].Hexes[0][0] == q && d.Segments[i].Hexes[0][1] == r
                                && d.Segments[i].Hexes.All(h => c.SettlementHexes.Any(x => x.Q == h[0] && x.R == h[1] && s.Cities.ContainsKey(x.Id))))))
                        {
                            var part = new VisualElement { name = $"corridor-part-{d.Id}-{i + 1}" };
                            host.Add(part);
                            Segment(part, bridge, text, d, i, selectPioneer);
                        }
                CityProjects(projects, bridge, text, q, r, townName, cityHere);
            }
            host.style.display = host.childCount > 0 ? DisplayStyle.Flex : DisplayStyle.None;
            projects.style.display = projects.childCount > 0 ? DisplayStyle.Flex : DisplayStyle.None;
            return title;
        }

        static void City(VisualElement host, SimBridge bridge, UiText text, string id)
        {
            var c = bridge.Content; var s = bridge.State; var city = s.Cities[id];
            // R-HOUSE-003: the housed are the civilians, craftsmen, recruits and groups in training, and under gdd-0.1 the
            // city's Israeli formations too (Cities.Housed), against the
            // capacity; R-HOUSE-001: the city's housing condition, 0 to 1, through the one percent formatter, on the same line
            // so the panel is no taller (the GDD loop always has a condition; the plain form is for a city without one).
            var housed = Cities.Housed(s, city); var capacity = Groups(text, city.HousingCapacity);
            Line(host, "city-housing", city.Condition is double condition
                ? text.Format("city.housing_condition", housed, capacity, PlayerText.Percent(condition))
                : text.Format("city.housing", housed, capacity));
            HousingLines(host, bridge, text, id);
            // #1121: the craftsmen (R-CRAFT-001) beside Jobs, as they fill ordinary jobs (R-CRAFT-002), and the overflow
            // (R-HOUSE-002, Cities.Overflow) beside the refugees waiting, the other people without housing. Each pair shares a
            // row (the labels keep their width and the row wraps only when they do not fit, Statecraft.uss), so on a short
            // window the panel stays clear of the left column (InfoPanelLayoutTests). Bare counts, like the Jobs line, to fit.
            var jobs = Row(host, "city-jobs-row"); jobs.AddToClassList(PairsClass);
            Line(jobs, "city-jobs", text.Format("city.jobs", city.Employed, city.JobSlots));
            Line(jobs, "city-craftsmen", text.Format("city.craftsmen", city.Craftsmen));
            var waiting = Row(host, "city-waiting-row"); waiting.AddToClassList(PairsClass);
            Line(waiting, "city-refugees", text.Format("city.refugees", Groups(text, city.Refugees)));
            Line(waiting, "city-overflow", text.Format("city.overflow", Cities.Overflow(s, city)));
            // #1345: under gdd-0.1 trained recruits are formations housed in their home city since #1130, so the line counts
            // every Israeli formation the city houses (Cities.Soldiers, part of Cities.Housed), not City.Recruits, which nothing
            // writes now. Under gdd-0.3 formations are not housed (R-HOUSE-003, 27M-18; #1703), so there is no such line: the
            // housing line above already shows the gdd-0.3 housed count.
            if (c.Ruleset != SaveGame.Gdd03Ruleset)
                Line(host, "city-soldiers", text.Format("city.soldiers", Groups(text, Cities.Soldiers(s, city))));

            // What End turn would do with this turn's queue (#2743 item 2): an order it refuses anyway takes nobody, so the sim's
            // limits below are asked over the queue less those orders (Live), and each later row asks it about the press.
            var current = Preview(bridge, bridge.Queued);
            var live = Live(bridge, current);
            // The Assign stepper: the ordered count (or the current one), one group a press, within R-CITY-001's limits as
            // the sim gives them with this turn's Train orders; stepping back to the current count withdraws the order.
            var queued = bridge.QueuedLike(new AssignWorkers(id, "job", 0)) as AssignWorkers;
            var target = queued?.Count ?? city.Employed;
            var max = Cities.MaxWorkers(s, id, live);
            var workers = Row(host, "city-workers-row");
            OrderButton(workers, bridge, "city-workers-less", "−", target > 0, () => Workers(bridge, id, city.Employed, target - 1));
            Line(workers, "city-workers", text.Format(queued == null ? "city.workers" : "city.workers_ordered", Groups(text, target)));
            OrderButton(workers, bridge, "city-workers-more", "+", target < max, () => Workers(bridge, id, city.Employed, target + 1));
            // The Assign order's Attention price (the queue's, at this turn's start) and when it applies (playtest B7): the
            // Jobs line stays the sim's actual count until End turn. Changing a queued target does not buy another order.
            // The line names the workers change, and where the city trains it adds the Train order's price: every Train order
            // costs the same, by its kind (AttentionSystem.Price), and at security level 5 it is 2.0 to the workers change's 1.0
            // (each kind's cost is R-GOV-002's; content/rules.yaml's rung_attention_step raises it by a quarter a level above
            // the first, AttentionSystem.Cost), so the one price no longer reads as Train's. On the existing line, as a new
            // line or a price on each Train button would push the city panel into the top bar in short windows
            // (InfoPanelLayoutTests). gdd-0.3 has no Attention.
            // The unit types the city can train (Training.HasFacility: its own facility, D-D5, or a built camp site's,
            // R-CAMP-001): the Train price shows where the Train buttons below show.
            var trainTypes = c.UnitTypes.Where(t => t.Facility != "" && Training.HasFacility(c, s, id, t.Facility)).ToList();
            var trainType = trainTypes.FirstOrDefault();
            var workersCost = bridge.Content.UsesAttention
                ? text.Format("city.workers_cost", bridge.Price(new AssignWorkers(id, "job", target))!.Value)
                : text.Format("city.workers_ordered", Groups(text, target));
            if (trainType != null && bridge.Price(new Train(id, trainType.Id, 1)) is double trainPrice)
                workersCost = text.Format("city.train_cost", workersCost, trainPrice);
            Line(host, "city-workers-cost", workersCost);

            // Train, for each facility the city has (Training.HasFacility: its own, D-D5, or a built camp site's, R-CAMP-001):
            // each press orders one more group. The exact preview below asks whether End turn would refuse that order, and
            // R-TRAIN-001's idle-civilian limit is Training.Available's, over the queue less the orders End turn refuses anyway.
            // A refused press says why under its button, in the UI's language (#2518), once for a reason two courses share.
            // #1548 (owner, 24 October 2026: "Yes, count them"): every queued Train, Reinforce and reassignment still takes
            // its groups from the civilians without work, as Training.Available counts them (the sim does not take a
            // reassigned craftsman off them). "Refused anyway" is the current queue's preview, without the press: an order
            // the press itself would make End turn refuse (a reassignment queued after a Train that takes its civilian) still
            // counts. The old order's own count is in the queue, so one more group needs one free.
            var free = Training.Available(s, id, live);
            var said = new System.Collections.Generic.HashSet<string>();
            foreach (var type in trainTypes)
            {
                var old = bridge.QueuedLike(new Train(id, type.Id, 1));
                var ordered = (old as Train)?.Count ?? 0;
                // #2573: the press queues Train(ordered + 1) where SimBridge.Queue puts it (the old order's slot, else last), so
                // the button asks End turn's own order runner (Simulation.Preview: queue order, conversions before Arms
                // purchases) whether that exact order would be refused, for a short Arms stock (R-ARMS-003) or any other reason,
                // or would make it refuse a queued order it accepts now (its civilians, Arms or anything else).
                var press = new Train(id, type.Id, ordered + 1);
                var refused = Refused(bridge, current, old, press);
                // #2978 (owner, 9 November 2026: "Enabled + toast (Recommended)"): an order the Attention left cannot pay for
                // keeps its Train button, as Build does: the bridge refuses the press and says why (order.no_attention,
                // SimBridge.Queue). The preview above charges Attention, so only Training's own rule is asked, on a copy of the
                // state the queue leaves, with the press run last, as End turn would. No Train of this type is queued here:
                // CanPay refunds a queued order of the same key, and every Train order costs the same, so with one queued the
                // press can pay. A press End turn refuses changes nothing, so it makes no queued order refused: only the press's
                // own refusal is replaced. As the preview did, an ended game refuses it (SimBridge.Queue says so; under gdd-0.3
                // OrderButton disables it anyway). Training.Start changes the state it is given, so it gets a fresh preview's,
                // not current's (the Return and Reassign rows below read that).
                if (s.GameOver == null && (refused == null || ReferenceEquals(refused.Command, press)) && !bridge.CanPay(press))
                {
                    var left = Preview(bridge, bridge.Queued).State;
                    var why = Training.Start(c, left, id, type.Id, ordered + 1, new System.Collections.Generic.List<Cause>());
                    refused = why == null ? null : new Rejection(press, why);
                }
                var row = Row(host, $"city-train-{type.Id}-row");
                OrderButton(row, bridge, "city-train-" + type.Id, text.Format("city.train_" + type.Id, PlayerText.Money(c, "treasury", type.TrainingCost), Turns(text, type.TrainingTurns)),
                    refused == null && free >= 1, () => bridge.Queue(new Train(id, type.Id, ordered + 1)));
                if (ordered > 0) Line(row, $"city-train-{type.Id}-ordered", text.Format("city.train_ordered", ordered));
                // A finished game's preview refuses every order: no reason line then (BuilderPart's rule).
                if (refused != null && s.GameOver == null && said.Add(refused.Reason))
                    Line(host, $"city-train-{type.Id}-reason", SimBridge.ReasonText(text, refused.Reason, c, bridge.TownNamesHe));
            }

            foreach (var k in s.Cohorts.Values.Where(x => x.City == id))
            {
                var row = Row(host, $"city-cohort-{k.Id}-row");
                Line(row, $"city-cohort-{k.Id}", text.Format("city.cohort", text["city.track_" + k.Type], Groups(text, k.Count), Turns(text, k.TurnsLeft)));
                var cancelled = bridge.QueuedLike(new CancelTraining(k.Id)) != null;
                OrderButton(row, bridge, $"city-cohort-{k.Id}-cancel", text[cancelled ? "city.cancel_ordered" : "city.cancel"],
                    !cancelled, () => bridge.Queue(new CancelTraining(k.Id)));
            }

            // Return and Reassign (#1511, R-QUAL-002 to R-QUAL-005): one group a press, like Train, shown where the city has
            // the people now or once this turn's queue has run (#2518: a queued Reassign makes craftsmen to return, a queued
            // Return qualified craftsmen to reassign; the sim takes both in one turn). The sim keeps the qualification and rules
            // on each order; a button is off only where End turn would refuse the press (more than the craftsmen or qualified
            // groups left once the queue has run, R-QUAL-006's loss to a queued Train included) or a queued order it accepts now.
            var after = current.State.Cities[id];
            var back = (bridge.QueuedLike(new ReturnCraftsmen(id, 1)) as ReturnCraftsmen)?.Count ?? 0;
            if (city.Craftsmen > 0 || back > 0 || after.Craftsmen > 0)
            {
                var old = bridge.QueuedLike(new ReturnCraftsmen(id, 1));
                var row = Row(host, "city-return-craftsmen-row");
                OrderButton(row, bridge, "city-return-craftsmen", text["city.return_craftsmen"], Refused(bridge, current, old, new ReturnCraftsmen(id, back + 1)) == null,
                    () => bridge.Queue(new ReturnCraftsmen(id, back + 1)));
                if (back > 0) Line(row, "city-return-craftsmen-ordered", text.Format("city.train_ordered", back));
            }
            // Training.Available already takes this turn's Train, Reinforce, Assign and Reassign orders off the idle civilians.
            var idleLeft = Training.Available(s, id, live);
            var q = city.Qualified; var then = after.Qualified;
            foreach (var (role, have, left) in new[] { ("craftsmen", q.Craftsmen, then.Craftsmen), ("halutz", q.Halutzim.Count, then.Halutzim.Count), (Projects.VeteranType, q.Veterans, then.Veterans) })
            {
                Command Order(int n) => role == "craftsmen" ? new ReassignCraftsmen(id, n) : (Command)new ReassignPioneers(id, role, n);
                var again = bridge.QueuedLike(Order(1));
                var ordered = again is ReassignCraftsmen rc ? rc.Count : again is ReassignPioneers rp ? rp.Count : 0;
                // The groups this role has once the queue has run, before its own reassignment (which the preview has applied).
                var before = left + (again != null && !current.Rejected.Any(x => ReferenceEquals(x.Command, again)) ? ordered : 0);
                if (have == 0 && ordered == 0 && before == 0) continue;
                var row = Row(host, $"city-reassign-{role}-row");
                OrderButton(row, bridge, "city-reassign-" + role, text.Format("city.reassign_" + role, have > 0 ? have : before),
                    idleLeft >= 1 && Refused(bridge, current, again, Order(ordered + 1)) == null, () => bridge.Queue(Order(ordered + 1)));
                if (ordered > 0) Line(row, $"city-reassign-{role}-ordered", text.Format("city.train_ordered", ordered));
            }
            var hex = c.SettlementHexes.First(h => h.Id == id);   // every settlement has one
            foreach (var u in s.Units.Values.Where(u => Projects.IsPioneer(u.Type) && u.Q == hex.Q && u.R == hex.R))
                PioneerReturn(host, bridge, text, u.Id);
            ProjectList(host, bridge, text, id);
        }

        /// <summary>#1722 (R-HOUSE-005), gdd-0.3 only: the city's housing readout under its housing line, Cities.HousingOutlook
        /// on the state as it is now: the surcharge a turn and the threshold it is charged below, or that there is none; the
        /// condition the overflow lowers it to, when it does; Social cohesion's change a turn and its threshold, when there is
        /// one. Every value and threshold is the sim's; nothing is computed here.</summary>
        static void HousingLines(VisualElement host, SimBridge bridge, UiText text, string id)
        {
            if (!(Cities.HousingOutlook(bridge.Content, bridge.State, id) is Cities.HousingReadout o)) return;
            var c = bridge.Content; var condition = bridge.State.Cities[id].Condition!.Value;
            // #1722 review S2: a term shows only when its figure, rounded as shown, says something. A surcharge under the
            // smallest amount shown has no line ("IL 0.0m a turn" says nothing, and "none" would not be true).
            var surcharge = PlayerText.Money(c, "treasury", o.Surcharge);
            if (o.Surcharge <= 0) Line(host, "city-surcharge", text.Format("city.housing_no_surcharge", PlayerText.Percent(o.MoneyThreshold)));
            else if (surcharge != PlayerText.Money(c, "treasury", 0))
                Line(host, "city-surcharge", text.Format("city.housing_surcharge", surcharge, PlayerText.Percent(o.MoneyThreshold)));
            if (o.ConditionAfter < condition && PlayerText.Percent(o.ConditionAfter) != PlayerText.Percent(condition))
                Line(host, "city-housing-falls", text.Format("city.housing_falls", PlayerText.Percent(o.ConditionAfter)));
            if (o.CohesionShift < 0 && PlayerText.PercentChange(o.CohesionShift) != PlayerText.PercentChange(0))
                Line(host, "city-housing-cohesion", text.Format("city.housing_cohesion", PlayerText.PercentChange(o.CohesionShift), PlayerText.Percent(o.CohesionThreshold)));
        }

        /// <summary>#1722 (R-PROJ-001 to R-PROJ-003, R-CITY-011, R-HOUSE-006), gdd-0.3 only: every project of the city in id
        /// order, wherever it stands (a repair has no hex of its own): for one being built its whole turns of work done of
        /// the kind's turns (the kind's turns less the record's TurnsLeft, which step 5 counts down, R-PROJ-003), the kind's
        /// cost, which its start paid in full (Projects.StartCity, R-PROJ-001), whether it has a builder (R-CITY-011) and Cancel
        /// (R-PROJ-002); for a built one the day it was finished and its cost. There is no upkeep column: upkeep is IL 0m in
        /// the MVP (27M-17).</summary>
        static void ProjectList(VisualElement host, SimBridge bridge, UiText text, string id)
        {
            var c = bridge.Content; var s = bridge.State;
            if (!Listed(c, s, id)) return;
            var mine = s.CityProjects.Values.Where(p => p.City == id).OrderBy(p => p.Id).ToList();
            Line(host, "city-list-header", text.Format("city.list_header", mine.Count));
            foreach (var p in mine)
            {
                var k = c.ProjectKinds.First(x => x.Id == p.Kind);
                var name = "city-list-project-" + p.Id.ToString(CultureInfo.InvariantCulture);
                var kind = PlayerText.Capitalised(ContentNames.Of(text, k));
                var cost = PlayerText.Money(c, "treasury", k.Cost);
                if (p.BuiltOn is DateTime built) { Line(host, name, text.Format("city.list_built", kind, Date(text, built), cost)); continue; }
                var row = Row(host, name + "-row");
                Line(row, name, text.Format("city.list_building", kind, k.Turns - p.TurnsLeft, k.Turns, cost, text[p.Builder ? "city.list_builder" : "city.list_no_builder"]));
                var cancelled = bridge.QueuedLike(new CancelProject(p.Id)) != null;
                OrderButton(row, bridge, name + "-cancel", text[cancelled ? "city.cancel_ordered" : "city.cancel"],
                    !cancelled, () => bridge.Queue(new CancelProject(p.Id)));
            }
        }

        /// <summary>Whether the city's block lists its projects (ProjectList): gdd-0.3, and the city has one.</summary>
        static bool Listed(Content c, GameState s, string city) => c.Ruleset == SaveGame.Gdd03Ruleset && s.CityProjects.Values.Any(p => p.City == city);

        /// <summary>A pioneer group's Return (R-QUAL-003; #1511): the sim's unit order return_civilian, offered where
        /// Qualification.CheckReturn takes the group (not one at work). It sits beside the places that list the group; the
        /// pioneer card (#1549) offers the same order through <see cref="PioneerReturnOrder"/>. A unit order, it takes
        /// effect at once (R-TURN-004): the group leaves the lists, and its Build buttons with it.</summary>
        static void PioneerReturn(VisualElement host, SimBridge bridge, UiText text, int unit)
        {
            var offer = PioneerReturnOrder(bridge, unit);
            if (!offer.Eligible) return;
            OrderButton(host, bridge, $"pioneer-return-{unit}", text.Format("pioneer.return", Group(text, bridge.State, unit)), !offer.WorkOrdered,
                () => PioneerReturnOrder(bridge, unit, submit: true));
        }

        /// <summary>The one guarded Return for both the rows and the pioneer card (#1549): Eligible when
        /// Qualification.CheckReturn takes the group, WorkOrdered while a Build or Stop is queued for it (that waits for End
        /// turn, which the group would no longer be there for). With <paramref name="submit"/> it queues the order only when
        /// both allow it, so a stale button cannot strand a queued Build or Stop.</summary>
        public static (bool Eligible, bool WorkOrdered) PioneerReturnOrder(SimBridge bridge, int unit, bool submit = false)
        {
            var eligible = Qualification.CheckReturn(bridge.State, unit) == null;
            var working = bridge.Queued.Any(x => (x is PioneerWork w && w.Unit == unit) || (x is StopWork sw && sw.Unit == unit));
            if (submit && eligible && !working) bridge.Queue(new UnitOrder(unit, Qualification.ReturnOrder));
            return (eligible, working);
        }

        static void Workers(SimBridge bridge, string city, int current, int count)
        {
            if (count != current) { bridge.Queue(new AssignWorkers(city, "job", count)); return; }
            if (bridge.QueuedLike(new AssignWorkers(city, "job", 0)) is Command order) bridge.Withdraw(order);
        }

        /// <summary>The pioneer action a site is for, as Projects.Start matches them (R-SITE-001, R-CAMP-001, R-FIELD-001,
        /// R-SWAMP-001), and the suffix of its strings; null for a site no pioneer work is for. A site of two kinds would get
        /// the first here; sites.yaml has none.</summary>
        static (string Action, string Key)? Work(Statecraft.Sim.Site site) =>
            Projects.IsYishuvSite(site) ? (Projects.BuildYishuv, "")
            : Projects.IsCamp(site) ? (Projects.BuildCamp, "_camp")
            : site.Kinds.Contains(Projects.FieldKind) ? (Projects.PlowFields, "_field")
            : site.Kinds.Contains(Projects.SwampKind) ? (Projects.DrySwamp, "_swamp")
            : ((string, string)?)null;

        static string Name(UiText text, Statecraft.Sim.Site site) =>
            text["ui.lang"] == UiLanguage.Hebrew && !string.IsNullOrWhiteSpace(site.NameHe) ? site.NameHe : site.Name;

        static void Site(VisualElement host, SimBridge bridge, UiText text, Statecraft.Sim.Site site, (string Action, string Key) kind, Action<int>? selectPioneer)
        {
            var c = bridge.Content; var s = bridge.State;
            var (action, key) = kind;
            s.Sites.TryGetValue(site.Id, out var work);
            if (work == null)
            {
                // The sim refuses to plow while the hex's yishuv or swamp is unfinished: the same helper Projects.Start asks.
                if (action == Projects.PlowFields && Projects.YishuvToBuildFirst(c, s, site) is Statecraft.Sim.Site first)
                {
                    Line(host, "site-state", text.Format(first.Kinds.Contains(Projects.SwampKind) ? "site.waits_swamp" : "site.waits_yishuv", Name(text, first)));
                    return;
                }
                Line(host, "site-state", text["site.available" + key]);
                Builds(null);
            }
            else if (work.BuiltOn == null)
            {
                var unit = work.Unit!.Value;   // a site being built names its unit (SiteWork)
                GroupLink(host, bridge, text, unit, selectPioneer);
                Line(host, "site-state", text.Format("site.building" + key, Group(text, s, unit), Turns(text, Projects.TurnsToBuild(c, s, unit, site, work.TurnsLeft, work.Progress))));
                var stopping = bridge.QueuedLike(new StopWork(unit)) is StopWork;
                OrderButton(host, bridge, "site-stop", text[stopping ? "site.ordered" : "site.stop" + key], !stopping,
                    () => bridge.Queue(new StopWork(unit)));
                // #2518: the sim takes a Stop and another group's Build of the site in one turn (the Stop frees it, Projects.Stop),
                // so with a Stop queued the idle groups' Build shows, each asked of End turn's own order runner.
                if (stopping) Builds(Preview(bridge, bridge.Queued));
            }
            else Line(host, "site-state", text.Format("site.built" + key, Date(text, work.BuiltOn.Value)));

            // Build with each idle pioneer group; with a preview of the queue (a site whose Stop is queued), only where End turn
            // would take the press.
            void Builds(PreviewResult? current)
            {
                var terms = Projects.Terms(c.RulesAt(s.Date).Mvp!, action);   // the loader requires the rules in the GDD loop
                var idle = s.Units.Values.Where(u => Projects.IsPioneer(u.Type) && !Projects.IsBusy(s, u.Id)).ToList();
                if (idle.Count == 0 && current == null) Line(host, "site-no-halutz", text["site.no_halutz"]);
                // One unit builds a site (question 15): once a group is ordered here, the others' Build is off, as the sim
                // would refuse the second order ("already being built").
                var taken = bridge.Queued.OfType<PioneerWork>().Any(w => w.Site == site.Id);
                foreach (var u in idle)
                {
                    // PioneerWork and StopWork share the unit's key: an order for this unit at this site is this button's.
                    var old = bridge.QueuedLike(new PioneerWork(u.Id, action, site.Id));
                    var ordered = old is PioneerWork p && p.Site == site.Id;
                    OrderButton(host, bridge, $"site-build-{u.Id}", ordered ? text["site.ordered"]
                            : text.Format("site.build" + key, Group(text, s, u.Id), PlayerText.Money(c, "treasury", terms.Cost),
                                Turns(text, Projects.TurnsToBuild(c, s, u.Id, site, terms.Turns, 0))),
                        !ordered && !taken && (current == null || Refused(bridge, current, old, new PioneerWork(u.Id, action, site.Id)) == null),
                        () => bridge.Queue(new PioneerWork(u.Id, action, site.Id)));
                    PioneerReturn(host, bridge, text, u.Id);
                }
            }
        }

        /// <summary>A corridor segment (#792, R-COR-001 to R-COR-003): its name, and Build road or Build railway (its corridor's
        /// kind) with each idle pioneer group, with the kind's cost and the unit's own turns (Projects.Terms,
        /// Corridors.TurnsToBuild); or its turns left and Stop while it is built; or the day it was built. The order is
        /// PioneerWork(unit, action, "corridor:N"), SimBridge's corridor key.</summary>
        static void Segment(VisualElement host, SimBridge bridge, UiText text, CorridorDef d, int index, Action<int>? selectPioneer)
        {
            var c = bridge.Content; var s = bridge.State;
            var action = d.Kind == Corridors.Rail ? Corridors.BuildRail : Corridors.BuildRoad;
            var target = d.Id + ":" + (index + 1).ToString(CultureInfo.InvariantCulture);
            var terms = Projects.Terms(c.RulesAt(s.Date).Mvp!, action);   // the loader requires the rules in the GDD loop
            var name = text["ui.lang"] == UiLanguage.Hebrew && !string.IsNullOrWhiteSpace(d.NameHe) ? d.NameHe : d.Name;
            Line(host, "corridor-name", text.Format("corridor.segment", name, index + 1));
            s.Corridors.TryGetValue(d.Id, out var corridor);
            var work = corridor?.Segments[index];
            if (work == null) Builds(null);
            else if (work.BuiltOn == null)
            {
                var unit = work.Unit!.Value;   // a segment being built names its unit (SegmentWork)
                GroupLink(host, bridge, text, unit, selectPioneer);
                Line(host, "corridor-state", text.Format("site.building", Group(text, s, unit), Turns(text, Corridors.TurnsToBuild(c, s, unit, terms.Turns - work.Progress, work.Carry))));
                var stopping = bridge.QueuedLike(new StopWork(unit)) is StopWork;
                OrderButton(host, bridge, "corridor-stop", text[stopping ? "site.ordered" : "site.stop"], !stopping,
                    () => bridge.Queue(new StopWork(unit)));
                // #2518: as on a site, a queued Stop frees the segment this turn (Corridors.Stop), so the idle groups' Build shows.
                if (stopping) Builds(Preview(bridge, bridge.Queued));
            }
            else Line(host, "corridor-state", text.Format("corridor.built", Date(text, work.BuiltOn.Value)));

            // Build with each idle pioneer group. Without a preview, the segment is free now and Corridors.CheckStart rules; with
            // one (a segment whose Stop is queued, which CheckStart would call taken), End turn's own order runner rules on the press.
            void Builds(PreviewResult? current)
            {
                var idle = s.Units.Values.Where(u => Projects.IsPioneer(u.Type) && !Projects.IsBusy(s, u.Id)).ToList();
                if (idle.Count == 0 && current == null) Line(host, "corridor-no-halutz", text["site.no_halutz"]);
                // One unit a segment (Q-COR-4): once a group is ordered here, the others' Build is off, as the sim would refuse it.
                var taken = bridge.Queued.OfType<PioneerWork>().Any(w => w.Site == target);
                var refusal = current == null ? Corridors.CheckStart(c, s, action, d, index) : null;
                foreach (var u in idle)
                {
                    var old = bridge.QueuedLike(new PioneerWork(u.Id, action, target));
                    var ordered = old is PioneerWork p && p.Site == target;
                    OrderButton(host, bridge, $"corridor-build-{u.Id}", ordered ? text["site.ordered"]
                            : text.Format("corridor.build_" + d.Kind, Group(text, s, u.Id), PlayerText.Money(c, "treasury", terms.Cost),
                                Turns(text, Corridors.TurnsToBuild(c, s, u.Id, terms.Turns, 0))),
                        refusal == null && !ordered && !taken && (current == null || Refused(bridge, current, old, new PioneerWork(u.Id, action, target)) == null),
                        () => bridge.Queue(new PioneerWork(u.Id, action, target)));
                    PioneerReturn(host, bridge, text, u.Id);
                }
            }
        }

        /// <summary>The city projects of hex (q, r) (#1122). A project there shows its state and, while it is built, Cancel
        /// (R-PROJ-002); on a city's own hex the list below then holds only the gdd-0.3 housing repair (R-HOUSE-006, #1700),
        /// which the sim takes there whatever the hex holds. Else, for the cities in reach (Projects.CitiesFor; none: nothing shows), the city that builds: the one
        /// the player picked on this hex, else the queued order's, else the nearest. Build for each kind queues StartProject for
        /// that city and hex, one order a hex (SimBridge's key, so another kind or city replaces it); the Attention is the
        /// bridge's, which refuses an order it cannot pay for as for every order. On a city's own hex (<paramref name="cityHere"/>)
        /// the cities and the kinds go into the ListName list under the ToggleName toggle, which the stylesheet shows only on a
        /// stacked bar or a short window (InfoPanelPresenter.ShortClass) and which opens and closes the list there.</summary>
        static void CityProjects(VisualElement host, SimBridge bridge, UiText text, int q, int r, Func<string, string> townName, bool cityHere)
        {
            var c = bridge.Content; var s = bridge.State;
            string Kind(string id) => PlayerText.Capitalised(ContentNames.Of(text, c.ProjectKinds.First(x => x.Id == id)));
            var kinds = c.ProjectKinds;
            var freed = false;
            if (Projects.CityProjectAt(s, q, r) is CityProject project)
            {
                if (project.BuiltOn is DateTime built)
                {
                    Line(host, "city-project-state", text.Format("city.project_built", Kind(project.Kind), townName(project.City), Date(text, built)));
                    WorkshopPart(host, bridge, text, project, townName);
                }
                else
                {
                    Line(host, "city-project-state", text.Format("city.project_building", Kind(project.Kind), townName(project.City), Turns(text, Projects.CityTurnsToBuild(c, s, project.Kind, project.TurnsLeft, project.Progress))));
                    var cancelled = bridge.QueuedLike(new CancelProject(project.Id)) != null;
                    OrderButton(host, bridge, "city-project-cancel", text[cancelled ? "city.cancel_ordered" : "city.cancel"],
                        !cancelled, () => bridge.Queue(new CancelProject(project.Id)));
                    BuilderPart(host, bridge, text, project);
                    freed = cancelled;
                }
                // #2518: the sim takes a Cancel and a new Start on the hex in one turn (the Cancel removes the project first), so
                // with a Cancel queued every kind shows below, each asked of End turn's own order runner as on a free hex (Refusal).
                // R-HOUSE-006 (#1700): else the sim takes a gdd-0.3 housing repair on its city's own hex whatever that hex holds
                // (Projects.CheckCityReason), so on a city's own hex the repair is still offered under the project; every other
                // kind is refused for the project the line above names. No other ruleset loads the kind: nothing more shows.
                if (!freed)
                {
                    if (!cityHere) return;
                    kinds = c.ProjectKinds.Where(k => k.Id == Projects.HousingRepair).ToList();
                }
            }
            if (cityHere) Repairs(host, bridge, text, q, r, townName);
            var cities = Projects.CitiesFor(c, s, q, r);
            if (cities.Count == 0 || kinds.Count == 0) return;
            var queued = bridge.QueuedLike(new StartProject("", "", q, r)) as StartProject;

            // Ask the sim about the exact queue a press would leave: replace this hex's order in its current slot, or append it,
            // after the committed orders. This costs one preview for each project kind the panel considers while it renders, not
            // on each frame; an earlier order can make a kind that the current state refuses valid.
            (string? kind, string? words) Refusal(ProjectKind k, string city)
            {
                // #2669 with #2679: a finished game's preview refuses every order, which would replace the buttons with that
                // refusal; under gdd-0.3 the panel keeps them, disabled by OrderButton (its same rule), so the ended game stays
                // inspectable. Under the other rules OrderButton does not disable them, so the refusal lines stay.
                if (s.GameOver != null && c.Ruleset == SaveGame.Gdd03Ruleset) return (null, null);
                var press = new StartProject(k.Id, city, q, r);
                var old = bridge.QueuedLike(press);
                var queue = bridge.Queued.ToList();
                var slot = old == null ? -1 : queue.IndexOf(old);
                // An order the Attention left cannot pay for keeps its Build button, as before the preview: the bridge refuses
                // the press and says why (order.no_attention, SimBridge.Queue). Only the rules are asked, on the state the rest
                // of the queue leaves (the press replaces this hex's order, so that order is left out too).
                if (!bridge.CanPay(press))
                {
                    if (slot >= 0) queue.RemoveAt(slot);
                    var rule = Projects.CheckCityReason(c, Simulation.Preview(c, bridge.TurnStart, bridge.Session.Committed.Concat(queue).ToList()).State,
                        k.Id, city, q, r);
                    return rule == null ? (null, null) : (rule.Kind, ReasonText(rule, text, c, townName));
                }
                if (slot >= 0) queue[slot] = press; else queue.Add(press);
                var preview = Simulation.Preview(c, bridge.TurnStart, bridge.Session.Committed.Concat(queue).ToList());
                var rejected = preview.Rejected.FirstOrDefault(x => ReferenceEquals(x.Command, press));
                if (rejected == null) return (null, null);

                var exact = Projects.CheckCityReason(c, preview.State, k.Id, city, q, r);
                return exact != null
                    ? (exact.Kind, ReasonText(exact, text, c, townName))
                    : (null, SimBridge.ReasonText(text, rejected.Reason, c, bridge.TownNamesHe));
            }
            // Owner ruling on #1150 (21 Oct 2026): under the city's own part the full list ran into the left column on a stacked
            // bar or a short window, so there it folds behind one toggle; a refusal is then one tap away. The open state is the
            // host's class, kept across renders (InfoPanelPresenter.Show closes it for a newly chosen hex).
            var list = host;
            if (cityHere)
            {
                Button(host, ToggleName, text.Format("city.projects_toggle", kinds.Count), () => host.ToggleInClassList(OpenClass));
                list = new VisualElement { name = ListName };
                list.AddToClassList(ListName);
                host.Add(list);
            }
            // The pick lives on the host, which the panel keeps across renders; it is for this hex only.
            var city = host.userData is ValueTuple<int, int, string> pick && pick.Item1 == q && pick.Item2 == r && cities.Contains(pick.Item3) ? pick.Item3
                : queued != null && cities.Contains(queued.City) ? queued.City : cities[0];
            // The city's line and, when several can build, the pick on one row, so the part stays short (InfoPanelLayoutTests).
            if (cities.Count == 1) Line(list, "city-project-for", text.Format("city.project_for", townName(city)));
            else
            {
                var row = Row(list, "city-project-cities");
                Line(row, "city-project-for", text.Format("city.project_for", townName(city)));
                foreach (var id in cities)
                    Button(row, "city-project-city-" + id, townName(id), () =>
                    {
                        host.userData = (q, r, id);
                        host.Clear();
                        CityProjects(host, bridge, text, q, r, townName, cityHere);
                        // The pressed button is rebuilt (and now disabled): the focus stays in the row, for the keyboard.
                        host.Q("city-project-cities")?.Query<Button>().Where(b => b.enabledSelf).First()?.Focus();
                    }).SetEnabled(id != city);
            }
            var refusals = kinds.Select(k => Refusal(k, city)).ToList();
            var words = refusals.Select(x => x.words).ToList();
            // Every kind refused for one reason (not land, a placement there, the turn's limit): said once, with no buttons,
            // as the map actions do (#398). A kind this city lacks the resource for (R-PROJ-005: the winery outside Rishon
            // LeZion) does not split that line into one per kind, nor does the gdd-0.3 housing repair off its city's own hex
            // (R-HOUSE-006: repair_city_hex comes before the shared reasons, so it would hide them on every other hex).
            var shared = words.Where((x, i) => refusals[i].kind != "no_resource" && refusals[i].kind != "repair_city_hex").ToList();
            if (words.All(x => x != null) && shared.Count > 0 && shared.Distinct().Count() == 1) { Line(list, "city-project-reason", shared[0]!); return; }
            // A kind the sim refuses shows its reason alone, which names the kind (no disabled Build above it: one line, not two).
            for (int i = 0; i < kinds.Count; i++)
            {
                var k = kinds[i];
                if (words[i] != null) { Line(list, $"city-project-{k.Id}-reason", words[i]!); continue; }
                var ordered = queued != null && queued.ProjectKind == k.Id && queued.City == city;
                OrderButton(list, bridge, "city-project-" + k.Id, ordered ? text.Format("city.project_ordered", ContentNames.Of(text, k))
                        : text.Format("city.project_start", ContentNames.Of(text, k), PlayerText.Money(c, "treasury", k.Cost), Turns(text, Projects.CityTurnsToBuild(c, s, k.Id, k.Turns, 0))),
                    !ordered, () => bridge.Queue(new StartProject(k.Id, city, q, r)));
            }
        }

        /// <summary>#1722 slice E (#1701; R-ARMS-005 to R-ARMS-007), gdd-0.3 only: on a built arms workshop (a kind with a worker
        /// slot, R-ARMS-004), its city's staffing stepper and this workshop's state. AssignWorkers(city, "workshop", n) staffs the
        /// city's first n built workshops in ascending id, so the stepper is the city's count (Workshops.Staffed, or the queued
        /// order's) of Workshops.Built; stepping back to the current count withdraws the order. + is off where Workshops.Check,
        /// asked with this turn's queue, refuses one more, and while a workshop is left unstaffed that refusal shows in the UI's
        /// language (SimBridge.ReasonText). This workshop: staffed or not (its Workshop record, or with an order queued what the
        /// order makes it, Workshops.Staffs), its cycle under way (staffed
        /// months of Workshops.CycleMonths and the Money paid) or, staffed before or not, the next cycle's price
        /// (Workshops.NextCyclePrice, what the production step would charge), the pause while the enemy holds its city
        /// (Cities.Held, R-CITY-010), and the last turn's pauses for its city as the Why screen words them
        /// (CauseKeys.WorkshopPaused). Nothing is computed here.</summary>
        static void WorkshopPart(VisualElement host, SimBridge bridge, UiText text, CityProject project, Func<string, string> townName)
        {
            var c = bridge.Content; var s = bridge.State;
            if (c.Ruleset != SaveGame.Gdd03Ruleset || c.ProjectKinds.First(k => k.Id == project.Kind).WorkerSlots == 0) return;
            var city = project.City;
            var built = Workshops.Built(c, s, city);
            var staffed = Workshops.Staffed(s, city);
            var queued = bridge.QueuedLike(new AssignWorkers(city, Workshops.Role, 0)) as AssignWorkers;
            var target = queued?.Count ?? staffed;
            // #2743 item 2: over the queue less the orders End turn refuses anyway, which take nobody.
            var refusal = Workshops.Check(c, s, city, target + 1, Live(bridge, Preview(bridge, bridge.Queued)));
            var row = Row(host, "city-workshops-row");
            OrderButton(row, bridge, "city-workshops-less", "−", target > 0, () => Staff(bridge, city, staffed, target - 1));
            Line(row, "city-workshops", text.Format(queued == null ? "city.workshops_staffed" : "city.workshops_ordered", target, built));
            OrderButton(row, bridge, "city-workshops-more", "+", refusal == null, () => Staff(bridge, city, staffed, target + 1));
            if (refusal != null && target < built) Line(host, "city-workshops-reason", SimBridge.ReasonText(text, refusal, c, bridge.TownNamesHe));

            s.Workshops.TryGetValue(project.Id, out var w);
            // #2711 item 1: with an order queued, the line follows it as the count above does (Workshops.Staffs), not the record.
            Line(host, "city-workshop-state", text[queued != null
                ? (Workshops.Staffs(c, s, project, target) ? "city.workshop_ordered_staffed" : "city.workshop_ordered_unstaffed")
                : w?.Staffed == true ? "city.workshop_staffed" : "city.workshop_unstaffed"]);
            if (w != null && w.PaidCost is decimal paid)
                Line(host, "city-workshop-cycle", text.Format("city.workshop_cycle", w.Progress, Workshops.CycleMonths(c)!.Value, PlayerText.Money(c, "treasury", (double)paid)));
            else if (Workshops.NextCyclePrice(c, s, project.Id) is decimal next)
                Line(host, "city-workshop-cycle", text.Format("city.workshop_next", PlayerText.Money(c, "treasury", (double)next)));
            if (Cities.Held(c, s).Contains(city)) Line(host, "city-workshop-held", text.Format("city.workshop_held", townName(city)));
            var paused = (bridge.Session.Last?.Why ?? Array.Empty<Cause>()).Where(x => x.Key == CauseKeys.WorkshopPaused && x.Target == city && x.Args.Count > 1 && x.Args[1] == project.Id.ToString(CultureInfo.InvariantCulture))
                .Select(x => CauseText.Line(x, c, Array.Empty<Statecraft.Game.Map.Units.UnitEntry>(), text, bridge.TownNamesHe)).Distinct().ToList();
            for (int i = 0; i < paused.Count; i++) Line(host, "city-workshop-paused-" + i.ToString(CultureInfo.InvariantCulture), paused[i]);
        }

        /// <summary>R-CITY-011 (#1700, #2477), gdd-0.3 only: on a city project being built, whether it has a builder, and its
        /// city's builder stepper. AssignWorkers(city, "build", n) sets how many of the city's projects being built have one
        /// (Projects.AssignBuilders), so the stepper is the city's count (Projects.Builders, or the queued order's) of its
        /// projects being built; stepping back to the current count withdraws the order. + asks End turn's own order runner
        /// (Simulation.Preview, as Train does) whether n + 1 in the order's slot would be refused, or would make it refuse an
        /// order of the queue it accepts now, so the queue's job, training, workshop, start and builder orders all count
        /// whichever runs first. While a project is left without one, that refusal shows in the UI's language. A repair's line
        /// is <paramref name="line"/>, and none when it is null (its row in the city's list says it, Repairs); <paramref name="stepper"/>
        /// off leaves the stepper to another project of the hex (Repairs).</summary>
        static void BuilderPart(VisualElement host, SimBridge bridge, UiText text, CityProject project, string? line = "city-project-builder", bool stepper = true)
        {
            var c = bridge.Content; var s = bridge.State;
            if (c.Ruleset != SaveGame.Gdd03Ruleset) return;
            var city = project.City;
            if (line != null) Line(host, line, text[project.Builder ? "city.project_builder" : "city.project_no_builder"]);
            if (!stepper) return;
            var building = s.CityProjects.Values.Count(p => p.City == city && p.BuiltOn == null);
            var builders = Projects.Builders(s, city);
            var queued = bridge.QueuedLike(new AssignWorkers(city, Projects.BuildRole, 0)) as AssignWorkers;
            var target = queued?.Count ?? builders;
            string? refusal = null;
            var accepted = true;
            // A finished game's preview refuses every order: OrderButton already disables + there (#2669), with no reason line.
            if (s.GameOver == null && target < building)
            {
                var press = new AssignWorkers(city, Projects.BuildRole, target + 1);
                var queue = bridge.Queued.ToList();
                var slot = queued == null ? -1 : queue.IndexOf(queued);
                if (slot >= 0) queue[slot] = press; else queue.Add(press);
                var current = Simulation.Preview(c, bridge.TurnStart, bridge.Session.Committed.Concat(bridge.Queued).ToList());
                var preview = Simulation.Preview(c, bridge.TurnStart, bridge.Session.Committed.Concat(queue).ToList());
                refusal = preview.Rejected.FirstOrDefault(x => ReferenceEquals(x.Command, press))?.Reason;
                // Nor may the press make End turn refuse a queued order it accepts now (a Train or a workshop's worker); then
                // that order's refusal is the reason line (#2477 review), so a greyed + always says why.
                var broken = refusal != null ? null : preview.Rejected.FirstOrDefault(r => !ReferenceEquals(r.Command, press)
                    && queue.Any(x => ReferenceEquals(x, r.Command)) && !current.Rejected.Any(k => ReferenceEquals(k.Command, r.Command)));
                accepted = refusal == null && broken == null;
                refusal ??= broken?.Reason;
            }
            var row = Row(host, "city-builders-row");
            OrderButton(row, bridge, "city-builders-less", "−", target > 0, () => Build(bridge, city, builders, target - 1));
            Line(row, "city-builders", text.Format(queued == null ? "city.builders" : "city.builders_ordered", target, building));
            OrderButton(row, bridge, "city-builders-more", "+", target < building && accepted, () => Build(bridge, city, builders, target + 1));
            if (refusal != null) Line(host, "city-builders-reason", SimBridge.ReasonText(text, refusal, c, bridge.TownNamesHe));
        }

        /// <summary>R-HOUSE-006 with R-CITY-011 (#2477 review): a housing repair being built has no hex of its own
        /// (Projects.CityProjectAt skips it), so it shows on its city's own hex, where it is offered: its line and whether it
        /// has a builder. Its city's builder stepper shows once on the hex: under the hex's own project being built when that
        /// is the same city's, else under the city's first repair, so a city whose only project being built is a repair has
        /// one too. Where the repair's city has its block on this hex and so its project list (ProjectList, #1722), the list's
        /// row is the repair's line and its builder, so only the stepper shows here (owner, 8 November 2026: "Drop the old lines
        /// here (Recommended)": each repair shows once).</summary>
        static void Repairs(VisualElement host, SimBridge bridge, UiText text, int q, int r, Func<string, string> townName)
        {
            var c = bridge.Content; var s = bridge.State;
            var stepped = new System.Collections.Generic.HashSet<string>();
            if (Projects.CityProjectAt(s, q, r) is CityProject { BuiltOn: null } here) stepped.Add(here.City);
            foreach (var repair in s.CityProjects.Values.Where(p => p.Kind == Projects.HousingRepair && p.Q == q && p.R == r && p.BuiltOn == null).OrderBy(p => p.Id))
            {
                if (Listed(c, s, repair.City) && c.SettlementHexes.Any(x => x.Id == repair.City && x.Q == q && x.R == r))
                {
                    BuilderPart(host, bridge, text, repair, null, stepped.Add(repair.City));
                    continue;
                }
                var kind = PlayerText.Capitalised(ContentNames.Of(text, c.ProjectKinds.First(x => x.Id == repair.Kind)));
                Line(host, "city-repair-state", text.Format("city.project_building", kind, townName(repair.City),
                    Turns(text, Projects.CityTurnsToBuild(c, s, repair.Kind, repair.TurnsLeft, repair.Progress))));
                BuilderPart(host, bridge, text, repair, "city-repair-builder", stepped.Add(repair.City));
            }
        }

        /// <summary>End turn's own order runner (GameSession.EndTurn: Step from the turn's start over the committed orders, then
        /// <paramref name="queue"/>), as ArmsPurchasePresenter asks it.</summary>
        static PreviewResult Preview(SimBridge bridge, System.Collections.Generic.IEnumerable<Command> queue) =>
            Simulation.Preview(bridge.Content, bridge.TurnStart, bridge.Session.Committed.Concat(queue).ToList());

        /// <summary>The bridge's queue less the orders End turn refuses anyway (<paramref name="current"/>, the queue's preview):
        /// those take no civilian, job or workshop place, so the sim's limits are asked without them (#2743 item 2).</summary>
        static System.Collections.Generic.List<Command> Live(SimBridge bridge, PreviewResult current) =>
            bridge.Queued.Where(x => !current.Rejected.Any(r => ReferenceEquals(r.Command, x))).ToList();

        /// <summary>Why End turn would refuse <paramref name="press"/> queued where SimBridge.Queue puts it (in
        /// <paramref name="old"/>'s slot, else last): its own refusal, else that of a queued order it accepts now
        /// (<paramref name="current"/>, the queue's preview) and the press would make it refuse; null where it takes them all.</summary>
        static Rejection? Refused(SimBridge bridge, PreviewResult current, Command? old, Command press)
        {
            var queue = bridge.Queued.ToList();
            var slot = old == null ? -1 : queue.IndexOf(old);
            if (slot >= 0) queue[slot] = press; else queue.Add(press);
            var preview = Preview(bridge, queue);
            return preview.Rejected.FirstOrDefault(x => ReferenceEquals(x.Command, press))
                ?? preview.Rejected.FirstOrDefault(r => queue.Any(x => ReferenceEquals(x, r.Command)) && !current.Rejected.Any(k => ReferenceEquals(k.Command, r.Command)));
        }

        static void Build(SimBridge bridge, string city, int current, int count)
        {
            if (count != current) { bridge.Queue(new AssignWorkers(city, Projects.BuildRole, count)); return; }
            if (bridge.QueuedLike(new AssignWorkers(city, Projects.BuildRole, 0)) is Command order) bridge.Withdraw(order);
        }

        static void Staff(SimBridge bridge, string city, int current, int count)
        {
            if (count != current) { bridge.Queue(new AssignWorkers(city, Workshops.Role, count)); return; }
            if (bridge.QueuedLike(new AssignWorkers(city, Workshops.Role, 0)) is Command order) bridge.Withdraw(order);
        }

        /// <summary>A city-project refusal (Projects.CheckCityReason) in the UI's language: the map actions' strings where the
        /// sim's English is theirs, else city.project_reason.*. The sim's English for the kinds this panel cannot meet: an
        /// unknown kind or city, a distance (CitiesFor lists only the cities in reach) or another project on the hex (its
        /// state shows instead).</summary>
        static string ReasonText(MapActionReason reason, UiText text, Content c, Func<string, string> townName)
        {
            switch (reason.Kind)
            {
                case "maabarot_policy": case "not_land": case "depopulated":
                    return text["info.map_action_reason." + reason.Kind];
                case "occupied": return text.Format("info.map_action_reason.occupied", text["info.map_action." + reason.Values[0]]);
                case "no_resource": return text.Format("city.project_reason.no_resource", townName(reason.Values[0]), ResourceName(text, reason.Values[1]),
                    ContentNames.Of(text, c.ProjectKinds.First(x => x.Id == reason.Values[2])));
                case "city_cap": return text.Format("city.project_reason.city_cap", townName(reason.Values[0]));   // R-PROJ-001, gdd-0.3 (#1700)
                case "repair_city_hex": return text.Format("city.project_reason.repair_city_hex", townName(reason.Values[0]));   // R-HOUSE-006, gdd-0.3
                case "turn_cap": return text.Format("city.project_reason.turn_cap", int.Parse(reason.Values[0], CultureInfo.InvariantCulture));
                default: return reason.Text;
            }
        }

        /// <summary>A resource's name in the UI's language (#1781), by its id. A resource is a record nested inside a
        /// city, so it cannot carry its own name_he: the translation contract binds a &lt;file&gt;#&lt;list&gt;.&lt;id&gt;.&lt;field&gt;
        /// key only (HebrewOverlay.Bindings), and a nested record has no such key. The name is a UI string instead, and
        /// without one the id stands, which is what the line showed before.</summary>
        static string ResourceName(UiText text, string id) =>
            text.Has("city.resource." + id) ? text["city.resource." + id] : id;

        /// <summary>"1 group" or "n groups" (population groups, D-A1), in the UI's language.</summary>
        public static string Groups(UiText t, int n) => n == 1 ? t["city.groups_one"] : t.Format("city.groups", n);
        /// <summary>"1 turn" or "n turns", in the UI's language.</summary>
        public static string Turns(UiText t, int n) => n == 1 ? t["city.turns_one"] : t.Format("city.turns", n);
        /// <summary>A pioneer group's name for the player: "halutz group n", numbered from 1 among the pioneer units (halutz and
        /// veteran, Projects.IsPioneer) in id order, so a group keeps its number when it becomes a veteran (unit ids are shared
        /// with cohorts and start at 0, so they are no names).</summary>
        public static string Group(UiText t, GameState s, int unit) =>
            t.Format("site.group", 1 + s.Units.Values.Where(u => Projects.IsPioneer(u.Type)).Select(u => u.Id).TakeWhile(id => id != unit).Count());

        /// <summary>A date in the UI's language, as the event card writes it (EventCardPresenter.ObjectiveLine).</summary>
        static string Date(UiText t, DateTime d) => t.Format("date.day_month_year", d.Day, t["date.month_" + d.Month], d.Year);

        /// <summary>The worker's link to its pioneer card (#1549) on a site or segment under way; none without a callback, so
        /// existing callers render as before. Idle candidates get none: they open from their own hex's list, and a link per
        /// candidate per segment ran a three-segment hex off a 1024x768 window (InfoPanelLayoutTests).</summary>
        static void GroupLink(VisualElement host, SimBridge bridge, UiText text, int id, Action<int>? select)
        {
            if (select == null) return;
            var b = Button(host, "pioneer-project-" + id.ToString(CultureInfo.InvariantCulture),
                text.Format("pioneer.card.open", Group(text, bridge.State, id)), () => select(id));
            b.AddToClassList("pioneer-link");
        }

        static Label Line(VisualElement parent, string name, string value)
        {
            var l = new Label { name = name };
            l.AddToClassList("wrap"); l.AddToClassList(LineClass);
            parent.Add(l);
            l.text = value;   // set once on the panel, so UiDirection's change callback gives it its direction (#1915)
            return l;
        }

        static VisualElement Row(VisualElement parent, string name)
        {
            var row = new VisualElement { name = name };
            row.AddToClassList("row"); row.AddToClassList(RowClass);
            parent.Add(row);
            return row;
        }

        static Button Button(VisualElement parent, string name, string label, Action onClick)
        {
            var b = new Button(onClick) { name = name };
            parent.Add(b);
            b.text = label;   // set once on the panel, so UiDirection's change callback gives it its direction (#1915)
            return b;
        }

        /// <summary>An order-producing control: in gdd-0.3, after GameOver it is read-only like the other order panels, while
        /// disclosure and navigation controls made with <see cref="Button"/> stay available for inspecting the finished game.</summary>
        static Button OrderButton(VisualElement parent, SimBridge bridge, string name, string label, bool enabled, Action onClick)
        {
            var b = Button(parent, name, label, onClick);
            b.SetEnabled(enabled && (bridge.Content.Ruleset != SaveGame.Gdd03Ruleset || bridge.State.GameOver == null));
            return b;
        }
    }
}