using TMPro;
using UnityEngine;

namespace MajacloudSdk.Samples.Starter
{
    /// <summary>
    /// One per demo scene: signs the player in when the scene starts and tells
    /// the panels in that scene. Every field is optional, so each scene only
    /// wires the panels it shows. Copy the panels you need into your own scenes.
    /// </summary>
    public sealed class StarterController : MonoBehaviour
    {
        public static StarterController Instance { get; private set; }

        [Header("Services")]
        [SerializeField] private string leaderboardSlug = "coins";
        [SerializeField] private string rewardKey = "daily_coins";
        [SerializeField] private string saveKey = "progress";
        [SerializeField] private bool signInOnStart = true;

        [Header("UI (all optional)")]
        [SerializeField] private StatusToast toast;
        [SerializeField] private TMP_Text connectionLabel;
        [SerializeField] private TabBar tabBar;
        [SerializeField] private PlayerBadge badge;
        [SerializeField] private LeaderboardPanel leaderboardPanel;
        [SerializeField] private CloudSavePanel cloudSavePanel;
        [SerializeField] private RewardsPanel rewardsPanel;
        [SerializeField] private ConfigPanel configPanel;
        [SerializeField] private AccountPanel accountPanel;

        public string LeaderboardSlug => leaderboardSlug;
        public string RewardKey => rewardKey;
        public string SaveKey => saveKey;

        private void Awake()
        {
            Instance = this;
            if (rewardsPanel != null && badge != null) rewardsPanel.CoinsChanged += badge.SetCoins;
            // The scenes ship without a camera so they work in every render pipeline.
            if (Camera.main == null)
            {
                var cameraGo = new GameObject("Main Camera") { tag = "MainCamera" };
                var camera = cameraGo.AddComponent<Camera>();
                camera.clearFlags = CameraClearFlags.SolidColor;
                camera.backgroundColor = new Color32(243, 246, 251, 255);
                camera.orthographic = true;
            }
        }

        private async void Start()
        {
            if (tabBar != null) tabBar.Select(0);
            if (!signInOnStart) return;
            if (!Majacloud.IsInitialized)
            {
                SetConnection(false, "Not set up yet. In the editor: Tools › Majacloud › Setup.");
                Toast("Run Tools › Majacloud › Setup and test the connection first.", true);
                return;
            }
            Majacloud.Auth.SessionExpired += OnSessionExpired;
            // A stored session is restored silently when moving between demo scenes.
            bool restoring = Majacloud.Auth.IsSignedIn;
            if (!restoring) Toast("Signing in…");
            var signIn = await Majacloud.Auth.SignInAnonymouslyAsync();
            if (this == null) return;
            if (!signIn.Ok)
            {
                SetConnection(false, "Can't sign in: " + signIn.Error.Message);
                Toast("Sign-in failed: " + signIn.Error.Message, true);
                return;
            }
            if (!restoring) Toast("Signed in as " + signIn.Value.DisplayName);
            var project = Majacloud.Settings != null ? Majacloud.Settings.ProjectName : string.Empty;
            SetConnection(true, "Connected" + (string.IsNullOrEmpty(project) ? string.Empty : " to " + project));
            if (leaderboardPanel != null) leaderboardPanel.OnSignedIn();
            if (cloudSavePanel != null) cloudSavePanel.OnSignedIn();
            if (rewardsPanel != null) rewardsPanel.OnSignedIn();
        }

        private void OnDestroy()
        {
            if (Majacloud.IsInitialized && Majacloud.Auth != null) Majacloud.Auth.SessionExpired -= OnSessionExpired;
            if (Instance == this) Instance = null;
        }

        private async void OnSessionExpired()
        {
            Toast("Session expired, signing in again…", true);
            var result = await Majacloud.Auth.SignInAnonymouslyAsync();
            if (this != null && !result.Ok) Toast(result.Error.Message, true);
        }

        private void SetConnection(bool ok, string text)
        {
            if (connectionLabel == null) return;
            connectionLabel.text = (ok ? "<color=#16A34A>●</color>  " : "<color=#D93F44>●</color>  ") + text;
        }

        public static void Toast(string message, bool isError = false)
        {
            if (Instance != null && Instance.toast != null) Instance.toast.Show(message, isError);
            else Debug.Log("[Majacloud Demo] " + message);
        }
    }
}
