import { world, Player } from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";

// omnitrix's module items
world.afterEvents.itemUse.subscribe(event => {
    const { source: player, itemStack } = event;

    let is_alien_x_unlock = 'alien_x_not_unlock';
    if (player.hasTag('playlist2')) {
        is_alien_x_unlock = 'alien_x_unlock';
    };

    if (!player || !itemStack) return;
    if (!(player instanceof Player)) return;

    if (itemStack.typeId === "yog:omni_quick_select" && player.hasTag(`master_control`)) {

        const quickTransform = new ActionFormData()
            .title('yog:quick_select.form.ui' + 'quick_select' + is_alien_x_unlock)
            .body('')
            .button(`Swampfire`, `textures/items/_yog/swampfire_skill_item`)
            .button(`Humungousaur`, `textures/items/_yog/humungousaur_skill_item`)
            .button(`Bigchill`, `textures/items/_yog/bigchill_skill_item`)
            .button(`Echo-Echo`, `textures/items/_yog/echo_skill_item`)
            .button(`Alien-X`, `textures/items/_yog/echo_skill_item`);

        quickTransform.show(player).then(response => {
            if (response.canceled) return;

            if (response.selection === 0) {
                if (player.hasTag(`swampfire`) || player.hasTag(`swampfire_ultimate`)) {
                    player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"§6Assistant §r: §aYou already on this alien form."}]}`);
                } else {
                    player.runCommandAsync(`tag @s add quick_transform`);
                    player.runCommandAsync(`tag @s add quick1`);
                    player.runCommandAsync(`function systems/untransform`);
                    player.runCommandAsync(`function systems/omni_quick_select`);
                }
            }
            else if (response.selection === 1) {
                if (player.hasTag(`humungousaur`) || player.hasTag(`humungousaur_full`) || player.hasTag(`humungousaur_ultimate`)) {
                    player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"§6Assistant §r: §aYou already on this alien form."}]}`);
                } else {
                    player.runCommandAsync(`tag @s add quick_transform`);
                    player.runCommandAsync(`tag @s add quick2`);
                    player.runCommandAsync(`function systems/untransform`);
                    player.runCommandAsync(`function systems/omni_quick_select`);
                }
            }
            else if (response.selection === 2) {
                if (player.hasTag(`bigchill`) || player.hasTag(`bigchill_ultimate`)) {
                    player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"§6Assistant §r: §aYou already on this alien form."}]}`);
                } else {
                    player.runCommandAsync(`tag @s add quick_transform`);
                    player.runCommandAsync(`tag @s add quick3`);
                    player.runCommandAsync(`function systems/untransform`);
                    player.runCommandAsync(`function systems/omni_quick_select`);
                }
            }
            else if (response.selection === 3) {
                if (player.hasTag(`echo`) || player.hasTag(`echo_ultimate`)) {
                    player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"§6Assistant §r: §aYou already on this alien form."}]}`);
                } else {
                    player.runCommandAsync(`tag @s add quick_transform`);
                    player.runCommandAsync(`tag @s add quick4`);
                    player.runCommandAsync(`function systems/untransform`);
                    player.runCommandAsync(`function systems/omni_quick_select`);
                }
            }
            else if (response.selection === 4) {
                if (player.hasTag(`alien_x`)) {
                    player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"§6Assistant §r: §aYou already on this alien form."}]}`);
                } else {
                    player.runCommandAsync(`tag @s add x_transformation`);
                    player.runCommandAsync(`function systems/untransform`);
                    player.runCommandAsync(`scoreboard players set @s cinematic 0`);
                }
            }
        });

    }

});

// Question-Test
function shuffle(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}
const questions = [
    {
        body: [
            {
                text: "Do you have a girl?",
                answers: [
                    { text: "Yes, I have.", correct: false },
                    { text: "No, I don't.", correct: true },
                    { text: "Still single.", correct: true }
                ]
            },
            {
                text: "Are you single?",
                answers: [
                    { text: "Yes, I am single.", correct: true },
                    { text: "Nope, I have someone.", correct: false },
                    { text: "Not single anymore.", correct: false }
                ]
            },
            {
                text: "Is it true, that you don't have any relationship with girl?",
                answers: [
                    { text: "Yes, it's true.", correct: true },
                    { text: "No, I have a girlfriend.", correct: false },
                    { text: "Maybe…", correct: false }
                ]
            }
        ]
    },
    {
        body: [
            {
                text: "Do you sleep at a regular time?",
                answers: [
                    { text: "Yes, I sleep early.", correct: true },
                    { text: "No, I always stay up late.", correct: false },
                    { text: "Sometimes only.", correct: true }
                ]
            },
            {
                text: "Do you stay up late all the time?",
                answers: [
                    { text: "Yes, every night.", correct: false },
                    { text: "No, I sleep on time.", correct: true },
                    { text: "Depends on the day.", correct: true }
                ]
            },
            {
                text: "Are you a Batman?",
                answers: [
                    { text: "Yes, I'm Batman.", correct: false },
                    { text: "No, I'm just human.", correct: true },
                    { text: "Sometimes I feel like Batman.", correct: false }
                ]
            }
        ]
    },
    {
        body: [
            {
                text: "Have you touch some grass?",
                answers: [
                    { text: "No, I don't.", correct: false },
                    { text: "What Grass?.", correct: false },
                    { text: "Yep, already touch it.", correct: true }
                ]
            },
            {
                text: "Do you like helping people?",
                answers: [
                    { text: "Sometimes.", correct: true },
                    { text: "Yes.", correct: false },
                    { text: "Nope.", correct: false }
                ]
            },
            {
                text: "Do you like vegetarian food?",
                answers: [
                    { text: "Nah, I don't like it", correct: false },
                    { text: "Of course, I like it.", correct: true },
                    { text: "Yeuhhh Green Food?", correct: false }
                ]
            }
        ]
    },
    {
        body: [
            {
                text: "Do you have friends?",
                answers: [
                    { text: "Nah, I don't", correct: false },
                    { text: "I guess not.", correct: false },
                    { text: "Yeah, I have friend.", correct: true }
                ]
            },
            {
                text: "Have lot friends?",
                answers: [
                    { text: "Not really...", correct: true },
                    { text: "Yes.", correct: false },
                    { text: "No...", correct: false }
                ]
            },
            {
                text: "Would you betray your friend?",
                answers: [
                    { text: "Why not.", correct: false },
                    { text: "No, I can't do that.", correct: true },
                    { text: "Yes, if results are profitable.", correct: false }
                ]
            }
        ]
    }
];
let playerData = new Map();
function resetQuiz(player) {
    playerData.set(player.id, { points: 1, index: 0 });
    player.sendMessage("You failed the test.");
    player.runCommandAsync(`function systems/test_failed`);
}
function showQuestion(player) {
    let data = playerData.get(player.id);
    if (!data) {
        data = { points: 1, index: 0 };
        playerData.set(player.id, data);
    }

    if (data.index >= questions.length) {
        player.sendMessage(`You deserve this power.`);
        player.runCommandAsync(`tag @s add finish_exam_test`);
        playerData.delete(player.id);
        return;
    }

    let q = questions[data.index];

    let qBody = q.body[Math.floor(Math.random() * q.body.length)];

    let shuffled = shuffle([...qBody.answers]);
    let selected = shuffled.slice(0, 3);

    if (!selected.some(ans => ans.correct)) {
        const correctAnswer = qBody.answers.find(ans => ans.correct);
        selected[Math.floor(Math.random() * selected.length)] = correctAnswer;
    }

    const form = new ActionFormData()
        .title('Exam Test')
        .body(`Point Remain: ${data.points}\n${qBody.text}`);

    selected.forEach(a => form.button(a.text));

    form.show(player).then(response => {
        if (response.canceled) {
            return;
        }

        const chosen = selected[response.selection];

        if (chosen.correct) {
            player.sendMessage("Correct.");
            data.index++;
            showQuestion(player);
        } else {
            data.points--;
            if (data.points <= 0) {
                resetQuiz(player);
            } else {
                data.index = 0;
                player.sendMessage(`Wrong.`);
                showQuestion(player);
            }
        }
    });
}
world.afterEvents.itemUse.subscribe(event => {
    const { source: player, itemStack } = event;

    if (itemStack.typeId === "yog:test_item") {
        if (!playerData.has(player.id)) {
            playerData.set(player.id, { points: 1, index: 0 });
        }
        showQuestion(player);
    }
});

// Alien-x Teleport
world.afterEvents.itemUse.subscribe(event => {
    const { source: player, itemStack } = event;
    if (!player || !(player instanceof Player) || !itemStack) return;

    if (itemStack.typeId === "yog:alien_x_skill2" && player.hasTag(`skill2_special`)) {

        const tpForm = new ModalFormData()
            .title("Teleport")
            .textField("§l§4X", "Example: 10", "")
            .textField("§l§2Y", "Example: 2", "")
            .textField("§l§1Z", "Example: 10", "");

        tpForm.show(player).then(response => {
            if (response.canceled) return;

            let [xInput, yInput, zInput] = response.formValues;

            let x = parseFloat(xInput);
            let y = parseFloat(yInput);
            let z = parseFloat(zInput);

            if (isNaN(x) || isNaN(y) || isNaN(z)) {
                player.sendMessage("§cInvalid Coordinates.");
                return;
            }

            player.teleport(
                { x: x, y: y, z: z },
                { dimension: player.dimension, rotation: player.getRotation() }
            );

            player.sendMessage(`§aHas been Teleported to §4X: ${x}, §2Y: ${y}, §1Z: ${z}`);
        });
    }
});

// Alien-x Special Ability
world.afterEvents.itemUse.subscribe(event => {
    const { source: player, itemStack } = event;

    if (!player || !itemStack) return;
    if (!(player instanceof Player)) return;

    if (itemStack.typeId === "yog:fly_skill" && player.hasTag("special_ability")) {
    let is_air_walk = player.hasTag("air_walk") ? "ON" : "OFF";
    let is_block_destroy = player.hasTag("block_destroy") ? "ON" : "OFF";

    const form = new ModalFormData()
        .title("Alien-X Special Ability")
        .toggle("Air Walk : " + is_air_walk, player.hasTag("air_walk"))
        .toggle("Block Destroy : " + is_block_destroy, player.hasTag("block_destroy"));

    form.show(player).then(response => {
        if (response.canceled) {
            player.removeTag("special_ability");
            return;
        }

        const isEnabled = response.formValues[0];
        const isEnabled2 = response.formValues[1];

        if (isEnabled) {
            player.addTag("air_walk");
            player.runCommandAsync(
                'tellraw @s {"rawtext":[{"text":"§6System §r: §eAir walk On."}]}'
            );
        } else {
            player.removeTag("air_walk");
            player.runCommandAsync(
                'tellraw @s {"rawtext":[{"text":"§6System §r: §4Air walk Off."}]}'
            );
        }

        if (isEnabled2) {
            player.addTag("block_destroy");
            player.runCommandAsync(
                'tellraw @s {"rawtext":[{"text":"§6System §r: §eBlock Destroy On."}]}'
            );
        } else {
            player.removeTag("block_destroy");
            player.runCommandAsync(
                'tellraw @s {"rawtext":[{"text":"§6System §r: §4Block Destroy Off."}]}'
            );
        }

        player.removeTag("special_ability");
    });
}

});