using UnityEngine;
using MarsFPSKit;
using MarsFPSKit.Weapons;
using Mirror;

public class Kit_WeaponPickup : MonoBehaviour
{
    [Tooltip("Weapon ID this pickup grants")]
    public int weaponID = 1;

    [SerializeField]
    private Kit_WeaponPickupRespawnManager respawnManager;

    private void Start()
    {
        if (respawnManager == null)
        {
            respawnManager = GetComponentInParent<Kit_WeaponPickupRespawnManager>();
            if (respawnManager == null)
            {
                Debug.LogWarning("[Kit_WeaponPickup] No Kit_WeaponPickupRespawnManager assigned or found in parent!");
            }
            else
            {
                Debug.Log("[Kit_WeaponPickup] RespawnManager found via parent.");
            }
        }
        else
        {
            Debug.Log("[Kit_WeaponPickup] RespawnManager assigned manually.");
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        Debug.Log($"[Kit_WeaponPickup] OnTriggerEnter called with: {other.gameObject.name}, tag: {other.tag}");

        // Find Kit_PlayerBehaviour in this collider or its parents
        Kit_PlayerBehaviour player = other.GetComponentInParent<Kit_PlayerBehaviour>();

        if (player == null)
        {
            Debug.Log("[Kit_WeaponPickup] No Kit_PlayerBehaviour found on collider or parents, ignoring.");
            return;
        }

        Debug.Log($"[Kit_WeaponPickup] Player detected: netId={player.netId}, collider={other.gameObject.name}");

        var weaponManager = player.weaponManager as Kit_ModernWeaponManager;
        if (weaponManager == null)
        {
            Debug.LogWarning("[Kit_WeaponPickup] Player's weaponManager is not Kit_ModernWeaponManager.");
            return;
        }

        int slot = weaponManager.HasWeapon(player, weaponID);
        if (slot != -1)
        {
            Debug.Log($"[Kit_WeaponPickup] Player already owns weapon in slot {slot}, ignoring pickup.");
            return;
        }

        Debug.Log("[Kit_WeaponPickup] Player does NOT have weapon, attempting to give...");

        bool success = TryGiveWeapon(weaponManager, player, weaponID);
        if (success)
        {
            Debug.Log("[Kit_WeaponPickup] Successfully gave weapon to player.");

            if (respawnManager != null)
            {
                Debug.Log("[Kit_WeaponPickup] Notifying respawn manager pickup taken.");
                respawnManager.PickupTaken();
            }
            else
            {
                Debug.LogWarning("[Kit_WeaponPickup] Respawn manager reference missing; cannot notify pickup.");
            }
        }
        else
        {
            Debug.LogWarning("[Kit_WeaponPickup] Failed to give weapon to player.");
        }
    }

    private bool TryGiveWeapon(Kit_ModernWeaponManager wpnManager, Kit_PlayerBehaviour player, int weaponID)
    {
        if (player == null || wpnManager == null)
        {
            Debug.LogWarning("[Kit_WeaponPickup] Invalid player or weapon manager in TryGiveWeapon.");
            return false;
        }

        var runtimeData = player.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
        if (runtimeData == null)
        {
            Debug.LogWarning("[Kit_WeaponPickup] Player's weaponManagerNetworkData is null or wrong type.");
            return false;
        }

        // Find empty or placeholder slot
        int slot = -1;
        for (int i = 0; i < runtimeData.weaponsInUseDataObjects.Length; i++)
        {
            var weaponData = runtimeData.weaponsInUseDataObjects[i];
            if (weaponData == null || weaponData.behaviour == null || weaponData.behaviour.GetType() == typeof(Kit_WeaponUnselectable))
            {
                slot = i;
                Debug.Log($"[Kit_WeaponPickup] Found free/unselectable weapon slot: {slot}");
                break;
            }
        }

        // If no free slot found
        if (slot == -1)
        {
            Debug.Log("[Kit_WeaponPickup] No free slot found. Adding weapon at the end.");
        }

        try
        {
            if (slot != -1 && slot < runtimeData.weaponsInUseSync.Count)
            {
                // Replace an existing slot
                wpnManager.NetworkReplaceWeapon(player, slot, weaponID, 0, 0, new int[0]);
                Debug.Log($"[Kit_WeaponPickup] Replaced weapon at slot {slot}, weaponID {weaponID}");
            }
            else
            {
                // Spawn new weapon and add it to SyncList (no replace)
                GameObject weaponGO = Kit_IngameMain.instance.gameInformation.allWeapons[weaponID]
                    .SetupSpawnData(player, runtimeData.weaponsInUseDataObjects.Length, new LoadoutWeapon { weaponID = weaponID, attachments = new int[0] });

                NetworkServer.Spawn(weaponGO, player.gameObject);

                uint netId = weaponGO.GetComponent<NetworkIdentity>().netId;

                runtimeData.weaponsInUseSync.Add(netId);

                Debug.Log($"[Kit_WeaponPickup] Spawned new weapon and added to weaponsInUseSync at index {runtimeData.weaponsInUseSync.Count - 1}, weaponID {weaponID}");
            }

            return true;
        }
        catch (System.Exception e)
        {
            Debug.LogError("[Kit_WeaponPickup] Exception during weapon spawn or replace: " + e);
            return false;
        }
    }
}

i cant drag and drop the respawn manager to the inspectors field here. fix it