
import { world, system, ItemStack } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
import { configUiProfile } from "./furnaceMain";

world.afterEvents.playerSpawn.subscribe(xZ => {
    if (xZ.initialSpawn && !xZ.player.hasTag('vtng_fn:first_guidebook')) {
        xZ.player.addTag('vtng_fn:first_guidebook');
        xZ.player.dimension.spawnItem(new ItemStack('vtng_fn:furnaces_guidebook'), xZ.player.location);
    };
});

world.beforeEvents.itemUse.subscribe(xZ => {
    if (xZ.itemStack?.typeId != 'vtng_fn:furnaces_guidebook') return;
    system.run(() => guidebookFirstPage(xZ.source));
});

const guidebookButtons = [
    'compatibility',
    'wooden_furnaces',
    'furnace_upgrade',
    'blast_furnace_upgrade',
    'smoker_upgrade',
    'industrial_furnace',
    'ice_furnace',
    'nether_furnace',
    'redstone_furnace',
    'crystal_furnace',
    'infinity_furnace',
    'chest_upgrade',
    'portal_chest',
    'magnet_chest',
    'locked_chest'
]; 

function guidebookFirstPage(source) {
    const page = new ActionFormData();
    page.title('vtng_fn.guidebook.first_page.title');

    if (!source.hasTag('vtng_fn:configured_ui')) page.body('vtng_fn.guidebook.first_page.text');
    else page.body('vtng_fn.guidebook.first_page.text_2');

    if (source.hasTag('vtng_fn:configured_ui')) page.button('vtng_fn.guidebook.config_ui.title', 'textures/vtng/fn/ui/guidebook_icons/config_ui');
    guidebookButtons.forEach(button => {
        page.button(`vtng_fn.guidebook.${button}.title`, `textures/vtng/fn/ui/guidebook_icons/${button}`);
    });
    page.show(source).then(r => {
        if (r.canceled) return;
        if (source.hasTag('vtng_fn:configured_ui')) {
            if (r.selection == 0) configUiProfile(source);
            else guidebookButtonPage(source, guidebookButtons[r.selection-1]);
        } else guidebookButtonPage(source, guidebookButtons[r.selection]);
    });
};

function guidebookButtonPage(source, button) {
    const page = new ActionFormData();
    page.title(`vtng_fn.guidebook.${button}.title`);
    page.body(`vtng_fn.guidebook.${button}.text`);
    if (button == 'compatibility') page.button(`vtng_fn.guidebook.clear_cache.button`, 'textures/vtng/fn/ui/guidebook_icons/bin');
    page.button(`vtng_fn.guidebook.return`, 'textures/vtng/fn/ui/guidebook_icons/return');
    page.show(source).then(r => {
        if (r.canceled) return;
        if (button == 'compatibility') {
            if (r.selection == 0) {
                world.setDynamicProperty('vtng_fn:custom_recipes', undefined);
                world.setDynamicProperty('vtng_fn:without_recipes', undefined); 
                world.setDynamicProperty('vtng_fn:recipe_tests', undefined); 
                source.playSound('note.bell');
                source.sendMessage({ translate: 'vtng_fn.guidebook.clear_cache.text' });
            } else guidebookFirstPage(source);
        } else guidebookFirstPage(source);
    });
};