package com.playerblocklife;

import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerRespawnEvent;

import java.util.UUID;

public class PlayerJoinListener implements Listener {
    private final PlayerBlockLife plugin;

    public PlayerJoinListener(PlayerBlockLife plugin) {
        this.plugin = plugin;
    }

    @EventHandler(priority = EventPriority.NORMAL)
    public void onPlayerJoin(PlayerJoinEvent event) {
        Player player = event.getPlayer();
        UUID playerId = player.getUniqueId();

        // 异步加载玩家皮肤
        plugin.getSkinManager().loadPlayerSkinAsync(player);

        // 延迟发送消息，确保皮肤加载完成
        Bukkit.getScheduler().runTaskLater(plugin, () -> {
            int remainingBlocks = plugin.getBlockManager().getRemainingBlocks(playerId);

            if (remainingBlocks > 0) {
                player.sendMessage("§a========================================");
                player.sendMessage("§e欢迎回来，§6" + player.getName() + "§e！");
                player.sendMessage("§7你还有 §e" + remainingBlocks + " §7个生命方块");
                player.sendMessage("§7使用 §e/checklifeblocks §7查看方块位置");
                player.sendMessage("§a========================================");

                if (remainingBlocks <= 2) {
                    player.sendMessage("§c⚠ 警告！你的生命方块即将耗尽！");
                    player.playSound(player.getLocation(),
                            org.bukkit.Sound.ENTITY_WITHER_SPAWN, 0.5f, 1.0f);
                }
            } else {
                player.sendMessage("§e欢迎加入游戏！");
                player.sendMessage("§7使用 §e/setlifeblocks §7来设置你的生命方块");
                player.sendMessage("§6游戏规则：");
                player.sendMessage("§7- 每个玩家有5个生命方块");
                player.sendMessage("§7- 方块被其他玩家挖光时，你将死亡");
                player.sendMessage("§7- 方块使用你的皮肤作为材质");
                player.sendMessage("§7- 你可以自由移动，但方块固定位置");
            }
        }, 40L);
    }

    @EventHandler
    public void onPlayerRespawn(PlayerRespawnEvent event) {
        Player player = event.getPlayer();
        UUID playerId = player.getUniqueId();

        if (!plugin.getLifeSystem().isPlayerAlive(playerId)) {
            Bukkit.getScheduler().runTaskLater(plugin, () -> {
                if (player.isOnline()) {
                    player.setGameMode(GameMode.SPECTATOR);
                    player.sendMessage("§e你已被淘汰，可以观察其他玩家。");
                    player.sendMessage("§7等待下一轮游戏开始...");
                }
            }, 20L);
        }
    }
}