/*
 * Copyright (c) 2026 盐灯水母
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

package com.remains_cave.event;

import com.remains_cave.RemainsCaveMod;
import com.remains_cave.item.custom.*;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.Tag;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.event.entity.living.LivingDeathEvent;
import net.neoforged.neoforge.event.entity.living.LivingIncomingDamageEvent;
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
import net.neoforged.neoforge.event.tick.PlayerTickEvent;
import com.remains_cave.dungeon.room.RoomManager;

import static com.remains_cave.item.ModItems.BONE_STATELY_SPEED_MODIFIER;

@EventBusSubscriber(modid = RemainsCaveMod.MODID)
public class ModPlayerEvents {

    private static final int INTERVAL_TICKS = 240; // 12秒触发一次
    @SubscribeEvent
    public static void onLivingIncomingDamage(LivingIncomingDamageEvent event) {
        if (event.getEntity() instanceof Player player && !player.level().isClientSide) {
            ItemStack offhand = player.getOffhandItem();
            if (offhand.getItem() instanceof BonePauldronItem) {
                float damage = event.getAmount();
                // 原版盔甲耐久消耗规则：每 4 点伤害消耗 1 点耐久，至少 1 点
                int durabilityToConsume = Math.max(1, (int) Math.floor(damage / 4.0f));
                offhand.hurtAndBreak(durabilityToConsume, player, EquipmentSlot.OFFHAND);
            }
        }
    }
    @SubscribeEvent
    public static void onPlayerTick(PlayerTickEvent.Post event) {
        Player player = event.getEntity();

        if (player.level().isClientSide) {
            return;
        }

        // ===== 1.皇冠动态属性（每 tick 检查）=====
        ItemStack helmet = player.getInventory().getArmor(3); // 头盔槽
        boolean hasHelmet = helmet.getItem() instanceof BoneStatelyItem;
        AttributeInstance attackSpeedAttr = player.getAttribute(Attributes.ATTACK_SPEED);
        if (attackSpeedAttr != null) {
            boolean hasModifier = attackSpeedAttr.hasModifier(BONE_STATELY_SPEED_MODIFIER.id());
            if (hasHelmet) {
                float healthPercent = player.getHealth() / player.getMaxHealth();
                boolean shouldApply = healthPercent < 0.5f;
                if (shouldApply && !hasModifier) {
                    attackSpeedAttr.addTransientModifier(BONE_STATELY_SPEED_MODIFIER);
                } else if (!shouldApply && hasModifier) {
                    attackSpeedAttr.removeModifier(BONE_STATELY_SPEED_MODIFIER.id());
                }
            } else if (hasModifier) {
                attackSpeedAttr.removeModifier(BONE_STATELY_SPEED_MODIFIER.id());
            }
        }

        // ===== 2.咒殁权杖周期性光环 =====
        boolean hasDoomHood = helmet.getItem() instanceof DoomHoodItem;
        int auraInterval = hasDoomHood ? 80 : 240;

        if (player.tickCount % auraInterval == 0) {
            ItemStack mainHand = player.getMainHandItem();
            ItemStack offHand = player.getOffhandItem();
            if (mainHand.getItem() instanceof DoomStaffItem staff) {
                staff.applyAura(player);
            } else if (offHand.getItem() instanceof DoomStaffItem staff) {
                staff.applyAura(player);
            }
        }
    }

    @SubscribeEvent
    public static void onLivingDeath(LivingDeathEvent event) {
        if (event.getEntity() instanceof Player player && !player.level().isClientSide) {
            RoomManager roomManager = RoomManager.get(player.level());
            String roomId = roomManager.getRoomIdAt(player.blockPosition());
            if (roomId != null && (roomManager.getBossRooms().contains(roomId) || roomManager.getTombRooms().contains(roomId))) {
                // 保存物品栏
                ListTag inventoryList = new ListTag();
                player.getInventory().save(inventoryList);
                player.getPersistentData().put("SavedInventory", inventoryList);
                player.getPersistentData().putBoolean("NoDropOnDeath", true);

                // 保存经验值（总经验、等级、进度）
                int totalExp = player.totalExperience;
                player.getPersistentData().putInt("SavedTotalExperience", totalExp);
// 扣除全部经验（注意：传入负数）
                player.giveExperiencePoints(-totalExp);
                // 清空所有原版物品槽位
                player.getInventory().clearContent();
                for (int i = 0; i < player.getInventory().armor.size(); i++) {
                    player.getInventory().armor.set(i, ItemStack.EMPTY);
                }
                player.getInventory().offhand.set(0, ItemStack.EMPTY);
            }
        }
    }

    @SubscribeEvent
    public static void onPlayerClone(PlayerEvent.Clone event) {
        if (!event.getEntity().level().isClientSide && event.isWasDeath()) {
            Player original = event.getOriginal();
            Player newPlayer = event.getEntity();
            CompoundTag persistentData = original.getPersistentData();
            if (persistentData.getBoolean("NoDropOnDeath")) {
                // 恢复物品栏
                ListTag inventoryList = persistentData.getList("SavedInventory", Tag.TAG_COMPOUND);
                if (!inventoryList.isEmpty()) {
                    newPlayer.getInventory().load(inventoryList);
                }
                // 恢复经验值
                if (persistentData.contains("SavedTotalExperience")) {
                    int savedTotalExp = persistentData.getInt("SavedTotalExperience");
                    newPlayer.giveExperiencePoints(savedTotalExp);
                }
                // 清除临时标记
                persistentData.remove("NoDropOnDeath");
                persistentData.remove("SavedInventory");
                persistentData.remove("SavedTotalExperience");
            }
        }
    }
}