const { Client, GatewayIntentBits, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js');
const fs = require('fs');
const axios = require('axios');
require('dotenv').config();

// Add this at the top of your file
console.log('Starting bot...');

const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent
    ]
});

// Add this just before the login call
console.log('Attempting to log in...');

client.once('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.login(process.env.BOT_TOKEN).then(() => {
    console.log('Login successful');
}).catch(error => {
    console.error('Login failed:', error);
});

// Read the users.json file
const rawData = fs.readFileSync('users.json');
const rawUsers = JSON.parse(rawData);

// Remove user_id and player_id from each user object
const users = rawUsers.map(({ user_id, player_id, ...rest }) => rest);

// Now you can use the users array in your bot logic
console.log(`Loaded ${users.length} users`);

async function findUserByUsername(username) {
  try {
    const response = await axios.get(`https://www.vrbattles.gg/api/get_player_data_by_username/${username}`);
    return response.data;
  } catch (error) {
    console.error('Error fetching user data:', error);
    return null;
  }
}

function getBadgeImageUrl(badgeName) {
  badgeName = badgeName.toUpperCase().replace(/ /g, '_');
  let badgeUrl = 'assets/images/badges/xp_badges/';

  if (badgeName.startsWith('BADGE_A')) {
    badgeUrl += 'A/';
  } else if (badgeName.startsWith('BADGE_B')) {
    badgeUrl += 'B/';
  } else if (badgeName.startsWith('BADGE_C')) {
    badgeUrl += 'C/';
  } else {
    // Default to 'A' if badge name doesn't match the expected format
    badgeUrl += 'A/';
  }

  badgeUrl += `BADGE_${badgeName}_72p.png`;
  console.log(badgeUrl);
  return badgeUrl;
}

client.on('interactionCreate', async interaction => {
  if (!interaction.isCommand()) return;

  const { commandName } = interaction;

  if (commandName === 'ping') {
    await interaction.reply('Pong!');
  } else if (commandName === 'finduser') {
    const username = interaction.options.getString('username');
    
    await interaction.deferReply();

    const userData = await findUserByUsername(username);
    if (userData && userData.success) {
      let playerData;
      try {
        playerData = JSON.parse(userData.player_data);
      } catch (error) {
        await interaction.editReply('Error parsing player data.');
        return;
      }

      if (!playerData || !playerData.profile) {
        await interaction.editReply('User found but profile data is null. They need to log in to VRBattles to update their profile.');
        return;
      }

      const user = playerData.profile;
      const badgeImageUrl = getBadgeImageUrl(user.current_level_badge);

      const embed = new EmbedBuilder()
        .setTitle(`User: ${playerData.username}`)
        .setDescription(`Bio: ${user.bio || 'No bio available'}`)
        .addFields(
          { name: 'Country', value: user.country || 'Unknown', inline: true },
          { name: 'Rank', value: user.rank || 'Unranked', inline: true },
          { name: 'Level', value: user.level.toString(), inline: true },
          { name: 'Prestige', value: user.prestige?.toString() || 'None', inline: true },
          { name: 'Current Level Badge', value: user.current_level_badge || 'None', inline: true },
          { name: 'XP', value: user.xp.toString(), inline: true }
        )
        .setImage(badgeImageUrl)
        .setColor('#0099ff');

      if (user.avatar) {
        embed.setThumbnail(`https://www.vrbattles.gg/assets/uploads/profile/${user.avatar}`);
      }

      const row = new ActionRowBuilder()
        .addComponents(
          new ButtonBuilder()
            .setLabel('🔵 View Profile')
            .setStyle(ButtonStyle.Link)
            .setURL(`https://www.vrbattles.gg/profile/${playerData.username}`),
          new ButtonBuilder()
            .setLabel('🟡 Join Discord')
            .setStyle(ButtonStyle.Link)
            .setURL('https://discord.gg/j3DKVATPGQ') // Replace with your Discord invite URL
        );

      await interaction.editReply({ embeds: [embed], components: [row] });
    } else {
      await interaction.editReply('User not found or error occurred while fetching data.');
    }
  }
});

// Use the bot token here
client.login(process.env.BOT_TOKEN);