package com.tiedup.remake.mixin;

import com.tiedup.remake.util.HumanChairHelper;
import com.tiedup.remake.state.PlayerBindState;
import com.tiedup.remake.v2.BodyRegionV2;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

/**
 * Mixin to lock player body rotation during human chair mode.
 *
 * Vanilla {@code LivingEntity.tickHeadTurn()} gradually rotates yBodyRot
 * toward the head/movement direction. This overrides any value set from
 * a tick handler. By cancelling the method here, the body stays locked
 * at the stored facing direction.
 */
@Mixin(LivingEntity.class)
public abstract class MixinLivingEntityBodyRot {

    @Inject(method = "tickHeadTurn", at = @At("HEAD"), cancellable = true)
    private void tiedup$lockBodyForHumanChair(
        float yRot,
        float animStep,
        CallbackInfoReturnable<Float> cir
    ) {
        LivingEntity self = (LivingEntity) (Object) this;
        if (!(self instanceof Player player)) {
            return;
        }

        PlayerBindState state = PlayerBindState.getInstance(player);
        if (state == null || !state.isTiedUp()) {
            return;
        }

        ItemStack bind = state.getEquipment(BodyRegionV2.ARMS);
        if (bind.isEmpty()) {
            return;
        }

        if (!HumanChairHelper.isActive(bind)) {
            return;
        }

        // Lock body rotation to the stored facing and skip vanilla update
        float lockedYaw = HumanChairHelper.getFacing(bind);
        self.yBodyRot = lockedYaw;
        self.yBodyRotO = lockedYaw;
        cir.setReturnValue(animStep);
    }
}
