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

// Companion mapping: altar typeId -> {name shown in lore, id keyword}
const COMPANIONS = {
  "aft_soulhunters:dragon_altar": { loreName: "Dragon Companion", id: "dragon" },
  "aft_soulhunters:elephant_altar":  { loreName: "Elephant Companion",  id: "elephant" },
  "aft_soulhunters:fox_altar": { loreName: "Fox Companion", id: "fox" },
  "aft_soulhunters:leopard_altar": { loreName: "Leopard Companion", id: "leopard" },
  "aft_soulhunters:manta_ray_altar": { loreName: "Manta Ray Companion", id: "manta_ray" },
  "aft_soulhunters:panda_altar": { loreName: "Panda Companion", id: "panda" },
  "aft_soulhunters:phoenix_altar": { loreName: "Phoenix Companion", id: "phoenix" },
  "aft_soulhunters:red_panda_altar": { loreName: "Red Panda Companion", id: "red_panda" },
  "aft_soulhunters:tiger_altar": { loreName: "Tiger Companion", id: "tiger" },
  "aft_soulhunters:wolf_altar": { loreName: "Wolf Companion", id: "wolf" },
};

/**
 * Handle crafting altar spawning and state restoration
 */
function handleCraftingAltarSpawn(altar) {
  // Find nearby players to check for saved altar state
  const nearbyPlayers = altar.dimension.getPlayers({
    location: altar.location,
    maxDistance: 10
  });
  
  for (const player of nearbyPlayers) {
    // Try to restore altar state from player's saved data
    if (loadAltarStateFromPlayer(player, altar)) {
      break; // State restored from this player
    }
  }
}

/**
 * Load altar state from player's dynamic properties
 */
function loadAltarStateFromPlayer(player, altar) {
  const altarStateKey = `aft_soulhunters:saved_altar_state`;
  const savedStateStr = player.getDynamicProperty(altarStateKey);
  
  if (!savedStateStr) {
    return false; // No saved state
  }
  
  try {
    const altarState = JSON.parse(savedStateStr);
    
    // Restore dynamic properties
    if (altarState.weapon) {
      altar.setDynamicProperty("altar_weapon", altarState.weapon);
    }
    if (altarState.weaponData) {
      altar.setDynamicProperty("altar_weapon_data", altarState.weaponData);
    }
    if (altarState.iron) {
      altar.setDynamicProperty("altar_iron", altarState.iron);
    }
    if (altarState.diamond) {
      altar.setDynamicProperty("altar_diamond", altarState.diamond);
    }
    if (altarState.netherStar) {
      altar.setDynamicProperty("altar_nether_star", altarState.netherStar);
    }
    if (altarState.gems) {
      altar.setDynamicProperty("altar_gems", altarState.gems);
    }
    
    // Restore component states
    if (altarState.componentStates) {
      altar.setProperty("aft_soulhunters:woodtable", altarState.componentStates.woodtable || "off");
      altar.setProperty("aft_soulhunters:stonetable", altarState.componentStates.stonetable || "off");
      altar.setProperty("aft_soulhunters:centertable", altarState.componentStates.centertable || "off");
      altar.setProperty("aft_soulhunters:gong", altarState.componentStates.gong || "off");
    }
    
    // Clear saved state since it's been applied
    player.setDynamicProperty(altarStateKey, undefined);
    
    player.sendMessage("§a§lAltar state restored from your saved configuration!");
    return true;
  } catch (error) {
    player.sendMessage("§c§lFailed to restore altar state. Starting fresh.");
    player.setDynamicProperty(altarStateKey, undefined);
    return false;
  }
}

// Listen for altar spawning to create companion
world.afterEvents.entitySpawn.subscribe(event => {
  const { entity } = event;
  if (!entity) return;

  // Handle crafting altar spawning and state restoration
  if (entity.typeId === "aft_soulhunters:crafting_altar") {
    handleCraftingAltarSpawn(entity);
    return;
  }

  const companionData = COMPANIONS[entity.typeId];
  if (!companionData) return; // Not an altar

  // Spawn the corresponding companion
  spawnAltarCompanion(entity, companionData);
});

function spawnAltarCompanion(altar, companionData) {
  const companionTypeId = `aft_soulhunters:altar_companion_${companionData.id}`;
  
  // Calculate spawn position near the altar (slightly offset)
  const spawnLocation = {
    x: altar.location.x + (Math.random() - 0.5) * 4, // Random offset within 2 blocks
    y: altar.location.y + 2, // Spawn 2 blocks above altar
    z: altar.location.z + (Math.random() - 0.5) * 4
  };
  
  try {
    // Spawn the companion
    const companion = altar.dimension.spawnEntity(companionTypeId, spawnLocation);
  } catch (error) {
    // removed debug log
  }
}