using System.Text.RegularExpressions;
using CoolGameX;
using UnityEngine;

/// <summary>
/// Minimal end-to-end test for the CoolAPI SDK.
///
///  1. Add the CoolAPI package to your project (Package Manager -> Add package
///     from disk -> select sdk/package.json).
///  2. Create an empty GameObject in your scene and attach this script.
///  3. To test in the Editor, get a token:
///        cd server
///        node scripts/get-token.js you@example.com yourpassword
///     and paste it into "Editor Test Token" in the Inspector.
///  4. Press Play. Click the on-screen "Unlock 'test'" button.
///  5. Open the Cool GameX app -> Achievements tab -> it should be unlocked.
///
/// When the real launcher runs your game, it passes the token automatically as
/// --cgx-token, so you can leave "Editor Test Token" blank for the shipped build.
/// </summary>
public class CoolGameXTester : MonoBehaviour
{
    [Header("Config")]
    [Tooltip("Must match the game's slug in Cool GameX.")]
    public string gameSlug = "test-game";

    [Tooltip("Your backend URL. Use http://localhost:4000 while developing.")]
    public string serverUrl = "http://localhost:4000";

    [Tooltip("The achievement slug to unlock when the button is clicked.")]
    public string achievementSlug = "test";

    [Header("Editor testing only")]
    [Tooltip("Paste a JWT from 'node scripts/get-token.js'. Leave blank in builds.")]
    [TextArea]
    public string editorTestToken = "";

    private string _status = "Initializing…";
    private bool _ready = false;
    private bool _busy = false;

    async void Start()
    {
        await CoolAPI.Initialize(gameSlug, serverUrl);

        // Prefer the launcher token; fall back to the editor test token.
        string raw = CoolAPI.IsAuthenticated ? CoolAPI.Token : editorTestToken;
        string token = ExtractJwt(raw);

        if (string.IsNullOrEmpty(token))
        {
            _status = "No valid token found. Run get-token.js and paste its token into 'Editor Test Token'.";
            Debug.LogWarning("[CGX] " + _status);
            return;
        }

        bool ok = await CoolAPI.Auth.LoginWithToken(token);
        _ready = ok;
        _status = ok
            ? "Logged in ✓  Ready to unlock."
            : $"Login failed → {CoolAPI.LastError}";
        Debug.Log("[CGX] " + _status);
    }

    /// <summary>
    /// Pulls a JWT out of arbitrary pasted text. Matches the three dot-separated
    /// base64url segments, so it works even if you copy extra lines around it.
    /// </summary>
    private static string ExtractJwt(string input)
    {
        if (string.IsNullOrWhiteSpace(input)) return null;
        var m = Regex.Match(input, @"eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+");
        return m.Success ? m.Value : null;
    }

    /// <summary>Hook this to a UI Button's OnClick, or use the on-screen button below.</summary>
    public async void UnlockTestAchievement()
    {
        if (_busy) return;
        if (!_ready)
        {
            _status = "Not logged in yet.";
            return;
        }

        _busy = true;
        _status = $"Unlocking '{achievementSlug}'…";
        bool ok = await CoolAPI.Achievements.Unlock(achievementSlug);
        _status = ok
            ? $"Unlocked '{achievementSlug}' 🎉  (check the app's Achievements tab)"
            : $"Unlock failed — does '{achievementSlug}' exist on '{gameSlug}'?";
        Debug.Log("[CGX] " + _status);
        _busy = false;
    }

    // Simple on-screen button so you don't need to wire up any UI to test.
    void OnGUI()
    {
        GUI.skin.button.fontSize = 18;
        GUI.skin.label.fontSize = 14;

        if (GUI.Button(new Rect(20, 20, 280, 60), $"Unlock '{achievementSlug}'"))
        {
            UnlockTestAchievement();
        }

        GUI.Label(new Rect(20, 90, 600, 60), _status);
    }
}
