using Sandbox;
using Sandbox.Network;

namespace GravCoin;

public sealed class GameSetup : Component, Component.INetworkListener
{
	[Property] public GameObject PlayerPrefab { get; set; }

	protected override void OnStart()
	{
		if ( !Networking.IsActive )
		{
			LoadingScreen.Title = "Création du lobby…";
			Networking.CreateLobby( new() );
		}
	} 

	void INetworkListener.OnActive( Connection channel )
	{
		GameObject player;
		if ( PlayerPrefab.IsValid() )
		{
			player = PlayerPrefab.Clone();
		}
		else
		{
			player = new GameObject( true, $"Trader_{channel.DisplayName}" );
			player.Components.Create<PlayerTrader>();
			player.Components.Create<UpgradeSystem>();
			player.Components.Create<InfrastructureManager>();
		}

		player.NetworkSpawn( channel );
		ChatSystem.Instance?.NotifyPlayerJoined( channel.DisplayName );
	}

	void INetworkListener.OnDisconnected( Connection channel )
	{
		// Best-effort flush for the local player when leaving
		if ( channel == Connection.Local )
			_ = PlayerTrader.Local?.ForceFlushOnExitAsync();

		ChatSystem.Instance?.NotifyPlayerLeft( channel.DisplayName );
	}
	void INetworkListener.OnBecameHost( Connection previousHost )
	{
		MarketManager.Instance?.RecoverFromHostMigration();
	}
}
