import { world, system, EquipmentSlot, EntityEquippableComponent, ItemStack, EnchantmentType } from "@minecraft/server";
import './book'
///////LAVA CAT
world.afterEvents.entityHitEntity.subscribe((eventData) => {
    const entity = eventData.damagingEntity
    const entity_hitted = eventData.hitEntity
    if (entity.typeId === 'bunny_ce:lava_cat' && entity.hasTag(`tamed_regeneration`)) {
        entity_hitted.setOnFire(5);
    }
});

system.runInterval(() => {
  const entities = world.getDimension("overworld").getEntities();
  entities.push(...world.getDimension("nether").getEntities());
  entities.push(...world.getDimension("the_end").getEntities());

  for (const entity of entities) {
    // Verificar si la entidad es de tipo 'bunny_ce' y no es uno de los excluidos
    if (!entity.typeId.startsWith('bunny_ce:')) continue;
    if (entity.nameTag) continue;
    
    // Excluir 'book' y 'chair_cat'
    if (entity.typeId === 'bunny_ce:book' || entity.typeId === 'bunny_ce:chair_cat') continue;

    // Generar el nombre a partir del typeId
    const name = entity.typeId.replace('bunny_ce:', '').split("_").map(word => 
      word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
    entity.nameTag = name;
  }
});
world.beforeEvents.playerBreakBlock.subscribe((event) => {
    const { player, block } = event;

    // Verificación directa del bloque de diamante
    if (block.typeId === 'minecraft:diamond_ore' || block.typeId === 'minecraft:diamond_ore') {
        system.run(() => {
            // Buscar gatos cerca (15 bloques)
            const cats = player.dimension.getEntities({
                location: player.location,
                maxDistance: 15,
                type: 'bunny_ce:lucky_cat'
            });

            // Verificar gatos con tag
            for (const cat of cats) {
                if (cat.hasTag('lucky_cat_tamed')) {
                    // 15% de probabilidad
                    if (Math.random() < 0.15) {
                        // 50% totem, 50% 2 diamantes
                        if (Math.random() < 0.5) {
                            player.runCommand(`give @s minecraft:totem_of_undying 1`);
                        } else {
                            player.runCommand(`give @s minecraft:diamond 2`);
                        }
                        break; // Solo activar una vez por rotura
                    }
                }
            }
        });
    }
});

/////MINER CAT
const COOLDOWN_TIME = 120000; // 2 minutes in ms
const cooldowns = new Map();

// Official Equipment Slots
const EquipmentSlots = {
    HEAD: "Head",
    CHEST: "Chest",
    LEGS: "Legs",
    FEET: "Feet",
    MAINHAND: "Mainhand",
    OFFHAND: "Offhand"
};

world.afterEvents.playerInteractWithEntity.subscribe((ev) => {
    try {
        const { player, target: entity } = ev;

        // Verify Miner Cat
        if (entity.typeId !== 'bunny_ce:miner_cat' || !entity.hasTag('miner_haste')) return;

        // Cooldown check
        if (player.isSneaking) {
            const now = Date.now();
            const lastUse = cooldowns.get(player.id) || 0;
            if (now - lastUse < COOLDOWN_TIME) {
                const remaining = Math.ceil((COOLDOWN_TIME - (now - lastUse)) / 1000);
                player.sendMessage(`§cPlease wait ${remaining} seconds to use again`);
                return;
            }

            // Get equipment component
            const equipment = player.getComponent("minecraft:equippable");
            let repaired = false;

            // Slots to check (armor + mainhand)
            const repairSlots = [
                EquipmentSlots.HEAD,
                EquipmentSlots.CHEST,
                EquipmentSlots.LEGS,
                EquipmentSlots.FEET,
                EquipmentSlots.MAINHAND
            ];

            for (const slot of repairSlots) {
                try {
                    const item = equipment.getEquipment(slot);
                    if (!item) continue;

                    // Check if repairable item
                    const itemType = item.typeId;
                    const isRepairable = /(helmet|chestplate|leggings|boots|pickaxe|shovel|axe|sword)/.test(itemType);

                    if (isRepairable) {
                        const durability = item.getComponent("minecraft:durability");
                        if (durability?.damage > 0) {
                            durability.damage = 0;
                            equipment.setEquipment(slot, item);
                            repaired = true;

                            // Visual feedback
                            const particle = slot === EquipmentSlots.MAINHAND ?
                                'minecraft:critical_hit' : 'minecraft:heart_particle';
                            player.runCommand(`particle ${particle} ~ ~1 ~`);
                        }
                    }
                } catch (error) {
                    console.warn(`Error processing ${slot}:`, error);
                }
            }

            // Player feedback
            if (repaired) {
                cooldowns.set(player.id, now);
                player.playSound("random.anvil_use");
                player.runCommand("title @s actionbar §aItems And Armor Repaired!");
                entity.runCommand("particle minecraft:flame ~ ~ ~");
            } else {
                player.sendMessage("§eNo damaged items found");
                player.playSound("random.orb");
            }
        }

    } catch (error) {
        console.error("Repair System Error:", error);
        player?.sendMessage("§cRepair failed. Please try again.");
    }
});
////WITCH CAT
const witchCooldowns = new Map();
const POSITIVE_EFFECTS = [
    { effect: 'speed', duration: 120, amplifier: 1, name: '§bSpeed' },
    { effect: 'haste', duration: 120, amplifier: 1, name: '§6Haste' },
    { effect: 'resistance', duration: 120, amplifier: 0, name: '§cResistance' },
    { effect: 'jump_boost', duration: 120, amplifier: 1, name: '§dLeaping' },
    { effect: 'strength', duration: 120, amplifier: 0, name: '§4Strength' },
    { effect: 'regeneration', duration: 120, amplifier: 0, name: '§aRegeneration' },
    { effect: 'water_breathing', duration: 120, amplifier: 0, name: '§3Aquatic Breathing' },
    { effect: 'night_vision', duration: 120, amplifier: 0, name: '§5Night Vidion' },
    { effect: 'fire_resistance', duration: 120, amplifier: 0, name: '§6Fire resistance' },
    { effect: 'health_boost', duration: 120, amplifier: 0, name: '§cHealth Boost' }
];

// Sistema principal
system.runInterval(() => {
    const players = world.getAllPlayers();

    for (const player of players) {
        // Buscar witch_cats cerca del jugador
        const entities = player.dimension.getEntities({
            location: player.location,
            maxDistance: 10,
            type: 'bunny_ce:witch_cat'
        });

        for (const witchCat of entities) {
            if (witchCat.hasTag('witch_poison')) {
                handleWitchCat(player, witchCat);
            }
        }
    }
}, 100);

function handleWitchCat(player, witchCat) {
    const playerId = player.id;
    const lastPotion = witchCooldowns.get(playerId) || 0;

    // Cooldown de 2 minutos
    if (Date.now() - lastPotion < 120000) return;

    const randomEffect = POSITIVE_EFFECTS[Math.floor(Math.random() * POSITIVE_EFFECTS.length)];

    // Aplicar efecto
    player.runCommand(`effect @s ${randomEffect.effect} ${randomEffect.duration} ${randomEffect.amplifier}`);

    // Efectos visuales
    player.playSound('random.levelup');
    player.runCommand(`particle minecraft:heart_particle ~ ~1 ~`);

    // Animación del gato
    player.runCommand(`particle minecraft:witch_magic ${witchCat.location.x} ${witchCat.location.y + 0.5} ${witchCat.location.z}`);

    // Mensaje mejorado
    player.onScreenDisplay.setActionBar(
        `§5${randomEffect.name} §fReceived from §dWitch Cat\n` +
        `§7Duration: §f2 Minutes §7| §7Level: §f${randomEffect.amplifier + 1}`
    );

    // Actualizar cooldown
    witchCooldowns.set(playerId, Date.now());
}

/////FARMER CAT
// Configuración
const GROWTH_RANGE = 3; // Radio de 3 bloques (6x6 total)
const GROWTH_CHANCE = 0.8; // 40% de probabilidad por cultivo
const CROPS = [
    "minecraft:wheat",
    "minecraft:carrots",
    "minecraft:potatoes",
    "minecraft:beetroots",
    "minecraft:nether_wart"
];

// Sistema que se ejecuta cada 30 segundos
system.runInterval(() => {
    const farmerCats = world.getDimension('overworld').getEntities({
        type: "bunny_ce:farmer_cat",
        tags: ["farmer_crops"]
    });

    for (const cat of farmerCats) {
        if (!cat.isValid()) continue;

        // Obtener posición del gato
        const { x, y, z } = cat.location;

        // Escanear área 6x6 alrededor del gato
        for (let dx = -GROWTH_RANGE; dx <= GROWTH_RANGE; dx++) {
            for (let dz = -GROWTH_RANGE; dz <= GROWTH_RANGE; dz++) {
                // Solo aplicar a 40% de los bloques (para optimizar)
                if (Math.random() > GROWTH_CHANCE) continue;

                const blockPos = { x: x + dx, y: y, z: z + dz };
                const block = cat.dimension.getBlock(blockPos);

                if (block && CROPS.includes(block.typeId)) {
                    // Aumentar crecimiento al máximo (nivel 7)
                    system.run(() => {
                        try {
                            // Usar setblock para actualizar el estado de crecimiento
                            cat.dimension.runCommand(
                                `setblock ${blockPos.x} ${blockPos.y} ${blockPos.z} ${block.typeId.replace('minecraft:', '')} ["growth"=7]`
                            );

                            // Efectos visuales
                            cat.dimension.runCommand(
                                `particle minecraft:crop_growth_area_emitter ${blockPos.x} ${blockPos.y} ${blockPos.z}`
                            );
                        } catch (error) {
                            console.error("Error al hacer crecer cultivos:", error);
                        }
                    });
                }
            }
        }

        // Efecto visual central
        cat.dimension.runCommand(`particle minecraft:happy_villager ${x} ${y + 0.5} ${z}`);
    }
}, 10 * 20); // Ejecutar cada 30 segundos (600 ticks)


const enchantCooldowns = new Map();
const ENCHANT_COOLDOWN = 30; // segundos
const ENCHANT_PARTICLES = "minecraft:enchant";

// Cache de tipos de encantamiento para mejor performance
const ENCHANTMENT_TYPES = {
    SHARPNESS: new EnchantmentType('sharpness'),
    UNBREAKING: new EnchantmentType('unbreaking'),
    EFFICIENCY: new EnchantmentType('efficiency'),
    MENDING: new EnchantmentType('mending')
};

// Configuración de encantamientos disponibles
const AVAILABLE_ENCHANTMENTS = [
    { type: ENCHANTMENT_TYPES.SHARPNESS, name: "Sharpnness", maxLevel: 5 },
    { type: ENCHANTMENT_TYPES.UNBREAKING, name: "Unbreaking", maxLevel: 3 },
    { type: ENCHANTMENT_TYPES.EFFICIENCY, name: "Efficiency", maxLevel: 5 },
    { type: ENCHANTMENT_TYPES.MENDING, name: "Mending", maxLevel: 1 }
];

// Sistema de cooldown mejorado
function checkCooldown(player) {
    const lastUse = enchantCooldowns.get(player.id) || 0;
    const currentTime = Date.now();
    const remaining = ENCHANT_COOLDOWN - Math.floor((currentTime - lastUse) / 1000);

    if (remaining > 0) {
        player.onScreenDisplay.setActionBar(`§eWait ${remaining}s for enchant`);
        return remaining;
    }
    return 0;
}

// Función principal de encantamiento
function applyRandomEnchantment(player, item) {
    try {
        const enchantable = item.getComponent('minecraft:enchantable');

    // Filtrar encantamientos posibles (que el item no tenga ya)
    const possibleEnchants = AVAILABLE_ENCHANTMENTS.filter(enc => {
        try {
            return !enchantable.hasEnchantment(enc.type);
        } catch {
            return false;
        }
    });

    if (possibleEnchants.length === 0) {
        player.onScreenDisplay.setActionBar("§6¡you item have already enchants!");
        return false;
    }

    // Seleccionar y aplicar encantamiento aleatorio
    const selectedEnchant = possibleEnchants[Math.floor(Math.random() * possibleEnchants.length)];
    const level = Math.floor(Math.random() * selectedEnchant.maxLevel) + 1;

    enchantable.addEnchantment({
        type: selectedEnchant.type,
        level: level
    });

    // Feedback al jugador
    player.onScreenDisplay.setActionBar(`§a${selectedEnchant.name} ${toRoman(level)} apply!`);
    player.playSound("random.orb");

    return true;
    } catch (error) {
        return
    }
}

// Función para números romanos (optimizada)
function toRoman(num) {
    const roman = ["I", "II", "III", "IV", "V"];
    return roman[num - 1] || num.toString();
}

// Evento principal
world.afterEvents.playerInteractWithEntity.subscribe((event) => {
    const { player, target: entity } = event;

    // Verificar si es el gato encantador correcto
    if (entity.typeId !== 'bunny_ce:enchanter_cat' || !entity.hasTag('enchantable_item')) return;
    if (!player.isSneaking) return;
    // Verificar cooldown sin bloquear el tick
    if (checkCooldown(player)) return;

    // Obtener item en mano
    const equipment = player.getComponent('equippable');
    const item = equipment.getEquipment('Mainhand');

    // Verificar item válido
    if (!item?.hasComponent?.('minecraft:enchantable')) {
        player.onScreenDisplay.setActionBar("§chold you item in your hand!");
        return;
    }

    try {
        // Intentar aplicar encantamiento
        if (applyRandomEnchantment(player, item)) {
            // Actualizar cooldown solo si fue exitoso
            enchantCooldowns.set(player.id, Date.now());
            // Efectos visuales
            entity.runCommand(`particle ${ENCHANT_PARTICLES} ~ ~ ~`);
            // Actualizar item en mano
            equipment.setEquipment('Mainhand', item);
        }
    } catch (error) {
        console.error("[Encantamiento] Error:", error);
        player.onScreenDisplay.setActionBar("§c¡Error al aplicar el encantamiento!");
    }
});


world.afterEvents.entityHitEntity.subscribe((eventData) => {
    const entity = eventData.damagingEntity
    const entity_hitted = eventData.hitEntity
    if (entity.typeId === 'bunny_ce:skeleton_cat' && entity.hasTag(`witch_poison`)) {
        if (entity_hitted.typeId === 'minecraft:skeleton') {
            entity_hitted.kill();
        }
    }
});



world.afterEvents.entityHitEntity.subscribe((eventData) => {
    const entity = eventData.damagingEntity
    const entity_hitted = eventData.hitEntity

    if (entity.typeId === 'bunny_ce:ender_cat' && entity.hasTag(`witch_poison`)) {
        if (entity_hitted.typeId === 'minecraft:enderman') {
            entity_hitted.kill();
        }
    }
});



// Constantes de dirección
const BlockFace = {
    Down: "Down",
    East: "East",
    North: "North",
    South: "South",
    Up: "Up",
    West: "West"
};

// Configuración
const BOWL_EMPTY = 'bunny_ce:cat_bowl';
const BOWL_WATER = 'bunny_ce:cat_bowl_water';
const BOWL_FOOD = 'bunny_ce:cat_bowl_food';
const WATER_ITEMS = ['minecraft:water_bucket'];
const FOOD_ITEMS = [
    'minecraft:fish',
    'minecraft:salmon',
    'minecraft:cod',
    'minecraft:tropical_fish',
    'minecraft:cooked_fish',
    'minecraft:cooked_salmon',
    'minecraft:beef',
    'minecraft:cooked_beef',
    'minecraft:chicken',
    'minecraft:cooked_chicken',
    'minecraft:porkchop',
    'minecraft:cooked_porkchop',
    'minecraft:mutton',
    'minecraft:cooked_mutton',
    'minecraft:rabbit',
    'minecraft:cooked_rabbit'
];

world.beforeEvents.playerInteractWithBlock.subscribe((ev) => {
    const { player, block, itemStack: item, blockFace } = ev;

    // Verificar si es el tazón vacío y tiene item
    system.run(() => {
        if (block.typeId !== BOWL_EMPTY || !item) return;

        const dimension = block.dimension;
        const loc = block.location;

        // Calcular posición relativa según la cara interactuada
        let offset = { x: 0, y: 0, z: 0 };

        switch (blockFace) {
            case BlockFace.Up: offset.y = 1; break;
            case BlockFace.Down: offset.y = -1; break;
            case BlockFace.North: offset.z = -1; break;
            case BlockFace.South: offset.z = 1; break;
            case BlockFace.East: offset.x = 1; break;
            case BlockFace.West: offset.x = -1; break;
        }

        // Posición del bloque adyacente
        const targetLoc = {
            x: loc.x + offset.x,
            y: loc.y + offset.y,
            z: loc.z + offset.z
        };

        // Manejar agua
        if (WATER_ITEMS.includes(item.typeId)) {
            // Quitar el agua en la posición donde se colocó
            dimension.setBlockType(targetLoc, 'minecraft:air');

            // Cambiar el tazón solo si se coloca desde arriba
            if (blockFace === BlockFace.Up) {
                dimension.setBlockType(loc, BOWL_WATER);

                // Reset después de 2 minutos
                system.runTimeout(() => {
                    if (dimension.getBlock(loc)?.typeId === BOWL_WATER) {
                        dimension.setBlockType(loc, BOWL_EMPTY);
                    }
                }, 120 * 20);
            }

            // Dar bucket vacío y quitar el lleno
            player.runCommand(`clear @s minecraft:water_bucket 0 1`);
            player.runCommand(`give @s minecraft:bucket 1`);
            return;
        }

        // Manejar comida
        if (FOOD_ITEMS.includes(item.typeId)) {
            // Quitar la comida del inventario
            player.runCommand(`clear @s ${item.typeId} 0 1`);

            // Cambiar el tazón solo si se coloca desde arriba
            if (blockFace === BlockFace.Up) {
                dimension.setBlockType(loc, BOWL_FOOD);

                // Reset después de 2 minutos
                system.runTimeout(() => {
                    if (dimension.getBlock(loc)?.typeId === BOWL_FOOD) {
                        dimension.setBlockType(loc, BOWL_EMPTY);
                    }
                }, 120 * 20);
            }
        }
    })
});


world.beforeEvents.playerInteractWithEntity.subscribe((ev) => {
    system.run(() => {
        const { player, target } = ev;

        // 1. Verificar si es el comedero especial
        if (target.typeId !== 'bunny_ce:feeder_food') return;
        // 4. Si está agachado: DESPAWN

        target.triggerEvent('bunny_ce:food');
    });
});


const playerCooldowns = new Map();
const COOLDOWN_DURATION = 1500;
world.afterEvents.entityHitEntity.subscribe((event) => {
    const player = event.damagingEntity;
    const hitEntity = event.hitEntity;

    if (player.typeId !== "minecraft:player") return;
    if (hitEntity.typeId !== 'bunny_ce:feeder_food') return;

    if (!hitEntity.isValid()) return;

    const playerId = player.id;
    const currentTime = Date.now();

    if (playerCooldowns.has(playerId)) {
        const lastHitTime = playerCooldowns.get(playerId);
        if (currentTime - lastHitTime < COOLDOWN_DURATION) {
            return;
        }
    }
    playerCooldowns.set(playerId, currentTime);
    hitEntity.triggerEvent('bunny_ce:despawn');
});



world.beforeEvents.playerInteractWithEntity.subscribe((ev) => {
    system.run(() => {
        const { player, target } = ev;
        // 1. Verificar si es la silla de gato
        if (target.typeId !== 'bunny_ce:chair_cat') return;
        // 3. Disparar evento de despawn inmediatamente
        if (player.isSneaking) {
            target.triggerEvent('bunny_ce:despawn');
        }
    });
});


// Aquí están las vainas que necesitamos, mi pana
const GATA_FINA = 'bunny_ce:sphynx_cat';  // La gata vip
const TERRENO_CHIMO = ['minecraft:sand', 'minecraft:sandstone'];  // Donde se pone la gata
const RADIO_CURACION = 5;  // El alcance de la bendición
const EFECTO_ZAMURO = {  // El poder sanador
    type: 'regeneration',
    duration: 5,  // 5 segundos (100 ticks)
    amplifier: 0,   // Nivel 1 suavecito
    showParticles: true  // Pa' que se vea fancy
};

// Éste es el peo que se ejecuta cada rato
system.runInterval(() => {
    // Buscamos to'a las gatas sphynx en el mapa
    const dimension = world.getDimension('overworld');
    const gatas = dimension.getEntities({ type: GATA_FINA });

    for (const gata of gatas) {
        const ubicacionGata = gata.location;

        // Verificamos si está en terreno chimbo (arena/sandstone)
        const bloqueAbajo = dimension.getBlock({
            x: Math.floor(ubicacionGata.x),
            y: Math.floor(ubicacionGata.y) - 1,  // El bloque de abajo
            z: Math.floor(ubicacionGata.z)
        });

        // Si está en arena, activa el poder
        if (bloqueAbajo && TERRENO_CHIMO.includes(bloqueAbajo.typeId)) {
            // Buscamos jugadores cerca (5 bloques)
            const jugadoresCerca = dimension.getPlayers({
                location: ubicacionGata,
                maxDistance: RADIO_CURACION,
                minDistance: 0
            });

            // Le damos el efecto a cada player
            for (const jugador of jugadoresCerca) {
                jugador.addEffect(
                    EFECTO_ZAMURO.type,
                    EFECTO_ZAMURO.duration,
                    EFECTO_ZAMURO
                );
            }
        }
    }
}, 20);



world.afterEvents.playerPlaceBlock.subscribe((ev) => {
    const player = ev.player
    const block = ev.block
    if (block.typeId === 'bunny_ce:paw_carpet' ||
        block.typeId === 'bunny_ce:cat_ball_of_yarn' ||
        block.typeId === 'bunny_ce:cat_bed_black' ||
        block.typeId === 'bunny_ce:cat_bed_blue' ||
        block.typeId === 'bunny_ce:cat_bed_green' ||
        block.typeId === 'bunny_ce:cat_bed_red' ||
        block.typeId === 'bunny_ce:cat_bed_white' ||
        block.typeId === 'bunny_ce:cat_bell' ||
        block.typeId === 'bunny_ce:cat_bowl' ||
        block.typeId === 'bunny_ce:cat_house' ||
        block.typeId === 'bunny_ce:cat_stratcher' ||
        block.typeId === 'bunny_ce:painting_1' ||
        block.typeId === 'bunny_ce:painting_2' ||
        block.typeId === 'bunny_ce:painting'
    ) {
        player.runCommand(`playsound carpeta.sonido4 @s`)

    }
})
// 1. Lista de IDs de gatos (excluyendo chair_cat y feeder_food)
const CAT_ENTITIES = [
    "bunny_ce:ice_cat",
    "bunny_ce:chest_cat",
    "bunny_ce:enchanter_cat",
    "bunny_ce:ender_cat",
    "bunny_ce:sus_cat",
    "bunny_ce:farmer_cat",
    "bunny_ce:flash_cat",
    "bunny_ce:floppa_cat",
    "bunny_ce:healer_cat",
    "bunny_ce:hunter_cat",
    "bunny_ce:lava_cat",
    "bunny_ce:lucky_cat",
    "bunny_ce:mermaid_cat",
    "bunny_ce:miner_cat",
    "bunny_ce:mount_cat",
    "bunny_ce:pirate_cat",
    "bunny_ce:shadow_cat",
    "bunny_ce:skeleton_cat",
    "bunny_ce:sphynx_cat",
    "bunny_ce:witch_cat"
];

// 2. Sonido a reproducir (ajusta la ruta)
// Configuración de sonidos
const CAT_SOUNDS = [
    "mob.cat.meow",  // Sonido vanilla de maullido
    "mob.cat.purr",   // Sonido vanilla de ronroneo
    "carpeta.sonido2",      // Tu sonido personalizado
    "carpeta.sonido3"       // Otro sonido personalizado (opcional)
];

// Función mejorada para reproducir sonidos
function playCatSound(player, entity) {
    try {
        // 80% probabilidad de sonido normal, 20% de sonido especial
        const isSpecialSound = Math.random() < 0.2;

        let soundToPlay;
        let pitch;

        if (isSpecialSound && CAT_SOUNDS.length > 2) {
            // Sonido especial (excluyendo los primeros 2 sonidos vanilla)
            soundToPlay = CAT_SOUNDS[2 + Math.floor(Math.random() * (CAT_SOUNDS.length - 2))];
            pitch = 0.7 + Math.random() * 0.6;
        } else {
            // Sonido vanilla (meow o purr)
            soundToPlay = CAT_SOUNDS[Math.floor(Math.random() * 2)];
            pitch = 0.8 + Math.random() * 0.4;
        }

        // Reproducir sonido
        player.runCommand(`/playsound ${soundToPlay} @a ~~~ 0.5 ${pitch}`);

        // Efecto visual opcional para sonidos especiales
        if (isSpecialSound) {
            entity.dimension.spawnParticle("minecraft:heart_particle", entity.location);
        }
    } catch (e) {
        console.error("Error al reproducir sonido de gato:", e);
    }
}

// Sistema de sonidos aleatorios cerca del jugador (mejorado)
system.runInterval(() => {
    try {
        const players = world.getAllPlayers();

        players.forEach((player) => {
            try {
                const nearbyEntities = player.dimension.getEntities({
                    location: player.location,
                    maxDistance: 10,  // Aumenté la distancia
                    maxCount: 20       // Límite para optimización
                });

                nearbyEntities.forEach((entity) => {
                    try {
                        if (CAT_ENTITIES.includes(entity.typeId)) {
                            // Probabilidad ajustada por cantidad de gatos cerca
                            const catCount = nearbyEntities.filter(e =>
                                CAT_ENTITIES.includes(e.typeId)).length;
                            const probability = Math.min(0.3, 0.1 * catCount);

                            if (Math.random() < probability) {
                                system.run(() => playCatSound(player, entity));
                            }
                        }
                    } catch (e) {
                        console.error("Error procesando entidad cercana:", e);
                    }
                });
            } catch (e) {
                console.error("Error obteniendo entidades cercanas:", e);
            }
        });
    } catch (e) {
        console.error("Error en el intervalo de sonidos:", e);
    }
}, 20 * 5); // Cada 5 segundos (reducí la frecuencia)

// Sonido al interactuar con el gato (integrado con el sistema de domesticación)
world.beforeEvents.playerInteractWithEntity.subscribe((event) => {
    const { player, target: entity } = event;

    system.run(() => {
        try {
            if (CAT_ENTITIES.includes(entity.typeId)) {
                // 100% de probabilidad al interactuar
                playCatSound(player, entity);

                // Si tiene manzana dorada, sonido especial
                const mainhand = player.getComponent('equippable')?.getEquipment('Mainhand');
                if (mainhand?.typeId === 'minecraft:golden_apple') {
                    player.runCommand(`/playsound minecraft:cat.purr @a ~~~ 1 0.8`);
                }
            }
        } catch (e) {
            console.error("Error en interacción con gato:", e);
        }
    });
});


world.afterEvents.itemUse.subscribe((ev) => {

    const player = ev.source
    const item = ev.itemStack

    if (item.typeId === 'bunny_ce:cat_bell' || item.typeId === 'bunny_ce:cat_bell_item') {
        player.runCommand(`playsound carpeta.sonido1 @s`)
    }
})


const ultimoUso = new Map();

world.beforeEvents.playerInteractWithEntity.subscribe((ev) => {
    const { player, target } = ev;

    system.run(() => {
        // Verificamos si es el gato sospechoso
        if (target.typeId !== 'bunny_ce:sus_cat') return;

        if (player.isSneaking) {
            const ahora = Date.now();
            const ultimaVez = ultimoUso.get(player.id) || 0;

            // Si ha pasado menos de 1 segundo, lo ignoramos
            if (ahora - ultimaVez < 1000) {
                return;
            }

            // Actualizamos el último uso
            ultimoUso.set(player.id, ahora);

            // Ejecutamos el comando
            player.runCommand(`time add 500`);
        }

        // Mensaje opcional
    });
});
const processingCats = new Set();

world.beforeEvents.playerInteractWithEntity.subscribe((ev) => {
    system.run(() => {
        try {
            const { player, target } = ev;

            // Verificación rápida de tipo de entidad
            if (!CAT_ENTITIES.includes(target.typeId)) {
                return;
            }

            // Verificar el ítem en la mano de forma segura
            let mainhand;
            try {
                const equippable = player.getComponent('equippable');
                if (!equippable) return;
                mainhand = equippable.getEquipment('Mainhand');
            } catch (e) {
                console.error("[Cat Taming] Error al obtener equipo: " + e);
                return;
            }

            const itemId = mainhand?.typeId || '';
            if (itemId !== 'minecraft:golden_apple') {
                return;
            }

            // Verificar tags del gato
            const targetTags = target.getTags();
            if (targetTags.length === 0) {
                return;
            }

            // ID único del gato para evitar duplicados
            const catId = target.id;
            if (processingCats.has(catId)) {
                return;
            }
            processingCats.add(catId);

            // Quitar manzana con verificación
            try {
                const clearSuccess = player.runCommand('clear @s minecraft:golden_apple 0 1');
                if (!clearSuccess) {
                    console.error("[Cat Taming] No se pudo remover la manzana dorada");
                    processingCats.delete(catId);
                    return;
                }

                // Disparar evento inicial
                target.triggerEvent('bunny_ce:variant1');

                // Temporizador para tameo completo
                system.runTimeout(() => {
                    try {
                        // Verificar si el gato aún existe
                        if (target.isValid()) {
                            target.triggerEvent('on_tame');
                        }
                    } catch (e) {
                        console.error("[Cat Taming] Error en evento on_tame: " + e);
                    } finally {
                        processingCats.delete(catId);
                    }
                }, 20 * 15); // 20 segundos

            } catch (e) {
                console.error("[Cat Taming] Error en el proceso: " + e);
                processingCats.delete(catId);
            }

        } catch (error) {
            console.error("[Cat Taming] Error crítico: " + error);
        }
    })
});

const processingCats_e = new Set();

world.beforeEvents.playerInteractWithEntity.subscribe((ev) => {
    system.run(() => {
        try {
            const { player, target } = ev;

            // Verificación rápida de tipo de entidad
            if (!CAT_ENTITIES.includes(target.typeId)) {
                return;
            }

            // Verificar el ítem en la mano de forma segura
            let mainhand;
            try {
                const equippable = player.getComponent('equippable');
                if (!equippable) return;
                mainhand = equippable.getEquipment('Mainhand');
            } catch (e) {
                console.error("[Cat Taming] Error al obtener equipo: " + e);
                return;
            }

            const itemId = mainhand?.typeId || '';
            if (itemId !== 'bunny_ce:catnip') {
                return;
            }

            // Verificar tags del gato
            const targetTags = target.getTags();
            if (targetTags.length === 0) {
                return;
            }

            // ID único del gato para evitar duplicados
            const catId = target.id;
            if (processingCats_e.has(catId)) {
                return;
            }
            processingCats_e.add(catId);

            // Quitar manzana con verificación
            try {
                const clearSuccess = player.runCommand('clear @s bunny_ce:catnip 0 1');
                if (!clearSuccess) {
                    console.error("[Cat Taming] No se pudo remover la manzana dorada");
                    processingCats_e.delete(catId);
                    return;
                }

                // Disparar evento inicial
                target.triggerEvent('bunny_ce:sleep1');

                // Temporizador para tameo completo
                system.runTimeout(() => {
                    try {
                        // Verificar si el gato aún existe
                        if (target.isValid()) {
                            target.triggerEvent('on_tame');
                        }
                    } catch (e) {
                        console.error("[Cat Taming] Error en evento on_tame: " + e);
                    } finally {
                        processingCats_e.delete(catId);
                    }
                }, 20 * 60); // 20 segundos

            } catch (e) {
                console.error("[Cat Taming] Error en el proceso: " + e);
                processingCats_e.delete(catId);
            }

        } catch (error) {
            console.error("[Cat Taming] Error crítico: " + error);
        }
    })
});