const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { getServerMode, getEmbedColor } = require('../utils/modeHelper');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('coinflip')
    .setDescription('Flip a coin')
    .addStringOption(option =>
      option.setName('call')
        .setDescription('Call heads or tails before the flip')
        .setRequired(false)
        .addChoices(
          { name: 'Heads', value: 'heads' },
          { name: 'Tails', value: 'tails' }
        )
    ),

  async execute(interaction, supabase, client) {
    const call = interaction.options.getString('call');
    const result = Math.random() < 0.5 ? 'heads' : 'tails';
    const emoji = result === 'heads' ? '🪙' : '💿';
    
    const mode = await getServerMode(supabase, interaction.guildId);

    const embed = new EmbedBuilder()
      .setColor(getEmbedColor(mode))
      .setTitle(`${emoji} Coin Flip`)
      .setDescription(`The coin landed on **${result.toUpperCase()}**!`)
      .setTimestamp();

    if (call) {
      const won = call === result;
      embed.addFields({
        name: won ? '🎉 Result' : '😔 Result',
        value: won ? `You called it! You win!` : `You called ${call}, better luck next time!`
      });
      embed.setColor(won ? 0x22C55E : 0xEF4444);
    }

    embed.setFooter({ text: `Flipped by ${interaction.user.username}` });

    await interaction.reply({ embeds: [embed] });
  },
};
