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

// Function to run commands
function runCommand(command) {
    try {
        return world.getDimension("overworld").runCommand(command);
    } catch (error) {
        // Removed: console.warn("Error running command: " + command);
        // Removed: console.warn(error);
    }
}

// Function to load first floor (special case with two parts)
function loadRandomFloor() {
    // Define the possible floor combinations
    const firstFloors = [
        { main: "mystructure:a3_f1", partner: "mystructure:a3_f1.1" },
        { main: "mystructure:a3_f2", partner: "mystructure:a3_f2.1" },
        { main: "mystructure:a3_f3", partner: "mystructure:a3_f3.1" }
    ];

    // Randomly select a floor combination
    const randomFloor = firstFloors[Math.floor(Math.random() * firstFloors.length)];

    // Load both parts of the selected first floor
    runCommand(`structure load ${randomFloor.main} 195 -62 -328`);
    runCommand(`structure load ${randomFloor.partner} 195 -62 -264`);
    runCommand("tp @a 239.44 -60.00 -285.44 facing 232.42 -60.00 -285.49");
    runCommand('give @a jam:extinguisher 1 1 {"minecraft:item_lock":{"mode":"lock_in_inventory"}}');
    runCommand('give @a jam:restart 1 1 {"minecraft:item_lock":{"mode":"lock_in_inventory"}}');
    runCommand("setworldspawn 61.50 -54.00 44.49");
    runCommand("tp @e[family=water] @s ");
    
    // Add floor1 tag after 5 seconds
    system.runTimeout(() => {
        runCommand("setblock 43 -59 -56 redstone_block");   
        runCommand("tag @a add a3_floor1");
        runCommand("tag @a add area_3");
    }, 60); // 5 seconds = 100 ticks
}

// Function to start persistent teleporter detection for a cleared floor
function startTeleporterDetection(floorNum) {
    // Add a tag to track that this floor is being monitored
    safeRunCommand(`tag @a add teleporter_monitoring_${floorNum}`);
    
    // Start the monitoring process using recursive timeouts
    function monitorTeleporter() {
        try {
            // Check if player still has the cleared tag and floor tag
            const hasClearedTag = safeRunCommand(`testfor @a[tag=a3_floor${floorNum}_cleared]`).successCount > 0;
            const hasFloorTag = safeRunCommand(`testfor @a[tag=a3_floor${floorNum}]`).successCount > 0;
            const isMonitoring = safeRunCommand(`testfor @a[tag=teleporter_monitoring_${floorNum}]`).successCount > 0;
            
            // If any tag is missing, stop monitoring this floor
            if (!hasClearedTag || !hasFloorTag || !isMonitoring) {
                return; // Stop monitoring
            }
            
            // Check if player is near teleporter
            const playerNearResult = safeRunCommand("execute as @e[type=jam:teleporter_1] at @s if entity @a[r=3]").successCount > 0;
            
            if (playerNearResult) {
                // Player is near teleporter, proceed to next floor
                // Remove monitoring tag
                safeRunCommand(`tag @a remove teleporter_monitoring_${floorNum}`);
                
                // Start the teleportation sequence
                safeRunCommand("camera @a fade time 0.5 7 1");
                
                system.runTimeout(() => {
                    safeRunCommand("kill @e[family=games]");
                    safeRunCommand("kill @e[type=item]");
                    system.runTimeout(() => {
                        safeRunCommand("camera @a clear");
                        safeRunCommand("inputpermission set @a movement enabled");
                        safeRunCommand("inputpermission set @a camera enabled");
                        
                        // Remove all floor tags before loading next floor
                        for (let i = 1; i <= 15; i++) {
                            safeRunCommand(`tag @a remove a3_floor${i}`);
                            safeRunCommand(`tag @a remove a3_floor${i}_cleared`);
                            safeRunCommand(`tag @a remove teleporter_monitoring_${i}`);
                        }
                        
                        // Load next floor based on current floor number
                        loadRandomMiddleFloor(floorNum);
                    }, 30);
                }, 20);
                
                return; // Stop monitoring
            }
            
            // Continue monitoring after 2 seconds (40 ticks)
            system.runTimeout(monitorTeleporter, 40);
            
        } catch (error) {
            // Silently handle any errors and continue monitoring
            system.runTimeout(monitorTeleporter, 40);
        }
    }
    
    // Start the monitoring process
    system.runTimeout(monitorTeleporter, 40);
}

// Function to load random middle floor at specific Y coordinate
function loadRandomMiddleFloor(currentFloor) {
    const middleFloors = [
        "mystructure:a3_m1",
        "mystructure:a3_m2",
        "mystructure:a3_m3",
        "mystructure:a3_m4",
        "mystructure:a3_m5",
        "mystructure:a3_m6",
        "mystructure:a3_m7",
        "mystructure:a3_m8",
    ];

    // Dialogue lines for each new floor
    const dialogues = [
        "It's hot here!",
        "I feel the heat rising...",
        "The flames are intense!",
        "Is it just me or is it getting hotter?",
        "The air shimmers with heat.",
        "I hope I brought enough water...",
        "The fire is everywhere!",
        "This place is like an oven!",
        "I hope the fire spirit is not a lot.",
        "Did someone turn up the thermostat?",
        "My shoes are melting!",
        "I can barely see through the heat waves.",
        "Why did I wear wool today?",
        "I think my eyebrows are singed...",
        "The flames seem alive...",
        "I hear crackling all around.",
        "Is that smoke or just my imagination?",
        "I hope we don't run into any fire spirits...",
        "This is hotter than the Nether!",
        "I could really use a cold drink right now."
    ];

    	// Calculate Y coordinate for each floor
	// Floors reuse a vertical "lane" set to avoid reaching world height.
	// Lane heights repeat every 7 floors: floor2..floor8 heights are reused by floor9..floor15.
	const nextFloor = currentFloor + 1;
	const baseY = -62;
	const floorHeight = 15; // Reduced from 50 to 15 for closer floor spacing
	const layerIndex = ((currentFloor - 1) % 7) + 1; // 1..7, wraps: 8->1, 9->2, etc.
	const newY = baseY + (floorHeight * layerIndex);

    // Debug logging
    // Removed: console.warn(`Loading floor: Current=${currentFloor}, Next=${nextFloor}, Y=${newY}`);
    runCommand('tellraw @a[tag=dev] {"rawtext":[{"text":"[DEBUG] playsound jam.reward @a executed"}]}');
    system.runTimeout(() => {
        if (currentFloor < 14) {
            // For floors 2-14, load random middle floor
            const randomMiddleFloor = middleFloors[Math.floor(Math.random() * middleFloors.length)];
            // Removed: console.warn(`Loading structure: ${randomMiddleFloor} at Y=${newY}`);
            
            // Load the structure and set up the floor
            runCommand(`structure load ${randomMiddleFloor} 202 ${newY} -304`);
            system.runTimeout(() => {
                runCommand(`execute as @e[type=jam:teleporter_2] at @s run tp @a ^ ^0.3 ^2 facing @e[type=jam:teleporter_2]`);
                system.runTimeout(() => {
                    runCommand(`tag @a add a3_floor${nextFloor}`);
                }, 100); // 100 ticks delay
                runCommand("setblock 43 -59 -56 redstone_block");
                runCommand("tp @e[family=water] @s ");
                runCommand("tag @a add alive");
                runCommand("effect @a instant_health 5 5");
                runCommand("tp @e[family=water] @s ");
                // Show a random dialogue message to all players
                const randomDialogue = dialogues[Math.floor(Math.random() * dialogues.length)];
                runCommand(`tellraw @a {\"rawtext\":[{\"text\":\"§e§l${randomDialogue}\"}]}`);
            }, 5); // 20 ticks = 1 second
        } else if (currentFloor === 14) {
            // For floor 14 to 15 (boss room), load specific structure
            // Removed: console.warn(`Loading boss floor at Y=${newY}`);
            runCommand(`structure load mystructure:a3_r1 202 ${newY} -304`);
            system.runTimeout(() => {
                runCommand(`execute as @e[type=jam:teleporter_2] at @s run tp @a ^ ^0.3 ^2 facing @e[type=jam:teleporter_2]`);
                runCommand("tag @a add a3_floor15");
                runCommand("setblock 43 -59 -56 redstone_block");
                runCommand("tp @e[family=water] @s ");
                runCommand("tag @a add alive");
                runCommand("effect @a instant_health 5 5");
                runCommand("kill @e[type=item]");
                // Show a random dialogue message to all players
                const randomDialogue = dialogues[Math.floor(Math.random() * dialogues.length)];
                runCommand(`tellraw @a {\"rawtext\":[{\"text\":\"§e§l${randomDialogue}\"}]}`);
            }, 20); // 20 ticks = 1 second
        }
    }, 20); // 60 ticks = 3 seconds
}

// Flag to track if cutscene is running
let isCutsceneActive = false;
let wasRedstonePresent = false;
let lastFireCheck = 0;
let messageShown = false;  // New flag to track if message was shown
let victorySequenceStarted = false;  // Flag to prevent duplicate victory sequences

// Safe command execution
function safeRunCommand(command) {
    try {
        return world.getDimension("overworld").runCommand(command);
    } catch {
        return { successCount: 0 };
    }
}

// Function to check redstone blocks and start cutscene
function startCutscene() {
    // Check both redstone block locations
    const mediumTowerBlock = world.getDimension("overworld").getBlock({ x: 61, y: -62, z: 21 });
    const mediumTowerUnlockBlock = world.getDimension("overworld").getBlock({ x: 59, y: -62, z: 21 });
    
    const isMediumTowerTriggered = mediumTowerBlock?.typeId === "minecraft:redstone_block";
    const isMediumTowerUnlocked = mediumTowerUnlockBlock?.typeId === "minecraft:redstone_block";
    
    // If medium tower is triggered (has redstone)
    if (isMediumTowerTriggered && !wasRedstonePresent && !isCutsceneActive) {
        // Check if medium tower is unlocked
        if (!isMediumTowerUnlocked && !messageShown) {
            // Get the highest area2 score among all players
            let area2Score = 0;
            try {
                // Try to get the highest area2 score among all players
                const result = world.scoreboard.getObjective("area2");
                if (result) {
                    let maxScore = 0;
                    for (const score of result.getScores()) {
                        if (score.score > maxScore) maxScore = score.score;
                    }
                    area2Score = maxScore;
                }
            } catch {}
            safeRunCommand(`tellraw @a {"rawtext":[{"text":"§c§l➜ You need to finish the medium tower 5x to unlock this area. You have finished the medium tower §e§l${area2Score}§c times."}]}`);
            messageShown = true;
            wasRedstonePresent = isMediumTowerTriggered;
            return;
        }
        
        // If both redstone blocks are present, start the cutscene
        if (isMediumTowerUnlocked) {
            // Check if any player has the "alive" tag
            const players = world.getPlayers();
            for (const player of players) {
                if (player.hasTag("alive")) {
                    runCommand("title @a actionbar §l§cGame in progress!");
                    return; // Do not start cutscene
                }
            }
            isCutsceneActive = true;
            victorySequenceStarted = false; // Reset victory flag when starting new game
            runCommand("setblock 24 -61 22 redstone_block");
            // Disable player movement and camera
            system.runTimeout(() => {
            runCommand("inputpermission set @a movement disabled");
            runCommand("inputpermission set @a camera disabled");
            runCommand("tp @a 61 -58.00 29.58 facing 61 -58.00 24.68");
            runCommand("tag @a add alive");
            runCommand("kill @e[family=fire]");
            runCommand("kill @e[family=summon]");
            runCommand("kill @e[type=item]");
            runCommand("kill @e[family=games]");
            
            // Initial fade
            runCommand("camera @a fade time 0.5 1 0.5");
            runCommand("clear @a jam:extinguisher");
            
            // Start cutscene sequence after 1 second
            system.runTimeout(() => {
                // First camera position
                runCommand("tp @a -247.49 -18.74 -350.31");
                runCommand("camera @a set minecraft:free pos -273.96 -18.24 -383.15 facing -276.35 -17.91 -379.92");
                runCommand("camera @a set minecraft:free ease 5 linear pos -273.96 -18.24 -383.15 facing -316 4 -392");
                
                // Second sequence after 5 seconds
                system.runTimeout(() => {
                    runCommand("camera @a set minecraft:free pos -273.96 -18.24 -383.15 facing -316 4 -392");
                    runCommand("camera @a set minecraft:free ease 5 linear pos -284.29 -18.23 -387.59 facing -304.70 -18.23 -390.55");
                    
                    // Remove all tags after camera fade
                    runCommand("tag @a remove dev");
                    runCommand("tag @a remove a3_floor1");
                    runCommand("tag @a remove a3_floor2");
                    runCommand("tag @a remove a3_floor3");
                    runCommand("tag @a remove a3_floor4");
                    runCommand("tag @a remove a3_floor5");
                    runCommand("tag @a remove a3_floor6");
                    runCommand("tag @a remove a3_floor7");
                    runCommand("tag @a remove a3_floor8");
                    runCommand("tag @a remove a3_floor9");
                    runCommand("tag @a remove a3_floor10");
                    runCommand("tag @a remove a3_floor11");
                    runCommand("tag @a remove a3_floor12");
                    runCommand("tag @a remove a3_floor13");
                    runCommand("tag @a remove a3_floor14");
                    runCommand("tag @a remove a3_floor15");
                    runCommand("tag @a remove a3_floor1_cleared");
                    runCommand("tag @a remove a3_floor2_cleared");
                    runCommand("tag @a remove a3_floor3_cleared");
                    runCommand("tag @a remove a3_floor4_cleared");
                    runCommand("tag @a remove a3_floor5_cleared");
                    runCommand("tag @a remove a3_floor6_cleared");
                    runCommand("tag @a remove a3_floor7_cleared");
                    runCommand("tag @a remove a3_floor8_cleared");
                    runCommand("tag @a remove a3_floor9_cleared");
                    runCommand("tag @a remove a3_floor10_cleared");
                    runCommand("tag @a remove a3_floor11_cleared");
                    runCommand("tag @a remove a3_floor12_cleared");
                    runCommand("tag @a remove a3_floor13_cleared");
                    runCommand("tag @a remove a3_floor14_cleared");
                    runCommand("tag @a remove a3_floor15_cleared");
                    // Remove teleporter monitoring tags
                    for (let i = 1; i <= 15; i++) {
                        runCommand(`tag @a remove teleporter_monitoring_${i}`);
                    }
                    
                    // Final sequence after 4 seconds
                    system.runTimeout(() => {
                        runCommand("camera @a fade time 0.5 4 2");
                        
                        // Add dramatic overhead view after 0.5 seconds
                        system.runTimeout(() => {
                            runCommand("tp @a 280.77 -61.00 -320.413");
                            
                            // Wait 1 second before clearing
                            system.runTimeout(() => {
                                runCommand("camera @a clear");
                                runCommand("structure load mystructure:build3 195 -62 -328");
                                runCommand("structure load mystructure:build3.1 195 -62 -264");
                                safeRunCommand("tp @a 240.37 -60.00 -282.47 facing 235.47 -60.00 -282.51");
                                runCommand("inputpermission set @a movement enabled");
                                runCommand("inputpermission set @a camera enabled");
                                isCutsceneActive = false;
                                // Load random floor and teleport player
                                loadRandomFloor();
                            }, 20);
                        }, 10); // 0.5 seconds = 10 ticks
                    }, 40); // 4 seconds = 80 ticks
                }, 100); // 5 seconds = 100 ticks
            }, 20);
        }, 260); // 1 second = 20 ticks
        }
    } else if (!isMediumTowerTriggered && wasRedstonePresent) {
        // Reset message flag when redstone is removed
        messageShown = false;
    }
    
    // Update wasRedstonePresent flag regardless of whether cutscene started
    wasRedstonePresent = isMediumTowerTriggered;
}

// Check for fire conditions every 3 seconds
system.runInterval(() => {
    startCutscene();
    
    // Only check every 3 seconds (60 ticks)
    const currentTick = system.currentTick;
    if (currentTick - lastFireCheck < 60) {
        return;
    }
    lastFireCheck = currentTick;
    

    
    try {
        // Only proceed if not in cutscene
        if (!isCutsceneActive) {
            // Check which floor the player is on (1-15)
            for (let floorNum = 1; floorNum <= 15; floorNum++) {
                const hasFloorTag = safeRunCommand(`testfor @a[tag=a3_floor${floorNum}]`).successCount > 0;
                
                if (hasFloorTag) {
                    // Removed: console.warn(`Checking floor ${floorNum}`); // Debug log
                    
                    // Check for both types of fire entities separately
                    const noSummonEntities = safeRunCommand("execute unless entity @e[family=summon]");
                    const noFireEntities = safeRunCommand("execute unless entity @e[family=fire]");
                    
                    // If both commands succeeded, show message and mark as cleared
                    if (noSummonEntities.successCount > 0 && noFireEntities.successCount > 0) {
                        const hasCleared = safeRunCommand(`testfor @a[tag=a3_floor${floorNum}_cleared]`).successCount > 0;
                        
                        if (!hasCleared) {
                            // Removed: console.warn(`Floor ${floorNum} cleared, showing message`); // Debug log
                            
                            // Display floor cleared message and add cleared tag
                            if (floorNum === 15 && !victorySequenceStarted) {
                                // Special message for completing the final floor
                                system.runTimeout(() => {
                                    handleVictorySequence();
                                }, 60); // Start after 3 seconds
                            } else {
                                safeRunCommand("setblock 44 -59 -56 redstone_block");
                                system.runTimeout(() => {
                                    safeRunCommand("playsound jam.reward @a ~ ~ ~ 1 1 1");
                                    safeRunCommand(`title @a[tag=a3_floor${floorNum}] title §a§lFloor ${floorNum} Cleared!`);
                                    safeRunCommand(`title @a[tag=a3_floor${floorNum}] subtitle §e§lApproach the teleporter to proceed`);
                                    // Give 30 Coins as floor completion reward
                                    system.runTimeout(() => {
                                        
                                        safeRunCommand("playsound floors.1 @a ~ ~ ~ 1 1 1");
                                        safeRunCommand('tellraw @a {"rawtext":[{"text":"§e§l➜ Floor Reward: §620 Coins"}]}');
                                        safeRunCommand("give @a jam:coin 20");
                                        safeRunCommand("particle minecraft:villager_happy ~~~ 1");
                                        system.runTimeout(() => {
                                            safeRunCommand("setblock 42 -59 -56 redstone_block");
                                        }, 40);
                                    }, 40);
                                }, 20);
                            }
                            safeRunCommand(`tag @a add a3_floor${floorNum}_cleared`);
                            
                            // Clear fire blocks
                            safeRunCommand("execute as @e[type=jam:teleporter_1] at @s run particle jam:water2 ~ ~ ~");
                            safeRunCommand("execute as @e[type=jam:teleporter_1] at @s run fill ~10 ~-1 ~10 ~-10 ~5 ~-10 air replace jam:small_fire_block");
                            safeRunCommand("execute as @e[type=jam:teleporter_1] at @s run fill ~10 ~-1 ~10 ~-10 ~5 ~-10 air replace jam:two_block_fire_block");
                            
                             // Start persistent teleporter detection for this cleared floor
                               if (floorNum < 15) {
                                system.runTimeout(() => {
                                    startTeleporterDetection(floorNum);
                                }, 60);
                            }
                        }
                    }
                }
            }
        }
    } catch (error) {
        // Removed: console.warn("Error in fire check interval: " + error);
    }
}, 1);

// Function to handle victory sequence
function handleVictorySequence() {
    // Prevent duplicate victory sequences
    if (victorySequenceStarted) {
        return;
    }
    victorySequenceStarted = true;
    
    safeRunCommand("camera @a clear");
    safeRunCommand("setblock 44 -59 -56 redstone_block");
    safeRunCommand('title @a title §6§lVictory!');
    safeRunCommand("playsound jam.reward @a ~ ~ ~ 1 1 1");
    safeRunCommand('title @a subtitle §e§lYou have conquered the Large Tower!');
    safeRunCommand("execute as @a at @s run playsound random.levelup @a ~~~ 1 0.5");
    safeRunCommand("particle minecraft:huge_explosion_emitter ~~~ 1");
    safeRunCommand("tag @a remove area_3");
    
    // Reward sequence after 2 seconds
    system.runTimeout(() => {
        safeRunCommand("playsound floors.2 @a ~ ~ ~ 1 1 1");
        safeRunCommand("execute as @a at @s run playsound random.orb @a ~~~ 1 0.5");
        safeRunCommand("particle minecraft:villager_happy ~~~ 1");
        safeRunCommand("tag @a remove alive");
        
        // Show completion message after 2 seconds
        system.runTimeout(() => {
            safeRunCommand('tellraw @a {"rawtext":[{"text":"§6⭐ Large Tower Completed! ⭐"}]}');
            safeRunCommand("execute as @a at @s run playsound random.orb @a ~~~ 1 0.5");
            safeRunCommand("particle minecraft:villager_happy ~~~ 1");
            
            // Give rewards after 2 seconds
            system.runTimeout(() => {
                safeRunCommand("execute as @a at @s run playsound random.levelup @a ~~~ 1 1");
                safeRunCommand("particle minecraft:villager_happy ~~~ 1");
                
                // Return to lobby after 3 seconds
                system.runTimeout(() => {
                    safeRunCommand("camera @a fade time 0.5 5 0.5");
                    
                    // Wait 0.5 seconds before loading structure (from floor 15 victory)
                    system.runTimeout(() => {
                        // Clear existing structure and load final one
                        safeRunCommand("structure load mystructure:build3 195 -62 -328");
                        safeRunCommand("structure load mystructure:build3.1 195 -62 -264");
                        safeRunCommand("structure load mystructure:roofer3 202 33 -304");
                        safeRunCommand("kill @e[family=games]");
                        safeRunCommand("tp @a 226.55 39.00 -274.29 facing 225.29 39.00 -279.86");
                        
                        // Re-enable player movement
                        safeRunCommand("inputpermission set @a movement enabled");
                        safeRunCommand("inputpermission set @a camera enabled");
                        safeRunCommand("kill @e[family=games]");
                        safeRunCommand("kill @e[type=item]");
                        safeRunCommand("kill @e[family=summon]");
                        safeRunCommand("kill @e[family=fire]");
                        safeRunCommand("tp @e[family=water] @r ");
                        
                        // Show victory message after 1 second
                        system.runTimeout(() => {
                            safeRunCommand("kill @e[family=games]");
                            safeRunCommand("kill @e[family=fire]");
                            safeRunCommand("execute as @a at @s run playsound random.levelup @a ~~~ 1 0.5");
                            safeRunCommand("particle minecraft:huge_explosion_emitter ~~~ 1");
                            
                            // Show completion message after 2 seconds
                            system.runTimeout(() => {
                                safeRunCommand('tellraw @a {"rawtext":[{"text":"§e§l➜ Receiving reward: §6100 Coins"}]}');
                                safeRunCommand("give @a jam:coin 100");
                                safeRunCommand("execute as @a at @s run playsound random.levelup @a ~~~ 1 1");
                                safeRunCommand("particle minecraft:villager_happy ~~~ 1");
                                
                                // Removed: Give rewards after 2 seconds (duplicate 100 coins reward)
                                
                                // Return to lobby after 3 seconds
                                system.runTimeout(() => {
                                    safeRunCommand("camera @a fade time 0.5 1 0.5");
                                    
                                    // Final teleport after 1 second
                                    system.runTimeout(() => {
                                        safeRunCommand("camera @a clear");
                                        safeRunCommand('tellraw @a {"rawtext":[{"text":"§e§l➜ Return to lobby to play again!"}]}');
                                        safeRunCommand("tp @a 61.51 -58.00 37.54 facing 61.49 -58.00 31.37");
                                        safeRunCommand("setworldspawn 61.50 -58.00 37.52");
                                        safeRunCommand("setblock 41 -59 -56 redstone_block");
                                        
                                        // Remove all tags
                                        for (let i = 1; i <= 15; i++) {
                                            safeRunCommand(`tag @a remove a3_floor${i}`);
                                            safeRunCommand(`tag @a remove a3_floor${i}_cleared`);
                                            safeRunCommand(`tag @a remove teleporter_monitoring_${i}`);
                                        }
                                        
                                        // Show credits
                                        safeRunCommand('title @a title §6§lCredits');
                                        safeRunCommand('title @a subtitle §e§lThank you for playing!');
                                        safeRunCommand("execute as @a at @s run playsound random.levelup @a ~~~ 1 0.5");
                                        safeRunCommand('tellraw @a {"rawtext":[{"text":"§6⭐ Project Team ⭐"}]}');
                                        safeRunCommand('tellraw @a {"rawtext":[{"text":"§e§l➜ Jamii - Project Manager"}]}');
                                        safeRunCommand('tellraw @a {"rawtext":[{"text":"§e§l➜ Noshi - Builder"}]}');
                                        safeRunCommand('tellraw @a {"rawtext":[{"text":"§e§l➜ Jocoskie - Artist"}]}');
                                        safeRunCommand('tellraw @a {"rawtext":[{"text":"§6➜ You can continue playing and exploring!"}]}');
                                    }, 20);
                                }, 60); // 3 seconds = 60 ticks
                            }, 40); // 2 seconds = 40 ticks
                        }, 40); // 2 seconds = 40 ticks
                    }, 20); // 1 second = 20 ticks
                }, 10); // 0.5 seconds = 10 ticks
            }, 20); // 1 second = 20 ticks
        }, 20);
    }, 40); // 2 seconds = 40 ticks
}

// Function to force finish the tower (for testing)
function forceFinishTower() {
    // Reset victory flag
    victorySequenceStarted = false;
    
    // Disable player movement first
    safeRunCommand("inputpermission set @a movement disabled");
    safeRunCommand("inputpermission set @a camera disabled");
    safeRunCommand("tag @a remove area_3");
    
    // Clear any existing floor tags
    for (let i = 1; i <= 15; i++) {
        safeRunCommand(`tag @a remove a3_floor${i}`);
        safeRunCommand(`tag @a remove a3_floor${i}_cleared`);
        safeRunCommand(`tag @a remove teleporter_monitoring_${i}`);
        safeRunCommand("tag @a remove alive");
    }
    
    // Quick fade out
    safeRunCommand("camera @a fade time 0.5 1 0.5");
    safeRunCommand("setworldspawn 61.50 -58.00 37.52");
    
    // After quick fade, start victory sequence
    system.runTimeout(() => {
        handleVictorySequence();
    }, 10);
}

// Function to force clean everything
function forceClean() {
    // Reset victory flag
    victorySequenceStarted = false;
    
    // Remove area tag first
    safeRunCommand("tag @a remove area_3");
    safeRunCommand("tag @a remove alive");

    // Kill all entities
    safeRunCommand("kill @e[family=games]");
    safeRunCommand("kill @e[type=item]");
    safeRunCommand("kill @e[family=summon]");
    safeRunCommand("kill @e[family=fire]");
    safeRunCommand("tp @e[family=water] @s ");

    // Remove all tags including teleporter monitoring tags
    for (let i = 1; i <= 15; i++) {
        safeRunCommand(`tag @a remove a3_floor${i}`);
        safeRunCommand(`tag @a remove a3_floor${i}_cleared`);
        safeRunCommand(`tag @a remove teleporter_monitoring_${i}`);
        safeRunCommand("setblock 41 -59 -56 redstone_block");
    }

    // Clear the building
    safeRunCommand("structure load mystructure:build3 195 -62 -328");
    safeRunCommand("structure load mystructure:build3.1 195 -62 -264");
    
    // Teleport players to lobby
    safeRunCommand("tp @a 61.51 -58.00 37.54 facing 61.49 -58.00 31.37");
    
    // Show message
    safeRunCommand('tellraw @a {"rawtext":[{"text":"§e§l➜ Area has been force cleaned!"}]}');
}

// Function to unlock hard tower
function unlockHardTower() {
    // Check if redstone block exists before placing
    const blockCheck = safeRunCommand("testforblock 61 -62 21 redstone_block");
    if (blockCheck.successCount === 0) {
        // Block doesn't exist, this is first unlock
        safeRunCommand("setblock 61 -62 21 redstone_block");
        safeRunCommand('tellraw @a {"rawtext":[{"text":"§d➜ Hard Tower has been unlocked!"}]}');
        safeRunCommand("execute as @a at @s run playsound random.levelup @a ~~~ 1 0.5");
    } else {
        // Block exists, just ensure it's there
        safeRunCommand("setblock 61 -62 21 redstone_block");
    }
}

// Function to handle loss scenario
function handleLoss() {
    // Disable player movement
    safeRunCommand("inputpermission set @a movement disabled");
    safeRunCommand("inputpermission set @a camera disabled");
    
    
    // First sequence - Game Over
    system.runTimeout(() => {
        // Show game over message
        safeRunCommand('title @a title §c§lGame Over');
        safeRunCommand('title @a subtitle §e§lNo one survived...');
        safeRunCommand("stopsound @a");
        safeRunCommand("particle minecraft:huge_explosion_emitter ~~~ 1");
        
        // Second sequence - Cleanup after 2 seconds
        system.runTimeout(() => {
            // Kill all entities
            safeRunCommand("execute as @a at @s run playsound jam.lose @a ~~~ 1 1");
            safeRunCommand("kill @e[family=games]");
            safeRunCommand("kill @e[type=item]");
            safeRunCommand("kill @e[family=summon]");
            safeRunCommand("kill @e[family=fire]");
            safeRunCommand("tp @e[family=water] @s ");
            
            // Remove all large tower specific tags
            for (let i = 1; i <= 15; i++) {
                safeRunCommand(`tag @a remove a3_floor${i}`);
                safeRunCommand(`tag @a remove a3_floor${i}_cleared`);
                safeRunCommand(`tag @a remove teleporter_monitoring_${i}`);
            }
            
            // Third sequence - Return message after 1 second
            system.runTimeout(() => {
                safeRunCommand('tellraw @a {"rawtext":[{"text":"§c§l➜ Mission Failed"}]}');
                
                // Fourth sequence - Fade and teleport after 2 seconds
                system.runTimeout(() => {
                    safeRunCommand("camera @a fade time 0.5 1 0.5");
                    
                    // Fifth sequence - Final cleanup and teleport after fade
                    system.runTimeout(() => {
                        // Clear the building (both parts for large tower)
                        safeRunCommand("structure load mystructure:build3 195 -62 -328");
                        safeRunCommand("structure load mystructure:build3.1 195 -62 -264");
                        
                        // Teleport to lobby
                        safeRunCommand("tp @a 61.51 -58.00 37.54 facing 61.49 -58.00 31.37");
                        safeRunCommand("setworldspawn 61.50 -58.00 37.52");
                        
                        // Re-enable player movement
                        safeRunCommand("inputpermission set @a movement enabled");
                        safeRunCommand("inputpermission set @a camera enabled");
                        safeRunCommand("setblock 41 -59 -56 redstone_block");
                        
                        // Clear camera fade
                        safeRunCommand("camera @a clear");
                        
                        // Final message
                        system.runTimeout(() => {
                            safeRunCommand('tellraw @a {"rawtext":[{"text":"§e§l➜ Return to lobby to try again!"}]}');
                            safeRunCommand("execute as @a at @s run playsound random.orb @a ~~~ 1 0.5");
                        }, 20);
                    }, 10);
                }, 40);
            }, 20);
        }, 40);
    }, 10);
}

// Add test triggers
system.runInterval(() => {
    // Check for large tower unlock test
    const testUnlock = safeRunCommand("testfor @a[tag=unlock_hard]").successCount > 0;
    if (testUnlock) {
        unlockHardTower();
        safeRunCommand("tag @a remove unlock_hard");
    }
    
    // Check for force finish test
    const testFinish = safeRunCommand("testfor @a[tag=finish_large]").successCount > 0;
    if (testFinish) {
        forceFinishTower();
        safeRunCommand("tag @a remove finish_large");
    }

    // Check for force clean test
    const testClean = safeRunCommand("testfor @a[tag=clean_large]").successCount > 0;
    if (testClean) {
        forceClean();
        safeRunCommand("tag @a remove clean_large");
    }

    // Check for force loss test
    const testLoss = safeRunCommand("testfor @a[tag=end_lost_large]").successCount > 0;
    if (testLoss) {
        handleLoss();
        safeRunCommand("tag @a remove end_lost_large");
    }
}, 20);

// For testing: Uncomment the next line to unlock large tower immediately when script loads
// system.runTimeout(() => { unlockLargeTower(); }, 100);
