using UnityEngine;
using UnityEngine.EventSystems;

public class TitleTooltipExpander : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler
{
    public Transform cameraTransform;
    public RectTransform expandablePanel; // Panel to animate
    public float expandedHeight = 150f;
    public float collapsedHeight = 30f;
    public float animationDuration = 0.4f;

    private bool isHovered = false;
    private bool isLocked = false;

#if LEANTWEEN_PRESENT
    private LTDescr currentTween;
#endif

    private static TitleTooltipExpander currentlyLockedPanel = null;

    void Start()
    {
        // Set initial collapsed state
        if (expandablePanel != null)
            SetPanelHeight(collapsedHeight, true);
    }

    void Update()
    {
        // Always face the camera
        if (cameraTransform != null)
            transform.LookAt(transform.position + cameraTransform.forward);
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        if (currentlyLockedPanel != null && currentlyLockedPanel != this) return;

        isHovered = true;
        if (!isLocked)
        {
            FadeOutOtherTooltips();
            Expand();
        }
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        if (isLocked) return;

        isHovered = false;
        RestoreAllTooltips();
        Collapse();
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        if (isLocked)
        {
            UnlockPanel();
        }
        else
        {
            if (currentlyLockedPanel != null)
                currentlyLockedPanel.ForceUnlockAndCollapse();

            LockPanel();
        }
    }

    void LockPanel()
    {
        isLocked = true;
        currentlyLockedPanel = this;
        Expand();
        FadeOutOtherTooltips();
    }

    void UnlockPanel()
    {
        isLocked = false;
        currentlyLockedPanel = null;
        if (!isHovered)
            Collapse();

        RestoreAllTooltips();
    }

    void ForceUnlockAndCollapse()
    {
        isLocked = false;
        currentlyLockedPanel = null;
        isHovered = false; // Force collapse regardless of hover state
        Collapse();
        RestoreAllTooltips();
    }

    void Expand()  => SetPanelHeight(expandedHeight, false);
    void Collapse() => SetPanelHeight(collapsedHeight, false);

    void SetPanelHeight(float targetHeight, bool instant)
    {
        if (expandablePanel == null) return;

#if LEANTWEEN_PRESENT
        if (currentTween != null)
            LeanTween.cancel(expandablePanel.gameObject, currentTween.id);
#endif

        if (instant
#if !LEANTWEEN_PRESENT
            || true // force instant if LeanTween not present
#endif
        )
        {
            expandablePanel.sizeDelta = new Vector2(expandablePanel.sizeDelta.x, targetHeight);
            return;
        }

#if LEANTWEEN_PRESENT
        currentTween = LeanTween.value(expandablePanel.gameObject, expandablePanel.sizeDelta.y, targetHeight, animationDuration)
            .setEaseOutExpo()
            .setOnUpdate((float val) =>
            {
                expandablePanel.sizeDelta = new Vector2(expandablePanel.sizeDelta.x, val);
            });
#endif
    }

    void FadeOutOtherTooltips()
    {
        var allTooltips = GameObject.FindGameObjectsWithTag("Tooltip");

        foreach (var tooltip in allTooltips)
        {
            if (!tooltip || tooltip == this.gameObject) continue;

            var group = tooltip.GetComponentInChildren<CanvasGroup>();
            if (!group) continue;

#if LEANTWEEN_PRESENT
            LeanTween.alphaCanvas(group, 0f, animationDuration).setEaseOutExpo();
#else
            group.alpha = 0f; // instant fallback
#endif
        }
    }

    void RestoreAllTooltips()
    {
        var allTooltips = GameObject.FindGameObjectsWithTag("Tooltip");

        foreach (var tooltip in allTooltips)
        {
            if (tooltip == currentlyLockedPanel?.gameObject) continue;

            var group = tooltip.GetComponentInChildren<CanvasGroup>();
            if (!group) continue;

#if LEANTWEEN_PRESENT
            LeanTween.alphaCanvas(group, 1f, animationDuration).setEaseOutExpo();
#else
            group.alpha = 1f; // instant fallback
#endif
        }
    }
}