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

// Function to remove all player-related tags
function removeAllPlayerTags() {
    safeRunCommand("tag @a remove dev");
    safeRunCommand("tag @a remove alive");
    safeRunCommand("tag @a remove area_1");
    safeRunCommand("tag @a remove area_2");
    safeRunCommand("tag @a remove area_3");

    // Small Tower tags (floor1-7)
    for (let i = 1; i <= 7; i++) {
        safeRunCommand(`tag @a remove floor${i}`);
        safeRunCommand(`tag @a remove floor${i}_cleared`);
        safeRunCommand(`tag @a remove teleporter_monitoring_${i}`);
    }

    // Medium Tower tags (a2_floor1-10)
    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}`);
    }

    // Large Tower tags (a3_floor1-15)
    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}`);
    }

    // Test-related tags
    safeRunCommand("tag @a remove unlock_medium");
    safeRunCommand("tag @a remove finish_normal");
    safeRunCommand("tag @a remove clean_normal");
    safeRunCommand("tag @a remove end_lost_normal");
    safeRunCommand("tag @a remove unlock_hard");
    safeRunCommand("tag @a remove finish_large");
    safeRunCommand("tag @a remove clean_large");
    safeRunCommand("tag @a remove end_lost_large");
    safeRunCommand("tag @a remove finish_medium");
    safeRunCommand("tag @a remove clean_medium");
    safeRunCommand("tag @a remove end_lost_medium");
}

// Function to remove water blocks from the current floor area
function removeWaterBlocks() {
    // Remove water blocks in a large area around the floor (adjust coordinates as needed)
    // This covers the typical floor area where water might spawn
    safeRunCommand("fill ~-20 ~-5 ~-20 ~20 ~10 ~20 air replace water");
    safeRunCommand("fill ~-20 ~-5 ~-20 ~20 ~10 ~20 air replace water");
    
    // Also remove any flowing water
    safeRunCommand("fill ~-20 ~-5 ~-20 ~20 ~10 ~20 air replace water");
    
    // Remove water from specific floor heights if needed
    safeRunCommand("fill ~-20 -60 ~-20 ~20 -50 ~20 air replace water");
    safeRunCommand("fill ~-20 -52 ~-20 ~20 -44 ~20 air replace water");
    safeRunCommand("fill ~-20 -44 ~-20 ~20 -36 ~20 air replace water");
    safeRunCommand("fill ~-20 -36 ~-20 ~20 -28 ~20 air replace water");
    safeRunCommand("fill ~-20 -28 ~-20 ~20 -20 ~20 air replace water");
    safeRunCommand("fill ~-20 -20 ~-20 ~20 -12 ~20 air replace water");
}

// 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:a1_f1",
        "mystructure:a1_f2",
        "mystructure:a1_f3"
    ];
    const randomFloor = floors[Math.floor(Math.random() * floors.length)];
    runCommand(`structure load ${randomFloor} 59 -60 158`);
    runCommand("tp @a 78.58 -58.00 173.47 facing 76.29 -58.00 173.48");
    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");
    
    // Add floor1 tag after 5 seconds
    system.runTimeout(() => {
        runCommand("setblock 43 -59 -56 redstone_block");
        runCommand("tag @a add floor1");
        runCommand("tag @a add area_1");
        runCommand("tp @e[family=water] @s ");
        // Remove any water blocks that might have spawned
        removeWaterBlocks();
    }, 40); // 5 seconds = 100 ticks
}

// Function to load random middle floor at specific Y coordinate
function loadRandomMiddleFloor(currentFloor) {
    const middleFloors = [
        "mystructure:a1_m1",
        "mystructure:a1_m2",
        "mystructure:a1_m3",
        "mystructure:a1_m4",
        "mystructure:a1_m5",
        "mystructure:a1_m6"
    ];

    // 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 = -60 (base floor)
    // Floor 2: Y = -52 (+8 from floor 1)
    // Floor 3: Y = -44 (+8 from floor 2)
    // Floor 4: Y = -36 (+8 from floor 3)
    // Floor 5: Y = -28 (+8 from floor 4)
    // Floor 6: Y = -20 (+8 from floor 5)
    // Floor 7: Y = -12 (+8 from floor 6) - 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 = -52;
            break;
        case 2: // Going from floor 2 to 3
            newY = -44;
            break;
        case 3: // Going from floor 3 to 4
            newY = -36;
            break;
        case 4: // Going from floor 4 to 5
            newY = -28;
            break;
        case 5: // Going from floor 5 to 6
            newY = -20;
            break;
        case 6: // Going from floor 6 to 7 (boss)
            newY = -12;
            break;
        default:
            newY = -52; // 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 < 6) {
            // For floors 1-5, 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} 59 ${newY} 158`);
            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("setblock 43 -59 -56 redstone_block");
                    runCommand("tag @a add alive");
                    runCommand(`tag @a add floor${nextFloor}`);
                    runCommand("tp @e[family=water] @s ");
                    runCommand("tag @s add alive");
                    runCommand("effect @a instant_health 5 5");
                    runCommand("tp @e[family=water] @s ");
                    runCommand("kill @e[type=item]");
                    // Remove any water blocks that might have spawned
                    removeWaterBlocks();
                    // 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
            
            // Debug confirmation
            // Removed: console.warn(`Added tag: floor${nextFloor}`);
        } else if (currentFloor === 6) {
            // For floor 6 to 7 (boss room), load specific structure
            // Removed: console.warn(`Loading boss floor at Y=${newY}`);
            runCommand(`structure load mystructure:a1_r1 59 ${newY} 158`);
            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("setblock 43 -59 -56 redstone_block");
                runCommand("tag @a add alive");
                runCommand("tag @a add floor7");
                runCommand("tp @e[family=water] @s ");
                runCommand("tag @s add alive");
                runCommand("effect @a instant_health 5 5");
                runCommand("tp @e[family=water] @s ");
                runCommand("kill @e[type=item]");
                // Remove any water blocks that might have spawned
                removeWaterBlocks();
                // 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
        }
    }, 60); // 60 ticks = 3 seconds
}

// Flag to track if cutscene is running
let isCutsceneActive = false;
let wasRedstonePresent = false;
let lastFireCheck = 0;
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 };
    }
}

// Main cutscene sequence
function startCutscene() {
    const block = world.getDimension("overworld").getBlock({ x: 49, y: -62, z: 21 });
    const isRedstonePresent = block?.typeId === "minecraft:redstone_block";
    
    // Only start the cutscene if redstone is present and cutscene isn't already running
    if (isRedstonePresent && !wasRedstonePresent && !isCutsceneActive) {
        // 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 49.50 -58.00 29.58 facing 49.53 -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 -186.62 -35.00 93.44");
            runCommand("camera @a set minecraft:free pos -193.21 -10.41 103.25 facing -209.33 -1.50 103.19");
            runCommand("camera @a set minecraft:free ease 5 linear pos -193.21 -32.62 103.25 facing -209.33 -1.50 103.19");
            
            // Second sequence after 5 seconds
            system.runTimeout(() => {
                runCommand("camera @a set minecraft:free pos -193.21 -32.62 103.25 facing -209.33 -1.50 103.19");
                runCommand("camera @a set minecraft:free ease 5 linear pos -200.70 -33.75 105.24 facing -208.28 -33.00 106.51");
                
                // Remove all tags after camera fade
                runCommand("tag @a remove dev");
                runCommand("tag @a remove floor1");
                runCommand("tag @a remove floor2");
                runCommand("tag @a remove floor3");
                runCommand("tag @a remove floor4");
                runCommand("tag @a remove floor5");
                runCommand("tag @a remove floor6");
                runCommand("tag @a remove floor7");
                runCommand("tag @a remove floor1_cleared");
                runCommand("tag @a remove floor2_cleared");
                runCommand("tag @a remove floor3_cleared");
                runCommand("tag @a remove floor4_cleared");
                runCommand("tag @a remove floor5_cleared");
                runCommand("tag @a remove floor6_cleared");
                runCommand("tag @a remove floor7_cleared");
                
                // Final sequence after 4 seconds
                system.runTimeout(() => {
                    runCommand("camera @a fade time 0.5 1 2");
                    
                    // Add dramatic overhead view after 0.5 seconds
                    system.runTimeout(() => {
                        runCommand("tp @a 93.52 -59.00 170.23");
                        
                        // Wait 1 second before clearing
                        system.runTimeout(() => {
                            runCommand("camera @a clear");
                            runCommand("structure load mystructure:build1 59 -60 158");
                            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
                }, 80); // 4 seconds = 80 ticks
            }, 100); // 5 seconds = 100 ticks
        }, 20);
    }, 260); // 1 second = 20 ticks
    }
    
    wasRedstonePresent = isRedstonePresent;
}

// 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=floor${floorNum}_cleared]`).successCount > 0;
            const hasFloorTag = safeRunCommand(`testfor @a[tag=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 <= 7; i++) {
                            safeRunCommand(`tag @a remove floor${i}`);
                            safeRunCommand(`tag @a remove 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-7)
            for (let floorNum = 1; floorNum <= 7; floorNum++) {
                const hasFloorTag = safeRunCommand(`testfor @a[tag=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=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 === 7 && !victorySequenceStarted) {
                                // Special message for completing the final floor
                                safeRunCommand("setblock 44 -59 -56 redstone_block");
                                system.runTimeout(() => {
                                    triggerTowerCompletion(); // Call the unified function
                                }, 60); // This delay was already there.
                            } else {
                                safeRunCommand("setblock 44 -59 -56 redstone_block");
                                system.runTimeout(() => {
                                safeRunCommand("playsound jam.reward @a ~ ~ ~ 1 1 1");
                                safeRunCommand(`title @a[tag=floor${floorNum}] title §a§lFloor ${floorNum} Cleared!`);
                                
                                safeRunCommand(`title @a[tag=floor${floorNum}] subtitle §e§lApproach the teleporter to proceed`);
                                }, 10);
                                // Give 10 Coins as floor completion reward
                                system.runTimeout(() => {
                                    safeRunCommand("playsound floors.1 @a ~ ~ ~ 1 1 1");
                                    safeRunCommand('tellraw @a {"rawtext":[{"text":"§e§l➜ Floor Reward: §62 Coins"}]}');
                                    safeRunCommand("give @a jam:coin 2");
                                    safeRunCommand("particle minecraft:villager_happy ~~~ 1");
                                    system.runTimeout(() => {
                                        safeRunCommand("setblock 42 -59 -56 redstone_block");
                                    }, 40);
                                }, 60);
                            }
                            safeRunCommand(`tag @a add 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 < 7) {
                                system.runTimeout(() => {
                                    startTeleporterDetection(floorNum);
                                }, 60);
                            }
                            
                            // If this is the final floor, start the ending sequence
                            // Removed the old victory sequence here as it's now in triggerTowerCompletion
                        }
                        
                        // Remove the old teleporter detection code since we now use the persistent system
                        // Removed: Add a 5-second delay before checking if player is near teleporter
                        // Removed: system.runTimeout(() => { ... }, 120);
                    }
                }
            }
        }
    } catch (error) {
        // Removed: console.warn("Error in fire check interval: " + error);
    }
}, 1);

// Function to unlock medium tower (for testing or normal progression)
function unlockMediumTower() {
    // Check if redstone block exists before placing
    const blockCheck = safeRunCommand("testforblock 53 -62 21 redstone_block");
    if (blockCheck.successCount === 0) {
        // Block doesn't exist, this is first unlock
        safeRunCommand('tellraw @a {"rawtext":[{"text":"§d➜ Medium 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
    }
}

// Function to force finish the tower (for testing)
function forceFinishTower() {
    // Reset victory flag
    victorySequenceStarted = false;
    
    triggerTowerCompletion();
}

// Function to force clean everything
function forceClean() {
    // Reset victory flag
    victorySequenceStarted = false;
    
    // Remove area tag first

    // 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 water blocks
    removeWaterBlocks();

    // Remove all tags
    removeAllPlayerTags(); // Call the new helper function
    safeRunCommand("setblock 41 -59 -56 redstone_block");

    // Clear the building
    safeRunCommand("structure load mystructure:build1 59 -60 158");
    
    // 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 handle loss scenario
function handleLoss() {
    // Disable player movement
    safeRunCommand("inputpermission set @a movement disabled");
    safeRunCommand("inputpermission set @a camera disabled");
    
    // Initial fade out
    
    // 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 tags
            safeRunCommand("tag @a remove dev");
            safeRunCommand("tag @a remove floor1");
            safeRunCommand("tag @a remove floor2");
            safeRunCommand("tag @a remove floor3");
            safeRunCommand("tag @a remove floor4");
            safeRunCommand("tag @a remove floor5");
            safeRunCommand("tag @a remove floor6");
            safeRunCommand("tag @a remove floor7");
            safeRunCommand("tag @a remove floor1_cleared");
            safeRunCommand("tag @a remove floor2_cleared");
            safeRunCommand("tag @a remove floor3_cleared");
            safeRunCommand("tag @a remove floor4_cleared");
            safeRunCommand("tag @a remove floor5_cleared");
            safeRunCommand("tag @a remove floor6_cleared");
            safeRunCommand("tag @a remove floor7_cleared");
            // Remove teleporter monitoring tags
            for (let i = 1; i <= 7; i++) {
                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:build1 59 -60 158");
                        
                        // 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!"}]}');
                        }, 20);
                    }, 10);
                }, 40);
            }, 20);
        }, 40);
    }, 10);
}

// New function to trigger tower completion victory sequence
function triggerTowerCompletion() {
    // Prevent duplicate victory sequences
    if (victorySequenceStarted) {
        return;
    }
    victorySequenceStarted = true;
    
    safeRunCommand("inputpermission set @a movement disabled");
    safeRunCommand("inputpermission set @a camera disabled");
    safeRunCommand("tag @a remove area_1");

    // Clear any existing floor tags
    for (let i = 1; i <= 7; i++) {
        safeRunCommand(`tag @a remove floor${i}`);
        safeRunCommand(`tag @a remove floor${i}_cleared`);
        safeRunCommand(`tag @a remove teleporter_monitoring_${i}`);
    }

    safeRunCommand("camera @a fade time 0.5 1 0.5"); // Initial fade out
    safeRunCommand("tag @a remove alive");
    safeRunCommand("playsound jam.reward @a ~ ~ ~ 1 1 1");

    system.runTimeout(() => {
        // Clear existing structure and load final one
        safeRunCommand("structure load mystructure:build1 59 -60 158");
        safeRunCommand("structure load mystructure:roofer1 59 -12 158");
        safeRunCommand("tp @a 69.48 -3.00 169.98 facing 69.51 -3.00 163.70");

        safeRunCommand("camera @a fade time 0.5 1 0.5"); // Quick fade in
        safeRunCommand("kill @e[family=games]");
        safeRunCommand("kill @e[family=games]");
        safeRunCommand("inputpermission set @a movement enabled");
        safeRunCommand("inputpermission set @a camera enabled");

        system.runTimeout(() => { // 1 second delay
            safeRunCommand('title @a title §6§lVictory!');
            safeRunCommand("kill @e[family=games]");
            safeRunCommand("kill @e[family=fire]");
            safeRunCommand('title @a subtitle §e§lYou have conquered the Small Tower!');
            safeRunCommand("playsound floors.2 @a ~ ~ ~ 1 1 1");
            safeRunCommand("execute as @a at @s run playsound random.levelup @a ~~~ 1 0.5");
            safeRunCommand("particle minecraft:huge_explosion_emitter ~~~ 1");

            system.runTimeout(() => { // 2 seconds delay
                safeRunCommand('tellraw @a {"rawtext":[{"text":"§6⭐ Small Tower Completed! ⭐"}]}');
                safeRunCommand("execute as @a at @s run playsound random.orb @a ~~~ 1 0.5");
                safeRunCommand("particle minecraft:villager_happy ~~~ 1");

                system.runTimeout(() => { // 2 seconds delay
                    safeRunCommand('tellraw @a {"rawtext":[{"text":"§e§l➜ Receiving reward: §610 Coins"}]}');
                    safeRunCommand("give @a jam:coin 10");
                    safeRunCommand("execute as @a at @s run playsound random.levelup @a ~~~ 1 1");
                    safeRunCommand("particle minecraft:villager_happy ~~~ 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 ");

                    system.runTimeout(() => { // 3 seconds delay
                        safeRunCommand("camera @a fade time 0.5 1 0.5");

                        system.runTimeout(() => { // 1 second delay
                            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");

                            // Remove all tags
                            removeAllPlayerTags(); // Call the new helper function
                            safeRunCommand("setblock 41 -59 -56 redstone_block");

                            // Check for medium tower unlock
                            safeRunCommand("scoreboard players add @a area1 1");
                        }, 20); // 1 second
                    }, 60); // 3 seconds
                }, 40); // 2 seconds
            }, 40); // 2 seconds
        }, 20); // 1 second
    }, 10); // 0.5 seconds
}

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

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

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

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

// Force Reset Detection
world.beforeEvents.itemUse.subscribe(event => {
    const player = event.source;
    const item = event.itemStack;

    if (item && item.typeId === "jam:restart") {
        event.cancel = true; // Prevent default item use behavior

        const form = new MessageFormData()
            .title("§lForce Reset")
            .body("Would you like to restart the game and head back to the lobby?")
            .button1("No")
            .button2("Force Reset");

        system.run(() => {
            form.show(player).then(response => {
                if (!response.canceled && response.selection === 1) {
                    // Player selected 'Force Reset'
                    resetGameAndReturnToLobby();
                }
            }).catch(e => console.error(e, e.stack));
        });
    }
});

// New function to handle game reset and return to lobby
function resetGameAndReturnToLobby() {
    // Reset victory flag
    victorySequenceStarted = false;
    
    // Disable player movement and camera
    safeRunCommand("inputpermission set @a movement disabled");
    safeRunCommand("inputpermission set @a camera disabled");
    safeRunCommand("clear @a jam:extinguisher"); // Clear extinguisher on reset

    // Initial fade out
    safeRunCommand("camera @a fade time 0.5 1 0.5");

    system.runTimeout(() => {
        // Perform the core cleanup actions
        removeAllPlayerTags(); // Call the new helper function
        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 water blocks
        removeWaterBlocks();
        safeRunCommand("structure load mystructure:build1 59 -60 158"); // Load base structure
        safeRunCommand("tp @a 61.51 -58.00 37.54 facing 61.49 -58.00 31.37"); // Teleport to lobby
        safeRunCommand("setworldspawn 61.50 -58.00 37.52"); // Set world spawn to lobby

        // After cleanup, continue with cinematic effects and re-enable input
        system.runTimeout(() => {
            safeRunCommand("camera @a fade time 0.5 1 0.5"); // Quick fade in after cleanup teleport
            safeRunCommand("inputpermission set @a movement enabled");
            safeRunCommand("inputpermission set @a camera enabled");
            safeRunCommand("setblock 41 -59 -56 redstone_block"); // Activate a block, similar to handleLoss

            system.runTimeout(() => {
                safeRunCommand('title @a title §a§lGame Reset!'); // Neutral reset message
                safeRunCommand('title @a subtitle §e§lReturning to Lobby...');
                safeRunCommand("playsound random.levelup @a ~~~ 1 0.5"); // Neutral sound effect
                safeRunCommand("particle minecraft:villager_happy ~~~ 1"); // Neutral particle effect

                system.runTimeout(() => {
                    safeRunCommand('tellraw @a {"rawtext":[{"text":"§e§l➜ Game has been reset!"}]}');
                    safeRunCommand("execute as @a at @s run playsound random.orb @a ~~~ 1 0.5");
                    safeRunCommand("particle minecraft:villager_happy ~~~ 1");
                }, 40); // 2 seconds delay
            }, 40); // 2 seconds delay
        }, 10); // 0.5 seconds delay after initial fade and cleanup
    }, 10); // Initial delay to allow first fade
}
