using System;
using System.Globalization;
using UnityEngine;

namespace ViKPI.Internal
{
    /// <summary>The player's stored choice. Kept in PlayerPrefs so it survives restarts.</summary>
    internal static class ConsentStore
    {
        private const string Key = "vikpi.consent";
        private const string AtKey = "vikpi.consent_at";

        internal static VikpiConsentStatus Read()
        {
            switch (PlayerPrefs.GetString(Key, ""))
            {
                case "granted": return VikpiConsentStatus.Granted;
                case "denied": return VikpiConsentStatus.Denied;
                default: return VikpiConsentStatus.Unknown;
            }
        }

        internal static void Write(bool granted)
        {
            PlayerPrefs.SetString(Key, granted ? "granted" : "denied");
            PlayerPrefs.SetString(AtKey, DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture));
            PlayerPrefs.Save();
        }

        internal static void Clear()
        {
            PlayerPrefs.DeleteKey(Key);
            PlayerPrefs.DeleteKey(AtKey);
            PlayerPrefs.Save();
        }

        /// <summary>Whether data may be collected right now under these settings.</summary>
        internal static bool Allows(VikpiSettings s)
        {
            if (s == null || s.AppTargetsChildren) return false;
            return s.ConsentMode == VikpiConsentMode.NotRequired || Read() == VikpiConsentStatus.Granted;
        }
    }

    /// <summary>
    /// The built-in consent prompt. Drawn with IMGUI so it needs no prefab, font or UI package;
    /// when uGUI is present an invisible full-screen blocker stops taps reaching the game behind it.
    /// Both choices are equally prominent, as consent rules (GDPR, store policies) expect.
    /// </summary>
    [AddComponentMenu("")]
    internal sealed class ConsentPrompt : MonoBehaviour
    {
        private static ConsentPrompt _open;

        private VikpiSettings _settings;
        private Action<bool> _onChoice;
        private GUIStyle _panel, _title, _body, _primary, _secondary, _link;
        private Texture2D _dim, _panelTex, _primaryTex, _secondaryTex;
#if VIKPI_UGUI
        private GameObject _blocker;
#endif

        internal static bool IsOpen => _open != null;

        internal static void Show(VikpiSettings settings, Action<bool> onChoice)
        {
            if (_open != null) return;
            var go = new GameObject("ViKPI Consent");
            DontDestroyOnLoad(go);
            var p = go.AddComponent<ConsentPrompt>();
            p._settings = settings;
            p._onChoice = onChoice;
            _open = p;
        }

        private void Awake()
        {
#if VIKPI_UGUI
            // Swallow taps aimed at the game while the prompt is up.
            _blocker = new GameObject("ViKPI Consent Blocker", typeof(RectTransform));
            DontDestroyOnLoad(_blocker);
            var canvas = _blocker.AddComponent<Canvas>();
            canvas.renderMode = RenderMode.ScreenSpaceOverlay;
            canvas.sortingOrder = short.MaxValue;
            _blocker.AddComponent<UnityEngine.UI.GraphicRaycaster>();
            var img = new GameObject("Blocker", typeof(RectTransform)).AddComponent<UnityEngine.UI.Image>();
            img.transform.SetParent(_blocker.transform, false);
            img.color = new Color(0, 0, 0, 0);
            var rt = (RectTransform)img.transform;
            rt.anchorMin = Vector2.zero;
            rt.anchorMax = Vector2.one;
            rt.offsetMin = rt.offsetMax = Vector2.zero;
#endif
        }

        private void Choose(bool granted)
        {
            var cb = _onChoice;
            _onChoice = null;
            Destroy(gameObject);
            cb?.Invoke(granted);
        }

        private void OnDestroy()
        {
            if (_open == this) _open = null;
#if VIKPI_UGUI
            if (_blocker != null) Destroy(_blocker);
#endif
            foreach (var t in new[] { _dim, _panelTex, _primaryTex, _secondaryTex })
                if (t != null) Destroy(t);
        }

        private static Texture2D Solid(Color c)
        {
            var t = new Texture2D(1, 1) { hideFlags = HideFlags.HideAndDontSave };
            t.SetPixel(0, 0, c);
            t.Apply();
            return t;
        }

        private void BuildStyles(float scale)
        {
            _dim = Solid(new Color(0, 0, 0, 0.6f));
            _panelTex = Solid(new Color(0.12f, 0.12f, 0.14f, 0.98f));
            _primaryTex = Solid(new Color(0.22f, 0.45f, 0.95f, 1f));
            _secondaryTex = Solid(new Color(0.28f, 0.28f, 0.32f, 1f));
            var pad = Mathf.RoundToInt(18 * scale);
            _panel = new GUIStyle { normal = { background = _panelTex }, padding = new RectOffset(pad, pad, pad, pad) };
            _title = new GUIStyle { fontSize = Mathf.RoundToInt(19 * scale), fontStyle = FontStyle.Bold, wordWrap = true, normal = { textColor = Color.white } };
            _body = new GUIStyle { fontSize = Mathf.RoundToInt(14 * scale), wordWrap = true, normal = { textColor = new Color(0.86f, 0.86f, 0.9f) } };
            _link = new GUIStyle(_body) { normal = { textColor = new Color(0.55f, 0.72f, 1f) }, fontStyle = FontStyle.Bold };
            GUIStyle Button(Texture2D bg) => new GUIStyle
            {
                fontSize = Mathf.RoundToInt(15 * scale),
                fontStyle = FontStyle.Bold,
                alignment = TextAnchor.MiddleCenter,
                normal = { background = bg, textColor = Color.white },
                active = { background = bg, textColor = new Color(1, 1, 1, 0.7f) },
                padding = new RectOffset(pad / 2, pad / 2, pad / 2, pad / 2),
            };
            _primary = Button(_primaryTex);
            _secondary = Button(_secondaryTex);
        }

        private void OnGUI()
        {
            if (_settings == null) return;
            var shortSide = Mathf.Min(Screen.width, Screen.height);
            var scale = Mathf.Clamp(shortSide / 420f, 1f, 4f);
            if (_panel == null) BuildStyles(scale);
            GUI.depth = -10000;

            GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), _dim);
            var w = Mathf.Min(Screen.width - 32 * scale, 460 * scale);
            var area = new Rect((Screen.width - w) / 2f, Screen.height * 0.18f, w, Screen.height * 0.7f);
            GUILayout.BeginArea(area);
            GUILayout.BeginVertical(_panel);
            GUILayout.Label(_settings.ConsentTitle, _title);
            GUILayout.Space(10 * scale);
            GUILayout.Label(_settings.ConsentMessage, _body);
            if (_settings.HasValidPrivacyPolicyUrl)
            {
                GUILayout.Space(8 * scale);
                if (GUILayout.Button(_settings.ConsentPolicyLabel, _link)) Application.OpenURL(_settings.PrivacyPolicyUrl.Trim());
            }
            GUILayout.Space(16 * scale);
            GUILayout.BeginHorizontal();
            if (GUILayout.Button(_settings.ConsentDeclineLabel, _secondary, GUILayout.Height(44 * scale))) Choose(false);
            GUILayout.Space(10 * scale);
            if (GUILayout.Button(_settings.ConsentAcceptLabel, _primary, GUILayout.Height(44 * scale))) Choose(true);
            GUILayout.EndHorizontal();
            GUILayout.EndVertical();
            GUILayout.EndArea();
        }
    }
}
