package com.playerblocklife;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.ScoreboardManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * 游戏状态管理器 - PlayerBlockLife生存游戏模式的核心管理器
 * 
 * <p>主要功能包括：
 * <ul>
 *   <li>管理游戏状态（等待中/游戏中/已结束）</li>
 *   <li>为非OP玩家分配独特颜色的生命方块</li>
 *   <li>处理游戏开始时的生命方块生成</li>
 *   <li>控制游戏开始和结束逻辑</li>
 *   <li>管理实时计分板显示（游戏状态、剩余方块、限时等）</li>
 *   <li>处理游戏重置和玩家淘汰</li>
 *   <li>监控游戏结束条件（仅剩一名存活玩家或限时结束）</li>
 * </ul>
 * 
 * <p><b>游戏模式特性：</b>
 * <ul>
 *   <li>OP玩家始终处于观察者模式，不参与游戏</li>
 *   <li>非OP玩家在等待时处于冒险模式，手中持有对应颜色方块</li>
 *   <li>游戏开始后非OP玩家转为生存模式并清空背包</li>
 *   <li>使用不同颜色的羊毛、玻璃、水泥方块作为生命方块</li>
 *   <li>支持限时游戏模式</li>
 *   <li>游戏结束时显示胜利玩家</li>
 * </ul>
 * 
 * @author xiaobai
 * @version 2.2.0-1.20.4
 * @since 4.0.0
 */
public class GameStateManager {
    public enum GameState {
        WAITING,    // 等待开始
        STARTED,    // 游戏进行中
        FINISHED    // 游戏结束
    }

    private final PlayerBlockLife plugin;
    private GameState currentState = GameState.WAITING;
    private final Map<UUID, Material> playerColors = new HashMap<>(); // 玩家颜色分配
    private final Map<UUID, List<Location>> playerBlocks = new HashMap<>(); // 玩家方块位置
    private final List<UUID> alivePlayers = new ArrayList<>(); // 存活玩家
    private int gameDuration = 0; // 限时游戏持续时间（分钟）
    private long gameStartTime = 0; // 游戏开始时间戳
    private boolean isLimitedTime = false; // 是否为限时游戏
    private final ScoreboardManager scoreboardManager;
    private Scoreboard gameScoreboard;
    private Objective gameObjective;

    // 可用的羊毛、玻璃、水泥颜色
    private static final Material[] WOOL_COLORS = {
        Material.WHITE_WOOL, Material.ORANGE_WOOL, Material.MAGENTA_WOOL, Material.LIGHT_BLUE_WOOL,
        Material.YELLOW_WOOL, Material.LIME_WOOL, Material.PINK_WOOL, Material.GRAY_WOOL,
        Material.LIGHT_GRAY_WOOL, Material.CYAN_WOOL, Material.PURPLE_WOOL, Material.BLUE_WOOL,
        Material.BROWN_WOOL, Material.GREEN_WOOL, Material.RED_WOOL, Material.BLACK_WOOL
    };
    
    private static final Material[] GLASS_COLORS = {
        Material.WHITE_STAINED_GLASS, Material.ORANGE_STAINED_GLASS, Material.MAGENTA_STAINED_GLASS, Material.LIGHT_BLUE_STAINED_GLASS,
        Material.YELLOW_STAINED_GLASS, Material.LIME_STAINED_GLASS, Material.PINK_STAINED_GLASS, Material.GRAY_STAINED_GLASS,
        Material.LIGHT_GRAY_STAINED_GLASS, Material.CYAN_STAINED_GLASS, Material.PURPLE_STAINED_GLASS, Material.BLUE_STAINED_GLASS,
        Material.BROWN_STAINED_GLASS, Material.GREEN_STAINED_GLASS, Material.RED_STAINED_GLASS, Material.BLACK_STAINED_GLASS
    };
    
    private static final Material[] CONCRETE_COLORS = {
        Material.WHITE_CONCRETE, Material.ORANGE_CONCRETE, Material.MAGENTA_CONCRETE, Material.LIGHT_BLUE_CONCRETE,
        Material.YELLOW_CONCRETE, Material.LIME_CONCRETE, Material.PINK_CONCRETE, Material.GRAY_CONCRETE,
        Material.LIGHT_GRAY_CONCRETE, Material.CYAN_CONCRETE, Material.PURPLE_CONCRETE, Material.BLUE_CONCRETE,
        Material.BROWN_CONCRETE, Material.GREEN_CONCRETE, Material.RED_CONCRETE, Material.BLACK_CONCRETE
    };

    public GameStateManager(PlayerBlockLife plugin) {
        this.plugin = plugin;
        this.scoreboardManager = Bukkit.getScoreboardManager();
        createGameScoreboard();
    }

    private void createGameScoreboard() {
        this.gameScoreboard = scoreboardManager.getNewScoreboard();
        this.gameObjective = gameScoreboard.registerNewObjective("pbl_game", "dummy", ChatColor.GOLD + "PlayerBlockLife 游戏");
        this.gameObjective.setDisplaySlot(DisplaySlot.SIDEBAR);
        
        // 初始化计分板内容
        updateScoreboard();
    }

    public GameState getCurrentState() {
        return currentState;
    }

    public void setCurrentState(GameState state) {
        this.currentState = state;
        updateScoreboard();
        
        // 根据新状态更新玩家
        switch (state) {
            case WAITING:
                for (Player player : Bukkit.getOnlinePlayers()) {
                    if (player.isOp()) {
                        player.setGameMode(GameMode.SPECTATOR);
                    } else {
                        player.setGameMode(GameMode.ADVENTURE);
                        player.getInventory().clear();
                        giveColorBlockToPlayer(player);
                    }
                }
                break;
            case STARTED:
                // 游戏开始后，非OP玩家设置为生存模式并清空背包
                for (Player player : Bukkit.getOnlinePlayers()) {
                    if (!player.isOp()) {
                        player.setGameMode(GameMode.SURVIVAL);
                        player.getInventory().clear();
                        // 添加玩家到存活列表（如果他们有分配的颜色，意味着他们是参与者）
                        if (playerColors.containsKey(player.getUniqueId())) {
                            if (!alivePlayers.contains(player.getUniqueId())) {
                                alivePlayers.add(player.getUniqueId());
                            }
                        }
                    }
                }
                gameStartTime = System.currentTimeMillis();
                break;
            case FINISHED:
                // 游戏结束后，所有玩家设置为冒险模式
                for (Player player : Bukkit.getOnlinePlayers()) {
                    if (player.isOp()) {
                        player.setGameMode(GameMode.SPECTATOR);
                    } else {
                        player.setGameMode(GameMode.ADVENTURE);
                    }
                }
                break;
        }
    }

    /**
     * 分配玩家颜色
     */
    /**
     * 为玩家分配颜色
     * 
     * @param player 要分配颜色的玩家
     */
    public void assignPlayerColor(Player player) {
        if (playerColors.containsKey(player.getUniqueId())) {
            return; // 已分配颜色
        }

        // 如果所有颜色都已分配，将玩家设置为观察者模式
        if (playerColors.size() >= WOOL_COLORS.length) {
            player.setGameMode(GameMode.SPECTATOR);
            player.sendMessage(ChatColor.YELLOW + "所有颜色都已分配，您将作为观察者参与游戏。");
            return;
        }

        // 随机分配一个未使用的颜色
        List<Material> availableColors = new ArrayList<>();
        for (Material wool : WOOL_COLORS) {
            boolean isUsed = false;
            for (Material usedColor : playerColors.values()) {
                if (usedColor == wool) {
                    isUsed = true;
                    break;
                }
            }
            if (!isUsed) {
                availableColors.add(wool);
            }
        }

        if (!availableColors.isEmpty()) {
            Material selectedColor = availableColors.get(new Random().nextInt(availableColors.size()));
            playerColors.put(player.getUniqueId(), selectedColor);
            
            // 给玩家对应颜色的方块
            giveColorBlockToPlayer(player);
            
            String colorName = getMaterialColorName(selectedColor);
            player.sendMessage(ChatColor.GREEN + "您被分配了 " + ChatColor.AQUA + colorName + ChatColor.GREEN + " 颜色的生命方块！");
        }
    }

    /**
     * 给玩家对应颜色的方块
     */
    private void giveColorBlockToPlayer(Player player) {
        Material color = playerColors.get(player.getUniqueId());
        if (color != null) {
            player.getInventory().clear();
            player.getInventory().addItem(new org.bukkit.inventory.ItemStack(color, 1));
        }
    }

    /**
     * 获取材料的颜色名称
     */
    private String getMaterialColorName(Material material) {
        String name = material.name();
        if (name.contains("WHITE")) return "白色";
        if (name.contains("ORANGE")) return "橙色";
        if (name.contains("MAGENTA")) return "品红色";
        if (name.contains("LIGHT_BLUE")) return "淡蓝色";
        if (name.contains("YELLOW")) return "黄色";
        if (name.contains("LIME")) return "黄绿色";
        if (name.contains("PINK")) return "粉色";
        if (name.contains("GRAY")) return "灰色";
        if (name.contains("LIGHT_GRAY")) return "淡灰色";
        if (name.contains("CYAN")) return "青色";
        if (name.contains("PURPLE")) return "紫色";
        if (name.contains("BLUE")) return "蓝色";
        if (name.contains("BROWN")) return "棕色";
        if (name.contains("GREEN")) return "绿色";
        if (name.contains("RED")) return "红色";
        if (name.contains("BLACK")) return "黑色";
        return "未知";
    }

    /**
     * 为玩家生成生命方块
     */
    /**
     * 为玩家生成生命方块
     * 
     * @param player 要生成生命方块的玩家
     * @return 生成成功返回true，否则返回false
     */
    public boolean generateLifeBlocksForPlayer(Player player) {
        if (!playerColors.containsKey(player.getUniqueId()) || currentState != GameState.STARTED) {
            return false;
        }

        Material color = playerColors.get(player.getUniqueId());
        ConfigManager config = plugin.getConfigManager();
        int blockAmount = 5; // 使用固定值，因为配置已移除
        int spreadRange = 5; // 使用固定值，因为配置已移除
        
        List<Location> blocks = new ArrayList<>();
        int blocksPlaced = 0;
        int attempts = 0;
        Random random = new Random();
        
        // 尝试生成指定数量的方块
        while (blocksPlaced < blockAmount && attempts < 50) {
            Location center = player.getLocation();
            int x = random.nextInt(spreadRange * 2 + 1) - spreadRange;
            int z = random.nextInt(spreadRange * 2 + 1) - spreadRange;
            
            Location testLoc = center.clone().add(x, 0, z);
            World world = testLoc.getWorld();
            if (world == null) continue;
            
            // 从世界最高点向下寻找第一个固体方块
            int maxHeight = world.getMaxHeight();
            Block groundBlock = null;
            for (int y = maxHeight; y > world.getMinHeight(); y--) {
                testLoc.setY(y);
                Block block = testLoc.getBlock();
                Material type = block.getType();
                
                // 检查是否是固体方块（可以作为支撑）
                if (type.isSolid() && type.isBlock() && !type.isTransparent()) {
                    groundBlock = block;
                    break;
                }
            }
            
            if (groundBlock == null) {
                attempts++;
                continue;
            }
            
            // 地表位置 = 固体方块上方一格
            Location surfaceLoc = groundBlock.getLocation().add(0, 1, 0);
            
            // 检查是否已有方块
            if (isLifeBlock(surfaceLoc)) {
                attempts++;
                continue;
            }
            
            // 检查位置是否合适
            if (!isSuitableLocation(surfaceLoc)) {
                attempts++;
                continue;
            }
            
            // 放置方块
            surfaceLoc.getBlock().setType(color);
            blocks.add(surfaceLoc);
            blocksPlaced++;
            
            // 添加放置效果
            spawnPlaceEffects(surfaceLoc);
        }
        
        if (blocksPlaced > 0) {
            playerBlocks.put(player.getUniqueId(), blocks);
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * 检查位置是否适合放置生命方块
     */
    private boolean isSuitableLocation(Location location) {
        Block block = location.getBlock();
        
        // 检查是否已有方块
        if (isLifeBlock(location)) {
            return false;
        }
        
        // 检查方块是否可替换
        Material type = block.getType();
        if (!type.isAir()) {
            // 固体方块不能替换
            if (type.isSolid()) {
                return false;
            }
            
            // 液体方块不能替换
            if (type == Material.WATER || type == Material.LAVA) {
                return false;
            }
        }
        
        // 检查下方是否有支撑方块
        Block below = location.clone().add(0, -1, 0).getBlock();
        Material belowType = below.getType();
        
        if (belowType.isAir() || belowType == Material.WATER || belowType == Material.LAVA) {
            return false;
        }
        
        return true;
    }
    
    /**
     * 生成放置效果
     */
    private void spawnPlaceEffects(Location location) {
        if (location.getWorld() != null) {
            // 粒子效果
            location.getWorld().spawnParticle(org.bukkit.Particle.ENCHANTMENT_TABLE,
                    location.clone().add(0.5, 0.5, 0.5),
                    30, 0.3, 0.3, 0.3, 0.1);
            
            // 音效
            location.getWorld().playSound(location, org.bukkit.Sound.BLOCK_ANVIL_PLACE, 0.5f, 1.2f);
        }
    }
    
    /**
     * 检查是否为生命方块
     */
    private boolean isLifeBlock(Location location) {
        // 检查是否有任何玩家的方块在此位置
        for (List<Location> playerBlockList : playerBlocks.values()) {
            if (playerBlockList.contains(location)) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 移除被破坏的生命方块
     */
    /**
     * 移除被破坏的生命方块
     * 
     * @param location 方块位置
     * @param breaker 破坏方块的玩家
     * @return 移除成功返回true，否则返回false
     */
    public boolean removeBlock(Location location, Player breaker) {
        // 找到此位置属于哪个玩家的方块
        UUID ownerId = null;
        for (Map.Entry<UUID, List<Location>> entry : playerBlocks.entrySet()) {
            if (entry.getValue().contains(location)) {
                ownerId = entry.getKey();
                break;
            }
        }
        
        if (ownerId == null) {
            return false;
        }
        
        List<Location> blocks = playerBlocks.get(ownerId);
        if (blocks == null || !blocks.contains(location)) {
            return false;
        }
        
        // 移除方块
        blocks.remove(location);
        location.getBlock().setType(Material.AIR);
        
        // 生成破坏效果
        spawnBreakEffects(location, breaker);
        
        // 通知所有相关玩家
        notifyBlockBreak(ownerId, breaker, blocks.size());
        
        // 检查玩家是否还有剩余方块
        if (blocks.isEmpty()) {
            handlePlayerElimination(ownerId);
        }
        
        return true;
    }
    
    /**
     * 生成破坏效果
     */
    private void spawnBreakEffects(Location location, Player breaker) {
        if (location.getWorld() != null) {
            // 粒子效果
            location.getWorld().spawnParticle(org.bukkit.Particle.BLOCK_CRACK,
                    location.clone().add(0.5, 0.5, 0.5),
                    50, 0.5, 0.5, 0.5, 0.5, location.getBlock().getBlockData());
            
            location.getWorld().spawnParticle(org.bukkit.Particle.SMOKE_LARGE,
                    location.clone().add(0.5, 0.5, 0.5),
                    20, 0.3, 0.3, 0.3, 0.05);
            
            // 音效
            location.getWorld().playSound(location, org.bukkit.Sound.ENTITY_ITEM_BREAK, 1.0f, 0.8f);
            location.getWorld().playSound(location, org.bukkit.Sound.BLOCK_GLASS_BREAK, 0.8f, 1.0f);
            
            // 对挖掘者造成轻微击退
            if (breaker != null) {
                Location breakerLoc = breaker.getLocation();
                org.bukkit.util.Vector direction = location.toVector().subtract(breakerLoc.toVector()).normalize();
                breaker.setVelocity(direction.multiply(-0.5).setY(0.3));
            }
        }
    }
    
    /**
     * 通知方块被破坏
     */
    private void notifyBlockBreak(UUID ownerId, Player breaker, int remaining) {
        Player owner = Bukkit.getPlayer(ownerId);
        String ownerName = Bukkit.getOfflinePlayer(ownerId).getName();
        
        // 通知方块所有者
        if (owner != null && owner.isOnline()) {
            owner.sendMessage(ChatColor.RED + "⚠ 警告！你的生命方块被破坏了！");
            owner.sendMessage(ChatColor.GRAY + "破坏者: " + ChatColor.YELLOW + (breaker != null ? breaker.getName() : "未知"));
            owner.sendMessage(ChatColor.GRAY + "剩余生命方块: " + ChatColor.GREEN + String.valueOf(remaining) + " " + ChatColor.GRAY + "/ " + ChatColor.RED + 5);
            
            if (remaining <= 2) {
                owner.sendMessage(ChatColor.DARK_RED + "⚠ 警告！生命方块即将耗尽！");
            }
            
            // 播放警告音效
            owner.playSound(owner.getLocation(), org.bukkit.Sound.ENTITY_ENDERMAN_TELEPORT, 0.8f, 0.5f);
        }
        
        // 通知破坏者
        if (breaker != null && !breaker.getUniqueId().equals(ownerId)) {
            breaker.sendMessage(ChatColor.GOLD + "你破坏了一个生命方块！");
            breaker.sendMessage(ChatColor.GRAY + "所有者: " + ChatColor.YELLOW + (ownerName != null ? ownerName : "未知玩家"));
            breaker.sendMessage(ChatColor.GRAY + "对方剩余生命方块: " + ChatColor.GREEN + String.valueOf(remaining));
            
            // 给予挖掘者经验奖励
            breaker.giveExp(5);
            breaker.playSound(breaker.getLocation(), org.bukkit.Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 1.0f, 1.0f);
        }
        
        // 广播给附近玩家
        org.bukkit.World world = owner != null ? owner.getWorld() : (breaker != null ? breaker.getWorld() : null);
        if (world != null) {
            for (Player nearby : world.getPlayers()) {
                if (nearby != owner && nearby != breaker &&
                        nearby.getLocation().distance(owner != null ? owner.getLocation() : breaker.getLocation()) < 30) {
                    nearby.sendMessage(ChatColor.GRAY + "[附近] " + ChatColor.YELLOW + "一个生命方块被破坏了！");
                }
            }
        }
    }
    
    /**
     * 处理玩家淘汰
     */
    private void handlePlayerElimination(UUID playerId) {
        Player player = Bukkit.getPlayer(playerId);
        if (player == null || !player.isOnline()) {
            return;
        }
        
        player.setGameMode(GameMode.SPECTATOR);
        player.sendTitle(ChatColor.DARK_RED + "☠ 你被淘汰了！", ChatColor.RED + "所有生命方块已被挖光", 20, 100, 20);
        
        // 从存活玩家列表中移除
        alivePlayers.remove(playerId);
        
        // 检查是否只剩一名玩家
        checkGameEnd();
    }
    
    /**
     * 检查游戏是否结束
     */
    public void checkGameEnd() {
        // 如果限时游戏且时间到了
        if (isLimitedTime && gameStartTime > 0) {
            long currentTime = System.currentTimeMillis();
            long elapsedMinutes = (currentTime - gameStartTime) / (1000 * 60);
            
            if (elapsedMinutes >= gameDuration) {
                endGame();
                return;
            }
        }
        
        // 如果只剩一名玩家存活
        if (alivePlayers.size() <= 1) {
            endGame();
        }
    }
    
    /**
     * 结束游戏
     */
    private void endGame() {
        if (currentState != GameState.STARTED) {
            return;
        }
        
        setCurrentState(GameState.FINISHED);
        
        Player winner = null;
        if (!alivePlayers.isEmpty()) {
            winner = Bukkit.getPlayer(alivePlayers.get(0));
        }
        
        // 广播胜利消息
        for (Player player : Bukkit.getOnlinePlayers()) {
            if (winner != null) {
                player.sendTitle(ChatColor.GOLD + "🎉 恭喜！", ChatColor.YELLOW + winner.getName() + " 获得了胜利！", 10, 70, 20);
                player.sendMessage(ChatColor.GOLD + "🎉 游戏结束！" + ChatColor.YELLOW + winner.getName() + ChatColor.GOLD + " 获得了胜利！");
            } else {
                player.sendTitle(ChatColor.GOLD + "游戏结束！", ChatColor.YELLOW + "平局！", 10, 70, 20);
                player.sendMessage(ChatColor.GOLD + "游戏结束！没有获胜者！");
            }
        }
    }
    
    /**
     * 开始限时游戏
     */
    /**
     * 开始限时游戏
     * 
     * @param minutes 游戏限时（分钟）
     */
    public void startTimedGame(int minutes) {
        this.gameDuration = minutes;
        this.isLimitedTime = true;
        startGame();
    }
    
    /**
     * 开始游戏
     */
    public void startGame() {
        if (currentState != GameState.WAITING) {
            return;
        }
        
        setCurrentState(GameState.STARTED);
        
        // 为所有玩家生成生命方块
        for (UUID playerId : playerColors.keySet()) {
            Player player = Bukkit.getPlayer(playerId);
            if (player != null && player.isOnline() && !player.isOp()) { // 只为非OP玩家生成方块
                generateLifeBlocksForPlayer(player);
            }
        }
    }
    
    /**
     * 重置游戏
     */
    public void resetGame() {
        // 清空所有数据
        playerColors.clear();
        playerBlocks.clear();
        alivePlayers.clear();
        gameDuration = 0;
        isLimitedTime = false;
        gameStartTime = 0;
        
        // 将所有玩家恢复到适当模式，并重新分配颜色
        for (Player player : Bukkit.getOnlinePlayers()) {
            if (player.isOp()) {
                player.setGameMode(GameMode.SPECTATOR);
            } else {
                player.setGameMode(GameMode.ADVENTURE);
                player.getInventory().clear();
                // 重新分配颜色
                assignPlayerColor(player);
            }
        }
        
        setCurrentState(GameState.WAITING);
    }
    
    /**
     * 获取玩家剩余方块数量
     */
    /**
     * 获取玩家剩余方块数量
     * 
     * @param playerId 玩家UUID
     * @return 玩家剩余方块数量
     */
    public int getRemainingBlocks(UUID playerId) {
        List<Location> blocks = playerBlocks.get(playerId);
        return blocks != null ? blocks.size() : 0;
    }
    
    /**
     * 获取玩家颜色
     */
    /**
     * 获取玩家颜色
     * 
     * @param playerId 玩家UUID
     * @return 玩家的颜色材料
     */
    public Material getPlayerColor(UUID playerId) {
        return playerColors.get(playerId);
    }
    
    /**
     * 更新计分板
     */
    public void updateScoreboard() {
        if (gameObjective == null) {
            return;
        }
        
        // 清空现有计分板条目
        for (String entry : gameScoreboard.getEntries()) {
            gameScoreboard.resetScores(entry);
        }
        
        // 设置标题
        gameObjective.setDisplayName(ChatColor.GOLD + "PlayerBlockLife 游戏");
        
        // 添加内容
        int line = 1;
        String statusText = "";
        switch (currentState) {
            case WAITING:
                statusText = ChatColor.YELLOW + "等待中...";
                break;
            case STARTED:
                statusText = ChatColor.GREEN + "开始游戏";
                break;
            case FINISHED:
                statusText = ChatColor.RED + "游戏结束";
                break;
        }
        
        gameScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(ChatColor.WHITE + "").setScore(line++);
        gameScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(ChatColor.AQUA + "状态:").setScore(line++);
        gameScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(statusText).setScore(line++);
        
        // 如果是游戏中，显示剩余时间和玩家方块数
        if (currentState == GameState.STARTED) {
            gameScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(" ").setScore(line++);
            
            // 显示剩余时间（如果有限时）
            if (isLimitedTime) {
                long currentTime = System.currentTimeMillis();
                long elapsedMinutes = (currentTime - gameStartTime) / (1000 * 60);
                long remainingMinutes = Math.max(0, gameDuration - elapsedMinutes);
                
                gameScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(ChatColor.AQUA + "剩余时间:").setScore(line++);
                gameScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(ChatColor.YELLOW + String.valueOf(remainingMinutes) + "分钟").setScore(line++);
                gameScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore("  ").setScore(line++);
            }
            
            // 显示当前玩家剩余方块数
            gameScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(ChatColor.AQUA + "我的方块:").setScore(line++);
            // 这个会在PlayerJoinListener中根据每个玩家更新
        }
        
        gameScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore("   ").setScore(line++);
        gameScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(ChatColor.GRAY + "PlayerBlockLife v" + plugin.getDescription().getVersion()).setScore(line++);
        
        // 给在线玩家设置计分板
        for (Player player : Bukkit.getOnlinePlayers()) {
            player.setScoreboard(gameScoreboard);
        }
    }
    
    /**
     * 更新玩家特定的计分板信息
     */
    /**
     * 更新玩家特定的计分板信息
     * 
     * @param player 要更新计分板的玩家
     */
    public void updatePlayerScoreboard(Player player) {
        if (currentState == GameState.STARTED && gameObjective != null) {
            // 为特定玩家更新剩余方块数
            int remainingBlocks = getRemainingBlocks(player.getUniqueId());
            String blocksText = ChatColor.YELLOW + String.valueOf(remainingBlocks) + "/5";
            
            // 临时更新计分板，为特定玩家显示他们的剩余方块
            Scoreboard playerScoreboard = player.getScoreboard();
            if (playerScoreboard != gameScoreboard) {
                playerScoreboard = gameScoreboard;
            }
            
            // 为每个玩家创建一个自定义的计分板
            Scoreboard customScoreboard = scoreboardManager.getNewScoreboard();
            Objective customObjective = customScoreboard.registerNewObjective("pbl_player", "dummy", ChatColor.GOLD + "PlayerBlockLife 游戏");
            customObjective.setDisplaySlot(DisplaySlot.SIDEBAR);
            
            // 复制原始计分板内容
            int line = 1;
            String statusText = "";
            switch (currentState) {
                case WAITING:
                    statusText = ChatColor.YELLOW + "等待中...";
                    break;
                case STARTED:
                    statusText = ChatColor.GREEN + "开始游戏";
                    break;
                case FINISHED:
                    statusText = ChatColor.RED + "游戏结束";
                    break;
            }
            
            customScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(ChatColor.WHITE + "").setScore(line++);
            customScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(ChatColor.AQUA + "状态:").setScore(line++);
            customScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(statusText).setScore(line++);
            
            if (isLimitedTime) {
                long currentTime = System.currentTimeMillis();
                long elapsedMinutes = (currentTime - gameStartTime) / (1000 * 60);
                long remainingMinutes = Math.max(0, gameDuration - elapsedMinutes);
                
                customScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(" ").setScore(line++);
                customScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(ChatColor.AQUA + "剩余时间:").setScore(line++);
                customScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(ChatColor.YELLOW + String.valueOf(remainingMinutes) + "分钟").setScore(line++);
            }
            
            customScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore("  ").setScore(line++);
            customScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(ChatColor.AQUA + "我的方块:").setScore(line++);
            customScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(blocksText).setScore(line++);
            
            customScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore("   ").setScore(line++);
            customScoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(ChatColor.GRAY + "PlayerBlockLife v" + plugin.getDescription().getVersion()).setScore(line++);
            
            player.setScoreboard(customScoreboard);
        }
    }
    
    /**
     * 获取存活玩家数量
     */
    /**
     * 获取存活玩家数量
     * 
     * @return 存活玩家数量
     */
    public int getAlivePlayersCount() {
        return alivePlayers.size();
    }
    
    /**
     * 获取所有存活玩家
     */
    /**
     * 获取所有存活玩家
     * 
     * @return 存活玩家UUID列表
     */
    public List<UUID> getAlivePlayers() {
        return new ArrayList<>(alivePlayers);
    }
    
    /**
     * 获取所有玩家的方块位置
     */
    /**
     * 获取所有玩家的方块位置
     * 
     * @return 玩家UUID到方块位置列表的映射
     */
    public Map<UUID, List<Location>> getPlayerBlocks() {
        return new HashMap<>(playerBlocks);
    }
    
    /**
     * 清除指定玩家的方块
     */
    /**
     * 清除指定玩家的方块
     * 
     * @param playerId 要清除方块的玩家UUID
     */
    public void clearPlayerBlocks(UUID playerId) {
        List<Location> blocks = playerBlocks.remove(playerId);
        if (blocks != null) {
            for (Location loc : blocks) {
                if (loc.getWorld() != null) {
                    loc.getBlock().setType(org.bukkit.Material.AIR);
                }
            }
        }
        
        // 从存活玩家列表中移除
        alivePlayers.remove(playerId);
    }
    
    /**
     * 获取游戏持续时间（分钟）
     */
    /**
     * 获取游戏持续时间（分钟）
     * 
     * @return 游戏持续时间（分钟）
     */
    public int getGameDuration() {
        return gameDuration;
    }
    
    /**
     * 获取游戏开始时间戳
     */
    /**
     * 获取游戏开始时间戳
     * 
     * @return 游戏开始时间戳
     */
    public long getGameStartTime() {
        return gameStartTime;
    }
    
    /**
     * 检查是否为限时游戏
     */
    /**
     * 检查是否为限时游戏
     * 
     * @return 如果是限时游戏返回true，否则返回false
     */
    public boolean isLimitedTime() {
        return isLimitedTime;
    }
}