using System;
using Jovian.PopupSystem.UI;
using UnityEngine;

namespace Jovian.PopupSystem {
    /// <summary>
    /// Handles popup behavior for a <see cref="PopupTrigger"/>. Holds the content callback and
    /// forwards pointer events to the <see cref="IPopupSystem"/>. This is the behavior layer;
    /// the MonoBehaviour trigger is the reference holder that forwards events here.
    /// </summary>
    public sealed class PopupTriggerView {
        readonly IPopupSystem popupSystem;
        Action<PopupContentBuilder> contentCallback;

        /// <summary>
        /// Creates a new trigger view bound to the given popup system.
        /// </summary>
        public PopupTriggerView(IPopupSystem popupSystem) {
            this.popupSystem = popupSystem;
        }

        /// <summary>
        /// Sets the content builder callback that will be invoked when the popup is shown.
        /// </summary>
        public void SetContent(Action<PopupContentBuilder> callback) {
            contentCallback = callback;
        }

        /// <summary>
        /// Called by <see cref="PopupTrigger"/> when the pointer enters. Reads the trigger's
        /// category, anchor side, and position mode to show the popup.
        /// </summary>
        public void OnPointerEnter(PopupTrigger trigger) {
            if(popupSystem == null || contentCallback == null) {
                return;
            }

            if(trigger.PositionMode == PopupPositionMode.AnchorToElement) {
                popupSystem.Show(trigger.Category, contentCallback, (RectTransform)trigger.transform, trigger.AnchorSide);
            }
            else {
                popupSystem.Show(trigger.Category, contentCallback);
            }
        }

        /// <summary>
        /// Called by <see cref="PopupTrigger"/> when the pointer exits. Hides the popup
        /// for the trigger's category.
        /// </summary>
        public void OnPointerExit(PopupTrigger trigger) {
            popupSystem?.Hide(trigger.Category);
        }
    }
}
