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

export function initSignSwap() {

    
    const eventChance = 0.005; 
    const signRemovalDistance = 48; 
    const signReplaceRadius = 112; 
    const maxAttempts = 15; 

    
    let savedSignData = null;

    
    const SIGN_LOCATIONS_KEY = "signLocations";

    
    function saveSignLocations(signLocations) {
        
    }

    
    function loadSignLocations() {
        let signData = world.getDynamicProperty(SIGN_LOCATIONS_KEY);
        if (signData) {
            return new Map(JSON.parse(signData));
        }
        return new Map();
    }

    
    let activeSignLocations = loadSignLocations();

    const signTypes = [
        "standing_sign", "spruce_standing_sign", "birch_standing_sign", "jungle_standing_sign",
        "acacia_standing_sign", "darkoak_standing_sign", "mangrove_standing_sign", "cherry_standing_sign",
        "pale_oak_standing_sign", "bamboo_standing_sign", "crimson_standing_sign", "warped_standing_sign",
        "wall_sign", "spruce_wall_sign", "birch_wall_sign", "jungle_wall_sign", "acacia_wall_sign", "darkoak_wall_sign",
        "mangrove_wall_sign", "cherry_wall_sign", "pale_oak_wall_sign", "bamboo_wall_sign", "crimson_wall_sign",
        "warped_wall_sign"
    ];


    
    let removeSignIntervalId = null;

    
    world.afterEvents.playerPlaceBlock.subscribe((eventData) => {
        const block = eventData.block;
        const player = eventData.player;

        
        const locationKey = `${block.location.x},${block.location.y},${block.location.z}`;
        activeSignLocations.set(locationKey, { x: block.location.x, y: block.location.y, z: block.location.z });
        saveSignLocations(activeSignLocations);

        
        if (signTypes.some(signType => block.matches(signType))) {
            
            if (fo.forebodingScore >= fo.scoreChapter4 && Math.random() < eventChance) {
                

                system.runTimeout(() => {
                    
                    const signBlock = block.dimension.getBlock(block.location);
                    const signComponent = signBlock.getComponent("sign");
                    const signText = signComponent.getText();

                    savedSignData = {
                        text: signText,
                        location: block.location,
                    };

                    

                    
                    removeSignIntervalId = system.runInterval(() => {
                        removeSign(block.location);
                    }, 360); 
                }, 2400);
            }
        }
    });

    
    function removeSign(signLocation) {
        const players = world.getPlayers();

        
        let isAnyPlayerNearby = false;
        for (const player of players) {
            const distance = getDistance(player.location, signLocation);
            if (distance <= signRemovalDistance) {
                isAnyPlayerNearby = true;
                break;
            }
        }

        if (!isAnyPlayerNearby) {
            
            const dimension = fo.overworld;
            const block = dimension.getBlock(signLocation);

            if (block && signTypes.some(signType => block.matches(signType))) {
                block.dimension.setBlockType(signLocation, "minecraft:air");
                

                
                if (removeSignIntervalId) {
                    system.clearRun(removeSignIntervalId);
                    
                }

                
                
                replaceRandomSignText(0); 
            }
        } else {
            
        }
    }

    
    function getDistance(pos1, pos2) {
        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 replaceRandomSignText(attempts) {
        if (!savedSignData) {
            
            return;
        }

        
        if (activeSignLocations.size > 0) {
            
            const players = world.getPlayers();
            if (players.length === 0) {
                
                return;
            }

            const randomPlayer = players[Math.floor(Math.random() * players.length)];
            const playerLocation = randomPlayer.location;

            
            const eligibleSigns = [];
            for (const [key, signLocation] of activeSignLocations.entries()) {
                const distanceToPlayer = getDistance(playerLocation, signLocation);
                let isEligible = distanceToPlayer <= signReplaceRadius;

                
                for (const player of players) {
                    const distance = getDistance(player.location, signLocation);
                    if (distance <= signRemovalDistance) {
                        isEligible = false;
                        break;
                    }
                }

                if (isEligible) {
                    eligibleSigns.push({ key, location: signLocation });
                }
            }

            if (eligibleSigns.length > 0) {
                
                const randomSign = eligibleSigns[Math.floor(Math.random() * eligibleSigns.length)];
                const dimension = fo.overworld;
                const block = dimension.getBlock(randomSign.location);

                
                if (signTypes.some(signType => block.matches(signType))) {
                    const signComponent = block.getComponent("sign");

                    
                    signComponent.setText(savedSignData.text);
                    
                } else {
                    
                    activeSignLocations.delete(randomSign.key);
                    saveSignLocations(activeSignLocations);
                    

                    
                    if (attempts < maxAttempts) {
                        
                        system.runTimeout(() => {
                            replaceRandomSignText(attempts + 1);
                        }, 20); 
                    } else {
                        
                        system.runTimeout(() => {
                            replaceRandomSignText(0); 
                        }, 3600); 
                    }
                }
            } else {
                

                
                if (attempts < maxAttempts) {
                    
                    system.runTimeout(() => {
                        replaceRandomSignText(attempts + 1);
                    }, 20); 
                } else {
                    
                    system.runTimeout(() => {
                        replaceRandomSignText(0); 
                    }, 3600); 
                }
            }
        } else {
            

            
            if (attempts < maxAttempts) {
                
                system.runTimeout(() => {
                    replaceRandomSignText(attempts + 1);
                }, 20); 
            } else {
                
                system.runTimeout(() => {
                    replaceRandomSignText(0); 
                }, 3600); 
            }
        }
    }

}