package com.tiedup.remake.mixin.client;

import com.tiedup.remake.items.base.PoseType;
import com.tiedup.remake.v2.bondage.PoseTypeHelper;
import com.tiedup.remake.util.HumanChairHelper;
import com.tiedup.remake.state.PlayerBindState;
import com.tiedup.remake.v2.BodyRegionV2;
import net.minecraft.client.Camera;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.phys.Vec3;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

/**
 * Mixin for Camera to lower first-person view when in DOG pose.
 *
 * In DOG pose, the player model is horizontal (like a dog), so the camera
 * should be lowered to match the eye level being closer to the ground.
 * Normal eye height is ~1.62 blocks, we lower it by ~0.6 blocks.
 */
@Mixin(Camera.class)
public abstract class MixinCamera {

    @Shadow
    private Vec3 position;

    @Shadow
    protected abstract void setPosition(Vec3 pos);

    @Inject(method = "setup", at = @At("TAIL"))
    private void tiedup$lowerCameraForDogPose(
        BlockGetter level,
        Entity entity,
        boolean detached,
        boolean thirdPersonReverse,
        float partialTick,
        CallbackInfo ci
    ) {
        // Only affect first-person view
        if (detached) {
            return;
        }

        if (!(entity instanceof Player player)) {
            return;
        }

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

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

        if (PoseTypeHelper.getPoseType(bind) != PoseType.DOG) {
            return;
        }

        // Lower camera by 0.6 blocks to match the horizontal body position
        // Normal eye height is ~1.62, DOG pose should be around ~1.0
        setPosition(position.add(0, -0.6, 0));

        // Human chair: move camera forward into the head
        if (HumanChairHelper.isActive(bind)) {
            float facing = HumanChairHelper.getFacing(bind);
            float facingRad = (float) Math.toRadians(facing);
            double fwdX = -Math.sin(facingRad) * 0.6;
            double fwdZ = Math.cos(facingRad) * 0.6;
            setPosition(position.add(fwdX, 0, fwdZ));
        }
    }
}
