using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using Mirror;
using MarsFPSKit.Networking;
using MarsFPSKit.UI;
using Unity.Services.Lobbies.Models;

#if INTEGRATION_STEAM
using Steamworks;
#endif

namespace MarsFPSKit
{
    //Pause Menu state enum
    public enum PauseMenuState { teamSelection = -1, main = 0 }

    public enum AfterTeamSelection { PauseMenu, AttemptSpawn, Loadout }

    /// <summary>
    /// This class is used to store spawns for a game mode internally
    /// </summary>
    [System.Serializable]
    public class InternalSpawns
    {
        public List<Kit_PlayerSpawn> spawns = new List<Kit_PlayerSpawn>();
    }

    [DefaultExecutionOrder(-1)]
    /// <summary>
    /// The Main script of the ingame logic (This is the heart of the game)
    /// </summary>
    /// //It is a PunBehaviour so we can have all the callbacks that we need
    public class Kit_IngameMain : NetworkBehaviour
    {
        public Kit_InputSystem inputSystem
        {
            get
            {
                return Kit_InputSystem.instance;
            }
        }

        public static Kit_IngameMain instance;

        /// <summary>
        /// The root of all UI
        /// </summary>
        public GameObject ui_root;

        /// <summary>
        /// Main canvas
        /// </summary>
        public Canvas canvas;

        //The current state of the pause menu
        public PauseMenuState pauseMenuState = PauseMenuState.teamSelection;

        //This hols all game information
        #region Game Information
        [Header("Internal Game Information")]
        [Tooltip("This object contains all game information such as Maps, Game Modes and Weapons")]
        public Kit_GameInformation gameInformation;

        public GameObject playerPrefab; //The player prefab that we should use
        #endregion

        #region Menu Managing
        [Header("Menu Manager")]
        /// <summary>
        /// Menu screens
        /// </summary>
        public MenuScreen[] menuScreens;
        /// <summary>
        /// ID for fading INTO the game
        /// </summary>
        public int ingameFadeId = 2;
        /// <summary>
        /// Do we have a screen to fade out?
        /// </summary>
        private bool wasFirstScreenFadedIn;
        /// <summary>
        /// The menu screen that is currently visible (in order to fade it out)
        /// </summary>
        public int currentScreen = -1;
        /// <summary>
        /// True if we are currently switching a screen
        /// </summary>
        private bool isSwitchingScreens;
        /// <summary>
        /// Where we are currently switching screens to
        /// </summary>
        private Coroutine currentlySwitchingScreensTo;
        #endregion

        [Header("Map Settings")]
        /// <summary>
        /// If you are below this position on your y axis, you die
        /// </summary>
        public float mapDeathThreshold = -50f;

        //This contains all the game mode informations
        #region Game Mode Variables
        [Header("Game Mode Variables")]
        [SyncVar]
        /// <summary>
        /// The game mode timer
        /// </summary>
        public float timer = 600f;
        [SyncVar]
        /// <summary>
        /// A universal stage for game modes, since every game mode requires one like this
        /// </summary>
        public int gameModeStage;
        /// <summary>
        /// Used for the game mode stage changed callback (Called for everyone)
        /// </summary>
        private int lastGameModeStage;
        [SyncVar]


        /// <summary>
        /// The game mode type (!) we are currently playing
        /// </summary>
        public int currentGameModeType;
        [SyncVar]
        /// <summary>
        /// The game mode we are currently playing
        /// </summary>
        public int currentGameMode;
        /// <summary>
        /// Here you can store runtime data for the game mode. Just make sure to sync it to everybody
        /// </summary>
        public Kit_GameModeNetworkDataBase currentGameModeRuntimeData;

        [HideInInspector]
        public List<InternalSpawns> internalSpawns = new List<InternalSpawns>();
        #endregion

        #region Team Selection
        /// <summary>
        /// Team selection module
        /// </summary>
        [Header("Team Selection")]
        public UI.Kit_IngameMenuTeamSelection ts;
        /// <summary>
        /// The text which displays that we cannot join that team
        /// </summary>
        public TextMeshProUGUI errorText;
        /// <summary>
        /// How long is the warning going to be displayed?
        /// </summary>
        public float errorTime = 3f;
        /// <summary>
        /// Current alpha of the cant join message
        /// </summary>
        private float errorAlpha = 0f;
        #endregion

        //This contains everything needed for the Pause Menu
        #region Pause Menu
        /// <summary>
        /// Pause Menu module
        /// </summary>
        [Header("Pause Menu, Use 'B' in the editor to open / close it")]
        public Kit_IngameMenuPauseMenu pauseMenu;
        #endregion

        /// <summary>
        /// New, modular options screen!!!
        /// </summary>
        [Header("Options")]
        public Kit_MenuOptions options;

        //This contains the local camera control
        #region Camera Control
        [Header("Camera Control")]
        public Camera mainCamera; //The main camera to use for the whole game
#if INTEGRATION_FPV2
        public Camera weaponCamera; //This is a second camera used by FPV2 for the matrix.
#elif INTEGRATION_FPV3
        public Camera weaponCamera; //This is a second camera used by FPV2 for the matrix.
#endif
        /// <summary>
        /// Camera shake!
        /// </summary>
        public Kit_CameraShake cameraShake;
        //We recycle the same camera for the whole game, for easy setup of image effects
        //Be careful when changing near and far clip
        public Transform activeCameraTransform
        {
            get
            {
                if (mainCamera)
                {
                    return mainCamera.transform.parent;
                }
                else
                {
                    return null;
                }
            }
            set
            {
                if (value)
                {
                    Debug.Log("[Camera] Changing camera parent to " + value.name, value);
                }
                else
                {
                    Debug.Log("[Camera] Changing camera parent to null");
                }

                if (mainCamera)
                {
                    //We use one camera for the complete game
                    //Set parent
                    mainCamera.transform.parent = value;
                    //If the parent is not null, reset position and rotation
                    if (value)
                    {
                        mainCamera.transform.localPosition = Vector3.zero;
                        mainCamera.transform.localRotation = Quaternion.identity;
                    }
                }
            }
        }
        public Transform spawnCameraPosition; //The spawn position for the camera
        #endregion

        [Header("Modules")]
        [Header("HUD")]
        //This contains the HUD reference
        #region HUD
        /// <summary>
        /// Use this to access the Player HUD
        /// </summary>
        public Kit_PlayerHUDBase hud;
        #endregion

        //This contains the Killfeed reference
        #region Killfeed
        [Header("Killfeed")]
        public Kit_KillFeedBase killFeed;
        #endregion

        #region Chat
        [Header("Chat")]
        public Kit_ChatBase chat;
        #endregion

        #region Impact Processor
        [Header("Impact Processor")]
        public Kit_ImpactParticleProcessor impactProcessor;
        #endregion

        #region Scoreboard
        [Header("Scoreboard")]
        public Scoreboard.Kit_ScoreboardBase scoreboard;
        #endregion

        #region PointsUI
        [Header("Points UI")]
        public Kit_PointsUIBase pointsUI;
        #endregion

        #region Victory Screen
        [Header("Victory Screen")]
        public Kit_VictoryScreenUI victoryScreenUI;
        #endregion

        #region MapVoting
        [Header("Map Voting")]
        public Kit_MapVotingUIBase mapVotingUI;
        #endregion

        #region Ping Limit
        [Header("Ping Limit")]
        public Kit_PingLimitBase pingLimitSystem;
        public Kit_PingLimitUIBase pingLimitUI;
        #endregion

        #region AFK Limit
        [Header("AFK Limit")]
        public Kit_AfkLimitBase afkLimitSystem;
        public Kit_AfkLimitUIBase afkLimitUI;
        #endregion

        #region Loadout
        [Header("Loadout")]
        public Kit_LoadoutBase loadoutMenu;
        #endregion

        #region Voting
        [Header("Voting")]
        public Kit_VotingUIBase votingMenu;
        [HideInInspector]
        public Kit_VotingBase currentVoting;
        #endregion

        #region Voice Chat
        [Header("Voice Chat")]
        public Kit_VoiceChatBase voiceChat;
        #endregion

        #region Leveling UI
        /// <summary>
        /// If this is assigned, it will display level ups
        /// </summary>
        [Header("Leveling UI")]
        public Kit_LevelingUIBase levelingUi;
        #endregion

        #region Minimap
        [Header("Minimap")]
        public Kit_MinimapBase minimap;
        #endregion

        #region Auto Spawn System
        /// <summary>
        /// Spawn system to use
        /// </summary>
        [Header("Auto Spawn System")]
        public Kit_AutoSpawnSystemBase autoSpawnSystem;
        #endregion

        #region Object Pooling
        [Header("Object Pooling")]
        /// <summary>
        /// Object Pooling interface
        /// </summary>
        public Optimization.Kit_ObjectPoolingBase objectPooling;
        #endregion

        #region Assists
        /// <summary>
        /// Assist manager module
        /// </summary>
        [Header("Assists")]
        public Kit_AssistManagerBase assistManager;
        /// <summary>
        /// Runtime data for the assist manager
        /// </summary>
        public object assistManagerData;
        #endregion

        #region Spectating
        [Header("Spectator")]
        /// <summary>
        /// Spectator manager
        /// </summary>
        public Spectating.Kit_SpectatorManagerBase spectatorManager;
        /// <summary>
        /// Runtime data for the spectator manager
        /// </summary>
        public object spectatorManagerRuntimeData;
        #endregion

        /// <summary>
        /// A hud that is only visible when the player is alive can be instantiated here
        /// </summary>
        [Header("Plugins")]
        public RectTransform pluginPlayerActiveHudGo;
        /// <summary>
        /// A hud that is always active can be instantiated here
        /// </summary>
        public RectTransform pluginAlwaysActiveHudGo;
        /// <summary>
        /// Where external modules can be instantiated
        /// </summary>
        public Transform pluginModuleGo;

        [Header("Instantiateables")]
        /// <summary>
        /// This contains the prefab for the victory screen. Once its setup it will sync to all other players.
        /// </summary>
        public GameObject victoryScreen;
        [HideInInspector]
        /// <summary>
        /// A reference to the victory screen so it can be destroyed when it's not needed anymore.
        /// </summary>
        public Kit_VictoryScreen currentVictoryScreen;
        /// <summary>
        /// This contains the prefab for the map voting. Once its setup it will sync to all other players
        /// </summary>
        public GameObject mapVoting;
        [HideInInspector]
        /// <summary>
        /// A reference to the map voting. Can be null
        /// </summary>
        public Kit_MapVotingBehaviour currentMapVoting;

        /// <summary>
        /// Prefab for the bot manager
        /// </summary>
        [Header("Bots")]
        public GameObject botManagerPrefab;
        [HideInInspector]
        /// <summary>
        /// If Bots are enabled, this is the bot manager
        /// </summary>
        public Kit_BotManager currentBotManager;
        [HideInInspector]
        /// <summary>
        /// All bot nav points
        /// </summary>
        public Transform[] botNavPoints;

        /// <summary>
        /// This is the input that shall be used if we have a touchscreen
        /// </summary>
        [Header("Touchscreen Input")]
        public GameObject touchScreenPrefab;
        [HideInInspector]
        /// <summary>
        /// If touch screen input is enabled, this is assigned.
        /// </summary>
        public Kit_TouchscreenBase touchScreenCurrent;

        // This is the new fix section added to prevent double kill counting
        private readonly HashSet<string> processedKillEvents = new HashSet<string>();
        private float lastKillEventsCleanupTime = 0f;
        private const float killEventsCleanupInterval = 10f;

        void Update()
        {
            // Existing Update code above remains intact. Insert this cleanup code:

            if (Time.time - lastKillEventsCleanupTime > killEventsCleanupInterval)
            {
                processedKillEvents.Clear();
                lastKillEventsCleanupTime = Time.time;
                Debug.Log("[Kit_IngameMain] Cleared processed kill events cache");
            }
        }

        #region Game Logic calls
        public void ServerDeathInfo(bool botShot, uint killer, bool botKilled, uint killed, int gunId, int thirdPersonPlayerModelId, int ragdollId)
        {
            // Generate unique key to avoid double counting the same kill
            string killKey = $"{killer}_{killed}_{gunId}_{Time.frameCount}";

            if (processedKillEvents.Contains(killKey))
            {
                Debug.LogWarning("[ServerDeathInfo] Duplicate kill detected: " + killKey + ", ignoring");
                return;
            }
            processedKillEvents.Add(killKey);

            // Existing functionality:
            if (botKilled)
            {
                if (isServer && currentBotManager)
                {
                    Kit_Bot killedBot = currentBotManager.GetBotWithID(killed);

                    killedBot.deaths++;

                    for (int i = 0; i < gameInformation.plugins.Length; i++)
                    {
                        gameInformation.plugins[i].BotWasKilled(killedBot);
                    }

                    Kit_IngameMain.instance.currentBotManager.ModifyBotData(killedBot);
                }
            }
            else
            {
                Kit_Player player = Kit_NetworkPlayerManager.instance.GetPlayerById(killed);
                player.deaths++;
                Kit_NetworkPlayerManager.instance.ModifyPlayerData(player);
            }

            if (botShot)
            {
                if (!botKilled || botKilled && killer != killed)
                {
                    if (isServer && currentBotManager)
                    {
                        Kit_Bot killerBot = currentBotManager.GetBotWithID(killer);
                        Debug.Log(
                        $"[ServerDeathInfo] Incrementing Kills for Bot ID={killerBot.id} - Current kills: {killerBot.kills}\n" +
                        new System.Diagnostics.StackTrace(true).ToString()
                        );
                        killerBot.kills++;

                        currentPvPGameModeBehaviour.MasterClientBotScoredKill(killerBot);

                        for (int i = 0; i < gameInformation.plugins.Length; i++)
                        {
                            gameInformation.plugins[i].BotScoredKill(killerBot, botKilled, killed, gunId, thirdPersonPlayerModelId, ragdollId);
                        }

                        Kit_IngameMain.instance.currentBotManager.ModifyBotData(killerBot);
                    }
                }
            }
            else
            {
                Kit_Player player = Kit_NetworkPlayerManager.instance.GetPlayerById(killer);

                player.kills++;

                Kit_NetworkPlayerManager.instance.ModifyPlayerData(player);

            }

            if (isServer)
            {
                if (currentPvPGameModeBehaviour)
                {
                    currentPvPGameModeBehaviour.PlayerDied(botShot, killer, botKilled, killed);
                }

                if (currentPvEGameModeBehaviour)
                {
                    currentPvEGameModeBehaviour.PlayerDied(botShot, killer, botKilled, killed);
                }
            }
        }

        public void ServerDeathInfo(bool botShot, uint killer, bool botKilled, uint killed, string cause, int thirdPersonPlayerModelId, int ragdollId)
        {
            // Generate unique key to avoid double counting the same kill
            string killKey = $"{killer}_{killed}_{cause}_{Time.frameCount}";

            if (processedKillEvents.Contains(killKey))
            {
                Debug.LogWarning("[ServerDeathInfo] Duplicate kill detected: " + killKey + ", ignoring");
                return;
            }
            processedKillEvents.Add(killKey);

            // Existing functionality:
            if (botKilled)
            {
                if (currentBotManager)
                {
                    Kit_Bot killedBot = currentBotManager.GetBotWithID(killed);

                    killedBot.deaths++;

                    for (int i = 0; i < gameInformation.plugins.Length; i++)
                    {
                        gameInformation.plugins[i].BotWasKilled(killedBot);
                    }

                    Kit_IngameMain.instance.currentBotManager.ModifyBotData(killedBot);
                }
            }
            else
            {
                Kit_Player player = Kit_NetworkPlayerManager.instance.GetPlayerById(killed);

                player.deaths++;

                Kit_NetworkPlayerManager.instance.ModifyPlayerData(player);
            }

            if (botShot)
            {
                if (!botKilled || botKilled && killer != killed)
                {
                    if (isServer && currentBotManager)
                    {
                        Kit_Bot killerBot = currentBotManager.GetBotWithID(killer);
                        killerBot.kills++;

                        currentPvPGameModeBehaviour.MasterClientBotScoredKill(killerBot);

                        for (int i = 0; i < gameInformation.plugins.Length; i++)
                        {
                            gameInformation.plugins[i].BotScoredKill(killerBot, botKilled, killed, cause, thirdPersonPlayerModelId, ragdollId);
                        }

                        Kit_IngameMain.instance.currentBotManager.ModifyBotData(killerBot);
                    }
                }
            }
            else
            {
                Kit_Player player = Kit_NetworkPlayerManager.instance.GetPlayerById(killer);
                player.kills++;
                Kit_NetworkPlayerManager.instance.ModifyPlayerData(player);
            }

            if (isServer)
            {
                if (currentPvPGameModeBehaviour)
                {
                    currentPvPGameModeBehaviour.PlayerDied(botShot, killer, botKilled, killed);
                }

                if (currentPvEGameModeBehaviour)
                {
                    currentPvEGameModeBehaviour.PlayerDied(botShot, killer, botKilled, killed);
                }
            }
        }
        #endregion

        //... the rest of your methods and code remain as currently implemented
    }
}        

        /// <summary>
        /// Tries to spawn a player
        /// <para>See also: <seealso cref="Kit_GameModeBase.CanSpawn(Kit_IngameMain, Photon.Realtime.Player)"/></para>
        /// </summary>
        public void Spawn(bool sendAnyway = false)
        {
            if (!myPlayer || sendAnyway)
            {
                CmdRequestSpawn(loadoutMenu.GetCurrentLoadout());
            }
        }

        [Command(requiresAuthority = false)]
        public void CmdRequestSpawn(Loadout requestedLoadout, NetworkConnectionToClient sender = null)
        {
            Kit_Player player = Kit_NetworkPlayerManager.instance.GetPlayerByConnection(sender);
            Debug.Log(player);
            Kit_PlayerBehaviour pb = GetPlayerOf(player);

            if (!pb)
            {
                switch (currentGameModeType)
                {
                    case 0:
                        //We can only spawn if we do not have a player currently
                        if (!pb)
                        {
                            //Check if we can currently spawn
                            if (!currentPvEGameModeBehaviour.UsesCustomSpawn())
                            {
                                if (gameInformation.allSingleplayerGameModes[currentGameMode].CanSpawn(player))
                                {
                                    //Get a spawn
                                    Transform spawnLocation = gameInformation.allSingleplayerGameModes[currentGameMode].GetSpawn(player);
                                    Loadout loadout = gameInformation.allSingleplayerGameModes[currentGameMode].GetSpawnLoadout();
                                    if (spawnLocation)
                                    {
                                        GameObject go = Instantiate(playerPrefab, spawnLocation.position, spawnLocation.rotation);
                                        pb = go.GetComponent<Kit_PlayerBehaviour>();
                                        pb.myTeam = player.team;
                                        pb.isBot = false;
                                        pb.id = player.id;
                                        //If you're wondering where the player model is being setup, its fetched from the game mode at creation time
                                        pb.weaponManager.SetupSpawnData(pb, loadout, sender);
                                        NetworkServer.ReplacePlayerForConnection(sender, go, ReplacePlayerOptions.KeepActive);
                                    }
                                }
                            }
                            else
                            {
                                GameObject playerGameObject = currentPvEGameModeBehaviour.DoCustomSpawn();
                                if (playerGameObject)
                                {
                                    pb = playerGameObject.GetComponent<Kit_PlayerBehaviour>();
                                    pb.myTeam = player.team;
                                    pb.isBot = false;
                                    pb.id = player.id;
                                    NetworkServer.ReplacePlayerForConnection(sender, playerGameObject, ReplacePlayerOptions.KeepActive);
                                }
                            }
                        }
                        break;
                    case 1:
                        //We can only spawn if we do not have a player currently
                        if (!pb)
                        {
                            //Check if we can currently spawn
                            if (!currentPvEGameModeBehaviour.UsesCustomSpawn())
                            {
                                if (gameInformation.allCoopGameModes[currentGameMode].CanSpawn(player))
                                {
                                    //Get a spawn
                                    Transform spawnLocation = gameInformation.allCoopGameModes[currentGameMode].GetSpawn(player);
                                    Loadout loadout = gameInformation.allCoopGameModes[currentGameMode].GetSpawnLoadout();
                                    if (spawnLocation)
                                    {
                                        GameObject go = Instantiate(playerPrefab, spawnLocation.position, spawnLocation.rotation);
                                        pb = go.GetComponent<Kit_PlayerBehaviour>();
                                        pb.myTeam = player.team;
                                        pb.isBot = false;
                                        pb.id = player.id;
                                        //If you're wondering where the player model is being setup, its fetched from the game mode at creation time
                                        pb.weaponManager.SetupSpawnData(pb, loadout, sender);
                                        NetworkServer.ReplacePlayerForConnection(sender, go, ReplacePlayerOptions.KeepActive);
                                    }
                                }
                            }
                            else
                            {
                                GameObject playerGameObject = currentPvEGameModeBehaviour.DoCustomSpawn();
                                if (playerGameObject)
                                {
                                    pb = playerGameObject.GetComponent<Kit_PlayerBehaviour>();
                                    pb.myTeam = player.team;
                                    pb.isBot = false;
                                    pb.id = player.id;
                                    NetworkServer.ReplacePlayerForConnection(sender, playerGameObject, ReplacePlayerOptions.KeepActive);
                                }
                            }
                        }

                        break;

                    case 2:
                        //We can only spawn if we do not have a player currently and picked a team
                        if (!pb && player.team >= 0)
                        {
                            //Check if we can currently spawn
                            if (!currentPvPGameModeBehaviour.UsesCustomSpawn())
                            {
                                if (gameInformation.allPvpGameModes[currentGameMode].CanSpawn(player))
                                {
                                    //Get a spawn
                                    Transform spawnLocation = gameInformation.allPvpGameModes[currentGameMode].GetSpawn(player);
                                    if (spawnLocation)
                                    {
                                        //Ideally, we should verify here that the loadout is valid first
                                        //IMPROVE:
                                        Loadout loadout = requestedLoadout;
                                        GameObject go = Instantiate(playerPrefab, spawnLocation.position, spawnLocation.rotation);
                                        pb = go.GetComponent<Kit_PlayerBehaviour>();
                                        pb.myTeam = player.team;
                                        pb.isBot = false;
                                        pb.id = player.id;
                                        pb.thirdPersonPlayerModelID = loadout.teamLoadout[player.team].playerModelID;
                                        pb.thirdPersonPlayerModelCustomizations.AddRange(loadout.teamLoadout[player.team].playerModelCustomizations);
                                        pb.weaponManager.SetupSpawnData(pb, loadout, sender);
                                        NetworkServer.ReplacePlayerForConnection(sender, go, ReplacePlayerOptions.KeepActive);
                                    }
                                }
                            }
                            else
                            {
                                //Get player from game mode
                                GameObject playerGameObject = currentPvPGameModeBehaviour.DoCustomSpawn(player, requestedLoadout);
                                if (playerGameObject)
                                {
                                    //End the spawn sequence
                                    pb = playerGameObject.GetComponent<Kit_PlayerBehaviour>();
                                    pb.myTeam = player.team;
                                    pb.isBot = false;
                                    pb.id = player.id;
                                    NetworkServer.ReplacePlayerForConnection(sender, playerGameObject, ReplacePlayerOptions.KeepActive);
                                }
                            }
                        }

                        break;
                }
            }
        }

        /// <summary>
        /// Get active player behaviour of the given player
        /// </summary>
        /// <param name="player"></param>
        /// <returns></returns>
        public Kit_PlayerBehaviour GetPlayerOf(Kit_Player player)
        {
            return allActivePlayers.Where(x => x.isBot == player.isBot && x.id == player.id).FirstOrDefault();
        }

        /// <summary>
        /// Ask the server if we can join this team
        /// </summary>
        /// <param name="teamID"></param>
        /// <param name="sender"></param>
        [Command(requiresAuthority = false)]
        public void CmdRequestJoinTeam(sbyte teamID, NetworkConnectionToClient sender = null)
        {
            //We can just do this if we are in a room
            if (NetworkServer.active)
            {
                //Update player
                Kit_Player player = Kit_NetworkPlayerManager.instance.GetPlayerByConnection(sender);
                //We only allow to change teams if we have not spawned
                if (!GetPlayerOf(player))
                {
                    //Clamp the team id to the available teams
                    teamID = (sbyte)Mathf.Clamp(teamID, 0, Mathf.Clamp(gameInformation.allPvpTeams.Length, 0, currentPvPGameModeBehaviour.maximumAmountOfTeams) - 1);
                    //Check if we can join this team OR if we are already in that team
                    if (gameInformation.allPvpGameModes[currentGameMode].CanJoinTeam(sender, teamID))
                    {
                        //Join the team
                        TeamJoinGranted(sender, teamID);
                        player.team = teamID;
                        Kit_NetworkPlayerManager.instance.ModifyPlayerData(player);

                        //Rebalance teams with bot
                        if (currentPvPGameModeBehaviour && currentBotManager)
                        {
                            currentPvPGameModeBehaviour.botManagerToUse.PlayerJoinedTeam(currentBotManager);
                        }
                    }
                    else
                    {
                        TargetTeamJoinNotGranted(sender);
                    }
                }
            }
        }

        [TargetRpc]
        public void TargetTeamJoinNotGranted(NetworkConnection target)
        {
            //Display message
            DisplayMessage("Could not join team");
        }

        [TargetRpc]
        public void TeamJoinGranted(NetworkConnection target, sbyte teamID)
        {
            //Don't display no error.
            errorAlpha = 0f;

            //Assign it to ourselves too
            assignedTeamID = teamID;

            //Loadout callback
            if (loadoutMenu)
            {
                loadoutMenu.TeamChanged(assignedTeamID);
            }
            //Voice Chat Callback
            try
            {
                if (voiceChat)
                {
                    voiceChat.JoinedTeam(teamID);
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Voice Chat Error: " + e);
            }
            //Minimap callback
            if (minimap)
            {
                minimap.LocalPlayerSwitchedTeams();
            }

            //Should we attempt to spawn?
            if (ts.afterSelection == AfterTeamSelection.AttemptSpawn)
            {
                pluginOnForceClose.Invoke();
                pauseMenuState = PauseMenuState.main;
                //Activate scoreboard
                scoreboard.Enable();
                //Try to spawn
                Spawn();
                if (!myPlayer)
                {
                    SwitchMenu(pauseMenu.pauseMenuId, true);
                }
            }
            else if (ts.afterSelection == AfterTeamSelection.Loadout)
            {
                pauseMenuState = PauseMenuState.main;
                isPauseMenuOpen = true;
                //Activate scoreboard
                scoreboard.Enable();

                //Then go to loadout
                OpenLoadoutMenu();
            }
            else
            {
                SwitchMenu(pauseMenu.pauseMenuId, true);
                pauseMenuState = PauseMenuState.main;
                isPauseMenuOpen = true;
                //Activate scoreboard
                scoreboard.Enable();
            }

            //Call Plugin
            for (int i = 0; i < gameInformation.plugins.Length; i++)
            {
                gameInformation.plugins[i].LocalPlayerChangedTeam(teamID);
            }
        }

        [TargetRpc]
        public void TargetDisplayPingWarning(NetworkConnection target, ushort ping, ushort warning)
        {
            //Display warning
            if (pingLimitUI)
            {
                pingLimitUI.DisplayWarning(ping, warning);
            }
        }

        [ClientRpc]
        public void RpcAssistEvent(byte eventCode, int content)
        {
            //Relay
            if (assistManager)
            {
                assistManager.OnGenericEvent(eventCode, content);
            }
        }

        [ClientRpc]
        public void RpcGenericEvent(byte eventCode, object content)
        {
            if (currentPvPGameModeBehaviour)
            {
                //Relay
                currentPvPGameModeBehaviour.OnGenericEvent(eventCode, content);
            }

            if (currentPvEGameModeBehaviour)
            {
                //Relay
                currentPvEGameModeBehaviour.OnGenericEvent(eventCode, content);
            }
            for (int i = 0; i < gameInformation.plugins.Length; i++)
            {
                gameInformation.plugins[i].OnGenericEvent(eventCode, content);
            }
        }

        [ClientRpc]
        public void RpcServerRespawnRequest()
        {
            Spawn(true);
        }

        /// <summary>
        /// Ends the game with the supplied Photon.Realtime.Player as winner
        /// </summary>
        /// <param name="winner">The Winner</param>
        public void EndGame(Kit_Player winner)
        {
            if (isServer)
            {
                GameObject go = Instantiate(victoryScreen, Vector3.zero, Quaternion.identity);
                Kit_VictoryScreen data = go.GetComponent<Kit_VictoryScreen>();
                data.winnerType = 0;
                data.winnerBot = winner.isBot;
                data.winnerId = winner.id;
                NetworkServer.Spawn(go);

                //Call Event System
                Kit_Events.onEndGamePlayerWin.Invoke(winner);
            }
        }

        /// <summary>
        /// Ends the game with the supplied team (or 2 for draw) as winner
        /// </summary>
        /// <param name="winner">The winning team. 2 means draw.</param>
        public void EndGame(uint winner)
        {
            if (isServer)
            {
                GameObject go = Instantiate(victoryScreen, Vector3.zero, Quaternion.identity);
                Kit_VictoryScreen data = go.GetComponent<Kit_VictoryScreen>();
                data.winnerType = 1;
                data.winnerId = winner;
                NetworkServer.Spawn(go);

                //Call Event System
                Kit_Events.onEndGameTeamWin.Invoke(winner);
            }
        }

        /// <summary>
        /// Ends the game and displays scores for two team
        /// </summary>
        /// <param name="winner"></param>
        /// <param name="scoreTeamOne"></param>
        /// <param name="scoreTeamTwo"></param>
        public void EndGame(uint winner, int[] scores)
        {
            if (isServer)
            {
                GameObject go = Instantiate(victoryScreen, Vector3.zero, Quaternion.identity);
                Kit_VictoryScreen data = go.GetComponent<Kit_VictoryScreen>();
                data.winnerType = 1;
                data.winnerId = winner;

                for (int i = 0; i < scores.Length; i++)
                {
                    data.winnerScores.Add(scores[i]);
                }

                NetworkServer.Spawn(go);

                //Call Event System
                Kit_Events.onEndGameTeamWinWithScore.Invoke(winner, scores);
            }
        }

        /// <summary>
        /// Opens the voting menu if we are the master client
        /// </summary>
        public void OpenVotingMenu()
        {
            if (isServer)
            {
                List<MapGameModeCombo> usedCombos = new List<MapGameModeCombo>();

                //Get combos
                while (usedCombos.Count < mapVotingUI.amountOfAvailableVotes)
                {
                    //Get a new combo
                    usedCombos.Add(Kit_MapVotingBehaviour.GetMapGameModeCombo(gameInformation, usedCombos));
                }

                GameObject go = Instantiate(mapVoting, Vector3.zero, Quaternion.identity);
                Kit_MapVotingBehaviour data = go.GetComponent<Kit_MapVotingBehaviour>();
                data.combos.AddRange(usedCombos);
                //Attach to network
                NetworkServer.Spawn(go);
            }
        }

        /// <summary>
        /// Destroys all Players if we are the master client
        /// </summary>
        public void DeleteAllPlayers()
        {
            if (isServer)
            {
                //Reverse iterate through player list and destroy all of them
                for (int i = allActivePlayers.Count - 1; i >= 0; i--)
                {
                    NetworkServer.Destroy(allActivePlayers[i].gameObject);
                }
            }
        }

        /// <summary>
        /// Called when the victory screen opened
        /// </summary>
        public void VictoryScreenOpened()
        {
            //Reset alpha
            errorAlpha = 0f;
            //Force close loadout menu
            if (loadoutMenu)
            {
                loadoutMenu.ForceClose();
            }
        }

        /// <summary>
        /// Called when the map voting screen opened
        /// </summary>
        public void MapVotingOpened()
        {
            errorAlpha = 0f;
            //Force close loadout menu
            if (loadoutMenu)
            {
                loadoutMenu.ForceClose();
            }
        }

        /// <summary>
        /// Switches the map to
        /// </summary>
        /// <param name="to"></param>
        public void SwitchMap(int to)
        {
            if (isServer && currentGameModeType == 2)
            {
                if (Kit_NetworkGameInformation.instance != null)
                {
                    Kit_NetworkGameInformation.instance.map = to;
                }

                string sceneToLoad = null;

                if (Kit_GameSettings.currentNetworkingMode == KitNetworkingMode.Traditional)
                {
                    if (currentPvPGameModeBehaviour == null)
                    {
                        Debug.LogError("[Kit_IngameMain] currentPvPGameModeBehaviour is null!");
                        return;
                    }

                    if (to < 0 || to >= currentPvPGameModeBehaviour.traditionalMaps.Length)
                    {
                        Debug.LogError($"[Kit_IngameMain] Map index 'to' ({to}) is out of bounds for traditionalMaps array!");
                        return;
                    }

                    sceneToLoad = currentPvPGameModeBehaviour.traditionalMaps[to].sceneName;
                }
                else if (Kit_GameSettings.currentNetworkingMode == KitNetworkingMode.Lobby)
                {
                    if (currentPvPGameModeBehaviour == null)
                    {
                        Debug.LogError("[Kit_IngameMain] currentPvPGameModeBehaviour is null!");
                        return;
                    }

                    if (to < 0 || to >= currentPvPGameModeBehaviour.lobbyMaps.Length)
                    {
                        Debug.LogError($"[Kit_IngameMain] Map index 'to' ({to}) is out of bounds for lobbyMaps array!");
                        return;
                    }

                    sceneToLoad = currentPvPGameModeBehaviour.lobbyMaps[to].sceneName;
                }
                else
                {
                    Debug.LogError("[Kit_IngameMain] Unknown Networking Mode: " + Kit_GameSettings.currentNetworkingMode);
                    return;
                }

                if (string.IsNullOrEmpty(sceneToLoad))
                {
                    Debug.LogError("[Kit_IngameMain] sceneName to load is null or empty!");
                    return;
                }

                // Add debug log to see which scene is about to be loaded
                Debug.Log("[Kit_IngameMain] Switching map to index " + to + " with scene: " + sceneToLoad);

                Kit_SceneSyncer.instance.LoadScene(sceneToLoad);
            }
        }

        /// <summary>
        /// Switches the game mode to
        /// </summary>
        /// <param name="to"></param>
        public void SwitchGameMode(int to)
        {
            if (isServer && currentGameModeType == 2)
            {
                //Update settings
                if (Kit_NetworkGameInformation.instance)
                {
                    Kit_NetworkGameInformation.instance.gameMode = to;
                }

                if (Kit_GameSettings.currentNetworkingMode == KitNetworkingMode.Traditional)
                {
                    //Load the map
                    Kit_SceneSyncer.instance.LoadScene(currentPvPGameModeBehaviour.traditionalMaps[to].sceneName);
                }
                else if (Kit_GameSettings.currentNetworkingMode == KitNetworkingMode.Lobby)
                {
                    //Load the map
                    Kit_SceneSyncer.instance.LoadScene(currentPvPGameModeBehaviour.lobbyMaps[to].sceneName);
                }
            }
        }
        #endregion

        public void DisplayMessage(string msg)
        {
            //Display message
            errorText.text = msg;
            //Set alpha
            errorAlpha = errorTime;
        }

        #region ButtonCalls
        /// <summary>
        /// Attempt to join the team with teamID
        /// </summary>
        /// <param name="teamID"></param>
        public void JoinTeam(sbyte teamID)
        {
            //Relay to server
            CmdRequestJoinTeam(teamID);
        }

        public void NoTeam()
        {
            //Ask server to join no team
            CmdRequestJoinTeam(-1);
        }

        public void ChangeTeam()
        {
            //We only allow to change teams if we have not spawned
            if (!myPlayer)
            {
                SwitchMenu(ts.teamSelectionId);
                pauseMenuState = PauseMenuState.teamSelection;
            }
            else
            {
                //Commit suicide
                myPlayer.CmdSuicide();
            }
        }

        /// <summary>
        /// Disconnect from the current room
        /// </summary>
        public void Disconnect()
        {
            isShuttingDown = true;

            //Save Leveling
            if (gameInformation.leveling)
            {
                gameInformation.leveling.Save();
            }
            if (gameInformation.statistics)
            {
                gameInformation.statistics.Save();
            }

            // stop host if host mode
            if (NetworkServer.active && NetworkClient.isConnected)
            {
                Kit_NetworkManager.instance.StopHost();

            }
            // stop client if client-only
            else if (NetworkClient.isConnected)
            {
                Kit_NetworkManager.instance.StopClient();
            }
            // stop server if server-only
            else if (NetworkServer.active)
            {
                Kit_NetworkManager.instance.StopServer();
            }
        }

        /// <summary>
        /// Press the resume button. Either locks cursor or tries to spawn
        /// </summary>
        public void ResumeButton()
        {
            //Check if we have spawned
            if (myPlayer)
            {
                //We have, just lock cursor
                //Close pause menu
                isPauseMenuOpen = false;
                SwitchMenu(ingameFadeId, true);
                pluginOnForceClose.Invoke();
                //Lock Cursor
                MarsScreen.lockCursor = true;
            }
            else if (currentPvPGameModeBehaviour && currentPvPGameModeBehaviour.CanSpawn(Kit_NetworkPlayerManager.instance.GetLocalPlayer()))
            {
                //We haven't, try to spawn
                Spawn();
            }
            else if (currentPvEGameModeBehaviour && currentPvEGameModeBehaviour.CanSpawn(Kit_NetworkPlayerManager.instance.GetLocalPlayer()))
            {
                //We haven't, try to spawn
                Spawn();
            }
            else if (spectatorManager && spectatorManager.IsCurrentlySpectating())
            {
                //Close pause menu
                isPauseMenuOpen = false;
                SwitchMenu(ingameFadeId, true);
                pluginOnForceClose.Invoke();
                //Lock Cursor
                MarsScreen.lockCursor = false;
            }
            else
            {
                //Close pause menu
                isPauseMenuOpen = false;
                SwitchMenu(ingameFadeId, true);
                pluginOnForceClose.Invoke();
                //Lock Cursor
                MarsScreen.lockCursor = false;
            }
        }

        /// <summary>
        /// Opens the loadout menu
        /// </summary>
        public void OpenLoadoutMenu()
        {
            //Check if something is blocking that
            if (!currentVictoryScreen && !currentMapVoting)
            {
                if (loadoutMenu)
                {
                    loadoutMenu.Open();
                }
            }
        }

        /// <summary>
        /// Opens the vote menu if no vote is in progress
        /// </summary>
        public void StartVote()
        {
            if (votingMenu)
            {
                votingMenu.OpenVotingMenu();
            }
        }

        public void OptionsButton()
        {
            if (options)
            {
                SwitchMenu(options.optionsScreenId);
            }
        }
        #endregion

        #region Plugin Calls
        /// <summary>
        /// Called when the menu is forcefully closed
        /// </summary>
        public UnityEvent pluginOnForceClose = new UnityEvent();

        public Button InjectButtonIntoPauseMenu(string txt)
        {
            GameObject go = Instantiate(pauseMenu.pluginButtonPrefab, pauseMenu.pluginButtonGo, false);
            go.transform.SetSiblingIndex(3);
            go.GetComponentInChildren<TextMeshProUGUI>().text = txt;
            return go.GetComponent<Button>();
        }
        #endregion

        #region Other Calls
        /// <summary>
        /// Opens or closes the pause menu
        /// </summary>
        /// <param name="open"></param>
        public void SetPauseMenuState(bool open, bool canLockCursor = true)
        {
            if (isPauseMenuOpen != open)
            {
                isPauseMenuOpen = open;
                //Set state
                if (isPauseMenuOpen)
                {
                    SwitchMenu(pauseMenu.pauseMenuId, true);
                    //Unlock cursor
                    MarsScreen.lockCursor = false;
                    //Chat callback
                    chat.PauseMenuOpened();
                    //Auto spawn system callack
                    if (autoSpawnSystem && currentPvPGameModeBehaviour)
                    {
                        autoSpawnSystem.Interruption();
                    }
                }
                else
                {
                    SwitchMenu(ingameFadeId, true);
                    pluginOnForceClose.Invoke();
                    if (canLockCursor)
                    {
                        //Lock cursor
                        MarsScreen.lockCursor = true;
                        //Chat callback
                        chat.PauseMenuClosed();
                    }
                }
            }
        }

        /// <summary>
        /// When the server tells us to reset ourselves!
        /// </summary>
        public UnityEvent pluginOnResetStats;

        public void ResetPlayers()
        {
            for (int i = allActivePlayers.Count - 1; i >= 0; i--)
            {
                NetworkServer.Destroy(allActivePlayers[i].gameObject);
            }
        }

        public void ResetAllStatsEndOfRound()
        {
            if (isServer)
            {
                for (int i = 0; i < Kit_NetworkPlayerManager.instance.players.Count; i++)
                {
                    Kit_NetworkPlayerManager.instance.players[i].team = -1;
                    Kit_NetworkPlayerManager.instance.players[i].kills = 0;
                    Kit_NetworkPlayerManager.instance.players[i].assists = 0;
                    Kit_NetworkPlayerManager.instance.players[i].deaths = 0;
                }

                //Callbacks for game modes
                if (currentPvPGameModeBehaviour)
                {
                    currentPvPGameModeBehaviour.ResetStats();
                }

                if (currentPvEGameModeBehaviour)
                {
                    currentPvEGameModeBehaviour.ResetStats();
                }
            }
        }

        /// <summary>
        /// Called when the game mode stage changes
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        void GameModeStageChanged(int from, int to)
        {

        }
        #endregion


        #region Menu Manager
        /// <summary>
        /// Call for buttons
        /// </summary>
        /// <param name="newMenu"></param>
        public void ChangeMenuButton(int newMenu)
        {
            if (!isSwitchingScreens)
            {
                //Start the coroutine
                StartCoroutine(SwitchRoutine(newMenu));
            }
        }

        public void ForceMenuActive(int menu)
        {
            //Disable all the roots
            for (int i = 0; i < menuScreens.Length; i++)
            {
                if (i != menu)
                {
                    if (menuScreens[i].root)
                    {
                        //Disable
                        menuScreens[i].root.SetActive(false);
                    }
                }
                else
                {
                    if (menuScreens[i].root)
                    {
                        //Disable
                        menuScreens[i].root.SetActive(true);
                    }
                }
            }
        }

        /// <summary>
        /// Switch to the given menu
        /// </summary>
        /// <param name="newMenu"></param>
        /// <returns></returns>
        public bool SwitchMenu(int newMenu)
        {
            Debug.Log("Requested switch from " + currentScreen + " to " + newMenu);

            if (currentScreen == newMenu) return true;

            if (!isSwitchingScreens)
            {
                //Start the coroutine
                currentlySwitchingScreensTo = StartCoroutine(SwitchRoutine(newMenu));
                //We are now switching
                return true;
            }

            //Not able to switch screens
            return false;
        }

        /// <summary>
        /// Switch to the given menu
        /// </summary>
        /// <param name="newMenu"></param>
        /// <returns></returns>
        public bool SwitchMenu(int newMenu, bool force)
        {
            Debug.Log("Requested switch from " + currentScreen + " to " + newMenu + ". Force? " + force);

            if (!isSwitchingScreens || force)
            {
                if (force)
                {
                    if (currentlySwitchingScreensTo != null)
                    {
                        StopCoroutine(currentlySwitchingScreensTo);
                    }

                    //Make sure all correct ones ARE disabled
                    //Disable all the roots
                    for (int i = 0; i < menuScreens.Length; i++)
                    {
                        if (i != currentScreen)
                        {
                            if (menuScreens[i].root)
                            {
                                //Disable
                                menuScreens[i].root.SetActive(false);
                            }
                        }
                    }
                }

                //Start the coroutine
                currentlySwitchingScreensTo = StartCoroutine(SwitchRoutine(newMenu));
                //We are now switching
                return true;
            }

            //Not able to switch screens
            return false;
        }

        private IEnumerator SwitchRoutine(int newMenu)
        {
            //Set bool
            isSwitchingScreens = true;
            if (wasFirstScreenFadedIn && currentScreen >= 0)
            {
                //Fade out screen
                //Play Animation
                menuScreens[currentScreen].anim.Play("Fade Out", 0, 0f);
                //Wait
                yield return new WaitForSeconds(menuScreens[currentScreen].fadeOutLength);
                menuScreens[currentScreen].root.SetActive(false);
            }

            //Fade in new screen
            //Set screen
            currentScreen = newMenu;
            if (currentScreen >= 0)
            {
                //Disable
                menuScreens[currentScreen].root.SetActive(true);
                //Play Animation
                menuScreens[currentScreen].anim.Play("Fade In", 0, 0f);
                //Wait
                yield return new WaitForSeconds(menuScreens[currentScreen].fadeInLength);
                //Set bool
                wasFirstScreenFadedIn = true;
            }
            //Done
            isSwitchingScreens = false;
        }
        #endregion
    }
}


fix it and show the whole script 100% with all comments and layout. Do not stop until all of the code is shown:
Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(615,9): error CS8803: Top-level statements must precede namespace and type declarations.

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(615,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(624,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(768,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(779,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(814,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(821,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(893,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(903,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(913,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(933,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(942,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(962,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(983,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1007,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1031,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1046,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1060,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1074,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1140,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1162,9): error CS1028: Unexpected preprocessor directive

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1164,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1177,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1183,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1189,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1207,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1242,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1288,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1303,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1311,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1326,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1340,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1379,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1387,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1429,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1438,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1467,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1490,9): error CS0106: The modifier 'public' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1528,9): error CS0106: The modifier 'private' is not valid for this item

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1560,5): error CS1022: Type or namespace definition, or end-of-file expected

Assets\314 Arts\MarsFPSKit\Scripts\GameLogic\Kit_IngameMain.cs(1561,1): error CS1022: Type or namespace definition, or end-of-file expected