import { world, system } from "@minecraft/server";
import { VEHICLES } from "./VehiclesRoot.js";
import { Vec3 } from "./ProjectileHelpers.js";

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

const lightState = new Map();
const BLOCK_TTL = 2;

function getLightPositions(tank) {
    
    const results = [];
    const dir = tank.getViewDirection();
    

    for (let dist = 5; dist <= 10; dist++) {
        const tx = Math.floor(tank.location.x + dir.x * dist);
        const ty = Math.floor(tank.location.y + 1);
        const tz = Math.floor(tank.location.z + dir.z * dist);
        

        const block = tank.dimension.getBlock({ x: tx, y: ty, z: tz });
        if (block && block.typeId === "minecraft:air") {
            
            results.push({ x: tx, y: ty, z: tz });
        }
    }
    return results;
}

function removeBlockIfStillLight(tank, { x, y, z }) {
    
    const block = tank.dimension.getBlock({ x, y, z });
    if (block && block.typeId === "minecraft:light_block_15") {
        block.setType("minecraft:air");
        
    }
}

function updateVehicleLights() {
    for (const dimension of dimensions) {
        for (const [vehicleType, config] of Object.entries(VEHICLES)) {
            const vehicles = dimension.getEntities({ type: config.identifier });
            
            
            for (const vehicle of vehicles) {
                const lightEnabled = vehicle.getDynamicProperty("ttav:vehicle_light");
                

                if (!lightEnabled) {
                    const data = lightState.get(vehicle.id);
                    if (data) {
                        
                        for (const blockPos of data.placedBlocks) {
                            removeBlockIfStillLight(vehicle, blockPos);
                        }
                        lightState.delete(vehicle.id);
                    }
                    continue;
                }

                let data = lightState.get(vehicle.id);
                if (!data) {
                    
                    data = {
                        placedBlocks: [],
                        lastLocation: null,
                        lastRotation: null
                    };
                    lightState.set(vehicle.id, data);
                }

                const locChanged = !data.lastLocation || 
                    Math.abs(data.lastLocation.x - vehicle.location.x) > 0.1 ||
                    Math.abs(data.lastLocation.z - vehicle.location.z) > 0.1;

                const currentRotation = vehicle.getRotation().y;
                const dirChanged = !data.lastRotation || Math.abs(data.lastRotation - currentRotation) > 0.01;

                

                if (locChanged || dirChanged) {
                    
                    
                    
                    const newPositions = getLightPositions(vehicle);
                    
                    
                    for (const pos of newPositions) {
                        try {
                            vehicle.dimension.runCommandAsync(
                                `setblock ${pos.x} ${pos.y} ${pos.z} minecraft:light_block_15 replace`
                            );
                            
                        } catch (err) {
                            
                        }
                    }

                    
                    for (const blockPos of data.placedBlocks) {
                        removeBlockIfStillLight(vehicle, blockPos);
                    }
                    
                    data.placedBlocks = newPositions;
                    data.lastLocation = { ...vehicle.location };
                    data.lastRotation = currentRotation;
                    
                }
            }
        }
    }
}

system.runInterval(updateVehicleLights, 20);

world.afterEvents.entityRemove.subscribe((event) => {
    if (!event.removedEntity) return;
    
    const data = lightState.get(event.removedEntity.id);
    if (data) {
        
        for (const blockPos of data.placedBlocks) {
            removeBlockIfStillLight(event.removedEntity, blockPos);
        }
        lightState.delete(event.removedEntity.id);
    }
});

world.afterEvents.entityDie.subscribe((event) => {
    const { deadEntity } = event;
    
    const data = lightState.get(deadEntity.id);
    if (data) {
        
        for (const blockPos of data.placedBlocks) {
            removeBlockIfStillLight(deadEntity, blockPos);
        }
        lightState.delete(deadEntity.id);
    }
});
