using UnityEngine;
#if UNITY_IOS
using UnityEngine.iOS;
#endif

namespace Davanci.Nexus
{
    // Native in-app rating prompt. Call TryAsk() at a genuinely happy moment; the OS
    // rating sheet appears in-context. Self-throttles on top of the OS's own limits.
    public static class NexusReview
    {
        const string KeyLastAsked = "Davanci.Nexus.Review.LastAskedUtc";
        const string KeyAskCount  = "Davanci.Nexus.Review.AskCount";

        const int    MaxAsks        = 3;
        const double MinDaysBetween = 20;

        // Returns true if a prompt was requested; the OS may still decline to show it.
        public static bool TryAsk()
        {
            if (!ShouldAsk())
                return false;

            RecordAsk();
            return RequestNative();
        }

        // Forces the native sheet, bypassing the soft throttle (OS limits still apply).
        public static bool RequestNow() => RequestNative();

        // Opens the store listing's review page directly (for an explicit "Rate us" button).
        // iOS needs the numeric App Store ID; Android falls back to the app's own package.
        public static void OpenStorePage(string iosAppId, string androidPackage = null)
        {
#if UNITY_IOS && !UNITY_EDITOR
            if (string.IsNullOrEmpty(iosAppId))
            {
                Debug.LogWarning("[Nexus] iOS App Store ID not set — set it in Davanci Nexus → Ratings to open the review page.");
                return;
            }
            Application.OpenURL($"itms-apps://itunes.apple.com/app/id{iosAppId}?action=write-review");
#elif UNITY_ANDROID && !UNITY_EDITOR
            string pkg = string.IsNullOrEmpty(androidPackage) ? Application.identifier : androidPackage;
            Application.OpenURL($"market://details?id={pkg}");
#else
            if (string.IsNullOrEmpty(iosAppId))
                Debug.LogWarning("[Nexus] iOS App Store ID not set — set it in Davanci Nexus → Ratings.");
            Debug.Log($"[Nexus] OpenStorePage (editor no-op), iOS id:{iosAppId}");
#endif
        }

        static bool ShouldAsk()
        {
            if (PlayerPrefs.GetInt(KeyAskCount, 0) >= MaxAsks)
                return false;

            string last = PlayerPrefs.GetString(KeyLastAsked, "");
            if (!string.IsNullOrEmpty(last) &&
                System.DateTime.TryParse(last, null,
                    System.Globalization.DateTimeStyles.RoundtripKind, out var when) &&
                (System.DateTime.UtcNow - when).TotalDays < MinDaysBetween)
            {
                return false;
            }

            return true;
        }

        static void RecordAsk()
        {
            PlayerPrefs.SetInt(KeyAskCount, PlayerPrefs.GetInt(KeyAskCount, 0) + 1);
            PlayerPrefs.SetString(KeyLastAsked, System.DateTime.UtcNow.ToString("o"));
            PlayerPrefs.Save();
        }

        static bool RequestNative()
        {
#if UNITY_IOS && !UNITY_EDITOR
            return Device.RequestStoreReview();
#elif UNITY_ANDROID && !UNITY_EDITOR
            // Play In-App Review needs the Google Play Review package; fall back to the store page.
            Application.OpenURL($"market://details?id={Application.identifier}");
            return true;
#else
            Debug.Log("[Nexus] Review prompt requested (editor / unsupported platform, no-op).");
            return false;
#endif
        }
    }
}
