import { world, system, ItemStack, Entity } from "@minecraft/server";
import { ActionFormData } from '@minecraft/server-ui';


system.runInterval(() => {
    const initScore = world.scoreboard.getObjective("world").getScore("initialised");

    if (initScore < 150) {
        return;
    }
    for (const player of world.getAllPlayers()) {
        if (!player.hasTag(`pm_m8:char_selected`) && !player.hasTag(`pm_m8:is_selecting_char`)) {
            selectChar(player)
        }
    }
}, 40);


function selectChar(player) {
    const form = new ActionFormData()
        .title('Select Primary Ability')
        .body('')
        .button('Titan Eight', "textures/pm/m8/items/skill_[transformation]")
        // .button('Sword-Blaster Combination', "textures/pm/m8/items/sword-gun_hybrid") //alex
        // .button('Long Range Cannon', 'textures/pm/m8/items/long-range_cannon') //ethan
        .button('Dual Swords', 'textures/pm/m8/items/dual_swords') //logan
        .button('Axe', 'textures/pm/m8/items/axe'); //travis

    player.addTag(`pm_m8:is_selecting_char`)
    form.show(player).then(response => {
        if (response.canceled) {
            player.removeTag(`pm_m8:is_selecting_char`)
            return;
        }
            

        const selection = response.selection;
        if (selection === 0) {
            player.runCommand('give @s pm_m8:transformation 1 0 {"minecraft:item_lock":{ "mode": "lock_in_inventory" },"minecraft:keep_on_death":{}}');
            player.runCommand('function pm_m8/char/m8');
            player.addTag(`pm_m8:char_selected`);
            player.removeTag(`pm_m8:is_selecting_char`)
            player.addTag(`pm_m8:kafka`)
            player.addTag(`pm_m8:monster_8_selected`)
        } else if (selection === 1) {
            player.runCommand('function pm_m8/char/alex');
            player.addTag('pm_m8:alex_selected')
            player.addTag(`pm_m8:char_selected`)
            player.removeTag(`pm_m8:is_selecting_char`)
        } else if (selection === 2) {
            player.runCommand('function pm_m8/char/ethan');
            player.addTag(`pm_m8:ethan_selected`)
            player.addTag(`pm_m8:char_selected`)
            player.removeTag(`pm_m8:is_selecting_char`)
        } else if (selection === 3) {
            player.runCommand('function pm_m8/char/logan');
            player.addTag(`pm_m8:logan_selected`)
            player.addTag(`pm_m8:char_selected`)
            player.removeTag(`pm_m8:is_selecting_char`)
        } else if (selection === 4) {
            player.runCommand('function pm_m8/char/travis');
            player.addTag(`pm_m8:travis_selected`)
            player.addTag(`pm_m8:char_selected`)
            player.removeTag(`pm_m8:is_selecting_char`)
        }
    });
}
system.afterEvents.scriptEventReceive.subscribe((event) => {
    const { id, sourceEntity: player } = event;

    if (!player || player.typeId !== 'minecraft:player') return;

    if (id === 'pm_m8:riley_knox') {
        const entity = player.dimension.getEntities({
            location: player.location,
            minDistance: 0,
            maxDistance: 5,
            type: 'pm_m8:riley_knox'
        });
        rileyKnoxShopListForm(player, entity[0]?.id);
    }
});

/**
 * @typedef {Object} RequiredPair
 * @property {string} name
 * @property {number} quantity  
 */

/**
 * @typedef {Object} ShopItem
 * @property {string} name
 * @property {RequiredPair[]} requiredMaterials
 * @property {string} unlockTag
 * @property {string} giveItem
 */

/**
 * @type {ShopItem[]}
 */
const monster8Items = [
    {
        name: "Impact",
        icon: "textures/pm/m8/items/skill_[current_activation]",
        requiredMaterials: [
            { type: "pm_m8:pterosaur_wing", quantity: 1 },
            { type: "pm_m8:spider_silk", quantity: 1 }
        ],
        unlockTag: "current_activation_unlocked",
        giveItem: "pm_m8:jump_act"
    },
    {
        name: "Charged Punch",
        icon: "textures/pm/m8/items/skill_[charged_punch]",
        requiredMaterials: [
            { type: "pm_m8:energy_orb", quantity: 1 },
            { type: "pm_m8:ant_exoskeleton", quantity: 1 }
        ],
        unlockTag: "charged_punch_unlocked",
        giveItem: "pm_m8:charged_punch"
    },
    {
        name: "Movement Speed Boost",
        icon: "textures/pm/m8/items/skill_[movement_speed_boost]",
        requiredMaterials: [
            { type: "pm_m8:giant_mushroom_cap", quantity: 1 },
            { type: "pm_m8:mushroom_spores", quantity: 2 }
        ],
        unlockTag: "m8_movement_speed_boost",
        giveItem: "pm_m8:movement_speed_boost"
    },
    {
        name: "Jump Boost",
        icon: "textures/pm/m8/items/skill_[jump_boost]",
        requiredMaterials: [
            { type: "pm_m8:cyclone_feather", quantity: 1 },
            { type: "pm_m8:monster_core", quantity: 2 }
        ],
        unlockTag: "m8_jump_boost",
        giveItem: "pm_m8:jump_boost_monster8"
    },
    {
        name: "Uppercut",
        icon: "textures/pm/m8/items/skill_[knockback_enhancement]",
        requiredMaterials: [
            { type: "pm_m8:inferno_fragment", quantity: 1 },
            { type: "pm_m8:spider_silk", quantity: 2 }
        ],
        unlockTag: "m8_uppercut",
        giveItem: "pm_m8:ultimate"
    },
    {
        name: "Continuous Strike",
        icon: "textures/pm/m8/items/skill_[continuous_strike]",
        requiredMaterials: [
            { type: "pm_m8:pyroclasm_shard", quantity: 2 },
            { type: "pm_m8:special_monster_core", quantity: 1 },
            { type: "pm_m8:juggernaut_plate", quantity: 1 }
        ],
        unlockTag: "continuous_strike_unlocket",
        giveItem: "pm_m8:continuous_strike"
    }
];

/**
 * @type {ShopItem[]}
 */
const swordGunItems = [
    {
        name: "Sword-Blaster\nMode Switch",
        icon: "textures/pm/m8/items/sword-gun_hybrid",
        requiredMaterials: [
            { type: "pm_m8:monster_core", quantity: 1 },
            { type: "pm_m8:special_monster_core", quantity: 1 },
            { type: "pm_m8:pyroclasm_shard", quantity: 2 }
        ],
        unlockTag: "mode_switch",
        giveItem: "pm_m8:mode_switch"
    }
]

/**
 * @type {ShopItem[]}
 */
const combatUniformItems = [
    {
        name: "Strength",
        icon: "textures/pm/m8/items/strength",
        requiredMaterials: [
            { type: "pm_m8:pterosaur_wing", quantity: 1 },
            { type: "pm_m8:ant_exoskeleton", quantity: 1 },
            { type: "pm_m8:biological_essence", quantity: 2 }
        ],
        unlockTag: "cs_strength",
        giveItem: "pm_m8:strength"
    },
    {
        name: "Speed",
        icon: "textures/pm/m8/items/speed",
        requiredMaterials: [
            { type: "pm_m8:energy_orb", quantity: 1 },
            { type: "pm_m8:mushroom_spores", quantity: 2 },
            { type: "pm_m8:spider_silk", quantity: 1 }
        ],
        unlockTag: "cs_speed",
        giveItem: "pm_m8:speed"
    },
    {
        name: "Health Regeneration",
        icon: "textures/pm/m8/items/health_regenation",
        requiredMaterials: [
            { type: "pm_m8:giant_mushroom_cap", quantity: 1 },
            { type: "pm_m8:biological_essence", quantity: 1 },
            { type: "pm_m8:ant_exoskeleton", quantity: 2 }
        ],
        unlockTag: "cs_regeneration",
        giveItem: "pm_m8:regeneration"
    },
    {
        name: "Jump Boost",
        icon: "textures/pm/m8/items/jump_boost",
        requiredMaterials: [
            { type: "pm_m8:pterosaur_wing", quantity: 2 },
            { type: "pm_m8:mushroom_spores", quantity: 1 },
            { type: "pm_m8:spider_silk", quantity: 1 }
        ],
        unlockTag: "cs_jump_boost",
        giveItem: "pm_m8:jump_boost"
    },
    {
        name: "Sprint Collision",
        icon: "textures/pm/m8/items/sprint_collision",
        requiredMaterials: [
            { type: "pm_m8:juggernaut_plate", quantity: 1 },
            { type: "pm_m8:monster_core", quantity: 1 },
            { type: "pm_m8:energy_orb", quantity: 2 }
        ],
        unlockTag: "cs_sprint_collision",
        giveItem: "pm_m8:sprint_collision"
    }
];

/**
 * @type {ShopItem[]}
 */
const monster2Items = [
    {
        name: "Juggernaut Armor\nCharged Attack",
        icon: "textures/pm/m8/items/charged_attack",
        requiredMaterials: [
            { type: "pm_m8:juggernaut_plate", quantity: 2 },
            { type: "pm_m8:monster_core", quantity: 1 },
            { type: "pm_m8:special_monster_core", quantity: 1 }
        ],
        unlockTag: "cs_charged_attack",
        giveItem: "pm_m8:charged_attack"
    }
]

/**
 * @type {ShopItem[]}
 */
const monster4Items = [
    {
        name: "Cyclone Suit\nGlide",
        icon: "textures/pm/m8/items/glide",
        requiredMaterials: [
            { type: "pm_m8:cyclone_feather", quantity: 2 },
            { type: "pm_m8:monster_core", quantity: 1 },
            { type: "pm_m8:biological_essence", quantity: 1 }
        ],
        unlockTag: "cs_glide",
        giveItem: "pm_m8:glide"
    }
]

/**
 * @type {ShopItem[]}
 */
const monster6Items = [
    {
        name: "Inferno Exoskeleton\nFrost",
        icon: "textures/pm/m8/items/frost",
        requiredMaterials: [
            { type: "pm_m8:monster_core", quantity: 1 },
            { type: "pm_m8:inferno_fragment", quantity: 1 },
            { type: "pm_m8:energy_orb", quantity: 1 }
        ],
        unlockTag: "cs_frost",
        giveItem: "pm_m8:frost"
    }
]

/**
 * @type {ShopItem[]}
 */
const monster10Items = [
    {
        name: "Pyroclasm Armor\nBattle Hardened",
        icon: "textures/pm/m8/items/battle_hardened",
        requiredMaterials: [
            { type: "pm_m8:pyroclasm_shard", quantity: 2 },
            { type: "pm_m8:monster_core", quantity: 1 },
            { type: "pm_m8:special_monster_core", quantity: 1 }
        ],
        unlockTag: "cs_battle_hardened",
        giveItem: "pm_m8:battle_hardened"
    },
    {
        name: "Pyroclasm Armor\nMultiple Hits",
        icon: "textures/pm/m8/items/multiple_hits",
        requiredMaterials: [
            { type: "pm_m8:pyroclasm_shard", quantity: 2 },
            { type: "pm_m8:monster_core", quantity: 1 },
            { type: "pm_m8:energy_orb", quantity: 1 }
        ],
        unlockTag: "cs_multiple_hits",
        giveItem: "pm_m8:multiple_hits"
    }
]


/**
 * @type {ShopItem[]}
 */
const consumableItems = [
    {
        name: "Health Core x 1",
        icon: "textures/pm/m8/items/health_core",
        requiredMaterials: [
            { type: "pm_m8:monster_core", quantity: 1 }
        ],
        giveItem: "pm_m8:health_core",
        itemQuantity: 1
    },
    {
        name: "Health Core x 10",
        icon: "textures/pm/m8/items/health_core",
        requiredMaterials: [
            { type: "pm_m8:monster_core", quantity: 10 }
        ],
        giveItem: "pm_m8:health_core",
        itemQuantity: 10
    },
    {
        name: "Regenerative Essence x 1",
        icon: "textures/pm/m8/items/regenerative_essence",
        requiredMaterials: [
            { type: "pm_m8:biological_essence", quantity: 1 }
        ],
        giveItem: "pm_m8:regenerative_essence",
        itemQuantity: 1
    },
    {
        name: "Regenerative Essence x 10",
        icon: "textures/pm/m8/items/regenerative_essence",
        requiredMaterials: [
            { type: "pm_m8:biological_essence", quantity: 10 }
        ],
        giveItem: "pm_m8:regenerative_essence",
        itemQuantity: 10
    },
    
]

/**
 * @typedef {Object} ShopConfig
 * @property {string} name
 * @property {ShopItem[]} shopItems
 */

/**
 * @type {ShopConfig[]}
 */
const rileyKnoxShopList = [
    {
        name: "Consumables",
        shopItems: consumableItems
    },
    {
        name: "Titan Eight",
        shopItems: monster8Items
    },
    // {
    //     name: "Sword-Blaster Combination",
    //     shopItems: swordGunItems
    // },
    {
        name: "Combat Suits (Standard Upgrades)",
        shopItems: combatUniformItems
    },
    {
        name: "Juggernaut Armor",
        shopItems: monster2Items
    },
    {
        name: "Cyclone Suit",
        shopItems: monster4Items
    },
    {
        name: "Inferno Exoskeleton",
        shopItems: monster6Items
    },
    {
        name: "Pyroclasm Armor",
        shopItems: monster10Items
    },
    
]

/**
 * @typedef {Object} MissingMaterial
 * @property {string} type
 * @property {number} missing
 */

/**
 * 
 * @param {Entity} player 
 * @returns {MissingMaterial[]}
 */
function getMaterials(player, requiredMaterials) {
    const inventory = player.getComponent("inventory").container;
    const missingMaterials = [];

    requiredMaterials.forEach(material => {
        let materialCount = 0;
        for (let i = 0; i < inventory.size; i++) {
            const item = inventory.getItem(i);
            if (item && item.typeId === material.type) {
                materialCount += item.amount;
            }
        }
        if (materialCount < material.quantity) {
            /**
             * @type {MissingMaterial}
             */
            const newMissingMaterial = {
                type: material.type,
                missing: material.quantity - materialCount
            }
            missingMaterials.push(newMissingMaterial);
        }
    });

    return missingMaterials;
}

function removeMaterials(player, requiredMaterials) {
    const inventory = player.getComponent("inventory").container;

    requiredMaterials.forEach(material => {
        let remaining = material.quantity;

        for (let i = 0; i < inventory.size && remaining > 0; i++) {
            const item = inventory.getItem(i);
            if (item && item.typeId === material.type) {
                if (item.amount > remaining) {
                    item.amount -= remaining;
                    inventory.setItem(i, item);
                    remaining = 0;
                } else {
                    remaining -= item.amount;
                    inventory.setItem(i, null);
                }
            }
        }
    });
}


/**
 * 
 * @param {MissingMaterial[]} missingMaterials 
 */
function makeRawMessage(missingMaterials){
    /**
    * @type {import("@minecraft/server").RawMessage}
    */
    let newRawMessage = {
        rawtext: [
            {
                text: '§e[Shop] You are missing:\n'
            }
        ]
    }

    missingMaterials.forEach(ele => {
        /**
        * @type {import("@minecraft/server").RawMessage}
        */
        const newCountText = {
            text: " §c" + ele.missing + "x §r"
        };
        const newItemIdTransed = {
            translate: "item." + ele.type
        };
        const newLineBreak = {
            text: "\n"
        };
        newRawMessage.rawtext.push(newCountText);
        newRawMessage.rawtext.push(newItemIdTransed);
        newRawMessage.rawtext.push(newLineBreak);
    })

    return newRawMessage;
}

const idleDialogues = [
    "Power is endless, as long as you dare to pursue it.",
    "These ability upgrades will give you an edge in battle.",
    "We learn much more from monsters than you might think.",
    "Every upgrade is aimed at helping you protect humanity better.",
    "Combining science and power creates infinite possibilities.",
    "Anyone can eventually become a Titan Eight with the right training.",
];

/**
 * @param {Entity} player 
 * @param {ShopItem[]} items 
 * @param {string} category 
 */
function shopCategory(player, items, category, entity) {
    // Select a random dialogue
    const randomDialogue = idleDialogues[Math.floor(Math.random() * idleDialogues.length)];


    const form = new ActionFormData()
        .title(`ck.skill.${category} Shop`)
        .body(randomDialogue);

    form.button(entity);
    items.forEach((item) => {
        // For Consumables, do not show unlock status
        if (category === "Consumables") {
            form.button(`${item.name}`, item.icon || "ui/task_ui/skill_icon_holder");
        } else {
            if (player.hasTag(item.unlockTag)) {
                form.button(`${item.name}\n§e(Skill Unlocked)§r`, item.icon || "ui/task_ui/skill_icon_holder");
            } else {
                form.button(`${item.name}`, item.icon || "ui/task_ui/skill_icon_holder");
            }
        }
    });

    form.button('§cExit§r', "ui/task_ui/skill_icon_holder");

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

        const selection = response.selection - 1;
        if (selection === undefined) return;
        if (selection >= items.length) return;

        const selectedItem = items[selection];

        // For Consumables, skip unlock check
        if (category !== "Consumables" && player.hasTag(selectedItem.unlockTag)) {
            player.sendMessage(`§e[Shop] §b${selectedItem.name}§r is already unlocked!`);
            return;
        }

        const missingMaterials = getMaterials(player, selectedItem.requiredMaterials);

        if (missingMaterials.length > 0) {
            /**
             * @type {import("@minecraft/server").RawMessage}
             */
            const missingMaterialRawMessage = makeRawMessage(missingMaterials);
            player.sendMessage(missingMaterialRawMessage);
            
            return;
        }

        removeMaterials(player, selectedItem.requiredMaterials);

        if (selectedItem.giveItem) {
            // const newItem = new ItemStack(selectedItem.giveItem, 1);
            
            // player.getComponent("inventory").container.addItem(newItem);
            

            if (category !== "Consumables") {
                player.runCommand('give @s ' + selectedItem.giveItem + ' 1 0 {"minecraft:item_lock":{ "mode": "lock_in_inventory" },"minecraft:keep_on_death":{}}');
                player.runCommand("function pm_m8/unlock_skill");
                player.sendMessage(`§e[Shop] You have received: §b${selectedItem.name}§r!`);
            }
            else {
                player.runCommand(`give @s ${selectedItem.giveItem} ${selectedItem.itemQuantity} 0`);
                player.sendMessage(`§e[Shop] You have received: §b${selectedItem.name}§r!`);
            }
            
        } else {
            player.sendMessage(`§e[Shop] §b${selectedItem.name}§r skill is now unlocked!`);
            player.runCommand("function pm_m8/unlock_skill");
        }
        player.runCommand("function pm_m8/mission_npc/after_purchase");

        if (category !== "Consumables") {
            player.addTag(selectedItem.unlockTag);
        }
       
    });
}

/**
 * @param {Entity} player 
 */
function rileyKnoxShopListForm(player, entity) {

    // Select a random dialogue
    const randomDialogue = idleDialogues[Math.floor(Math.random() * idleDialogues.length)];

    const form = new ActionFormData()
        .title(`ck.skill.`)
        .body(randomDialogue);  // Set random dialogue as body text

    form.button(entity);
    rileyKnoxShopList.forEach((shop) => {
        form.button(shop.name, "ui/task_ui/skill_icon_holder")
    });
    form.button('§cExit§r', "ui/task_ui/skill_icon_holder");

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

        const selection = response.selection - 1;
        if (selection === undefined) return;
        if (selection >= rileyKnoxShopList.length) return;

        const shopConfig = rileyKnoxShopList[selection];
        shopCategory(player, shopConfig.shopItems, shopConfig.name, entity);
    });
}
