package com.tiedup.remake.client.animation.render;

import com.tiedup.remake.client.state.PetBedClientState;
import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.items.base.ItemBind;
import com.tiedup.remake.items.base.PoseType;
import com.tiedup.remake.state.HumanChairHelper;
import com.tiedup.remake.state.PlayerBindState;
import com.tiedup.remake.v2.BodyRegionV2;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

/**
 * Handles pet bed render adjustments (SIT and SLEEP modes).
 *
 * <p>Applies vertical offset and forced standing pose for pet bed states.
 * Runs at HIGH priority alongside DogPoseRenderHandler.
 *
 * <p>Extracted from PlayerArmHideEventHandler for single-responsibility.
 */
@OnlyIn(Dist.CLIENT)
@Mod.EventBusSubscriber(
    modid = TiedUpMod.MOD_ID,
    bus = Mod.EventBusSubscriber.Bus.FORGE,
    value = Dist.CLIENT
)
public class PetBedRenderHandler {

    /**
     * Before player render: Apply vertical offset and forced pose for pet bed.
     */
    @SubscribeEvent(priority = EventPriority.HIGH)
    public static void onRenderPlayerPre(RenderPlayerEvent.Pre event) {
        Player player = event.getEntity();
        if (!(player instanceof AbstractClientPlayer)) {
            return;
        }

        if (player.isRemoved() || !player.isAlive()) {
            return;
        }

        java.util.UUID petBedUuid = player.getUUID();
        byte petBedMode = PetBedClientState.get(petBedUuid);

        if (petBedMode == 1 || petBedMode == 2) {
            // Skip Y-offset if DogPoseRenderHandler already applies it
            // (DOG/HUMAN_CHAIR pose uses the same offset amount)
            if (!isDogOrChairPose(player)) {
                event
                    .getPoseStack()
                    .translate(0, RenderConstants.DOG_AND_PETBED_Y_OFFSET, 0);
            }
        }
        if (petBedMode == 2) {
            // SLEEP: force STANDING pose to prevent vanilla sleeping rotation
            player.setForcedPose(net.minecraft.world.entity.Pose.STANDING);

            // Compensate for vanilla sleeping Y offset
            player
                .getSleepingPos()
                .ifPresent(pos -> {
                    double yOffset = player.getY() - pos.getY();
                    if (yOffset > 0.01) {
                        event.getPoseStack().translate(0, -yOffset, 0);
                    }
                });
        }
    }

    /**
     * Check if the player is in DOG or HUMAN_CHAIR pose.
     * Used to avoid double Y-offset with DogPoseRenderHandler.
     */
    private static boolean isDogOrChairPose(Player player) {
        PlayerBindState state = PlayerBindState.getInstance(player);
        if (state == null) return false;
        ItemStack bind = state.getEquipment(BodyRegionV2.ARMS);
        if (
            bind.isEmpty() || !(bind.getItem() instanceof ItemBind itemBind)
        ) return false;
        PoseType pose = HumanChairHelper.resolveEffectivePose(
            itemBind.getPoseType(),
            bind
        );
        return pose == PoseType.DOG || pose == PoseType.HUMAN_CHAIR;
    }

    /**
     * After player render: Restore forced pose for pet bed SLEEP mode.
     */
    @SubscribeEvent
    public static void onRenderPlayerPost(RenderPlayerEvent.Post event) {
        Player player = event.getEntity();
        if (!(player instanceof AbstractClientPlayer)) {
            return;
        }

        byte petBedMode = PetBedClientState.get(player.getUUID());
        if (petBedMode == 2) {
            player.setForcedPose(null);
        }
    }
}
