import { world } from "@minecraft/server";
import { VEHICLES } from "./VehiclesRoot.js";

function getCardinalDirection(damagerLoc, tankLoc) {
    if (!damagerLoc || !tankLoc) return "§e未知";

    const dx = damagerLoc.x - tankLoc.x;
    const dz = damagerLoc.z - tankLoc.z;
    const distance = Math.sqrt(dx * dx + dz * dz);
    
    if (distance < 0.1) return "§ePoint Blank";
    
    const angle = Math.atan2(dz, dx) * (180 / Math.PI);
    
    if (angle >= -45 && angle < 45) return "§eWest";
    if (angle >= 45 && angle < 135) return "§eNorth";
    if (angle >= 135 || angle < -135) return "§eEast";
    return "§eSouth";
}

const explosionSources = {
    "entityExplosion": {
        "ttav:tank_shell": "§c坦克炮弹爆炸",
        "ttav:artillery_shell": "§c火炮弹爆炸",
        "ttav:rocket": "§c火箭弹爆炸",
        "ttav:missile": "§c导弹爆炸",
        "ttav:homing_missile": "§c装甲车导弹爆炸",
        "ttav:heat_shell": "§c温压弹爆炸",
        "ttav:hesh_shell": "§c温压弹爆炸",
        "minecraft:tnt": "§cTNT爆炸"
    }
};

const damageCauses = {
    "none": "§c未知",
    "contact": "§c接触",
    "entityAttack": "§c直接攻击",
    "projectile": "§c发射物",
    "suffocation": "§c窒息",
    "fall": "§c跌落",
    "fire": "§c火",
    "fireTick": "§c燃烧",
    "lava": "§c岩浆",
    "drowning": "§c溺水",
    "blockExplosion": "§c方块爆炸",
    "entityExplosion": "§c实体爆炸",
    "void": "§c虚空",
    "suicide": "§c自爆",
    "magic": "§c魔法",
    "wither": "§凋零",
    "starve": "§c饥饿",
    "anvil": "§c铁砧",
    "thorns": "§c荆棘",
    "fallingBlock": "§c落下的方块",
    "piston": "§c活塞",
    "flyIntoWall": "§c入墙",
    "magma": "§c岩浆",
    "fireworks": "§c烟花",
    "lightning": "§c闪电",
    "charging": "§c冲击",
    "temperature": "§c温度",
    "freezing": "§c冰冻",
    "stalactite": "§c钟乳石",
    "stalagmite": "§c石笋"
};

const damagerFamilies = {
    "heat_shell": "§c温压弹",
    "small_heat_shell": "§c小温压弹",
    "hesh_shell": "§c温压弹",
    "small_hesh_shell": "§c小温压弹",
    "bullet_projectile": "§c弹药",
    "tank_explosion": "§c坦克炮弹",
    "artillery_shell": "§c火炮弹",
    "rocket_projectile": "§c火箭弹",
    "missile_projectile": "§c导弹",
    "ifv_rocket": "§cIFV火箭弹",
    "apv_rocket": "§cAPV火箭弹",
    "tank_shell": "§c坦克炮弹",
    "tank_mg": "§c重机枪"
};

function formatEntityName(typeId) {
    if (!typeId) return "未知";
    const nameParts = typeId.split(':')[1].split('_');
    return nameParts.map(part => part.charAt(0).toUpperCase() + part.slice(1)).join(' ');
}

function get子Type(entityId) {
    
    for (const [tankName, tankData] of Object.entries(VEHICLES)) {
        if (entityId.includes(tankData.identifier)) {
            
            return tankName;
        }
    }
    return "未知载具";
}

world.afterEvents.entityHurt.subscribe((event) => {
    const { hurtEntity, damageSource } = event;

    let hurtEntityPos = null;
    let damagerPos = null;

    try {
        if (hurtEntity) {
            hurtEntityPos = hurtEntity.location;
            if (!hurtEntityPos) {
                const pos = hurtEntity.getComponent("minecraft:position");
                if (pos) {
                    hurtEntityPos = { x: pos.x, y: pos.y, z: pos.z };
                }
            }
        }
        
        if (damageSource.damagingEntity) {
            damagerPos = damageSource.damagingEntity.location;
            
            if (!damagerPos) {
                const pos = damageSource.damagingEntity.getComponent("minecraft:position");
                if (pos) {
                    damagerPos = { x: pos.x, y: pos.y, z: pos.z };
                }
            }
            
            if (!damagerPos && damageSource.damagingEntity.dimension) {
                const block = damageSource.damagingEntity.dimension.getBlock(damageSource.damagingEntity.blockLocation);
                if (block) {
                    damagerPos = { x: block.x, y: block.y, z: block.z };
                }
            }
        }
    } catch (error) {
    }


    if (!hurtEntity?.typeId.startsWith("pn:")) return;

    let tags = [];
    try {
        tags = Array.from(hurtEntity.getTags());
        
    } catch (error) {
        return;
    }

    const riderTag = tags.find(tag => tag.startsWith('rider_'));
    
    if (!riderTag) return;

    const riderId = riderTag.split('_')[1];
    const tankType = get子Type(hurtEntity.typeId);
    let damageType = damageCauses[damageSource.cause] || "未知";
    let damagerType = "未知";

    if (damageSource.cause === "entityExplosion" && damageSource.damagingEntity) {
        const sourceType = damageSource.damagingEntity.typeId;
        damagerType = explosionSources.entityExplosion[sourceType] || 
                      "§c" + formatEntityName(sourceType);
    } else if (damageSource.damagingEntity) {
        try {
            const damagerTags = Array.from(damageSource.damagingEntity.getTags());
            
            
            let foundFamilyTag = false;
            for (const tag of damagerTags) {
                if (damagerFamilies[tag]) {
                    damagerType = damagerFamilies[tag];
                    foundFamilyTag = true;
                    break;
                }
            }
            
            if (!foundFamilyTag && damageSource.damagingEntity.typeId) {
                damagerType = "§c" + formatEntityName(damageSource.damagingEntity.typeId);
            }
        } catch (error) {
            
        }
    }

    let direction = "§e未知";
    if (damagerPos && hurtEntityPos) {
        direction = getCardinalDirection(damagerPos, hurtEntityPos);
    }

    const message = `§7[§c警告§7] 你的载具受到了来自 ${direction} 由 ${damagerType} 造成的 ${damageType} 伤害!`;
    

    const dimensions = [
        world.getDimension("minecraft:overworld"),
        world.getDimension("minecraft:nether"),
        world.getDimension("minecraft:the_end")
    ];

    for (const dimension of dimensions) {
        const players = dimension.getPlayers();
        for (const player of players) {
            if (player.id === riderId) {
                player.sendMessage(message);
                player.playSound("ttavRadioAction", {
                    pitch: 1.0,
                    volume: 1.0
                });
                break;
            }
        }
    }
});
