using System; using System.Collections.Generic; using Core; using UnityEngine; namespace AppleHills.UI.CardSystem { /// /// Manages UI page transitions and maintains a stack of active pages. /// Pages are pushed onto a stack for navigation and popped when going back. /// public class UIPageController : MonoBehaviour { private static UIPageController _instance; public static UIPageController Instance => _instance; private Stack _pageStack = new Stack(); public UIPage CurrentPage => _pageStack.Count > 0 ? _pageStack.Peek() : null; // Event fired when the page stack changes public event Action OnPageChanged; private void Awake() { if (_instance != null && _instance != this) { Destroy(gameObject); return; } _instance = this; } /// /// Pushes a new page onto the stack, hiding the current page and showing the new one. /// public void PushPage(UIPage page) { if (page == null) return; // Hide current page if there is one if (_pageStack.Count > 0) { UIPage currentPage = _pageStack.Peek(); currentPage.TransitionOut(); } // Push and show new page _pageStack.Push(page); page.TransitionIn(); OnPageChanged?.Invoke(page); Logging.Debug($"[UIPageController] Pushed page: {page.PageName}"); } /// /// Pops the current page from the stack and shows the previous page. /// public void PopPage() { if (_pageStack.Count <= 0) return; // Hide and pop current page UIPage currentPage = _pageStack.Pop(); currentPage.TransitionOut(); // Show previous page if there is one if (_pageStack.Count > 0) { UIPage previousPage = _pageStack.Peek(); previousPage.TransitionIn(); OnPageChanged?.Invoke(previousPage); Logging.Debug($"[UIPageController] Popped to previous page: {previousPage.PageName}"); } else { OnPageChanged?.Invoke(null); Logging.Debug("[UIPageController] Popped last page, no pages left in stack"); } } /// /// Clears all pages from the stack. /// public void ClearStack() { if (_pageStack.Count <= 0) return; // Hide current page UIPage currentPage = _pageStack.Peek(); currentPage.TransitionOut(); // Clear stack _pageStack.Clear(); OnPageChanged?.Invoke(null); Logging.Debug("[UIPageController] Cleared page stack"); } /// /// Handles back button input and navigates to the previous page if possible. /// private void Update() { if (UnityEngine.Input.GetKeyDown(KeyCode.Escape) && _pageStack.Count > 0) { _pageStack.Peek().OnBackPressed(); } } } }