using System.Collections.Generic;
using UnityEngine;

namespace ViKPI
{
    /// <summary>
    /// Hides this object from session recordings: its screen area is painted black on the device,
    /// before the frame is encoded, so the pixels never leave the phone. Put it on password fields,
    /// chat, payment forms, or any UI or renderer with personal data.
    /// </summary>
    [DisallowMultipleComponent]
    [AddComponentMenu("ViKPI/Recording Mask")]
    public sealed class VikpiMask : MonoBehaviour
    {
        private static readonly List<VikpiMask> Active = new List<VikpiMask>();
        private static readonly Vector3[] Corners = new Vector3[4];

        [Tooltip("Extra margin around the object, in screen pixels.")]
        [SerializeField] private float padding = 4f;

        private RectTransform _rect;
        private Renderer _renderer;
        private Canvas _canvas;

        private void OnEnable()
        {
            _rect = transform as RectTransform;
            _renderer = _rect == null ? GetComponent<Renderer>() : null;
            _canvas = _rect != null ? GetComponentInParent<Canvas>() : null;
            Active.Add(this);
        }

        private void OnDisable() => Active.Remove(this);

        /// <summary>Set from the settings: also black out every text input field (see <see cref="VikpiSettings.MaskTextInputs"/>).</summary>
        internal static bool MaskTextInputs = true;

        /// <summary>Screen-space rects (pixels, origin bottom-left) of every visible mask.</summary>
        internal static void CollectScreenRects(List<Rect> into)
        {
            into.Clear();
            for (var i = 0; i < Active.Count; i++)
            {
                if (Active[i].TryGetScreenRect(out var r)) into.Add(r);
            }
#if VIKPI_UGUI
            if (MaskTextInputs) CollectTextInputs(into);
#endif
        }

#if VIKPI_UGUI
        private static UnityEngine.UI.Selectable[] _selectables = new UnityEngine.UI.Selectable[64];

        /// <summary>
        /// Text fields hold what players type (names, chat, codes), so they are masked without any
        /// setup. Uses uGUI's registry of enabled selectables: no scene search, no allocation.
        /// </summary>
        private static void CollectTextInputs(List<Rect> into)
        {
            var count = UnityEngine.UI.Selectable.allSelectableCount;
            if (count == 0) return;
            if (count > _selectables.Length) _selectables = new UnityEngine.UI.Selectable[Mathf.NextPowerOfTwo(count)];
            count = UnityEngine.UI.Selectable.AllSelectablesNoAlloc(_selectables);
            for (var i = 0; i < count; i++)
            {
                var s = _selectables[i];
                _selectables[i] = null;
                if (s == null || !s.isActiveAndEnabled) continue;
                // TMP_InputField lives in another assembly; matching by name avoids a hard dependency.
                if (!(s is UnityEngine.UI.InputField) && s.GetType().Name != "TMP_InputField") continue;
                if (!(s.transform is RectTransform rt)) continue;
                var canvas = s.GetComponentInParent<Canvas>();
                if (canvas == null || !canvas.isActiveAndEnabled) continue;
                if (TryRectTransformRect(rt, canvas, 4f, out var r)) into.Add(r);
            }
        }
#endif

        private static bool TryRectTransformRect(RectTransform rt, Canvas canvas, float pad, out Rect rect)
        {
            float minX = float.MaxValue, minY = float.MaxValue, maxX = float.MinValue, maxY = float.MinValue;
            var cam = canvas.renderMode == RenderMode.ScreenSpaceOverlay ? null : canvas.worldCamera;
            rt.GetWorldCorners(Corners);
            for (var i = 0; i < 4; i++)
            {
                var p = RectTransformUtility.WorldToScreenPoint(cam, Corners[i]);
                Expand(p.x, p.y, ref minX, ref minY, ref maxX, ref maxY);
            }
            rect = Rect.MinMaxRect(minX - pad, minY - pad, maxX + pad, maxY + pad);
            return rect.xMax > 0 && rect.yMax > 0 && rect.xMin < Screen.width && rect.yMin < Screen.height;
        }

        private bool TryGetScreenRect(out Rect rect)
        {
            rect = default;
            float minX = float.MaxValue, minY = float.MaxValue, maxX = float.MinValue, maxY = float.MinValue;

            if (_rect != null)
            {
                if (_canvas == null) _canvas = GetComponentInParent<Canvas>();
                if (_canvas == null || !_canvas.isActiveAndEnabled) return false;
                var cam = _canvas.renderMode == RenderMode.ScreenSpaceOverlay ? null : _canvas.worldCamera;
                _rect.GetWorldCorners(Corners);
                for (var i = 0; i < 4; i++)
                {
                    var p = RectTransformUtility.WorldToScreenPoint(cam, Corners[i]);
                    Expand(p.x, p.y, ref minX, ref minY, ref maxX, ref maxY);
                }
            }
            else if (_renderer != null && _renderer.isVisible)
            {
                var cam = Camera.main;
                if (cam == null) return false;
                var b = _renderer.bounds;
                for (var i = 0; i < 8; i++)
                {
                    var corner = new Vector3(
                        (i & 1) == 0 ? b.min.x : b.max.x,
                        (i & 2) == 0 ? b.min.y : b.max.y,
                        (i & 4) == 0 ? b.min.z : b.max.z);
                    var p = cam.WorldToScreenPoint(corner);
                    // Behind the camera: cover the whole screen rather than leak.
                    if (p.z < 0) { rect = new Rect(0, 0, Screen.width, Screen.height); return true; }
                    Expand(p.x, p.y, ref minX, ref minY, ref maxX, ref maxY);
                }
            }
            else
            {
                return false;
            }

            rect = Rect.MinMaxRect(minX - padding, minY - padding, maxX + padding, maxY + padding);
            return rect.xMax > 0 && rect.yMax > 0 && rect.xMin < Screen.width && rect.yMin < Screen.height;
        }

        private static void Expand(float x, float y, ref float minX, ref float minY, ref float maxX, ref float maxY)
        {
            if (x < minX) minX = x;
            if (y < minY) minY = y;
            if (x > maxX) maxX = x;
            if (y > maxY) maxY = y;
        }
    }
}
