package de.viper.survivalplus.listeners;

import de.viper.survivalplus.SurvivalPlus;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.configuration.file.FileConfiguration;
import java.util.logging.Level;

public class InventoryClickListener implements Listener {
    private final SurvivalPlus plugin;

    public InventoryClickListener(SurvivalPlus plugin) {
        this.plugin = plugin;
    }

    @EventHandler
    public void onInventoryClick(InventoryClickEvent event) {
        FileConfiguration lang = plugin.getLangConfig();
        String guiTitle = event.getView().getTitle();
        String homeGuiTitle = lang.getString("homelist.gui-title", "Deine Homes");
        if (!guiTitle.equals(homeGuiTitle)) {
            plugin.getLogger().log(Level.FINE, "Ignoriere Klick in GUI mit Titel: " + guiTitle);
            return;
        }

        plugin.getLogger().log(Level.FINE, "Verarbeite Klick in Home-Liste GUI für Spieler: " + event.getWhoClicked().getName());
        event.setCancelled(true);
        if (!(event.getWhoClicked() instanceof Player) || event.getCurrentItem() == null) {
            return;
        }

        Player player = (Player) event.getWhoClicked();
        String homeName = event.getCurrentItem().getItemMeta().getDisplayName().replace("§a", "");
        String path = "homes." + player.getUniqueId() + "." + homeName.toLowerCase();

        FileConfiguration homes = plugin.getHomesConfig();
        if (!homes.contains(path)) {
            player.sendMessage(lang.getString("homelist.home-deleted", "§cDieses Home existiert nicht mehr!"));
            player.closeInventory();
            return;
        }

        String worldName = homes.getString(path + ".world");
        World world = plugin.getServer().getWorld(worldName);
        if (world == null) {
            player.sendMessage(lang.getString("homelist.world-not-found", "§cDie Welt dieses Homes existiert nicht!"));
            player.closeInventory();
            return;
        }

        Location loc = new Location(
            world,
            homes.getDouble(path + ".x"),
            homes.getDouble(path + ".y"),
            homes.getDouble(path + ".z"),
            (float) homes.getDouble(path + ".yaw"),
            (float) homes.getDouble(path + ".pitch")
        );

        player.teleport(loc);
        player.sendMessage(lang.getString("homelist.teleported", "§aZum Home %name% teleportiert!")
            .replace("%name%", homeName));
        player.closeInventory();
    }
}