import { system, world } from "@minecraft/server";
import * as game from "./game";

const INTRO_MESSAGES = [
    "Hello §a{PLAYER}§r and welcome to §6§lCombine Weapons Add-On!§r",
    "Check out the §l§9Combine Weapons Guide Book§r to discover all the possible fusion recipes!",
    "Let's begin by crafting your first weapon: §l§dAmethyst Staff.§r",
    "Combine an §l§dAmethyst Shard§r and a §l§nStick§r on a crafting table or in your inventory.",
    "Use the §l§dAmethyst Staff§r to shoot explosive Amethyst shard projectiles.",
    "Have fun with §6§lCombine Weapons§r Add-On!§r",
    "Don't forget to rate it §l§e5 STARS§r on the Marketplace!"
];

const INTRO_TICK_DELAY = 80;

function showIntroMessage(player, messageIndex) {
    game.playSound(player, "@s", "tcs_cwp:info");
    let msg = INTRO_MESSAGES[messageIndex].replace("{PLAYER}", player.name);
    game.runPlayerCommand(player, `tellraw @s {\"rawtext\":[{\"text\":\"${msg}\"}]}`);
    
    if (messageIndex === 4) {
        game.runPlayerCommand(player, `structure load tcs_cwp:intro_items ~ ~ ~`);
    }
    
    player.setDynamicProperty("tcs_cwp_intro_index", messageIndex + 1);
    player.setDynamicProperty("tcs_cwp_intro_last_tick", system.currentTick);
}

function startIntroSequence(player) {
    showIntroMessage(player, 0);
    player.setDynamicProperty("tcs_cwp_intro_active", 1);
    player.addTag(`already_joined_before`);
}

export function onPlayerSpawn(event) {

    const player = event.player;

    if(!player.hasTag(`already_joined_before`)) {
        system.runTimeout(() => {
            startIntroSequence(player);
        }, 100);
    }
}

export function onTick() {
    for (const player of world.getAllPlayers()) {
        if (!player.getDynamicProperty("tcs_cwp_intro_active")) continue;
        let idx = player.getDynamicProperty("tcs_cwp_intro_index") ?? 0;
        let lastTick = player.getDynamicProperty("tcs_cwp_intro_last_tick") ?? 0;
        if (idx >= INTRO_MESSAGES.length) {
            game.runPlayerCommand(player, `structure load tcs_cwp:welcome_book ~ ~ ~`);
            player.dimension.spawnEntity("tcs_cwp:celebration_fx", player.location);
            player.setDynamicProperty("tcs_cwp_intro_active", 0);
            continue;
        }
        if (system.currentTick - lastTick >= INTRO_TICK_DELAY) {
            showIntroMessage(player, idx);
        }
    }
}
