No chat to show

This project's files are all here to explore.

Files
src
build.gradle
README.md
settings.gradle
Code
6 242
src/main/java/com/customsmp/CustomSMP.java
package com.customsmp;

import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.command.*;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.*;
import org.bukkit.event.*;
import org.bukkit.event.block.*;
import org.bukkit.event.entity.*;
import org.bukkit.event.inventory.*;
import org.bukkit.event.player.*;
import org.bukkit.inventory.*;
import org.bukkit.inventory.meta.*;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

public final class CustomSMP extends JavaPlugin implements Listener, CommandExecutor, TabCompleter {
    private YamlConfiguration data;
    private File dataFile;
    private final NamespacedKey key;
    private final Map<UUID,UUID> tpa = new HashMap<>();
    private final Map<UUID,Long> combat = new HashMap<>(), cooldown = new HashMap<>();
    private final Map<UUID,UUID> duels = new HashMap<>();
    private final Set<UUID> duelParticipants = new HashSet<>();
    private final Map<String,Long> lastSpawnerTick = new HashMap<>();
    private final Random random = new Random();

    public CustomSMP() { key = new NamespacedKey(this, "customsmp"); }
    @Override public void onEnable() {
        saveDefaultConfig(); dataFile = new File(getDataFolder(), "data.yml");
        if (!dataFile.exists()) try { getDataFolder().mkdirs(); dataFile.createNewFile(); } catch (IOException e) { getLogger().severe(e.getMessage()); }
        data = YamlConfiguration.loadConfiguration(dataFile);
        getServer().getPluginManager().registerEvents(this, this);
        for (String cmd : List.of("balance","pay","shop","sell","ah","spawner","crate","customtool","sethome","home","spawn","setspawn","tpa","tpaccept","tpdeny","rtp","leaderboard","arena","kit","duel")) {
            Objects.requireNonNull(getCommand(cmd)).setExecutor(this); getCommand(cmd).setTabCompleter(this);
        }
        new BukkitRunnable(){ public void run(){ produceSpawners(); } }.runTaskTimer(this, 1200L, 1200L);
        getLogger().info("CustomSMP enabled.");
    }
    @Override public void onDisable(){ saveData(); }
    private void saveData(){ try { data.save(dataFile); } catch(IOException e){ getLogger().severe("Could not save data.yml: "+e.getMessage()); } }
    private double bal(UUID id){ return data.getDouble("balances."+id, getConfig().getDouble("starting-balance",1000)); }
    private void setBal(UUID id,double v){ data.set("balances."+id, Math.max(0,v)); saveData(); }
    private boolean take(UUID id,double amount){ if(!Double.isFinite(amount)||amount<=0||bal(id)<amount)return false; setBal(id,bal(id)-amount); return true; }
    private void give(UUID id,double amount){ if(Double.isFinite(amount)&&amount>0)setBal(id,bal(id)+amount); }
    private String money(double d){return String.format(Locale.US,"$%,.2f",d);}
    private void msg(CommandSender s,String m){s.sendMessage(ChatColor.GOLD+"[CustomSMP] "+ChatColor.RESET+m);}
    private Player player(CommandSender s){ if(s instanceof Player p)return p; msg(s,"Players only."); return null; }
    private ItemStack item(Material m,int amount,String name,String... lore){ ItemStack i=new ItemStack(m,Math.max(1,amount)); ItemMeta meta=i.getItemMeta(); if(name!=null)meta.setDisplayName(ChatColor.RESET+name); if(lore.length>0)meta.setLore(Arrays.asList(lore)); i.setItemMeta(meta); return i; }
    private void mark(ItemStack i,String value){ if(i==null||!i.hasItemMeta())return; ItemMeta m=i.getItemMeta();m.getPersistentDataContainer().set(key,PersistentDataType.STRING,value);i.setItemMeta(m); }
    private String marker(ItemStack i){return i!=null&&i.hasItemMeta()?i.getItemMeta().getPersistentDataContainer().get(key,PersistentDataType.STRING):null;}
    private Location loc(String path){ ConfigurationSection s=getConfig().getConfigurationSection(path); if(s==null)return Bukkit.getWorlds().get(0).getSpawnLocation(); World w=Bukkit.getWorld(s.getString("world",Bukkit.getWorlds().get(0).getName())); if(w==null)w=Bukkit.getWorlds().get(0);return new Location(w,s.getDouble("x"),s.getDouble("y"),s.getDouble("z"), (float)s.getDouble("yaw"),(float)s.getDouble("pitch")); }
    private void setLoc(String path,Location l){getConfig().set(path+".world",l.getWorld().getName());getConfig().set(path+".x",l.getX());getConfig().set(path+".y",l.getY());getConfig().set(path+".z",l.getZ());getConfig().set(path+".yaw",l.getYaw());getConfig().set(path+".pitch",l.getPitch());saveConfig();}
    private boolean safe(Location l){ if(l.getWorld()==null)return false; Block b=l.getBlock(), h=b.getRelative(0,1,0);return b.isPassable()&&h.isPassable()&&b.getRelative(0,-1,0).getType().isSolid()&&!b.isLiquid()&&!h.isLiquid(); }
    private boolean protectedSpawn(Location l){ if(!l.getWorld().getName().equalsIgnoreCase(getConfig().getString("spawn.world","world")))return false; Location s=loc("spawn");return l.distanceSquared(s)<=Math.pow(getConfig().getDouble("spawn-protection-radius",100),2); }
    private void openShop(Player p){ Inventory inv=Bukkit.createInventory(null,54,ChatColor.DARK_GREEN+"CustomSMP Shop"); ConfigurationSection prices=getConfig().getConfigurationSection("prices.shop"); if(prices!=null)for(String k:prices.getKeys(false)){Material m=Material.matchMaterial(k);if(m!=null)inv.addItem(item(m,1,ChatColor.GREEN+m.name().replace('_',' '),ChatColor.GRAY+"Buy: "+money(prices.getDouble(k)),ChatColor.YELLOW+"Click to buy"));} p.openInventory(inv); }
    private void openAH(Player p){Inventory inv=Bukkit.createInventory(null,54,ChatColor.DARK_AQUA+"Auction House");for(String id:data.getConfigurationSection("auctions") == null?Collections.<String>emptySet():data.getConfigurationSection("auctions").getKeys(false)){ItemStack stack=data.getItemStack("auctions."+id+".item");if(stack==null)continue;ItemStack view=stack.clone();ItemMeta m=view.getItemMeta();List<String> lore=m.hasLore()?new ArrayList<>(m.getLore()):new ArrayList<>();lore.add(ChatColor.GOLD+"Price: "+money(data.getDouble("auctions."+id+".price")));lore.add(ChatColor.GRAY+"Seller: "+data.getString("auctions."+id+".sellerName","Unknown"));lore.add(ChatColor.YELLOW+"Click to buy now");m.setLore(lore);view.setItemMeta(m);mark(view,"ah:"+id);inv.addItem(view);}p.openInventory(inv);}
    private void openCrate(Player p){Inventory inv=Bukkit.createInventory(null,27,ChatColor.LIGHT_PURPLE+"Crate Preview");ConfigurationSection rewards=getConfig().getConfigurationSection("crates.rewards.common"); if(rewards!=null)for(String k:rewards.getKeys(false)){String mat=rewards.getString(k+".material");Material m=Material.matchMaterial(mat==null?"STONE":mat);if(m!=null)inv.addItem(item(m,rewards.getInt(k+".amount",1),ChatColor.AQUA+m.name(),ChatColor.GRAY+"Weight: "+rewards.getInt(k+".weight",1)));} inv.setItem(22,item(Material.TRIPWIRE_HOOK,1,ChatColor.YELLOW+"Open crate",ChatColor.GRAY+"Requires a common key"));p.openInventory(inv);}
    private void giveSpawner(Player p,String type,int amount){Material m=Material.SPAWNER;ItemStack i=item(m,Math.min(64,amount),ChatColor.LIGHT_PURPLE+type+" Item Spawner",ChatColor.GRAY+"Place to generate items",ChatColor.YELLOW+"Type: "+type);mark(i,"spawner:"+type);p.getInventory().addItem(i).values().forEach(x->p.getWorld().dropItemNaturally(p.getLocation(),x));}
    private void giveTool(Player p,String type){Material m=type.equals("miner")?Material.DIAMOND_PICKAXE:type.equals("reaper")?Material.DIAMOND_SWORD:Material.DIAMOND_AXE;ItemStack i=item(m,1,ChatColor.AQUA+"Custom "+type,ChatColor.GRAY+(type.equals("miner")?"3x3 mining":type.equals("reaper")?"Heal on hit":"Chop nearby logs"));mark(i,"tool:"+type);p.getInventory().addItem(i);}
    private void requestDuel(Player a,Player b){duels.put(b.getUniqueId(),a.getUniqueId());msg(a,"Duel request sent to "+b.getName()+".");msg(b,a.getName()+" challenged you. Use /duel accept "+a.getName()+".");}
    private void startDuel(Player a,Player b){Location arena=loc("pvp.arena");Location aLoc=arena.clone().add(2,0,0),bLoc=arena.clone().add(-2,0,0); if(!safe(aLoc)||!safe(bLoc)){msg(a,"Arena spawn points are unsafe; configure pvp.arena.");return;} duelParticipants.add(a.getUniqueId());duelParticipants.add(b.getUniqueId());a.teleport(aLoc);b.teleport(bLoc);giveKit(a,"practice");giveKit(b,"practice");msg(a,"Duel started!");msg(b,"Duel started!");}
    private void giveKit(Player p,String kit){List<String> mats=getConfig().getStringList("pvp.kits."+kit);if(mats.isEmpty())mats=List.of("DIAMOND_SWORD","OBSIDIAN","END_CRYSTAL","END_CRYSTAL","GOLDEN_APPLE");for(String s:mats){Material m=Material.matchMaterial(s);if(m!=null)p.getInventory().addItem(new ItemStack(m));}}
    @Override public boolean onCommand(CommandSender s,Command c,String label,String[] a){String cmd=c.getName().toLowerCase(Locale.ROOT);Player p=player(s);if(p==null&&!cmd.equals("setspawn"))return true;
      switch(cmd){
        case "balance": msg(s,"Balance: "+money(bal(p.getUniqueId())));return true;
        case "pay": if(a.length!=2)return usage(s,"/pay <player> <amount>");Player t=Bukkit.getPlayerExact(a[0]);double amt=parse(a[1]);if(t==null||t==p||amt<=0||!take(p.getUniqueId(),amt)){msg(s,"Player, amount, or balance is invalid.");return true;}give(t.getUniqueId(),amt);msg(p,"Paid "+t.getName()+" "+money(amt));msg(t,"Received "+money(amt)+" from "+p.getName());return true;
        case "shop":openShop(p);return true;
        case "sell": if(a.length==1&&a[0].equalsIgnoreCase("hand")){sellHand(p);return true;}sellInventory(p);return true;
        case "ah": if(a.length==2&&a[0].equalsIgnoreCase("sell")){double price=parse(a[1]);ItemStack hand=p.getInventory().getItemInMainHand();if(hand.getType().isAir()||price<=0){msg(p,"Hold an item and use /ah sell <price>.");return true;}String id=UUID.randomUUID().toString();data.set("auctions."+id+".item",hand.clone());data.set("auctions."+id+".price",price);data.set("auctions."+id+".seller",p.getUniqueId().toString());data.set("auctions."+id+".sellerName",p.getName());p.getInventory().setItemInMainHand(null);saveData();msg(p,"Listed item for "+money(price));return true;}openAH(p);return true;
        case "spawner": if(a.length>=3&&a[0].equalsIgnoreCase("give")&&p.hasPermission("customsmp.admin")){giveSpawner(p,a[1].toUpperCase(),(int)parse(a[2]));return true;}msg(p,"Usage: /spawner give <zombie|skeleton|spider|blaze|iron|gold|diamond> <amount> (admin)");return true;
        case "crate": if(a.length>0&&a[0].equalsIgnoreCase("give")&&p.hasPermission("customsmp.admin")){int n=a.length>1?(int)parse(a[1]):1;p.getInventory().addItem(item(Material.TRIPWIRE_HOOK,n,ChatColor.YELLOW+"Common Crate Key"));return true;}openCrate(p);return true;
        case "customtool":if(p.hasPermission("customsmp.admin")&&a.length>0){giveTool(p,a[0].toLowerCase());return true;}msg(p,"Usage: /customtool <miner|reaper|lumber> (admin)");return true;
        case "sethome":data.set("homes."+p.getUniqueId(),serialize(p.getLocation()));saveData();msg(p,"Home set.");return true;
        case "home":if(!ready(p,"home-seconds"))return true;String hs=data.getString("homes."+p.getUniqueId());if(hs==null){msg(p,"Set a home first.");return true;}Location hl=deserialize(hs);if(hl!=null)p.teleport(hl);return true;
        case "spawn":p.teleport(loc("spawn"));return true;
        case "setspawn":if(s instanceof Player pl&&pl.hasPermission("customsmp.admin")){setLoc("spawn",pl.getLocation());msg(pl,"Spawn set.");}return true;
        case "tpa":if(a.length!=1)return usage(p,"/tpa <player>");Player dest=Bukkit.getPlayerExact(a[0]);if(dest==null||dest==p){msg(p,"Player not found.");return true;}tpa.put(dest.getUniqueId(),p.getUniqueId());msg(p,"Request sent.");msg(dest,p.getName()+" wants to teleport to you. /tpaccept or /tpdeny");return true;
        case "tpaccept":UUID req=tpa.remove(p.getUniqueId());if(req==null){msg(p,"No pending request.");return true;}Player requester=Bukkit.getPlayer(req);if(requester!=null){requester.teleport(p);msg(p,"Accepted.");}return true;
        case "tpdeny":tpa.remove(p.getUniqueId());msg(p,"Request denied.");return true;
        case "rtp":if(!ready(p,"rtp-seconds"))return true;World w=p.getWorld();for(int i=0;i<30;i++){int x=p.getLocation().getBlockX()+random.nextInt(2001)-1000,z=p.getLocation().getBlockZ()+random.nextInt(2001)-1000;int y=w.getHighestBlockYAt(x,z)+1;Location l=new Location(w,x+.5,y,z+.5);if(safe(l)&&!protectedSpawn(l)){p.teleport(l);msg(p,"Randomly teleported.");return true;}}msg(p,"Could not find a safe location. Try again.");return true;
        case "leaderboard":String type=a.length>0?a[0].toLowerCase():"money";List<String> ids=new ArrayList<>();ConfigurationSection section=data.getConfigurationSection(type.equals("money")?"balances":type.equals("kills")?"kills":type.equals("deaths")?"deaths":"spawner-count");if(section!=null)ids.addAll(section.getKeys(false));ids.sort((x,y)->Double.compare(data.getDouble((type.equals("money")?"balances":type.equals("kills")?"kills":type.equals("deaths")?"deaths":"spawner-count")+"."+y),data.getDouble((type.equals("money")?"balances":type.equals("kills")?"kills":type.equals("deaths")?"deaths":"spawner-count")+"."+x)));msg(p,"Top "+type+":");for(int i=0;i<Math.min(10,ids.size());i++){OfflinePlayer op=Bukkit.getOfflinePlayer(UUID.fromString(ids.get(i)));msg(p,(i+1)+". "+(op.getName()==null?ids.get(i):op.getName())+" — "+data.getDouble((type.equals("money")?"balances":type.equals("kills")?"kills":type.equals("deaths")?"deaths":"spawner-count")+"."+ids.get(i)));}return true;
        case "arena":if(p.hasPermission("customsmp.admin")&&a.length>0&&a[0].equalsIgnoreCase("set")){setLoc("pvp.arena",p.getLocation());msg(p,"Arena set.");}else msg(p,"/arena set (admin)");return true;
        case "kit":giveKit(p,a.length>0?a[0]:"practice");return true;
        case "duel":if(a.length==2&&a[0].equalsIgnoreCase("accept")){UUID id=duels.remove(p.getUniqueId());Player opponent=id==null?null:Bukkit.getPlayer(id);if(opponent==null||!opponent.getName().equalsIgnoreCase(a[1])){msg(p,"No matching duel request.");return true;}startDuel(opponent,p);return true;}if(a.length==1){Player opponent=Bukkit.getPlayerExact(a[0]);if(opponent!=null&&opponent!=p)requestDuel(p,opponent);else msg(p,"Player not found.");return true;}return usage(p,"/duel <player> or /duel accept <player>");
      }return false;
    }
    private boolean usage(CommandSender s,String text){msg(s,"Usage: "+text);return true;}
    private double parse(String s){try{return Double.parseDouble(s);}catch(Exception e){return -1;}}
    private boolean ready(Player p,String config){long now=System.currentTimeMillis(),last=cooldown.getOrDefault(p.getUniqueId(),0L);long sec=getConfig().getLong("cooldowns."+config,10);if(now-last<sec*1000){msg(p,"Wait "+((sec*1000-(now-last))/1000+1)+" seconds.");return false;}cooldown.put(p.getUniqueId(),now);return true;}
    private String serialize(Location l){return l.getWorld().getName()+","+l.getX()+","+l.getY()+","+l.getZ()+","+l.getYaw()+","+l.getPitch();}
    private Location deserialize(String s){try{String[] a=s.split(",");return new Location(Bukkit.getWorld(a[0]),Double.parseDouble(a[1]),Double.parseDouble(a[2]),Double.parseDouble(a[3]),Float.parseFloat(a[4]),Float.parseFloat(a[5]));}catch(Exception e){return null;}}
    private void sellHand(Player p){ItemStack i=p.getInventory().getItemInMainHand();double price=getConfig().getDouble("prices.sell."+i.getType().name(),0);if(price<=0||i.getType().isAir()){msg(p,"This item cannot be sold.");return;}give(p.getUniqueId(),price*i.getAmount());p.getInventory().setItemInMainHand(null);msg(p,"Sold for "+money(price*i.getAmount()));}
    private void sellInventory(Player p){double total=0;for(int slot=0;slot<p.getInventory().getStorageContents().length;slot++){ItemStack i=p.getInventory().getItem(slot);if(i==null)continue;double price=getConfig().getDouble("prices.sell."+i.getType().name(),0);if(price>0){total+=price*i.getAmount();p.getInventory().setItem(slot,null);}}if(total>0){give(p.getUniqueId(),total);msg(p,"Sold inventory items for "+money(total));}else msg(p,"No sellable items.");}
    private void produceSpawners(){ConfigurationSection sec=data.getConfigurationSection("placed-spawners");if(sec==null)return;for(String id:sec.getKeys(false)){String[] a=id.split(";");if(a.length!=4)continue;World w=Bukkit.getWorld(a[0]);if(w==null)continue;try{Location l=new Location(w,Integer.parseInt(a[1]),Integer.parseInt(a[2]),Integer.parseInt(a[3]));if(l.getBlock().getType()!=Material.SPAWNER)continue;String type=sec.getString(id+".type","ZOMBIE");int count=sec.getInt(id+".count",1);Material drop=spawnerDrop(type);int rate=getConfig().getInt("spawners.rates-per-minute."+type,1)*count;if(drop!=null&&rate>0)l.getWorld().dropItemNaturally(l.clone().add(.5,1,.5),new ItemStack(drop,Math.min(64,rate)));}catch(Exception ignored){}}}
    private Material spawnerDrop(String type){return switch(type){case "ZOMBIE"->Material.ROTTEN_FLESH;case "SKELETON"->Material.BONE;case "SPIDER"->Material.STRING;case "BLAZE"->Material.BLAZE_ROD;case "IRON"->Material.IRON_INGOT;case "GOLD"->Material.GOLD_INGOT;case "DIAMOND"->Material.DIAMOND;default->null;};}
    @EventHandler public void onPlace(BlockPlaceEvent e){String m=marker(e.getItemInHand());if(m!=null&&m.startsWith("spawner:")){String type=m.substring(8).toUpperCase();Location l=e.getBlockPlaced().getLocation();String id=l.getWorld().getName()+";"+l.getBlockX()+";"+l.getBlockY()+";"+l.getBlockZ();data.set("placed-spawners."+id+".type",type);data.set("placed-spawners."+id+".count",1);saveData();}}
    @EventHandler public void onInteract(PlayerInteractEvent e){if(e.getAction()!=Action.RIGHT_CLICK_BLOCK||e.getClickedBlock()==null)return;Block b=e.getClickedBlock();String id=b.getWorld().getName()+";"+b.getX()+";"+b.getY()+";"+b.getZ();if(data.contains("placed-spawners."+id)){String type=data.getString("placed-spawners."+id+".type");ItemStack hand=e.getItem();if(hand!=null&&Objects.equals(marker(hand),"spawner:"+type)){int count=data.getInt("placed-spawners."+id+".count",1);if(count<getConfig().getInt("spawners.max-stack",64)){data.set("placed-spawners."+id+".count",count+1);hand.setAmount(hand.getAmount()-1);saveData();e.getPlayer().sendMessage("Spawner stack: "+(count+1));e.setCancelled(true);}}}}
    @EventHandler public void onBreak(BlockBreakEvent e){if(protectedSpawn(e.getBlock().getLocation())&&!e.getPlayer().hasPermission("customsmp.admin")){e.setCancelled(true);return;}Location l=e.getBlock().getLocation();String id=l.getWorld().getName()+";"+l.getBlockX()+";"+l.getBlockY()+";"+l.getBlockZ();if(data.contains("placed-spawners."+id)){String type=data.getString("placed-spawners."+id+".type");int count=data.getInt("placed-spawners."+id+".count",1);data.set("placed-spawners."+id,null);e.setDropItems(false);giveSpawner(e.getPlayer(),type,count);saveData();}}
    @EventHandler public void onProtect(BlockPlaceEvent e){if(protectedSpawn(e.getBlock().getLocation())&&!e.getPlayer().hasPermission("customsmp.admin"))e.setCancelled(true);}
    @EventHandler public void onDamage(EntityDamageByEntityEvent e){if(e.getEntity() instanceof Player victim){Player attacker=e.getDamager() instanceof Player p?p:e.getDamager() instanceof Projectile pr&&pr.getShooter() instanceof Player p?p:null;if(attacker!=null){if(protectedSpawn(victim.getLocation())||protectedSpawn(attacker.getLocation())||!safeZoneAllowed(victim.getLocation())||!safeZoneAllowed(attacker.getLocation())){e.setCancelled(true);return;}combat.put(attacker.getUniqueId(),System.currentTimeMillis());combat.put(victim.getUniqueId(),System.currentTimeMillis());if(e.getDamager() instanceof EnderCrystal){e.setDamage(e.getDamage()*getConfig().getDouble("pvp.crystal-damage-multiplier",1));}if(duelParticipants.contains(attacker.getUniqueId())&&duelParticipants.contains(victim.getUniqueId())){e.setDamage(e.getDamage());}}}}
    private boolean safeZoneAllowed(Location l){for(Map<?,?> zone:getConfig().getMapList("pvp.safe-zones")){try{if(l.getWorld().getName().equals(zone.get("world"))){double x=((Number)zone.get("x")).doubleValue(),z=((Number)zone.get("z")).doubleValue(),r=((Number)zone.get("radius")).doubleValue();if((l.getX()-x)*(l.getX()-x)+(l.getZ()-z)*(l.getZ()-z)<=r*r)return false;}}catch(Exception ignored){}}return true;}
    @EventHandler public void onDeath(PlayerDeathEvent e){Player dead=e.getEntity();data.set("deaths."+dead.getUniqueId(),data.getInt("deaths."+dead.getUniqueId())+1);Player killer=dead.getKiller();if(killer!=null){data.set("kills."+killer.getUniqueId(),data.getInt("kills."+killer.getUniqueId())+1);give(killer.getUniqueId(),getConfig().getDouble("pvp.kill-reward",100));}if(duelParticipants.contains(dead.getUniqueId())){e.setKeepInventory(true);e.getDrops().clear();dead.setKeepLevel(true);dead.setExp(0);duelParticipants.remove(dead.getUniqueId());if(killer!=null)duelParticipants.remove(killer.getUniqueId());}if(combat.containsKey(dead.getUniqueId())&&System.currentTimeMillis()-combat.get(dead.getUniqueId())<getConfig().getLong("pvp.combat-tag-seconds",15)*1000){e.setKeepInventory(true);e.getDrops().clear();}saveData();}
    @EventHandler public void onQuit(PlayerQuitEvent e){if(combat.containsKey(e.getPlayer().getUniqueId())&&System.currentTimeMillis()-combat.get(e.getPlayer().getUniqueId())<getConfig().getLong("pvp.combat-tag-seconds",15)*1000){e.getPlayer().setHealth(0);}}
    @EventHandler public void onClick(InventoryClickEvent e){if(!(e.getWhoClicked() instanceof Player p))return;String title=e.getView().getTitle();if(title.equals(ChatColor.DARK_GREEN+"CustomSMP Shop")){e.setCancelled(true);ItemStack i=e.getCurrentItem();if(i==null)return;double price=getConfig().getDouble("prices.shop."+i.getType().name(),-1);if(price>0&&take(p.getUniqueId(),price)){p.getInventory().addItem(new ItemStack(i.getType()));msg(p,"Purchased for "+money(price));}else msg(p,"Insufficient funds or unavailable.");}else if(title.equals(ChatColor.DARK_AQUA+"Auction House")){e.setCancelled(true);String mark=marker(e.getCurrentItem());if(mark==null||!mark.startsWith("ah:"))return;String id=mark.substring(3);double price=data.getDouble("auctions."+id+".price");UUID seller;try{seller=UUID.fromString(data.getString("auctions."+id+".seller"));}catch(Exception ex){return;}if(seller.equals(p.getUniqueId())){msg(p,"You cannot buy your own listing.");return;}if(!take(p.getUniqueId(),price)){msg(p,"Insufficient funds.");return;}ItemStack stack=data.getItemStack("auctions."+id+".item");Player online=Bukkit.getPlayer(seller);if(online!=null)give(seller,price);else data.set("balances."+seller,bal(seller)+price);if(stack!=null)p.getInventory().addItem(stack);data.set("auctions."+id,null);saveData();p.closeInventory();msg(p,"Purchased for "+money(price));}else if(title.equals(ChatColor.LIGHT_PURPLE+"Crate Preview")){e.setCancelled(true);if(e.getRawSlot()==22){ItemStack keyItem=null;for(ItemStack i:p.getInventory().getContents())if(i!=null&&i.getType()==Material.TRIPWIRE_HOOK&&i.hasItemMeta()&&ChatColor.stripColor(i.getItemMeta().getDisplayName()).contains("Crate Key")){keyItem=i;break;}if(keyItem==null){msg(p,"You need a crate key.");return;}keyItem.setAmount(keyItem.getAmount()-1);ConfigurationSection rewards=getConfig().getConfigurationSection("crates.rewards.common");if(rewards==null)return;int total=0;for(String k:rewards.getKeys(false))total+=rewards.getInt(k+".weight",1);int roll=random.nextInt(Math.max(1,total));String chosen=null;for(String k:rewards.getKeys(false)){roll-=rewards.getInt(k+".weight",1);if(roll<0){chosen=k;break;}}if(chosen!=null){Material m=Material.matchMaterial(rewards.getString(chosen+".material","STONE"));if(m!=null)p.getWorld().dropItemNaturally(p.getLocation(),new ItemStack(m,rewards.getInt(chosen+".amount",1)));p.closeInventory();msg(p,"Crate opened!");}}}}
    @EventHandler public void onTool(PlayerInteractEvent e){ItemStack i=e.getItem();String m=marker(i);if(m==null||!m.startsWith("tool:"))return;String type=m.substring(5);if(type.equals("miner")&&e.getAction()==Action.LEFT_CLICK_BLOCK&&e.getClickedBlock()!=null){Block center=e.getClickedBlock();if(!center.getType().isBlock()||center.getType()==Material.BEDROCK)return;for(int x=-1;x<=1;x++)for(int y=-1;y<=1;y++)for(int z=-1;z<=1;z++){Block b=center.getRelative(x,y,z);if(b.getType().isSolid()&&b.getType()!=Material.BEDROCK){b.breakNaturally(i);}}}else if(type.equals("reaper")&&e.getAction().name().contains("LEFT_CLICK")&&e.getPlayer().getLastDamage()>0){e.getPlayer().setHealth(Math.min(e.getPlayer().getMaxHealth(),e.getPlayer().getHealth()+2));}else if(type.equals("lumber")&&e.getAction()==Action.LEFT_CLICK_BLOCK&&e.getClickedBlock()!=null){Block b=e.getClickedBlock();if(b.getType().name().endsWith("LOG")){for(int n=0;n<32;n++){Block above=b.getRelative(0,n,0);if(!above.getType().name().endsWith("LOG"))break;above.breakNaturally(i);}}}
    }
    @Override public List<String> onTabComplete(CommandSender s,Command c,String a,String[] args){if(c.getName().equalsIgnoreCase("spawner")&&args.length==1)return List.of("give");if(c.getName().equalsIgnoreCase("spawner")&&args.length==2)return List.of("zombie","skeleton","spider","blaze","iron","gold","diamond");if(c.getName().equalsIgnoreCase("customtool")&&args.length==1)return List.of("miner","reaper","lumber");if(c.getName().equalsIgnoreCase("leaderboard")&&args.length==1)return List.of("money","kills","deaths","spawners");return Collections.emptyList();}
}