import { world } from "@minecraft/server";
import { multiblockGAMFormationManager } from "./GAMFormationManager.js";
import { multiblockGAMInteractionManager } from "./GAMInteractionManager.js";
import {
  multiblockTTFormationManager,
  multiblockTTDummyBlockCheck,
} from "./TTFormationManager.js";
import {
  multiblockUPFormationManager,
  multiblockUPDummyBlockCheck,
} from "./UPFormationManager.js";

// Register custom components for multiblock functionality
let initialized = false;
world.beforeEvents.worldInitialize.subscribe((data) => {
  if (initialized) return;
  initialized = true;

  const registry = data.blockComponentRegistry;

  registry.registerCustomComponent("pb_gat:mb_tick_handler", { onTick });
  registry.registerCustomComponent("pb_gat:mb_interact_handler", {
    onPlayerInteract,
  });

});

// Event handlers for multiblock ticking and interaction
function onTick(data) {
  const block = data.block;
  const handler = tickHandlersByBlockType[block.typeId];
  if (handler) {
    handler(block);
  }
}
function onPlayerInteract(event) {
  const block = event.block;
  const player = event.player;
  const handler = interactHandlersByBlockType[block.typeId];
  if (handler) {
    handler(block, player);
  }
}

// Handlers for specific block types
const tickHandlersByBlockType = {
  "pb_gat:mb_gam": multiblockGAMFormationManager,
  "pb_gat:mb_tinker_table_bottom": multiblockTTFormationManager,
  "pb_gat:mb_tinker_table_top": multiblockTTDummyBlockCheck,
  "pb_gat:mb_upgrade_puncher_bottom": multiblockUPFormationManager,
  "pb_gat:mb_upgrade_puncher_top": multiblockUPDummyBlockCheck,
};

const interactHandlersByBlockType = {
  "pb_gat:mb_gam": multiblockGAMInteractionManager,
};
