using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using ZenFulcrum.EmbeddedBrowser;
using Debug = UnityEngine.Debug;

namespace NeoriginPCSDK
{
    /// <summary>
    /// Steam平台服务器实现
    /// 继承NeoriginPlatformBaseServer，实现Steam平台的初始化、登录、支付等功能
    /// </summary>
    public class NeoriginPlatformSteamServer : NeoriginPlatformBaseServer
    {
        #region 字段

        /// <summary>
        /// Steam AppID配置
        /// </summary>
        private uint steamAppId = 480; // 默认使用测试AppID

        private NeoriginSDKConfig _sdkConfig;
        
        protected override string PlatformAiHelpPlatformTag => "Platform_Steam";

        #endregion

        #region 公共方法 - 生命周期

        /// <summary>
        /// 初始化Steam平台
        /// </summary>
        public override void Initialize(NeoriginSDKConfig.Platform sdkConfig, NeoriginSDKDevice deviceData, NeoriginSDKParamsInit initData, NeoriginSDK.InitCallBack callBack)
        {
            Debug.Log("<color=cyan>NeoriginPlatformSteamServer.Initialize Start initializing Steam platform...</color>");

            // 从配置获取Steam AppID
            _sdkConfig = NeoriginSDK.Instance.SDKConfig;
            if (_sdkConfig.platform != null && !string.IsNullOrEmpty(_sdkConfig.platform.platformSteamAppId))
            {
                steamAppId = uint.Parse(_sdkConfig.platform.platformSteamAppId);
            }

            // 初始化Steam SDK
            if (!SteamManager.Instance.InitSteam(steamAppId))
            {
                Debug.LogError("<color=red>Steam SDK initialization failed</color>");
                callBack?.Invoke(NeoriginSDKStatusCode.InternalError, "Steam SDK initialization failed, please ensure Steam client is running", new NeoriginSDKCallbackDataInit());
                return;
            }
            // 调用基类初始化
            base.Initialize(sdkConfig, deviceData, initData, callBack);
        }

        #endregion

        #region 公共方法 - 登录

        /// <summary>
        /// Steam账号登录
        /// </summary>
        public override void Login(string userAccount, int touristFlag, NeoriginSDK.LoginCallBack callBack)
        {
            if (!CheckSteamInitialized(callBack))
                return;

            SteamManager.Instance.GetAuthTicket(
                onSuccess: (ticket) => HandleSteamLogin(userAccount, touristFlag, ticket, callBack),
                onFail: (errorMsg) => HandleSteamTicketError(errorMsg, callBack)
            );
        }

        public override void LoginAccount(NeoriginSDK.LoginAccountCallBack callBack, NeoriginSDK.LoginAccountProcessCallBack processCallBack = null)
        {
            if (!CheckSteamInitialized(callBack))
                return;

            SteamManager.Instance.GetAuthTicket(
                onSuccess: (ticket) => HandleSteamAccountLogin(ticket, callBack, processCallBack),
                onFail: (errorMsg) => HandleSteamTicketError(errorMsg, callBack)
            );
        }

        #endregion

        #region 公共方法 - 用户中心

        /// <summary>
        /// 打开用户中心
        /// Steam渠道拦截切换账号功能
        /// </summary>
        public override void OpenUserCenter(NeoriginSDKCallbackDataUserInfo u8User, NeoriginSDKU8UserExtraData u8Role,NeoriginSDK.OpenUserCenterCallBack callBack, NeoriginSDK.OpenUserCenterProcessCallBack processCallBack = null)
        {
            base.OpenUserCenter(u8User, u8Role, callBack, (action, data) =>
            {
                // 拦截切换账号 - 用户点击时立即关闭WebView并提示
                if (action == "ucenter_accountchange_click")
                {
                    Debug.Log("<color=yellow>Steam渠道不支持切换账号，直接返回</color>");
                    // 通知H5显示提示信息
                    // 这里可以调用H5的JS方法显示toast提示
                    return;
                }
                // 其他操作正常传递
                processCallBack?.Invoke(action, data);
            });
        }

        #endregion

        #region 公共方法 - 支付

        /// <summary>
        /// Steam平台支付
        /// </summary>
        public override void Pay(NeoriginSDKPlatformPayParameter payParams, NeoriginSDK.PayCallBack callBack, NeoriginSDK.PayProcessCallBack payProcessCallBack = null)
        {
            Debug.Log($"<color=cyan>NeoriginPlatformSteamServer.Pay Start Steam payment, Product ID: {payParams.product_id}</color>");
            
            // 检查Steam是否已初始化
            if (!SteamManager.Instance.IsInitialized)
            {
                Debug.LogError("<color=red>Steam not initialized, cannot proceed with payment</color>");
                callBack?.Invoke(NeoriginSDKStatusCode.InternalError, "Steam not initialized", new NeoriginSDKCallbackDataPay());
                return;
            }
            
            base.Pay(payParams, callBack, payProcessCallBack);
        }

        #endregion

        #region 重写方法 - H5交互

         /// <summary>
        /// 重写基类方法，处理从H5触发的Steam登录
        /// 参考 Google 登录流程，调用 hwThirdAccount 接口
        /// </summary>
        protected override void HandleSteamLoginFromH5(NeoriginSDK.LoginAccountCallBack callBack, NeoriginSDK.LoginAccountProcessCallBack processCallBack, NeoriginSDKWebview webview = null)
        {
            Debug.Log("<color=cyan>NeoriginPlatformSteamServer.HandleSteamLoginFromH5</color>");
            
            if (string.IsNullOrEmpty(SteamData.Instance.SteamId))
            {
                Debug.LogError("<color=red>Steam ID is empty, cannot login</color>");
                callBack?.Invoke(NeoriginSDKStatusCode.InternalError, "Steam not properly initialized", new NeoriginSDKCallbackDataLoginAccount());
                return;
            }

            // 获取Steam Ticket，然后调用 hwThirdAccount 接口
            SteamManager.Instance.GetAuthTicket(
                onSuccess: (ticket) =>
                {
                    if (webview != null)
                    {
                        webview.CloseWebview();
                    }
                    ShowUserPolicyAgreement(ticket, callBack);
                },
                onFail: (errorMsg) =>
                {
                    Debug.LogError($"<color=red>Failed to get Steam Ticket: {errorMsg}</color>");
                    // Ticket获取失败时，返回错误给H5
                    callBack?.Invoke(NeoriginSDKStatusCode.LoginFailed, $"Failed to get Steam Ticket: {errorMsg}", new NeoriginSDKCallbackDataLoginAccount());
                }
            );
        }

        /// <summary>
        /// 重写基类方法，处理从H5触发的Steam绑定
        /// </summary>
        protected override void HandleSteamBindFromH5(NeoriginSDK.OpenUserCenterCallBack callBack, NeoriginSDK.OpenUserCenterProcessCallBack processCallBack, NeoriginSDKWebview webview = null)
        {
            Debug.Log("<color=cyan>NeoriginPlatformSteamServer.HandleSteamBindFromH5</color>");

            if (string.IsNullOrEmpty(SteamData.Instance.SteamId))
            {
                Debug.LogError("<color=red>Steam ID is empty, cannot bind</color>");

                // 通过 WebView 回调 H5 显示错误
                if (webview != null)
                {
                    var errorData = new { type = "bind_steam_result", code = (int)NeoriginSDKStatusCode.InternalError, msg = "Steam not properly initialized" };
                    string json = Newtonsoft.Json.JsonConvert.SerializeObject(errorData);
                    webview.CallJsFunc(json);
                }

                callBack?.Invoke(NeoriginSDKStatusCode.InternalError, "Steam not properly initialized", new NeoriginSDKCallbackDataLoginAccount());
                return;
            }

            // 获取Steam Ticket进行绑定
            SteamManager.Instance.GetAuthTicket(
                onSuccess: (ticket) =>
                {
                    DoSteamBindWithTicket(ticket, (code, msg, data) =>
                    {
                        Debug.Log($"<color=cyan>Steam bind completed. Code: {code}, Msg: {msg}</color>");
                        if (code == NeoriginSDKStatusCode.Success)
                        {
                            //上报数数绑定成功
                            NeoriginSDKU8UserExtraData roleInfo = NeoriginSDKStorage.LoadU8RoleInfo();
                            Dictionary<string, object> dic = new Dictionary<string, object>();
                            dic.Add("mj_channel", _sdkConfig.sdk.u8ChannelId);
                            dic.Add("SDKID", data.sdkLogUserId);
                            dic.Add("bind_account", data.sdkLogThirdUserName);
                            
                            dic.Add("mj_bind_name", "Steam");
                            dic.Add("mj_bind_Steam", data.sdkLogThirdUserName);
                            dic.Add("role_id", roleInfo.roleID);
                            dic.Add("role_name", roleInfo.roleName);
                            dic.Add("server_name", roleInfo.serverName);
                            NeoriginSDK.Instance.SubmitTAUserInfo(0, "mj_pc_bind_account", dic, (taCode, taMsg, taData) =>
                            {
                                Debug.Log("SubmitTAUserInfo mj_pc_bind_account code: " + taCode + ", taMsg: " + taMsg);
                            });
                        }
                        // 通过 WebView 回调 H5，通知绑定结果
                        if (webview != null)
                        {
                            var resultData = new
                            {
                                type = "bind_steam_result",
                                code = (int)code,
                                msg,
                            };
                            string json = Newtonsoft.Json.JsonConvert.SerializeObject(resultData);
                            Debug.Log($"<color=cyan>Calling H5 unityToJsFunc with: {json}</color>");
                            webview.CallJsFunc(json);
                        }

                        // 同时调用 processCallBack 保持兼容性
                        processCallBack?.Invoke("bind_steam_result", data);
                    });
                },
                onFail: (errorMsg) =>
                {
                    Debug.LogError($"<color=red>Failed to get Steam Ticket for bind: {errorMsg}</color>");

                    // 通过 WebView 回调 H5 显示错误
                    if (webview != null)
                    {
                        var errorData = new { type = "bind_steam_result", code = (int)NeoriginSDKStatusCode.LoginFailed, msg = $"Failed to get Steam Ticket: {errorMsg}" };
                        string json = Newtonsoft.Json.JsonConvert.SerializeObject(errorData);
                        webview.CallJsFunc(json);
                    }

                    callBack?.Invoke(NeoriginSDKStatusCode.LoginFailed, $"Failed to get Steam Ticket: {errorMsg}", new NeoriginSDKCallbackDataLoginAccount());
                }
            );
        }

        #endregion

        #region Private Methods
      

        #region 检查与错误处理

        private bool CheckSteamInitialized(NeoriginSDK.LoginCallBack callBack)
        {
            if (!string.IsNullOrEmpty(SteamData.Instance.SteamId))
                return true;

            Debug.LogError("<color=red>Steam ID is empty, cannot proceed</color>");
            callBack?.Invoke(NeoriginSDKStatusCode.InternalError, "Steam not properly initialized", new NeoriginSDKCallbackDataLogin());
            return false;
        }

        private bool CheckSteamInitialized(NeoriginSDK.LoginAccountCallBack callBack)
        {
            if (!string.IsNullOrEmpty(SteamData.Instance.SteamId))
                return true;

            Debug.LogError("<color=red>Steam ID is empty, cannot proceed</color>");
            callBack?.Invoke(NeoriginSDKStatusCode.InternalError, "Steam not properly initialized", new NeoriginSDKCallbackDataLoginAccount());
            return false;
        }

        private void HandleSteamTicketError(string errorMsg, NeoriginSDK.LoginCallBack callBack)
        {
            Debug.LogError($"<color=red>Failed to get Steam Ticket: {errorMsg}</color>");
            callBack?.Invoke(NeoriginSDKStatusCode.LoginFailed, $"Failed to get Steam Ticket: {errorMsg}", new NeoriginSDKCallbackDataLogin());
        }

        private void HandleSteamTicketError(string errorMsg, NeoriginSDK.LoginAccountCallBack callBack)
        {
            Debug.LogError($"<color=red>Failed to get Steam Ticket: {errorMsg}</color>");
            callBack?.Invoke(NeoriginSDKStatusCode.LoginFailed, $"Failed to get Steam Ticket: {errorMsg}", new NeoriginSDKCallbackDataLoginAccount());
        }
      

        #endregion

        #region 登录流程处理

        private void HandleSteamLogin(string userAccount, int touristFlag, string ticket, NeoriginSDK.LoginCallBack callBack)
        {
            HandleSteamAccountLogin(ticket, (code, msg, data) =>
            {
                var resData = CreateLoginData(data);
                callBack.Invoke(code, msg, resData);
            }, null);
        }
      

        private void HandleSteamAccountLogin(string ticket, NeoriginSDK.LoginAccountCallBack callBack, NeoriginSDK.LoginAccountProcessCallBack processCallBack)
        {
            // Steam不使用登陆态登陆，登陆态直接替换成Steam状态登陆
            SteamLogin(ticket, (code, msg, res) =>
            {
                // 没有绑定过Steam账号，弹出H5登录框选择登录方式
                if (code == NeoriginSDKStatusCode.LoginNotBind)
                {
                    NeoriginSDKStorage.DeletePlatformUserInfo();  // 删除本地登录状态
                    // 保存原始callback供后续使用
                    NeoriginSDK.LoginAccountCallBack originalCallBack = callBack;
                    // 拉起H5登录框，选择登录方式
                    base.LoginAccount((loginCode, loginMsg, loginData) =>
                    {
                        if (loginCode == NeoriginSDKStatusCode.Success)
                        {
                            // Steam 渠道下本次实际发生 Google 授权时，单独上报 google_auth
                            if (loginData.thirdLoginType == 1)
                            {
                                Dictionary<string, object> authDic = new Dictionary<string, object>
                                {
                                    { "mj_channel", _sdkConfig.sdk.u8ChannelId },
                                    { "SDKID", loginData.sdkLogUserId }
                                };
                                NeoriginSDK.Instance.SubmitTAUserInfo(0, "mj_pc_google_auth", authDic, (taCode, taMsg, taData) =>
                                {
                                    Debug.Log($"SubmitTAUserInfo mj_pc_google_auth (steam flow) code: {taCode}, taMsg: {taMsg}");
                                });
                            }
                            if (loginData.thirdLoginType != NeoriginThirdLoginType.ThirdLogin_Steam)
                            {   // 不是Steam登录，绑定Steam
                                DoSteamBindWithTicket(ticket, originalCallBack, true);
                                return;
                            }
                        }
                        originalCallBack?.Invoke(loginCode, loginMsg, loginData);
                    }, processCallBack);
                }
                else
                {
                    callBack?.Invoke(code, msg, res);
                }
            });
        }
        
         /// <summary>
        /// 显示用户协议界面（点击Steam登录按钮时显示）
        /// 参考V1.4.0文档3.5节：Steam渠道首次注册登陆，需要显示用户协议
        /// 同意协议后调用hwThirdAccount注册账号，不同意则退出游戏
        /// </summary>
        private void ShowUserPolicyAgreement(string ticket, NeoriginSDK.LoginAccountCallBack callBack)
        {
            Debug.Log("<color=cyan>ShowUserPolicyAgreement: Opening user policy agreement...</color>");
            NeoriginSDK.Instance.ResetAgreementPopupReportState();

            NeoriginSDKPlatformInitGameOtherCfg gameOtherConfig = NeoriginSDKStorage.LoadPlatformInitGameOtherCfg();
            string userPolicyUrl = gameOtherConfig.user_policy;
            string privacyPolicyUrl = gameOtherConfig.privacy_agreement_url;

            // 如果没有配置协议URL，直接调用hwThirdAccount注册账号
            if (string.IsNullOrEmpty(userPolicyUrl) && string.IsNullOrEmpty(privacyPolicyUrl))
            {
                Debug.LogWarning("<color=yellow>Policy URLs are empty, register Steam account directly...</color>");
                DoSteamThirdAccountLogin(ticket, callBack);
                return;
            }
            
            NeoriginSDKWebview sdkWebView = new NeoriginSDKWebview(
                onCloseListener: () =>
                {
                    Debug.Log("<color=cyan>ShowUserPolicyAgreement: User closed the agreement window.</color>");
                    // 用户关闭窗口视为不同意，退出游戏
                    callBack?.Invoke(NeoriginSDKStatusCode.LoginCanceled, "User closed policy agreement", new NeoriginSDKCallbackDataLoginAccount());
                },
                isShowCloseBtn: false
            );

            sdkWebView.adjustmentProportion(0.82f, 0.82f);
            // 使用H5登录页面，传入特殊参数显示协议界面
            string h5Url = platformH5Url + "/" + platformH5Steam;
            string urlParams = GetWebViewParameters();
            urlParams += $"&page=agreement";

            NeoriginSDKShowWebViewParams webviewParams = new NeoriginSDKShowWebViewParams
            {
                isDebug = platformIsDebug
            };

            sdkWebView.ShowWebView(h5Url + urlParams, webviewParams, () =>
            {
                Debug.Log("<color=cyan>ShowUserPolicyAgreement: WebView loaded successfully</color>");
            }, (args) =>
            {
                if (args == null || args.Count < 2)
                {
                    Debug.Log("<color=red>ShowUserPolicyAgreement: Invalid arguments</color>");
                    return;
                }

                Debug.Log($"<color=cyan>ShowUserPolicyAgreement JS call: {args[0]}, {args[1]}</color>");

                // 获取 JSONNode 的实际值
                string action = args[0].Value as string;
                Debug.Log($"<color=cyan>Action value: '{action}'</color>");

                switch (action)
                {
                    case "policy_agree_click":
                        // 用户同意协议，调用hwThirdAccount注册Steam账号
                        Debug.Log("<color=green>ShowUserPolicyAgreement: User agreed to policy, registering Steam account...</color>");
                        NeoriginSDK.Instance.ReportAgreementPopupEvent();
                        sdkWebView.CloseWebview();
                        DoSteamThirdAccountLogin(ticket, callBack);
                        break;

                    case "policy_disagree_click":
                        // 用户不同意协议，退出游戏
                        Debug.Log("<color=yellow>ShowUserPolicyAgreement: User disagreed to policy, quitting game...</color>");
                        sdkWebView.CloseWebview();
                        Application.Quit();
                        break;

                    case "close_window":
                        // 关闭用户协议界面，退出游戏
                        Debug.Log("<color=yellow>ShowUserPolicyAgreement: User closed policy window, quitting game...</color>");
                        sdkWebView.CloseWebview();
                        callBack?.Invoke(NeoriginSDKStatusCode.LoginCanceled, "User closed policy agreement", new NeoriginSDKCallbackDataLoginAccount());
                        break;

                    case "reg_policy_entry":
                        // 点击用户协议链接，打开浏览器查看详情
                        Debug.Log("<color=cyan>ShowUserPolicyAgreement: User clicked policy link</color>");
                        OpenPolicyBroswer();
                        break;

                    default:
                        Debug.Log("<color=yellow>ShowUserPolicyAgreement: Unknown action " + args[0] + "</color>");
                        break;
                }
            });
        }
        #endregion

        #region 辅助方法

        private static NeoriginSDKCallbackDataLogin CreateLoginData(NeoriginSDKCallbackDataLoginAccount data)
        {
            if (data == null)
                return new NeoriginSDKCallbackDataLogin();
            return new NeoriginSDKCallbackDataLogin
            {
                userID = data.userID,
                username = data.username,
                sdkUserID = data.sdkUserID,
                sdkUserName = data.sdkUserName,
                sdkLogUserId = data.sdkLogUserId,
                sdkLogThirdUserName = data.sdkLogThirdUserName,
                token = data.token,
                isNew = data.isNew,
                thirdLoginType = data.thirdLoginType,
                callbackFrom = data.callbackFrom
            };
        }

        #endregion

        #region Steam API请求

        private void SteamLogin(string ticket, NeoriginSDK.LoginAccountCallBack callBack)
        {
            string time = System.DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
            Dictionary<string, string> reqParams = new Dictionary<string, string>();
            
            // 基础参数
            reqParams.Add("third_token", ticket);
            reqParams.Add("login_type", NeoriginThirdLoginType.ThirdLogin_Steam + "");
            reqParams.Add("open_id", SteamData.Instance.SteamId);
            reqParams.Add("time", time);
            
             // 调用后端Steam登录接口
            NeoHttpUtils.MakePostResult("v1.4.1/login/hwSteamLogin", reqParams, (code, msg, status, repData) =>
            {
                if (code != NeoriginSDKStatusCode.Success)
                {
                    Debug.LogError($"<color=yellow>Steam login request failed: {msg}</color>");
                    callBack?.Invoke(code, msg, new NeoriginSDKCallbackDataLoginAccount());
                    return;
                }

                if (status != 0)
                {
                    Debug.LogError($"<color=yellow>Steam login request failed: {msg}</color>");
                    callBack?.Invoke(MapServerErrorCodeToSDK(status), msg, new NeoriginSDKCallbackDataLoginAccount());
                    return;
                }
               
                LoginHandle(repData);
                NeoriginSDKCallbackDataLoginAccount resultData = new NeoriginSDKCallbackDataLoginAccount
                {
                    sdkUserID = (string)repData["showName"],
                    sdkUserName = (string)repData["showName"],
                    sdkLogUserId = (string)repData["displayName"],
                    thirdLoginType = NeoriginThirdLoginType.ThirdLogin_Steam, // Steam登录类型
                    sdkLogThirdUserName = SteamData.Instance.PersonaName,
                    isNew = repData["isNew"] != null ? (int)repData["isNew"] : 0,
                    thirdLoginTypeName = "steam",
                    callbackFrom = 0
                };
                Debug.Log("<color=green>Steam login successful!</color>");
                callBack?.Invoke(NeoriginSDKStatusCode.Success, "Steam login successful", resultData);
            });
        }

        /// <summary>
        /// 执行Steam绑定请求
        /// </summary>
        private void DoSteamBindWithTicket(string ticket, NeoriginSDK.LoginAccountCallBack callBack, bool reportBindEvent = false)
        {
            NeoriginSDKPlatformUserInfo userInfo = NeoriginSDKStorage.LoadPlatformUserInfo();
            Debug.Log($"<color=cyan>Executing Steam login, Ticket length: {ticket.Length}, uuid={userInfo.uuid}</color>");
            string time = System.DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
            Dictionary<string, string> reqParams = new Dictionary<string, string>();
            // 基础参数
            reqParams.Add("third_token", ticket);
            reqParams.Add("bind_type", NeoriginThirdLoginType.ThirdLogin_Steam + "");
            reqParams.Add("open_id", SteamData.Instance.SteamId);
            reqParams.Add("time", time);
            reqParams.Add("uuid", userInfo.uuid);
            reqParams.Add("token", userInfo.token);

            // 调用后端Steam绑定接口
            NeoHttpUtils.MakePostResult("v1.4.1/login/hwBindThirdAccount", reqParams,  (code, msg, status, repData) =>
            {
                if (code != 0)
                {
                    Debug.LogError($"<color=red>Steam login failed: {msg} (Error code: {code})</color>");
                    callBack?.Invoke(NeoriginSDKStatusCode.LoginFailed, msg,  new NeoriginSDKCallbackDataLoginAccount());
                    return; 
                }
                
                if (status != 0)
                {
                    Debug.LogError($"<color=yellow>Steam login request failed: {msg}</color>");
                    callBack?.Invoke(MapServerErrorCodeToSDK(status), msg, new NeoriginSDKCallbackDataLoginAccount());
                    return;
                }
              
                LoginHandle(repData);
                NeoriginSDKCallbackDataLoginAccount resultData = new NeoriginSDKCallbackDataLoginAccount
                {
                    sdkUserID = (string)repData["showName"],
                    sdkUserName = (string)repData["showName"],
                    sdkLogUserId = (string)repData["displayName"],
                    thirdLoginType = NeoriginThirdLoginType.ThirdLogin_Steam, // Steam登录类型
                    sdkLogThirdUserName = SteamData.Instance.PersonaName,
                    isNew = repData["isNew"] != null ? (int)repData["isNew"] : 0,
                    thirdLoginTypeName = "steam",
                    callbackFrom = 0
                };

                if (reportBindEvent)
                {
                    NeoriginSDKU8UserExtraData roleInfo = NeoriginSDKStorage.LoadU8RoleInfo();
                    Dictionary<string, object> dic = new Dictionary<string, object>();
                    dic.Add("mj_channel", _sdkConfig.sdk.u8ChannelId);
                    dic.Add("SDKID", resultData.sdkLogUserId);
                    dic.Add("bind_account", resultData.sdkLogThirdUserName);
                    dic.Add("mj_bind_name", "Steam");
                    dic.Add("mj_bind_Steam", resultData.sdkLogThirdUserName);
                    dic.Add("role_id", roleInfo != null ? roleInfo.roleID : "");
                    dic.Add("role_name", roleInfo != null ? roleInfo.roleName : "");
                    dic.Add("server_name", roleInfo != null ? roleInfo.serverName : "");
                    NeoriginSDK.Instance.SubmitTAUserInfo(0, "mj_pc_bind_account", dic, (taCode, taMsg, taData) =>
                    {
                        Debug.Log("SubmitTAUserInfo mj_pc_bind_account (steam auto bind) code: " + taCode + ", taMsg: " + taMsg);
                    });
                }

                Debug.Log("<color=green>Steam login successful!</color>");
                callBack?.Invoke(NeoriginSDKStatusCode.Success, "Steam login successful", resultData);
            });
        }
        
        /// <summary>
        /// 调用 hwThirdAccount 接口进行 Steam 登录
        /// </summary>
        private void DoSteamThirdAccountLogin(string ticket, NeoriginSDK.LoginAccountCallBack callBack)
        {
            Debug.Log($"<color=cyan>DoSteamThirdAccountLogin: Calling hwThirdAccount API with ticket</color>");

            Dictionary<string, string> reqParams = new Dictionary<string, string>();
            string time = System.DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();

            // 基础参数 - 后端要求 type 和 token，不是 login_type 和 third_token
            reqParams.Add("type", NeoriginThirdLoginType.ThirdLogin_Steam + "");
            reqParams.Add("open_id", SteamData.Instance.SteamId);
            reqParams.Add("token", ticket);
            reqParams.Add("time", time);

            // 调用后端第三方登录接口
            NeoHttpUtils.MakePostResult("v1.4.1/login/hwThirdAccount", reqParams, (code, msg, status, repData) =>
            {
                if (code != 0)
                {
                    Debug.LogError($"<color=red>Steam third account login failed: {msg} (Error code: {code})</color>");
                    callBack?.Invoke(NeoriginSDKStatusCode.LoginFailed, msg, new NeoriginSDKCallbackDataLoginAccount());
                    return;
                }
                
                if (status != 0)
                {
                    Debug.LogError($"<color=yellow>Steam login request failed: {msg}</color>");
                    callBack?.Invoke(MapServerErrorCodeToSDK(status), msg, new NeoriginSDKCallbackDataLoginAccount());
                    return;
                }

                // 登录成功，处理返回数据
                LoginHandle(repData);

                NeoriginSDKCallbackDataLoginAccount resultData = new NeoriginSDKCallbackDataLoginAccount
                {
                    sdkUserID = (string)repData["showName"],
                    sdkUserName = (string)repData["showName"],
                    sdkLogUserId = (string)repData["displayName"],
                    thirdLoginType = NeoriginThirdLoginType.ThirdLogin_Steam,
                    sdkLogThirdUserName = SteamData.Instance.PersonaName,
                    isNew = repData["isNew"] != null ? (int)repData["isNew"] : 0,
                    thirdLoginTypeName = "steam",
                    callbackFrom = 1
                };

                Debug.Log("<color=green>Steam third account login successful!</color>");
                callBack?.Invoke(NeoriginSDKStatusCode.Success, "Steam login successful", resultData);
            });
        }

        #endregion

        #endregion
    }
}
