package com.tiedup.remake.events.captivity;

import com.tiedup.remake.state.IPlayerLeashAccess;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

/**
 * Handles leash ticking for players via Forge events.
 * This replaces the mixin @Inject approach which had refmap issues.
 *
 * Security fix: Uses per-player tick count instead of global counter
 * to prevent erratic physics behavior with multiple players.
 */
@Mod.EventBusSubscriber(
    modid = "tiedup",
    bus = Mod.EventBusSubscriber.Bus.FORGE
)
public class LeashTickHandler {

    @SubscribeEvent
    public static void onPlayerTick(TickEvent.PlayerTickEvent event) {
        // Only on server side, at end of tick
        if (event.phase != TickEvent.Phase.END) return;
        if (!(event.player instanceof ServerPlayer serverPlayer)) return;

        // FIX: Removed throttling (was: tickCount % 2 != 0)
        // Throttling caused rubber-banding and jerky movement because:
        // 1. Client predicts movement between ticks
        // 2. Server sends velocity corrections every 2 ticks
        // 3. This creates visible "snapping" effect
        // Now physics runs every tick (20 Hz) for smooth movement.

        // Call the leash tick method via the mixin interface
        if (serverPlayer instanceof IPlayerLeashAccess access) {
            access.tiedup$tickLeash();
        }
    }
}
