radiation:
  levels:
    "1":
      duration: 200
      amplifier: 1
      effects:
        - POISON
      degrade_factor: 1
    "2":
      duration: 200
      amplifier: 2
      effects:
        - POISON
        - CONFUSION
      degrade_factor: 2
    "3":
      duration: 200
      amplifier: 3
      effects:
        - POISON
        - CONFUSION
        - BLINDNESS
      degrade_factor: 3
    "4":
      duration: 200
      amplifier: 4
      effects:
        - POISON
        - CONFUSION
        - BLINDNESS
        - WEAKNESS
      degrade_factor: 4
    "5":
      duration: 200
      amplifier: 5
      effects:
        - POISON
        - CONFUSION
        - BLINDNESS
        - WEAKNESS
        - WITHER
      degrade_factor: 5

nuclear_storm:
  duration: 6000  # Длительность бури в тиках (5 минут)
  mutant_spawn_interval: 100  # Интервал спавна мутантов во время бури
  mutant_spawn_count: 30  # Количество мутантов, спаунящихся за раз

rad_zone:
  random_spawn_interval: 7200  # Интервал случайного появления радиационных зон
  min_level: 3  # Минимальный уровень радиации зоны
  max_level: 5  # Максимальный уровень радиации зоны
  min_decrease_interval: 2120  # Минимальный интервал уменьшения уровня зоны (в секундах)
  max_decrease_interval: 7200  # Максимальный интервал уменьшения уровня зоны (в секундах)

name: RadiationPlugin
version: 1.0
main: com.yourpackage.RadiationPlugin
api-version: 1.20
commands:
  radiationzone:
    description: Управление радиационными зонами
    usage: /radiationzone <create|delete|list|info> [args]
    permission: radiationplugin.radiationzone
  radiationcheck:
    description: Проверить уровень радиации
    usage: /radiationcheck
    permission: radiationplugin.radiationcheck
  startnuclearstorm:
    description: Запуск ядерной бури (только для администраторов)
    usage: /startnuclearstorm
    permission: radiationplugin.startnuclearstorm
    permission-message: "У вас нет прав для выполнения этой команды."
permissions:
  radiationplugin.radiationzone:
    description: Позволяет управлять радиационными зонами
    default: op
  radiationplugin.radiationcheck:
    description: Позволяет проверять уровень радиации
    default: true
  radiationplugin.startnuclearstorm:
    description: Позволяет запускать ядерную бурю
    default: op

package com.yourpackage;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Particle;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.attribute.Attribute;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.*;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.event.Listener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.PlayerItemConsumeEvent;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;

import java.util.*;
import java.util.stream.Collectors;

public class RadiationPlugin extends JavaPlugin implements CommandExecutor, TabCompleter, Listener {

    // Map to store active Radiation Zones by their name
    private final Map<String, RadiationZone> zones = new HashMap<>();

    // Map to store radiation levels per player
    private final Map<UUID, Integer> radiationLevels = new HashMap<>();

    private final Random random = new Random();

    private FileConfiguration config;

    @Override
    public void onEnable() {
        // Save default configuration if not present
        saveDefaultConfig();
        config = getConfig();

        // Register commands
        getCommand("radiationzone").setExecutor(this);
        getCommand("radiationzone").setTabCompleter(this);
        getCommand("radiationcheck").setExecutor(this);

        // Register event listeners
        getServer().getPluginManager().registerEvents(this, this);

        // Start the random radiation zone spawner
        startRandomRadiationZoneSpawner();

        // Register crafting recipes
        registerRecipes();

        getLogger().info("RadiationPlugin включен!");
    }

    @Override
    public void onDisable() {
        // Force end all radiation zones
        for (RadiationZone zone : zones.values()) {
            zone.forceEndZone();
        }
        zones.clear();

        getLogger().info("RadiationPlugin выключен!");
    }

    /**
     * Register custom crafting recipes for radiation equipment and items.
     */
    private void registerRecipes() {
        // Create the Filter item
        ItemStack filter = createCustomItem(Material.PAPER, ChatColor.AQUA + "Фильтр", null);

        NamespacedKey filterKey = new NamespacedKey(this, "filter");
        ShapedRecipe filterRecipe = new ShapedRecipe(filterKey, filter);
        filterRecipe.shape(" C ", "WPW", " C ");
        filterRecipe.setIngredient('C', Material.CHARCOAL);
        filterRecipe.setIngredient('W', Material.WHITE_WOOL);
        filterRecipe.setIngredient('P', Material.PAPER);
        Bukkit.addRecipe(filterRecipe);

        // Create the Antidote
        ItemStack antidote = createCustomItem(Material.POTION, ChatColor.GOLD + "Антидот", null);
        PotionMeta antidoteMeta = (PotionMeta) antidote.getItemMeta();
        if (antidoteMeta != null) {
            antidoteMeta.setColor(Color.LIME);
            antidoteMeta.addCustomEffect(new PotionEffect(PotionEffectType.HEAL, 1, 1), true);
            antidote.setItemMeta(antidoteMeta);
        }

        NamespacedKey antidoteKey = new NamespacedKey(this, "antidote");
        ShapelessRecipe antidoteRecipe = new ShapelessRecipe(antidoteKey, antidote);
        antidoteRecipe.addIngredient(Material.HONEY_BOTTLE);
        antidoteRecipe.addIngredient(Material.SPIDER_EYE);
        antidoteRecipe.addIngredient(new RecipeChoice.ExactChoice(filter)); // Add Filter to recipe
        Bukkit.addRecipe(antidoteRecipe);

        // Create Radiation Boots
        ItemStack radBoots = createCustomItem(Material.LEATHER_BOOTS, ChatColor.GREEN + "Радиационные ботинки", null);
        NamespacedKey radBootsKey = new NamespacedKey(this, "radiation_boots");
        ShapedRecipe radBootsRecipe = new ShapedRecipe(radBootsKey, radBoots);
        radBootsRecipe.shape("F F", "F F", "   "); // Three rows, third is empty
        radBootsRecipe.setIngredient('F', new RecipeChoice.ExactChoice(filter));
        Bukkit.addRecipe(radBootsRecipe);

        // Create Radiation Leggings
        ItemStack radLeggings = createCustomItem(Material.LEATHER_LEGGINGS, ChatColor.GREEN + "Радиационные штаны", null);
        NamespacedKey radLeggingsKey = new NamespacedKey(this, "radiation_leggings");
        ShapedRecipe radLeggingsRecipe = new ShapedRecipe(radLeggingsKey, radLeggings);
        radLeggingsRecipe.shape("FFF", "F F", "   "); // Three rows, third is empty
        radLeggingsRecipe.setIngredient('F', new RecipeChoice.ExactChoice(filter));
        Bukkit.addRecipe(radLeggingsRecipe);

        // Create Protective Gloves
        ItemStack gloves = createCustomItem(Material.LEATHER_GLOVES, ChatColor.GREEN + "Защитные перчатки", null);
        NamespacedKey glovesKey = new NamespacedKey(this, "protective_gloves");
        ShapedRecipe glovesRecipe = new ShapedRecipe(glovesKey, gloves);
        glovesRecipe.shape("F F", " I ", "   "); // Three rows, third is empty
        glovesRecipe.setIngredient('F', new RecipeChoice.ExactChoice(filter));
        glovesRecipe.setIngredient('I', Material.IRON_INGOT);
        Bukkit.addRecipe(glovesRecipe);

        // Create Strong Antidote
        ItemStack strongAntidote = createCustomItem(Material.POTION, ChatColor.DARK_PURPLE + "Усиленный антидот", null);
        PotionMeta strongAntidoteMeta = (PotionMeta) strongAntidote.getItemMeta();
        if (strongAntidoteMeta != null) {
            strongAntidoteMeta.setColor(Color.PURPLE);
            strongAntidoteMeta.addCustomEffect(new PotionEffect(PotionEffectType.REGENERATION, 200, 1), true);
            strongAntidote.setItemMeta(strongAntidoteMeta);
        }

        NamespacedKey strongAntidoteKey = new NamespacedKey(this, "strong_antidote");
        ShapelessRecipe strongAntidoteRecipe = new ShapelessRecipe(strongAntidoteKey, strongAntidote);
        strongAntidoteRecipe.addIngredient(new RecipeChoice.ExactChoice(antidote));
        strongAntidoteRecipe.addIngredient(Material.GHAST_TEAR);
        Bukkit.addRecipe(strongAntidoteRecipe);

        // Note: Mutaционные предметы и соответствующие рецепты удалены.
    }

    /**
     * Helper method to create a custom item with name and lore.
     *
     * @param material Material of the item
     * @param name     Display name of the item
     * @param lore     Lore of the item (can be null)
     * @return Custom ItemStack
     */
    private ItemStack createCustomItem(Material material, String name, List<String> lore) {
        ItemStack item = new ItemStack(material);
        if (name != null || lore != null) {
            ItemMeta meta = item.getItemMeta();
            if (meta != null) {
                if (name != null) {
                    meta.setDisplayName(name);
                }
                if (lore != null) {
                    meta.setLore(lore);
                }
                meta.setUnbreakable(false); // Items should be breakable
                item.setItemMeta(meta);
            }
        }
        return item;
    }

    /**
     * Handle commands.
     */
    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {

        // Handle /radiationcheck
        if (command.getName().equalsIgnoreCase("radiationcheck")) {
            if (!sender.hasPermission("radiationplugin.radiationcheck")) {
                sender.sendMessage(ChatColor.RED + "У вас нет прав для выполнения этой команды.");
                return true;
            }

            if (!(sender instanceof Player)) {
                sender.sendMessage("Эта команда может использоваться только игроками.");
                return true;
            }

            Player player = (Player) sender;
            int radiationLevel = radiationLevels.getOrDefault(player.getUniqueId(), 0);
            player.sendMessage(ChatColor.YELLOW + "Ваш текущий уровень радиации: " + radiationLevel);
            return true;
        }

        // Handle /radiationzone
        if (command.getName().equalsIgnoreCase("radiationzone")) {
            if (!sender.hasPermission("radiationplugin.radiationzone")) {
                sender.sendMessage(ChatColor.RED + "У вас нет прав для выполнения этой команды.");
                return true;
            }

            if (!(sender instanceof Player)) {
                sender.sendMessage("Эта команда может использоваться только игроками.");
                return true;
            }

            Player player = (Player) sender;

            if (args.length == 0) {
                player.sendMessage(ChatColor.RED + "Использование: /radiationzone <create|delete|list|info> [args]");
                return true;
            }

            switch (args[0].toLowerCase()) {
                case "create":
                    return handleCreateZone(player, args);
                case "delete":
                    return handleDeleteZone(player, args);
                case "list":
                    return handleListZones(player);
                case "info":
                    return handleInfoZone(player, args);
                default:
                    player.sendMessage(ChatColor.RED + "Неверная подкоманда. Используйте: create, delete, list, info");
                    return true;
            }
        }

        // Unhandled command
        return false;
    }

    /**
     * Handle the creation of a radiation zone.
     *
     * @param player Player executing the command
     * @param args   Command arguments
     * @return true
     */
    private boolean handleCreateZone(Player player, String[] args) {
        if (args.length != 10) { // radiationzone, create, 8 params
            player.sendMessage(ChatColor.RED + "Использование: /radiationzone create <min.x> <min.y> <min.z> <max.x> <max.y> <max.z> <level> <name> <decrease_interval (ticks)>");
            return true;
        }

        try {
            double minX = Double.parseDouble(args[1]);
            double minY = Double.parseDouble(args[2]);
            double minZ = Double.parseDouble(args[3]);
            double maxX = Double.parseDouble(args[4]);
            double maxY = Double.parseDouble(args[5]);
            double maxZ = Double.parseDouble(args[6]);
            int level = Integer.parseInt(args[7]);
            String name = args[8];
            int decreaseInterval = Integer.parseInt(args[9]);

            // Validate level
            int minLevel = config.getInt("rad_zone.min_level", 1);
            int maxLevel = config.getInt("rad_zone.max_level", 5);
            if (level < minLevel || level > maxLevel) {
                player.sendMessage(ChatColor.RED + "Уровень радиации должен быть между " + minLevel + " и " + maxLevel + ".");
                return true;
            }

            // Check if zone with same name exists
            if (zones.containsKey(name)) {
                player.sendMessage(ChatColor.RED + "Радиационная зона с таким названием уже существует.");
                return true;
            }

            // Create and store the zone
            RadiationZone zone = new RadiationZone(minX, minY, minZ, maxX, maxY, maxZ, level, name, decreaseInterval);
            zones.put(name, zone);
            zone.startRadiation();

            player.sendMessage(ChatColor.GREEN + "Радиационная зона '" + name + "' успешно создана.");

        } catch (NumberFormatException e) {
            player.sendMessage(ChatColor.RED + "Ошибка: убедитесь, что координаты, уровень и интервал указаны числом.");
            return true;
        } catch (Exception e) {
            player.sendMessage(ChatColor.RED + "Произошла непредвиденная ошибка при создании зоны.");
            e.printStackTrace();
            return true;
        }

        return true;
    }

    /**
     * Handle deletion of a radiation zone.
     *
     * @param player Player executing the command
     * @param args   Command arguments
     * @return true
     */
    private boolean handleDeleteZone(Player player, String[] args) {
        if (args.length != 2) { // radiationzone, delete, name
            player.sendMessage(ChatColor.RED + "Использование: /radiationzone delete <name>");
            return true;
        }

        String name = args[1];
        RadiationZone zone = zones.get(name);
        if (zone == null) {
            player.sendMessage(ChatColor.RED + "Радиационная зона с названием '" + name + "' не найдена.");
            return true;
        }

        zone.forceEndZone();
        zones.remove(name);
        player.sendMessage(ChatColor.GREEN + "Радиационная зона '" + name + "' успешно удалена.");
        return true;
    }

    /**
     * Handle listing all active radiation zones.
     *
     * @param player Player executing the command
     * @return true
     */
    private boolean handleListZones(Player player) {
        if (zones.isEmpty()) {
            player.sendMessage(ChatColor.YELLOW + "Нет активных радиационных зон.");
            return true;
        }

        player.sendMessage(ChatColor.GOLD + "Список активных радиационных зон:");
        for (String name : zones.keySet()) {
            player.sendMessage(ChatColor.GRAY + "- " + name);
        }
        return true;
    }

    /**
     * Handle displaying info about a specific radiation zone.
     *
     * @param player Player executing the command
     * @param args   Command arguments
     * @return true
     */
    private boolean handleInfoZone(Player player, String[] args) {
        if (args.length != 2) { // radiationzone, info, name
            player.sendMessage(ChatColor.RED + "Использование: /radiationzone info <name>");
            return true;
        }

        String name = args[1];
        RadiationZone zone = zones.get(name);
        if (zone == null) {
            player.sendMessage(ChatColor.RED + "Радиационная зона с названием '" + name + "' не найдена.");
            return true;
        }

        player.sendMessage(ChatColor.GOLD + "Информация о радиационной зоне '" + name + "':");
        player.sendMessage(ChatColor.WHITE + "Координаты: [" + zone.minX + ", " + zone.minY + ", " + zone.minZ + "] до [" + zone.maxX + ", " + zone.maxY + ", " + zone.maxZ + "]");
        player.sendMessage(ChatColor.WHITE + "Текущий уровень радиации: " + zone.getLevel());

        return true;
    }

    /**
     * Helper method to check if a player is wearing full radiation protection.
     *
     * @param player Player to check
     * @return true if player is wearing full protection, false otherwise
     */
    private boolean isWearingFullProtection(Player player) {
        PlayerInventory inv = player.getInventory();
        ItemStack helmet = inv.getHelmet();
        ItemStack chestplate = inv.getChestplate();
        ItemStack leggings = inv.getLeggings();
        ItemStack boots = inv.getBoots();
        ItemStack gloves = inv.getItemInOffHand(); // Assuming gloves are in off-hand; adjust as needed

        return isProtectiveItem(helmet, ChatColor.WHITE + "Противогаз") &&
                isProtectiveItem(chestplate, ChatColor.WHITE + "Химический костюм") &&
                isProtectiveItem(leggings, ChatColor.GREEN + "Радиационные штаны") &&
                isProtectiveItem(boots, ChatColor.GREEN + "Радиационные ботинки") &&
                isProtectiveItem(gloves, ChatColor.GREEN + "Защитные перчатки");
    }

    /**
     * Helper method to verify if an item is part of the radiation protection set.
     *
     * @param item ItemStack item
     * @param name Expected name of the protective item
     * @return true if item matches the name, false otherwise
     */
    private boolean isProtectiveItem(ItemStack item, String name) {
        if (item == null || !item.hasItemMeta() || !item.getItemMeta().hasDisplayName()) return false;
        String itemName = ChatColor.stripColor(item.getItemMeta().getDisplayName());
        String expectedName = ChatColor.stripColor(name);
        return itemName.equalsIgnoreCase(expectedName);
    }

    /**
     * Start spawning random radiation zones based on config settings.
     */
    private void startRandomRadiationZoneSpawner() {
        long interval = config.getLong("rad_zone.random_spawn_interval", 7200);

        Bukkit.getScheduler().runTaskTimer(this, () -> {
            double minX = random.nextDouble() * 16000 - 8000;
            double minY = 0;
            double minZ = random.nextDouble() * 16000 - 8000;
            double maxX = minX + random.nextInt(50) + 50;
            double maxY = 256;
            double maxZ = minZ + random.nextInt(50) + 50;
            int initialLevel = random.nextInt(config.getInt("rad_zone.max_level", 5) - config.getInt("rad_zone.min_level", 1) + 1) + config.getInt("rad_zone.min_level", 1);
            String zoneName = "РадЗона-" + System.currentTimeMillis();
            int decreaseInterval = random.nextInt(config.getInt("rad_zone.max_decrease_interval", 4800) - config.getInt("rad_zone.min_decrease_interval", 1200) + 1) + config.getInt("rad_zone.min_decrease_interval", 1200);

            // Validate coordinates if necessary (optional)

            // Create the radiation zone
            RadiationZone zone = new RadiationZone(minX, minY, minZ, maxX, maxY, maxZ, initialLevel, zoneName, decreaseInterval);
            zones.put(zoneName, zone);
            zone.startRadiation();

            Bukkit.broadcastMessage(ChatColor.GOLD + "Появилась новая радиационная зона: " + zoneName);

        }, interval, interval); // Initial delay: interval ticks, Repeat: interval ticks
    }

    /**
     * RadiationZone class handling radiation effects within a defined area.
     */
    private class RadiationZone {
        private final double minX, minY, minZ, maxX, maxY, maxZ;
        private int level;
        private final String name;
        private final int decreaseInterval;
        private BukkitTask task;

        public RadiationZone(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, int initialLevel, String name, int decreaseInterval) {
            this.minX = Math.min(minX, maxX);
            this.minY = Math.min(minY, maxY);
            this.minZ = Math.min(minZ, maxZ);
            this.maxX = Math.max(minX, maxX);
            this.maxY = Math.max(minY, maxY);
            this.maxZ = Math.max(minZ, maxZ);
            this.level = initialLevel;
            this.name = name;
            this.decreaseInterval = decreaseInterval;
        }

        /**
         * Get current radiation level of the zone.
         *
         * @return Current level
         */
        public int getLevel() {
            return level;
        }

        /**
         * Start applying radiation effects to players in the zone and decrease level over time.
         */
        public void startRadiation() {
            task = new BukkitRunnable() {
                @Override
                public void run() {
                    if (level <= 0) {
                        endZone();
                        return;
                    }

                    // Apply radiation effects to players in zone
                    for (Player player : Bukkit.getOnlinePlayers()) {
                        if (isInZone(player.getLocation())) {
                            // If player is spectator or creative, switch to survival
                            if (player.getGameMode() == GameMode.SPECTATOR || player.getGameMode() == GameMode.CREATIVE) {
                                player.setGameMode(GameMode.SURVIVAL);
                                player.sendMessage(ChatColor.RED + "Вы были переключены в режим выживания из-за радиационной зоны.");
                            }
                            applyRadiationEffects(player);
                        }
                    }

                    // Show particles in zone
                    showParticles();

                    // Decrease level
                    level--;

                    if (level > 0) {
                        Bukkit.broadcastMessage(ChatColor.YELLOW + "Уровень радиации в зоне '" + name + "' снизился до " + level);
                    }

                    if (level <= 0) {
                        Bukkit.broadcastMessage(ChatColor.GREEN + "Радиационная зона '" + name + "' больше не активна.");
                        endZone();
                    }

                }
            }.runTaskTimer(RadiationPlugin.this, 0L, decreaseInterval); // Initial delay: 0 ticks, Repeat: decreaseInterval ticks
        }

        /**
         * Force end the radiation zone.
         */
        public void forceEndZone() {
            if (task != null) {
                task.cancel();
            }
            endZone();
        }

        /**
         * End the radiation zone by removing from zones map and cancelling tasks.
         */
        private void endZone() {
            zones.remove(name);
            if (task != null) {
                task.cancel();
            }
        }

        /**
         * Check if a location is inside this radiation zone.
         */
        private boolean isInZone(Location loc) {
            return loc.getX() >= minX && loc.getX() <= maxX &&
                    loc.getY() >= minY && loc.getY() <= maxY &&
                    loc.getZ() >= minZ && loc.getZ() <= maxZ;
        }

        /**
         * Show particles within the zone (for visualization).
         */
        private void showParticles() {
            World world = Bukkit.getWorlds().get(0); // Use the first world; adjust if multiple worlds
            if (world == null) return;

            // Display particles at regular intervals for visualization (optional)
            double particleDensity = 50; // Average distance between particles
            for (double x = minX; x <= maxX; x += particleDensity) {
                for (double z = minZ; z <= maxZ; z += particleDensity) {
                    double y = world.getHighestBlockYAt((int) x, (int) z) + 1;
                    Location loc = new Location(world, x, y, z);
                    world.spawnParticle(Particle.REDSTONE, loc, 10, 0.5, 0.5, 0.5, 0.05, new Particle.DustOptions(Color.GRAY, 1f));
                }
            }
        }

        /**
         * Apply radiation effects to a player based on current level.
         */
        private void applyRadiationEffects(Player player) {
            UUID playerId = player.getUniqueId();
            int currentRadiation = radiationLevels.getOrDefault(playerId, 0);

            if (isWearingFullProtection(player)) {
                // Player has full protection, skip effects
                return;
            }

            if (level > 0) {
                List<String> effectsList = config.getStringList("radiation.levels." + level + ".effects");
                int duration = config.getInt("radiation.levels." + level + ".duration", 200); // duration in ticks
                int amplifier = config.getInt("radiation.levels." + level + ".amplifier", 0); // amplifier

                for (String effectName : effectsList) {
                    PotionEffectType effectType = PotionEffectType.getByName(effectName);
                    if (effectType != null) {
                        PotionEffect effect = new PotionEffect(effectType, duration, amplifier);
                        player.addPotionEffect(effect, true); // true: override existing
                    } else {
                        getLogger().warning("PotionEffectType '" + effectName + "' не найден.");
                    }
                }

                // Increase player's radiation level
                radiationLevels.put(playerId, currentRadiation + level);
            }
        }
    }

    /**
     * Degrade player's equipment within the radiation zone.
     *
     * @param player Player whose equipment is to be degraded
     */
    private void degradePlayerEquipment(Player player) {
        PlayerInventory inventory = player.getInventory();
        ItemStack[] equipment = {
                inventory.getHelmet(),
                inventory.getChestplate(),
                inventory.getLeggings(),
                inventory.getBoots(),
                inventory.getItemInMainHand(),
                inventory.getItemInOffHand()
        };

        // Iterate over each piece of equipment
        for (ItemStack item : equipment) {
            if (item != null) {
                ItemMeta meta = item.getItemMeta();
                if (meta instanceof Damageable) {
                    Damageable damageable = (Damageable) meta;
                    int currentDamage = damageable.getDamage();
                    int degradationAmount = config.getInt("radiation.levels." + ((RadiationZone) zones.get(name)).getLevel() + ".degrade_factor", 1);
                    int newDamage = currentDamage + degradationAmount;
                    damageable.setDamage(newDamage);
                    item.setItemMeta(damageable); // Set the updated meta back to the item

                    // Check if item should break
                    if (newDamage >= item.getType().getMaxDurability()) {
                        String itemName = item.hasItemMeta() && item.getItemMeta().hasDisplayName()
                                ? item.getItemMeta().getDisplayName()
                                : item.getType().toString();

                        // Remove the item from inventory
                        if (item.equals(inventory.getItemInMainHand())) {
                            inventory.setItemInMainHand(null);
                        } else if (item.equals(inventory.getItemInOffHand())) {
                            inventory.setItemInOffHand(null);
                        } else {
                            // Iterate through inventory slots to remove the specific item
                            for (int i = 0; i < inventory.getSize(); i++) {
                                ItemStack invItem = inventory.getItem(i);
                                if (invItem != null && invItem.equals(item)) {
                                    inventory.setItem(i, null);
                                    break;
                                }
                            }
                        }

                        player.sendMessage(ChatColor.RED + "Ваш предмет '" + itemName + "' разрушился из-за радиации!");
                    }
                }
            }
        }
    }
}

1) Убераем все предметы кроме противогаза
2) Сделай, чтобы радиактивные зоны были постоянно. То каждую секунду - 2 секунды проверялось, если в обалсти радиации есть человек, то ему накладывается радиация + эффект. Чтобы не получать эффекты - нужен противогаз. И давай вот вместо уровней радиактивных зон, будет радиация. То есть например если радиация 100 - накладывается эффект радиации 1 уровня, если скольк-то то 2 уровня и тд. Улучши и напиши полнрый код