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.

47.8 KB
Raw Blame
#nullable enable
using System.Linq;
using System.Collections.Generic;
using Statecraft.Game.Map.Units;
using Statecraft.Sim;
using UnityEngine.UIElements;

namespace Statecraft.Game.UI
{
    /// <summary>The decision card, in the middle of the screen under the bar (decision cards, 2026-10-13): the first pending
    /// event the player has not yet answered, with its 16:9 media header (an archival photograph of the event with its credit
    /// line, as the promo's card; EventImageCatalog) or, when the event has none, the responsible minister's portrait, the
    /// text with today's office holders filled in, and one button per option.
    /// While it shows, the root has OpenClass: a backdrop dims the map and takes the pointer, and ScreenNav.DisableCovered
    /// takes the panels under it out of reach. Hide collapses it to the "Decision waiting" button, which brings it back; a
    /// new event opens it again by itself. A new event puts the keyboard focus on the card itself, not on an
    /// option, so no choice is lit as if recommended; Tab then reaches the options in order.
    /// A choice is an order: it takes effect at End Turn, and an unanswered event is delegated to the minister.</summary>
    public sealed class EventCardPresenter : System.IDisposable
    {
        /// <summary>The portrait thumbnail's size in the card (Statecraft.uss .event-image).</summary>
        public const float PortraitWidth = 96f, PortraitHeight = 128f;
        /// <summary>The class on each option button (Statecraft.uss).</summary>
        public const string OptionClass = "event-option";
        /// <summary>On the "root" element while the card shows (not collapsed): Statecraft.uss shows the backdrop.</summary>
        public const string OpenClass = "event-open";
        /// <summary>On the "root" element while the card shows and no start screen or screen covers it (set by
        /// ScreenNav.DisableCovered): the panels under the backdrop are disabled and the toast moves clear of the card.</summary>
        public const string ModalClass = "event-modal";
        /// <summary>The media header's width over its height (the photographs and the clips are 960x540).</summary>
        public const float MediaAspect = 16f / 9f;
        /// <summary>On End Turn while the shown card cannot be answered with the Attention left (#1034): Statecraft.uss
        /// highlights it, as ending the turn is then the way on (EventSystem.Delegate hands the card to its minister).</summary>
        public const string EndTurnWaitingClass = "end-turn-waiting";
        /// <summary>The line under an option that returns the course to the record (EventOption.Rejoin, #954; Statecraft.uss).</summary>
        public const string RejoinClass = "event-rejoin";
        /// <summary>One line under an option for one of its effects, from the sim's preview (#1125, R-EVT-005; Statecraft.uss).</summary>
        public const string EffectClass = "event-effect";
        public const string RequirementClass = "event-requirement";
        public const string MissingRequirementClass = "event-requirement-unmet";
        /// <summary>The red line under an operation option that waits for, or is ended by, its front's armistice (Q3).</summary>
        public const string ArmisticeClass = "event-requirement-armistice";

        /// <summary>The map's sourced unit rows, supplied by GameRoot after map parsing, for operation requirement names.</summary>
        public IReadOnlyList<UnitEntry> Units { get; set; } = System.Array.Empty<UnitEntry>();

        readonly VisualElement card; readonly SimBridge bridge; readonly UiText text; readonly PortraitCatalog? portraits;
        readonly EventImageCatalog? photos;
        /// <summary>The catalog when the first event shows (EventPhotos.Get: off the boot path, issue #321), when photos is null.</summary>
        readonly System.Func<EventImageCatalog?>? photosLater;
        /// <summary>The card was built under the start screen and it has not closed yet (issue #592): the photograph (and the
        /// portrait in its place) waits for onUncovered, so a Continue with a decision waiting loads no catalog in GameRoot.Begin.</summary>
        bool photoWaits;
        /// <summary>A screenshot run (HiddenInCaptures): the card never shows, so the captures show the map.</summary>
        readonly bool hiddenInCapture;
        /// <summary>Tests: the card is waiting for the start screen to close before it looks up its photograph.</summary>
        internal bool PhotoWaits => photoWaits;
        readonly VisualElement band, head, options, layer, hudRoot; readonly Label credit, delegateLine;
        readonly VisualElement? toast; float toastDefaultTop = float.NaN;
        /// <summary>The body: the text and the options with their effect lines, which scroll together only when they overflow
        /// the card (#1853); the head above it and the foot with Hide below it stay pinned.</summary>
        readonly ScrollView scroll;
        readonly Button? endTurn;
        readonly Button hide, reopen, illustrationSwitch;
        readonly System.Action onHide, onReopen, onUncovered;
        readonly EventCallback<PointerDownEvent> onHidePointer;
        readonly EventCallback<NavigationSubmitEvent> onHideSubmit;
        readonly EventCallback<NavigationCancelEvent> onCancel;
        /// <summary>The last Hide came from the pointer (PointerBlur's rule: no focus fill left behind for a mouse click).</summary>
        bool hideByPointer;
        /// <summary>The session the card last showed: a new one (New Game, a load) forgets what was collapsed or focused.</summary>
        GameSession? session;
        readonly CardVideo? video; readonly System.Func<string, EventVideoMapping.Row?>? clipFor;
        /// <summary>The shown event's clip URL and its alt text, or null (none, video off, or it failed this session).</summary>
        string? clip, clipAlt;
        /// <summary>The player chose Illustration: kept for the session (not saved), so later cards open on their clip too.</summary>
        bool illustration;
        /// <summary>Events whose clip failed this session: they show the photograph and no switch.</summary>
        readonly System.Collections.Generic.HashSet<string> failed = new System.Collections.Generic.HashSet<string>();
        readonly System.Action onSwitch;
        readonly PressSource presses;
        /// <summary>The event the player collapsed the card on (Hide), or null; a different event opens the card again.</summary>
        string? collapsedFor;
        /// <summary>The event whose first option last took the focus, so an event already open never takes it again.</summary>
        string? focusedFor;
        /// <summary>The event whose card last raised Opened, so a card already in view never raises it again.</summary>
        string? openedFor;
        /// <summary>The event the body was last put back to its top for: a new event opens at its text, never part way down
        /// the last card's options (#1853).</summary>
        string? scrolledFor;
        float appliedWidth = float.NaN;

        /// <param name="video">The illustration loop's player, or null when video is off (CardVideo.ForcedOff): then the
        /// card never offers the Illustration switch.</param>
        /// <param name="clipFor">An event's clip (event-videos.yaml), or null when it has none.</param>
        /// <param name="photosLater">With no <paramref name="photos"/>: gives the catalog, asked only once an event shows.</param>
        /// <param name="underStartScreen">The start screen goes up over the card once it is built (GameRoot.Begin): the card
        /// looks up no photograph until the screen closes, then renders again with it before it is first seen (issue #592).</param>
        /// <param name="hiddenInCapture">A screenshot run (HiddenInCaptures): neither the card, its scrim nor "Decision
        /// waiting" ever shows. Shown still names the event; the sim is untouched.</param>
        public EventCardPresenter(VisualElement root, SimBridge bridge, UiText text, PortraitCatalog? portraits, EventImageCatalog? photos = null,
            CardVideo? video = null, System.Func<string, EventVideoMapping.Row?>? clipFor = null, System.Func<EventImageCatalog?>? photosLater = null,
            bool underStartScreen = false, bool hiddenInCapture = false)
        {
            photoWaits = underStartScreen;
            this.hiddenInCapture = hiddenInCapture;
            this.video = clipFor == null ? null : video; this.clipFor = clipFor;
            card = root.Q<VisualElement>("event-card"); this.bridge = bridge; this.text = text; this.portraits = portraits; this.photos = photos; this.photosLater = photosLater;
            band = card.Q<VisualElement>("event-photo"); credit = card.Q<Label>("event-photo-credit");
            // The band and its credit settle the drop (FitPhoto); the column, which only the window sizes, brings a dropped
            // photograph back when the window grows. A hidden element keeps its old layout, so a band shown again at the
            // size it was dropped at gets no geometry event of its own; the head below it always moves, so it checks too.
            head = card.Q<VisualElement>(className: "event-head");
            scroll = card.Q<ScrollView>("event-scroll"); options = card.Q<VisualElement>("event-options");
            delegateLine = card.Q<Label>("event-delegate");
            layer = card.parent; hudRoot = root.Q("root") ?? root;
            endTurn = hudRoot.Q<Button>("end-turn");
            hide = card.Q<Button>("event-hide"); reopen = layer.Q<Button>("event-reopen");
            hide.text = text["event.hide"]; reopen.text = text["event.reopen"];
            card.Q<Label>("event-draft").text = text["event.draft"];
            onHide = Collapse; onReopen = Reopen;
            onUncovered = () =>
            {
                // A cover has closed: render the first visible cue too; a start-screen photograph waits until now (#592).
                photoWaits = false;
                if (Shown != null) Render();
                focusedFor = null; if (!hiddenInCapture && !heldForPlayback && Shown != null && !Collapsed) FocusCard(Shown.Id, force: true);
            };
            onHidePointer = _ => hideByPointer = true;
            onHideSubmit = _ => hideByPointer = false;
            onCancel = e => { if (Escape()) e.StopPropagation(); };
            hide.clicked += onHide; reopen.clicked += onReopen;
            card.focusable = true; card.tabIndex = 0;   // the card takes the focus itself (FocusCard); Statecraft.uss .event-card:focus
            // Hide with the pointer leaves no focus fill on "Decision waiting" (PointerBlur's rule); with the keyboard it moves there.
            hide.RegisterCallback<PointerDownEvent>(onHidePointer, TrickleDown.TrickleDown);
            hide.RegisterCallback<NavigationSubmitEvent>(onHideSubmit, TrickleDown.TrickleDown);
            // Escape on the open card is Hide (GameRoot also polls the key when nothing has the focus: Escape()).
            card.RegisterCallback<NavigationCancelEvent>(onCancel);
            // A start screen or a screen that covered the layer has closed (ScreenNav.DisableCovered): the open card takes
            // the focus it could not take under it.
            ScreenNav.OnUncovered(layer, onUncovered);
            illustrationSwitch = card.Q<Button>("event-illustration");
            onSwitch = () => { illustration = !illustration; ApplyIllustration(); };
            illustrationSwitch.clicked += onSwitch;
            foreach (var e in new[] { band, credit, head, scroll, options }) e.RegisterCallback<GeometryChangedEvent>(OnPhotoGeometry);
            layer.RegisterCallback<GeometryChangedEvent>(OnColumnGeometry);
            toast = hudRoot.Q("toast");
            toast?.RegisterCallback<GeometryChangedEvent>(OnToastGeometry);
            card.RegisterCallback<GeometryChangedEvent>(OnToastGeometry);
            card.RegisterCallback<GeometryChangedEvent>(OnCardGeometry);
            presses = new PressSource(options);
            bridge.Changed += Render;
            Render();
        }

        /// <summary>True for a screenshot run (?shot, -shot; VisualShots.Requested) that is not also a smoke run: the card is
        /// then never shown, so the captures show the map, as before the GDD cutover opened every new game on a card. The
        /// units are left out of the same runs (UnitLayer.HiddenInCaptures). A smoke run presses the card's options, so it
        /// keeps the card; with no flag (normal play) the card shows.</summary>
        public static bool HiddenInCaptures(string? url, string[] args, bool webgl) =>
            Statecraft.Game.Map.VisualShots.Requested(url, args, webgl) && GameRoot.SmokeTurns(url, args, webgl) == 0;

        /// <summary>Unsubscribes from the bridge, removes the option buttons and hides the card (the owner calls this when disabled).</summary>
        public void Dispose()
        {
            bridge.Changed -= Render;
            hide.clicked -= onHide; reopen.clicked -= onReopen;
            hide.UnregisterCallback(onHidePointer, TrickleDown.TrickleDown); hide.UnregisterCallback(onHideSubmit, TrickleDown.TrickleDown);
            card.UnregisterCallback(onCancel);
            ScreenNav.OnUncovered(layer, null);
            illustrationSwitch.clicked -= onSwitch;
            video?.Stop();
            foreach (var e in new[] { band, credit, head, scroll, options }) e.UnregisterCallback<GeometryChangedEvent>(OnPhotoGeometry);
            layer.UnregisterCallback<GeometryChangedEvent>(OnColumnGeometry);
            toast?.UnregisterCallback<GeometryChangedEvent>(OnToastGeometry);
            card.UnregisterCallback<GeometryChangedEvent>(OnToastGeometry);
            card.UnregisterCallback<GeometryChangedEvent>(OnCardGeometry);
            presses.Dispose();
            card.Q<VisualElement>("event-options")?.Clear(); card.style.display = DisplayStyle.None;
            reopen.style.display = DisplayStyle.None;
            hudRoot.RemoveFromClassList(OpenClass);
            endTurn?.RemoveFromClassList(EndTurnWaitingClass);
            ScreenNav.DisableCovered(hudRoot);
        }

        /// <summary>True while the card is collapsed to the "Decision waiting" button (Hide).</summary>
        public bool Collapsed => Shown != null && collapsedFor == Shown.Id;

        /// <summary>Hide: the card gives the map back and waits behind the "Decision waiting" button, which takes the focus.</summary>
        public void Collapse() => Collapse(takeFocus: true);
        int collapsedAt = -1;
        internal bool CollapsedThisFrame => collapsedAt == UnityEngine.Time.frameCount;

        /// <summary>Hide; with <paramref name="takeFocus"/> false "Decision waiting" leaves the focus where it is (the
        /// advisor opening chain hides the card while its popup has the focus).</summary>
        public void Collapse(bool takeFocus)
        {
            if (Shown == null) return;
            collapsedFor = Shown.Id; collapsedAt = UnityEngine.Time.frameCount;
            Render();
            if (!takeFocus) return;
            if (hideByPointer) { hideByPointer = false; return; }
            reopen.Focus();
            // Tried again once styles resolve: the button was hidden a moment ago and may not take it yet.
            reopen.schedule.Execute(() => { if (Collapsed && reopen.focusController?.focusedElement != reopen) reopen.Focus(); });
        }

        /// <summary>Escape: Hide, when the card is open and in reach. True when it did.</summary>
        public bool Escape()
        {
            if (Shown == null || Collapsed || !layer.enabledInHierarchy) return false;
            hideByPointer = false;
            Collapse();
            return true;
        }

        /// <summary>"Decision waiting": the card opens again and takes the focus.</summary>
        public void Reopen()
        {
            collapsedFor = null; focusedFor = null;
            Render();
        }

        bool heldForPlayback;
        /// <summary>#2202: true while End turn's enemy playback runs (EnemyTurnPlayback.Holding; owner, Q1 a: the card waits for
        /// it). The card and "Decision waiting" stay out of view and a new card raises <see cref="Opened"/>, with its cue,
        /// only once the playback ends. Nothing is answered or queued here: the card is the same card, shown later.</summary>
        public bool HeldForPlayback
        {
            get => heldForPlayback;
            set
            {
                if (heldForPlayback == value) return;
                heldForPlayback = value;
                if (value) { Render(); return; }
                // Back in view: it takes the focus as from under a cover (#2967 review, N1), whatever had it before the hold.
                focusedFor = null; restoring = true;
                try { Render(); }
                finally { restoring = false; }
            }
        }
        bool restoring;   // the held card is coming back (HeldForPlayback false): FocusCard takes the focus over any other

        /// <summary>The event the card shows, or null when every pending event has a queued answer.</summary>
        public GameEvent? Shown { get; private set; }

        /// <summary>Raised with the event's id when its card comes into view: once per showing, never while the card waits
        /// under the start screen, is collapsed or is hidden in a capture run (GameAudio's cue, #39).</summary>
        public event System.Action<string>? Opened;

        /// <summary>Raised at the end of every render, whatever it showed: the capture dialog (CaptureDialogPresenter) waits
        /// while this card is open, and follows it when it is hidden, answered or opened again.</summary>
        public event System.Action? Rendered;

        public void Render()
        {
            try { RenderCard(); }
            finally { Rendered?.Invoke(); }
        }

        void RenderCard()
        {
            var c = bridge.Content; var s = bridge.State;
            var pending = s.PendingEvents.Select(id => c.Events.First(e => e.Id == id)).ToList();
            var open = pending.Where(e => bridge.QueuedLike(new ChooseEventOption(e.Id, "")) == null && !bridge.EndingCardSeen(e.Id))
                // R-ENEMY-007: an operation card that waits (postponed, for its units) is shown after the turn's other cards, and one
                // that waits for its front's pending armistice after that armistice (Q3, owner, 7 November 2026: "Decide armistice
                // first (Recommended)"), so the cards the player can decide now come first. A stable sort: otherwise as before.
                .OrderBy(e => s.PostponedOperations.ContainsKey(e.Id)
                    || e.Options.Any(o => EventSystem.ArmisticeBlock(c, s, e, o) == EventSystem.RefusedOperationArmisticeFirst) ? 1 : 0)
                .ToList();
            Shown = open.FirstOrDefault();
            if (Shown == null) { collapsedFor = null; openedFor = null; scrolledFor = null; }
            if (bridge.Session != session) { session = bridge.Session; collapsedFor = null; focusedFor = null; openedFor = null; scrolledFor = null; }
            var shown = !hiddenInCapture && !heldForPlayback && Shown != null && !Collapsed;
            ScreenNav.Show(card, shown);   // #1106: grows in, shrinks away
            card.SetEnabled(shown);   // a child of an undisplayed element can still take the focus (#400): a collapsed card's options must not
            reopen.style.display = !hiddenInCapture && !heldForPlayback && Collapsed ? DisplayStyle.Flex : DisplayStyle.None;
            hudRoot.EnableInClassList(OpenClass, shown);
            ScreenNav.DisableCovered(hudRoot);
            // An answer is an order and costs Attention (choose_event_option): the bridge prices it and checks it as Queue
            // does. When the turn's Attention left cannot pay, every option would be refused (#1034, #1043): the options are
            // greyed out with their price, the card says End Turn hands it to its minister, and End Turn is highlighted.
            var answer = Shown == null ? null : new ChooseEventOption(Shown.Id, "");
            // A card on the turn that ended the game (#2536) is answered on the spot (Choose): no order, so no price.
            var ending = Shown != null && bridge.IsEndingCard(Shown.Id);
            var price = answer == null || ending ? null : bridge.Price(answer);
            var unpaid = answer != null && !ending && !bridge.CanPay(answer);
            endTurn?.EnableInClassList(EndTurnWaitingClass, !hiddenInCapture && unpaid);
            if (Shown == null || Collapsed || heldForPlayback) video?.Stop();   // held (#3004): it plays again when the card is back
            if (Shown == null) { clip = null; clipAlt = null; ShowPhoto(null); return; }
            var e = Shown;
            var date = EventSystem.FillDate(e, s.Date);
            var holder = e.Office == "" ? null : Cabinet.Holder(c, s, e.Office, date);
            // The header photograph when the event has one; otherwise the minister's portrait plate (the fallback). Neither
            // while the card waits under the start screen (photoWaits): it is not seen, and the catalog is not loaded yet.
            var photo = photoWaits ? null : (photos ?? photosLater?.Invoke())?.Find(e.Id);
            var row = video != null && photo != null && !failed.Contains(e.Id) ? clipFor!(e.Id) : null;
            clip = row == null ? null : CardVideo.Url(row.File);
            clipAlt = row == null ? null : LocalAlt(row.Alt, row.AltHe);
            ShowPhoto(photo);
            var image = card.Q<VisualElement>("event-image");
            var entry = photo == null && !photoWaits ? portraits?.Find(holder?.Id) : null;
            var portrait = entry?.image;
            image.style.backgroundImage = portrait == null ? (StyleBackground)StyleKeyword.None : new StyleBackground(portrait);
            image.style.display = portrait == null ? DisplayStyle.None : DisplayStyle.Flex;
            if (portrait != null)   // keep the face in view (playtest 2, P2-5)
                image.style.backgroundPositionY = new BackgroundPosition(BackgroundPositionKeyword.Top,
                    new Length(PortraitFraming.PositionYPercent(portrait.width, portrait.height, PortraitWidth, PortraitHeight, entry!.Value.focusY), LengthUnit.Percent));
            card.Q<Label>("event-draft").style.display = e.Status == "draft" ? DisplayStyle.Flex : DisplayStyle.None;
            // The card in the UI's language (#1064): in Hebrew a field shows the event's Hebrew text where it has one, with
            // the ministers' Hebrew names in its placeholders, and the English where it has none (fail open). A variant
            // (R-ALT-010) has no Hebrew, so a card on a road not taken keeps its variant's English.
            var variant = Timeline.Variant(c, s, e);
            string Local(string english, string he) => ContentNames.Fill(text, c, s, date, english, he);
            card.Q<Label>("event-title").text = Local(EventSystem.Title(c, s, e), variant == null || variant.Title == "" ? e.TitleHe : "");
            // A consequence card's road (#954), or an armistice card's early path (R-WAR-008, #1709; owner, 9 November 2026:
            // "Banner (Recommended)"): an alternative course either way. None on any other card.
            var early = variant == null && EventSystem.ShowsEarly(e, s.Date);
            var banner = card.Q<Label>("event-alt-banner");
            banner.text = early ? text["event.alt_early"] : OriginLine(c, s, e, text);
            banner.style.display = banner.text.Length == 0 ? DisplayStyle.None : DisplayStyle.Flex;
            var office = holder == null ? null : c.Offices.First(o => o.Id == e.Office);
            card.Q<Label>("event-office").text = holder == null ? "" : text.Format("event.office", ContentNames.Of(text, office!, holder, date), ContentNames.Of(text, holder));
            // R-ENEMY-007: a card shown after its window closed shows its late text, in Hebrew its late_text_he; R-WAR-008: one
            // shown before its `from` shows its early text, in Hebrew its early_text_he (EventSystem.Render picks the English).
            card.Q<Label>("event-text").text = Local(EventSystem.Render(c, s, e),
                variant != null ? "" : early ? e.EarlyTextHe : EventSystem.ShowsLate(e, s.Date) ? e.LateTextHe : e.TextHe);
            var objective = card.Q<Label>("event-objective");   // an objective card's line (#380); none on any other card
            objective.text = ObjectiveLine(c, s, e, text);
            objective.style.display = objective.text.Length == 0 ? DisplayStyle.None : DisplayStyle.Flex;
            // The minister End Turn hands the card to, after this turn's queued orders (an appointment included): the sim's answer.
            var minister = unpaid ? bridge.DelegatedTo(e) : null;
            delegateLine.text = unpaid ? text.Format("event.no_attention", minister == null ? text["event.cabinet"] : ContentNames.Of(text, minister)) : "";
            delegateLine.style.display = unpaid ? DisplayStyle.Flex : DisplayStyle.None;
            var options = card.Q<VisualElement>("event-options");
            options.Clear();
            // R-ENEMY-007 (owner, 7 November 2026: "show each unit once on operation cards"): a unit two options need in the same
            // regions gets its line once, under the first of them.
            var shownRequirements = new HashSet<string>(System.StringComparer.Ordinal);
            foreach (var o in e.Options)
            {
                var option = o;
                var requirement = EventSystem.OperationStatus(c, s, o);
                var label = Local(Cabinet.Fill(c, s, o.Text, date), o.TextHe);
                var b = new Button(() => Choose(e, option)) { name = "option-" + o.Id, text = price is double cost && cost > 0 ? text.Format("event.option_cost", label, cost) : label };
                b.AddToClassList(OptionClass);
                // Q3 (owner, 7 November 2026: "Decide armistice first (Recommended)"): while the front's armistice card is pending,
                // or once that armistice is signed, the operation option is disabled and a red line says why.
                var armistice = EventSystem.ArmisticeBlock(c, s, e, o);
                b.SetEnabled(!unpaid && requirement.Met && armistice == null);
                options.Add(b);
                if (armistice != null)
                {
                    var front = text["map.front_" + e.ArmisticeFront];
                    var why = new Label(text.Format(armistice == EventSystem.RefusedOperationArmisticeFirst ? "event.operation_armistice_first" : "event.operation_armistice_signed", front));
                    why.AddToClassList(MissingRequirementClass); why.AddToClassList(ArmisticeClass); options.Add(why);
                }
                // R-ENEMY-007: one line per required unit, in the requirement's ordinal order. A unit in place gets the muted
                // "must be in" line; a unit elsewhere gets only the "Move ... before" line, which names the same regions.
                foreach (var need in requirement.Required)
                {
                    if (!shownRequirements.Add(need.Unit + ":" + string.Join("|", need.Regions))) continue;
                    var regions = string.Join(" / ", need.Regions.Select(id => text["operation.region." + id]));
                    bool away = requirement.Missing.Any(x => x.Unit == need.Unit);
                    // Review item 6: a required unit no longer on the board cannot be moved, so the card says that instead; the card
                    // lapses at its next consideration ("Lapse at once (Recommended)").
                    bool lost = away && EventSystem.Lost(c, s, o).Contains(need.Unit);
                    var line = new Label(lost ? text.Format("event.operation_lost", OperationUnitName(need.Unit))
                        : text.Format(away ? "event.operation_missing" : "event.operation_requirement", OperationUnitName(need.Unit), regions));
                    if (away) line.AddToClassList(MissingRequirementClass);
                    else { line.AddToClassList("muted"); line.AddToClassList(RequirementClass); }
                    options.Add(line);
                }
                // What the option does, one line per effect, from the sim's preview (#1125, R-EVT-005): Unity only words it. Under
                // the option like the rejoin line, so a Label takes no Tab stop. The rejoin effect has that line already, below.
                foreach (var preview in EventSystem.OptionEffectPreviews(c, s, o))
                {
                    if (preview.Kind == OptionEffectPreviewKind.Rejoin) continue;
                    var effect = new Label(EffectLine(c, preview, text));
                    effect.AddToClassList("muted"); effect.AddToClassList(EffectClass);
                    options.Add(effect);
                }
                if (o.Rejoin == "") continue;
                // Under the option, not in it: the button's label stays the choice itself, and a Label takes no Tab stop.
                var rejoin = new Label(text["event.rejoin"]);
                rejoin.AddToClassList("muted"); rejoin.AddToClassList(RejoinClass);
                options.Add(rejoin);
            }
            if (scrolledFor != e.Id) { scrolledFor = e.Id; scroll.scrollOffset = UnityEngine.Vector2.zero; }
            card.Q<Label>("event-count").text = open.Count > 1 ? text.Format(open.Count == 2 ? "event.more_one" : "event.more", open.Count - 1) : "";
            if (shown && !photoWaits && layer.enabledInHierarchy && openedFor != e.Id) { openedFor = e.Id; Opened?.Invoke(e.Id); }
            if (shown && focusedFor != e.Id) FocusCard(e.Id, force: restoring);
        }

        string OperationUnitName(string row)
        {
            var unit = Units.FirstOrDefault(x => x.Id == row);
            if (unit == null) return row;
            return text["ui.lang"] == UiLanguage.Hebrew && !string.IsNullOrEmpty(unit.NameHe) ? unit.NameHe : unit.Name;
        }

        /// <summary>One option-effect row in the UI's language. An indicator, money or policy is named as the top bar and the Why
        /// panel name it (why.name.&lt;id&gt;, Hebrew in Hebrew), the sim's English name where the strings have none; a project
        /// unlock takes the kind's own Hebrew name (ContentNames).</summary>
        public static string EffectLine(Content c, OptionEffectPreview row, UiText text)
        {
            var key = "why.name." + row.ContextId;
            var name = row.Kind switch
            {
                OptionEffectPreviewKind.Amount or OptionEffectPreviewKind.SetPolicy => text.Has(key) ? text[key] : null,
                OptionEffectPreviewKind.ProjectUnlock => HebrewKindName(text, c.ProjectKinds.First(k => k.Id == row.ContextId)),
                _ => null,
            };
            return EventEffectText.Format(row, text, name);
        }

        /// <summary>The kind's Hebrew name in Hebrew; null otherwise, so the sim's capitalised English row stands.</summary>
        static string? HebrewKindName(UiText text, ProjectKind k) { var n = ContentNames.Of(text, k); return n == k.Name ? null : n; }

        /// <summary>An objective card's line under its text (#380; the owner's wording, #379): completed early, "Completed on
        /// {date}; historically {date}; n months early."; in the same calendar month, "Completed on time, as in history.";
        /// later, "Completed n months later than in history.". The dates are the recorded completion (GameState.Objectives)
        /// and the objective's reference date, in the UI's language; the months are Objectives.MonthsFromHistory. Empty for
        /// an event that is not an objective's card, or whose objective is not recorded (the card fires only once it is,
        /// R-OBJ-003).</summary>
        public static string ObjectiveLine(Content c, GameState s, GameEvent e, UiText t)
        {
            if (e.Objective.Length == 0 || !s.Objectives.TryGetValue(e.Objective, out var done)) return "";
            var o = c.Objectives.First(x => x.Id == e.Objective);   // the loader checks the event names an objective
            string Date(System.DateTime d) => t.Format("date.day_month_year", d.Day, t["date.month_" + d.Month], d.Year);
            var months = Objectives.MonthsFromHistory(done, o.ReferenceDate);
            if (months == 0) return t["event.objective_on_time"];
            if (months < 0) return months == -1 ? t["event.objective_late_one"] : t.Format("event.objective_late", -months);
            var early = Objectives.MonthsEarly(done, o.ReferenceDate);
            return early == 1 ? t.Format("event.objective_early_one", Date(done), Date(o.ReferenceDate))
                : t.Format("event.objective_early", Date(done), Date(o.ReferenceDate), early);
        }

        /// <summary>A consequence card's banner (#954; plan 2026-10-17-alternate-timelines.md, A.4.7): the road it follows as
        /// the player took it (Timeline.Origin: that card's option and title, through the same text pipeline as that card's
        /// own labels) and, where that card has one, the record's option beside it (Timeline.HistoricalOption). A chained
        /// card follows a consequence card, which has no historical option: the comparison is left out, never made up.
        /// Empty for any other card.</summary>
        public static string OriginLine(Content c, GameState s, GameEvent e, UiText t)
        {
            var origin = Timeline.Origin(c, s, e);
            if (origin == null) return "";
            // The loader checks every requirement names an event, but a save from older content may hold an option the card
            // no longer has: then no banner rather than a broken card.
            var road = c.Events.FirstOrDefault(x => x.Id == origin.Value.Event);
            var option = road?.Options.FirstOrDefault(o => o.Id == origin.Value.Option);
            if (road == null || option == null) return "";
            var date = EventSystem.FillDate(road, s.Date);
            // Use the road card's own per-field fallback and name/date routing (#1064), not the consequence's date.
            bool hebrew = t["ui.lang"] == UiLanguage.Hebrew;
            string Local(string english, string he) => hebrew && he != "" ? Cabinet.Fill(c, s, he, date, p => ContentNames.Of(t, p)) : english;
            var variant = Timeline.Variant(c, s, road);
            var took = Local(Cabinet.Fill(c, s, option.Text, date), option.TextHe);
            var title = Local(EventSystem.Title(c, s, road), variant == null || variant.Title == "" ? road.TitleHe : "");
            var record = Timeline.HistoricalOption(road);
            return record == null ? t.Format("event.alt_origin_no_record", took, title)
                : t.Format("event.alt_origin", took, title, Local(Cabinet.Fill(c, s, record.Text, date), record.TextHe));
        }

        /// <summary>A newly shown event puts the keyboard focus on the card (keyboard play, #41): the next Tab reaches its
        /// first option, and no option is lit before the player picks. Not while the layer is out of reach (the start screen
        /// or a screen covers it): then nothing is recorded, and the card takes the focus when the cover closes
        /// (onUncovered, <paramref name="force"/>). It is tried again once styles resolve, as a still-hidden card cannot take
        /// it; that retry takes it from nothing, or, when forced, from whatever the closing cover left focused.</summary>
        void FocusCard(string id, bool force)
        {
            if (!layer.enabledInHierarchy) return;
            focusedFor = id;
            card.Focus();
            card.schedule.Execute(() =>
            {
                if (Shown?.Id != id || Collapsed) return;
                if (!layer.enabledInHierarchy) { if (focusedFor == id) focusedFor = null; return; }   // covered meanwhile: try again when uncovered
                var now = card.focusController?.focusedElement;
                if (card.panel != null && now != card && (force || now == null)) card.Focus();
            });
        }

        /// <summary>Shows the event's photograph with its credit line, its alt text as the picture's tooltip, or hides both.</summary>
        void ShowPhoto(EventImageCatalog.Entry? photo)
        {
            current = photo;
            credit.text = photo?.credit ?? "";
            SetPhotoShown(photo != null);
        }

        /// <summary>Shows the current photograph (band, credit, tooltip, texture) or hides all of it. Idempotent.</summary>
        void SetPhotoShown(bool shown)
        {
            var photo = shown ? current : null;
            var display = photo != null ? DisplayStyle.Flex : DisplayStyle.None;
            band.style.display = display; credit.style.display = display;
            // While the photograph shows it alone gives way (flex-shrink 1000): with the body's own flex-shrink 1 beside it,
            // the body took a sliver of the shortfall, and once rounded that was a device pixel of scroll on a card that fits
            // (1366x657 at 100%, #1853). Dropped, the body shrinks and scrolls as the stylesheet says.
            scroll.style.flexShrink = photo != null ? 0f : (StyleFloat)StyleKeyword.Null;
            band.style.backgroundImage = photo == null ? (StyleBackground)StyleKeyword.None : new StyleBackground(photo.Value.image);
            var photoAlt = photo == null ? null : LocalAlt(photo.Value.alt, photo.Value.altHe);
            band.tooltip = photoAlt ?? "";
            PhotoAlt = photoAlt;
            ApplyMediaHeight();
            ApplyIllustration();
        }

        /// <summary>The Illustration switch: shown only when the event has a clip and its photograph shows (the clip is never
        /// the only picture of a real event). On, the header plays the clip, labelled "AI-generated illustration" in place
        /// of the photograph's credit; off, or when the clip fails, the photograph and its credit come back.</summary>
        void ApplyIllustration()
        {
            var offered = clip != null && PhotoAlt != null && !Collapsed && !heldForPlayback;
            illustrationSwitch.style.display = offered ? DisplayStyle.Flex : DisplayStyle.None;
            if (offered && illustration)
            {
                illustrationSwitch.text = text["event.photo"];
                credit.text = text["event.ai_label"];
                band.tooltip = clipAlt ?? "";
                if (video!.Current != clip) { var id = Shown!.Id; video.Play(clip!, band, _ => { failed.Add(id); Render(); }); }
                else video.ShowIn(band);
                return;
            }
            illustrationSwitch.text = text["event.illustration"];
            if (video?.Current != null)
            {
                video.Stop();
                if (current != null && PhotoAlt != null) band.style.backgroundImage = new StyleBackground(current.Value.image);
            }
            if (current != null) { credit.text = current.Value.credit; if (PhotoAlt != null) band.tooltip = LocalAlt(current.Value.alt, current.Value.altHe); }
        }

        string LocalAlt(string english, string? hebrew) =>
            text["ui.lang"] == UiLanguage.Hebrew && !string.IsNullOrWhiteSpace(hebrew) ? hebrew! : english;

        /// <summary>True while the header plays the event's clip (or is preparing it).</summary>
        public bool IllustrationShown => video?.Current != null;

        /// <summary>The playtest 2 P2-3 line (UiLayoutTests): in a window at least this tall (logically) the body and the
        /// options of every event fit without scrolling. The media header gives way first on every window
        /// (ApplyMediaHeight), so below it the body scrolls only once the photograph is dropped.</summary>
        public const float ScrollFallbackHeight = 990f;

        /// <summary>The media header's height: 16:9 of the card's content width (the stylesheet's 540 px until the card is laid
        /// out). On every window the header gives way first when the card is taller than the layer (Statecraft.uss
        /// flex-shrink 1000; the picture is cropped, background-size cover), so the text and the options show whole; below
        /// PhotoNeeds it is dropped (FitPhoto), and only then may the body scroll. The 200 px band of the old right-hand
        /// column needed the body to scroll first on short windows, or 21:9 never showed a photograph; a 16:9 header has
        /// the room to give.</summary>
        void ApplyMediaHeight()
        {
            var w = card.contentRect.width;
            appliedWidth = w;
            band.style.height = float.IsNaN(w) || w <= 0 ? (StyleLength)StyleKeyword.Null : new StyleLength(UnityEngine.Mathf.Round(w / MediaAspect));
        }

        /// <summary>The card's width changed (it was first laid out, or the window changed): the media header follows it. The
        /// card's height changes with the header, so only a new width counts, or the two would chase each other.</summary>
        void OnCardGeometry(GeometryChangedEvent evt)
        {
            var w = card.contentRect.width;
            if (float.IsNaN(w) || w <= 0 || UnityEngine.Mathf.Abs(w - appliedWidth) < 0.5f) return;
            ApplyMediaHeight(); FitPhoto();
        }

        /// <summary>The smallest height of the picture left visible above its credit strip (Statecraft.uss .event-photo
        /// shrinks first). On a window too short for a long event the band would show a sliver, or cut into the credit that
        /// CC BY 4.0 requires: below credit height + MinPhotoHeight the photograph is dropped (credit, tooltip and all), so
        /// the body and the options keep their room and the card reads as a card without a picture. The minister's
        /// portrait does not come back in its place: it is taller still (docs/event-images.md).</summary>
        public const float MinPhotoHeight = 48f;

        /// <summary>The band height the photograph needs: its whole credit strip plus MinPhotoHeight of picture. The credit is
        /// measured from its text at the band's width, not read from its layout: in a squeezed band the label's layout is
        /// clamped to the room left, which is exactly the clipping this guards against.</summary>
        public float PhotoNeeds => CreditHeight() + MinPhotoHeight;

        float CreditHeight()
        {
            var s = credit.resolvedStyle;
            var bandWidth = band.layout.width > 0 ? band.layout.width : card.contentRect.width;
            var width = bandWidth - band.resolvedStyle.borderLeftWidth - band.resolvedStyle.borderRightWidth - s.paddingLeft - s.paddingRight;
            if (float.IsNaN(width) || width <= 0) return float.NaN;
            var text = credit.MeasureTextSize(credit.text, width, VisualElement.MeasureMode.Exactly, 0, VisualElement.MeasureMode.Undefined);
            return text.y + s.paddingTop + s.paddingBottom + s.borderTopWidth + s.borderBottomWidth;
        }

        /// <summary>Drops the shown photograph when its band is shorter than <see cref="PhotoNeeds"/>. Only ever hides, so the
        /// layout pass it causes cannot bring the photo back and loop; OnColumnGeometry is what restores it.</summary>
        void FitPhoto()
        {
            if (PhotoAlt == null) return;
            var h = band.layout.height; var needs = PhotoNeeds;
            if (float.IsNaN(h) || float.IsNaN(needs)) return;
            if (h < needs - 0.5f) SetPhotoShown(false);
        }

        /// <summary>R-ENEMY-007 (owner, 7 November 2026: "Smaller lines, then toast moves (Recommended)"): over an open card the toast
        /// sits at the top middle, over the photograph and clear of its credit (Statecraft.uss, `.event-modal .toast`). When the
        /// photograph band is too short to hold it above the credit (a tall card on a short window), it moves below the band,
        /// under the office line, over the top of the body, still clear of the title and the options; when even that has no
        /// room, it stays put. Only a changed value is written, so its own geometry event settles at once.</summary>
        void OnToastGeometry(GeometryChangedEvent evt) => PlaceToast();

        void PlaceToast()
        {
            if (toast == null || toast.parent == null) return;
            // An inline top set by this method has keyword Undefined; unset (the stylesheet's place) is Null.
            var moved = toast.style.top.keyword == StyleKeyword.Undefined;
            if (!moved) toastDefaultTop = toast.worldBound.yMin;
            var open = Shown != null && !Collapsed && toast.resolvedStyle.display == DisplayStyle.Flex && PhotoAlt != null;
            float? want = null;
            if (open && !float.IsNaN(toastDefaultTop))
            {
                var height = toast.worldBound.height;
                if (toastDefaultTop + height > credit.worldBound.yMin - 2)
                {
                    var below = card.Q<Label>("event-office").worldBound.yMax + 6;
                    if (below + height < options.worldBound.yMin - 2)
                        want = below - toast.parent.worldBound.yMin - toast.resolvedStyle.marginTop;
                }
            }
            if (want == null) { if (moved) toast.style.top = StyleKeyword.Null; }
            else if (!moved || System.Math.Abs(toast.style.top.value.value - want.Value) > 0.5f) toast.style.top = want.Value;
        }

        void OnPhotoGeometry(GeometryChangedEvent evt)
        {
            // A padding change can resize the header without changing the card's outer rectangle (#649).
            // The existing width guard prevents the height update from chasing its own geometry events.
            OnCardGeometry(evt);
            FitPhoto();
        }

        /// <summary>The decision layer changed size (the window did; the card's content never moves it, as the layer is pinned
        /// to the window on every side). A shown photograph is checked again; a dropped one comes back only when the room now
        /// free in the layer holds it (<see cref="RoomForDroppedPhoto"/>), so it is never shown just to be measured (a hidden
        /// element keeps its old layout, so a re-shown band may get no new geometry event).</summary>
        void OnColumnGeometry(GeometryChangedEvent evt)
        {
            if (current != null && PhotoAlt == null) { if (RoomForDroppedPhoto() >= PhotoNeeds) SetPhotoShown(true); }
            else { ApplyMediaHeight(); FitPhoto(); }
        }

        /// <summary>The band height a dropped photograph would get now (at most; the band itself stops at 16:9): the layer's
        /// height the card leaves free (the card's max-height is the layer's), less the band's margins.</summary>
        float RoomForDroppedPhoto()
        {
            var room = layer.contentRect.height;
            if (float.IsNaN(room) || float.IsNaN(card.layout.height)) return 0;
            var slack = room - card.layout.height;
            return slack - band.resolvedStyle.marginTop - band.resolvedStyle.marginBottom;
        }

        /// <summary>The event's photograph, whether or not the window has room to show it.</summary>
        EventImageCatalog.Entry? current;

        /// <summary>The shown photograph's alt text (what it depicts), or null when the card shows no photograph (none for
        /// this event, or dropped on a short window).</summary>
        public string? PhotoAlt { get; private set; }

        void Choose(GameEvent e, EventOption o)
        {
            // The bridge raises Refused (the toast shows it) or Changed (the toast clears and Render shows the next event,
            // which takes the focus). Answered from the keyboard with no event left, the focus goes to End Turn (#41 M1),
            // unless a control outside the card took it meanwhile (the opening chain's Next, as it moves on, #1323).
            // An objective's card on the turn that ended the game (R-OBJ-003, #2536) has one option and no turn left to run
            // it: the answer only marks it seen, and the end screen follows the last one (SimBridge.SeeEndingCard).
            if (bridge.IsEndingCard(e.Id)) bridge.SeeEndingCard(e.Id);
            else bridge.Queue(new ChooseEventOption(e.Id, o.Id));
            var focused = hudRoot.focusController?.focusedElement as VisualElement;
            bool kept = focused != null && focused.panel != null && !layer.Contains(focused);
            if (Shown == null && presses.ByKeyboard && !kept && bridge.State.GameOver == null) FocusReturn.To(hudRoot.Q<Button>("end-turn"));   // ended: the end screen has it
        }
    }
}