using System; using DevilLink2.Core; using DevilLink2.Interaction; using DevilLink2.Gameplay; using UnityEngine; using UnityEngine.UI; namespace DevilLink2.Presentation { [DisallowMultipleComponent] public sealed class BoardInteractionController : MonoBehaviour { private BoardView view; private BoardPathRenderer paths; private Text status; private GameFlowController flow; private bool ownsRuntime; private Action unbindState; public BoardInteractionState State { get; private set; } public GameSessionRuntime Runtime { get; private set; } // The domain runtime consumes the underlying InvalidMatch once; forwarding is observational. public event Action InvalidMatch; // Legacy visual-completion notification after the 240ms lock. Runtime owns the clear bonus. public event Action BoardCleared; public event Action HintRequested; public void Initialize(BoardView boardView, int shuffleSeed = 2026) { InitializeState(boardView, shuffleSeed, null, null); } public void Initialize(BoardView boardView, GameSession session, IMonotonicClock clock = null) { if (session == null) throw new ArgumentNullException(nameof(session)); if (!boardView || !ReferenceEquals(boardView.Data, session.Board)) throw new ArgumentException("BoardView must display the session's exact board.", nameof(boardView)); InitializeState(boardView, session.RandomSeed, session, clock ?? new StopwatchClock()); } public void Initialize(BoardView boardView, GameFlowController gameFlow) { if (gameFlow == null) throw new ArgumentNullException(nameof(gameFlow)); if (!boardView) throw new ArgumentNullException(nameof(boardView)); Detach(); view = boardView; flow = gameFlow; flow.SessionChanged += BindFlowRuntime; flow.StateChanged += OnFlowStateChanged; flow.Items.HintRequested += OnHintRequested; if (flow.State == GameFlowState.Abandoned) { view.Clear(); return; } BindFlowRuntime(flow.Runtime); } private void BindFlowRuntime(GameSessionRuntime runtime) { if (flow == null || !ReferenceEquals(flow.Runtime, runtime)) return; DetachState(); Runtime = runtime; ownsRuntime = false; view.Show(runtime.Session.Board); EnsureOverlay(); paths.Clear(); status.text = ""; State = runtime.Interaction; BindState(); if (State.Error != null) OnFailed(State.Error); UpdateFlowInput(); } private void OnFlowStateChanged(GameFlowState previous, GameFlowState next) { if (next == GameFlowState.Abandoned) { DetachState(); Runtime = null; if (paths) paths.Clear(); if (status) status.text = ""; view.Clear(); } else { if (next == GameFlowState.Paused) { if (paths) paths.Clear(); if (view) view.FinishVisuals(); } UpdateFlowInput(); } } private void UpdateFlowInput() { if (view) view.SetInteraction(flow.State == GameFlowState.Running ? OnClick : (Action)null); } private void OnHintRequested(HintInfo hint) { if (flow != null && flow.State == GameFlowState.Running && Runtime != null && hint.SessionId == Runtime.Session.Id) HintRequested?.Invoke(hint); } private void BindState() { // Unsubscribing does not cancel an event invocation already in flight. // Guard each visual callback by its bound state to isolate old sessions. var source = State; Action selection = tile => { if (ReferenceEquals(State, source)) OnSelection(tile); }; Action invalid = (a,b) => { if (ReferenceEquals(State, source)) OnInvalid(a,b); }; Action matched = pair => { if (ReferenceEquals(State, source)) OnMatched(pair); }; Action shuffled = result => { if (ReferenceEquals(State, source)) OnReshuffled(result); }; Action cleared = () => { if (ReferenceEquals(State, source)) OnCleared(); }; Action failed = error => { if (ReferenceEquals(State, source)) OnFailed(error); }; source.SelectionChanged += selection; source.InvalidMatch += invalid; source.Matched += matched; source.Reshuffled += shuffled; source.BoardCleared += cleared; source.Failed += failed; unbindState = () => { source.SelectionChanged -= selection; source.InvalidMatch -= invalid; source.Matched -= matched; source.Reshuffled -= shuffled; source.BoardCleared -= cleared; source.Failed -= failed; }; } private void DetachState() { if (view) { view.SetInteraction(null); view.FinishVisuals(); } unbindState?.Invoke(); unbindState = null; State = null; } private void InitializeState(BoardView boardView, int shuffleSeed, GameSession session, IMonotonicClock clock) { Detach(); view = boardView; if (!view || view.Data == null) throw new InvalidOperationException("Show a Core board before enabling interaction."); EnsureOverlay(); paths.Clear(); status.text = ""; Runtime = session == null ? null : new GameSessionRuntime(session, clock); State = Runtime == null ? new BoardInteractionState(view.Data, shuffleSeed) : Runtime.Interaction; ownsRuntime = Runtime != null; BindState(); // Runtime initialization may have shuffled the shared board before visual subscriptions. if (Runtime != null) view.Refresh(); view.SetInteraction(OnClick); // Runtime already initialized its state before subscribing the visual observers. if (State.Error != null) OnFailed(State.Error); State.Initialize(); } private void Update() { if (flow != null) flow.Update(); else if (Runtime != null) Runtime.Update(); else State?.Advance(Time.unscaledDeltaTime); } private void OnClick(TileView tile) { if (!tile || !view || !ReferenceEquals(view.FindTile(tile.TileId), tile)) return; if (flow != null) flow.Click(tile.Data.Row, tile.Data.Column); else if (Runtime != null) Runtime.Click(tile.Data.Row, tile.Data.Column); else State?.Click(tile.Data.Row, tile.Data.Column); } private void OnSelection(Tile tile) { view.Highlight(tile == null ? 0 : tile.Id); } private void OnInvalid(Tile a, Tile b) { view.FindTile(a.Id)?.Shake(); view.FindTile(b.Id)?.Shake(); InvalidMatch?.Invoke(a, b); } private void OnMatched(PairMatch match) { var layout = view.CurrentLayout; paths.Show(match.Path, view.BoardRoot, layout); view.AnimateRemoval(match.First.Id); view.AnimateRemoval(match.Second.Id); } private void OnReshuffled(BoardShuffleResult result) { paths.Clear(); view.Refresh(); status.text = "Board reshuffled"; } private void OnCleared() { status.text = "Board cleared"; BoardCleared?.Invoke(); } private void OnFailed(string error) { status.text = error; Debug.LogError(error, this); } private void EnsureOverlay() { // Sibling of the scroll viewport, so the viewport RectMask2D cannot clip border links. var parent = view.transform.parent; if (!parent) parent = view.transform; var child = parent.Find("InteractionOverlay"); if (!child) child = new GameObject("InteractionOverlay", typeof(RectTransform)).transform; child.SetParent(parent, false); child.SetAsLastSibling(); var rect = (RectTransform)child; rect.anchorMin = Vector2.zero; rect.anchorMax = Vector2.one; rect.offsetMin = rect.offsetMax = Vector2.zero; paths = child.GetComponent(); if (!paths) paths = child.gameObject.AddComponent(); var label = child.Find("Status"); if (!label) label = new GameObject("Status", typeof(RectTransform)).transform; label.SetParent(child, false); var textRect = (RectTransform)label; textRect.anchorMin = new Vector2(0, 0); textRect.anchorMax = new Vector2(1, 0); textRect.pivot = new Vector2(.5f, 0); textRect.sizeDelta = new Vector2(0, 38); textRect.anchoredPosition = Vector2.zero; status = label.GetComponent(); if (!status) status = label.gameObject.AddComponent(); status.font = Resources.GetBuiltinResource("LegacyRuntime.ttf"); status.fontSize = 12; status.alignment = TextAnchor.MiddleCenter; status.color = new Color32(255, 211, 77, 255); status.raycastTarget = false; } private void OnDisable() { if (paths) paths.Clear(); if (view) view.FinishVisuals(); } private void OnDestroy() { Detach(); } private void Detach() { if (flow != null) { flow.SessionChanged -= BindFlowRuntime; flow.StateChanged -= OnFlowStateChanged; flow.Items.HintRequested -= OnHintRequested; flow = null; } DetachState(); if (ownsRuntime) Runtime?.Dispose(); Runtime = null; ownsRuntime = false; if (paths) paths.Clear(); } } }