using UnityEngine;

namespace Davanci.Nexus
{
    // Fits a RectTransform to the device safe area. Drop it on a full-stretch
    // container and parent content under it; re-applies on safe-area changes.
    [RequireComponent(typeof(RectTransform))]
    [DisallowMultipleComponent]
    public class NexusSafeArea : MonoBehaviour
    {
        RectTransform _rt;
        Rect _lastSafe;
        Vector2Int _lastScreen;

        void Awake() { _rt = (RectTransform)transform; Apply(); }
        void OnEnable() { Apply(); }

        void Update()
        {
            if (Screen.safeArea != _lastSafe ||
                Screen.width != _lastScreen.x || Screen.height != _lastScreen.y)
                Apply();
        }

        void Apply()
        {
            if (_rt == null) _rt = (RectTransform)transform;
            int w = Screen.width, h = Screen.height;
            if (w <= 0 || h <= 0) return;

            _lastSafe = Screen.safeArea;
            _lastScreen = new Vector2Int(w, h);

            Vector2 min = _lastSafe.position;
            Vector2 max = _lastSafe.position + _lastSafe.size;
            min.x /= w; min.y /= h;
            max.x /= w; max.y /= h;

            _rt.anchorMin = min;
            _rt.anchorMax = max;
            _rt.offsetMin = Vector2.zero;
            _rt.offsetMax = Vector2.zero;
        }
    }
}
