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

module.exports = {
  data: new SlashCommandBuilder()
    .setName('define')
    .setDescription('Look up the definition of a word')
    .addStringOption(option =>
      option.setName('word')
        .setDescription('The word to define')
        .setRequired(true)
        .setMaxLength(100)
    ),

  async execute(interaction, supabase, client) {
    const word = interaction.options.getString('word').toLowerCase().trim();
    const mode = await getServerMode(supabase, interaction.guildId);

    await interaction.deferReply();

    try {
      const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${encodeURIComponent(word)}`);
      
      if (!response.ok) {
        const embed = new EmbedBuilder()
          .setColor(EMBED_COLORS.error)
          .setTitle('📖 Word Not Found')
          .setDescription(`Could not find a definition for "**${word}**".`)
          .setTimestamp();
        return interaction.editReply({ embeds: [embed] });
      }

      const data = await response.json();
      const entry = data[0];

      const embed = new EmbedBuilder()
        .setColor(getEmbedColor(mode))
        .setTitle(`📖 ${entry.word}`)
        .setTimestamp();

      if (entry.phonetic) {
        embed.setDescription(`*${entry.phonetic}*`);
      }

      const meanings = entry.meanings.slice(0, 3);
      for (const meaning of meanings) {
        const definitions = meaning.definitions.slice(0, 2);
        const defText = definitions.map((d, i) => {
          let text = `${i + 1}. ${d.definition}`;
          if (d.example) {
            text += `\n   *"${d.example}"*`;
          }
          return text;
        }).join('\n');

        embed.addFields({
          name: `${meaning.partOfSpeech}`,
          value: defText.substring(0, 1024)
        });
      }

      if (entry.sourceUrls && entry.sourceUrls[0]) {
        embed.setFooter({ text: 'Source: Wiktionary' });
      }

      await interaction.editReply({ embeds: [embed] });
    } catch (e) {
      const embed = new EmbedBuilder()
        .setColor(EMBED_COLORS.error)
        .setTitle('📖 Error')
        .setDescription('Failed to fetch definition. Please try again.')
        .setTimestamp();
      await interaction.editReply({ embeds: [embed] });
    }
  },
};
