import { world, system } from "@minecraft/server";

const NOTEBOOK_ITEM_ID = "pr:trainer_notebook";

// Simple, Realms-safe Trainer Guide (NO server-ui forms to avoid client freezes).
// Usage: !guide [topic]
// Topics: catching, battling, riding, apricorns, villages, pc, healing, moves, evolution

const TOPICS = {
  index: {
    title: "Trainer Guide",
    lines: [
      "§aUse: §f!guide §7[topic]",
      "§aTopics: §fcatching, battling, riding, apricorns, villages, pc, healing, moves, evolution",
      "§7Example: §f!guide catching",
    ],
  },
  catching: {
    title: "Catching Pokémon",
    lines: [
      "1) Find a wild Pokémon",
      "2) Start a battle",
      "3) Weaken it (lower HP helps)",
      "4) Use a Poké Ball from your bag",
      "5) If it succeeds, it joins your team",
    ],
  },
  battling: {
    title: "Battling",
    lines: [
      "Battles are turn-based using the battle menu. Click your pokemon with nothing in hand.",
"Type !pve or !pvp to start battle searching.",
"Click a wild pokemon or another players.",
      "Options: Battle (moves), Bag (items), Pokémon (switch), Run (if allowed).",
      "Win battles to gain XP and progress toward evolution.",
    ],
  },
  riding: {
    title: "Riding",
    lines: [
      "Ride a Pokémon you own:",
      "§a!ride",
      "Dismount:",
      "§a!dismount",
    ],
  },
  apricorns: {
    title: "Apricorn Trees",
    lines: [
      "Walk up to an apricorn tree and interact to pluck apricorns.",
      "Trees regrow after being harvested.",
      "Apricorns are used for crafting and progression.",
    ],
  },
  villages: {
    title: "Poke Villages",
    lines: [
      "Villages can spawn in:",
      "• Cherry Grove",
      "• Plains",
      "• Nether",
      "Tip: explore new/unloaded chunks to find more.",
    ],
  },
  pc: {
    title: "PC",
    lines: [
      "Craft a PC to store and manage Pokémon.",
      "Use it to deposit/withdraw and organize your collection.",
    ],
  },
  healing: {
    title: "Healing Station",
    lines: [
      "Craft/place a Healing Station to heal your team.",
      "Interact with it to restore Pokémon to full health.",
      "Tip: keep one at your base!",
    ],
  },
  moves: {
    title: "Learning New Moves",
    lines: [
      "Pokémon earn Move Points as they level up.",
      "Open the Learn Moves menu, pick a slot, and spend points to learn/unlock moves.",
      "Stronger moves usually cost more points.",
    ],
  },
  evolution: {
    title: "Evolution",
    lines: [
      "Pokémon evolve when they meet requirements like level or special items.",
      "Evolution changes the Pokémon form and may change stats/moves.",
    ],
  },
};

function sendGuide(player, topicKey) {
  const key = (topicKey || "index").toLowerCase();
  const topic = TOPICS[key] ?? TOPICS.index;

  // Header
  player.sendMessage(`§6§l${topic.title}§r`);
  // Body
  for (const line of topic.lines) player.sendMessage(`§f${line}`);
}

function parseTopic(messageLower) {
  // messageLower is already lowercased and trimmed
  // supports: "!guide", "!guide catching", "!trainer moves", "!notebook pc"
  const parts = messageLower.split(/\s+/g).filter(Boolean);
  if (parts.length <= 1) return "index";
  return parts.slice(1).join(" "); // allow multi-word (not used now)
}

// Chat command (afterEvents is reliable; we do not cancel chat here to avoid platform issues)
const __lastGuideTick = new Map(); // pid -> tick
world.afterEvents.chatSend.subscribe((ev) => {
  const player = ev.sender;
  if (!player || player.typeId !== "minecraft:player") return;

  const msgRaw = (ev.message ?? "").trim();
  if (!msgRaw) return;
  const msg = msgRaw.toLowerCase();

  const isGuide = msg.startsWith("!guide") || msg.startsWith("!trainer") || msg.startsWith("!notebook");
  if (!isGuide) return;

  // debounce to prevent spam
  const pid = player.id;
  const nowTick = system.currentTick ?? 0;
  const last = __lastGuideTick.get(pid) ?? -999999;
  if (nowTick - last < 10) return;
  __lastGuideTick.set(pid, nowTick);

  const topic = parseTopic(msg);
  try { sendGuide(player, topic); } catch {}
});

// Notebook item use -> just hints (no UI, no freeze)
world.afterEvents.itemUse.subscribe((ev) => {
  const player = ev.source;
  if (!player || player.typeId !== "minecraft:player") return;
  const item = ev.itemStack;
  if (!item || item.typeId !== NOTEBOOK_ITEM_ID) return;

  const pid = player.id;
  const nowTick = system.currentTick ?? 0;
  const last = __lastGuideTick.get(pid) ?? -999999;
  if (nowTick - last < 10) return;
  __lastGuideTick.set(pid, nowTick);

  try {
    player.sendMessage("§aTrainer Notebook: §fType §6!guide §fto open the Trainer Guide. §7(Example: !guide catching)");
  } catch {}
});
