using System.Collections.Generic;
using System.Linq;
using FishNet;
using FishNet.Object;
using UnityEngine;
using IStalk.Data;
using IStalk.Runner;

namespace IStalk.Core
{
    public class LootSpawner : MonoBehaviour
    {
        [SerializeField] private NetworkObject _worldItemPrefab;

        public void SpawnLoot(IReadOnlyList<Vector3> positions)
        {
            if (!InstanceFinder.IsServerStarted) return;

            var allLoot = ItemDatabase.Instance.AllLootItems.ToList();
            if (allLoot.Count == 0) return;

            foreach (var pos in positions)
            {
                var item = PickWeightedItem(allLoot);
                if (item == null) continue;

                if (_worldItemPrefab != null)
                {
                    var go = Instantiate(_worldItemPrefab, pos, Quaternion.identity);
                    InstanceFinder.ServerManager.Spawn(go);
                    var worldItem = go.GetComponent<WorldItem>();
                    if (worldItem != null)
                        worldItem.Initialize(item.itemId);
                }
                else
                {
                    WorldItem.SpawnWorldItem(item.itemId, pos);
                }
            }
        }

        private ItemData_SO PickWeightedItem(List<ItemData_SO> items)
        {
            float totalWeight = 0;
            foreach (var item in items)
            {
                float w = item.rarity switch
                {
                    Rarity.Common => 10f,
                    Rarity.Uncommon => 5f,
                    Rarity.Rare => 2f,
                    Rarity.Legendary => 0.5f,
                    _ => 5f
                };
                totalWeight += w;
            }

            float roll = Random.Range(0, totalWeight);
            float cumulative = 0;
            foreach (var item in items)
            {
                float w = item.rarity switch
                {
                    Rarity.Common => 10f,
                    Rarity.Uncommon => 5f,
                    Rarity.Rare => 2f,
                    Rarity.Legendary => 0.5f,
                    _ => 5f
                };
                cumulative += w;
                if (roll <= cumulative)
                    return item;
            }
            return items[^1];
        }
    }
}
