/**
 * Comprehensive Companion Management System for Soul Hunters
 * 
 * This system handles all companion logic based on inventory weapons with lore:
 * - Detects weapons with companion lore in inventory
 * - Spawns/switches companions based on main hand or last held weapon
 * - Handles activation via Shift + Right-click on weapon
 * - Manages soul counts and companion states
 * 
 * @author SoulHunters Team
 * @version 2.0.0
 */

import { world, EquipmentSlot, system, ItemStack } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
import { getAbilityInfo, getAbilityCooldown } from "./companion_abilities.js";

// ================================================================================================
// CONSTANTS AND CONFIGURATION
// ================================================================================================

const MOD_PREFIX = "aft_soulhunters:";

// Soul and companion management constants
const MAX_SOULS = 10;
const SOUL_ITEM_ID = "aft_soulhunters:soul";
const ACTIVE_PROP = "active";
const BEHAVIOR_PROP = "soulhunters_behavior";

// Events
const tameEvent = "aft_soulhunters:tame";
const despawnEvent = "aft_soulhunters:despawn";
const activateEvent = "aft_soulhunters:activate";
const removeActivateEvent = "aft_soulhunters:remove_activate";
const noSoulsEvent = "aft_soulhunters:no_souls";
const dontAttackEvent = "aft_soulhunters:dont_attack";

// UI Options for companion control
const UI_OPTIONS = [
  { text: "Attack all monsters", event: "aft_soulhunters:attack_all", texture: "textures/aft/soulhunters/icons/all_monsters" },
  { text: "Attack only what I attack", event: "aft_soulhunters:attack_only_when_attacked", texture: "textures/aft/soulhunters/icons/some_monsters" },
  { text: "Use Special Ability", event: "special_ability", texture: "textures/items/book_enchanted" },
  { text: "Ride Companion", event: "ride_companion", texture: "textures/aft/soulhunters/icons/ride" },
  { text: "Don't attack", event: "aft_soulhunters:dont_attack", texture: "textures/aft/soulhunters/icons/no_attack" }
];

// Soul count to event mapping
const SCORE_TO_EVENT = {
  0: "cero", 1: "one", 2: "two", 3: "three", 4: "four",
  5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten"
};

// Companion type mappings
const COMPANION_TYPES = {
  "Dragon Companion": "dragon",
  "Elephant Companion": "elephant", 
  "Fox Companion": "fox",
  "Leopard Companion": "leopard",
  "Manta Ray Companion": "manta_ray",
  "Red Panda Companion": "red_panda",
  "Panda Companion": "panda",
  "Phoenix Companion": "phoenix",
  "Tiger Companion": "tiger",
  "Wolf Companion": "wolf"
};

// Valid weapons for companion system
const COMPANION_WEAPONS = [
  "aft_soulhunters:charge_fan_2", "aft_soulhunters:fire_katana_2", "aft_soulhunters:flame_tanto_2",
  "aft_soulhunters:hurricane_sai_2", "aft_soulhunters:kunai_knife_2", "aft_soulhunters:rumbling_hammer_2",
  "aft_soulhunters:speed_yari_2", "aft_soulhunters:spirit_masakari_2", "aft_soulhunters:thunder_long_bow_2",
  "aft_soulhunters:wind_naginata_2", "aft_soulhunters:charge_fan_3", "aft_soulhunters:fire_katana_3",
  "aft_soulhunters:flame_tanto_3", "aft_soulhunters:hurricane_sai_3", "aft_soulhunters:kunai_knife_3",
  "aft_soulhunters:rumbling_hammer_3", "aft_soulhunters:speed_yari_3", "aft_soulhunters:spirit_masakari_3",
  "aft_soulhunters:thunder_long_bow_3", "aft_soulhunters:wind_naginata_3", "aft_soulhunters:charge_fan_4",
  "aft_soulhunters:fire_katana_4", "aft_soulhunters:flame_tanto_4", "aft_soulhunters:hurricane_sai_4",
  "aft_soulhunters:kunai_knife_4", "aft_soulhunters:rumbling_hammer_4", "aft_soulhunters:speed_yari_4",
  "aft_soulhunters:spirit_masakari_4", "aft_soulhunters:thunder_long_bow_4", "aft_soulhunters:wind_naginata_4"
];

// Player state tracking
const playerStates = new Map();

// Track recent activations to prevent UI conflicts
const recentActivations = new Map();

// ================================================================================================
// UTILITY FUNCTIONS
// ================================================================================================

/**
 * Gets companion type from weapon lore
 */
function getCompanionFromLore(item) {
  if (!item) return null;
  
  const lore = item.getLore();
  if (lore.length === 0) return null;
  
  for (const [loreName, companionType] of Object.entries(COMPANION_TYPES)) {
    if (lore[0].includes(loreName)) {
      return companionType;
    }
  }
  return null;
}

/**
 * Gets soul count from weapon lore
 */
function getSoulCount(item) {
  if (!item) return 0;
  
  const lore = item.getLore();
  if (lore.length < 2) return 0;
  
  const soulsMatch = lore[1].match(/(\d+)\/\d+/);
  return soulsMatch ? parseInt(soulsMatch[1]) : 0;
}

/**
 * Converts soul count to event name
 */
function getSoulEventName(souls) {
  const soulNames = ["cero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
  return soulNames[Math.max(0, Math.min(10, souls))];
}

/**
 * Gets complete weapon info including companion type and souls from lore
 */
function getWeaponInfo(item) {
  if (!item || !COMPANION_WEAPONS.includes(item.typeId)) return null;
  
  const companion = getCompanionFromLore(item);
  if (!companion) return null;
  
  const souls = getSoulCount(item);
  return { 
    companion, 
    souls, 
    hasLore: true 
  };
}

/**
 * Updates weapon lore with companion type and souls
 */
function updateWeaponLore(item, companionType, souls) {
  const companionName = Object.keys(COMPANION_TYPES).find(key => COMPANION_TYPES[key] === companionType);
  if (!companionName) return;
  
  const newLore = [companionName, `${souls}/${MAX_SOULS} Souls`];
  item.setLore(newLore);
}

/**
 * Capitalizes text and replaces underscores with spaces
 */
function capitalize(text) {
  return text.replace(/_/g, ' ').replace(/\b\w/g, char => char.toUpperCase());
}

/**
 * Finds entity by ID in dimension
 */
function findEntityById(id, dimension) {
  for (const entity of dimension.getEntities()) {
    if (entity.id === id) return entity;
  }
  return null;
}

/**
 * Finds all companion weapons in player inventory
 */
function findCompanionWeapons(player) {
  const weapons = [];
  
  // Check main hand
  const mainhand = player.getComponent("equippable").getEquipment(EquipmentSlot.Mainhand);
  if (mainhand && COMPANION_WEAPONS.includes(mainhand.typeId)) {
    const companion = getCompanionFromLore(mainhand);
    if (companion) {
      weapons.push({
        item: mainhand,
        companion: companion,
        souls: getSoulCount(mainhand),
        slot: "mainhand",
        priority: 1 // Highest priority
      });
    }
  }
  
  // Check inventory slots
  const inventory = player.getComponent("inventory").container;
  for (let i = 0; i < inventory.size; i++) {
    const item = inventory.getItem(i);
    if (item && COMPANION_WEAPONS.includes(item.typeId)) {
      const companion = getCompanionFromLore(item);
      if (companion) {
        weapons.push({
          item: item,
          companion: companion,
          souls: getSoulCount(item),
          slot: i,
          priority: 2 // Lower priority
        });
      }
    }
  }
  
  return weapons;
}

/**
 * Gets the current active companion weapon for player
 */
function getActiveCompanionWeapon(player) {
  const weapons = findCompanionWeapons(player);
  
  if (weapons.length === 0) return null;
  
  // Priority 1: Main hand weapon (if it has companion lore)
  const mainhandWeapon = weapons.find(w => w.slot === "mainhand");
  if (mainhandWeapon) return mainhandWeapon;
  
  // Priority 2: If no main hand companion weapon, find best inventory weapon
  // This allows switching to other companion weapons when main hand weapon is removed
  const playerState = playerStates.get(player.id) || {};
  
  // Try to maintain the same companion type if possible
  if (playerState.currentCompanion) {
    const sameTypeWeapon = weapons.find(w => w.companion === playerState.currentCompanion);
    if (sameTypeWeapon) return sameTypeWeapon;
  }
  
  // Otherwise return the first available weapon
  return weapons[0];
}

// ================================================================================================
// COMPANION MANAGEMENT
// ================================================================================================

/**
 * Gets all companions of a specific type belonging to player
 */
function getPlayerCompanions(player, companionType = null) {
  const entities = player.dimension.getEntities({
    location: player.location,
    maxDistance: 100
  });
  
  const companions = [];
  entities.forEach(entity => {
    const entityId = entity.typeId;
    const ownerId = entity.getDynamicProperty("ownerId");
    
    if (ownerId === player.id && entityId.startsWith(MOD_PREFIX)) {
      if (companionType) {
        // Check for specific companion type
        if (entityId === `${MOD_PREFIX}${companionType}`) {
          companions.push(entity);
        }
      } else {
        // Get all companion types
        if (entityId.includes("dragon") || entityId.includes("elephant") || entityId.includes("fox") || 
            entityId.includes("leopard") || entityId.includes("manta_ray") || entityId.includes("panda") || 
            entityId.includes("phoenix") || entityId.includes("red_panda") || entityId.includes("tiger") || 
            entityId.includes("wolf")) {
          companions.push(entity);
        }
      }
    }
  });
  
  return companions;
}

/**
 * Despawns all companions belonging to player
 */
function despawnAllCompanions(player) {
  const entities = player.dimension.getEntities({
    location: player.location,
    maxDistance: 100
  });
  
  let despawnedCount = 0;
  entities.forEach(entity => {
    const entityId = entity.typeId;
    const ownerId = entity.getDynamicProperty("ownerId");
    
    if (ownerId === player.id && entityId.startsWith(MOD_PREFIX)) {
      // Check if it's any type of companion
      if (entityId.includes("dragon") || entityId.includes("elephant") || entityId.includes("fox") || 
          entityId.includes("leopard") || entityId.includes("manta_ray") || entityId.includes("panda") || 
          entityId.includes("phoenix") || entityId.includes("red_panda") || entityId.includes("tiger") || 
          entityId.includes("wolf")) {
        entity.triggerEvent("aft_soulhunters:despawn");
        despawnedCount++;
      }
    }
  });
  
  // Despawn completed silently
}

/**
 * Spawns a companion for the player (always deactivated)
 */
function spawnCompanion(player, companionType, souls) {
  try {
    const companionId = `${MOD_PREFIX}${companionType}`;
    const location = {
      x: player.location.x,
      y: player.location.y + 1,
      z: player.location.z
    };
    
    const companion = player.dimension.spawnEntity(companionId, location);
    if (!companion) return null;
    
    // Setup companion
    try {
      const tameable = companion.getComponent("minecraft:tameable");
      if (tameable && !tameable.isTamed) {
        tameable.tame(player);
      }
      companion.triggerEvent("aft_soulhunters:tame");
    } catch (e) {}
    
    // Set ownership and properties
    companion.setDynamicProperty("ownerId", player.id);
    companion.setDynamicProperty(ACTIVE_PROP, false); // Companions spawn deactivated
    
    // Add tags for abilities system
    companion.addTag("companion");
    
    // Keep companion deactivated 
    companion.triggerEvent(removeActivateEvent);
    
    // Set soul count
    try {
      const soulEventName = getSoulEventName(souls);
      companion.runCommand(`event entity @s aft_soulhunters:souls_bar_${soulEventName}`);
    } catch (e) {
      companion.triggerEvent(`aft_soulhunters:souls_bar_${getSoulEventName(souls)}`);
    }
    
    // Don't start soul drain - companion spawns deactivated
    // startSoulDrain(companion);
    
    return companion;
    
  } catch (error) {
    return null;
  }
}

/**
 * Activates a companion and starts soul drain
 */
function activateCompanion(companion) {
  if (!companion || !companion.isValid()) return false;
  
  companion.setDynamicProperty(ACTIVE_PROP, true);
  companion.triggerEvent(activateEvent);
  
  // Add active companion tag for abilities system
  companion.addTag("active_companion");
  
  startSoulDrain(companion);
  
  return true;
}

/**
 * Deactivates a companion and stops soul drain
 */
function deactivateCompanion(companion) {
  if (!companion || !companion.isValid()) return false;
  
  companion.setDynamicProperty(ACTIVE_PROP, false);
  companion.triggerEvent(removeActivateEvent);
  companion.triggerEvent(dontAttackEvent);
  
  // Remove active companion tag
  companion.removeTag("active_companion");
  
  return true;
}

/**
 * Updates player's companion based on current state
 */
function updatePlayerCompanion(player) {
  const playerState = playerStates.get(player.id) || {
    currentCompanion: null,
    lastCompanionType: null,
    isActivated: false,
    weaponWasInMainHand: false,
    lastUpdateHash: null,
    companionExists: false
  };
  
  const activeWeapon = getActiveCompanionWeapon(player);
  const allWeapons = findCompanionWeapons(player);
  
  // Create a hash of current state to prevent unnecessary updates
  const currentStateHash = `${activeWeapon?.companion || 'none'}_${activeWeapon?.slot || 'none'}_${allWeapons.length}`;
  
  // Skip update if state hasn't changed (unless companion is missing)
  if (playerState.lastUpdateHash === currentStateHash && playerState.companionExists) {
    return;
  }
  
  if (!activeWeapon) {
    // No active weapon found
    if (allWeapons.length === 0) {
      // No companion weapons at all - despawn completely
      if (playerState.currentCompanion) {
        despawnAllCompanions(player);
        player.sendMessage("§7Companion despawned - no companion weapons");
        playerState.currentCompanion = null;
        playerState.lastCompanionType = null;
        playerState.isActivated = false;
        playerState.companionExists = false;
      }
    }
  } else {
    // We have an active weapon
    const needsChange = !playerState.currentCompanion || 
                       playerState.currentCompanion !== activeWeapon.companion;
    
    if (needsChange) {
      // Only despawn if we actually have a different companion
      if (playerState.currentCompanion && playerState.currentCompanion !== activeWeapon.companion) {
        despawnAllCompanions(player);
        playerState.companionExists = false;
      }
      
      // Spawn new companion if we don't have one or need a different type
      if (!playerState.companionExists || playerState.currentCompanion !== activeWeapon.companion) {
        const companion = spawnCompanion(player, activeWeapon.companion, activeWeapon.souls);
        if (companion) {
          playerState.currentCompanion = activeWeapon.companion;
          playerState.currentSouls = activeWeapon.souls;
          playerState.lastCompanionType = activeWeapon.companion;
          playerState.isActivated = false; // Always spawn deactivated
          playerState.companionExists = true;
        }
      }
    } else if (playerState.currentCompanion === activeWeapon.companion) {
      // Same companion type - check if companion exists
      const existingCompanions = getPlayerCompanions(player, activeWeapon.companion);
      
      // Remove any duplicate companions (but keep the first one)
      if (existingCompanions.length > 1) {
        for (let i = 1; i < existingCompanions.length; i++) {
          if (existingCompanions[i].isValid()) {
            existingCompanions[i].remove();
          }
        }
      }
      
      if (existingCompanions.length === 0) {
        // Companion disappeared somehow, respawn it (but only once)
        if (playerState.companionExists) {
          const companion = spawnCompanion(player, activeWeapon.companion, activeWeapon.souls);
          if (companion) {
            playerState.isActivated = false;
            player.sendMessage(`§7Companion respawned: §a${activeWeapon.companion}`);
          }
        }
        playerState.companionExists = false;
      } else {
        playerState.companionExists = true;
        
        // Handle activation/deactivation based on weapon location
        const companion = existingCompanions[0];
        
        if (activeWeapon.slot === "mainhand") {
          // Weapon is in main hand - companion can be activated
          if (!playerState.weaponWasInMainHand) {
            // Only message when transitioning to main hand
            player.sendMessage(`§7Companion ready: §a${activeWeapon.companion} §7- shift+right-click to activate`);
            playerState.weaponWasInMainHand = true;
          }
        } else {
          // Weapon is in inventory, not main hand - only deactivate if currently activated
          if (playerState.isActivated) {
            deactivateCompanion(companion);
            playerState.isActivated = false;
            player.sendMessage("§7Companion deactivated - weapon not in main hand");
          }
          playerState.weaponWasInMainHand = false;
        }
      }
    }
  }
  
  // Update the hash to prevent unnecessary future updates
  playerState.lastUpdateHash = currentStateHash;
  playerStates.set(player.id, playerState);
}

/**
 * Activates/deactivates companion
 */
function toggleCompanionActivation(player) {
  const playerState = playerStates.get(player.id);
  if (!playerState || !playerState.currentCompanion) return;
  
  // Find the companion entity
  const entities = player.dimension.getEntities({
    location: player.location,
    maxDistance: 50
  });
  
  for (const entity of entities) {
    if (entity.getDynamicProperty("ownerId") === player.id && 
        entity.typeId === `${MOD_PREFIX}${playerState.currentCompanion}`) {
      
      if (playerState.isActivated) {
        // Deactivate
        entity.setDynamicProperty(ACTIVE_PROP, false);
        entity.triggerEvent("aft_soulhunters:remove_activate");
        entity.triggerEvent(dontAttackEvent);
        playerState.isActivated = false;
        player.sendMessage("§cCompanion deactivated");
      } else {
        // Activate
        entity.triggerEvent("aft_soulhunters:activate");
        entity.setDynamicProperty(ACTIVE_PROP, true);
        startSoulDrain(entity); // Start soul drain when activated
        playerState.isActivated = true;
        player.sendMessage("§aCompanion activated!");
        
        // Set activation cooldown to prevent UI conflict
        recentActivations.set(player.id, Date.now());
        system.runTimeout(() => {
          recentActivations.delete(player.id);
        }, 40); // 2 second cooldown
      }
      
      playerStates.set(player.id, playerState);
      break;
    }
  }
}

// ================================================================================================
// EVENT HANDLERS
// ================================================================================================

// Monitor player inventory changes every 3 seconds for responsive companion management
system.runInterval(() => {
  for (const player of world.getPlayers()) {
    try {
      updatePlayerCompanion(player);
    } catch (error) {
      // Silently handle errors
    }
  }
}, 60); // Every 3 seconds (60 ticks) - less frequent to prevent spam

// Handle shift + right-click on weapons
world.afterEvents.itemUse.subscribe((event) => {
  const { source: player, itemStack } = event;
  
  if (!player.isSneaking) return;
  if (!itemStack || !COMPANION_WEAPONS.includes(itemStack.typeId)) return;
  
  const companion = getCompanionFromLore(itemStack);
  if (!companion) return;
  
  // Only allow activation if this weapon is the active weapon
  const activeWeapon = getActiveCompanionWeapon(player);
  if (activeWeapon && activeWeapon.companion === companion) {
    toggleCompanionActivation(player);
  }
});

// Clean up when players leave
world.afterEvents.playerLeave.subscribe((event) => {
  playerStates.delete(event.playerId);
});

// Reset companion state when player respawns to prevent double spawning
world.afterEvents.playerSpawn.subscribe((event) => {
  const { player, initialSpawn } = event;
  
  if (!initialSpawn) {
    // Player respawned after death - reset companion state
    const playerState = playerStates.get(player.id);
    if (playerState) {
      playerState.companionExists = false;
      playerState.isActivated = false;
      playerState.currentCompanion = null;
      playerState.lastUpdateHash = null;
      playerStates.set(player.id, playerState);
    }
    
    // Remove any existing companions for this player to prevent duplicates
    const allCompanions = world.getDimension("overworld").getEntities({
      families: ["companion"]
    });
    
    for (const companion of allCompanions) {
      try {
        const ownerId = companion.getDynamicProperty("ownerId");
        if (ownerId === player.id) {
          companion.remove();
        }
      } catch (error) {
        // Skip invalid companions
      }
    }
  }
});

// Track player item changes for immediate companion response
const playerItemTracker = new Map();

// More frequent monitoring for immediate response to weapon changes
system.runInterval(() => {
  for (const player of world.getPlayers()) {
    try {
      // Track main hand item changes for immediate companion response
      const mainhand = player.getComponent("equippable")?.getEquipment(EquipmentSlot.Mainhand);
      const mainhandId = mainhand?.typeId || "empty";
      const lastMainhandId = playerItemTracker.get(player.id) || "";
      
      if (mainhandId !== lastMainhandId) {
        // Item changed, immediately update companion
        playerItemTracker.set(player.id, mainhandId);
        updatePlayerCompanion(player);
      }
    } catch (error) {
      // Silently handle errors
    }
  }
}, 20); // Every 1 second (20 ticks) for main hand changes only

// Clean up item tracker when players leave
world.afterEvents.playerLeave.subscribe((event) => {
  playerItemTracker.delete(event.playerId);
});

// ================================================================================================
// TESTING COMMANDS
// ================================================================================================

// Register testing commands
system.afterEvents.scriptEventReceive.subscribe((event) => {
  const { id, message, sourceEntity } = event;
  
  if (!id.startsWith("soulhunters:")) return;
  if (!sourceEntity || sourceEntity.typeId !== "minecraft:player") return;
  
  const player = sourceEntity;
  
  switch (id) {
    case "soulhunters:test_new_companion":
      if (!message || message.trim() === "") {
        player.sendMessage("§e§lAvailable Types: §fdragon, elephant, fox, leopard, manta_ray, panda, phoenix, red_panda, tiger, wolf");
        player.sendMessage("§bUsage: §f/scriptevent soulhunters:test_new_companion <type>");
        return;
      }
      
      const companionType = message.trim().toLowerCase();
      if (!Object.values(COMPANION_TYPES).includes(companionType)) {
        player.sendMessage("§cInvalid companion type!");
        return;
      }
      
      // Add companion lore to held weapon
      const mainhand = player.getComponent("equippable").getEquipment(EquipmentSlot.Mainhand);
      if (!mainhand || !COMPANION_WEAPONS.includes(mainhand.typeId)) {
        player.sendMessage("§cYou must be holding a valid Soul Hunters weapon (Tier 2, 3, or 4)!");
        return;
      }
      
      const companionName = Object.keys(COMPANION_TYPES).find(key => COMPANION_TYPES[key] === companionType);
      const newLore = [companionName, "10/10 Souls"];
      mainhand.setLore(newLore);
      
      player.getComponent("equippable").setEquipment(EquipmentSlot.Mainhand, mainhand);
      player.sendMessage(`§a§lSuccess! Added ${companionName} lore to your weapon!`);
      player.sendMessage("§7The companion should spawn automatically in a few seconds.");
      break;
      
    case "soulhunters:companion_status":
      const weapons = findCompanionWeapons(player);
      const playerState = playerStates.get(player.id) || {};
      
      player.sendMessage("§e§l=== Companion Status ===");
      player.sendMessage(`§7Current Companion: §f${playerState.currentCompanion || "None"}`);
      player.sendMessage(`§7Activated: §f${playerState.isActivated ? "Yes" : "No"}`);
      player.sendMessage(`§7Last Type: §f${playerState.lastCompanionType || "None"}`);
      player.sendMessage(`§7Weapons Found: §f${weapons.length}`);
      
      weapons.forEach((weapon, index) => {
        const slotText = weapon.slot === "mainhand" ? "Main Hand" : `Slot ${weapon.slot}`;
        player.sendMessage(`§8${index + 1}. §f${weapon.companion} §7(${weapon.souls}/10) §8[${slotText}]`);
      });
      break;
      
    case "soulhunters:force_update":
      updatePlayerCompanion(player);
      player.sendMessage("§aForced companion update!");
      break;
  }
});

// ================================================================================================
// UI AND SOUL MANAGEMENT FUNCTIONS
// ================================================================================================

/**
 * Shows companion control UI with behavior options
 */
function showCompanionControlUI(player, companion) {
  if (!player || !companion) return;

  // Check if companion was recently activated via shift+click
  const recentActivation = recentActivations.get(player.id);
  if (recentActivation && (Date.now() - recentActivation) < 2000) {
    // Don't show UI if companion was recently activated
    return;
  }

  const isActive = companion.getDynamicProperty(ACTIVE_PROP);
  if (!isActive) {
    // Skip inactive companions - they should be activated through other means
    player.sendMessage("§cThis companion is not currently active.");
    return;
  }

  // Get the weapon that this companion belongs to
  const weapons = findCompanionWeapons(player);
  const companionType = companion.typeId.replace(MOD_PREFIX, "");
  const companionWeapon = weapons.find(w => w.companion === companionType);
  
  if (!companionWeapon) {
    player.sendMessage("Cannot find companion weapon in inventory.");
    return;
  }

  const currentSouls = companionWeapon.souls;

  if (currentSouls <= 0) {
    player.sendMessage("Your companion has no souls left to fight.");
    companion.triggerEvent(dontAttackEvent);
    return;
  }

  const form = new ActionFormData()
    .title("Companion Control")
    .body("Select an option for your companion:");
  
  UI_OPTIONS.forEach(option => form.button(option.text, option.texture));

  form.show(player).then(response => {
    if (response.canceled) return;

    const selectedOption = UI_OPTIONS[response.selection];
    if (!selectedOption) return;

    if (currentSouls <= 0) {
      player.sendMessage("Your companion has no souls left and cannot fight.");
      companion.triggerEvent(dontAttackEvent);
      return;
    }

    // Handle special abilities separately
    if (selectedOption.event === "special_ability") {
      const abilityInfo = getAbilityInfo(companionType);
      const cooldown = getAbilityCooldown(companion.id, "special");
      
      if (cooldown > 0) {
        player.sendMessage(`§cSpecial ability is on cooldown for ${Math.ceil(cooldown / 1000)} seconds.`);
        return;
      }
      
      if (abilityInfo) {
        // Set both attack state and special trigger for abilities system
        companion.setProperty("aft_soulhunters:attack_state", "special");
        companion.setProperty("aft_soulhunters:special_trigger", 1);
        
        // Ensure companion has proper tags for abilities system
        companion.addTag("active_companion");
        
        player.sendMessage(`§6${companion.nameTag} used ${abilityInfo.name}!`);
        player.sendMessage(`§7${abilityInfo.description}`);
      } else {
        player.sendMessage("§cSpecial ability not available for this companion type.");
      }
      return;
    }
    
    // Handle riding separately
    if (selectedOption.event === "ride_companion") {
      try {
        // Get the rideable component and make player ride the companion
        const rideable = companion.getComponent("minecraft:rideable");
        if (rideable) {
          // Add the player as a rider
          rideable.addRider(player);
          player.sendMessage(`§aYou are now riding ${companion.nameTag}!`);
        } else {
          player.sendMessage("§cThis companion cannot be ridden.");
        }
      } catch (error) {
        player.sendMessage("§cFailed to ride companion. Make sure the companion is close to you.");
      }
      return;
    }

    companion.triggerEvent(selectedOption.event);
    companion.setDynamicProperty(BEHAVIOR_PROP, selectedOption.event);
    player.sendMessage(`Mode changed to: ${selectedOption.text}`);
    
    // Play companion interaction sound
    player.playSound("aft_soulhunters_companion_hihi");
  });
}

/**
 * Handles soul feeding to companions
 */
function handleCompanionSoulFeeding(player, companion, soulItem) {
  const weapons = findCompanionWeapons(player);
  const companionType = companion.typeId.replace(MOD_PREFIX, "");
  const companionWeapon = weapons.find(w => w.companion === companionType);
  
  if (!companionWeapon) {
    player.sendMessage("Cannot find companion weapon in inventory.");
    return;
  }

  let souls = companionWeapon.souls;
  if (souls >= MAX_SOULS) {
    player.sendMessage("Your companion already has maximum souls!");
    return;
  }

  // Consume the soul item
  const equippable = player.getComponent("minecraft:equippable");
  const mainHandItem = equippable?.getEquipment(EquipmentSlot.Mainhand);
  
  if (mainHandItem && mainHandItem.typeId === SOUL_ITEM_ID) {
    if (mainHandItem.amount > 1) {
      mainHandItem.amount -= 1;
      equippable.setEquipment(EquipmentSlot.Mainhand, mainHandItem);
    } else {
      equippable.setEquipment(EquipmentSlot.Mainhand, undefined);
    }
  }

  // Update souls
  souls++;
  updateWeaponLore(companionWeapon.item, companionType, souls);
  
  // Update weapon in inventory
  if (companionWeapon.slot === "mainhand") {
    equippable.setEquipment(EquipmentSlot.Mainhand, companionWeapon.item);
  } else {
    const inventory = player.getComponent("inventory");
    if (inventory && inventory.container) {
      inventory.container.setItem(companionWeapon.slot, companionWeapon.item);
    }
  }

  // Update companion soul bar
  const scoreName = SCORE_TO_EVENT[souls];
  try {
    companion.runCommand(`event entity @s aft_soulhunters:souls_bar_${scoreName}`);
    companion.triggerEvent("aft_soulhunters:eat");
    player.sendMessage(`§aFed soul to ${companion.nameTag}! (${souls}/${MAX_SOULS})`);
  } catch (e) {
    // Soul bar update failed silently
  }
}

/**
 * Starts soul drain for active companion
 */
function startSoulDrain(companion) {
  const companionType = companion.typeId.replace(MOD_PREFIX, "");
  const ownerId = companion.getDynamicProperty("ownerId");
  
  const intervalId = system.runInterval(() => {
    if (!companion.isValid()) {
      system.clearRun(intervalId);
      return;
    }
    
    const isActive = companion.getDynamicProperty(ACTIVE_PROP);
    if (!isActive) {
      system.clearRun(intervalId);
      return;
    }

    // Find the companion owner
    const owner = world.getPlayers().find(p => p.id === ownerId);
    if (!owner) {
      system.clearRun(intervalId);
      return;
    }

    const weapons = findCompanionWeapons(owner);
    const companionWeapon = weapons.find(w => w.companion === companionType);
    
    if (!companionWeapon) {
      // No weapon found, but don't deactivate - let the update system handle it
      return;
    }

    let souls = companionWeapon.souls;
    const scoreName = SCORE_TO_EVENT[souls];

    // Update soul bar
    try {
      companion.runCommand(`event entity @s aft_soulhunters:souls_bar_${scoreName}`);
    } catch (e) {}

    if (souls > 0) {
      souls--;
      updateWeaponLore(companionWeapon.item, companionType, souls);
      
      // Update weapon in inventory
      if (companionWeapon.slot === "mainhand") {
        const equippable = owner.getComponent("minecraft:equippable");
        equippable.setEquipment(EquipmentSlot.Mainhand, companionWeapon.item);
      } else {
        const inventory = owner.getComponent("inventory");
        if (inventory && inventory.container) {
          inventory.container.setItem(companionWeapon.slot, companionWeapon.item);
        }
      }
      
      // Update player state to track current souls
      const playerState = playerStates.get(owner.id) || {};
      playerState.currentSouls = souls;
      playerStates.set(owner.id, playerState);
    }

    // Only deactivate if souls reach 0 AND weapon is in main hand (actively being used)
    if (souls <= 0 && companionWeapon.slot === "mainhand") {
      companion.setDynamicProperty(ACTIVE_PROP, false);
      companion.triggerEvent(noSoulsEvent);
      companion.triggerEvent(dontAttackEvent);
      
      // Update player state
      const playerState = playerStates.get(owner.id) || {};
      playerState.isActivated = false;
      playerStates.set(owner.id, playerState);
      
      system.clearRun(intervalId);
      owner.sendMessage(`§c${companion.nameTag} has run out of souls and stopped fighting.`);
    }
  }, 600); // Every 30 seconds (600 ticks) - longer interval to prevent rapid deactivation
}

// ================================================================================================
// COMPANION INTERACTION HANDLERS
// ================================================================================================

// NOTE: Companion interactions are handled by interaction_handler.js unified system
// This avoids duplicate event handlers for the same interactions

// ================================================================================================
// EXPORTS
// ================================================================================================

export {
  updatePlayerCompanion,
  toggleCompanionActivation,
  getActiveCompanionWeapon,
  findCompanionWeapons,
  showCompanionControlUI,
  handleCompanionSoulFeeding,
  updateWeaponLore,
  getWeaponInfo,
  startSoulDrain,
  activateCompanion,
  deactivateCompanion,
  getPlayerCompanions
};
