const { SlashCommandBuilder, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('foundation')
    .setDescription('View AeThex Foundation info and your contribution stats')
    .addUserOption(option =>
      option.setName('user')
        .setDescription('User to view (defaults to yourself)')
        .setRequired(false)
    ),

  async execute(interaction, supabase, client) {
    const target = interaction.options.getUser('user') || interaction.user;
    await interaction.deferReply();

    let contributionData = null;

    if (supabase) {
      try {
        const { data: link } = await supabase
          .from('discord_links')
          .select('user_id')
          .eq('discord_id', target.id)
          .maybeSingle();

        if (link) {
          const { data: contribution } = await supabase
            .from('foundation_contributions')
            .select('total_donated, volunteer_hours, badges')
            .eq('user_id', link.user_id)
            .maybeSingle();

          contributionData = contribution;
        }
      } catch (e) {
        console.warn('Foundation data fetch failed:', e.message);
      }
    }

    const embed = new EmbedBuilder()
      .setColor(0x7c3aed)
      .setTitle('AeThex Foundation')
      .setDescription('Supporting creators, developers, and the gaming community.')
      .setThumbnail(target.displayAvatarURL())
      .addFields(
        { name: 'Mission', value: 'Empowering the next generation of creators through education, resources, and community support.' }
      )
      .setTimestamp();

    if (contributionData) {
      embed.addFields(
        { name: `${target.tag}'s Contributions`, value: '\u200b' },
        { name: 'Total Donated', value: `$${contributionData.total_donated || 0}`, inline: true },
        { name: 'Volunteer Hours', value: `${contributionData.volunteer_hours || 0}h`, inline: true }
      );

      if (contributionData.badges && contributionData.badges.length > 0) {
        embed.addFields({ name: 'Badges', value: contributionData.badges.join(', ') });
      }
    } else if (target.id === interaction.user.id) {
      embed.addFields({ 
        name: 'Your Contributions', 
        value: 'Link your account with `/verify` to track your contributions!' 
      });
    }

    const row = new ActionRowBuilder()
      .addComponents(
        new ButtonBuilder()
          .setLabel('Visit Foundation')
          .setStyle(ButtonStyle.Link)
          .setURL('https://aethex.foundation'),
        new ButtonBuilder()
          .setLabel('Donate')
          .setStyle(ButtonStyle.Link)
          .setURL('https://aethex.foundation/donate')
      );

    await interaction.editReply({ embeds: [embed], components: [row] });
  },
};
