package com.tiedup.remake.core;

import com.tiedup.remake.entities.EntityMaster;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectCategory;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;

public class ChokeEffect extends MobEffect {

    private static final int AIR_DRAIN_PER_TICK = 8; // net -4 after vanilla +4 restoration

    public ChokeEffect() {
        super(MobEffectCategory.HARMFUL, 0x5C3317); // dark brown (leather)
    }

    @Override
    public void applyEffectTick(LivingEntity entity, int amplifier) {
        // Drain air (runs AFTER baseTick which restores +4)
        int air = entity.getAirSupply();
        int drain = AIR_DRAIN_PER_TICK + amplifier * 4;
        entity.setAirSupply(Math.max(-20, air - drain));

        // Darkness when air gets low
        if (air < 200 && entity.tickCount % 40 == 0) {
            entity.addEffect(
                new MobEffectInstance(MobEffects.DARKNESS, 60, 0, false, false)
            );
        }

        // Slowness in advanced phase
        if (air < 100 && entity.tickCount % 40 == 0) {
            entity.addEffect(
                new MobEffectInstance(
                    MobEffects.MOVEMENT_SLOWDOWN,
                    60,
                    0,
                    false,
                    false
                )
            );
        }

        // Damage when air exhausted (every 20 ticks)
        if (air <= 0 && entity.tickCount % 20 == 0) {
            // Non-lethal when used by Master (safety: pet cannot die from master's choke)
            boolean masterOwned =
                entity instanceof Player p &&
                EntityMaster.getMasterUUID(p) != null;
            if (masterOwned && entity.getHealth() <= 2.0f) {
                if (entity.getHealth() > 1.0f) {
                    entity.setHealth(1.0f);
                }
            } else {
                entity.hurt(entity.damageSources().generic(), 2.0f);
            }
        }

        // Sound every 20 ticks
        if (entity.tickCount % 20 == 0) {
            entity
                .level()
                .playSound(
                    null,
                    entity.getX(),
                    entity.getY(),
                    entity.getZ(),
                    SoundEvents.PLAYER_HURT,
                    SoundSource.PLAYERS,
                    0.6f,
                    0.5f + entity.getRandom().nextFloat() * 0.2f
                );
        }
    }

    @Override
    public boolean isDurationEffectTick(int duration, int amplifier) {
        return true; // tick every tick
    }
}
