import { world, system } from "@minecraft/server";
import { trinketChecker } from "./trinketChecker.js";
import { flightChecker } from "./flightManager.js";
import { ItemInventoryContents } from "../utilities.js";

//// Creates a ticking area if not yet initialized. This is used to have a safe space to spawn the satchel, and break it, revealing the contents
world.afterEvents.worldInitialize.subscribe(() => {
  initializeTickingArea();
});

export function initializeTickingArea() {
  const id = system.runInterval(() => {
    const loc = world.getPlayers()[0]?.location;
    if (!loc) return;

    const key = "ItemInventoryContents";
    if (!world.getDynamicProperty(key)) {
      try {
        world
          .getDimension("overworld")
          .runCommand(
            `tickingarea add ${loc.x} 319 ${loc.z} ${loc.x} 319 ${loc.z} ItemInventoryContents`
          );
        world.setDynamicProperty(key, { x: loc.x, y: 319, z: loc.z });
      } catch (e) {
        console.error(`[Satchel] Failed to create ticking area: ${e}`);
      }
    }

    system.clearRun(id);
  }, 40);
}

// Tick to check satchel contents and apply effects
system.runInterval(() => {
  for (const player of world.getPlayers()) {
    const { satchel } = getActiveSatchel(player);

    // If satchel exists, extract its contents; otherwise, pass empty array
    const satchelContents = satchel
      ? new ItemInventoryContents(satchel).getContainer().content
      : [];

    trinketChecker(player, satchelContents);
    flightChecker(player);
  }
});

// Helper function to get the first non-empty satchel, prioritizing off-hand
export function getActiveSatchel(player) {
  const equipment = player.getComponent("equippable");
  const container = player.getComponent("inventory")?.container;
  if (!equipment || !container) return { satchel: null, fromOffhand: false };

  // 1️⃣ Check off-hand first
  const offhand = equipment.getEquipment("Offhand");
  if (offhand?.typeId.endsWith("trinket_satchel")) {
    const cloned = offhand.clone();
    const contents = new ItemInventoryContents(cloned).getContainer().content;
    if (contents.length > 0) {
      equipment.setEquipment("Offhand", cloned); // Replace off-hand to avoid vanilla bug
      return { satchel: cloned, fromOffhand: true };
    }
    // If empty, continue to check inventory
  }

  // 2️⃣ Check inventory slots 0-35
  for (let i = 0; i <= 35; i++) {
    const item = container.getItem(i);
    if (item?.typeId.endsWith("trinket_satchel")) {
      const contents = new ItemInventoryContents(item).getContainer().content;
      if (contents.length > 0) {
        return { satchel: item, fromOffhand: false };
      }
      // Empty satchel, continue
    }
  }

  return { satchel: null, fromOffhand: false };
}
