import { system } from "@minecraft/server";
import { pokemonUtils } from "./utils/pokemonUtils.js";
import { openPCPaged } from "./utils/pokemonUtils_PC_PAGED.js";

/**
 * Deferred install to avoid circular-import / init-order issues.
 * If anything fails, we leave the original PC untouched.
 */
system.run(() => {
  try {
    const originalOpenPC = pokemonUtils.openPC?.bind(pokemonUtils);

    // Expanded deposit (optional) - won't throw if not used
    pokemonUtils.depositPokemonToPC_Expanded = (player, maxCapacity) => {
      try {
        const slotIndex = player.getDynamicProperty("pr:selectedSlot");
        if (slotIndex == -1) return false;
        if (slotIndex < 6) {
          const pokemonData = pokemonUtils.getPokemonFromSlot(player, slotIndex);
          if (!pokemonData) return false;

          const current = pokemonUtils.getPCPokemonCount(player);
          if (current >= maxCapacity) {
            try { player.sendMessage(`PC is full! (${current}/${maxCapacity})`); } catch {}
            return false;
          }

          const success = pokemonUtils.movePokemonToPC(player, slotIndex);
          if (success) {
            try { player.sendMessage(`Deposited Pokémon: ${pokemonData.name} to PC.`); } catch {}
            return true;
          }
        }
        return false;
      } catch (e) {
        try { return pokemonUtils.depositPokemonToPC(player); } catch {}
        return false;
      }
    };

    pokemonUtils.openPC = (player) => {
      try {
        return openPCPaged(pokemonUtils, player, { pageSize: 30, maxBoxes: 30 });
      } catch (e) {
        try { player.sendMessage(`§cPC UI error: ${e?.message ?? e}`); } catch {}
        if (typeof originalOpenPC === "function") return originalOpenPC(player);
      }
    };

    // optional: lightweight confirmation in console only (won't spam players)
    // eslint-disable-next-line no-console
    console.warn("[PC PAGED] Installed openPC override.");
  } catch (e) {
    // eslint-disable-next-line no-console
    console.warn("[PC PAGED] Install failed:", e);
  }
});
