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

const gsce_cineTick = new Map();
const originalGamemode = new Map();

// Function to restore original gamemode (kept from original)
function restoreOriginalGamemode(player) {
    const name = player.name;
    
    // Try to restore from Map first
    const originalMode = originalGamemode.get(name);
    if (originalMode !== undefined) {
        player.setGameMode(originalMode);
        originalGamemode.delete(name);
    } else {
        // Fallback: restore from scoreboard
        try {
            const origObj = world.scoreboard.getObjective("originalGamemode");
            if (origObj) {
                const score = origObj.getScore(player);
                if (score !== undefined) {
                    switch (score) {
                        case 0: player.setGameMode(GameMode.survival); break;
                        case 1: player.setGameMode(GameMode.creative); break;
                        case 2: player.setGameMode(GameMode.adventure); break;
                        case 3: player.setGameMode(GameMode.spectator); break;
                    }
                }
            }
        } catch (e) {
            console.warn(`Failed to restore gamemode from scoreboard: ${e}`);
            player.setGameMode(GameMode.survival); // Final fallback
        }
    }
    
    // Clean up scoreboard entry
    try {
        const origObj = world.scoreboard.getObjective("originalGamemode");
        if (origObj) {
            origObj.removeParticipant(player);
        }
    } catch (e) {
        console.warn(`Failed to clean up original gamemode scoreboard: ${e}`);
    }
}

system.runInterval(() => {
    for (const player of world.getPlayers()) {
        const name = player.name;

        if (player.hasTag("cinematic")) {
            let current = gsce_cineTick.get(name) ?? 0;
            current += 1;
            gsce_cineTick.set(name, current);

            console.log(`Player ${name} cinematic tick: ${current}`);

            // Start cinematic
            if (current === 1) {
                console.log(`Starting cinematic for ${name}`);
                
                // Start cinematic
                try {
                    player.runCommand("gamerule sendcommandfeedback false");
                    player.runCommand("camera @s fade time 0 10 2");
                    player.runCommand("time set midnight");
                    player.setGameMode(GameMode.spectator);
                    player.runCommand("gamerule doDaylightCycle false");
                    player.runCommand("inputpermission set @s camera disabled");
                } catch (e) {
                    console.warn(`Error in cinematic initialization for ${name}: ${e}`);
                }
            }

            // Initial teleport phase
            if (current >= 2 && current <= 40) {
                try {
                    player.runCommand("tp @s @e[type=gs_ce:portal_locator,c=1]");
                } catch (e) {
                    if (current === 2) console.warn(`Portal locator not found for ${name}: ${e}`);
                }
            }

            // Title sequences and audio
            if (current === 100) {
                try {
                    player.runCommand(`title @s title "Glorious Studios"`);
                    player.runCommand(`title @s subtitle "Presents..."`);
                } catch (e) {
                    console.warn(`Title error at tick 100 for ${name}: ${e}`);
                }
            }

            if (current === 101) {
                try {
                    player.runCommand("playsound gs_ce.useportal @s ~~~");
                    player.runCommand("camera @s fade time 0 7 1");
                } catch (e) {
                    console.warn(`Audio/camera error at tick 101 for ${name}: ${e}`);
                }
            }

            if (current === 150) {
                try {
                    player.runCommand("playsound gs_ce.camerashake @s ~~~");
                } catch (e) {
                    console.warn(`Audio error at tick 150 for ${name}: ${e}`);
                }
            }

            if (current === 160) {
                try {
                    player.runCommand(`title @s title §eCREAKING EXPANSION!`);
                } catch (e) {
                    console.warn(`Title error at tick 160 for ${name}: ${e}`);
                }
            }

            if (current === 270) {
                try {
                    player.runCommand("playsound gs_ce.cinematic @s ~~~ 0.2");
                } catch (e) {
                    console.warn(`Audio error at tick 270 for ${name}: ${e}`);
                }
            }

            if (current === 280) {
                try {
                    player.runCommand("playsound gs_ce.earthquake @s ~~~");
                } catch (e) {
                    console.warn(`Audio error at tick 280 for ${name}: ${e}`);
                }
            }

            // Portal approach sequence (301-402)
            if (current === 301) {
                try {
                    player.runCommand("execute at @e[type=gs_ce:portal_locator,c=1] run tp @s ^^^-2 facing @e[type=gs_ce:portal_locator,c=1]");
                } catch (e) {
                    console.warn(`Portal approach start error for ${name}: ${e}`);
                }
            }

            if (current >= 302 && current <= 394) {
                try {
                    player.runCommand("tp @s ~~0.1~-0.3 facing @e[type=gs_ce:portal_locator,c=1]");
                } catch (e) {
                    if (current === 302) console.warn(`Portal movement error for ${name}: ${e}`);
                }
            }

            if (current >= 302 && current <= 360) {
                try {
                    player.runCommand("camerashake add @s 0.02 2 positional");
                } catch (e) {
                    if (current === 302) console.warn(`Camera shake error for ${name}: ${e}`);
                }
            }

            if (current === 380) {
                try {
                    player.runCommand("camera @s fade time 0.5 1 0.5");
                } catch (e) {
                    console.warn(`Camera fade error at 380 for ${name}: ${e}`);
                }
            }

            if (current === 390) {
                try {
                    player.runCommand("camerashake stop @s");
                } catch (e) {
                    console.warn(`Camera shake stop error for ${name}: ${e}`);
                }
            }

            if (current >= 394 && current <= 402) {
                try {
                    player.runCommand("execute at @e[type=gs_ce:portal_locator,c=1] run tp @s ^^^-2");
                } catch (e) {
                    if (current === 394) console.warn(`Portal end position error for ${name}: ${e}`);
                }
            }

            // Island 2 sequence (403-502)
            if (current === 403) {
                try {
                    player.runCommand("execute at @e[type=gs_ce:island_locator,tag=island_2,c=1] run tp @s ~~15~-50 facing @e[type=gs_ce:island_locator,tag=island_2,c=1]");
                } catch (e) {
                    console.warn(`Island 2 start error for ${name}: ${e}`);
                }
            }

            if (current >= 404 && current <= 494) {
                try {
                    player.runCommand("tp @s ^-0.5^^ facing @e[type=gs_ce:island_locator,tag=island_2,c=1]");
                } catch (e) {
                    if (current === 404) console.warn(`Island 2 movement error for ${name}: ${e}`);
                }
            }

            if (current === 480) {
                try {
                    player.runCommand("camera @s fade time 0.5 1 0.5");
                } catch (e) {
                    console.warn(`Camera fade error at 480 for ${name}: ${e}`);
                }
            }

            if (current >= 494 && current <= 502) {
                try {
                    player.runCommand("execute at @e[type=gs_ce:portal_locator,c=1] run tp @s ^^^-2");
                } catch (e) {
                    if (current === 494) console.warn(`Island 2 end error for ${name}: ${e}`);
                }
            }

            // Island 3 sequence (503-602)
            if (current === 503) {
                try {
                    player.runCommand("execute at @e[type=gs_ce:island_locator,tag=island_3,c=1] run tp @s ~~15~-50 facing @e[type=gs_ce:island_locator,tag=island_3,c=1]");
                } catch (e) {
                    console.warn(`Island 3 start error for ${name}: ${e}`);
                }
            }

            if (current >= 504 && current <= 594) {
                try {
                    player.runCommand("tp @s ^-0.5^^ facing @e[type=gs_ce:island_locator,tag=island_3,c=1]");
                } catch (e) {
                    if (current === 504) console.warn(`Island 3 movement error for ${name}: ${e}`);
                }
            }

            if (current === 580) {
                try {
                    player.runCommand("camera @s fade time 0.5 1 0.5");
                } catch (e) {
                    console.warn(`Camera fade error at 580 for ${name}: ${e}`);
                }
            }

            if (current >= 594 && current <= 602) {
                try {
                    player.runCommand("execute at @e[type=gs_ce:portal_locator,c=1] run tp @s ^^^-2");
                } catch (e) {
                    if (current === 594) console.warn(`Island 3 end error for ${name}: ${e}`);
                }
            }

            // Island 4 sequence (603-702)
            if (current === 603) {
                try {
                    player.runCommand("execute at @e[type=gs_ce:island_locator,tag=island_4,c=1] run tp @s ~~15~-50 facing @e[type=gs_ce:island_locator,tag=island_4,c=1]");
                } catch (e) {
                    console.warn(`Island 4 start error for ${name}: ${e}`);
                }
            }

            if (current >= 604 && current <= 694) {
                try {
                    player.runCommand("tp @s ^-0.5^^ facing @e[type=gs_ce:island_locator,tag=island_4,c=1]");
                } catch (e) {
                    if (current === 604) console.warn(`Island 4 movement error for ${name}: ${e}`);
                }
            }

            if (current === 680) {
                try {
                    player.runCommand("camera @s fade time 0.5 1 0.5");
                } catch (e) {
                    console.warn(`Camera fade error at 680 for ${name}: ${e}`);
                }
            }

            if (current >= 694 && current <= 702) {
                try {
                    player.runCommand("execute at @e[type=gs_ce:portal_locator,c=1] run tp @s ^^^-2");
                } catch (e) {
                    if (current === 694) console.warn(`Island 4 end error for ${name}: ${e}`);
                }
            }

            // Island 5 sequence (703-802)
            if (current === 703) {
                try {
                    player.runCommand("execute at @e[type=gs_ce:island_locator,tag=island_5,c=1] run tp @s ~~15~-50 facing @e[type=gs_ce:island_locator,tag=island_5,c=1]");
                } catch (e) {
                    console.warn(`Island 5 start error for ${name}: ${e}`);
                }
            }

            if (current >= 704 && current <= 794) {
                try {
                    player.runCommand("tp @s ^-0.5^^ facing @e[type=gs_ce:island_locator,tag=island_5,c=1]");
                } catch (e) {
                    if (current === 704) console.warn(`Island 5 movement error for ${name}: ${e}`);
                }
            }

            if (current === 780) {
                try {
                    player.runCommand("camera @s fade time 0.5 1 0.5");
                } catch (e) {
                    console.warn(`Camera fade error at 780 for ${name}: ${e}`);
                }
            }

            if (current >= 794 && current <= 802) {
                try {
                    player.runCommand("execute at @e[type=gs_ce:portal_locator,c=1] run tp @s ^^^-2");
                } catch (e) {
                    if (current === 794) console.warn(`Island 5 end error for ${name}: ${e}`);
                }
            }

            // Island 6 and final sequence (803-994)
            if (current === 803) {
                try {
                    player.runCommand("execute at @e[type=gs_ce:island_locator,tag=island_6,c=1] run tp @s ~~15~-50 facing @e[type=gs_ce:island_locator,tag=island_6,c=1]");
                } catch (e) {
                    console.warn(`Island 6 start error for ${name}: ${e}`);
                }
            }

            if (current >= 804 && current <= 894) {
                try {
                    player.runCommand("tp @s ^-0.5^^ facing @e[type=gs_ce:island_locator,tag=island_6,c=1]");
                } catch (e) {
                    if (current === 804) console.warn(`Island 6 movement error for ${name}: ${e}`);
                }
            }

            if (current === 880) {
                try {
                    player.runCommand("camera @s fade time 0.5 1 0.5");
                } catch (e) {
                    console.warn(`Camera fade error at 880 for ${name}: ${e}`);
                }
            }

            if (current >= 894 && current <= 902) {
                try {
                    player.runCommand("execute at @e[type=gs_ce:portal_locator,c=1] run tp @s ^^10^-20");
                } catch (e) {
                    if (current === 894) console.warn(`Final approach start error for ${name}: ${e}`);
                }
            }

            if (current >= 902 && current <= 994) {
                try {
                    player.runCommand("tp @s ~~-0.1~0.15 facing @e[type=gs_ce:portal_locator,c=1]");
                } catch (e) {
                    if (current === 902) console.warn(`Final descent error for ${name}: ${e}`);
                }
            }

            if (current === 980) {
                try {
                    player.runCommand("camera @s fade time 0.5 1 0.5");
                } catch (e) {
                    console.warn(`Final camera fade error for ${name}: ${e}`);
                }
            }

            // End cinematic
            if (current === 1000) {
                console.log(`Ending cinematic for ${name}`); // Debug log
                
                try {
                    player.runCommand("gamerule doDaylightCycle true");
                    
                    const portals = world.getDimension("overworld").getEntities({
                        type: "gs_ce:portal_locator"
                    });
                    
                    if (portals.length > 0) {
                        player.runCommand("tp @s @e[type=gs_ce:portal_locator,c=1]");
                        player.runCommand("tp @s ~~~ 180 0");
                    }

                    // Restore original gamemode using the function
                    restoreOriginalGamemode(player);

                    player.runCommand("gamerule sendcommandfeedback true");
                    player.runCommand("inputpermission set @s camera enabled");
                    
                    // Clean up entities
                    player.runCommand("event entity @e[type=gs_ce:portal_locator] despawn");
                    player.runCommand("event entity @e[type=gs_ce:island_locator] despawn");
                    
                    player.removeTag("cinematic");

                    // Clear tracking
                    gsce_cineTick.delete(name);
                    
                } catch (e) {
                    console.warn(`Error ending cinematic for ${name}: ${e}`);
                    player.removeTag("cinematic");
                    gsce_cineTick.delete(name);
                }
            }

        } else {
            // Reset tick counter for players without cinematic tag
            if (gsce_cineTick.has(name)) {
                gsce_cineTick.set(name, 0);
            }
        }
    }
}, 1);