const { SlashCommandBuilder, Interaction, EmbedBuilder, ActionRowBuilder, ButtonBuilder } = require('discord.js');
const voteMap = new Map(); // Stores vote counts and user IDs for each option

module.exports = {
  data: new SlashCommandBuilder()
    .setName('wouldyourather')
    .setDescription('Start a "Would you rather...?" poll anonymously')
    .addStringOption(option => option.setName('option1').setDescription('Enter the first option'))
    .addStringOption(option => option.setName('option2').setDescription('Enter the second option')), // Added input options
  async execute(interaction) {
    const option1 = interaction.options.getString('option1');
    const option2 = interaction.options.getString('option2');

    // Input Validation (Optional)
    if (!option1 || !option2) {
      return await interaction.reply({ content: 'Please provide both options for "Would you rather...?"', ephemeral: true });
    }

    const scenario = `**Would you rather...**\n1. ${option1}\n2. ${option2}`;

    // Check for existing scenario (to avoid duplicate polls)
    if (voteMap.has(scenario)) {
      return await interaction.reply({ content: 'This "Would you rather...?" scenario is already active!', ephemeral: true });
    }

    voteMap.set(scenario, { option1: [], option2: [] }); // Initialize vote counts and user IDs

    const embed = new EmbedBuilder()
      .setColor(0x00ffff)
      .setTitle('Would You Rather?')
      .setDescription(scenario);

    const buttonRow = new ActionRowBuilder()
    .addComponents(
      new ButtonBuilder().setCustomId('option1').setLabel(option1).setStyle('Primary'),
      new ButtonBuilder().setCustomId('option2').setLabel(option2).setStyle('Primary'),
    );
    await interaction.reply({ embeds: [embed], components: [buttonRow] });

    const message = await interaction.fetchReply(); // Get the message containing the embed and buttons

    const collector = message.createMessageComponentCollector({ time: 60000 }); // 1 minute timeout

    collector.on('collect', async (buttonInteraction) => {
      if (!buttonInteraction.isButton()) return;
      if (!buttonInteraction.data) { // Check for missing 'data' property
        console.log('Invalid button interaction: missing data');
        return;
    }

      if (!buttonInteraction.data.customId) { // Add this check
        return console.log('Invalid button interaction: customId missing');
    }
      const { customId } = buttonInteraction.data;

      const votes = voteMap.get(scenario);
      if (!votes) return; // Handle potential race condition (less likely)

      if (votes.option1.includes(buttonInteraction.user.id) || votes.option2.includes(buttonInteraction.user.id)) {
        return await buttonInteraction.reply({ content: 'You already voted!', ephemeral: true });
      }

      if (customId === 'option1') {
        votes.option1.push(buttonInteraction.user.id);
      } else if (customId === 'option2') {
        votes.option2.push(buttonInteraction.user.id);
      }

      voteMap.set(scenario, votes); // Update vote counts

      await buttonInteraction.deferUpdate(); // Acknowledge button interaction
    });

    collector.on('end', async () => {
      const votes = voteMap.get(scenario);
      const totalVotes = votes.option1.length + votes.option2.length;

      if (totalVotes === 0) {
        return await message.edit({ content: 'Nobody participated in the "Would you rather...?" poll.', embeds: [], components: [] });
      }

      const winner = votes.option1.length > votes.option2.length ? 'Option 1' : 'Option 2';
      const winPercentage = Math.round((votes[winner === 'Option 1' ? 'option1' : 'option2'].length / totalVotes) * 100);
      const results = `**Results:**\n${option1} - ${votes.option1.length} votes (${winPercentage}%)\n${option2} - ${votes.option2.length} votes ${(100 - winPercentage)}%`;

      const newEmbed = new EmbedBuilder().setColor(0x00ffff).setTitle('Would You Rather? Results').setDescription(results);

      await message.edit({ embeds: [newEmbed], components: [] });
      voteMap.delete(scenario); // Cleanup after the poll ends
    });
  },
};