import { EmbedBuilder, ActionRowBuilder, StringSelectMenuBuilder, ButtonBuilder, ButtonStyle } from 'discord.js';
import { db } from '../../core/db.js';
import { getGuildConfig } from '../../core/db.js';

function emjText(tag) {
  if (!tag) return '';
  // Insert ZWSP after < to prevent Discord from parsing <:name:id> as emoji
  return tag.replace(/<(:\w+:)\d+>/g, '\u200B$1').replace(/<a?(:\w+:)\d+>/g, '\u200B$1');
}

// Render store panel sesuai panel_id (UI mirip foto: header image + dropdown kategori + footer note)
export async function sendStorePanel(client, panelId, channelId) {
  const panel = db.prepare('SELECT * FROM store_panels WHERE id = ?').get(panelId);
  if (!panel) throw new Error('Panel not found');

  const categories = db.prepare(
    'SELECT * FROM categories WHERE panel_id = ? AND enabled = 1 ORDER BY sort_order, id'
  ).all(panelId);

  const channel = await client.channels.fetch(channelId);
  if (!channel) throw new Error('Channel not found');

  const embed = new EmbedBuilder()
    .setColor(0xed4245)
    .setTitle(panel.title);
  if (panel.image_url) embed.setImage(panel.image_url);
  if (panel.footer_note) embed.setDescription(panel.footer_note);
  if (panel.copyright) embed.setFooter({ text: panel.copyright });

  const components = [];

  if (categories.length) {
    const select = new StringSelectMenuBuilder()
      .setCustomId(`store_category:${panelId}`)
      .setPlaceholder(panel.placeholder || 'Pilih Di Sini')
      .addOptions(categories.slice(0, 25).map(c => {
        const opt = {
          label: c.name.slice(0, 100),
          description: (c.description || `Menu ${c.name}`).slice(0, 100),
          value: `${c.id}`,
        };
        if (c.emoji) {
          // Support custom emoji "<:name:id>" or unicode
          const customMatch = c.emoji.match(/<a?:(\w+):(\d+)>/);
          if (customMatch) opt.emoji = { id: customMatch[2], name: customMatch[1], animated: c.emoji.startsWith('<a:') };
          else opt.emoji = { name: c.emoji };
        }
        return opt;
      }));
    components.push(new ActionRowBuilder().addComponents(select));
  }

  const msg = await channel.send({ embeds: [embed], components });
  return { ok: true, message_id: msg.id };
}

// Render product list when user picks a category from dropdown
export async function renderCategoryView(interaction, categoryId) {
  const cat = db.prepare('SELECT * FROM categories WHERE id = ?').get(categoryId);
  if (!cat) return interaction.reply({ content: '❌ Kategori tidak ditemukan', ephemeral: true });

  const products = db.prepare(
    'SELECT *, (SELECT COUNT(*) FROM stock WHERE product_id = products.id AND sold = 0) AS stock_count FROM products WHERE category_id = ? AND enabled = 1 ORDER BY sort_order, id'
  ).all(categoryId);

  const cfg = getGuildConfig(interaction.guildId);
  const ep = cfg.emoji_price || '💰';
  const es = cfg.emoji_stock || '📦';
  const ticketColor = cfg.ticket_color ? parseInt(cfg.ticket_color.replace('#', ''), 16) : 0xed4245;

  const embed = new EmbedBuilder()
    .setColor(ticketColor)
    .setTitle(`${cat.emoji ? cat.emoji + ' ' : ''}${cat.name}`)
    .setDescription(cat.description || `Menu ${cat.name}`);

  if (cat.note) {
    embed.addFields({ name: '📝 NOTE', value: cat.note });
  }

  if (!products.length) {
    embed.addFields({ name: 'Produk', value: '_(belum ada produk di kategori ini)_' });
    return interaction.reply({ embeds: [embed], ephemeral: true });
  }

  embed.addFields({
    name: 'Produk Tersedia',
    value: products.map(p => {
      const priceText = p.price_max
        ? `Rp${p.price.toLocaleString('id-ID')} - ${p.price_max.toLocaleString('id-ID')}`
        : `Rp${p.price.toLocaleString('id-ID')}`;
      const stockBadge = p.stock_count > 0 ? `${es} ${p.stock_count}` : '❌ habis';
      return `\`#${p.id}\` **${p.name}**\n${ep} ${priceText}\n${stockBadge}`;
    }).join('\n\n'),
  });

  // Show first product image if available
  const firstWithImage = products.find(p => p.image_url);
  if (firstWithImage) embed.setThumbnail(firstWithImage.image_url);

  const emojiStock = cfg.emoji_stock || '📦';

  const select = new StringSelectMenuBuilder()
    .setCustomId(`store_buy`)
    .setPlaceholder('Pilih produk untuk dibeli…')
    .addOptions(products.slice(0, 25).map(p => {
      const opt = {
        label: `${p.name} — Rp${p.price.toLocaleString('id-ID')}${p.price_max ? '+' : ''}`.slice(0, 100),
        description: emjText(p.description || cat.name).slice(0, 100),
        value: `${p.id}`,
      };
      const customMatch = emojiStock.match(/<a?:(\w+):(\d+)>/);
      if (customMatch) opt.emoji = { id: customMatch[2], name: customMatch[1], animated: emojiStock.startsWith('<a:') };
      else opt.emoji = { name: emojiStock };
      return opt;
    }));

  await interaction.reply({
    embeds: [embed],
    components: [new ActionRowBuilder().addComponents(select)],
    ephemeral: true,
  });
}
