const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { getLeaderboard, getXPProgress } = require('../../functions/xp/xp.js');
const { colors, emojis } = require('../../utils/constants');

module.exports = {
    category: 'xp',
    data: new SlashCommandBuilder()
        .setName('leaderboard')
        .setDescription('Affiche le classement des niveaux')
        .addIntegerOption(option =>
            option.setName('limit')
                .setDescription('Nombre d\'utilisateurs à afficher (par défaut: 10)')
                .setRequired(false)
                .setMinValue(1)
                .setMaxValue(25)),
    async execute(interaction) {
        await interaction.deferReply();
        
        const limit = interaction.options.getInteger('limit') || 10;
        const leaderboard = await getLeaderboard(interaction.guild.id, limit);
        
        if (leaderboard.length === 0) {
            return interaction.editReply({
                content: '❌ Aucun utilisateur trouvé dans le classement.'
            });
        }
        
        const leaderboardData = [];
        for (const user of leaderboard) {
            try {
                const member = await interaction.guild.members.fetch(user.userId).catch(() => null);
                if (member) {
                    leaderboardData.push({
                        user: member.user,
                        xp: user.xp,
                        level: user.level
                    });
                }
            } catch (err) { /* Ignorer */ }
        }
        
        const medals = ['🥇', '🥈', '🥉'];
        const description = leaderboardData.map((data, index) => {
            const medal = medals[index] || `\`${index + 1}.\``;
            const progress = getXPProgress(data.xp, data.level);
            return `${medal} **${data.user.displayName}** • ${emojis.level} Niveau \`${data.level}\` • ${emojis.xp} \`${data.xp.toLocaleString()} XP\` • \`${progress.percentage}%\``;
        }).join('\n');
        
        const embed = new EmbedBuilder()
            .setAuthor({ 
                name: interaction.guild.name, 
                iconURL: interaction.guild.iconURL({ dynamic: true }) || undefined 
            })
            .setTitle(`${emojis.leaderboard} Classement des Niveaux`)
            .setColor(colors.xp)
            .setDescription(description || 'Aucun utilisateur dans le classement')
            .setFooter({ 
                text: `Top ${limit} • ${interaction.guild.name}`, 
                iconURL: interaction.guild.iconURL({ dynamic: true }) || undefined 
            })
            .setTimestamp();
        
        await interaction.editReply({ embeds: [embed] });
    },
};