using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Image))]
public class GradientMaskUI : MonoBehaviour
{
    public enum GradientDirection
    {
        LeftToRight,
        RightToLeft,
        TopToBottom,
        BottomToTop
    }

    [SerializeField] private GradientDirection direction = GradientDirection.TopToBottom;
    [SerializeField] private float gradientSoftness = 0.5f;

    private Image image;
    private Material material;
    private static readonly int GradientDir = Shader.PropertyToID("_GradientDir");
    private static readonly int Softness = Shader.PropertyToID("_Softness");

    private void Awake()
    {
        image = GetComponent<Image>();
        
        // 创建渐变遮罩材质
        material = new Material(Shader.Find("UI/GradientMaskUI"));
        image.material = material;
        
        UpdateGradient();
    }

    private void OnValidate()
    {
        if (material != null)
        {
            UpdateGradient();
        }
    }

    public void UpdateGradient()
    {
        if (material == null) return;

        Vector2 dir = Vector2.zero;
        
        switch (direction)
        {
            case GradientDirection.LeftToRight:
                dir = new Vector2(1, 0);
                break;
            case GradientDirection.RightToLeft:
                dir = new Vector2(-1, 0);
                break;
            case GradientDirection.TopToBottom:
                dir = new Vector2(0, -1);
                break;
            case GradientDirection.BottomToTop:
                dir = new Vector2(0, 1);
                break;
        }
        
        material.SetVector(GradientDir, dir);
        material.SetFloat(Softness, Mathf.Clamp(gradientSoftness, 0.01f, 1f));
    }

    public void SetDirection(GradientDirection newDirection)
    {
        direction = newDirection;
        UpdateGradient();
    }

    public void SetSoftness(float softness)
    {
        gradientSoftness = Mathf.Clamp(softness, 0.01f, 1f);
        UpdateGradient();
    }
} 