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

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.state.PlayerBindState;
import com.tiedup.remake.v2.BodyRegionV2;
import com.tiedup.remake.v2.bondage.capability.V2EquipmentHelper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.client.event.RenderHandEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

/**
 * Hide first-person hand/item rendering based on bondage state.
 *
 * <p>Behavior:</p>
 * <ul>
 *   <li><b>Tied up</b> (legacy V1 state): hide hands completely — hands are behind back</li>
 *   <li><b>Mittens</b> (legacy V1 item): hide hands + items (Forge limitation: RenderHandEvent
 *       controls hand + item together)</li>
 *   <li><b>V2 item in HANDS or ARMS region</b>: hide hands + items. An armbinder, handcuffs,
 *       gloves, or any item whose {@link com.tiedup.remake.v2.bondage.IV2BondageItem} declares
 *       HANDS/ARMS as an occupied or blocked region triggers this. Artists don't need to do
 *       anything special — declaring the region in the item JSON is enough.</li>
 * </ul>
 *
 * <p>This is the pragmatic alternative to rendering the full GLB item in first-person
 * (audit P1-05): the user decided that a player whose arms are restrained shouldn't see
 * their arms at all, matching the third-person silhouette where the arms are bound.</p>
 */
@OnlyIn(Dist.CLIENT)
@Mod.EventBusSubscriber(
    modid = TiedUpMod.MOD_ID,
    bus = Mod.EventBusSubscriber.Bus.FORGE,
    value = Dist.CLIENT
)
public class FirstPersonHandHideHandler {

    @SubscribeEvent
    public static void onRenderHand(RenderHandEvent event) {
        Minecraft mc = Minecraft.getInstance();
        if (mc == null) {
            return;
        }
        LocalPlayer player = mc.player;

        if (player == null) {
            return;
        }

        PlayerBindState state = PlayerBindState.getInstance(player);
        if (state != null && (state.isTiedUp() || state.hasMittens())) {
            // Legacy V1 state or item.
            event.setCanceled(true);
            return;
        }

        // V2: any item occupying or blocking HANDS/ARMS hides both arms in first-person.
        // isRegionBlocked includes the blocked-regions whitelist from equipped items,
        // so an armbinder on ARMS that also blocks HANDS hides both even if the HANDS
        // slot itself is empty.
        if (
            V2EquipmentHelper.isRegionOccupied(player, BodyRegionV2.HANDS) ||
            V2EquipmentHelper.isRegionOccupied(player, BodyRegionV2.ARMS) ||
            V2EquipmentHelper.isRegionBlocked(player, BodyRegionV2.HANDS) ||
            V2EquipmentHelper.isRegionBlocked(player, BodyRegionV2.ARMS)
        ) {
            event.setCanceled(true);
        }
    }
}
