using UdonSharp;
using UnityEngine;
using UnityEngine.Rendering;
using VRC.SDKBase;
using VRC.Udon;
using VRC.Udon.Common;
using UCS;
using VRC.SDK3.UdonNetworkCalling;
using VRC.Udon.Common.Interfaces;
using VRC.SDK3.Persistence;

namespace UdonChipsHat
{
    /// <summary>
    /// Global manager that handles hat state, rendering via pool, and economy.
    /// Uses a pool of HatInteract objects positioned on player heads.
    /// Master owns this object and syncs hat state for all players.
    /// </summary>
    [UdonBehaviourSyncMode(BehaviourSyncMode.Manual)]
    public class HatManager : UdonSharpBehaviour
    {
        #region Persistence Keys
        
        // PlayerData keys (namespaced) - each player saves their own hat state locally
        public const string SaveKeyPrefix = "S1_";
        private const string PersistenceHatTypeKey = SaveKeyPrefix + "UdonChipsHat/Type";
        private const string PersistenceGiverKey = SaveKeyPrefix + "UdonChipsHat/Giver";
        private const string PersistenceHasHatKey = SaveKeyPrefix + "UdonChipsHat/HasHat";
        
        #endregion

        #region Hat Event Broadcasting
        
        [Header("Hat Event Subscribers")]
        [Tooltip("Components that inherit from HatEventSubscriber and will receive OnHatEvent calls")]
        private HatEventSubscriber[] hatEventSubscribers;

        /// <summary>
        /// Subscribes a HatEventSubscriber to receive hat events.
        /// Finds the first empty slot and assigns the subscriber.
        /// </summary>
        /// <param name="subscriber">The subscriber to register</param>
        public void Subscribe(HatEventSubscriber subscriber)
        {
            if (subscriber == null) return;

            // Initialize array if needed
            if (hatEventSubscribers == null)
            {
                hatEventSubscribers = new HatEventSubscriber[8];
            }

            // Check if already subscribed
            for (int i = 0; i < hatEventSubscribers.Length; i++)
            {
                if (hatEventSubscribers[i] == subscriber)
                {
                    return; // Already subscribed
                }
            }

            // Find first empty slot
            for (int i = 0; i < hatEventSubscribers.Length; i++)
            {
                if (hatEventSubscribers[i] == null)
                {
                    hatEventSubscribers[i] = subscriber;
                    Debug.Log($"[HatManager] Subscriber registered at index {i}");
                    return;
                }
            }

            Debug.LogWarning("[HatManager] Could not register subscriber - array is full");
        }

        #endregion

        #region Global Economy Settings (Shared by all hats)
        
        [Header("Global Economy Settings")]
        [Tooltip("Cost in UdonChips to place ANY hat on another player")]
        public int costToPlaceHat = 1000;

        [Tooltip("Amount the target player receives when ANY hat is placed on them")]
        public int rewardToTarget = 500;

        [Tooltip("Cost in UdonChips to remove a hat (paid by the remover)")]
        public int costToRemoveHat = 5000;

        [Tooltip("Furthest a player can be from the target to place or remove a hat")]
        public float maxReachMeters = 5f;

        [Tooltip("Players it has flagged can't place or remove hats")]
        public HoldemAuthority authority;

        #endregion

        #region Hat Pool

        [Header("Hat Pool")]
        [Tooltip("Pool of HatInteract objects (one per possible hat)")]
        public HatInteract[] hatInteractPool;

        [Tooltip("Maximum number of players to support")]
        public int maxPlayers = 80;

        #endregion

        #region Hat Visual Definitions

        [Header("Hat Prefabs")]
        [Tooltip("Prefab GameObjects containing MeshRenderer for each hat type")]
        public GameObject[] hatPrefabs;

        [Tooltip("Offset from head position for each hat type")]
        public Vector3[] hatOffsets;

        [Tooltip("Scale multiplier for each hat type")]
        public float[] hatScaleMultipliers;

        [Tooltip("Hat type ID for which the seatObject (e.g., halo) should be visible on other players")]
        public byte seatObjectHatTypeId = 3;

        [Tooltip("Base avatar eye height for default scaling")]
        public float baseAvatarHeight = 1.6f;

        #endregion

        #region Synced State (Indexed by Player ID)

        // Synced arrays - index is player ID (0-79)
        [UdonSynced]
        public byte[] PlayerHatTypes;

        [UdonSynced]
        public bool[] PlayerHasHats;

        [UdonSynced]
        public string[] PlayerGiverNames;

        #endregion

        #region Internal State

        // Pool tracking - which player ID is assigned to each pool slot
        private int[] poolPlayerAssignments;  // Length = hatInteractPool.Length
        private int[] playerPoolSlot;         // Length = maxPlayers, value = pool slot or -1
        
        // Per-slot mirrors of what the pool objects were last given, so the per-frame pass only touches the
        // transform and calls into a HatInteract when something actually changed.
        private int[] _slotUsedFrame;     // Time.frameCount when a player last used the slot
        private bool[] _slotActive;       // Mirrors the pool object's activeSelf
        private int _activeSlotCount;
        private int[] _slotActivatedFrame; // HatInteract.Start runs after activation and resets its visuals
        private int[] _slotHatType;       // -1 = visuals not applied
        private float[] _slotHatScale;
        private int[] _slotSeatObject;    // -1 unknown, 0 off, 1 on
        private int[] _slotPlayerId;
        // Touching hatInteractPool itself (even a null check or Length) costs tens of µs in the Udon VM, so the
        // per-frame pass reads this instead
        private int _poolLen;

        // Player tracking
        private VRCPlayerApi[] allPlayers;
        private int playerCount;
        private bool _playersDirty = true;

        // Local pending tracking to prevent double-hat
        private int[] pendingHatFrame;  // Frame count when hat was requested
        private const int PENDING_FRAMES = 120; // ~2 seconds at 60fps

        // Initial load tracking
        private bool initialLoadTriggered = false;

        private bool persistenceRestoreComplete = false;

        // Set while waiting for the master to confirm a requested hat restore
        private bool awaitingRestoreApply = false;

        private bool lastSavedHasHat = false;
        private byte lastSavedHatType = 0;
        private string lastSavedGiverName = "";


        // Track previous hat state to detect removals
        private bool[] previousPlayerHasHats;
        private byte[] previousPlayerHatTypes;

        #endregion

        void Start()
        {
            // Initialize synced arrays. Only allocate when missing.
            if (PlayerHatTypes == null || PlayerHatTypes.Length != maxPlayers)
            {
                PlayerHatTypes = new byte[maxPlayers];
            }
            if (PlayerHasHats == null || PlayerHasHats.Length != maxPlayers)
            {
                PlayerHasHats = new bool[maxPlayers];
            }
            if (PlayerGiverNames == null || PlayerGiverNames.Length != maxPlayers)
            {
                PlayerGiverNames = new string[maxPlayers];
            }

            // Initialize tracking arrays
            poolPlayerAssignments = new int[hatInteractPool != null ? hatInteractPool.Length : 0];
            playerPoolSlot = new int[maxPlayers];
            pendingHatFrame = new int[maxPlayers];
            allPlayers = new VRCPlayerApi[maxPlayers];

            // Initialize pool assignments to -1 (unassigned)
            for (int i = 0; i < poolPlayerAssignments.Length; i++)
            {
                poolPlayerAssignments[i] = -1;
            }
            for (int i = 0; i < playerPoolSlot.Length; i++)
            {
                playerPoolSlot[i] = -1;
                pendingHatFrame[i] = 0;
            }

            int poolLen = poolPlayerAssignments.Length;
            _poolLen = poolLen;
            _slotUsedFrame = new int[poolLen];
            _slotActive = new bool[poolLen];
            _activeSlotCount = 0;
            _slotActivatedFrame = new int[poolLen];
            _slotHatType = new int[poolLen];
            _slotHatScale = new float[poolLen];
            _slotSeatObject = new int[poolLen];
            _slotPlayerId = new int[poolLen];
            for (int i = 0; i < poolLen; i++)
            {
                _slotUsedFrame[i] = -1;
                ForgetSlotVisuals(i);
            }

            // Initialize pool objects
            if (hatInteractPool != null)
            {
                for (int i = 0; i < hatInteractPool.Length; i++)
                {
                    if (hatInteractPool[i] != null)
                    {
                        hatInteractPool[i].Initialize(this, i);
                        hatInteractPool[i].gameObject.SetActive(false);
                    }
                }
            }

            // Initialize previous state tracking arrays
            previousPlayerHasHats = new bool[maxPlayers];
            previousPlayerHatTypes = new byte[maxPlayers];
            for (int i = 0; i < maxPlayers; i++)
            {
                previousPlayerHasHats[i] = false;
                previousPlayerHatTypes[i] = 0;
            }
        }

        public override void OnDeserialization()
        {
            TryCompleteRestoreFromSyncedState();
            ApplyLocalHatEffects();
            SaveLocalHatStateToPersistence();
        }

        // Ownership only moves to the new master when the owner leaves
        public override bool OnOwnershipRequest(VRCPlayerApi requestingPlayer, VRCPlayerApi requestedOwner)
        {
            return false;
        }

        public void _BeginPersistenceRestore()
        {
            awaitingRestoreApply = true;
        }

        private void TryCompleteRestoreFromSyncedState()
        {
            if (!awaitingRestoreApply) return;

            VRCPlayerApi local = Networking.LocalPlayer;
            if (local == null || !local.IsValid()) return;

            int localPlayerId = local.playerId;
            if (localPlayerId < 0 || localPlayerId >= maxPlayers) return;
            if (PlayerHasHats == null || localPlayerId >= PlayerHasHats.Length) return;

            if (PlayerHasHats[localPlayerId])
            {
                _MarkPersistenceRestoreComplete();
            }
        }

        public void _MarkPersistenceRestoreComplete()
        {
            persistenceRestoreComplete = true;
            awaitingRestoreApply = false;

            ApplyLocalHatEffects();
            SaveLocalHatStateToPersistence();
        }

        public bool IsPersistenceRestoreComplete()
        {
            return persistenceRestoreComplete;
        }

        /// <summary>
        /// Applies hat effects for the local player based on synced state.
        /// Called from OnDeserialization for non-owners and directly by owner
        /// after modifying state since OnDeserialization doesn't run for the owner.
        /// </summary>
        private void ApplyLocalHatEffects()
        {
            // Get local player
            VRCPlayerApi localPlayer = Networking.LocalPlayer;
            if (localPlayer == null || !localPlayer.IsValid()) return;

            int localPlayerId = localPlayer.playerId;
            if (localPlayerId < 0 || localPlayerId >= maxPlayers) return;

            // Only consumed if hat is actually present
            if (!initialLoadTriggered)
            {
                // Check if local player has a hat
                if (PlayerHasHats[localPlayerId])
                {
                    byte hatType = PlayerHatTypes[localPlayerId];
                    string giverName = PlayerGiverNames[localPlayerId];
                    
                    initialLoadTriggered = true;
                    BroadcastHatInitialLoad(hatType, giverName);
                }
            }

            // Check for hat removal (previous state had hat, current state doesn't)
            if (previousPlayerHasHats[localPlayerId] && !PlayerHasHats[localPlayerId])
            {
                byte previousHatType = previousPlayerHatTypes[localPlayerId];
                BroadcastHatRemoved(previousHatType, "");
            }

            // Update previous state tracking for local player
            previousPlayerHasHats[localPlayerId] = PlayerHasHats[localPlayerId];
            previousPlayerHatTypes[localPlayerId] = PlayerHatTypes[localPlayerId];
        }

        /// <summary>
        /// Saves the local player's hat state to their own PlayerData persistence.
        /// Called from OnDeserialization when synced data is received.
        /// Each player can only save their own data - the master cannot save for others.
        /// </summary>
        private void SaveLocalHatStateToPersistence()
        {
            // Never write before the restore has been reconciled
            if (!persistenceRestoreComplete) return;
            WriteLocalHatStateToPersistence();
        }

        private void WriteLocalHatStateToPersistence()
        {
            // Get local player - we can only save our own data
            VRCPlayerApi localPlayer = Networking.LocalPlayer;
            if (localPlayer == null || !localPlayer.IsValid()) return;

            int localPlayerId = localPlayer.playerId;
            if (localPlayerId < 0 || localPlayerId >= maxPlayers) return;

            // Get current hat state from synced arrays
            bool currentHasHat = PlayerHasHats[localPlayerId];
            byte currentHatType = PlayerHatTypes[localPlayerId];
            string currentGiverName = PlayerGiverNames[localPlayerId];
            if (currentGiverName == null) currentGiverName = "";

            if (currentHasHat == lastSavedHasHat
                && currentHatType == lastSavedHatType
                && currentGiverName == lastSavedGiverName)
            {
                return;
            }

            // Save to our own persistence (we can only save local player data)
            PlayerData.SetInt(PersistenceHatTypeKey, currentHatType);
            PlayerData.SetString(PersistenceGiverKey, currentGiverName);
            PlayerData.SetInt(PersistenceHasHatKey, currentHasHat ? 1 : 0);

            lastSavedHasHat = currentHasHat;
            lastSavedHatType = currentHatType;
            lastSavedGiverName = currentGiverName;

            Debug.Log($"[HatManager] Saved hat state to persistence: Type={currentHatType}, Giver={currentGiverName}, HasHat={currentHasHat}");
        }

        void PostLateUpdate()
        {
            UpdateHatPositions();
        }

        /// <summary>
        /// Updates positions of all pooled hat objects to follow player heads.
        /// </summary>
        private void UpdateHatPositions()
        {
            if (_poolLen == 0) return;

            // Get all players (cached, only refreshes when players join/leave)
            RefreshPlayers();

            int frame = Time.frameCount;
            int usedActiveCount = 0;

            // Assign/update pool slots for players with hats
            for (int i = 0; i < playerCount; i++)
            {
                VRCPlayerApi player = allPlayers[i];
                if (player == null || !player.IsValid()) continue;

                int playerId = player.playerId;
                if (playerId < 0 || playerId >= maxPlayers) continue;

                // Check if player has a hat
                if (!PlayerHasHats[playerId]) continue;

                // Get or assign pool slot
                int slot = playerPoolSlot[playerId];
                if (slot < 0)
                {
                    slot = FindFreePoolSlot();
                    if (slot >= 0)
                    {
                        playerPoolSlot[playerId] = slot;
                        poolPlayerAssignments[slot] = playerId;
                    }
                }

                if (slot >= 0)
                {
                    _slotUsedFrame[slot] = frame;
                    PositionHatAtHead(slot, player, PlayerHatTypes[playerId]);
                    if (_slotActive[slot]) usedActiveCount++;
                }
            }

            // Every active slot was used this frame: nothing to disable
            if (usedActiveCount == _activeSlotCount) return;

            // Disable unused pool slots
            for (int i = 0; i < _poolLen; i++)
            {
                if (!_slotActive[i] || _slotUsedFrame[i] == frame) continue;
                DeactivateSlot(i);
                if (poolPlayerAssignments[i] >= 0)
                {
                    playerPoolSlot[poolPlayerAssignments[i]] = -1;
                    poolPlayerAssignments[i] = -1;
                }
            }
        }

        private void DeactivateSlot(int slot)
        {
            if (hatInteractPool[slot] != null) hatInteractPool[slot].gameObject.SetActive(false);
            if (_slotActive[slot]) _activeSlotCount--;
            _slotActive[slot] = false;
        }

        private void ForgetSlotVisuals(int slot)
        {
            _slotHatType[slot] = -1;
            _slotHatScale[slot] = -1f;
            _slotSeatObject[slot] = -1;
            _slotPlayerId[slot] = -1;
        }

        /// <summary>
        /// Refreshes the cached player list if dirty (players joined/left).
        /// </summary>
        private void RefreshPlayers()
        {
            if (!_playersDirty) return;
            playerCount = VRCPlayerApi.GetPlayerCount();
            VRCPlayerApi.GetPlayers(allPlayers);
            _playersDirty = false;
        }

        /// <summary>
        /// Finds a free slot in the hat pool.
        /// </summary>
        private int FindFreePoolSlot()
        {
            for (int i = 0; i < poolPlayerAssignments.Length; i++)
            {
                if (poolPlayerAssignments[i] < 0)
                {
                    return i;
                }
            }
            return -1; // No free slots
        }

        /// <summary>
        /// Positions a pooled hat at the player's head.
        /// </summary>
        private void PositionHatAtHead(int poolSlot, VRCPlayerApi player, byte hatType)
        {
            if (poolSlot < 0 || poolSlot >= _poolLen) return;
            HatInteract hat = hatInteractPool[poolSlot];
            if (hat == null) return;

            // Get head tracking data
            VRCPlayerApi.TrackingData headData = player.GetTrackingData(VRCPlayerApi.TrackingDataType.Head);

            // Calculate scale based on avatar height
            float avatarScale = player.GetAvatarEyeHeightAsMeters() / baseAvatarHeight;
            float hatScale = avatarScale;

            // Apply hat-specific multiplier if available
            if (hatScaleMultipliers != null && hatType < hatScaleMultipliers.Length && hatScaleMultipliers[hatType] > 0)
            {
                hatScale *= hatScaleMultipliers[hatType];
            }

            // Position the root at head position (no offset here)
            Transform hatTransform = hat.transform;
            hatTransform.SetPositionAndRotation(headData.position, headData.rotation);

            // The hat's own Start resets its visuals on the frame after it is first activated, so reapply until then
            bool justActivated = Time.frameCount - _slotActivatedFrame[poolSlot] <= 1;
            float previousScale = _slotHatScale[poolSlot];
            if (justActivated || _slotHatType[poolSlot] != hatType
                || Mathf.Abs(hatScale - previousScale) > previousScale * 0.001f)
            {
                // Apply hat-specific offset if available
                Vector3 offset = Vector3.zero;
                if (hatOffsets != null && hatType < hatOffsets.Length)
                {
                    offset = hatOffsets[hatType];
                }

                // Note: Scale is applied in SetHatVisuals to avoid double-scaling
                hatTransform.localScale = Vector3.one;

                // Update mesh/material based on hat type, passing the offset and hat scale
                hat.SetHatVisuals(hatType, offset, hatScale);
                _slotHatType[poolSlot] = hatType;
                _slotHatScale[poolSlot] = hatScale;
            }

            // Enable seat object (e.g. halo) only for matching hat type and only on other players
            int showSeatObject = (hatType == seatObjectHatTypeId) && !player.isLocal ? 1 : 0;
            if (justActivated || _slotSeatObject[poolSlot] != showSeatObject)
            {
                hat.SetSeatObjectActive(showSeatObject == 1);
                _slotSeatObject[poolSlot] = showSeatObject;
            }

            int playerId = player.playerId;
            if (_slotPlayerId[poolSlot] != playerId)
            {
                hat.assignedPlayerId = playerId;
                _slotPlayerId[poolSlot] = playerId;
            }

            if (!_slotActive[poolSlot])
            {
                hat.gameObject.SetActive(true);
                _slotActive[poolSlot] = true;
                _activeSlotCount++;
                _slotActivatedFrame[poolSlot] = Time.frameCount;
            }
        }

        public override void OnPlayerJoined(VRCPlayerApi player)
        {
            _playersDirty = true;
        }

        public override void OnPlayerLeft(VRCPlayerApi player)
        {
            _playersDirty = true;
            int playerId = player.playerId;
            if (playerId < 0 || playerId >= maxPlayers) return;

            // Free up pool slot
            int slot = playerPoolSlot[playerId];
            if (slot >= 0 && slot < hatInteractPool.Length)
            {
                DeactivateSlot(slot);
                if (hatInteractPool[slot] != null) hatInteractPool[slot].assignedPlayerId = -1;
                _slotPlayerId[slot] = -1;
                poolPlayerAssignments[slot] = -1;
            }
            playerPoolSlot[playerId] = -1;

            // Clear pending flag
            pendingHatFrame[playerId] = 0;

            // Master clears hat state for left player
            if (Networking.IsOwner(gameObject))
            {
                PlayerHasHats[playerId] = false;
                PlayerHatTypes[playerId] = 0;
                PlayerGiverNames[playerId] = "";
                RequestSerialization();
            }
        }

        #region Public API - Called by HatItem/HatInteract

        /// <summary>
        /// Called by the local player to place a hat on a nearby target.
        /// The master charges the giver and pays the target.
        /// </summary>
        public void RequestApplyHat(int targetPlayerId, byte hatType)
        {
            if (Networking.IsOwner(gameObject))
            {
                ApplyHat(Networking.LocalPlayer, targetPlayerId, hatType);
                return;
            }

            SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(MasterApplyHat), targetPlayerId, hatType);
        }

        [NetworkCallable(2)]
        public void MasterApplyHat(int targetPlayerId, byte hatType)
        {
            ApplyHat(NetworkCalling.CallingPlayer, targetPlayerId, hatType);
        }

        private void ApplyHat(VRCPlayerApi giver, int targetPlayerId, byte hatType)
        {
            if (!Networking.IsOwner(gameObject) || !Utilities.IsValid(giver) || IsFlagged(giver)) return;
            if (targetPlayerId < 0 || targetPlayerId >= maxPlayers || targetPlayerId == giver.playerId) return;
            if (hatPrefabs != null && hatType >= hatPrefabs.Length) return;

            // Double-check target doesn't already have a hat
            if (PlayerHasHats[targetPlayerId])
            {
                Debug.Log($"[HatManager] Master rejected hat application - player {targetPlayerId} already has hat");
                return;
            }

            VRCPlayerApi target = VRCPlayerApi.GetPlayerById(targetPlayerId);
            if (!Utilities.IsValid(target) || !InReach(giver, target)) return;

            PlayerBalanceComponent giverBalance = PlayerBalanceComponent.GetPlayerBalanceComponent(giver);
            if (giverBalance == null || !giverBalance.IsReady() || giverBalance.GetBalance() < costToPlaceHat) return;

            SetHat(targetPlayerId, true, hatType, giver.displayName);

            giverBalance.ModifyBalance(-costToPlaceHat);
            giverBalance._RecordHatGiven();
            PlayerBalanceComponent targetBalance = PlayerBalanceComponent.GetPlayerBalanceComponent(target);
            if (targetBalance != null && targetBalance.IsReady())
            {
                targetBalance.ModifyBalance(rewardToTarget);
                targetBalance._RecordHatReceived();
            }
        }

        /// <summary>
        /// Called by HatPlayerData to put back the local player's own saved hat. Free, and only on themselves.
        /// </summary>
        public void RequestRestoreOwnHat(byte hatType, string giverName)
        {
            if (Networking.IsOwner(gameObject))
            {
                RestoreHat(Networking.LocalPlayer, hatType, giverName);
                return;
            }

            SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RestoreOwnHat), hatType, giverName);
        }

        [NetworkCallable(1)]
        public void RestoreOwnHat(byte hatType, string giverName)
        {
            RestoreHat(NetworkCalling.CallingPlayer, hatType, giverName);
        }

        private void RestoreHat(VRCPlayerApi player, byte hatType, string giverName)
        {
            if (!Networking.IsOwner(gameObject) || !Utilities.IsValid(player)) return;
            int playerId = player.playerId;
            if (playerId < 0 || playerId >= maxPlayers || PlayerHasHats[playerId]) return;

            SetHat(playerId, true, hatType, giverName);
        }

        /// <summary>
        /// Called by the local player to remove a nearby player's hat. The master charges the remover.
        /// </summary>
        public void RequestRemoveHat(int targetPlayerId)
        {
            if (Networking.IsOwner(gameObject))
            {
                RemoveHat(Networking.LocalPlayer, targetPlayerId);
                return;
            }

            SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(MasterRemoveHat), targetPlayerId);
        }

        [NetworkCallable(2)]
        public void MasterRemoveHat(int targetPlayerId)
        {
            RemoveHat(NetworkCalling.CallingPlayer, targetPlayerId);
        }

        private void RemoveHat(VRCPlayerApi remover, int targetPlayerId)
        {
            if (!Networking.IsOwner(gameObject) || !Utilities.IsValid(remover) || IsFlagged(remover)) return;
            if (targetPlayerId < 0 || targetPlayerId >= maxPlayers) return;

            if (!PlayerHasHats[targetPlayerId])
            {
                Debug.Log($"[HatManager] Master rejected hat removal - player {targetPlayerId} has no hat");
                return;
            }

            VRCPlayerApi target = VRCPlayerApi.GetPlayerById(targetPlayerId);
            if (!Utilities.IsValid(target) || !InReach(remover, target)) return;

            PlayerBalanceComponent removerBalance = PlayerBalanceComponent.GetPlayerBalanceComponent(remover);
            if (removerBalance == null || !removerBalance.IsReady() || removerBalance.GetBalance() < costToRemoveHat) return;

            SetHat(targetPlayerId, false, 0, "");
            removerBalance.ModifyBalance(-costToRemoveHat);
        }

        private bool IsFlagged(VRCPlayerApi player)
        {
            return authority != null && authority.IsFlagged(player.displayName);
        }

        private bool InReach(VRCPlayerApi player, VRCPlayerApi target)
        {
            return player.playerId == target.playerId
                || Vector3.Distance(player.GetPosition(), target.GetPosition()) <= maxReachMeters;
        }

        private void SetHat(int playerId, bool hasHat, byte hatType, string giverName)
        {
            PlayerHatTypes[playerId] = hatType;
            PlayerGiverNames[playerId] = giverName;
            PlayerHasHats[playerId] = hasHat;

            RequestSerialization();
            Debug.Log($"[HatManager] Player {playerId} hat set to {hasHat} (type {hatType}, from {giverName})");

            // Apply effects for owner since OnDeserialization doesn't run for them
            VRCPlayerApi localPlayer = Networking.LocalPlayer;
            if (localPlayer != null && localPlayer.IsValid() && localPlayer.playerId == playerId)
            {
                // local so is authoratative
                _MarkPersistenceRestoreComplete();
            }
        }

        /// <summary>
        /// Force refresh of all hat positions (called after hat state changes)
        /// </summary>
        public void RefreshHats()
        {
            // The next PostLateUpdate will handle it
        }

        /// <summary>
        /// Get the cost to place any hat
        /// </summary>
        public int GetCostToPlace()
        {
            return costToPlaceHat;
        }

        /// <summary>
        /// Get the reward amount given to the target when any hat is placed
        /// </summary>
        public int GetRewardToTarget()
        {
            return rewardToTarget;
        }

        /// <summary>
        /// Get the cost to remove any hat
        /// </summary>
        public int GetCostToRemove()
        {
            return costToRemoveHat;
        }

        /// <summary>
        /// Check if a player has a hat
        /// </summary>
        public bool PlayerHasHat(int playerId)
        {
            if (playerId < 0 || playerId >= maxPlayers) return false;
            return PlayerHasHats[playerId];
        }

        /// <summary>
        /// Get the hat type for a player
        /// </summary>
        public byte GetPlayerHatType(int playerId)
        {
            if (playerId < 0 || playerId >= maxPlayers) return 0;
            return PlayerHatTypes[playerId];
        }

        #endregion

        #region Hat Event Broadcasting

        /// <summary>
        /// Broadcast an event to all HatBell instances, credited to the local player.
        /// </summary>
        /// <param name="hatTypeId">Hat type to target (0-254), or 255 for any hat type</param>
        public void BroadcastHatEvent(byte hatTypeId)
        {
            // Each HatBell will receive this and check against its local HatPlayerData
            SendCustomNetworkEvent(NetworkEventTarget.All, nameof(OnHatEvent), hatTypeId);

            Debug.Log($"[HatManager] Broadcasting event for hat type {hatTypeId}");
        }

        /// <summary>
        /// Broadcasts the initial hat load event to all subscribers.
        /// Called once when the local player's persisted hat state is first received.
        /// This is a local-only call since data is already synced via persistence.
        /// </summary>
        /// <param name="hatTypeId">Hat type of the local player</param>
        /// <param name="triggerPlayerName">Display name of the player who gave the hat</param>
        public void BroadcastHatInitialLoad(byte hatTypeId, string triggerPlayerName)
        {
            Debug.Log($"[HatManager] Broadcasting initial load event for hat type {hatTypeId} from {triggerPlayerName}");

            if (hatEventSubscribers == null) return;

            for (int i = 0; i < hatEventSubscribers.Length; i++)
            {
                HatEventSubscriber subscriber = hatEventSubscribers[i];
                if (subscriber == null) continue;

                subscriber.OnHatInitialLoad(hatTypeId, triggerPlayerName);
            }
        }

        /// <summary>
        /// Called on all clients via SendCustomNetworkEvent.
        /// Dispatches to all registered IHatEventSubscriber instances.
        /// </summary>
        [NetworkCallable(2)]
        public void OnHatEvent(byte hatTypeId)
        {
            // The trigger is whoever sent the event, so a giver's name can't be spoofed
            VRCPlayerApi caller = NetworkCalling.CallingPlayer;
            if (!Utilities.IsValid(caller)) return;
            string triggerPlayerName = caller.displayName;
            Debug.Log($"[HatManager] Received event for hat type {hatTypeId} from {triggerPlayerName}");

            if (hatEventSubscribers == null) return;

            for (int i = 0; i < hatEventSubscribers.Length; i++)
            {
                HatEventSubscriber subscriber = hatEventSubscribers[i];
                if (subscriber == null) continue;

                subscriber.OnHatEvent(hatTypeId, triggerPlayerName);
            }
        }

        /// <summary>
        /// Broadcasts the hat removed event to all subscribers.
        /// Called locally when a hat is removed from the local player.
        /// </summary>
        /// <param name="hatTypeId">Hat type that was removed</param>
        /// <param name="triggerPlayerName">Display name of the player who triggered the removal</param>
        public void BroadcastHatRemoved(byte hatTypeId, string triggerPlayerName)
        {
            Debug.Log($"[HatManager] Broadcasting hat removed event for hat type {hatTypeId}");

            if (hatEventSubscribers == null) return;

            for (int i = 0; i < hatEventSubscribers.Length; i++)
            {
                HatEventSubscriber subscriber = hatEventSubscribers[i];
                if (subscriber == null) continue;

                subscriber.OnHatRemoved(hatTypeId, triggerPlayerName);
            }
        }

        #endregion
    }
}
