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

module.exports = {
  data: new SlashCommandBuilder()
    .setName("help")
    .setDescription("View all AeThex bot commands and features")
    .addStringOption(option =>
      option.setName('category')
        .setDescription('Specific category to view')
        .setRequired(false)
        .addChoices(
          { name: '🔗 Account', value: 'account' },
          { name: '⚔️ Realms', value: 'realms' },
          { name: '📊 Community', value: 'community' },
          { name: '⭐ Leveling', value: 'leveling' },
          { name: '🎮 Fun & Games', value: 'fun' },
          { name: '💰 Economy', value: 'economy' },
          { name: '👥 Social', value: 'social' },
          { name: '🛡️ Moderation', value: 'moderation' },
          { name: '🔧 Utility', value: 'utility' },
          { name: '⚙️ Admin', value: 'admin' }
        )
    ),

  async execute(interaction, supabase) {
    const category = interaction.options.getString('category');
    const mode = await getServerMode(supabase, interaction.guildId);

    if (category) {
      const embed = getCategoryEmbed(category, mode);
      return interaction.reply({ embeds: [embed], ephemeral: true });
    }

    const modeIndicator = `${getModeEmoji(mode)} ${getModeDisplayName(mode)} Mode`;

    const mainEmbed = new EmbedBuilder()
      .setColor(getEmbedColor(mode))
      .setAuthor({ 
        name: 'AeThex Bot Help',
        iconURL: interaction.client.user.displayAvatarURL()
      })
      .setDescription(`Welcome to AeThex Bot! Select a category below to view commands.\n\n**Current Mode:** ${modeIndicator}`)
      .addFields(
        {
          name: "🔗 Account",
          value: "`/verify` `/unlink` `/profile`",
          inline: true,
        },
        {
          name: "⚔️ Realms",
          value: "`/set-realm` `/federation` `/refresh-roles`",
          inline: true,
        },
        {
          name: "📊 Community",
          value: "`/stats` `/leaderboard` `/poll` `/post`",
          inline: true,
        },
        {
          name: "⭐ Leveling",
          value: "`/rank` `/daily` `/prestige` `/badges`",
          inline: true,
        },
        {
          name: "🎮 Fun & Games",
          value: "`/8ball` `/roll` `/trivia` `/duel` `/slots`",
          inline: true,
        },
        {
          name: "💰 Economy",
          value: "`/work` `/heist` `/gift` `/shop`",
          inline: true,
        },
        {
          name: "👥 Social",
          value: "`/rep` `/hug` `/birthday` `/remind`",
          inline: true,
        },
        {
          name: "🛡️ Moderation",
          value: "`/warn` `/kick` `/ban` `/timeout`",
          inline: true,
        },
        {
          name: "🔧 Utility",
          value: "`/translate` `/define` `/math` `/qr`",
          inline: true,
        },
        {
          name: "⚙️ Admin",
          value: "`/config` `/starboard` `/automod`",
          inline: true,
        }
      )
      .setFooter({ 
        text: "Use /help [category] for detailed commands",
        iconURL: interaction.client.user.displayAvatarURL()
      })
      .setTimestamp();

    const selectMenu = new StringSelectMenuBuilder()
      .setCustomId('help_category')
      .setPlaceholder('Select a category for details...')
      .addOptions([
        { label: 'Account', description: 'Link and manage your account', emoji: '🔗', value: 'account' },
        { label: 'Realms', description: 'Realm selection and roles', emoji: '⚔️', value: 'realms' },
        { label: 'Community', description: 'Community features', emoji: '📊', value: 'community' },
        { label: 'Leveling', description: 'XP and leveling system', emoji: '⭐', value: 'leveling' },
        { label: 'Fun & Games', description: 'Fun commands and minigames', emoji: '🎮', value: 'fun' },
        { label: 'Economy', description: 'Earn and spend XP', emoji: '💰', value: 'economy' },
        { label: 'Social', description: 'Social interactions', emoji: '👥', value: 'social' },
        { label: 'Moderation', description: 'Moderation tools', emoji: '🛡️', value: 'moderation' },
        { label: 'Utility', description: 'Utility commands', emoji: '🔧', value: 'utility' },
        { label: 'Admin', description: 'Admin and config', emoji: '⚙️', value: 'admin' },
      ]);

    const row = new ActionRowBuilder().addComponents(selectMenu);

    await interaction.reply({ embeds: [mainEmbed], components: [row], ephemeral: true });
  },
};

function getCategoryEmbed(category, mode = 'federated') {
  const categories = {
    account: {
      title: '🔗 Account Commands',
      color: 0x3b82f6,
      commands: [
        { name: '/verify', desc: 'Link your Discord account to AeThex' },
        { name: '/unlink', desc: 'Disconnect your Discord from AeThex' },
        { name: '/profile [@user]', desc: 'View your or another user\'s profile' },
      ]
    },
    realms: {
      title: '⚔️ Realm Commands',
      color: 0xf97316,
      commands: [
        { name: '/set-realm', desc: 'Choose your primary realm (Federation mode only)' },
        { name: '/federation', desc: 'Manage cross-server role sync' },
        { name: '/refresh-roles', desc: 'Sync your roles based on AeThex profile' },
        { name: '/verify-role', desc: 'Check your assigned Discord roles' },
      ]
    },
    community: {
      title: '📊 Community Commands',
      color: 0x22c55e,
      commands: [
        { name: '/stats', desc: 'View your AeThex statistics and activity' },
        { name: '/leaderboard [category]', desc: 'See the top contributors' },
        { name: '/post', desc: 'Create a post in the AeThex community feed' },
        { name: '/poll', desc: 'Create a community poll' },
        { name: '/studio [@user]', desc: 'View AeThex Studio profile' },
        { name: '/foundation [@user]', desc: 'View Foundation contributions' },
      ]
    },
    leveling: {
      title: '⭐ Leveling Commands',
      color: 0xfbbf24,
      commands: [
        { name: '/rank [@user]', desc: 'View your level and XP' },
        { name: '/daily', desc: 'Claim your daily XP bonus (+50 base + streak)' },
        { name: '/prestige', desc: 'Prestige at Level 50 for permanent bonuses' },
        { name: '/badges', desc: 'View earned badges' },
        { name: '/achievements', desc: 'View available achievements' },
        { name: '/quests', desc: 'View and track your quests' },
      ]
    },
    fun: {
      title: '🎮 Fun & Games Commands',
      color: 0xec4899,
      commands: [
        { name: '/8ball [question]', desc: 'Ask the magic 8-ball a question' },
        { name: '/coinflip [call]', desc: 'Flip a coin' },
        { name: '/roll [dice]', desc: 'Roll dice (e.g., 2d6, d20, 3d8+5)' },
        { name: '/trivia [category]', desc: 'Answer trivia questions for XP' },
        { name: '/duel @user [bet]', desc: 'Challenge someone to a duel' },
        { name: '/slots [bet]', desc: 'Try your luck at the slot machine' },
        { name: '/afk [reason]', desc: 'Set your AFK status' },
      ]
    },
    economy: {
      title: '💰 Economy Commands',
      color: 0x10b981,
      commands: [
        { name: '/work', desc: 'Work to earn XP (hourly)' },
        { name: '/heist [target]', desc: 'Start a group heist' },
        { name: '/gift @user [amount]', desc: 'Gift XP to another user' },
        { name: '/shop', desc: 'Browse and purchase items' },
        { name: '/inventory [@user]', desc: 'View your inventory' },
        { name: '/trade @user [offer] [request]', desc: 'Trade items with another user' },
      ]
    },
    social: {
      title: '👥 Social Commands',
      color: 0x8b5cf6,
      commands: [
        { name: '/rep @user [reason]', desc: 'Give reputation to someone' },
        { name: '/hug @user', desc: 'Give someone a virtual hug' },
        { name: '/birthday set/view/upcoming', desc: 'Manage birthdays' },
        { name: '/remind set/list/cancel', desc: 'Set personal reminders' },
      ]
    },
    moderation: {
      title: '🛡️ Moderation Commands',
      color: 0xef4444,
      commands: [
        { name: '/warn @user [reason]', desc: 'Warn a user' },
        { name: '/kick @user [reason]', desc: 'Kick a user from the server' },
        { name: '/ban @user [reason]', desc: 'Ban a user from the server' },
        { name: '/timeout @user [minutes] [reason]', desc: 'Timeout a user' },
        { name: '/modlog @user', desc: 'View a user\'s moderation history' },
        { name: '/auditlog', desc: 'View admin action history' },
      ]
    },
    utility: {
      title: '🔧 Utility Commands',
      color: 0x6366f1,
      commands: [
        { name: '/translate [text] [to]', desc: 'Translate text to another language' },
        { name: '/define [word]', desc: 'Look up word definitions' },
        { name: '/math [expression]', desc: 'Calculate math expressions' },
        { name: '/color [hex/rgb]', desc: 'View color information' },
        { name: '/qr [text]', desc: 'Generate a QR code' },
        { name: '/userinfo [@user]', desc: 'View detailed user information' },
        { name: '/serverinfo', desc: 'View server statistics' },
        { name: '/avatar [@user]', desc: 'Get a user\'s avatar' },
        { name: '/status', desc: 'View bot status' },
      ]
    },
    admin: {
      title: '⚙️ Admin Commands',
      color: 0x6b7280,
      commands: [
        { name: '/config', desc: 'View and edit server configuration (including mode)' },
        { name: '/starboard setup/disable/status', desc: 'Configure the starboard' },
        { name: '/announce', desc: 'Send announcements' },
        { name: '/embed', desc: 'Create custom embed messages' },
        { name: '/rolepanel', desc: 'Create role button panels' },
        { name: '/giveaway', desc: 'Create and manage giveaways' },
        { name: '/schedule', desc: 'Schedule messages for later' },
        { name: '/automod', desc: 'Configure auto-moderation' },
        { name: '/xp-settings', desc: 'Configure XP system' },
        { name: '/level-roles', desc: 'Set up level-up role rewards' },
        { name: '/quests-manage', desc: 'Manage quests' },
        { name: '/shop-manage', desc: 'Manage shop items' },
      ]
    }
  };

  const cat = categories[category] || categories.account;

  return new EmbedBuilder()
    .setColor(cat.color)
    .setTitle(cat.title)
    .setDescription(cat.commands.map(c => `**${c.name}**\n${c.desc}`).join('\n\n'))
    .setFooter({ text: 'Use /help to see all categories' })
    .setTimestamp();
}

module.exports.getCategoryEmbed = getCategoryEmbed;
