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 random floor
function loadRandomFloor() {
    const floors = [
        "mystructure:a2_f1",
        "mystructure:a2_f2",
        "mystructure:a2_f3"
    ];
    const randomFloor = floors[Math.floor(Math.random() * floors.length)];
    runCommand(`structure load ${randomFloor} 42 -62 -320`);
    runCommand("tp @a 68.49 -60.00 -292.53 facing 67.22 -60.00 -292.52");
    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 a2_floor1");
        runCommand("tag @a add area_2");
    }, 40); // 5 seconds = 100 ticks
}

// Function to load random middle floor at specific Y coordinate
function loadRandomMiddleFloor(currentFloor) {
    const middleFloors = [
        "mystructure:a2_m1",
        "mystructure:a2_m2",
        "mystructure:a2_m3",
        "mystructure:a2_m4",
        "mystructure:a2_m5",
        "mystructure:a2_m6",
        "mystructure:a2_m7",
        "mystructure:a2_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
    // Floor 1: Y = -33 (base floor)
    // Floor 2: Y = -22 (+11 from floor 1)
    // Floor 3: Y = -11 (+11 from floor 2)
    // Floor 4: Y = 0 (+11 from floor 3)
    // Floor 5: Y = 11 (+11 from floor 4)
    // Floor 6: Y = 22 (+11 from floor 5)
    // Floor 7: Y = 33 (+11 from floor 6)
    // Floor 8: Y = 44 (+11 from floor 7)
    // Floor 9: Y = 55 (+11 from floor 8)
    // Floor 10: Y = 66 (+11 from floor 9) - Boss floor
    
    const nextFloor = currentFloor + 1;
    let newY;
    
    // Explicit Y coordinate calculation for each floor transition
    switch(currentFloor) {
        case 1: // Going from floor 1 to 2
            newY = -22;
            break;
        case 2: // Going from floor 2 to 3
            newY = -11;
            break;
        case 3: // Going from floor 3 to 4
            newY = 0;
            break;
        case 4: // Going from floor 4 to 5
            newY = 11;
            break;
        case 5: // Going from floor 5 to 6
            newY = 22;
            break;
        case 6: // Going from floor 6 to 7
            newY = 33;
            break;
        case 7: // Going from floor 7 to 8
            newY = 44;
            break;
        case 8: // Going from floor 8 to 9
            newY = 55;
            break;
        case 9: // Going from floor 9 to 10 (boss)
            newY = 66;
            break;
        default:
            newY = -22; // Default to floor 2 height if something goes wrong
    }

    // Debug logging
    // Removed: console.warn(`Loading floor: Current=${currentFloor}, Next=${nextFloor}, Y=${newY}`);

    system.runTimeout(() => {
        if (currentFloor < 9) {
            // For floors 1-8, load random middle floor
            const randomMiddleFloor = middleFloors[Math.floor(Math.random() * middleFloors.length)];
            runCommand(`structure load ${randomMiddleFloor} 42 ${newY} -320`);
            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 a2_floor${nextFloor}`);
                runCommand("setblock 43 -59 -56 redstone_block");
                runCommand("tag @a add alive");
                runCommand("tp @e[family=water] @s ");
                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}\"}]}`);
            }, 20); // 20 ticks = 1 second
        } else if (currentFloor === 9) {
            // For floor 9 to 10 (boss room), load specific structure
            runCommand(`structure load mystructure:a2_r1 42 ${newY} -320`);
            runCommand("camera @a shake add blink 0.5 1 0.5");
            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 a2_floor10");
                runCommand("tag @a add alive");
                runCommand("setblock 43 -59 -56 redstone_block");
                runCommand("tp @e[family=water] @s ");
                runCommand("effect @a instant_health 5 5");
                // 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
        }
    }, 60); // 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: 55, y: -62, z: 21 });
    const MediumTowerBlock = world.getDimension("overworld").getBlock({ x: 53, y: -62, z: 21 });
    
    const isMediumTowerTriggered = mediumTowerBlock?.typeId === "minecraft:redstone_block";
    const isMediumTowerUnlocked = MediumTowerBlock?.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 area1 score among all players
            let area1Score = 0;
            try {
                // Try to get the highest area1 score among all players
                const result = world.scoreboard.getObjective("area1");
                if (result) {
                    let maxScore = 0;
                    for (const score of result.getScores()) {
                        if (score.score > maxScore) maxScore = score.score;
                    }
                    area1Score = maxScore;
                }
            } catch {}
            safeRunCommand(`tellraw @a {"rawtext":[{"text":"§c§l➜ You need to finish the small tower 5x to unlock this area. You have finished the small tower §e§l${area1Score}§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 55 -58.00 29.58 facing 55 -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 -201.67 -31.32 -152.04");
                runCommand("camera @a set minecraft:free pos -211.17 -17.13 -145.18 facing -252.43 15.11 -175.53");
                runCommand("camera @a set minecraft:free ease 5 linear pos -211.17 -30.20 -145.18 facing -252.43 15.11 -175.53");
                
                // Second sequence after 5 seconds
                system.runTimeout(() => {
                    runCommand("camera @a set minecraft:free pos -211.17 -30.20 -145 facing -252.43 15.11 -175.53");
                    runCommand("camera @a set minecraft:free ease 5 linear pos -219.43 -30.20 -147.20 facing -230.24 -30.10 -147.50");
                    
                    // Remove all tags after camera fade
                    runCommand("tag @a remove dev");
                    runCommand("tag @a remove a2_floor1");
                    runCommand("tag @a remove a2_floor2");
                    runCommand("tag @a remove a2_floor3");
                    runCommand("tag @a remove a2_floor4");
                    runCommand("tag @a remove a2_floor5");
                    runCommand("tag @a remove a2_floor6");
                    runCommand("tag @a remove a2_floor7");
                    runCommand("tag @a remove a2_floor8");
                    runCommand("tag @a remove a2_floor9");
                    runCommand("tag @a remove a2_floor10");
                    runCommand("tag @a remove a2_floor1_cleared");
                    runCommand("tag @a remove a2_floor2_cleared");
                    runCommand("tag @a remove a2_floor3_cleared");
                    runCommand("tag @a remove a2_floor4_cleared");
                    runCommand("tag @a remove a2_floor5_cleared");
                    runCommand("tag @a remove a2_floor6_cleared");
                    runCommand("tag @a remove a2_floor7_cleared");
                    runCommand("tag @a remove a2_floor8_cleared");
                    runCommand("tag @a remove a2_floor9_cleared");
                    runCommand("tag @a remove a2_floor10_cleared");
                    // Remove teleporter monitoring tags
                    for (let i = 1; i <= 10; i++) {
                        runCommand(`tag @a remove teleporter_monitoring_${i}`);
                    }
                    
                    // Final sequence after 4 seconds
                    system.runTimeout(() => {
                        runCommand("camera @a fade time 0.5 4 1");
                        
                        // Add dramatic overhead view after 0.5 seconds
                        system.runTimeout(() => {
                            runCommand("tp @a 86.03 -61.00 -300.47");
                            
                            // Wait 1 second before clearing
                            system.runTimeout(() => {
                                runCommand("camera @a clear");
                                runCommand("structure load mystructure:build2 42 -62 -320");
                                runCommand("inputpermission set @a movement enabled");
                                runCommand("inputpermission set @a camera enabled");
                                isCutsceneActive = false;
                                // Load random floor and teleport player
                                loadRandomFloor();
                            }, 20); // 1 second = 20 ticks
                        }, 10); // 0.5 seconds = 10 ticks
                    }, 60); // 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;
}

// 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=a2_floor${floorNum}_cleared]`).successCount > 0;
            const hasFloorTag = safeRunCommand(`testfor @a[tag=a2_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 <= 10; i++) {
                            safeRunCommand(`tag @a remove a2_floor${i}`);
                            safeRunCommand(`tag @a remove a2_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);
}

// 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-10)
            for (let floorNum = 1; floorNum <= 10; floorNum++) {
                const hasFloorTag = safeRunCommand(`testfor @a[tag=a2_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=a2_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 === 10) {
                                // 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(`title @a[tag=a2_floor${floorNum}] title §a§lFloor ${floorNum} Cleared!`);
                                    safeRunCommand("playsound jam.reward @a ~ ~ ~ 1 1 1");
                                    safeRunCommand(`title @a[tag=a2_floor${floorNum}] subtitle §e§lApproach the teleporter to proceed`);
                                }, 10);
                                // Give 30 Coins as floor completion reward
                                system.runTimeout(() => {
                                    safeRunCommand('tellraw @a {"rawtext":[{"text":"§e§l➜ Floor Reward: §65 Coins"}]}');
                                    safeRunCommand("give @a jam:coin 5");
                                    safeRunCommand("playsound floors.1 @a ~ ~ ~ 1 1 1");
                                    safeRunCommand("setblock 44 -59 -56 redstone_block");
                                    safeRunCommand("particle minecraft:villager_happy ~~~ 1");
                                    system.runTimeout(() => {
                                        safeRunCommand("setblock 42 -59 -56 redstone_block");
                                    }, 20);
                                }, 60);
                            }
                            safeRunCommand(`tag @a add a2_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 < 10) {
                                system.runTimeout(() => {
                                    startTeleporterDetection(floorNum);
                                }, 60);
                            }
                            
                            // If this is the final floor, start the ending sequence
                            if (floorNum === 10 && !victorySequenceStarted) {
                                system.runTimeout(() => {
                                    handleVictorySequence();
                                }, 60); // Start after 3 seconds
                            }
                        }
                        
                        // Remove the old teleporter detection code since we now use the persistent system
                        // Removed: Check if player is near teleporter (only for non-final floors)
                        // Removed: system.runTimeout(() => { ... }, 120);
                    }
                }
            }
        }
    } catch (error) {
        // Log errors for debugging
        // 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("setblock 44 -59 -56 redstone_block");
    safeRunCommand("camera @a clear");
    safeRunCommand('title @a title §6§lVictory!');
    safeRunCommand("playsound jam.reward @a ~ ~ ~ 1 1 1");
    safeRunCommand('title @a subtitle §e§lYou have conquered the Medium 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_2");
    
    // 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");
        
        // Show completion message after 2 seconds
        system.runTimeout(() => {
            safeRunCommand('tellraw @a {"rawtext":[{"text":"§6⭐ Medium Tower Completed! ⭐"}]}');
            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");
            
            // 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");
                    
                    // Clear existing structure and load final one - from floor 10 victory
                    system.runTimeout(() => {
                        safeRunCommand("structure load mystructure:build2 42 -62 -320");
                        safeRunCommand("structure load mystructure:roofer2 45 0 -320");
                        safeRunCommand("tp @a 68.88 3.50 -265.97 facing 70.63 3.5 -266.02");
                        safeRunCommand("kill @e[family=games]");

                        // Quick fade in and show victory - from floor 10 victory

                        // Re-enable player movement - from floor 10 victory
                        safeRunCommand("inputpermission set @a movement enabled");
                        safeRunCommand("inputpermission set @a camera enabled");

                        // Show victory message after 1 second - from floor 10 victory
                        system.runTimeout(() => {
                            safeRunCommand("execute as @a at @s run playsound random.levelup @a ~~~ 1 0.5");
                            safeRunCommand("particle minecraft:huge_explosion_emitter ~~~ 1");
                            safeRunCommand("kill @e[family=games]");
                            safeRunCommand("kill @e[family=fire]");

                            // Show completion message after 2 seconds - from floor 10 victory
                            system.runTimeout(() => {
                                safeRunCommand('tellraw @a {"rawtext":[{"text":"§e§l➜ Receiving reward: §630 Coins"}]}');
                                safeRunCommand("give @a jam:coin 30");
                                safeRunCommand("execute as @a at @s run playsound random.levelup @a ~~~ 1 1");
                                safeRunCommand("particle minecraft:villager_happy ~~~ 1");

                                // Give rewards after 2 seconds - from floor 10 victory
                                system.runTimeout(() => {
                                    safeRunCommand("camera @a fade time 0.5 1 0.5");
                                    // Final teleport after 1 second - from floor 10 victory
                                    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("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
                                        for (let i = 1; i <= 10; i++) {
                                            safeRunCommand(`tag @a remove a2_floor${i}`);
                                            safeRunCommand(`tag @a remove a2_floor${i}_cleared`);
                                            safeRunCommand(`tag @a remove teleporter_monitoring_${i}`);
                                        }
                                        safeRunCommand("setblock 41 -59 -56 redstone_block");
                                        safeRunCommand("scoreboard players add @a area2 1");
                                    }, 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");
    
    // Remove area tag first, then alive
    safeRunCommand("tag @a remove area_2");
    safeRunCommand("tag @a remove alive");
    
    // Clear any existing floor tags
    for (let i = 1; i <= 10; i++) {
        safeRunCommand(`tag @a remove a2_floor${i}`);
        safeRunCommand(`tag @a remove a2_floor${i}_cleared`);
        safeRunCommand(`tag @a remove teleporter_monitoring_${i}`);
    }
    
    // Quick fade out
    safeRunCommand("camera @a fade time 0.5 1 0.5");
    
    // After quick fade, start victory sequence
    system.runTimeout(() => {
        handleVictorySequence();
    }, 10); // 0.5 seconds = 10 ticks
}

// Function to force clean everything
function forceClean() {
    // Reset victory flag
    victorySequenceStarted = false;
    
    // Remove area tag first
    safeRunCommand("tag @a remove area_2");
    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
    for (let i = 1; i <= 10; i++) {
        safeRunCommand(`tag @a remove a2_floor${i}`);
        safeRunCommand(`tag @a remove a2_floor${i}_cleared`);
        safeRunCommand(`tag @a remove teleporter_monitoring_${i}`);
        safeRunCommand("setblock 41 -59 -56 redstone_block");
    }

    // Clear the building
    safeRunCommand("structure load mystructure:build2 42 -62 -320");
    
    // 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 59 -62 21 redstone_block");
    if (blockCheck.successCount === 0) {
        // Block doesn't exist, this is first unlock
        safeRunCommand("setblock 59 -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 59 -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 medium tower specific tags
            for (let i = 1; i <= 10; i++) {
                safeRunCommand(`tag @a remove a2_floor${i}`);
                safeRunCommand(`tag @a remove a2_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
                        safeRunCommand("structure load mystructure:build2 42 -62 -320");
                        
                        // 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);
        }, 20);
    }, 10);
}

// Add test triggers
system.runInterval(() => {
    // Check for medium 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_medium]").successCount > 0;
    if (testFinish) {
        forceFinishTower();
        safeRunCommand("tag @a remove finish_medium");
    }

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

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

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