// scripts/ui.js
import { ActionFormData } from '@minecraft/server-ui';
import { categories } from './data.js';
import { spawnWithUndo, undoLast } from './undo.js';
import { structureSizes } from './data.js';

export function showCategoryMenu(player) {
  const form = new ActionFormData()
    .title("§l§4Dante Gaming Menu")
    //.body("§7Select a category. Use Undo to revert your last spawn.");
  for (const cat of categories) {
    form.button(`§3§l${cat.name}`, cat.icon);
  }

  form.button("§2§lSubscribe", "textures/ui/subscribe");

  form.button("§c§lUndo Last Build");

  form.show(player).then((res) => {
    if (res.canceled) return;
    const idx = res.selection;

    if (idx === categories.length) {
    player.sendMessage("§bSubscribe Youtube: @dantegaming77");
    return;
  }

    if (idx === categories.length + 1) {
      undoLast(player);
      return;
    }
    const cat = categories[idx];
    if (cat) showStructureMenu(player, cat);
  }).catch(() => {
    player.sendMessage?.("§cError showing categories.");
  });
}

export function showStructureMenu(player, category) {
  const form = new ActionFormData()
    .title(`§l§6${category.name}`)
    .body("§7Select a structure:");
  for (const s of category.structures) {
    form.button(`§l§a${s.name}`, s.icon);
  }

  form.show(player).then((res) => {
    if (res.canceled) return;
    const selected = category.structures[res.selection];
    if (selected) spawnWithUndo(player, selected, structureSizes);
  }).catch(() => {
    player.sendMessage?.("§cError showing structures.");
  });
}
