import { world, system } from "@minecraft/server";
import { fo } from './utilities/fo_constants.js';



export function initGlass() {

    
    const chance = 1 / 48; 
    const forebodingCheck = fo.scoreChapter4; 
    const interval = 4440; 

    let eventflag = false; 

    
    const GLASS_LIST_PROPERTY = "glass_locations";

    
    const glassBlocks = fo.glassBlocks

    
    function getDistance(pos1, pos2) {
        if (!pos1 || !pos2) {
            return Infinity; 
        }
        return Math.sqrt(
            Math.pow(pos1.x - pos2.x, 2) +
            Math.pow(pos1.y - pos2.y, 2) +
            Math.pow(pos1.z - pos2.z, 2)
        );
    }

    
    function isPlayerLookingAtGlass(player, glassPos) {
        if (!player || !glassPos) {
            return false;
        }

        const playerPos = player.location;
        if (!playerPos) {
            return false;
        }

        const playerViewDir = player.getViewDirection();
        if (!playerViewDir) {
            return false;
        }

        
        const glassDir = {
            x: glassPos.x - playerPos.x,
            y: glassPos.y - playerPos.y,
            z: glassPos.z - playerPos.z
        };

        
        const glassDirLength = Math.sqrt(glassDir.x ** 2 + glassDir.y ** 2 + glassDir.z ** 2);
        const normalizedGlassDir = {
            x: glassDir.x / glassDirLength,
            y: glassDir.y / glassDirLength,
            z: glassDir.z / glassDirLength
        };

        
        const dotProduct = playerViewDir.x * normalizedGlassDir.x + playerViewDir.y * normalizedGlassDir.y + playerViewDir.z * normalizedGlassDir.z;

        
        const angle = Math.acos(dotProduct);

        
        const angleThreshold = (55 * Math.PI) / 180; 

        
        return angle <= angleThreshold;
    }

    
    function breakRandomGlass() {
        const glassLocations = JSON.parse(world.getDynamicProperty(GLASS_LIST_PROPERTY) || "[]");

        if (!Array.isArray(glassLocations) || glassLocations.length === 0) {
            return; 
        }

        const players = world.getPlayers();

        if (!Array.isArray(players)) {
            return; 
        }

        
        
        
        
        const validGlasses = glassLocations.filter(glassPos => {
            
            const playersInSameDimension = players.filter(player =>
                player.dimension.id === glassPos.dimension
            );
            if (playersInSameDimension.length === 0) {
                return false; 
            }
            
            const isNearPlayer = playersInSameDimension.some(player => {
                const distance = getDistance(player.location, glassPos);
                return distance <= 32;
            });

            
            const isFarFromAllPlayers = playersInSameDimension.every(player => {
                const distance = getDistance(player.location, glassPos);
                return distance >= 6;
            });
            
            const isNotBeingLookedAt = playersInSameDimension.every(player =>
                !isPlayerLookingAtGlass(player, glassPos)
            );

            return isNearPlayer && isFarFromAllPlayers && isNotBeingLookedAt;
        });

        if (validGlasses.length === 0) {
            return; 
        }

        
        const randomGlass = validGlasses[Math.floor(Math.random() * validGlasses.length)];
        
        const dimension = world.getDimension(randomGlass.dimension);
        const block = dimension.getBlock({ x: randomGlass.x, y: randomGlass.y, z: randomGlass.z });

        if (!block || !glassBlocks.includes(block.typeId)) {
            
            const updatedLocations = glassLocations.filter(loc =>
                !(loc.x === randomGlass.x && loc.y === randomGlass.y && loc.z === randomGlass.z && loc.dimension === randomGlass.dimension)
            );
            world.setDynamicProperty(GLASS_LIST_PROPERTY, JSON.stringify(updatedLocations));
            
            return;
        }

        
        block.setType("minecraft:air"); 
        dimension.playSound("random.glass", block.location, { volume: 2 });
        

        eventflag = false;

        
        const updatedLocations = glassLocations.filter(loc =>
            !(loc.x === randomGlass.x && loc.y === randomGlass.y && loc.z === randomGlass.z && loc.dimension === randomGlass.dimension)
        );
        world.setDynamicProperty(GLASS_LIST_PROPERTY, JSON.stringify(updatedLocations));
        
    }

    
    system.runInterval(() => {

        if (!eventflag && fo.forebodingScore >= forebodingCheck && Math.random() <= (chance * fo.netProbabilityModifier)) {
            eventflag = true
        }

    }, interval);


    
    system.runInterval(() => {

        if (eventflag) {
            breakRandomGlass();
        }

    }, 1400);

}