using System;
using System.Collections.Generic;
using UnityEngine;

namespace eagle {
    using ProvinceId = Int32;

    public class PopupCanvasController : MonoBehaviour {
        public GameObject modalBlocker;
        public GameObject panel;

        // Single owner of MapController.OverrideTargetedProvinces while popups are visible:
        // each PopupPanelController declares which provinces its current popup wants highlighted
        // via CurrentAffectedProvinceIds, and we apply the topmost active panel's choice each frame
        // so panels can't clobber one another's highlights. When no popup is active we leave the
        // field alone so non-popup writers (table hovers etc.) can drive it normally.
        public MapController mapController;

        private bool _hadActivePopupLastFrame = false;

        void Update() {
            bool enable = false;
            bool blocksInteraction = false;
            PopupPanelController topmostActive = null;

            // GetComponentsInChildren returns in hierarchy order; for direct children of `panel`,
            // last in the array == last sibling == topmost in render order.
            foreach (var controller in panel.GetComponentsInChildren<PopupPanelController>()) {
                bool hasInfo = controller.HasInfo;
                enable = enable || hasInfo;
                blocksInteraction = blocksInteraction || (hasInfo && controller.BlocksInteraction);
                controller.gameObject.SetActive(hasInfo);
                if (hasInfo) topmostActive = controller;
            }
            modalBlocker.SetActive(blocksInteraction);
            panel.SetActive(enable);

            if (topmostActive != null) {
                mapController.OverrideTargetedProvinces =
                        topmostActive.CurrentAffectedProvinceIds ?? new List<ProvinceId>();
                _hadActivePopupLastFrame = true;
            } else if (_hadActivePopupLastFrame) {
                // Last frame we owned the override; clear once on the transition so the map returns
                // to its non-popup state. Subsequent frames leave the field for hover handlers.
                mapController.OverrideTargetedProvinces = new List<ProvinceId>();
                _hadActivePopupLastFrame = false;
            }
        }

        public void SetChildActive(bool val) {
            // if (val)
            //{
            //     gameObject.SetActive(true);
            // }
            // else
            //{
            //     MainQueue.Q.EnqueueForNextUpdate(() =>
            //     {
            //         gameObject.SetActive(HasActiveChild);
            //     });
            // }
        }
    }
}
