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

const playerEffectIntervals = new Map();
const playerTargetLasers = new Map();

function calculateDistance(pos1, pos2) {
    const dx = pos2.x - pos1.x;
    const dy = pos2.y - pos1.y;
    const dz = pos2.z - pos1.z;
    return Math.sqrt(dx * dx + dy * dy + dz * dz);
}

function updateTargetInfo(player) {
    const viewDirection = player.getViewDirection();
    const startPos = {
        x: player.location.x,
        y: player.location.y + 1.62,
        z: player.location.z
    };

    const maxDistance = 300;
    const stepSize = 0.5;
    let currentDistance = 0;
    let lastAirPos = null;

    while (currentDistance < maxDistance) {
        const checkPos = {
            x: startPos.x + (viewDirection.x * currentDistance),
            y: startPos.y + (viewDirection.y * currentDistance),
            z: startPos.z + (viewDirection.z * currentDistance)
        };

        const block = player.dimension.getBlock({
            x: Math.floor(checkPos.x),
            y: Math.floor(checkPos.y),
            z: Math.floor(checkPos.z)
        });

        if (!block) break;

        const blockId = block.typeId;
        if (blockId === "minecraft:air" || blockId.startsWith("minecraft:light_block")) {
            lastAirPos = { ...checkPos };
        }
        else if (lastAirPos) {
            const distance = calculateDistance(startPos, lastAirPos);
            player.onScreenDisplay.setActionBar(`§a目标: §a${Math.floor(lastAirPos.x)}, ${Math.floor(lastAirPos.y)}, ${Math.floor(lastAirPos.z)} §a| 距离: §a${Math.floor(distance)}m`);
            return;
        }

        currentDistance += stepSize;
    }

    player.onScreenDisplay.setActionBar(`§e搜寻目标...`);
}

function findTargetPosition(player, maxDistance = 300, stepSize = 0.5) {
    const viewDirection = player.getViewDirection();
    const startPos = {
        x: player.location.x,
        y: player.location.y + 1.62,
        z: player.location.z
    };

    let currentDistance = 0;
    let lastAirPos = null;

    while (currentDistance < maxDistance) {
        const checkPos = {
            x: startPos.x + (viewDirection.x * currentDistance),
            y: startPos.y + (viewDirection.y * currentDistance),
            z: startPos.z + (viewDirection.z * currentDistance)
        };

        const block = player.dimension.getBlock({
            x: Math.floor(checkPos.x),
            y: Math.floor(checkPos.y),
            z: Math.floor(checkPos.z)
        });

        if (!block) {
            break;
        }

        const blockId = block.typeId;

        if (blockId === "minecraft:air" || blockId.startsWith("minecraft:light_block")) {
            lastAirPos = { ...checkPos };
        }
        else if (lastAirPos) {
            return lastAirPos;
        }

        currentDistance += stepSize;
    }

    return null;
}

function startTargeting(player) {
    player.addTag("targeting_mode");
    player.onScreenDisplay.setTitle("target_finder_scope");
    player.playSound("ttavCameraSwitch", { pitch: 1.0, volume: 1.0 });
    player.runCommand("effect @s slowness infinite 5 true");
    player.runCommand("effect @s night_vision infinite 9 true");
    
    const effectInterval = system.runInterval(() => {
        updateTargetInfo(player);
    }, 1);
    
    playerEffectIntervals.set(player.id, effectInterval);
}
function completeTargeting(player) {
    const targetPosition = findTargetPosition(player);
    if (targetPosition) {
        const targetTags = player.getTags().filter(tag => tag.startsWith('ttavtrgt_'));
        const newTag = `ttavtrgt_${Math.floor(targetPosition.x)}_${Math.floor(targetPosition.y)}_${Math.floor(targetPosition.z)}`;
        
        if (targetTags.length >= 3) {
            player.removeTag(targetTags[0]);
        }
        player.addTag(newTag);

        
        const savedCoords = `${Math.floor(targetPosition.x)}, ${Math.floor(targetPosition.y)}, ${Math.floor(targetPosition.z)}`;
        player.sendMessage(`§a保存坐标:\n§e${savedCoords}`);
        player.playSound("ttavRadioAction", { pitch: 1.0, volume: 1.0 });
    } else {
        player.sendMessage("§c未找到有效的目标位置!");
        player.playSound("ttavRadioAction", { pitch: 0.5, volume: 1.0 });
    }
}


function reloadTargeting(player) {
    const effectInterval = playerEffectIntervals.get(player.id);
    if (effectInterval) {
        system.clearRun(effectInterval);
        playerEffectIntervals.delete(player.id);
    }
    
    player.removeTag("targeting_mode");
    player.runCommand("effect @s clear");
    player.onScreenDisplay.setTitle("tank_clear_cam");
    player.playSound("ttavCameraSwitch", { pitch: 1.0, volume: 1.0 });
}

world.afterEvents.itemUse.subscribe((event) => {
    const player = event.source;
    const item = event.itemStack;

    if (item?.typeId === "ttav:target_finder_controller") {
        const isTargeting = player.hasTag("targeting_mode");
        
        if (!isTargeting && player.isSneaking) {
            startTargeting(player);
            return;
        }
        
        if (isTargeting) {
            if (player.isSneaking) {
                completeTargeting(player);
            } else {
                reloadTargeting(player);
            }
            return;
        }
    }
});

world.afterEvents.playerLeave.subscribe((event) => {
    const effectInterval = playerEffectIntervals.get(event.playerId);
    if (effectInterval) {
        system.clearRun(effectInterval);
        playerEffectIntervals.delete(event.playerId);
    }
    playerTargetLasers.delete(event.playerId);
});
