import { world, BlockPermutation, system, EntityInventoryComponent, EntityColorComponent, ItemStack, Player, InputPermissionCategory, Entity, ContainerSlot, EntityIsTamedComponent, EntityHealthComponent, EntityItemComponent, EntityEquippableComponent, EquipmentSlot, WeatherType, MoonPhase, GameMode } from '@minecraft/server';
import { MessageFormData, FormRejectError, FormCancelationReason, ActionFormData, ModalFormData } from '@minecraft/server-ui';

// Based off https://stackoverflow.com/a/1349426/688379
const RANDOM_ID_CHARACTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const makeRandomId = (length = 16) => {
    return [...new Array(length)].map(() => RANDOM_ID_CHARACTERS.charAt(Math.floor(Math.random() * RANDOM_ID_CHARACTERS.length))).join('');
};
const makeRandomNumber = (min, max) => {
    return min + Math.floor(Math.random() * (max - min + 1));
};
const makeRandomNumberDecimal = (min, max) => {
    return min + Math.random() * (max - min + 1);
};

const TRANSLATE$1 = (key, ...params) => ({
    translate: key,
    with: params.length > 0 ? typeof params[0] === 'string' ? params : RAW_TEXT(...params) : undefined
});
const RAW_TEXT = (...rawText) => ({
    rawtext: rawText
});
const TEXT = (value) => ({
    text: value.toString()
});
const TEXT_OR_RAW_TEXT = (value) => {
    if (typeof value === 'string' || typeof value === 'number') {
        return TEXT(value);
    }
    return value;
};
const ITEM = (item) => {
    let key = item.typeId;
    let addName = false;
    if (item.hasComponent("display_name")) {
        addName = true;
    }
    // Removes minecraft prefix if found.
    if (key.startsWith("minecraft:")) {
        addName = true;
        key = key.substring("minecraft:".length);
    }
    // Moves spawn_egg postfix if found
    if (key.endsWith("_spawn_egg")) {
        addName = true;
        key = `spawn_egg.entity.${key.replace("_spawn_egg", "")}`;
    }
    let isBlock;
    try {
        BlockPermutation.resolve(item.typeId);
        isBlock = true;
        addName = true;
    }
    catch (e) {
        isBlock = false;
    }
    if (addName) {
        key = `${key}.name`;
    }
    if (isBlock) {
        key = `tile.${key}`;
    }
    else {
        key = `item.${key}`;
    }
    return TRANSLATE$1(key);
};
const ENTITY = (entity) => {
    let key = entity;
    if (key.startsWith("minecraft:")) {
        key = `entity.${key.substring("minecraft:".length)}.name`;
    }
    else {
        key = `entity.${key}.name`;
    }
    return TRANSLATE$1(key);
};
// export const blockTypeToString = (blockType: string | BlockType) => typeof blockType === 'string' ? blockType : blockType.id;
const debug = (what, segment) => {
    let tag = 'debug';
    if (segment) {
        tag += `-${segment}`;
    }
    const players = world.getPlayers({
        tags: [tag]
    });
    if (players.length > 0) {
        const text = typeof what === 'string' ? what : what();
        for (const player of players) {
            void player.dimension.runCommandAsync(`w ${player.name} ${tag}: ${text}`);
        }
    }
};
const getDistance = (start, end) => {
    let x1 = start.x;
    let y1 = start.y;
    let z1 = start.z;
    let x2 = end.x;
    let y2 = end.y;
    let z2 = end.z;
    return Math.ceil(Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2) + Math.pow(z2 - z1, 2)));
};
const getHorDistance = (start, end) => {
    let x1 = start.x;
    start.y;
    let z1 = start.z;
    let x2 = end.x;
    end.y;
    let z2 = end.z;
    return Math.ceil(Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(z2 - z1, 2)));
};
const getVerDistance = (start, end) => {
    start.x;
    let y1 = start.y;
    start.z;
    end.x;
    let y2 = end.y;
    end.z;
    return Math.ceil(y1 - y2 + 1);
};
const getDirection = (start, end) => {
    const xDiff = end.x - start.x;
    const yDiff = end.y - start.y;
    const zDiff = start.z - end.z;
    const isSouth = isFarAwayInDirection(zDiff);
    const isWest = isFarAwayInDirection(xDiff);
    const isAbove = isFarAwayInDirection(yDiff);
    const where = [];
    if (isSouth === undefined && isWest === undefined && isAbove === undefined) {
        return [0 /* Direction.NEXT_TO_YOU */];
    }
    if (isSouth) {
        where.push(1 /* Direction.NORTH */);
    }
    else if (isSouth === false) {
        where.push(2 /* Direction.SOUTH */);
    }
    if (isWest) {
        where.push(4 /* Direction.EAST */);
    }
    else if (isWest === false) {
        where.push(3 /* Direction.WEST */);
    }
    if (isAbove) {
        where.push(5 /* Direction.ABOVE */);
    }
    else if (isAbove === false) {
        where.push(6 /* Direction.BELOW */);
    }
    return where;
};
const isFarAwayInDirection = (diff) => {
    const howFar = 3;
    if (Math.abs(diff) > howFar) {
        return diff > 0;
    }
    // Means that is next to us in the direction
    return undefined;
};

const getEmptySlot = (container) => {
    for (let i = 0; i < container.size; ++i) {
        if (container.getItem(i) === undefined) {
            return i;
        }
    }
    return undefined;
};
const getSlotByCondition = (container, condition) => {
    for (let i = 0; i < container.size; ++i) {
        const item = container.getItem(i);
        if (item && condition(item)) {
            return i;
        }
    }
    return undefined;
};

const PROP = (...identifier) => `jig_ccomp:${identifier.join(':')}`;
const GET_RAW_PROP = (target, identifier) => {
    return target.getDynamicProperty(identifier);
};
const SET_RAW_PROP = (target, identifier, value) => {
    target.setDynamicProperty(identifier, value);
};
const GET_PROP$1 = (target, identifier, defaultValue) => {
    const value = target.getDynamicProperty(identifier);
    if (typeof value === 'string') {
        return JSON.parse(value);
    }
    if (defaultValue) {
        return defaultValue;
    }
    const message = `Invalid identifier ${identifier}`;
    debug(message);
    throw new Error(message);
};
const SET_PROP$1 = (target, identifier, value) => {
    target.setDynamicProperty(identifier, JSON.stringify(value));
};
// export const mutateDynamicProperty = <T>(target: WithDynamicProperty, identifier: string, mutator: DynamicPropertyMutator<T>) => {
//   const input = target.getDynamicProperty(identifier);
//   const output = mutator(typeof input === 'string' ? JSON.parse(input) : undefined);
//   target.setDynamicProperty(identifier, JSON.stringify(output));
// }
//
// export class DynamicPropertyContext<T> {
//   private _value: T;
//   private target: WithDynamicProperty;
//   private identifier: string;
//
//   constructor(target: WithDynamicProperty, identifier: string, defaultValue: T) {
//     this.target = target;
//     this.identifier = identifier;
//     const value = target.getDynamicProperty(identifier);
//     this._value = typeof value === 'string' ? JSON.parse(value) : undefined;
//   }
//
//   public get value() {
//     return this._value;
//   }
//
//   private set value(value: T) {
//     this._value = value;
//   }
//
//   mutate(mutator: DynamicPropertyMutator<T>) {
//     this.value = mutator(this.value);
//   }
//
//   commit() {
//     this.target.setDynamicProperty(this.identifier, JSON.stringify(this.value));
//   }
// }

// Add operations that we need to do over entities, but entities might not be loaded/online.
// Delay the operations for later.
const FUTURE_OPERATION_ID = 'jig_ccomp:future-operation';
const NO_OPERATION_ID = -1;
const scheduleOperation = (entity, operationRequest) => {
    const time = system.currentTick + operationRequest.timeFromNow;
    const operation = {
        id: makeRandomId(),
        operation: operationRequest.operation,
        params: operationRequest.params,
        timerId: NO_OPERATION_ID,
        time
    };
    operation.timerId = system.runTimeout(() => runOperation(entity, operation), operationRequest.timeFromNow);
    addOperation(entity, operation);
};
const cancelOperations = (entity) => {
    SET_PROP$1(entity, FUTURE_OPERATION_ID, getOperations(entity).map(operation => {
        if (operation.timerId !== NO_OPERATION_ID) {
            system.clearRun(operation.timerId);
        }
        operation.timerId = NO_OPERATION_ID;
        return operation;
    }));
};
const runPendingOperations = (entity) => {
    const operations = getOperations(entity).map(operation => {
        if (operation.timerId !== NO_OPERATION_ID) {
            system.clearRun(operation.timerId);
        }
        operation.timerId = system.runTimeout(() => runOperation(entity, operation), Math.max(1, operation.time - system.currentTick));
        return operation;
    });
    entity.setDynamicProperty(FUTURE_OPERATION_ID, JSON.stringify(operations));
};
const runOperation = async (entity, operation) => {
    if (entity.isValid()) {
        switch (operation.operation) {
            case "send-email-mob" /* FutureOperationType.COMPUTER_SEND_EMAIL_FROM_MOB */:
                const { operationSendEmailFromMob } = await Promise.resolve().then(function () { return Email; });
                operationSendEmailFromMob(entity, operation.params);
                break;
            case "enable-npc" /* FutureOperationType.PLAYER_ENABLE_NPC */:
                const { operationEnableNpc } = await Promise.resolve().then(function () { return Email; });
                operationEnableNpc(entity, operation.params);
                break;
        }
        removeOperation(entity, operation);
    }
};
const getOperations = (entity) => {
    return JSON.parse(entity.getDynamicProperty(FUTURE_OPERATION_ID) ?? '[]');
};
const addOperation = (entity, ...operation) => {
    const operations = getOperations(entity);
    operations.push(...operation);
    entity.setDynamicProperty(FUTURE_OPERATION_ID, JSON.stringify(operations));
};
const removeOperation = (entity, operation) => {
    const operations = getOperations(entity);
    entity.setDynamicProperty(FUTURE_OPERATION_ID, JSON.stringify(operations.filter(o => o.id !== operation.id)));
};

const arrayFromLength = (length) => {
    return [...Array(length)].map((_, index) => index);
};

const NUMBERED_ENTITY_COUNT = 16;
const VALID_COMPUTERS_TYPES = [
    "jig_ccomp:computer_old",
    "jig_ccomp:computer_old_c",
    "jig_ccomp:computer_ok",
    "jig_ccomp:computer_ok_c",
    "jig_ccomp:computer_good",
    "jig_ccomp:computer_good_c",
    "jig_ccomp:computer_great",
    "jig_ccomp:computer_great_c",
    "jig_ccomp:computer_lap",
    "jig_ccomp:computer_lap_b",
];
const COLORED_COMPUTERS = [
    'jig_ccomp:computer_old_c',
    'jig_ccomp:computer_ok_c',
    'jig_ccomp:computer_good_c',
    'jig_ccomp:computer_great_c',
    'jig_ccomp:computer_lap'
];
const getAllValidItemTypes = () => {
    return VALID_COMPUTERS_TYPES.flatMap(type => {
        if (COLORED_COMPUTERS.includes(type)) {
            // For every index in [0, NUMBERED_ENTITY_COUNT - 1]
            return arrayFromLength(NUMBERED_ENTITY_COUNT).map((i) => `${type}${i}_item`);
        }
        else {
            return [`${type}_item`];
        }
    });
};
const initComputers = () => {
    world.beforeEvents.itemUseOn.subscribe((event) => {
        const isInteractable = event.block.typeId === 'minecraft:frame' || event.block.typeId === 'minecraft:glow_frame' || event.block.typeId === 'minecraft:chest' || event.block.typeId === 'minecraft:trapped_chest' || event.block.typeId === 'minecraft:ender_chest';
        if (!isInteractable) {
            const validItemTypes = getAllValidItemTypes();
            if (validItemTypes.includes(event.itemStack.typeId)) {
                event.cancel = true;
                system.runTimeout(() => {
                    const targetLocation = {
                        x: event.block.location.x + event.faceLocation.x,
                        y: event.block.location.y + event.faceLocation.y,
                        z: event.block.location.z + event.faceLocation.z,
                    };
                    const extractNumber = (typeId) => {
                        const match = typeId.match(/(\d+)_item$/);
                        return match ? match[1] : "";
                    };
                    const stripItemSuffixAndNumber = (typeId) => {
                        // Regular expression to match the "_item" suffix and any trailing digits
                        return typeId.replace(/(\d+)?_item$/, "");
                    };
                    const computer = event.block.dimension.spawnEntity(stripItemSuffixAndNumber(event.itemStack.typeId), targetLocation);
                    computer.setRotation({
                        x: computer.getRotation().x,
                        y: (event.source.getRotation().y + 180) % 360,
                    });
                    const number = extractNumber(event.itemStack.typeId);
                    if (number !== undefined && number !== "") {
                        computer.runCommand(`event entity @s jig_ccomp:color_${number}`);
                    }
                    // Hydrating a computer
                    if (event.itemStack.getLore().length === 2) {
                        const computerId = event.itemStack.getLore()[1];
                        computer.setDynamicProperty("jig_ccomp:COMPUTER_ID", computerId);
                        if (GET_RAW_PROP(world, IDENTIFIER_NAME(computerId)) === undefined) {
                            // We lost the data. The computer has an id but not a name in the system.
                            // Mark as lost data and set the name from the lore
                            SET_RAW_PROP(world, IDENTIFIER_LOST_DATA(computerId), true);
                            SET_RAW_PROP(world, IDENTIFIER_NAME(computerId), event.itemStack.getLore()[0]);
                        }
                        SET_RAW_PROP(world, IDENTIFIER_CREATOR(computerId), event.source.name);
                        // No longer an item
                        SET_RAW_PROP(world, IDENTIFIER_ITEMIZED_ON(computerId), undefined);
                        if (GET_RAW_PROP(world, IDENTIFIER_TRIGGER_EMAIL_NOTIFICATION(computerId))) {
                            computer.triggerEvent("jig_ccomp:got_email");
                            SET_RAW_PROP(world, IDENTIFIER_TRIGGER_EMAIL_NOTIFICATION(computerId), undefined);
                        }
                        // Hydrate operations
                        addOperation(computer, ...GET_PROP$1(world, IDENTIFIER_SAVED_OPERATIONS(computerId), []));
                        SET_RAW_PROP(world, IDENTIFIER_SAVED_OPERATIONS(computerId), undefined);
                        runPendingOperations(computer);
                        const settingsValues = GET_PROP$1(world, IDENTIFIER_SETTINGS(computerId), { mute_startup: false, mute_shutdown: false, mute_notification: false, mute_typing_sound: false, mute_typing_animation: false, email_notification: false, hide_tower: false });
                        if (settingsValues.mute_startup) {
                            computer.addTag("jig_ccomp.mute_startup");
                        }
                        else {
                            computer.removeTag("jig_ccomp.mute_startup");
                        }
                        if (settingsValues.mute_shutdown) {
                            computer.addTag("jig_ccomp.mute_shutdown");
                        }
                        else {
                            computer.removeTag("jig_ccomp.mute_shutdown");
                        }
                        if (settingsValues.mute_notification) {
                            computer.addTag("jig_ccomp.mute_notification");
                        }
                        else {
                            computer.removeTag("jig_ccomp.mute_notification");
                        }
                        if (settingsValues.mute_typing_sound) {
                            computer.addTag("jig_ccomp.mute_typing_sound");
                        }
                        else {
                            computer.removeTag("jig_ccomp.mute_typing_sound");
                        }
                        if (settingsValues.mute_typing_animation) {
                            computer.setProperty("jig_ccomp:mute_keyboard_jiggle", true);
                        }
                        else {
                            computer.setProperty("jig_ccomp:mute_keyboard_jiggle", false);
                        }
                        if (settingsValues.email_notification) {
                            computer.setProperty("jig_ccomp:got_email", true);
                        }
                        else {
                            computer.setProperty("jig_ccomp:got_email", false);
                        }
                        if (settingsValues.hide_tower) {
                            computer.setProperty("jig_ccomp:hide_tower", true);
                        }
                        else {
                            computer.setProperty("jig_ccomp:hide_tower", false);
                        }
                        const inventory = event.source.getComponent(EntityInventoryComponent.componentId);
                        if (inventory.container) {
                            for (let i = 0; i < inventory.container.size; ++i) {
                                const item = inventory.container.getItem(i);
                                if (item?.typeId === event.itemStack.typeId &&
                                    item.getLore().length === 2 &&
                                    item.getLore()[1] === computerId) {
                                    inventory.container.setItem(i);
                                    break;
                                }
                            }
                        }
                    }
                    else {
                        // New computer
                        new CraftComputer(computer).setCreator(event.source.name);
                        const inventory = event.source.getComponent(EntityInventoryComponent.componentId);
                        if (inventory.container) {
                            for (let i = 0; i < inventory.container.size; ++i) {
                                const item = inventory.container.getItem(i);
                                if (item?.typeId === event.itemStack.typeId && item.getLore().length === 0) {
                                    // decrease one or remove if only one
                                    if (item.amount >= 2) {
                                        item.amount -= 1;
                                        inventory.container.setItem(i, item);
                                    }
                                    else {
                                        inventory.container.setItem(i);
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }, 1);
            }
        }
    });
    world.afterEvents.entityDie.subscribe((event) => {
        ////_______________
        if (CraftComputer.isComputer(event.deadEntity)) {
            const computer = new CraftComputer(event.deadEntity);
            let colortostring = ``;
            if (event.deadEntity.hasComponent(EntityColorComponent.componentId)) {
                const colorComponent = event.deadEntity.getComponent(EntityColorComponent.componentId);
                //debug(`color ${colorComponent.value}`);
                colortostring = `${colorComponent.value}`;
                if (colortostring === undefined) {
                    colortostring = ``;
                }
            }
            const computerItem = new ItemStack(computer.computer.typeId + colortostring + "_item", 1);
            computerItem.setLore([computer.getName(), computer.computerId]);
            const dimension = computer.computer.dimension;
            const location = computer.computer.location;
            dimension.spawnItem(computerItem, location);
            const container = computer.computer.getComponent(EntityInventoryComponent.componentId).container;
            for (let i = 0; i < container.size; i++) {
                const item = container.getItem(i);
                if (item) {
                    dimension.spawnItem(item, location);
                }
            }
            // Mark attachments as downloaded
            computer.setEmails(computer.getEmails().map((e) => {
                if (e.attachment !== undefined && e.attachment >= 0) {
                    e.attachment = -1;
                }
                return e;
            }));
            // Cancel & save future operations
            cancelOperations(computer.computer);
            const operations = getOperations(computer.computer);
            SET_PROP$1(world, IDENTIFIER_SAVED_OPERATIONS(computer.computerId), operations);
            SET_PROP$1(world, IDENTIFIER_ITEMIZED_ON(computer.computerId), world.getDay());
            let settings = {
                mute_startup: computer.computer.hasTag("jig_ccomp.mute_startup") || false,
                mute_shutdown: computer.computer.hasTag("jig_ccomp.mute_shutdown") || false,
                mute_notification: computer.computer.hasTag("jig_ccomp.mute_notification") || false,
                mute_typing_sound: computer.computer.hasTag("jig_ccomp.mute_typing_sound") || false,
                mute_typing_animation: computer.computer.getProperty("jig_ccomp:mute_keyboard_jiggle") || false,
                email_notification: computer.computer.getProperty("jig_ccomp:got_email") || false,
                hide_tower: computer.computer.getProperty("jig_ccomp:hide_tower") || false,
            };
            SET_PROP$1(world, IDENTIFIER_SETTINGS(computer.computerId), settings);
        }
    });
    // Vacuum at startup and then every 24 hours
    craftComputers.vacuumOldComputers();
    system.runInterval(() => {
        craftComputers.vacuumOldComputers();
    }, 20 * 60 * 60 * 24);
};
const findBlocked = (senderType, blockType, id) => (blocked) => {
    return blocked.sender_type === senderType && blocked.block_type === blockType && blocked.data.id === id;
};
const isPlayerBlocked = (playerType, player, blocks) => {
    return !!blocks.find((b) => {
        if (b.sender_type === playerType) {
            if (b.block_type === "player") {
                if (b.data.id === player) {
                    return true;
                }
            }
        }
        return false;
    });
};
const evaluateBlocks = (blocks, email) => {
    return !!blocks.find((b) => {
        if (b.sender_type === email.sender_type) {
            if (b.block_type === "computer") {
                if (b.data.id === email.from_computer_id) {
                    return true;
                }
            }
            else if (b.block_type === "player") {
                if (b.data.id === email.from_player_id) {
                    return true;
                }
            }
            return false;
        }
    });
};
const COMPUTER_VERSION = 2;
const COMPUTER_PREFIX = "COMP";
const ITEMIZED_ON = "ITEMIZED_ON";
const IDENTIFIER_NAME = (computerId) => PROP(COMPUTER_PREFIX, computerId, "NAME");
const IDENTIFIER_VERSION = (computerId) => PROP(COMPUTER_PREFIX, computerId, "VERSION");
const IDENTIFIER_CREATOR = (computerId) => PROP(COMPUTER_PREFIX, computerId, "CREATOR");
const IDENTIFIER_EMAILS = (computerId) => PROP(COMPUTER_PREFIX, computerId, "EMAILS");
const IDENTIFIER_BLOCKS = (computerId) => PROP(COMPUTER_PREFIX, computerId, "EMAIL_BLOCKS");
const IDENTIFIER_WELCOME_SENT = (computerId) => PROP(COMPUTER_PREFIX, computerId, "WELCOME_SENT");
const IDENTIFIER_ITEMIZED_ON = (computerId) => PROP(COMPUTER_PREFIX, computerId, ITEMIZED_ON);
const IDENTIFIER_LOST_DATA = (computerId) => PROP(COMPUTER_PREFIX, computerId, "LOST_DATA");
const IDENTIFIER_SETTINGS = (computerId) => PROP(COMPUTER_PREFIX, computerId, "SETTINGS");
const IDENTIFIER_SAVED_OPERATIONS = (computerId) => PROP(COMPUTER_PREFIX, computerId, "SAVED_OPERATIONS");
const IDENTIFIER_TRIGGER_EMAIL_NOTIFICATION = (computerId) => PROP(COMPUTER_PREFIX, computerId, "TRIGGER_EMAIL_NOTIFICATION");
class CraftComputer {
    computer;
    computerId;
    static isComputer(maybeComputer) {
        return VALID_COMPUTERS_TYPES.includes(maybeComputer.typeId);
    }
    constructor(entity) {
        if (!CraftComputer.isComputer(entity)) {
            throw new Error("Not a computer");
        }
        this.computer = entity;
        this.computerId = this.fetchInternalId();
        this.upgradeFromVersion1();
        const version = this.getVersion();
        if (version < COMPUTER_VERSION) {
            const name = () => {
                if (this.computer.typeId === "jig_ccomp:computer_old") {
                    return `Old JX${makeRandomNumber(100, 999)}`;
                }
                else if (this.computer.typeId == "jig_ccomp:computer_old_c") {
                    return `Old JX${makeRandomNumber(100, 999)}`;
                }
                else if (this.computer.typeId == "jig_ccomp:computer_lap") {
                    return `LAP U${makeRandomNumber(100, 999)}`;
                }
                else if (this.computer.typeId == "jig_ccomp:computer_lap_b") {
                    return `LAP U${makeRandomNumber(100, 999)}`;
                }
                else if (this.computer.typeId == "jig_ccomp:computer_ok") {
                    return `OK JTX${makeRandomNumber(1000, 4000)}`;
                }
                else if (this.computer.typeId == "jig_ccomp:computer_ok_c") {
                    return `OK JTX${makeRandomNumber(1000, 4000)}`;
                }
                else if (this.computer.typeId == "jig_ccomp:computer_good") {
                    return `RGB JigForce${makeRandomNumber(5000, 9999)}`;
                }
                else if (this.computer.typeId == "jig_ccomp:computer_good_c") {
                    return `RGB JigForce${makeRandomNumber(5000, 9999)}`;
                }
                else if (this.computer.typeId == "jig_ccomp:computer_great") {
                    return `JigMD${makeRandomNumber(5000, 9999)}`;
                }
                else if (this.computer.typeId == "jig_ccomp:computer_great_c") {
                    return `JigMD${makeRandomNumber(5000, 9999)}`;
                }
                return this.computerId;
            };
            switch (version) {
                case 0:
                    this.setName(name());
            }
            this.setVersion(COMPUTER_VERSION);
        }
    }
    fetchInternalId() {
        const computerId = GET_RAW_PROP(this.computer, "jig_ccomp:COMPUTER_ID" /* COMPUTER_PROPERTIES.COMPUTER_ID */);
        if (typeof computerId !== "string") {
            const newId = makeRandomId();
            SET_RAW_PROP(this.computer, "jig_ccomp:COMPUTER_ID" /* COMPUTER_PROPERTIES.COMPUTER_ID */, newId);
            return newId;
        }
        return computerId;
    }
    upgradeFromVersion1() {
        const V1_COMPUTER_NAME = "jig_ccomp:COMPUTER_NAME";
        const V1_EMAILS = "jig_ccomp:EMAILS";
        const V1_EMAIL_BLOCKS = "jig_ccomp:EMAIL_BLOCKS";
        const oldComputerName = this.computer.getDynamicProperty(V1_COMPUTER_NAME);
        if (oldComputerName !== undefined) {
            // Found a computer with name, it must be a v1 computer entity, upgrading...
            this.setName(oldComputerName);
            this.setEmails(JSON.parse(this.computer.getDynamicProperty(V1_EMAILS) ?? "[]"));
            this.setEmailBlocks(JSON.parse(this.computer.getDynamicProperty(V1_EMAIL_BLOCKS) ?? "[]"));
            this.setWelcomeSent(true);
            this.computer.setDynamicProperty(V1_COMPUTER_NAME, undefined);
            this.computer.setDynamicProperty(V1_EMAILS, undefined);
            this.computer.setDynamicProperty(V1_EMAIL_BLOCKS, undefined);
            this.setVersion(2);
        }
    }
    getId() {
        return this.computerId;
    }
    getName() {
        return GET_RAW_PROP(world, IDENTIFIER_NAME(this.computerId));
    }
    setName(name) {
        SET_RAW_PROP(world, IDENTIFIER_NAME(this.computerId), name);
    }
    getVersion() {
        return GET_RAW_PROP(world, IDENTIFIER_VERSION(this.computerId)) ?? 0;
    }
    setVersion(version) {
        SET_RAW_PROP(world, IDENTIFIER_VERSION(this.computerId), version);
    }
    getCreator() {
        return GET_RAW_PROP(world, IDENTIFIER_CREATOR(this.computerId));
    }
    setCreator(creator) {
        SET_RAW_PROP(world, IDENTIFIER_CREATOR(this.computerId), creator);
    }
    getWelcomeSent() {
        return !!GET_RAW_PROP(world, IDENTIFIER_WELCOME_SENT(this.computerId));
    }
    setWelcomeSent(welcomeSent) {
        SET_RAW_PROP(world, IDENTIFIER_WELCOME_SENT(this.computerId), welcomeSent);
    }
    getLostData() {
        return GET_RAW_PROP(world, IDENTIFIER_LOST_DATA(this.computerId)) ?? 0;
    }
    getEmails() {
        return GET_PROP$1(world, IDENTIFIER_EMAILS(this.computerId), []);
    }
    setEmails(emails) {
        SET_PROP$1(world, IDENTIFIER_EMAILS(this.computerId), emails);
    }
    getEmailBlocks() {
        return GET_PROP$1(world, IDENTIFIER_BLOCKS(this.computerId), []);
    }
    setEmailBlocks(emailBlocks) {
        SET_PROP$1(world, IDENTIFIER_BLOCKS(this.computerId), emailBlocks);
    }
    addBlock(emailBlock) {
        if (!this.isBlocked(emailBlock.sender_type, emailBlock.block_type, emailBlock.data.id)) {
            const blocks = this.getEmailBlocks();
            blocks.push(emailBlock);
            this.setEmailBlocks(blocks);
        }
    }
    getBlocked(senderType, blockType, id) {
        const blocks = this.getEmailBlocks();
        return blocks.find(findBlocked(senderType, blockType, id));
    }
    isBlocked(senderType, blockType, id) {
        return !!this.getBlocked(senderType, blockType, id);
    }
    addPlayerBlock(email) {
        this.addBlock({
            id: makeRandomId(),
            sender_type: email.sender_type,
            block_type: "player",
            data: {
                id: email.from_player_id,
                name: TEXT_OR_RAW_TEXT(email.from_player),
            },
        });
    }
    removePlayerBlock(email) {
        this.removeBlockByEmail(email, "player");
    }
    removeComputerBlock(email) {
        this.removeBlockByEmail(email, "computer");
    }
    removeBlockByEmail(email, blockType) {
        const blocks = this.getEmailBlocks();
        blocks.filter((block) => {
            return (block.sender_type !== email.sender_type &&
                block.block_type !== blockType &&
                block.data.id !== email.from_player_id);
        });
        this.setEmailBlocks(blocks);
    }
    addComputerBlock(email) {
        this.addBlock({
            id: makeRandomId(),
            sender_type: email.sender_type,
            block_type: "computer",
            data: {
                id: email.from_computer_id,
                name: TEXT_OR_RAW_TEXT(email.from_computer_name),
            },
        });
    }
    removeBlock(blockId) {
        const blocks = this.getEmailBlocks();
        this.setEmailBlocks(blocks.filter((b) => blockId !== b.id));
    }
    addEmail(email, attachment, forceSend = false) {
        const blocks = this.getEmailBlocks();
        const blockFound = evaluateBlocks(blocks, email);
        if (blockFound) {
            //debug(`Computer blocked email from: ${typeof email.from_player === 'string' ? email.from_player : email.from_player_id} to computer ${email.from_computer_name} was blocked`);
            return "blocked";
        }
        if (attachment) {
            const inventory = this.computer.getComponent(EntityInventoryComponent.componentId);
            if (inventory.container) {
                const container = inventory.container;
                const emptySlot = getEmptySlot(container);
                if (emptySlot !== undefined) {
                    if (attachment.container && attachment.index !== undefined) {
                        attachment.container.setItem(attachment.index);
                    }
                    container.setItem(emptySlot, attachment.item);
                    email.attachment = emptySlot;
                }
                else {
                    if (!forceSend) {
                        return false;
                    }
                }
            }
        }
        this.setEmails([
            ...this.getEmails(),
            {
                ...email,
                id: makeRandomId(),
            },
        ]);
        this.computer.triggerEvent("jig_ccomp:got_email");
        return true;
    }
    downloadAttachment(emailId, player) {
        // Todo: this is simpler in later versions
        const playerContainer = player.getComponent(EntityInventoryComponent.componentId)
            ?.container;
        const computerContainer = this.computer.getComponent(EntityInventoryComponent.componentId)?.container;
        const emails = this.getEmails();
        const email = emails.find((e) => e.id === emailId);
        if (email.attachment !== undefined && email.attachment >= 0 && playerContainer && computerContainer) {
            const emptySlot = getEmptySlot(playerContainer);
            if (emptySlot !== undefined) {
                const item = computerContainer.getItem(email.attachment);
                computerContainer.setItem(email.attachment);
                playerContainer.setItem(emptySlot, item);
                email.attachment = -1;
                this.setEmails(emails);
                //player.runCommand('/say you got'+test)
                player.runCommand("/playsound jig_common.suckpop");
                this.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_emdo`);
                this.computer.triggerEvent("jig_ccomp:typing");
            }
            else {
                this.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_at_emdo`);
                this.computer.triggerEvent("jig_ccomp:typing");
            }
        }
        return false;
    }
    deleteEmail(emailId) {
        const computerContainer = this.computer.getComponent(EntityInventoryComponent.componentId)?.container;
        const emails = this.getEmails();
        const emailIndex = emails.findIndex((e) => e.id === emailId);
        const email = emails[emailIndex];
        if (email.attachment !== undefined && email.attachment >= 0 && computerContainer) {
            computerContainer.setItem(email.attachment);
        }
        emails.splice(emailIndex, 1);
        this.setEmails(emails);
    }
    markAsRead(emailId) {
        const emails = this.getEmails();
        const email = emails.find((e) => e.id === emailId);
        email.isRead = true;
        this.setEmails(emails);
    }
    getEmailById(emailId) {
        const emails = this.getEmails();
        return emails.find((e) => e.id === emailId);
    }
    say(message, player) {
        void this.computer.runCommandAsync(`w ${player.name} ${message}`);
    }
    getProp(property, defaultValue) {
        return this.computer.getDynamicProperty(property) ?? defaultValue;
    }
    setProp(property, value) {
        this.computer.setDynamicProperty(property, value);
    }
}
class CraftComputers {
    computers = {};
    dimensions = [];
    init(dimension) {
        if (this.dimensions.includes(dimension)) {
            return;
        }
        this.dimensions.push(dimension);
        for (const computerType of VALID_COMPUTERS_TYPES) {
            dimension
                .getEntities({
                type: computerType,
            })
                .forEach((computer) => {
                this.addComputer(computer);
            });
        }
    }
    addComputer(entity) {
        if (!CraftComputer.isComputer(entity)) {
            return;
        }
        const computer = new CraftComputer(entity);
        this.computers[computer.getId()] = computer;
    }
    removeComputer(entity) {
        if (!CraftComputer.isComputer(entity)) {
            return;
        }
        if (entity.isValid()) {
            const computer = new CraftComputer(entity);
            const computerId = computer.getId();
            delete this.computers[computerId];
        }
    }
    getComputers() {
        return Object.values(this.computers).filter((c) => c.computer.isValid());
    }
    getComputer(id) {
        if (id in this.computers && this.computers[id].computer.isValid()) {
            return this.computers[id];
        }
        return undefined;
    }
    isComputerAvailable(id) {
        if (id in this.computers && this.computers[id].computer.isValid()) {
            return true;
        }
        const reachableComputers = craftComputers.getReachableStoredComputerRecipients();
        if (reachableComputers.find((c) => c.id === id)) {
            return true;
        }
        return false;
    }
    getUnlockedNpcs() {
        return new Set(this.getComputers().flatMap((c) => {
            return c
                .getEmails()
                .filter((e) => e.sender_type === "npc")
                .map((e) => e.from_player_id);
        }));
    }
    broadcastEmail(email) {
        const attachment = email.attachment
            ? {
                item: new ItemStack(email.attachment, email.attachmentCount ?? 1),
            }
            : undefined;
        this.getComputers()
            .filter((c) => filterComputer(c, email.filter))
            .forEach((c) => {
            c.addEmail({
                sender_type: "script",
                from_player_id: email.addon,
                from_computer_id: email.computer,
                from_player: email.addon_name,
                from_computer_name: email.computer_name,
                isRead: false,
                message: email.message,
                printable: false,
                subject: email.subject,
            }, attachment, true);
        });
    }
    getReachableStoredComputerRecipients() {
        const prefix = `${PROP(COMPUTER_PREFIX, "")}`;
        const postfix = `:${ITEMIZED_ON}`;
        const itemized_ids = world.getDynamicPropertyIds().filter((p) => p.startsWith(prefix) && p.endsWith(postfix));
        return itemized_ids
            .filter((itemized_on_id) => {
            const day = parseInt(GET_RAW_PROP(world, itemized_on_id));
            return world.getDay() <= day + 1;
        })
            .map((itemized_on_id) => {
            const path = itemized_on_id.split(":");
            return path[path.length - 2];
        })
            .map((computer_id) => {
            return {
                id: computer_id,
                name: GET_RAW_PROP(world, IDENTIFIER_NAME(computer_id)),
            };
        });
    }
    vacuumOldComputers() {
        //debug(`Running itemized computer vacuum`);
        const VACUUM_AFTER_COMPUTERS = 200; // only vacuum when we hit this number of itemized computers
        const VACUUM_OLDER_THAN = 2000; // minecraft days 2000 is around 30 natural days
        const prefix = `${PROP(COMPUTER_PREFIX, "")}`;
        const postfix = `:${ITEMIZED_ON}`;
        const itemized_ids = world.getDynamicPropertyIds().filter((p) => p.startsWith(prefix) && p.endsWith(postfix));
        //debug(`Found ${itemized_ids.length} itemized entries`);
        if (itemized_ids.length > VACUUM_AFTER_COMPUTERS) {
            const vacuum_ids = itemized_ids
                .filter((last_seen_id) => {
                const last_seen = parseInt(GET_RAW_PROP(world, last_seen_id));
                if (last_seen + VACUUM_OLDER_THAN < world.getDay()) {
                    return true;
                }
            })
                .map((itemized_on_id) => {
                const path = itemized_on_id.split(":");
                return path[path.length - 2];
            });
            debug(`Vacuuming ${vacuum_ids.length} itemized computers.`);
            // Vacuum ids
            vacuum_ids.forEach((id) => {
                SET_RAW_PROP(world, IDENTIFIER_NAME(id), undefined);
                SET_RAW_PROP(world, IDENTIFIER_VERSION(id), undefined);
                SET_RAW_PROP(world, IDENTIFIER_EMAILS(id), undefined);
                SET_RAW_PROP(world, IDENTIFIER_BLOCKS(id), undefined);
                SET_RAW_PROP(world, IDENTIFIER_WELCOME_SENT(id), undefined);
                SET_RAW_PROP(world, IDENTIFIER_ITEMIZED_ON(id), undefined);
                SET_RAW_PROP(world, IDENTIFIER_LOST_DATA(id), undefined);
                SET_RAW_PROP(world, IDENTIFIER_SAVED_OPERATIONS(id), undefined);
            });
        }
    }
}
const filterComputer = (computer, filter) => {
    if (filter) {
        if (filter.players) {
            const creator = computer.getCreator();
            if (!creator) {
                return false;
            }
            if (!filter.players.includes(creator)) {
                return false;
            }
        }
    }
    return true;
};
const craftComputers = new CraftComputers();
/// Add this near the bottom of your script or in a relevant logic file
function transformComputerToColoredVariant(original, newTypeId, colorIndex) {
    if (!CraftComputer.isComputer(original))
        return;
    const old = new CraftComputer(original);
    const id = old.getId();
    const location = original.location;
    const rotation = original.getRotation();
    const dimension = original.dimension;
    const name = old.getName();
    const creator = old.getCreator() ?? "unknown";
    const emails = old.getEmails();
    const blocks = old.getEmailBlocks();
    const settings = GET_PROP$1(world, IDENTIFIER_SETTINGS(id), {
        mute_startup: false,
        mute_shutdown: false,
        mute_notification: false,
        mute_typing_sound: false,
        mute_typing_animation: false,
        email_notification: false,
        hide_tower: false,
    });
    const containerItems = [];
    const inventory = original.getComponent(EntityInventoryComponent.componentId);
    if (inventory?.container) {
        for (let i = 0; i < inventory.container.size; i++) {
            const item = inventory.container.getItem(i);
            if (item)
                containerItems.push(item);
        }
    }
    cancelOperations(original);
    const pendingOperations = getOperations(original);
    SET_RAW_PROP(original, "jig_ccomp:COMPUTER_ID" /* COMPUTER_PROPERTIES.COMPUTER_ID */, undefined);
    original.remove();
    system.runTimeout(() => {
        const upgraded = dimension.spawnEntity(newTypeId, location);
        upgraded.setRotation(rotation);
        upgraded.triggerEvent(`jig_ccomp:color_${colorIndex}`);
        SET_RAW_PROP(upgraded, "jig_ccomp:COMPUTER_ID" /* COMPUTER_PROPERTIES.COMPUTER_ID */, id);
        addOperation(upgraded, ...pendingOperations);
        runPendingOperations(upgraded);
        const newComputer = new CraftComputer(upgraded);
        newComputer.setCreator(creator);
        newComputer.setVersion(COMPUTER_VERSION);
        newComputer.setName(name);
        newComputer.setEmails(emails);
        newComputer.setEmailBlocks(blocks);
        if (settings.mute_startup)
            upgraded.addTag("jig_ccomp.mute_startup");
        if (settings.mute_shutdown)
            upgraded.addTag("jig_ccomp.mute_shutdown");
        if (settings.mute_notification)
            upgraded.addTag("jig_ccomp.mute_notification");
        if (settings.mute_typing_sound)
            upgraded.addTag("jig_ccomp.mute_typing_sound");
        upgraded.setProperty("jig_ccomp:mute_keyboard_jiggle", settings.mute_typing_animation);
        upgraded.setProperty("jig_ccomp:got_email", settings.email_notification);
        upgraded.setProperty("jig_ccomp:hide_tower", settings.email_notification);
        const upgradedInv = upgraded.getComponent(EntityInventoryComponent.componentId);
        if (upgradedInv?.container) {
            for (let i = 0; i < containerItems.length; i++) {
                upgradedInv.container.setItem(i, containerItems[i]);
            }
        }
    }, 1);
}
/// Comprehensive dye-to-color computer transformation
const dyeToColorIndex = {
    "minecraft:white_dye": 0,
    "minecraft:orange_dye": 1,
    "minecraft:magenta_dye": 2,
    "minecraft:light_blue_dye": 3,
    "minecraft:yellow_dye": 4,
    "minecraft:lime_dye": 5,
    "minecraft:pink_dye": 6,
    "minecraft:gray_dye": 7,
    "minecraft:light_gray_dye": 8,
    "minecraft:cyan_dye": 9,
    "minecraft:purple_dye": 10,
    "minecraft:blue_dye": 11,
    "minecraft:brown_dye": 12,
    "minecraft:green_dye": 13,
    "minecraft:red_dye": 14,
    "minecraft:black_dye": 15,
};
const baseToColoredMap = {
    "jig_ccomp:computer_old": "jig_ccomp:computer_old_c",
    "jig_ccomp:computer_ok": "jig_ccomp:computer_ok_c",
    "jig_ccomp:computer_good": "jig_ccomp:computer_good_c",
    "jig_ccomp:computer_great": "jig_ccomp:computer_great_c",
    "jig_ccomp:computer_lap_b": "jig_ccomp:computer_lap",
};
world.beforeEvents.playerInteractWithEntity.subscribe(event => {
    const { player, itemStack, target } = event;
    if (!target || !player || !itemStack)
        return;
    const colorIndex = dyeToColorIndex[itemStack.typeId];
    const newTypeId = baseToColoredMap[target.typeId];
    if (colorIndex !== undefined && newTypeId) {
        event.cancel = true;
        system.run(() => {
            transformComputerToColoredVariant(target, newTypeId, colorIndex);
            const inventory = player.getComponent(EntityInventoryComponent.componentId);
            if (inventory?.container) {
                const selectedSlot = player.selectedSlotIndex;
                const selectedItem = inventory.container.getItem(selectedSlot);
                if (selectedItem?.typeId === itemStack.typeId) {
                    if (selectedItem.amount > 1) {
                        selectedItem.amount--;
                        inventory.container.setItem(selectedSlot, selectedItem);
                    }
                    else {
                        inventory.container.setItem(selectedSlot);
                    }
                }
            }
        });
    }
});

const asyncWait = async (ticks) => {
    return new Promise((resolve) => {
        system.runTimeout(() => {
            resolve();
        }, ticks);
    });
};
const runUntilSuccess = (target, command, expectedCount, stopIf) => {
    return new Promise((resolve) => {
        const handler = system.runInterval(() => {
            const result = target.runCommand(command);
            if (result.successCount === expectedCount || stopIf()) {
                resolve();
                system.clearRun(handler);
            }
        }, 1);
    });
};
const TRANSLATE = (translate, with_, ...with__) => {
    return {
        translate,
        with: typeof with_ === 'string' ? [with_, ...with__] : with_,
    };
};

const DefaultShowDialogOptions = Object.freeze({
    lockPlayerCamera: true,
    busyRetriesCount: 5,
    busyRetriesTick: 5,
});
let isCameraLockingEnabled = true;
/**
 * Disables camera locking globally, regardless of settings
 * @deprecated Removing on 2.0.0
 */
const disableCameraLocking = () => {
    isCameraLockingEnabled = false;
};
/**
 * Base class for all the script dialogues
 *
 * @category Script dialogue
 */
class ScriptDialogue {
    constructor() { }
    /**
     * Opens the script dialogue. It requires the {@link ShowDialogueOptions#player player} as one of the options.
     *
     * You can configure displaying features by setting the optional values in the {@link ShowDialogueOptions options}
     * @param options used to configure what and how to display the script dialogue.
     *
     * @see {@link ShowDialogueOptions}
     */
    async open(options) {
        const resolvedOptions = this.resolveShowDialogueOptions(options);
        try {
            if (isCameraLockingEnabled && resolvedOptions.lockPlayerCamera) {
                this.lockPlayerCamera(resolvedOptions);
            }
            try {
                const showable = await this.getShowable(resolvedOptions);
                const response = await this.show(showable, resolvedOptions);
                if (response.canceled) {
                    return new DialogueCanceledResponse(response.cancelationReason);
                }
                return await this.processResponse(response, resolvedOptions);
            }
            catch (e) {
                if (e && e instanceof FormRejectError) {
                    return new DialogueRejectedResponse(e.reason, e);
                }
                else {
                    return new DialogueRejectedResponse(undefined, e);
                }
            }
        }
        finally {
            if (isCameraLockingEnabled && resolvedOptions.lockPlayerCamera) {
                await this.unlockPlayerCamera(resolvedOptions);
            }
        }
    }
    async show(showable, options) {
        let i = 0;
        for (;;) {
            const response = await showable.show(options.player);
            if (response.canceled && response.cancelationReason === FormCancelationReason.UserBusy) {
                if (i < options.busyRetriesCount) {
                    i++;
                    await asyncWait(options.busyRetriesTick);
                    if (options.player.isValid()) {
                        continue;
                    }
                }
            }
            return response;
        }
    }
    lockPlayerCamera(options) {
        options.player.runCommand(`inputpermission set "${options.player.name}" camera disabled`);
        options.player.runCommand(`inputpermission set "${options.player.name}" movement disabled`);
    }
    async unlockPlayerCamera(options) {
        await runUntilSuccess(options.player, `inputpermission set "${options.player.name}" camera enabled`, 1, () => !options.player.isValid());
        await runUntilSuccess(options.player, `inputpermission set "${options.player.name}" movement enabled`, 1, () => !options.player.isValid());
    }
    resolveShowDialogueOptions(options) {
        return {
            ...DefaultShowDialogOptions,
            ...options,
        };
    }
}
/**
 * Base class for script dialogue responses
 *
 * @category Responses
 */
class ScriptDialogueResponse {
}
/**
 * Dialogue response when the script dialogue was canceled.
 *
 * Typically this happens if the player was busy when trying to open the script dialogue or if the user
 * pressed the close button (x).
 *
 * Valid reasons can be seen in {@link @minecraft/server-ui!FormCancelationReason FormCancelationReason}
 *
 * @category Responses
 */
class DialogueCanceledResponse extends ScriptDialogueResponse {
    /**
     * Reason the script dialogue was cancel.
     */
    reason;
    /**
     * @internal
     */
    constructor(reason) {
        super();
        this.reason = reason;
    }
}
/**
 * Dialogue response when the script dialogue was rejected, throwing an exception.
 *
 * Reasons can be seen in {@link @minecraft/server-ui!FormRejectReason FormRejectReason} if any reason could be
 * determined.
 *
 * Known reasons can be seen in {@link @minecraft/server-ui!FormRejectReason FormRejectReason}
 * @category Responses
 */
class DialogueRejectedResponse extends ScriptDialogueResponse {
    /**
     * Reason the script dialogue was rejected if there was any, else the {@link exception} needs to be checked
     * to further determine what was the error.
     */
    reason;
    /**
     * Exception that was throw to rejected the script dialogue.
     */
    exception;
    /**
     * @internal
     */
    constructor(reason, exception) {
        super();
        this.reason = reason;
        this.exception = exception;
    }
}
/**
 * Response for button script dialogues.
 *
 * Contains the selected button's name.
 *
 * @category Responses
 * @category Dual button script dialogue
 * @category Multi button script dialogue
 */
class ButtonDialogueResponse extends ScriptDialogueResponse {
    /**
     * Selected button's name.
     *
     * @see {@link DualButton#name}
     * @see {@link MultiButton#name}
     */
    selected;
    callback;
    /**
     * @internal
     */
    constructor(selected, callback) {
        super();
        this.selected = selected;
        this.callback = callback;
    }
}
class MissingButtonsException extends Error {
    constructor() {
        super('Missing buttons');
    }
}

/**
 * Creates a new dual button script dialogue
 *
 * @category Creation
 * @category Dual button script dialogue
 * @param title Title of the dual button script dialogue
 * @param topButton Contents of the top button
 * @param bottomButton Contents of the bottom button
 */
const dualButtonScriptDialogue = (title, topButton, bottomButton) => {
    return new DualButtonScriptDialogue(title, undefined, topButton, bottomButton);
};
/**
 * Dual button script dialogue class.
 *
 * User's don't need to instantiate this class directly, instead they can use {@link dualButtonScriptDialogue}.
 *
 * Allows the users to optionally set a value for the body by calling {@link DualButtonScriptDialogue#setBody setBody}.
 *
 * @category Dual button script dialogue
 */
class DualButtonScriptDialogue extends ScriptDialogue {
    title;
    body;
    topButton;
    bottomButton;
    /**
     * @internal
     */
    constructor(title, body, topButton, bottomButton) {
        super();
        this.title = title;
        this.body = body;
        this.topButton = topButton;
        this.bottomButton = bottomButton;
    }
    /**
     * Sets content of the script dialogue
     * @param body
     */
    setBody(body) {
        return new DualButtonScriptDialogue(this.title, body, this.topButton, this.bottomButton);
    }
    getShowable(_options) {
        const data = new MessageFormData();
        data.title(this.title);
        if (this.body) {
            data.body(this.body);
        }
        data.button1(this.bottomButton.text);
        data.button2(this.topButton.text);
        return data;
    }
    async processResponse(response, _options) {
        const selectedButton = response.selection === 0 ? this.bottomButton : this.topButton;
        let callbackResponse = undefined;
        if (selectedButton.callback) {
            callbackResponse = await selectedButton.callback(selectedButton.name);
        }
        return new ButtonDialogueResponse(selectedButton.name, callbackResponse);
    }
}

/**
 * Initializes a empty multi button script dialogue.
 *
 * Buttons needs to be added using {@link MultiButtonDialogue#addButton} or {@link MultiButtonDialogue#addButtons}
 *
 * @category Creation
 * @category Multi button script dialogue
 * @param title
 */
const multiButtonScriptDialogue = (title) => {
    return new MultiButtonDialogue(title, undefined, []);
};
/**
 * Class used to build multi button script dialogues.
 *
 * Use {@link multiButtonScriptDialogue} to initialize one.
 *
 * @category Multi button script dialogue
 * @see {@link multiButtonScriptDialogue}
 */
class MultiButtonDialogue extends ScriptDialogue {
    title;
    body;
    buttons;
    /**
     * @internal
     */
    constructor(title, body, buttons) {
        super();
        this.title = title;
        this.body = body;
        this.buttons = buttons;
    }
    /**
     * Sets the content body of the multi button dialogue
     * @param body
     */
    setBody(body) {
        return new MultiButtonDialogue(this.title, body, this.buttons);
    }
    /**
     * Adds a button to the multi button script dialogue.
     * @param name name of the button
     * @param text content of the button
     * @param iconPath path to an icon to show in the button
     */
    addButton(name, text, iconPath, callback) {
        return new MultiButtonDialogue(this.title, this.body, [
            ...this.buttons,
            {
                name,
                text,
                iconPath,
                callback,
            },
        ]);
    }
    /**
     * Adds multiple buttons to the multi button script dialogue.
     * @param buttons array of buttons
     */
    addButtons(buttons) {
        return new MultiButtonDialogue(this.title, this.body, [
            ...this.buttons,
            ...buttons,
        ]);
    }
    getShowable(_options) {
        if (this.buttons.length === 0) {
            throw new MissingButtonsException();
        }
        const formData = new ActionFormData();
        formData.title(this.title);
        if (this.body) {
            formData.body(this.body);
        }
        this.buttons.forEach((button) => {
            formData.button(button.text, button.iconPath);
        });
        return formData;
    }
    async processResponse(response, _options) {
        const selectedButton = this.buttons[response.selection];
        let callbackResponse = undefined;
        if (selectedButton.callback) {
            callbackResponse = await selectedButton.callback(selectedButton.name);
        }
        return new ButtonDialogueResponse(selectedButton.name, callbackResponse);
    }
}

/**
 * Initializes a empty input script dialogue.
 *
 * Elements needs to be added using {@link InputScriptDialogue#addElement} or {@link InputScriptDialogue#addElements}
 *
 * @category Creation
 * @category Input script dialogue
 *
 * @param title Title for the script dialogue
 */
const inputScriptDialogue = (title) => {
    return new InputScriptDialogue(title, []);
};
/**
 * Creates a new dropdown element to use in a input script dialogue.
 *
 * @category Input script dialogue
 * @param name
 * @param label
 */
const inputDropdown = (name, label) => {
    return new InputDropdown(name, label, [], 0);
};
/**
 * Creates a new slider element to use in a input script dialogue.
 *
 * @category Input script dialogue
 * @param name
 * @param label
 * @param minimumValue
 * @param maximumValue
 * @param valueStep
 * @param defaultValue
 */
const inputSlider = (name, label, minimumValue, maximumValue, valueStep, defaultValue) => {
    return new InputSlider(name, label, minimumValue, maximumValue, valueStep, defaultValue);
};
/**
 * Creates a new text field element to use in a input script dialogue.
 *
 * @category Input script dialogue
 * @param name
 * @param label
 * @param placeholderText
 * @param defaultValue
 */
const inputText = (name, label, placeholderText, defaultValue) => {
    return new InputText(name, label, placeholderText, defaultValue);
};
/**
 * Creates a new toggle element to use in a input script dialogue.
 *
 * @category Input script dialogue
 * @param name
 * @param label
 * @param defaultValue
 */
const inputToggle = (name, label, defaultValue) => {
    return new InputToggle(name, label, defaultValue);
};
/**
 * Base for all input elements displayed in the input script dialogue.
 *
 * You don't need to instantiate this class directly, instead you can use any of the builder function
 * depending the type you want to use.
 *
 * @category Input script dialogue
 * @see {@link inputDropdown}
 * @see {@link inputSlider}
 * @see {@link inputToggle}
 * @see {@link inputText}
 */
class InputElement {
    /**
     * @internal
     */
    name;
    /**
     * @internal
     */
    label;
    /**
     * @internal
     */
    constructor(name, label) {
        this.name = name;
        this.label = label;
    }
}
/**
 * Base for all input elements that have a fixed default value.
 *
 * You don't need to instantiate this class directly, instead you can use any of the builder function
 * depending the type you want to use.
 *
 * @category Input script dialogue
 * @see {@link inputDropdown}
 * @see {@link inputSlider}
 * @see {@link inputToggle}
 * @see {@link inputText}
 */
class InputWithDefaultValue extends InputElement {
    /**
     * @internal
     */
    defaultValue;
    /**
     * @internal
     */
    constructor(name, label, defaultValue) {
        super(name, label);
        this.defaultValue = defaultValue;
    }
}
/**
 * @internal
 */
class InputDropdownOption {
    label;
    value;
    constructor(label, value) {
        this.label = label;
        this.value = value;
    }
}
/**
 * Input element's representation of a dropdown.
 *
 * Instantiate by using {@link inputDropdown}
 *
 * @category Input script dialogue
 * @see {@link inputDropdown}
 */
class InputDropdown extends InputElement {
    /**
     * @internal
     */
    options;
    /**
     * @internal
     */
    defaultValueIndex;
    /**
     * @internal
     */
    constructor(name, label, options, defaultValueIndex) {
        super(name, label);
        this.defaultValueIndex = defaultValueIndex ?? 0;
        this.options = options;
    }
    /**
     * Sets the default index of the option you would like to use
     * @param defaultValueIndex
     */
    setDefaultValueIndex(defaultValueIndex) {
        return new InputDropdown(this.name, this.label, [...this.options], defaultValueIndex);
    }
    /**
     * Adds an option to the dropdown
     * @param label
     * @param value
     */
    addOption(label, value) {
        return new InputDropdown(this.name, this.label, [...this.options, new InputDropdownOption(label, value)], this.defaultValueIndex);
    }
}
/**
 * Input element's representation of a slider.
 *
 * Instantiate by using {@link inputSlider}
 *
 * @category Input script dialogue
 * @see {@link inputSlider}
 */
class InputSlider extends InputWithDefaultValue {
    /**
     * @internal
     */
    minimumValue;
    /**
     * @internal
     */
    maximumValue;
    /**
     * @internal
     */
    valueStep;
    /**
     * @internal
     */
    constructor(name, label, minimumValue, maximumValue, valueStep, defaultValue) {
        super(name, label, defaultValue ?? minimumValue);
        this.minimumValue = minimumValue;
        this.maximumValue = maximumValue;
        this.valueStep = valueStep;
    }
}
/**
 * Input element's representation of text field.
 *
 * Instantiate by using {@link inputText}
 *
 * @category Input script dialogue
 * @see {@link inputText}
 */
class InputText extends InputWithDefaultValue {
    /**
     * @internal
     */
    placeholderText;
    /**
     * @internal
     */
    constructor(name, label, placeholderText, defaultValue) {
        super(name, label, defaultValue ?? '');
        this.placeholderText = placeholderText;
    }
}
/**
 * Input element's representation of toggle.
 *
 * Instantiate by using {@link inputToggle}
 *
 * @category Input script dialogue
 * @see {@link inputToggle}
 */
class InputToggle extends InputWithDefaultValue {
    /**
     * @internal
     */
    constructor(name, label, defaultValue) {
        super(name, label, !!defaultValue);
    }
}
/**
 * Class used to build input script dialogues.
 *
 * Use {@link inputScriptDialogue} to initialize one.
 *
 * @category Input script dialogue
 * @see {@link inputScriptDialogue}
 */
class InputScriptDialogue extends ScriptDialogue {
    elements;
    title;
    submitButton;
    // work around TS2848: The right-hand side of an instanceof expression must not be an instantiation expression.
    InputDropdown = (InputDropdown);
    InputSlider = (InputSlider);
    InputText = (InputText);
    InputToggle = (InputToggle);
    /**
     * @internal
     */
    constructor(title, elements, submitButton) {
        super();
        this.title = title;
        this.elements = elements;
        this.submitButton = submitButton;
    }
    withSubmitButton(submitButton) {
        return new InputScriptDialogue(this.title, [...this.elements], submitButton);
    }
    /**
     * Adds an input element to the input script dialogue.
     * @param element
     *
     * @see {@link inputDropdown}
     * @see {@link inputSlider}
     * @see {@link inputToggle}
     * @see {@link inputText}
     */
    addElement(element) {
        return new InputScriptDialogue(this.title, [...this.elements, element], this.submitButton);
    }
    /**
     * Adds multiple input element to the input script dialogue.
     * @param elements
     *
     * @see {@link inputDropdown}
     * @see {@link inputSlider}
     * @see {@link inputToggle}
     * @see {@link inputText}
     */
    addElements(elements) {
        return new InputScriptDialogue(this.title, [...this.elements, ...elements], this.submitButton);
    }
    getShowable(_options) {
        if (this.elements.length === 0) {
            throw new MissingElementsError();
        }
        const data = new ModalFormData();
        data.title(this.title);
        if (this.submitButton) {
            data.submitButton(this.submitButton);
        }
        this.elements.forEach((element) => {
            if (element instanceof this.InputDropdown) {
                if (element.options.length === 0) {
                    throw new MissingDropdownOptionsError(element.name);
                }
                data.dropdown(element.label, element.options.map((o) => o.label), element.defaultValueIndex);
            }
            else if (element instanceof this.InputSlider) {
                data.slider(element.label, element.minimumValue, element.maximumValue, element.valueStep, element.defaultValue);
            }
            else if (element instanceof this.InputText) {
                data.textField(element.label, element.placeholderText, element.defaultValue);
            }
            else if (element instanceof this.InputToggle) {
                data.toggle(element.label, element.defaultValue);
            }
        });
        return data;
    }
    async processResponse(response, _options) {
        const formValues = response.formValues ?? this.elements.map((_e) => undefined);
        const values = this.elements.map((element, index) => {
            const name = element.name;
            let value = 0;
            const formValue = formValues[index];
            if (element instanceof this.InputDropdown) {
                value = element.options[element.defaultValueIndex].value;
                if (formValue !== undefined) {
                    value = element.options[formValue].value;
                }
            }
            else if (element instanceof this.InputSlider ||
                element instanceof this.InputText ||
                element instanceof this.InputToggle) {
                value = element.defaultValue;
                if (formValue !== undefined) {
                    value = formValue;
                }
            }
            return {
                [name]: value,
            };
        });
        return new InputScriptDialogueResponse(Object.assign({}, ...values));
    }
}
/**
 * Script dialogue response from a input script dialogue.
 * Holds a map with the values used by each of the element's name.
 *
 * @category Input script dialogue
 * @category Responses
 */
class InputScriptDialogueResponse {
    /**
     * Map with the values of the script dialogue..
     */
    values;
    constructor(values) {
        this.values = values;
    }
}
class MissingElementsError extends Error {
    constructor() {
        super('Missing input elements');
    }
}
class MissingDropdownOptionsError extends Error {
    constructor(name) {
        super(`Missing dropdown options for ${name}`);
    }
}

const setPcIdDialogue = (oldName) => {
    return inputScriptDialogue(TRANSLATE$1("jig_ccomp:pc-id-set.title"))
        .addElement(inputText("name", TRANSLATE$1("jig_ccomp:pc-id-set.name.label", "\n", "\n\n"), TRANSLATE$1("jig_ccomp:pc-id-set.name.placeholder"), oldName));
};

const WORLD_INFO_OBJECTIVE = 'jig_ccomp:world_info';
const COMPUTER_INFO_OBJECTIVE = 'jig_ccomp:jig_computer.addon_stats';
const CUSTOM_OBJECTIVES = 'jig_computer.addon_stats';
const STATS_DEFAULT = 'default';
const STATS_SORT_A_Z = 'group_a_z';
const STATS_SORT_Z_A = 'group_z_a';
const STATS_SORT_Highest_Lowest = 'highest_lowest';
const STATS_SORT_Lowest_Highest = 'lowest_highest';

const viewBoardsList = (boards) => {
    let boardsElement = inputDropdown("board", RAW_TEXT(TEXT("\n"), TRANSLATE$1("jig_ccomp:view-stat-list.board", "\n\n")));
    boards.forEach(t => {
        boardsElement = boardsElement.addOption(t, t);
    });
    const toIndex = boards.findIndex(t => t === WORLD_INFO_OBJECTIVE);
    boardsElement = boardsElement.setDefaultValueIndex(toIndex === -1 ? 0 : toIndex);
    let statsElement = inputDropdown("sort", RAW_TEXT(TEXT("\n"), TRANSLATE$1("jig_ccomp:view-stat-list.sorting", "\n\n")))
        .addOption(TRANSLATE$1("jig_ccomp:view-stat-list.sorting.default"), STATS_DEFAULT)
        .addOption(TRANSLATE$1("jig_ccomp:view-stat-list.sorting.group_a_z"), STATS_SORT_A_Z)
        .addOption(TRANSLATE$1("jig_ccomp:view-stat-list.sorting.group_z_a"), STATS_SORT_Z_A)
        .addOption(TRANSLATE$1("jig_ccomp:view-stat-list.sorting.highest_lowest"), STATS_SORT_Highest_Lowest)
        .addOption(TRANSLATE$1("jig_ccomp:view-stat-list.sorting.lowest_highest"), STATS_SORT_Lowest_Highest)
        .setDefaultValueIndex(0);
    return inputScriptDialogue(TRANSLATE$1("jig_ccomp:view-stat-list.title"))
        .addElement(boardsElement)
        .addElement(statsElement);
};

const viewStats = (board, TimeOfDay, worldDay, installedDays, stats) => {
    return dualButtonScriptDialogue(RAW_TEXT(TRANSLATE$1("jig_ccomp:view-stats-board.title")), {
        name: "other-stats",
        text: TRANSLATE$1("jig_ccomp:view-stats-board.other-stats")
    }, {
        name: "quit",
        text: TRANSLATE$1("jig_ccomp:quit"),
    }).setBody(RAW_TEXT(TEXT("§l"), TRANSLATE$1(board), TEXT("§r"), ...isItWorldObjectives(board, TimeOfDay, worldDay, installedDays, stats.map(p => p.key)), TEXT("\n\n"), ...isThereNone(board), ...buildStats(board, stats), TEXT("\n"), TRANSLATE$1(getCreditsKey(board), "\n")));
};
const getCreditsKey = (board) => {
    if (board === WORLD_INFO_OBJECTIVE) {
        return '';
    }
    return board.replace(CUSTOM_OBJECTIVES, "credits.for.computers");
};
const isItWorldObjectives = (board, TimeOfDay, worldDay, installedDays, stats) => {
    if (board === WORLD_INFO_OBJECTIVE) {
        const worldInfoRawText = [
            TEXT("\n"), TRANSLATE$1("jig_ccomp:current_time"), TEXT(TimeOfDay),
            TEXT("\n"), TRANSLATE$1("jig_ccomp:world_age"), TRANSLATE$1("jig_ccomp:days"), TEXT(worldDay),
            TEXT("\n"), TRANSLATE$1("jig_ccomp:installed_age"), TRANSLATE$1("jig_ccomp:days"), TEXT(installedDays),
        ];
        if (stats.length > 0) {
            worldInfoRawText.push(TEXT("\n"), TRANSLATE$1("jig_ccomp:since-installed-disclaimer"));
        }
        return worldInfoRawText;
    }
    return [];
};
const isThereNone = (board) => {
    const objective = world.scoreboard.getObjective(board);
    if (!objective) {
        debug(`Couldn't find objective ${board}`);
        return [];
    }
    let test = objective.getParticipants();
    if (test.length == 0) {
        return [
            TRANSLATE$1("jig_ccomp:there_isnt_any_stats_yet"), TEXT("\n")
        ];
    }
    return [];
};
const buildStats = (board, stats) => {
    const objective = world.scoreboard.getObjective(board);
    if (!objective) {
        debug(`Couldn't find objective ${board}`);
        return [];
    }
    return stats.map(stat => RAW_TEXT(TRANSLATE$1(stat.key), TEXT(":\n"), TEXT(prettyNumberFormat(stat.value)), TEXT("\n")));
};
const prettyNumberFormat = (value) => {
    const stringNumber = value.toString().split('.');
    let integerPart = stringNumber[0];
    for (let i = integerPart.length - 3; i > 0; i -= 3) {
        integerPart = integerPart.substring(0, i) + ',' + integerPart.substring(i);
    }
    stringNumber[0] = integerPart;
    return stringNumber.join('.');
};

const defaultScriptDialogueOptions = {
    busyRetriesCount: 5,
    busyRetriesTick: 5,
    lockPlayerCamera: false,
};

const Config = {
    usePredefined: false,
    favoriteEmailAttachtment: 'jig_ccomp:favorite_email',
    JigarBoxNpcId: 'JigarBox',
    world: {
        installedTime: 'jig_ccomp:installed_time'
    },
    player: {
        jignetContacted: 'jig_ccomp:jignet_contacted'
    },
    forum: {
        post_capacity: 50,
        random_npc_post_ticks: 60 * 60 * 20 // every hour
    },
    radar: {
        //Radar modification tags
        tags: {
            // for chainmail simulation
            chain_protect: 'jig_ccomp:chain_protect',
            // for hidden completely
            radar_protect: 'jig_ccomp:radar_protect'
        }
    },
    predefinedPcId: [
        'Ancient PC 1',
        'Ancient PC 2',
        'Ancient PC 3',
        'Ancient PC 4',
        'Ancient PC 5',
        'OK PC 1',
        'OK PC 2',
        'OK PC 3',
        'OK PC 4',
        'OK PC 5',
        'RGB PC 1',
        'RGB PC 2',
        'RGB PC 3',
        'RGB PC 4',
        'RGB PC 5',
        'Home 1',
        'Home 2',
        'Home 3',
        'Spare 1',
        'Spare 2',
        'Spare 3',
        'Farm PC',
        'Basement PC',
        'Upstairs PC',
        'Castle PC',
        'Mom',
        'Dad',
        'Sister 1',
        'Sister 2',
        'Sister 3',
        'Sister 4',
        'Brother 1',
        'Brother 2',
        'Brother 3',
        'Brother 4',
        'Friend 1',
        'Friend 2',
        'Friend 3',
        'Friend 4',
        'Friend 5',
        'Friend 6',
        'Friend 7',
        'Best Friend',
        'Basalt Delta PC',
        'Beach PC',
        'Birch PC',
        'Caves PC',
        'Cherry Grove PC',
        'Crimson Forest PC',
        'Dark Oak Forest PC',
        'Deep Ocean PC',
        'Deep Dark PC',
        'Desert PC',
        'Dripstone Caves PC',
        'Edge PC',
        'Extreme Hills PC',
        'Flower Forest PC',
        'Forest PC',
        'Frozen PC',
        'Frozen Peaks PC',
        'Grove PC',
        'Hills PC',
        'Ice PC',
        'Ice Plains PC',
        'Jagged Peaks PC',
        'Jungle PC',
        'Lakes PC',
        'Lush Cave PC',
        'Mangrove Swamp PC',
        'Mega PC',
        'Mesa PC',
        'Mooshroom Island PC',
        'Mountain PC',
        'Mutated Biome PC',
        'Nether PC',
        'Nether Wastes PC',
        'Netherwart Forest PC',
        'Ocean PC',
        'Plains PC',
        'Plateau PC',
        'River PC',
        'Roofed Forest PC',
        'Savanna PC',
        'Shore PC',
        'Snowy Slopes PC',
        'Soulsand Valley PC',
        'Stone Beach PC',
        'Swamp PC',
        'Taiga PC',
        'The End PC',
        'Warped Forest PC',
    ]
};

const getScoreOr = (scoreboardObjectiveOrName, score, defaultValue) => {
    try {
        const value = getScoreInternal(scoreboardObjectiveOrName, score);
        if (value === undefined) {
            return defaultValue;
        }
        return value;
    }
    catch (e) {
        return defaultValue;
    }
};
const getScoreInternal = (scoreboardObjectiveOrName, score) => {
    const scoreboardObjective = typeof scoreboardObjectiveOrName === 'string' ? world.scoreboard.getObjective(scoreboardObjectiveOrName) : scoreboardObjectiveOrName;
    if (!scoreboardObjective) {
        return undefined;
    }
    return scoreboardObjective.getScore(score);
};

class WorldInfo {
    constructor() {
    }
    getObjectives() {
        return [
            WORLD_INFO_OBJECTIVE,
            COMPUTER_INFO_OBJECTIVE,
            ...world
                .scoreboard
                .getObjectives()
                .filter(o => o.id !== COMPUTER_INFO_OBJECTIVE)
                .filter(o => o.id.endsWith(CUSTOM_OBJECTIVES))
                .map(o => o.id)
        ];
    }
    sortItems(items, sorting) {
        if (items.length > 0) {
            switch (sorting) {
                case STATS_DEFAULT:
                    return items;
                case STATS_SORT_A_Z:
                    return items.sort((a, b) => a.key.localeCompare(b.key));
                case STATS_SORT_Z_A:
                    return items.sort((a, b) => b.key.localeCompare(a.key));
                case STATS_SORT_Highest_Lowest:
                    return items.sort((a, b) => b.value - a.value);
                case STATS_SORT_Lowest_Highest:
                    return items.sort((a, b) => a.value - b.value);
                default:
                    throw new Error("Error something happened");
            }
        }
        return [];
    }
    getStats(objective, sorting) {
        const items = world.scoreboard.getObjective(objective).getParticipants();
        if (items) {
            const stats = items.map(i => ({
                key: i.displayName,
                value: getScoreOr(objective, i.displayName, 0)
            }));
            return this.sortItems(stats, sorting) ?? [];
        }
        return [];
    }
}
const worldInfo = new WorldInfo();
const initWorldInfo = () => {
    // Init trackers
    world.afterEvents.entityDie.subscribe(async () => {
        world.scoreboard.getObjective('jig_ccomp:world_info')?.addScore('jig_ccomp:deadentities', 1);
    });
    //world.afterEvents.entityHurt.subscribe((event) => {
    //  const sourceEntity = event.hurtEntity;
    //	let health = (sourceEntity.getComponent(EntityHealthComponent.componentId) as EntityHealthComponent).currentValue
    //	let inventory = (sourceEntity.getComponent(EntityInventoryComponent.componentId) as EntityInventoryComponent).container
    //
    //	world.sendMessage('my health is '+health)
    //	world.sendMessage('my inventory is '+inventory)
    //});
    //world.afterEvents.entityDie.subscribe(async (event) => {
    //  const sourceEntity = event.deadEntity;
    //	let health = (sourceEntity.getComponent(EntityHealthComponent.componentId) as EntityHealthComponent).currentValue
    //	let inventory = (sourceEntity.getComponent(EntityInventoryComponent.componentId) as EntityInventoryComponent).container
    //	world.sendMessage('now im dead '+health)
    //});
    world.afterEvents.playerPlaceBlock.subscribe(async () => {
        world.scoreboard.getObjective('jig_ccomp:world_info')?.addScore('jig_ccomp:playerplaceblock', 1);
    });
    world.afterEvents.playerBreakBlock.subscribe(async () => {
        world.scoreboard.getObjective('jig_ccomp:world_info')?.addScore('jig_ccomp:playerbreakblock', 1);
    });
    world.afterEvents.buttonPush.subscribe(async () => {
        world.scoreboard.getObjective('jig_ccomp:world_info')?.addScore('jig_ccomp:buttonpush', 1);
    });
    world.afterEvents.leverAction.subscribe(async () => {
        world.scoreboard.getObjective('jig_ccomp:world_info')?.addScore('jig_ccomp:leveraction', 1);
    });
    world.afterEvents.pressurePlatePush.subscribe(async () => {
        world.scoreboard.getObjective('jig_ccomp:world_info')?.addScore('jig_ccomp:pressureplatepush', 1);
    });
    world.afterEvents.tripWireTrip.subscribe(async () => {
        world.scoreboard.getObjective('jig_ccomp:world_info')?.addScore('jig_ccomp:tripwiretrip', 1);
    });
    function convertToDays(timeUnits) {
        const secondsPerUnit = 3.6;
        return Math.floor(secondsPerUnit / (60 * 60 * 24));
    }
    function convertToTimeOfDay(timeUnits) {
        const baseTime = new Date(0);
        const baseTimeHours = 6;
        const millisecondsPerUnit = 3.6 * 1000; // 1 unit is 3.6 seconds
        const totalMilliseconds = timeUnits * millisecondsPerUnit;
        const shiftedTime = new Date(baseTime.getTime() + totalMilliseconds);
        const hours = ((shiftedTime.getUTCHours() + baseTimeHours) % 24).toString().padStart(2, '0');
        const minutes = shiftedTime.getUTCMinutes().toString().padStart(2, '0');
        const seconds = shiftedTime.getUTCSeconds().toString().padStart(2, '0');
        const milliseconds = shiftedTime.getUTCMilliseconds().toString().padStart(2, '0').slice(0, 2);
        return `${hours}§7:§r${minutes}§7:§r${seconds}§7.§r${milliseconds}`;
    }
    // Init custom world info
    system.afterEvents.scriptEventReceive.subscribe((event) => {
        const player = event.initiator;
        const sourceEntity = event.sourceEntity;
        let timeUnits = world.getTimeOfDay();
        let TimeOfDay = convertToTimeOfDay(timeUnits);
        let worldDay = world.getDay();
        const timeAfterInstalling = convertToDays(world.getAbsoluteTime() - GET_RAW_PROP(world, Config.world.installedTime));
        if (player && player instanceof Player && sourceEntity && CraftComputer.isComputer(sourceEntity)) {
            const computer = new CraftComputer(sourceEntity);
            if (event.id === 'jig_ccomp:show_stats') {
                computer.computer.triggerEvent('jig_ccomp:typing');
                player.playSound('jig_common.robot_bleeps');
                system.runTimeout(async () => {
                    while (true) {
                        const response = await viewBoardsList(worldInfo.getObjectives()).open({ ...defaultScriptDialogueOptions, player });
                        if (response instanceof InputScriptDialogueResponse) {
                            const { board, sort } = response.values;
                            const objective = world.scoreboard.getObjective(board);
                            if (!objective) {
                                return [];
                            }
                            let test = objective.getParticipants();
                            if (test.length == 0) {
                                sourceEntity?.runCommand("/event entity @s jig_ccomp:screen_stac");
                            }
                            else {
                                player.playSound('jig_common.robot_bleeps');
                                sourceEntity?.runCommand("/event entity @s jig_ccomp:screen_stab");
                            }
                            sourceEntity?.runCommand("/event entity @s jig_ccomp:typing");
                            if ((board && board) && (sort && sort)) {
                                debug("The user opened Computer Stats");
                                const innerResponse = await viewStats(board, TimeOfDay, worldDay, timeAfterInstalling, worldInfo.getStats(board, sort)).open({ ...defaultScriptDialogueOptions, player });
                                computer.computer.triggerEvent('jig_ccomp:typing');
                                if (innerResponse instanceof ButtonDialogueResponse) {
                                    if (innerResponse.selected === "other-stats") {
                                        player.playSound('jig_common.robot_bleeps');
                                        sourceEntity?.runCommand("/event entity @s jig_ccomp:screen_stat");
                                        sourceEntity?.runCommand("/event entity @s jig_ccomp:typing");
                                        continue;
                                    }
                                }
                            }
                        }
                        break;
                    }
                }, 10);
            }
        }
    }, {
        namespaces: ['jig_ccomp']
    });
};

const viewSelectRadar = () => {
    return inputScriptDialogue(TRANSLATE$1("jig_ccomp:select-radar.title"))
        .addElement(inputDropdown("radar", RAW_TEXT(TEXT("\n"), TRANSLATE$1("jig_ccomp:select-radar.radar", "\n\n")))
        .addOption(TRANSLATE$1("jig_ccomp:select-radar.radar.computer"), "computer")
        .addOption(TRANSLATE$1("jig_ccomp:select-radar.radar.everything"), "everything")
        .addOption(TRANSLATE$1("jig_ccomp:select-radar.radar.item"), "item")
        .addOption(TRANSLATE$1("jig_ccomp:select-radar.radar.mob"), "mob")
        .addOption(TRANSLATE$1("jig_ccomp:select-radar.radar.monster"), "monster")
        .addOption(TRANSLATE$1("jig_ccomp:select-radar.radar.playercheck"), "playercheck")
        .addOption(TRANSLATE$1("jig_ccomp:select-radar.radar.rideable"), "rideable")
        .addOption(TRANSLATE$1("jig_ccomp:select-radar.radar.tamed"), "tamed")
        .addOption(TRANSLATE$1("jig_ccomp:select-radar.radar.villager"), "villager")
        .setDefaultValueIndex(4))
        .addElement(inputToggle("sort", TRANSLATE$1("jig_ccomp:select-radar.sort-closest"), false))
        .addElement(inputSlider("count", TRANSLATE$1("jig_ccomp:select-radar.count"), 1, 50, 1, 10));
};

const locks = {};
const callOrSchedule = async (mightFail) => {
    try {
        await mightFail();
    }
    catch {
        system.runTimeout(() => {
            mightFail();
        }, 1);
    }
};
// We could use something more elaborated to keep track of the current state, like a smart pointer that only releases when all releases.
const lockMovementWhile = async (player, whileProcessing) => {
    try {
        locks[player.id] = player.id in locks ? locks[player.id] + 1 : 1;
        await callOrSchedule(async () => {
            player.inputPermissions.setPermissionCategory(InputPermissionCategory.Camera, false);
            player.inputPermissions.setPermissionCategory(InputPermissionCategory.Movement, false);
        });
        return await whileProcessing();
    }
    finally {
        locks[player.id]--;
        if (locks[player.id] <= 0) {
            locks[player.id] = 0;
            await callOrSchedule(async () => {
                player.inputPermissions.setPermissionCategory(InputPermissionCategory.Camera, true);
                player.inputPermissions.setPermissionCategory(InputPermissionCategory.Movement, true);
            });
        }
    }
};

const viewRadar = (radar, entries, player) => {
    const showPrintButton = (entries.filter(e => !e.protected).length > 0);
    let moreOptionsButtons = multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:view-radar.more-options.title"))
        .setBody(RAW_TEXT(TEXT("\n"), TRANSLATE$1(`jig_ccomp:view-radar.more-options.body`)))
        .addButton("other-radar", TRANSLATE$1("jig_ccomp:view-radar.other-radar"), "textures/jig/ccomp/myui/radar.png", async (selected) => {
        return {
            selectedOther: true
        };
    });
    if (showPrintButton) {
        moreOptionsButtons = moreOptionsButtons.addButton("print-entry", TRANSLATE$1("jig_ccomp:view-radar.print-entry"), "textures/jig/ccomp/myui/print.png", async (selected) => {
            const response = await lockMovementWhile(player, async () => {
                return await multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:view-radar.print-entry.title"))
                    .setBody(RAW_TEXT(TEXT("\n"), TRANSLATE$1("jig_ccomp:view-radar.print-entry.body", "\n")))
                    .addButtons(entries
                    .map((e, index) => ({ ...e, index }))
                    .filter(e => !e.protected)
                    .map((e) => ({
                    name: e.index.toString(),
                    text: RAW_TEXT(TEXT(`${e.index + 1}: `), getEntityRawMessage(e), TEXT(` Distance: ${e.distance}`))
                }))).open({ player });
            });
            if (response instanceof ButtonDialogueResponse) {
                return {
                    selectedPrintEntry: response.selected
                };
            }
        });
    }
    moreOptionsButtons = moreOptionsButtons.addButton("quit", TRANSLATE$1("jig_ccomp:quit"));
    return dualButtonScriptDialogue(RAW_TEXT(TRANSLATE$1("jig_ccomp:view-radar.title")), {
        name: "more-options",
        text: TRANSLATE$1("jig_ccomp:view-radar.more-options"),
        callback: async (selected) => {
            const response = await lockMovementWhile(player, async () => {
                return await moreOptionsButtons.open({
                    ...defaultScriptDialogueOptions,
                    player
                });
            });
            if (response instanceof ButtonDialogueResponse) {
                return {
                    ...response.callback,
                    selectedOptions: "more-options"
                };
            }
        }
    }, {
        name: "quit",
        text: TRANSLATE$1("jig_ccomp:quit"),
    })
        .setBody(RAW_TEXT(TEXT("§l"), TRANSLATE$1(`jig_ccomp:view-radar.${radar}`), TEXT("§r"), TEXT("\n"), ...buildEntries(entries), TEXT("\n"), entries.some(e => e.protected) ? TRANSLATE$1("jig_ccomp:view-radar.chainmail-warning") : TEXT("")));
};
const moreround = (value) => {
    return Math.ceil(value);
};
const buildEntries = (entries) => {
    if (entries.length === 0) {
        return [
            TRANSLATE$1("jig_ccomp:view-radar.not-found")
        ];
    }
    return entries.map(e => buildEntry(e));
};
const getEntityRawMessage = (entry) => {
    if (entry.id == "minecraft:player") {
        return ENTITY("jig_ccomp:fake_player");
    }
    if (entry.item) {
        const message = [
            ENTITY(entry.id),
            TEXT(" "),
            ITEM(entry.item),
        ];
        if (entry.item.isStackable) {
            message.push(TEXT(` x${entry.item.amount}`));
        }
        return RAW_TEXT(...message);
    }
    return ENTITY(entry.id);
};
const buildEntry = (entry) => {
    const messages = [];
    if (entry.protected) {
        messages.push(TEXT("§k"));
    }
    messages.push(getEntityRawMessage(entry));
    if (entry.nametag) {
        messages.push(TEXT(" "));
        messages.push(TRANSLATE$1("jig_ccomp:view-radar.entity.name"));
        messages.push(TEXT(" " + entry.nametag));
    }
    if (entry.health !== undefined) {
        messages.push(TEXT(` \uE10C ${moreround(entry.health)}`));
    }
    messages.push(TEXT("\n"));
    messages.push(TEXT(`x: ${moreround(entry.location.x)}, y: ${moreround(entry.location.y)}, z: ${moreround(entry.location.z)}`));
    messages.push(TEXT(" "));
    messages.push(TRANSLATE$1("jig_ccomp:view-radar.distance"));
    messages.push(TEXT(` ${moreround(entry.distance)}`));
    messages.push(TEXT("\n\n"));
    if (entry.protected) {
        messages.push(TEXT("§r"));
    }
    return RAW_TEXT(...messages);
};

class FormError extends Error {
    constructor(msg) {
        super(msg);
    }
}
class FormArgumentError extends FormError {
    path;
    step;
    current;
    constructor(path, step, current) {
        super(`Invalid path: ${path} at step: ${step} in object: ${JSON.stringify(current)}`);
        this.path = path;
        this.step = step;
        this.current = current;
    }
}

class FormArguments {
    _args = {};
    set(name, arg) {
        this._args[name] = arg;
    }
    setAll(args) {
        this._args = {
            ...this._args,
            ...args,
        };
    }
    getAll() {
        return this._args;
    }
    get(name) {
        return this._args[name];
    }
    resolvePath(path) {
        let current = this._args;
        const splitPath = path.split('.');
        for (const step of splitPath) {
            if (typeof current === 'object' && step in current) {
                current = current[step];
            }
            else {
                throw new FormArgumentError(path, step, current);
            }
        }
        return current;
    }
    resolveTemplate(template) {
        return template.replace(/\{\s*([^}\s]+)\s*\}/g, (_, p1) => {
            return this.resolvePath(p1).toString();
        });
    }
    normalize(content) {
        if (typeof content === 'string') {
            return {
                type: 'text',
                text: this.resolveTemplate(content),
            };
        }
        else if (Array.isArray(content)) {
            return {
                type: 'array',
                array: content.map((c) => this.normalize(c)),
            };
        }
        else {
            return {
                type: 'translate',
                translate: this.resolveTemplate(content.translate),
                args: content.args ? content.args.map((a) => this.normalize(a)) : undefined,
            };
        }
    }
}

class FormEventProducer {
    _hub;
    _formAction;
    _args;
    static fromFormHub(hub) {
        if (typeof hub.entrypoint === 'string') {
            return new FormEventProducer(hub, {
                form: hub.entrypoint,
            });
        }
        else {
            return new FormEventProducer(hub, {
                form: hub.entrypoint.form,
                event: hub.entrypoint.events,
                eventArgs: hub.entrypoint.eventArgs,
                setArgs: hub.entrypoint.initialArgs,
            });
        }
    }
    constructor(hub, formAction, previousArgs) {
        this._hub = hub;
        this._formAction = formAction;
        this._args = new FormArguments();
        if (this._formAction?.copyArgs && previousArgs) {
            this._args.setAll(previousArgs.getAll());
        }
        if (this._formAction?.setArgs) {
            this._args.setAll(this._formAction.setArgs);
        }
    }
    get args() {
        return this._args;
    }
    getInitialForm() {
        return this._formAction?.form ? this._hub.forms[this._formAction.form] : undefined;
    }
    *iterator() {
        if (this._formAction) {
            if (!this._formAction.event) {
                yield new FormEvent(this._hub, undefined, this._args);
            }
            else if (typeof this._formAction.event === 'string') {
                yield new FormEvent(this._hub, {
                    event: this._formAction.event,
                    args: this._formAction.eventArgs,
                }, this._args);
            }
            else {
                for (const event of this._formAction.event) {
                    yield new FormEvent(this._hub, {
                        event: event.event,
                        args: event.args ?? this._formAction.eventArgs,
                    }, this._args);
                }
            }
        }
    }
}
class FormEvent {
    _form = undefined;
    _name = undefined;
    _continueProcessing = true;
    _hub;
    _args;
    _eventArgs = [];
    constructor(hub, eventAction, args) {
        this._hub = hub;
        this._args = args;
        if (eventAction) {
            this._name = eventAction.event;
            if (eventAction.args) {
                this._eventArgs = eventAction.args;
            }
        }
    }
    loadForm(name, type) {
        if (name in this._hub.forms) {
            const form = this._hub.forms[name];
            if (type && form.type !== type) {
                throw new FormError(`Invalid type ${type} for form named ${name}. The actual type is ${form.type}`);
            }
            return JSON.parse(JSON.stringify(form));
        }
        throw new FormError(`Unknown form named ${name}`);
    }
    set form(form) {
        this._form = form;
    }
    get form() {
        return this._form;
    }
    get name() {
        return this._name;
    }
    get args() {
        return this._args;
    }
    get eventArgs() {
        return this._eventArgs;
    }
    get continueProcessing() {
        return this._continueProcessing;
    }
    cancelProcessing() {
        this._continueProcessing = false;
    }
}
const triggerEvent = async (eventProducer, receiver) => {
    let form = eventProducer.getInitialForm();
    if (receiver) {
        for (const event of eventProducer.iterator()) {
            event.form = form;
            if (event.name) {
                if (typeof receiver === 'function') {
                    await receiver(event);
                }
                else if (event.name in receiver) {
                    await receiver[event.name](event);
                }
            }
            form = event.form;
            if (!event.continueProcessing) {
                break;
            }
        }
    }
    return form;
};

const _ = (value, ...args) => ({
    translate: value,
    args: args.length > 0 ? args : undefined,
});

const assertNever = (arg) => {
    throw new Error(`Should have been never but got ${arg} instead`);
};
const toRawMessage = (content) => {
    switch (content.type) {
        case 'text':
            return {
                text: content.text,
            };
        case 'translate':
            if (!content.args) {
                return {
                    translate: content.translate,
                };
            }
            return {
                translate: content.translate,
                with: {
                    rawtext: content.args.map((t) => {
                        if (typeof t === 'string') {
                            return {
                                text: t,
                            };
                        }
                        else {
                            return toRawMessage(t);
                        }
                    }),
                },
            };
        case 'array':
            return {
                rawtext: content.array.map(toRawMessage),
            };
    }
    assertNever(content);
};
const configureFormMultiButton = (form, args) => {
    let dialogue;
    dialogue = multiButtonScriptDialogue(toRawMessage(args.normalize(form.title)));
    if (form.body) {
        dialogue = dialogue.setBody(toRawMessage(args.normalize(form.body)));
    }
    for (let i = 0; i < form.elements.length; ++i) {
        const element = form.elements[i];
        if (element.type === 'button') {
            dialogue = dialogue.addButton(i.toString(), toRawMessage(args.normalize(element.text)), element.icon);
        }
    }
    return dialogue;
};
const configureFormDualButton = (form, args) => {
    let dialogue;
    dialogue = dualButtonScriptDialogue(toRawMessage(args.normalize(form.title)), {
        name: 'top',
        text: toRawMessage(args.normalize(form.topButton.text)),
    }, {
        name: 'bottom',
        text: toRawMessage(args.normalize(form.bottomButton.text)),
    });
    if (form.body) {
        dialogue = dialogue.setBody(toRawMessage(args.normalize(form.body)));
    }
    return dialogue;
};
const configureFormInput = (form, args) => {
    let dialogue;
    dialogue = inputScriptDialogue(toRawMessage(args.normalize(form.title)));
    if (form.submit) {
        dialogue = dialogue.withSubmitButton(toRawMessage(args.normalize(form.submit)));
    }
    for (let i = 0; i < form.elements.length; ++i) {
        const element = form.elements[i];
        if (element.type === 'slider') {
            dialogue = dialogue.addElement(inputSlider(element.name ?? i.toString(), toRawMessage(args.normalize(element.text)), element.min, element.max, element.step, element.defaultValue));
        }
        else if (element.type === 'dropdown') {
            let dropdown = inputDropdown(element.name ?? i.toString(), toRawMessage(args.normalize(element.text)));
            if (element.defaultValue) {
                dropdown =
                    dropdown.setDefaultValueIndex(element.options.findIndex((o) => o.value === element.defaultValue)) ?? 0;
            }
            for (let j = 0; j < element.options.length; ++j) {
                const option = element.options[j];
                dropdown = dropdown.addOption(toRawMessage(args.normalize(option.text)), option.value);
            }
            dialogue = dialogue.addElement(dropdown);
        }
        else if (element.type === 'text') {
            dialogue = dialogue.addElement(inputText(element.name ?? i.toString(), toRawMessage(args.normalize(element.text)), toRawMessage(args.normalize(element.placeholder)), element.defaultValue));
        }
        else if (element.type === 'toggle') {
            dialogue = dialogue.addElement(inputToggle(element.name ?? i.toString(), toRawMessage(args.normalize(element.text)), element.defaultValue));
        }
        else {
            assertNever(element);
        }
    }
    return dialogue;
};
const configureForm = (form, args) => {
    switch (form.type) {
        case 'multi-button':
            return configureFormMultiButton(form, args);
        case 'dual-button':
            return configureFormDualButton(form, args);
        case 'input':
            return configureFormInput(form, args);
    }
    assertNever(form);
};
const renderForm = async (player, formHub, form, args) => {
    const dialogue = configureForm(form, args);
    const response = await dialogue.open({ player });
    if (response instanceof ButtonDialogueResponse) {
        if (form.type === 'multi-button') {
            const multiButtonForm = form;
            const selected = parseInt(response.selected);
            return new FormEventProducer(formHub, multiButtonForm.elements[selected].action, args);
        }
        else if (form.type === 'dual-button') {
            const dualButtonForm = form;
            if (response.selected === 'top') {
                return new FormEventProducer(formHub, dualButtonForm.topButton.action, args);
            }
            else if (response.selected === 'bottom') {
                return new FormEventProducer(formHub, dualButtonForm.bottomButton.action, args);
            }
        }
    }
    else if (response instanceof InputScriptDialogueResponse) {
        const inputForm = form;
        const event = new FormEventProducer(formHub, {
            ...inputForm.action,
            setArgs: {
                ...inputForm.action?.setArgs,
                ...response.values,
            },
        }, args);
        return event;
    }
    return new FormEventProducer(formHub);
};
const renderLoop = async (player, formHub, receiver) => {
    const initialProducer = FormEventProducer.fromFormHub(formHub);
    let currentForm = await triggerEvent(initialProducer, receiver);
    let args = initialProducer.args;
    while (currentForm !== undefined) {
        const eventProducer = await renderForm(player, formHub, currentForm, args);
        currentForm = await triggerEvent(eventProducer, receiver);
        args = eventProducer.args;
    }
};

const CHARS_PER_LINE = 40;
const printContentFavoriteEmail = (title, content, computer, paper) => {
    const printedPaper = new ItemStack(paper, 1);
    printedPaper.nameTag = title;
    writeContent(printedPaper, content);
    return printedPaper;
};
const showUIError = async (player, screen) => {
    let shouldCloseApp = false;
    await lockMovementWhile(player, () => {
        return renderLoop(player, { ...ui$7, entrypoint: screen }, {
            close_app: async () => {
                shouldCloseApp = true;
            }
        });
    });
    return shouldCloseApp;
};
const printContent = async (title, content, computer, player, paper) => {
    computer?.computer.triggerEvent('jig_ccomp:typing');
    const printers = (computer?.computer ?? player).dimension.getEntities({
        families: ["jig_ccomp:printer"],
        closest: 1,
        maxDistance: 10,
        location: (computer?.computer ?? player).location
    });
    if (printers.length === 0) {
        if (computer !== undefined) {
            computer?.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:printer_none`);
        }
        else {
            if (await showUIError(player, "printer_none")) {
                return 'quit';
            }
        }
        debug("Could not find a printer");
        return;
    }
    const printer = printers[0];
    const container = printer.getComponent(EntityInventoryComponent.componentId).container;
    const hasEmptySpace = container.emptySlotsCount > 0;
    const paperSlot = getSlotByCondition(container, (item) => {
        if (item.typeId === "minecraft:paper" && item.getLore().length === 0) {
            return hasEmptySpace || item.amount === 1;
        }
        return false;
    });
    if (paperSlot === undefined) {
        if (hasEmptySpace) {
            if (computer !== undefined) {
                computer?.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:printer_pape`);
            }
            else {
                if (await showUIError(player, "printer_paper")) {
                    return 'quit';
                }
            }
            debug("The printer is out of paper");
        }
        else {
            if (computer !== undefined) {
                computer?.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:printer_full`);
            }
            else {
                if (await showUIError(player, "printer_full")) {
                    return 'quit';
                }
            }
            debug("Found no space to put the new paper");
        }
        return;
    }
    const item = container.getItem(paperSlot);
    const printedPaper = new ItemStack(paper, 1);
    if (item.amount === 1) {
        container.setItem(paperSlot);
    }
    else {
        item.amount = item.amount - 1;
        container.setItem(paperSlot, item);
    }
    printedPaper.nameTag = title;
    if (content?.trim()) {
        writeContent(printedPaper, content);
    }
    printer.triggerEvent('jig_ccomp:printing');
    const emptySlot = getEmptySlot(container);
    container.setItem(emptySlot, printedPaper);
    player.sendMessage(TRANSLATE$1("jig_ccomp:print.job.sent"));
    return Promise.resolve(printedPaper);
};
const writeContent = (paper, content) => {
    const loreList = [];
    content.split("\n").forEach(line => {
        do {
            const result = getNextLine(line);
            line = result[1];
            loreList.push(result[0]);
        } while (line.length > 0);
    });
    paper.setLore(loreList);
};
const getNextLine = (content) => {
    let nextLine = '';
    const words = content.split(' ');
    while (words.length > 0) {
        if (nextLine.length + words[0].length <= CHARS_PER_LINE) {
            nextLine = `${nextLine} ${words.shift()}`.trim();
        }
        else if (words[0].length > CHARS_PER_LINE) {
            nextLine = `${nextLine} ${words[0].substring(0, CHARS_PER_LINE)}`.trim();
            words[0] = words[0].substring(CHARS_PER_LINE);
        }
        else {
            break;
        }
    }
    return [nextLine, words.join(' ')];
};
const ui$7 = {
    entrypoint: 'printer_none',
    forms: {
        printer_none: {
            type: 'multi-button',
            title: _('jig_ccomp:printer.error'),
            body: _('jig_ccomp:printer_none', "\n\n", "\n\n"),
            elements: [
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.back'),
                    action: {
                        form: 'main',
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.close'),
                    action: {
                        event: 'close_app',
                    }
                }
            ]
        },
        printer_paper: {
            type: 'multi-button',
            title: _('jig_ccomp:printer.error'),
            body: _('jig_ccomp:printer_pape', "\n\n", "\n\n"),
            elements: [
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.back'),
                    action: {
                        form: 'main',
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.close'),
                    action: {
                        event: 'close_app',
                    }
                }
            ]
        },
        printer_full: {
            type: 'multi-button',
            title: _('jig_ccomp:printer.error'),
            body: _('jig_ccomp:printer_full', "\n\n", "\n\n"),
            elements: [
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.back'),
                    action: {
                        form: 'main',
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.close'),
                    action: {
                        event: 'close_app',
                    }
                }
            ]
        },
    }
};

const GET_PROP = (target, identifier, defaultValue) => {
    const value = target.getDynamicProperty(identifier);
    if (typeof value === 'string') {
        return JSON.parse(value);
    }
    if (defaultValue) {
        return defaultValue;
    }
    const message = `Invalid identifier ${identifier}`;
    debug(message);
    throw new Error(message);
};
const SET_PROP = (target, identifier, value) => {
    target.setDynamicProperty(identifier, JSON.stringify(value));
};
// export const mutateDynamicProperty = <T>(target: WithDynamicProperty, identifier: string, mutator: DynamicPropertyMutator<T>) => {
//   const input = target.getDynamicProperty(identifier);
//   const output = mutator(typeof input === 'string' ? JSON.parse(input) : undefined);
//   target.setDynamicProperty(identifier, JSON.stringify(output));
// }
//
// export class DynamicPropertyContext<T> {
//   private _value: T;
//   private target: WithDynamicProperty;
//   private identifier: string;
//
//   constructor(target: WithDynamicProperty, identifier: string, defaultValue: T) {
//     this.target = target;
//     this.identifier = identifier;
//     const value = target.getDynamicProperty(identifier);
//     this._value = typeof value === 'string' ? JSON.parse(value) : undefined;
//   }
//
//   public get value() {
//     return this._value;
//   }
//
//   private set value(value: T) {
//     this._value = value;
//   }
//
//   mutate(mutator: DynamicPropertyMutator<T>) {
//     this.value = mutator(this.value);
//   }
//
//   commit() {
//     this.target.setDynamicProperty(this.identifier, JSON.stringify(this.value));
//   }
// }

const settingsMenuDialogue = async (player, descriptor, settings, prefix) => {
    const elements = Object.keys(descriptor)
        .filter((key) => !("hidden" in descriptor[key]) || !descriptor[key].hidden)
        .map((key) => {
        const labelKey = `${prefix}.setting.${key}`;
        const params = descriptor[key].labelParams ?? [];
        const label = TRANSLATE(labelKey, ...params);
        const setting = descriptor[key];
        switch (setting.kind) {
            case "dropdown": {
                let dropdown = inputDropdown(key, label);
                setting.options.forEach((o) => {
                    dropdown = dropdown.addOption(TRANSLATE(`${labelKey}.${o}`), o);
                });
                return dropdown.setDefaultValueIndex(setting.options.indexOf(settings[key] ?? setting.value));
            }
            case "toggle":
                return inputToggle(key, label, !!settings[key]);
            case "slider":
                return inputSlider(key, label, setting.min, setting.max, setting.step, settings[key] ?? setting.value);
            case "submenu":
                return inputToggle(key, label, false);
            case "external":
                return inputToggle(key, label, false);
        }
    });
    return await inputScriptDialogue(TRANSLATE(`${prefix}.title`))
        .addElements(elements)
        .open({ player });
};
class SettingSubmenu {
    descriptor;
    settings;
    constructor(descriptor, settings) {
        this.descriptor = descriptor;
        this.settings = settings;
    }
    getBoolean(key) {
        return this.settings[key];
    }
    getString(key) {
        return this.settings[key];
    }
    getNumber(key) {
        return this.settings[key];
    }
}
let Settings$1 = class Settings {
    target;
    propIdentifier;
    descriptor;
    options;
    keys;
    listeners = [];
    constructor(target, propIdentifier, descriptor, options = {}) {
        this.target = target;
        this.propIdentifier = propIdentifier;
        this.descriptor = descriptor;
        this.options = options;
        this.keys = Object.keys(descriptor);
        const scriptEventMap = {};
        for (const key in descriptor) {
            const setting = descriptor[key];
            if (setting.kind === "toggle") {
                if (setting.toggleOnScriptEvent) {
                    if (setting.toggleOnScriptEvent in scriptEventMap) {
                        scriptEventMap[setting.toggleOnScriptEvent].add(key);
                    }
                    else {
                        scriptEventMap[setting.toggleOnScriptEvent] = new Set(key);
                    }
                }
                if (setting.toggleOffScriptEvent) {
                    if (setting.toggleOffScriptEvent in scriptEventMap) {
                        scriptEventMap[setting.toggleOffScriptEvent].add(key);
                    }
                    else {
                        scriptEventMap[setting.toggleOffScriptEvent] = new Set(key);
                    }
                }
            }
        }
        system.afterEvents.scriptEventReceive.subscribe((event) => {
            if (event.id in scriptEventMap) {
                const keys = scriptEventMap[event.id];
                for (const key of keys) {
                    const setting = descriptor[key];
                    if ("toggleOnScriptEvent" in setting && setting.toggleOnScriptEvent === event.id) {
                        this.setBoolean(key, true);
                    }
                    else if ("toggleOffScriptEvent" in setting && setting.toggleOffScriptEvent === event.id) {
                        this.setBoolean(key, false);
                    }
                }
            }
        });
    }
    getBoolean(key) {
        return this.getSettings()[key];
    }
    getString(key) {
        return this.getSettings()[key];
    }
    getNumber(key) {
        return this.getSettings()[key];
    }
    getSubmenu(key) {
        if (this.descriptor[key].kind !== "submenu") {
            throw new Error(`Invalid key for submenu setting ${String(key)}`);
        }
        return new SettingSubmenu(this.descriptor[key].options, this.getSettings()[key]);
    }
    setBoolean(key, value) {
        const settings = this.getSettings();
        settings[key] = value;
        this.updateSettings(settings);
    }
    setString(key, value) {
        const settings = this.getSettings();
        settings[key] = value;
        this.updateSettings(settings);
    }
    getSettings() {
        const settings = GET_PROP(this.target, this.propIdentifier, {});
        this.internalProcessSettings(this.descriptor, settings);
        return settings;
    }
    async open(player) {
        const currentSettings = this.getSettings();
        if (this.options.onOpen) {
            this.options.onOpen(player, currentSettings);
        }
        const mutableSettings = JSON.parse(JSON.stringify(currentSettings));
        const response = await this.openDescriptor(player, this.propIdentifier, this.descriptor, currentSettings, [], mutableSettings, this.options.shouldOpenSubmenu, this.options.openExternal);
        if (response) {
            this.updateSettings(response);
            if (this.options.onSave) {
                this.options.onSave(player, response);
            }
        }
    }
    subscribeOnSettingsChange(listener) {
        this.listeners.push(listener);
        return listener;
    }
    unsubscribeOnSettingsChange(listener) {
        const index = this.listeners.indexOf(listener);
        if (index !== -1) {
            this.listeners.splice(index, 1);
        }
    }
    internalProcessSettings(descriptor, settings) {
        for (const key in descriptor) {
            if (descriptor[key].kind === "submenu") {
                if (settings[key] === undefined || typeof settings[key] !== "object") {
                    settings[key] = {};
                }
                this.internalProcessSettings(descriptor[key].options, settings[key]);
            }
            else if (descriptor[key].kind === "external") ;
            else if (settings[key] === undefined || typeof settings[key] !== typeof descriptor[key].value) {
                settings[key] = descriptor[key].value;
            }
        }
    }
    async openDescriptor(player, prefix, descriptor, settings, keypath, mutableSettings, shouldOpenSubmenu, openExternal) {
        const response = await settingsMenuDialogue(player, descriptor, settings, prefix);
        const submenus = {};
        const external = {};
        if (response instanceof InputScriptDialogueResponse) {
            const values = { ...response.values };
            for (const key in descriptor) {
                if (descriptor[key].kind === "submenu") {
                    if (values[key]) {
                        submenus[key] = descriptor[key];
                    }
                    values[key] = settings[key];
                }
                else if (descriptor[key].kind === "external") {
                    if (values[key]) {
                        external[key] = descriptor[key];
                    }
                }
                else {
                    // update mutable settings
                    let current = mutableSettings;
                    keypath.forEach(key => {
                        current = current[key];
                    });
                    current[key] = values[key];
                }
            }
            for (const key in submenus) {
                if (submenus[key]) {
                    let shouldOpen = true;
                    if (shouldOpenSubmenu) {
                        const path = (keypath.length > 0 ? (keypath.join('.') + `.${key}`) : key);
                        shouldOpen = shouldOpenSubmenu(path, player, mutableSettings);
                    }
                    if (shouldOpen) {
                        const subValues = await this.openDescriptor(player, `${prefix}.${key}`, submenus[key].options, values[key], [...keypath, key], mutableSettings, shouldOpenSubmenu, openExternal);
                        if (subValues) {
                            values[key] = subValues;
                        }
                    }
                }
            }
            if (openExternal) {
                for (const key in external) {
                    if (external[key]) {
                        await openExternal(player, key);
                    }
                }
            }
            return values;
        }
        return undefined;
    }
    updateSettings(settings) {
        const old = this.getSettings();
        SET_PROP(this.target, this.propIdentifier, settings);
        this.fireListener(old, settings);
    }
    fireListener(prev, current) {
        for (const key in prev) {
            if (prev[key] !== current[key]) {
                this.listeners.forEach((listener) => listener({
                    old: prev,
                    new: current,
                }));
                break;
            }
        }
    }
};

class PhoneApp {
    _componentId;
    constructor(componentId) {
        this._componentId = componentId;
    }
    get componentId() {
        return this._componentId;
    }
    async onAction(event) {
        event.cancel = false;
        event.closeApp = true;
    }
    async onSelected(event) {
        event.cancel = false;
        event.closeApp = true;
    }
}

const isPhone = (maybePhone) => {
    return maybePhone.typeId.startsWith("jig_ccomp:phone");
};

class SettingsSerializer {
    target;
    constructor(target) {
        this.target = target;
    }
}
class NamespacedSettingsSerializer {
    target;
    constructor(target) {
        this.target = target;
    }
}
class PhoneSettingsSerializer extends SettingsSerializer {
    PHONE_SETTINGS = 'jig_ccomp:settings';
    save(data) {
        SET_PROP$1(this.target, this.PHONE_SETTINGS, data);
    }
    load(defaultData) {
        return GET_PROP$1(this.target, this.PHONE_SETTINGS, defaultData);
    }
    isValid() {
        if (this.target instanceof Entity) {
            return this.target.isValid();
        }
        else if (this.target instanceof ContainerSlot) {
            return this.target.isValid() && this.target.hasItem() && isPhone(this.target);
        }
        return false;
    }
}
class AppSettingsSerializer extends SettingsSerializer {
    dataKey;
    constructor(appId, player) {
        super(player);
        this.dataKey = `jig_ccomp:phone-data-${appId}`;
    }
    save(data) {
        SET_PROP$1(this.target, this.dataKey, data);
    }
    load(defaultValue) {
        return GET_PROP$1(this.target, this.dataKey, defaultValue);
    }
    isValid() {
        return this.target.isValid();
    }
}
class GlobalSettingsSerializer extends SettingsSerializer {
    dataKey;
    constructor(appId, world) {
        super(world);
        this.dataKey = `jig_ccomp:phone-data-${appId}`;
    }
    save(data) {
        SET_PROP$1(this.target, this.dataKey, data);
    }
    load(defaultValue) {
        return GET_PROP$1(this.target, this.dataKey, defaultValue);
    }
    isValid() {
        return true; // The world is always valid
    }
}
class GlobalNamespacedSettingsSerializer extends NamespacedSettingsSerializer {
    dataKey;
    constructor(appId, world, prefix = '') {
        super(world);
        if (prefix.length > 0) {
            prefix = '-' + prefix;
        }
        this.dataKey = `jig_ccomp:namespaced-phone-data-${appId}${prefix}`;
    }
    getKey(namespace) {
        return `${this.dataKey}-${namespace}`;
    }
    save(namespace, data) {
        SET_PROP$1(this.target, this.getKey(namespace), data);
    }
    load(namespace, defaultValue) {
        return GET_PROP$1(this.target, this.getKey(namespace), defaultValue);
    }
    isValid() {
        return true; // The world is always valid
    }
}
class Settings {
    serializer;
    constructor(serializer) {
        this.serializer = serializer;
    }
    ensureValid() {
        if (!this.serializer.isValid()) {
            const message = `Tried to use an invalid target.`;
            debug(message, 'phone');
            throw new Error(message);
        }
    }
    getData(defaultData) {
        return this.serializer.load(defaultData);
    }
    setData(data) {
        this.serializer.save(data);
    }
}
class NamespacedSettings {
    serializer;
    constructor(serializer) {
        this.serializer = serializer;
    }
    ensureValid() {
        if (!this.serializer.isValid()) {
            const message = `Tried to use an invalid target.`;
            debug(message, 'phone');
            throw new Error(message);
        }
    }
    getData(namespace, defaultData) {
        return this.serializer.load(namespace, defaultData);
    }
    setData(namespace, data) {
        this.serializer.save(namespace, data);
    }
}
class GlobalSettings extends Settings {
}
class NamespacedGlobalSettings extends NamespacedSettings {
}
class AppSettings extends Settings {
}
class PhoneSettings extends Settings {
    getPhoneSettingsData() {
        return this.getData({
            appsIds: [
                'appstore'
            ],
            activeApp: undefined,
            apps: {},
            appSettings: {}
        });
    }
    getAppIds() {
        return this.getPhoneSettingsData().appsIds;
    }
    getActiveApp() {
        return this.getPhoneSettingsData().activeApp;
    }
    setActiveApp(appId) {
        this.setData({
            ...this.getPhoneSettingsData(),
            activeApp: appId
        });
    }
    addApp(appId) {
        const oldData = this.getPhoneSettingsData();
        if (!oldData.appsIds.includes(appId)) {
            oldData.appsIds.push(appId);
            this.setData({
                ...oldData,
                appsIds: oldData.appsIds,
            });
            return true;
        }
        return false;
    }
    setVolume(volume, appId) {
        const oldData = this.getPhoneSettingsData();
        if (!('appSettings' in oldData)) {
            oldData.appSettings = {};
        }
        oldData.appSettings[appId] = { volume: volume };
        this.setData({
            ...oldData,
            appSettings: oldData.appSettings
        });
    }
    getVolume(appId) {
        return (this.getPhoneSettingsData()?.appSettings?.[appId]?.volume ?? 50) / 100;
    }
    removeApp(appId) {
        const oldData = this.getPhoneSettingsData();
        if (oldData.appsIds.includes(appId)) {
            this.setData({
                ...oldData,
                appsIds: oldData.appsIds.filter(a => a !== appId),
            });
        }
    }
    setMessages(messages, appId) {
        const oldData = this.getPhoneSettingsData();
        oldData.appSettings[appId] = { volume: oldData.appSettings[appId]?.volume ?? 0, messages: messages };
        this.setData({
            ...oldData,
            appSettings: oldData.appSettings
        });
    }
    getMessages(appId) {
        return this.getPhoneSettingsData().appSettings[appId]?.messages ?? 10;
    }
}

const CONTACT_APP_COMPONENT_ID = 'contacts';
const CONTACT_APP_NAMESPACE = 'jig_app:';
class Contacts {
    owner;
    contacts = new NamespacedGlobalSettings(new GlobalNamespacedSettingsSerializer(CONTACT_APP_COMPONENT_ID, world, 'player'));
    constructor(owner) {
        this.owner = owner;
    }
    getDefault() {
        return {
            contacts: []
        };
    }
    getAllContacts() {
        return this.contacts.getData(this.owner, this.getDefault()).contacts;
    }
    getPlayerContacts() {
        return this.getAllContacts().filter(c => !c.startsWith(CONTACT_APP_NAMESPACE));
    }
    getAppContacts() {
        return this.getAllContacts().filter(c => c.startsWith(CONTACT_APP_NAMESPACE));
    }
    addContact(contact) {
        const data = this.contacts.getData(this.owner, this.getDefault());
        if (data.contacts.includes(contact)) {
            return false;
        }
        data.contacts.push(contact);
        this.contacts.setData(this.owner, data);
        return true;
    }
}

var Direction$1;
(function (Direction) {
    Direction[Direction["RECEIVED"] = 0] = "RECEIVED";
    Direction[Direction["SENT"] = 1] = "SENT";
})(Direction$1 || (Direction$1 = {}));
const getNamespace$1 = (owner, target) => {
    return `${owner}.${target}`;
};
const getOwner = (event) => {
    return event.player.name;
};
const targetToTextContent = (target) => {
    if (target.startsWith(CONTACT_APP_NAMESPACE)) {
        return _(`jig_ccomp:phone.app.${target.slice(CONTACT_APP_NAMESPACE.length)}.name`);
    }
    return target;
};
class MessageApp extends PhoneApp {
    globalSettings;
    settings;
    static COMPONENT_ID = "messages";
    constructor(globalSettings, settings) {
        super(MessageApp.COMPONENT_ID);
        this.globalSettings = globalSettings;
        this.settings = settings;
    }
    async onSelected(event) {
        await this.openApp(event);
    }
    async onAction(event) {
        await this.openApp(event);
    }
    getNamespacedData(owner, target) {
        return this.globalSettings.getData(getNamespace$1(owner, target), {
            owner,
            target,
            messages: [],
            lastReadLength: 0,
        });
    }
    formatMessages(messages, target) {
        let lastDirection;
        const targetTextContent = targetToTextContent(target);
        return messages.reduce((message, entry) => {
            const isSender = entry.direction === Direction$1.SENT;
            const color = isSender ? "§a" : "§7";
            const nameLine = isSender ? "§a§oYou: §r" : [`§7§o`, targetTextContent, `: §r`];
            if (entry.direction !== lastDirection) {
                message.push(nameLine);
                lastDirection = entry.direction;
            }
            message.push([color, entry.content, '§r\n']);
            return message;
        }, []);
    }
    saveNamespacedData(owner, target, data) {
        this.globalSettings.setData(getNamespace$1(owner, target), data);
    }
    async openApp(phoneEvent) {
        phoneEvent.cancel = true;
        await renderLoop(phoneEvent.player, ui$6, {
            close_app: async (event) => {
                phoneEvent.closeApp = true;
            },
            load_main: async (event) => {
                event.form = event.loadForm("main", "multi-button");
                event.form.elements = [
                    event.form.elements[0],
                    ...new Contacts(getOwner(phoneEvent)).getAllContacts().map((t) => {
                        const convo = this.getNamespacedData(getOwner(phoneEvent), t);
                        const visibleMessages = convo.messages;
                        const latestTimestamp = visibleMessages[visibleMessages.length - 1]?.timestamp ?? 0;
                        return { t, convo, latestTimestamp };
                    })
                        .filter(({ latestTimestamp }) => latestTimestamp > 0)
                        .sort((a, b) => {
                        const aUnread = (a.convo.lastReadLength ?? 0) < a.convo.messages.length;
                        const bUnread = (b.convo.lastReadLength ?? 0) < b.convo.messages.length;
                        if (aUnread && !bUnread)
                            return -1; // a is unread, b is read → a comes first
                        if (!aUnread && bUnread)
                            return 1; // a is read, b is unread → b comes first
                        // both same read state → sort by latest timestamp
                        return b.latestTimestamp - a.latestTimestamp;
                    })
                        .map(({ t, convo }) => {
                        const readCount = convo.lastReadLength ?? 0;
                        const unreadCount = Math.max(0, convo.messages.length - readCount);
                        const cappedCount = Math.min(unreadCount, 10);
                        const icon = unreadCount > 0
                            ? `textures/jig/ccomp/phone/apps/messaging_u${cappedCount}`
                            : "textures/jig/ccomp/phone/apps/messaging_r";
                        return {
                            type: "button",
                            text: targetToTextContent(t),
                            icon,
                            action: {
                                event: "load_messages",
                                setArgs: {
                                    player: t,
                                },
                            },
                        };
                    }),
                    event.form.elements[1],
                ];
            },
            load_messages: async (event) => {
                const target = event.args.get("player");
                const data = this.getNamespacedData(getOwner(phoneEvent), target);
                // Mark all messages as read
                data.lastReadLength = data.messages.length;
                this.saveNamespacedData(getOwner(phoneEvent), target, data);
                event.form = event.loadForm("message", "multi-button");
                event.form.title = _("jig_ccomp:phone.app.messages.conversation", targetToTextContent(target));
                const messages = this.settings.getMessages(MessageApp.COMPONENT_ID);
                const visibleMessages = data.messages.slice(-messages);
                const isTruncated = data.messages.length > messages;
                event.form.body = [
                    ...(isTruncated ? ["§7§o...\n§r"] : []),
                    ...this.formatMessages(visibleMessages, target),
                ];
                if (target.startsWith(CONTACT_APP_NAMESPACE)) {
                    event.form.elements.splice(0, 1); // Delete first, Reply.
                }
            },
            delete_conversation: async (event) => {
                const target = event.args.get("player");
                const owner = getOwner(phoneEvent);
                // hide convo
                const convo = this.getNamespacedData(owner, target);
                convo.messages = [];
                convo.lastReadLength = 0;
                this.saveNamespacedData(owner, target, convo);
            },
            confirm_delete: async (event) => {
                event.form = event.loadForm("confirm_delete", "multi-button");
                event.form.body = _("jig_ccomp:phone.app.messages.delete.body", targetToTextContent(event.args.get('player')));
            },
            load_send_message: async (event) => {
                const players = world
                    .getAllPlayers()
                    .map((p) => p.name)
                    .filter((p) => p !== getOwner(phoneEvent));
                if (players.length > 0) {
                    event.form = event.loadForm("select_player", "multi-button");
                    event.form.elements = [
                        ...players.map((p) => ({
                            type: "button",
                            text: p,
                            action: {
                                event: "load_send_message_with_context",
                                setArgs: {
                                    player: p,
                                },
                            },
                        })),
                        event.form.elements[0],
                    ];
                }
                else {
                    event.form = event.loadForm("no_one");
                }
            },
            load_send_message_with_context: async (event) => {
                const player = event.args.get("player");
                const ownerData = this.getNamespacedData(getOwner(phoneEvent), player);
                const visibleMessages = ownerData.messages;
                const context = this.formatMessages(visibleMessages.slice(-4), player);
                const form = event.loadForm("send_message", "input");
                form.title = _("jig_ccomp:phone.app.messages.send.message", targetToTextContent(player));
                if (context.length > 0) {
                    form.elements[0].text = [`§7§o...\n§r`, context, `\n`, _("jig_ccomp:phone.app.messages.message.send")];
                }
                else {
                    form.elements[0].text = _("jig_ccomp:phone.app.messages.message.send");
                }
                event.form = form;
                // Add player to targets if not already there
                new Contacts(getOwner(phoneEvent)).addContact(player);
            },
            send_message: async (event) => {
                const player = event.args.get("player");
                const content = event.args.get("content");
                const owner = getOwner(phoneEvent);
                sendMessagePlayerToPlayer(owner, player, content);
                event.form = event.loadForm("message");
            },
        });
    }
}
const ui$6 = {
    entrypoint: {
        events: "load_main",
    },
    forms: {
        main: {
            type: "multi-button",
            title: _("jig_ccomp:phone.app.messages.name"),
            body: _("jig_ccomp:phone.app.messages.body"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:phone.app.messages.send"),
                    icon: "textures/jig/ccomp/phone/apps/messaging_c",
                    action: {
                        event: "load_send_message",
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:gui.close"),
                    action: {
                        event: "close_app",
                    },
                },
            ],
        },
        message: {
            type: "multi-button",
            title: _("jig_ccomp:phone.app.messages.conversation", "{player}"),
            body: "",
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:phone.app.messages.reply"),
                    icon: "textures/jig/ccomp/phone/apps/messaging_c",
                    action: {
                        event: "load_send_message_with_context",
                        copyArgs: true,
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:phone.app.messages.delete"),
                    icon: "textures/jig/ccomp/phone/apps/messaging_d",
                    action: {
                        event: "confirm_delete",
                        copyArgs: true,
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:gui.back"),
                    action: {
                        event: "load_main",
                    },
                },
            ],
        },
        confirm_delete: {
            type: "multi-button",
            title: _("jig_ccomp:phone.app.messages.delete.title"),
            body: _("jig_ccomp:phone.app.messages.delete.body", "{player}"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:phone.app.messages.delete.confirm"),
                    icon: "textures/jig/ccomp/phone/apps/messaging_d",
                    action: {
                        event: [{ event: "delete_conversation" }, { event: "load_main" }],
                        copyArgs: true,
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:phone.app.messages.delete.dontconfirm"),
                    action: {
                        event: "load_messages",
                        copyArgs: true,
                    },
                },
            ],
        },
        no_one: {
            type: "multi-button",
            title: _("jig_ccomp:phone.app.messages.no_one.title"),
            body: _("jig_ccomp:phone.app.messages.no_one.body"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:gui.back"),
                    action: {
                        event: "load_main",
                    },
                },
            ],
        },
        select_player: {
            type: "multi-button",
            title: _("jig_ccomp:phone.app.messages.start.conversation.title"),
            body: _("jig_ccomp:phone.app.messages.start.conversation.select"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:gui.back"),
                    action: {
                        event: "load_main",
                    },
                },
            ],
        },
        send_message: {
            type: "input",
            title: _("jig_ccomp:phone.app.messages.send.message", "{player}"),
            elements: [
                {
                    type: "text",
                    text: _("jig_ccomp:phone.app.messages.message.send"),
                    placeholder: _("jig_ccomp:phone.app.messages.message.example"),
                    name: "content",
                },
            ],
            action: {
                copyArgs: true,
                event: [
                    {
                        event: "send_message",
                    },
                    {
                        event: "load_messages",
                    },
                ],
            },
        },
    },
};

var Direction;
(function (Direction) {
    Direction[Direction["RECEIVED"] = 0] = "RECEIVED";
    Direction[Direction["SENT"] = 1] = "SENT";
})(Direction || (Direction = {}));
const getNamespace = (owner, target) => `${owner}.${target}`;
const addTarget = (owner, target) => {
    new Contacts(owner).addContact(target);
};
/**
 * Send a message from player fromPlayer to player toPlayer.
 * This is as if the message was send with the message app directly.
 *
 * @param fromPlayer
 * @param toPlayer
 * @param content
 */
const sendMessagePlayerToPlayer = (fromPlayer, toPlayer, content) => {
    const globalSettings = new NamespacedGlobalSettings(new GlobalNamespacedSettingsSerializer(MessageApp.COMPONENT_ID, world));
    const now = Date.now();
    // Store in sender's global data
    const fromData = globalSettings.getData(getNamespace(fromPlayer, toPlayer), {
        owner: fromPlayer,
        target: toPlayer,
        messages: [],
        lastReadLength: 0,
    });
    fromData.messages.push({ content, direction: Direction.SENT, timestamp: now });
    globalSettings.setData(getNamespace(fromPlayer, toPlayer), fromData);
    addTarget(fromPlayer, toPlayer);
    // Store in recipient's global data
    const toData = globalSettings.getData(getNamespace(toPlayer, fromPlayer), {
        owner: toPlayer,
        target: fromPlayer,
        messages: [],
        lastReadLength: 0,
    });
    toData.messages.push({ content, direction: Direction.RECEIVED, timestamp: now });
    globalSettings.setData(getNamespace(toPlayer, fromPlayer), toData);
    addTarget(toPlayer, fromPlayer);
};
/**
 * Sends a system or app message from an arbitrary name (e.g. "BugSmash") to a real player.
 * This omits creating entries in the "fromApp" so its more performant (memory wise) to use this one when you are sending from an app
 */
function sendMessageAppToPlayer(fromApp, toPlayerName, content) {
    const globalSettings = new NamespacedGlobalSettings(new GlobalNamespacedSettingsSerializer(MessageApp.COMPONENT_ID, world));
    const now = Date.now();
    const fromName = `${CONTACT_APP_NAMESPACE}${fromApp}`;
    // Store in recipient's global data
    const toData = globalSettings.getData(getNamespace(toPlayerName, fromName), {
        owner: toPlayerName,
        target: fromName,
        messages: [],
        lastReadLength: 0,
    });
    toData.messages.push({ content, direction: Direction.RECEIVED, timestamp: now });
    globalSettings.setData(getNamespace(toPlayerName, fromName), toData);
    addTarget(toPlayerName, fromName);
}

const DEFAULT_CURRENCIES = ["minecraft:gold_ingot", "minecraft:emerald", "minecraft:diamond"];
const toDisplayName = (typeId) => {
    try {
        const item = new ItemStack(typeId);
        const translated = ITEM(item);
        if (translated.translate) {
            return _(translated.translate);
        }
    }
    catch (e) {
        debug(`Can't find item ${e}`);
    }
    return _(typeId);
};
const currencyCandidatesFromInventory = (player) => {
    const inventory = player.getComponent(EntityInventoryComponent.componentId);
    const size = inventory?.container?.size;
    if (!size) {
        return [];
    }
    const currencies = new Set();
    for (let i = 0; i < size; i++) {
        const item = inventory.container.getItem(i);
        if (item && item.isStackable) {
            currencies.add(item.typeId);
        }
    }
    return [...currencies.values()];
};
const getCurrencyCountFromInventory = (typeId, player) => {
    const inventory = player.getComponent(EntityInventoryComponent.componentId);
    const size = inventory?.container?.size;
    if (!size) {
        return 0;
    }
    let count = 0;
    for (let i = 0; i < size; i++) {
        const item = inventory.container.getItem(i);
        if (item && item.typeId === typeId) {
            count += item.amount;
        }
    }
    return count;
};
const takeFromInventory = (typeId, player, amount) => {
    const inventory = player.getComponent(EntityInventoryComponent.componentId);
    const size = inventory?.container?.size;
    if (!size) {
        return 0;
    }
    let taken = 0;
    for (let i = 0; i < size; i++) {
        const item = inventory.container.getItem(i);
        if (item && item.typeId === typeId) {
            const take = Math.min(amount - taken, item.amount);
            debug(`take: ${take}, amount: ${amount}, taken: ${taken}, item.aount: ${item.amount}`);
            taken += take;
            if (item.amount === take) {
                inventory.container.setItem(i, undefined);
            }
            else {
                item.amount -= take;
                inventory.container.setItem(i, item);
            }
            if (taken >= amount) {
                break;
            }
        }
    }
    return taken;
};
const giveToInventory = (typeId, player, amount) => {
    const inventory = player.getComponent(EntityInventoryComponent.componentId);
    const size = inventory?.container?.size;
    if (!size) {
        return 0;
    }
    let given = 0;
    for (let i = 0; i < size; i++) {
        const item = inventory.container.getItem(i);
        if (item === undefined) {
            const newItem = new ItemStack(typeId);
            const give = Math.min(amount - given, newItem.maxAmount);
            given += give;
            newItem.amount = give;
            inventory.container.setItem(i, newItem);
        }
        else if (item && item.typeId === typeId) {
            const give = Math.min(amount - given, item.maxAmount - item.amount);
            given += give;
            item.amount += give;
            inventory.container.setItem(i, item);
        }
        if (given >= amount) {
            break;
        }
    }
    return given;
};
class BankPlayerSettings {
    owner;
    settings = new NamespacedGlobalSettings(new GlobalNamespacedSettingsSerializer(BankingApp.COMPONENT_ID, world, "player"));
    constructor(owner) {
        this.owner = owner;
    }
    defaultSettings() {
        return {
            balance: {},
        };
    }
    getData() {
        return this.settings.getData(this.owner, this.defaultSettings());
    }
    addBalance(currency, amount) {
        const data = this.getData();
        if (!(currency in data.balance)) {
            data.balance[currency] = 0;
        }
        data.balance[currency] += amount;
        this.settings.setData(this.owner, data);
    }
    getBalances(allowedCurrencies) {
        const balance = this.getData().balance;
        // Delete currencies that have a balance of zero - to prevent showing non-configured currencies or currencies that were removed.
        for (const currency in balance) {
            if (balance[currency] === 0) {
                delete balance[currency];
            }
        }
        // Add allowed currencies as 0
        for (const defaultCurrency of allowedCurrencies) {
            if (!(defaultCurrency in balance)) {
                balance[defaultCurrency] = 0;
            }
        }
        return balance;
    }
    /**
     * Returns balance that is safe to be send or deposit.
     * i.e. currencies that have been approved by the admins
     * It removes from your balances the one that are not in the global settings
     */
    getSafeBalance(allowedCurrencies) {
        const balances = this.getBalances(allowedCurrencies);
        for (const currency in balances) {
            if (!allowedCurrencies.includes(currency)) {
                delete balances[currency];
            }
        }
        return balances;
    }
    transferBalance(currency, to, amount) {
        const data = this.getData();
        const transferAmount = Math.min(amount, data.balance[currency] ?? 0);
        data.balance[currency] -= transferAmount;
        this.settings.setData(this.owner, data);
        const targetData = this.settings.getData(to, this.defaultSettings());
        if (!(currency in targetData.balance)) {
            targetData.balance[currency] = 0;
        }
        targetData.balance[currency] += transferAmount;
        this.settings.setData(to, targetData);
    }
}
class BankingApp extends PhoneApp {
    globalSettings;
    static COMPONENT_ID = "banking";
    constructor(globalSettings) {
        super(BankingApp.COMPONENT_ID);
        this.globalSettings = globalSettings;
    }
    async configure(player) {
        await renderLoop(player, {
            entrypoint: {
                events: "load_main",
            },
            forms: {
                main: {
                    type: "multi-button",
                    title: _("jig_ccomp:phone.apps.banking.admin.main.title"),
                    body: _("jig_ccomp:phone.apps.banking.admin.main.body", _("jig_ccomp:phone.apps.banking.admin.main.add_currency")),
                    elements: [
                        {
                            type: "button",
                            text: _("jig_ccomp:phone.apps.banking.admin.main.add_currency"),
                            icon: "textures/jig/ccomp/phone/apps/bank_b",
                            action: {
                                form: "add",
                                event: "add",
                            },
                        },
                    ],
                },
                add: {
                    type: "multi-button",
                    title: _("jig_ccomp:phone.apps.banking.admin.main.add_currency"),
                    body: _("jig_ccomp:phone.apps.banking.admin.main.add_currency.body"),
                    elements: [
                        {
                            type: "button",
                            text: _("jig_ccomp:cancel"),
                            action: {
                                event: "load_main",
                            },
                        },
                    ],
                },
                remove: {
                    type: "multi-button",
                    title: _("jig_ccomp:phone.apps.banking.admin.main.remove_currency.title"),
                    body: _("jig_ccomp:phone.apps.banking.admin.main.remove_currency.body"),
                    elements: [
                        {
                            type: "button",
                            text: _("jig_ccomp:banking.currency.yes"),
                            icon: "textures/jig/ccomp/phone/apps/bank_b_delete",
                            action: {
                                copyArgs: true,
                                event: [
                                    {
                                        event: "remove_yes",
                                    },
                                    {
                                        event: "load_main",
                                    },
                                ],
                            },
                        },
                        {
                            type: "button",
                            text: _("jig_ccomp:banking.currency.no"),
                            action: {
                                event: "load_main",
                            },
                        },
                    ],
                },
            },
        }, {
            load_main: async (event) => {
                event.form = event.loadForm("main", "multi-button");
                event.form.elements.push(...this.getGlobalData().currencies.map((currency) => ({
                    type: "button",
                    text: toDisplayName(currency),
                    icon: "textures/jig/ccomp/phone/apps/bank_b_delete",
                    action: {
                        form: "remove",
                        event: "remove",
                        eventArgs: [currency],
                    },
                })));
                event.form.elements.push({
                    type: "button",
                    text: "jig_ccomp:close",
                });
            },
            remove: async (event) => {
                event.args.set("currency", event.eventArgs[0]);
            },
            remove_yes: async (event) => {
                const data = this.getGlobalData();
                const currency = event.args.get("currency");
                data.currencies = data.currencies.filter((c) => c !== currency);
                this.globalSettings.setData(data);
            },
            add: async (event) => {
                const data = this.getGlobalData();
                const currencies = currencyCandidatesFromInventory(player).filter((c) => !data.currencies.includes(c));
                event.form = event.loadForm("add", "multi-button");
                event.form.elements.unshift(...currencies.map((c) => ({
                    type: "button",
                    text: toDisplayName(c),
                    icon: "textures/jig/ccomp/phone/apps/bank_b",
                    action: {
                        event: [
                            {
                                event: "add_yes",
                                args: [c],
                            },
                            {
                                event: "load_main",
                            },
                        ],
                    },
                })));
            },
            add_yes: async (event) => {
                const data = this.getGlobalData();
                const currency = event.eventArgs[0];
                data.currencies = data.currencies.filter((c) => c !== currency);
                data.currencies.push(currency);
                this.globalSettings.setData(data);
            },
        });
    }
    async onSelected(event) {
        await this.openApp(event);
    }
    async onAction(event) {
        await this.openApp(event);
    }
    getGlobalData() {
        return this.globalSettings.getData({
            currencies: DEFAULT_CURRENCIES,
        });
    }
    async openApp(phoneEvent) {
        phoneEvent.cancel = true;
        const bankPlayerSettings = new BankPlayerSettings(phoneEvent.player.name);
        await renderLoop(phoneEvent.player, ui$5, {
            close_app: async (_event) => {
                phoneEvent.closeApp = true;
            },
            balance: async (event) => {
                const balance = bankPlayerSettings.getBalances(this.getGlobalData().currencies);
                const keys = Object.keys(balance).filter((k) => balance[k] > 0);
                const removed = keys.filter((c) => !this.getGlobalData().currencies.includes(c));
                if (keys.length === 0) {
                    event.form = event.loadForm("no_balance_view");
                    return;
                }
                const screen = event.loadForm("balance", "multi-button");
                screen.body = [
                    _("jig_ccomp:phone.apps.banking.balance.body"),
                    "\n",
                    "\n",
                    "§6Current Balance:§r\n",
                    ...keys.flatMap((c) => [
                        removed.includes(c) ? "§cNo Longer Depositable-\n" : "",
                        toDisplayName(c), "§r: ", `{balance.${c}}`, "\n"
                    ]),
                ];
                event.form = screen;
                event.args.set("balance", balance);
            },
            deposit: async (event) => {
                debug("calling deposit event");
                event.form = event.loadForm("deposit", "input");
                const data = this.getGlobalData();
                if (data.currencies.length === 0) {
                    event.form = event.loadForm("no_currencies");
                    return;
                }
                const hasAny = data.currencies.some((c) => getCurrencyCountFromInventory(c, phoneEvent.player) > 0);
                if (!hasAny) {
                    const accepted = data.currencies;
                    const screen = event.loadForm("no_deposit_view", "multi-button");
                    screen.body = [
                        _("jig_ccomp:phone.apps.banking.deposit.none"),
                        "\n",
                        ...accepted.flatMap((c) => [toDisplayName(c), "\n"]),
                    ];
                    event.form = screen;
                    return;
                }
                const balance = bankPlayerSettings.getSafeBalance(this.getGlobalData().currencies);
                event.form.elements.push(...Object.keys(balance).map((c) => ({
                    type: "slider",
                    name: c,
                    min: 0,
                    max: getCurrencyCountFromInventory(c, phoneEvent.player),
                    default: 0,
                    step: 1,
                    text: toDisplayName(c),
                })));
            },
            deposit_process: async (event) => {
                const args = event.args.getAll();
                const oldBalance = bankPlayerSettings.getBalances(this.getGlobalData().currencies);
                const diffs = [];
                for (const [key, value] of Object.entries(args)) {
                    if (typeof value === "number" && value > 0) {
                        const taken = takeFromInventory(key, phoneEvent.player, value);
                        if (taken > 0) {
                            bankPlayerSettings.addBalance(key, taken);
                        }
                    }
                }
                const newBalance = bankPlayerSettings.getBalances(this.getGlobalData().currencies);
                for (const currency of Object.keys(newBalance)) {
                    const oldAmount = oldBalance[currency] ?? 0;
                    const newAmount = newBalance[currency];
                    const diff = newAmount - oldAmount;
                    if (diff !== 0) {
                        const sign = diff > 0 ? "§a+" : "§c";
                        diffs.push(sign + diff + " ", toDisplayName(currency), "\n");
                    }
                }
                if (diffs.length === 0) {
                    diffs.push(_("jig_ccomp:phone.apps.banking.no_changes"), "\n");
                }
                const keys = Object.keys(newBalance).filter((k) => newBalance[k] > 0);
                const removed = keys.filter((c) => !this.getGlobalData().currencies.includes(c));
                const screen = event.loadForm("balance", "multi-button");
                screen.body = [
                    _("jig_ccomp:phone.apps.banking.updated.body"),
                    "\n",
                    "\n",
                    _("jig_ccomp:phone.apps.banking.transaction.change"),
                    ...diffs,
                    "\n",
                    _("jig_ccomp:phone.apps.banking.transaction.balance"),
                    ...keys.flatMap((c) => [
                        removed.includes(c) ? "§cNo Longer Depositable-\n" : "",
                        toDisplayName(c), "§r: ", `{balance.${c}}`, "\n"
                    ]),
                ];
                event.form = screen;
                event.args.set("balance", newBalance);
            },
            retrieve: async (event) => {
                const balance = Object.fromEntries(Object.entries(bankPlayerSettings.getBalances(this.getGlobalData().currencies)).filter((v) => v[1] > 0));
                const hasBalance = Object.values(balance).length > 0;
                if (!hasBalance) {
                    event.form = event.loadForm("no_balance");
                    return;
                }
                const removed = Object.keys(balance).filter((c) => !this.getGlobalData().currencies.includes(c));
                event.form = event.loadForm("retrieve", "input");
                event.form.elements.push(...Object.keys(balance).map((c) => ({
                    type: "slider",
                    name: c,
                    min: 0,
                    max: balance[c],
                    default: 0,
                    step: 1,
                    text: removed.includes(c) ? ["§cNo Longer Depositable-\n", toDisplayName(c), "§r"] : toDisplayName(c),
                })));
            },
            retrieve_process: async (event) => {
                const args = event.args.getAll();
                const oldBalance = bankPlayerSettings.getBalances(this.getGlobalData().currencies);
                const diffs = [];
                for (const [key, value] of Object.entries(args)) {
                    if (typeof value === "number" && value > 0) {
                        const given = giveToInventory(key, phoneEvent.player, value);
                        if (given > 0) {
                            bankPlayerSettings.addBalance(key, -given);
                        }
                    }
                }
                const newBalance = bankPlayerSettings.getBalances(this.getGlobalData().currencies);
                for (const currency of Object.keys(newBalance)) {
                    const oldAmount = oldBalance[currency] ?? 0;
                    const newAmount = newBalance[currency];
                    const diff = newAmount - oldAmount;
                    if (diff !== 0) {
                        const sign = diff > 0 ? "§a+" : "§c";
                        diffs.push(sign + diff + " ", toDisplayName(currency), "\n");
                    }
                }
                if (diffs.length === 0) {
                    diffs.push(_("jig_ccomp:phone.apps.banking.no_changes"), "\n");
                }
                const keys = Object.keys(newBalance).filter((k) => newBalance[k] > 0);
                const removed = keys.filter((c) => !this.getGlobalData().currencies.includes(c));
                const screen = event.loadForm("balance", "multi-button");
                screen.body = [
                    _("jig_ccomp:phone.apps.banking.updated.body"),
                    "\n",
                    "\n",
                    _("jig_ccomp:phone.apps.banking.transaction.change"),
                    ...diffs,
                    "\n",
                    _("jig_ccomp:phone.apps.banking.transaction.balance"),
                    ...keys.flatMap((c) => [
                        removed.includes(c) ? "§cNo Longer Depositable-\n" : "",
                        toDisplayName(c), "§r: ", `{balance.${c}}`, "\n"
                    ]),
                ];
                event.form = screen;
                event.args.set("balance", newBalance);
            },
            load_transfer: async (event) => {
                event.form = event.loadForm("transfer", "multi-button");
                const owner = phoneEvent.player.name;
                const contacts = new Contacts(owner);
                const players = new Set(contacts.getPlayerContacts());
                world
                    .getPlayers()
                    .map((p) => p.name)
                    .filter((p) => p !== owner)
                    .forEach((p) => players.add(p));
                event.form.elements.unshift(...[...players].map((p) => ({
                    type: "button",
                    text: p,
                    icon: "textures/jig/ccomp/phone/apps/bank_t",
                    action: {
                        event: "transfer_start",
                        setArgs: {
                            __player: p,
                        },
                    },
                })));
            },
            transfer_start: async (event) => {
                const rawBalances = bankPlayerSettings.getBalances(this.getGlobalData().currencies);
                const safe = this.getGlobalData().currencies;
                const balance = Object.fromEntries(Object.entries(rawBalances).filter(([_, v]) => v > 0));
                const hasBalance = Object.values(balance).length > 0;
                if (!hasBalance) {
                    event.form = event.loadForm("no_transfer_view");
                    return;
                }
                event.form = event.loadForm("transfer_start", "input");
                const removed = Object.keys(balance).filter((c) => !safe.includes(c));
                event.form.elements.push(...Object.keys(balance).map((c) => ({
                    type: "slider",
                    name: c,
                    min: 0,
                    max: balance[c],
                    default: 0,
                    step: 1,
                    text: removed.includes(c) ? ["§cNo Longer Depositable-\n", toDisplayName(c), "§r"] : toDisplayName(c),
                })));
            },
            transfer_process: async (event) => {
                const args = event.args.getAll();
                const target = event.args.get("__player").toString();
                const oldBalance = bankPlayerSettings.getBalances(this.getGlobalData().currencies);
                const diffs = [];
                for (const [key, value] of Object.entries(args)) {
                    if (key === "__player")
                        continue;
                    if (typeof value === "number" && value > 0) {
                        bankPlayerSettings.transferBalance(key, target, value);
                        sendMessageAppToPlayer(BankingApp.COMPONENT_ID, target, _("jig_ccomp:phone.apps.banking.messages.send_currency", phoneEvent.player.name, value.toString(), toDisplayName(key)));
                    }
                }
                const newBalance = bankPlayerSettings.getBalances(this.getGlobalData().currencies);
                for (const currency of Object.keys(newBalance)) {
                    const oldAmount = oldBalance[currency] ?? 0;
                    const newAmount = newBalance[currency];
                    const diff = newAmount - oldAmount;
                    if (diff !== 0) {
                        const sign = diff > 0 ? "§a+" : "§c";
                        diffs.push(sign + diff + " ", toDisplayName(currency), "\n");
                    }
                }
                if (diffs.length === 0) {
                    diffs.push(_("jig_ccomp:phone.apps.banking.no_changes"), "\n");
                }
                const keys = Object.keys(newBalance).filter((k) => newBalance[k] > 0);
                const removed = keys.filter((c) => !this.getGlobalData().currencies.includes(c));
                const screen = event.loadForm("balance", "multi-button");
                screen.body = [
                    _("jig_ccomp:phone.apps.banking.updated.body"),
                    "\n",
                    "\n",
                    _("jig_ccomp:phone.apps.banking.transaction.transferred"),
                    ...diffs,
                    "\n",
                    _("jig_ccomp:phone.apps.banking.transaction.balance"),
                    ...keys.flatMap((c) => [
                        removed.includes(c) ? "§cNo Longer Depositable-\n" : "",
                        toDisplayName(c), "§r: ", `{balance.${c}}`, "\n"
                    ]),
                ];
                event.form = screen;
                event.args.set("balance", newBalance);
            },
        });
    }
}
const ui$5 = {
    entrypoint: "main",
    forms: {
        main: {
            type: "multi-button",
            title: _("jig_ccomp:phone.apps.banking.main.title"),
            body: _("jig_ccomp:phone.apps.banking.main.body"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:phone.apps.banking.main.balance"),
                    icon: "textures/jig/ccomp/phone/apps/bank_b",
                    action: {
                        event: "balance",
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:phone.apps.banking.main.deposit"),
                    icon: "textures/jig/ccomp/phone/apps/bank_d",
                    action: {
                        event: "deposit",
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:phone.apps.banking.main.retrieve"),
                    icon: "textures/jig/ccomp/phone/apps/bank_w",
                    action: {
                        event: "retrieve",
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:phone.apps.banking.main.transfer"),
                    icon: "textures/jig/ccomp/phone/apps/bank_t",
                    action: {
                        event: "load_transfer",
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:phone.apps.banking.main.close"),
                    action: {
                        event: "close_app",
                    },
                },
            ],
        },
        no_currencies: {
            type: "multi-button",
            title: _("jig_ccomp:phone.apps.banking.main.no_currencies.title"),
            body: _("jig_ccomp:phone.apps.banking.main.no_currencies.body"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:gui.back"),
                    action: {
                        form: "main",
                        event: "load_main",
                    },
                },
            ],
        },
        no_balance: {
            type: "multi-button",
            title: _("jig_ccomp:phone.apps.banking.main.no_balance.title"),
            body: _("jig_ccomp:phone.apps.banking.main.no_balance.body"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:gui.back"),
                    action: {
                        form: "main",
                        event: "load_main",
                    },
                },
            ],
        },
        no_balance_view: {
            type: "multi-button",
            title: _("jig_ccomp:phone.apps.banking.no.balance.title"),
            body: _("jig_ccomp:phone.apps.banking.balance.none"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:gui.back"),
                    action: {
                        form: "main",
                        event: "load_main",
                    },
                },
            ],
        },
        balance: {
            type: "multi-button",
            title: _("jig_ccomp:phone.apps.banking.balance.title"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:gui.back"),
                    action: {
                        form: "main",
                    },
                },
            ],
        },
        deposit: {
            type: "input",
            title: _("jig_ccomp:phone.apps.banking.deposit.title"),
            submit: _("jig_ccomp:phone.apps.banking.deposit.submit"),
            elements: [],
            action: {
                form: "main",
                event: "deposit_process",
            },
        },
        no_deposit_view: {
            type: "multi-button",
            title: _("jig_ccomp:phone.apps.banking.deposit.title"),
            body: _("jig_ccomp:phone.apps.banking.deposit.none"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:gui.back"),
                    action: {
                        form: "main",
                        event: "load_main",
                    },
                },
            ],
        },
        retrieve: {
            type: "input",
            title: _("jig_ccomp:phone.apps.banking.retrieve.title"),
            submit: _("jig_ccomp:phone.apps.banking.retrieve.submit"),
            elements: [],
            action: {
                form: "main",
                event: "retrieve_process",
            },
        },
        transfer: {
            type: "multi-button",
            title: _("jig_ccomp:phone.apps.banking.transfer.title"),
            body: _("jig_ccomp:phone.apps.banking.transfer.body"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:gui.back"),
                    action: {
                        form: "main",
                    },
                },
            ],
        },
        no_transfer_view: {
            type: "multi-button",
            title: _("jig_ccomp:phone.apps.banking.transfer.title"),
            body: _("jig_ccomp:phone.apps.banking.transfer.none"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:gui.back"),
                    action: {
                        form: "main",
                        event: "load_main",
                    },
                },
            ],
        },
        transfer_start: {
            type: "input",
            title: _("jig_ccomp:phone.apps.banking.transfer.title"),
            submit: _("jig_ccomp:phone.apps.banking.transfer.submit"),
            elements: [],
            action: {
                form: "main",
                event: [
                    {
                        event: "transfer_process",
                    },
                    {
                        event: "load_main",
                    },
                ],
                copyArgs: true,
            },
        },
    },
};

class NotesApp extends PhoneApp {
    settings;
    static COMPONENT_ID = 'notes';
    constructor(settings) {
        super(NotesApp.COMPONENT_ID);
        this.settings = settings;
    }
    async onSelected(event) {
        await this.openApp(event);
    }
    async onAction(event) {
        await this.openApp(event);
    }
    getData() {
        return this.settings.getData({
            notes: []
        });
    }
    addNote(note) {
        const appData = this.getData();
        appData.notes.push(note);
        this.settings.setData(appData);
    }
    updateNote(note) {
        const appData = this.getData();
        appData.notes = appData.notes.map(n => {
            if (n.id === note.id) {
                return note;
            }
            return n;
        });
        this.settings.setData(appData);
    }
    deleteNote(noteId) {
        const appData = this.getData();
        appData.notes = appData.notes.filter(n => n.id !== noteId);
        this.settings.setData(appData);
    }
    async openApp(event) {
        event.cancel = true;
        while (true) {
            const response = await notes(event.player, this.getData().notes);
            if (response instanceof ButtonDialogueResponse) {
                if (response.selected === "close-app") {
                    event.closeApp = true;
                    break;
                }
                else if (response.selected === "add") {
                    const newNote = await noteEdit(event.player, {
                        id: makeRandomId(),
                        title: '',
                        content: '',
                    });
                    if (newNote) {
                        this.addNote(newNote);
                    }
                }
                else {
                    const index = parseInt(response.selected.split('.')[1]);
                    const note = this.getData().notes[index];
                    const responseView = await noteView(event.player, note);
                    if (responseView instanceof ButtonDialogueResponse) {
                        if (responseView.selected === "edit") {
                            const updatedNote = await noteEdit(event.player, note);
                            if (updatedNote) {
                                this.updateNote(updatedNote);
                            }
                        }
                        else if (responseView.selected === "print") {
                            await printContent(note.title, note.content, undefined, event.player, "jig_ccomp:printed_paper");
                        }
                        else if (responseView.selected === "delete") {
                            this.deleteNote(note.id);
                        }
                        continue;
                    }
                }
                continue;
            }
            break;
        }
    }
}
const notes = async (player, notes) => {
    return await lockMovementWhile(player, async () => {
        return await multiButtonScriptDialogue(TRANSLATE("jig_ccomp:gui.notes.title"))
            .setBody(TRANSLATE("jig_ccomp:gui.notes.body"))
            .addButton('add', TRANSLATE('jig_ccomp:gui.notes.add'), "textures/jig/ccomp/phone/apps/notes_n")
            .addButtons(notes.slice().reverse().map((note, idx) => ({
            name: `note.${notes.length - 1 - idx}`,
            text: note.title,
            iconPath: idx % 2 === 0
                ? "textures/jig/ccomp/phone/apps/notes_a"
                : "textures/jig/ccomp/phone/apps/notes_b",
        })))
            .addButton('close-app', TRANSLATE('jig_ccomp:gui.notes.close'))
            .open({ player });
    });
};
const noteEdit = async (player, note) => {
    const response = await lockMovementWhile(player, async () => {
        return await inputScriptDialogue(TRANSLATE("jig_ccomp:gui.notes.edit"))
            .addElement(inputText("title", TRANSLATE("jig_ccomp:gui.edit.notes.title"), TRANSLATE(""), note.title))
            .addElement(inputText('content', TRANSLATE("jig_ccomp:gui.edit.notes.content"), TRANSLATE(""), note.content))
            .withSubmitButton(TRANSLATE('jig_ccomp:gui.notes.save'))
            .open({ player });
    });
    if (response instanceof InputScriptDialogueResponse) {
        return {
            id: note.id,
            title: response.values.title,
            content: response.values.content,
        };
    }
    return undefined;
};
const noteView = async (player, note) => {
    return await lockMovementWhile(player, async () => {
        return await multiButtonScriptDialogue(TRANSLATE("jig_ccomp:gui.notes.view"))
            .setBody(`${note.title}\n\n${note.content}`)
            .addButton('edit', TRANSLATE("jig_ccomp:gui.notes.edit"), "textures/jig/ccomp/phone/apps/notes_e")
            .addButton('print', TRANSLATE("jig_ccomp:gui.notes.print"), "textures/jig/ccomp/phone/apps/notes_p")
            .addButton('delete', TRANSLATE("jig_ccomp:gui.notes.delete"), "textures/jig/ccomp/phone/apps/notes_d")
            .addButton('back', TRANSLATE("jig_ccomp:gui.notes.back"))
            .open({ player });
    });
};

const JOKES_AMOUNT = 52;
const LAST_SEEN_PROP = "jig_ccomp:last-joke-seen";
const JOKES = Array.from({ length: JOKES_AMOUNT }, (_, i) => {
    const id = String(i + 1).padStart(3, "0");
    return {
        title: `jig_ccomp:joke.${id}`,
        body: `jig_ccomp:joke_${id}.c`,
        punchline: `jig_ccomp:joke_${id}.r`,
    };
});
const getJokeSeed = () => {
    const jokeSeedProp = "jig_ccomp:joke-seed";
    const jokeSeed = GET_RAW_PROP(world, jokeSeedProp);
    if (jokeSeed === undefined) {
        const newJokeSeed = makeRandomNumber(1, 999999999);
        SET_RAW_PROP(world, jokeSeedProp, newJokeSeed);
        return newJokeSeed;
    }
    return jokeSeed;
};
const toStars = (rating) => {
    const wholeStars = Math.floor(rating);
    let blank = 5 - wholeStars;
    let halfStar = false;
    if (rating - wholeStars >= 0.5) {
        halfStar = true;
        blank--;
    }
    let stars = "";
    for (let i = 0; i < wholeStars; i++) {
        stars += "★";
    }
    if (halfStar) {
        stars += "⯪";
    }
    for (let i = 0; i < blank; i++) {
        stars += "☆";
    }
    return stars;
};
const getJokeOfTheDay = () => {
    const jokeStartDayProp = "jig_ccomp:joke-start-day";
    const lastSeenDayProp = "jig_ccomp:last-joke-day";
    const currentDay = world.getDay();
    let startDay = GET_RAW_PROP(world, jokeStartDayProp);
    if (startDay === undefined) {
        startDay = currentDay;
        SET_RAW_PROP(world, jokeStartDayProp, startDay);
    }
    const rawLastSeen = GET_RAW_PROP(world, LAST_SEEN_PROP);
    const rawLastSeenDay = GET_RAW_PROP(world, lastSeenDayProp);
    const lastSeen = typeof rawLastSeen === "number" ? rawLastSeen : -1;
    const lastSeenDay = typeof rawLastSeenDay === "number" ? rawLastSeenDay : -1;
    const nextJokeId = lastSeen + 1;
    // Regular jokes, one per day max
    if (nextJokeId < JOKES.length) {
        if (currentDay > lastSeenDay) {
            // Eligible to unlock next joke
            SET_RAW_PROP(world, LAST_SEEN_PROP, nextJokeId);
            SET_RAW_PROP(world, lastSeenDayProp, currentDay);
            debug(`[JOKES] Advancing to joke ${nextJokeId} on day ${currentDay}`);
            return {
                ...JOKES[nextJokeId],
                id: nextJokeId,
            };
        }
        else {
            // Same day as last viewed, show the same one again
            const fallbackId = Math.max(lastSeen, 0);
            return {
                ...JOKES[fallbackId],
                id: fallbackId,
            };
        }
    }
    // All jokes seen — fallback to seeded random
    const seed = getJokeSeed();
    const index = Math.floor((seed * currentDay) % JOKES.length);
    return {
        ...JOKES[index],
        id: index,
    };
};
class JokeApp extends PhoneApp {
    settings;
    globalSettings;
    phonesettings;
    static COMPONENT_ID = "jokes";
    constructor(settings, globalSettings, phonesettings) {
        super(JokeApp.COMPONENT_ID);
        this.settings = settings;
        this.globalSettings = globalSettings;
        this.phonesettings = phonesettings;
    }
    playHaha(player) {
        const pitch = 0.8 + Math.random() * 0.4;
        const volume = this.phonesettings.getVolume(JokeApp.COMPONENT_ID);
        player.playSound("jig_ccomp.laugh", {
            pitch,
            volume: volume,
        });
    }
    async onSelected(event) {
        this.playHaha(event.player);
        await this.openApp(event);
    }
    async onAction(event) {
        this.playHaha(event.player);
        await this.openApp(event);
    }
    getData() {
        return this.settings.getData({
            rating: {},
        });
    }
    getGlobalData() {
        return this.globalSettings.getData({
            rating: {},
        });
    }
    rateJoke(jokeId, rating) {
        const localRate = this.getData();
        const globalRate = this.getGlobalData();
        if (!(jokeId in globalRate.rating)) {
            globalRate.rating[jokeId] = {
                rate: 0,
                sumRate: 0,
                count: 0,
            };
        }
        if (jokeId in localRate.rating) {
            // Already rated - remove it
            const rate = globalRate.rating[jokeId];
            rate.sumRate -= localRate.rating[jokeId];
            rate.count--;
        }
        localRate.rating[jokeId] = rating;
        globalRate.rating[jokeId].count++;
        globalRate.rating[jokeId].sumRate += rating;
        globalRate.rating[jokeId].rate = globalRate.rating[jokeId].sumRate / globalRate.rating[jokeId].count;
        this.settings.setData(localRate);
        this.globalSettings.setData(globalRate);
    }
    getTopJoke() {
        const ratingsMap = this.getGlobalData().rating;
        const entries = Object.entries(ratingsMap);
        if (entries.length === 0)
            return undefined;
        let [topId, topRating] = entries[0];
        for (const [id, rating] of entries) {
            const isBetter = rating.rate > topRating.rate || (rating.rate === topRating.rate && rating.count > topRating.count);
            if (isBetter) {
                topId = id;
                topRating = rating;
            }
        }
        const jokeId = Number(topId);
        return {
            id: jokeId,
            ...JOKES[jokeId],
            globalRating: toStars(topRating.rate),
            localRating: toStars(this.getData().rating[jokeId]),
        };
    }
    async openApp(phoneEvent) {
        phoneEvent.cancel = true;
        await renderLoop(phoneEvent.player, ui$4, {
            close_app: async (event) => {
                phoneEvent.closeApp = true;
            },
            play_punchline: async (event) => {
                this.playHaha(phoneEvent.player);
            },
            load_joke: async (event) => {
                const joke = getJokeOfTheDay();
                event.args.set("joke", joke);
                const raw = GET_RAW_PROP(world, LAST_SEEN_PROP);
                const currentLastSeen = typeof raw === "number" ? raw : -1;
                if (joke.id > currentLastSeen) {
                    debug(`[JOKES] Marking joke ${joke.id} as seen (was ${currentLastSeen})`);
                    SET_RAW_PROP(world, LAST_SEEN_PROP, joke.id);
                }
            },
            rate_joke: async (event) => {
                const [rating] = event.eventArgs;
                this.rateJoke(event.args.get("joke").id, rating);
            },
            load_top_rated: async (event) => {
                const joke = this.getTopJoke();
                if (joke === undefined) {
                    event.form = event.loadForm("no_top_joke");
                }
                else {
                    event.args.set("joke", joke);
                }
            },
        });
    }
}
const randomInt = makeRandomNumber(1, 9); // assuming this returns inclusive
const ui$4 = {
    entrypoint: "main",
    forms: {
        main: {
            type: "multi-button",
            title: _("jig_ccomp:phone.apps.joke.main.title"),
            body: _(`jig_ccomp:phone.apps.joke.main.body` + [randomInt.toString()]),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:phone.apps.joke.main.joke-of-day"),
                    icon: "textures/jig/ccomp/phone/apps/jokes",
                    action: {
                        event: "load_joke",
                        form: "view_joke_rate_1",
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:phone.apps.joke.main.top-rated"),
                    icon: "textures/jig/ccomp/phone/apps/jokes_rate",
                    action: {
                        event: "load_top_rated",
                        form: "view_top_joke_rate_1",
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:gui.joke.close"),
                    action: {
                        event: "close_app",
                    },
                },
            ],
        },
        view_top_joke_rate_1: {
            type: "multi-button",
            title: _("{joke.title}"),
            body: [
                _("jig_ccomp:phone.apps.joke.global"),
                "{joke.globalRating}",
                "\n",
                _("jig_ccomp:phone.apps.joke.your-rate"),
                "{joke.localRating}",
                "\n",
                "\n",
                _("{joke.body}"),
            ],
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:gui.continue"),
                    icon: "textures/jig/ccomp/phone/apps/jokes_flat",
                    action: {
                        event: [{ event: "play_punchline" }],
                        form: "view_top_joke_rate_2",
                        copyArgs: true,
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:gui.joke.main"),
                    action: {
                        form: "main",
                    },
                },
            ],
        },
        view_top_joke_rate_2: {
            type: "multi-button",
            title: _("{joke.title}"),
            body: [
                _("jig_ccomp:phone.apps.joke.global"),
                "{joke.globalRating}",
                "\n",
                _("jig_ccomp:phone.apps.joke.your-rate"),
                "{joke.localRating}",
                "\n",
                "\n",
                _("{joke.body}"),
                "\n",
                "\n",
                _("{joke.punchline}"),
            ],
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:gui.joke.main"),
                    icon: "textures/jig/ccomp/phone/apps/jokes",
                    action: {
                        form: "main",
                    },
                },
            ],
        },
        view_joke_rate_1: {
            type: "multi-button",
            title: _("{joke.title}"),
            body: _("{joke.body}"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:gui.continue"),
                    icon: "textures/jig/ccomp/phone/apps/jokes_flat",
                    action: {
                        event: [{ event: "play_punchline" }],
                        form: "view_joke_rate_2",
                        copyArgs: true,
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:gui.joke.main"),
                    action: {
                        form: "main",
                    },
                },
            ],
        },
        view_joke_rate_2: {
            type: "multi-button",
            title: _("{joke.title}"),
            body: [_("{joke.body}"), "\n\n", _("{joke.punchline}")],
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:phone.apps.joke.rate-joke"),
                    icon: "textures/jig/ccomp/phone/apps/jokes",
                    action: {
                        form: "view_joke_rate_3",
                        copyArgs: true,
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:gui.joke.main"),
                    action: {
                        form: "main",
                    },
                },
            ],
        },
        view_joke_rate_3: {
            type: "multi-button",
            title: _("jig_ccomp:phone.apps.joke.rate.title"),
            body: _("jig_ccomp:phone.apps.joke.rate.body"),
            elements: [
                {
                    type: "button",
                    text: "★★★★★",
                    icon: "textures/jig/ccomp/phone/apps/jokes_5",
                    action: {
                        event: "rate_joke",
                        eventArgs: [5],
                        copyArgs: true,
                        form: "main",
                    },
                },
                {
                    type: "button",
                    text: "★★★★",
                    icon: "textures/jig/ccomp/phone/apps/jokes_4",
                    action: {
                        event: "rate_joke",
                        eventArgs: [4],
                        copyArgs: true,
                        form: "main",
                    },
                },
                {
                    type: "button",
                    text: "★★★",
                    icon: "textures/jig/ccomp/phone/apps/jokes_3",
                    action: {
                        event: "rate_joke",
                        eventArgs: [3],
                        copyArgs: true,
                        form: "main",
                    },
                },
                {
                    type: "button",
                    text: "★★",
                    icon: "textures/jig/ccomp/phone/apps/jokes_2",
                    action: {
                        event: "rate_joke",
                        eventArgs: [2],
                        copyArgs: true,
                        form: "main",
                    },
                },
                {
                    type: "button",
                    text: "★",
                    icon: "textures/jig/ccomp/phone/apps/jokes_1",
                    action: {
                        event: "rate_joke",
                        eventArgs: [1],
                        copyArgs: true,
                        form: "main",
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:phone.apps.joke.rate.do-not-rate"),
                    action: {
                        form: "main",
                    },
                },
            ],
        },
        no_top_joke: {
            type: "multi-button",
            title: _("jig_ccomp:phone.apps.no-top-rated.title"),
            body: _("jig_ccomp:phone.apps.no-top-rated.body"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:phone.apps.joke.rate.do-not-rate"),
                    action: {
                        form: "main",
                    },
                },
            ],
        },
    },
};

const jigTrivia = [
    {
        "id": "jig_ccomp:jig.question_01_a",
        "number": "01",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:jig.question_02_c",
        "number": "02",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:jig.question_03_b",
        "number": "03",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:jig.question_04_c",
        "number": "04",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:jig.question_05_b",
        "number": "05",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:jig.question_06_a",
        "number": "06",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:jig.question_07_b",
        "number": "07",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:jig.question_08_a",
        "number": "08",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:jig.question_09_c",
        "number": "09",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:jig.question_10_c",
        "number": "10",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:jig.question_11_a",
        "number": "11",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:jig.question_12_b",
        "number": "12",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:jig.question_13_b",
        "number": "13",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:jig.question_14_b",
        "number": "14",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:jig.question_15_b",
        "number": "15",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:jig.question_16_c",
        "number": "16",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:jig.question_17_b",
        "number": "17",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:jig.question_18_a",
        "number": "18",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:jig.question_19_c",
        "number": "19",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:jig.question_20_b",
        "number": "20",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:jig.question_21_a",
        "number": "21",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:jig.question_22_c",
        "number": "22",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:jig.question_23_a",
        "number": "23",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:jig.question_24_c",
        "number": "24",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:jig.question_25_c",
        "number": "25",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:jig.question_26_b",
        "number": "26",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:jig.question_27_c",
        "number": "27",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:jig.question_28_a",
        "number": "28",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:jig.question_29_c",
        "number": "29",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:jig.question_30_c",
        "number": "30",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:jig.question_31_a",
        "number": "31",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:jig.question_32_b",
        "number": "32",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:jig.question_33_c",
        "number": "33",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:jig.question_34_b",
        "number": "34",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:jig.question_35_b",
        "number": "35",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:jig.question_36_c",
        "number": "36",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:jig.question_37_a",
        "number": "37",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:jig.question_38_b",
        "number": "38",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:jig.question_39_a",
        "number": "39",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:jig.question_40_b",
        "number": "40",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:jig.question_41_a",
        "number": "41",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:jig.question_42_c",
        "number": "42",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:jig.question_43_a",
        "number": "43",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:jig.question_44_c",
        "number": "44",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:jig.question_45_a",
        "number": "45",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:jig.question_46_a",
        "number": "46",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:jig.question_47_b",
        "number": "47",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:jig.question_48_c",
        "number": "48",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:jig.question_49_a",
        "number": "49",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:jig.question_50_a",
        "number": "50",
        "answer": "a"
    }
];

const minTrivia = [
    {
        "id": "jig_ccomp:min.question_01_a",
        "number": "01",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:min.question_02_b",
        "number": "02",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:min.question_03_a",
        "number": "03",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:min.question_04_b",
        "number": "04",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:min.question_05_b",
        "number": "05",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:min.question_06_b",
        "number": "06",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:min.question_07_c",
        "number": "07",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_08_c",
        "number": "08",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_09_c",
        "number": "09",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_10_b",
        "number": "10",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:min.question_11_a",
        "number": "11",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:min.question_12_c",
        "number": "12",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_13_b",
        "number": "13",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:min.question_14_a",
        "number": "14",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:min.question_15_c",
        "number": "15",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_16_b",
        "number": "16",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:min.question_17_c",
        "number": "17",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_18_c",
        "number": "18",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_19_c",
        "number": "19",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_20_c",
        "number": "20",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_21_c",
        "number": "21",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_22_b",
        "number": "22",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:min.question_23_c",
        "number": "23",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_24_a",
        "number": "24",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:min.question_25_b",
        "number": "25",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:min.question_26_b",
        "number": "26",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:min.question_27_b",
        "number": "27",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:min.question_28_c",
        "number": "28",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_29_c",
        "number": "29",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_30_b",
        "number": "30",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:min.question_31_a",
        "number": "31",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:min.question_32_b",
        "number": "32",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:min.question_33_c",
        "number": "33",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_34_a",
        "number": "34",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:min.question_35_a",
        "number": "35",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:min.question_36_c",
        "number": "36",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_37_a",
        "number": "37",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:min.question_38_a",
        "number": "38",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:min.question_39_c",
        "number": "39",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_40_c",
        "number": "40",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_41_b",
        "number": "41",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:min.question_42_c",
        "number": "42",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_43_c",
        "number": "43",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_44_b",
        "number": "44",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:min.question_45_c",
        "number": "45",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_46_b",
        "number": "46",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:min.question_47_b",
        "number": "47",
        "answer": "b"
    },
    {
        "id": "jig_ccomp:min.question_48_a",
        "number": "48",
        "answer": "a"
    },
    {
        "id": "jig_ccomp:min.question_49_c",
        "number": "49",
        "answer": "c"
    },
    {
        "id": "jig_ccomp:min.question_50_c",
        "number": "50",
        "answer": "c"
    }
];

var TriviaType;
(function (TriviaType) {
    TriviaType["JIG"] = "jig";
    TriviaType["MIN"] = "min";
})(TriviaType || (TriviaType = {}));
var PrizeType;
(function (PrizeType) {
    PrizeType["GOOD"] = "good";
    PrizeType["BAD"] = "bad";
})(PrizeType || (PrizeType = {}));
const minGoodPrize = ["sculk", "iron_ingot", "diamond", "emerald"];
const minBadPrize = ['stick', 'coal', 'clay_ball', 'wheat_seeds'];
const jigGoodPrize = ["jig_common:redstone_circuit", "netherite_scrap", "sculk", "gold_ingot"];
const jigBadPrize = ['dirt', 'bone', 'rotten_flesh', 'paper'];
const nextTrivia = (selectedTrivia) => {
    if (selectedTrivia === TriviaType.MIN) {
        return minTrivia[Math.floor(Math.random() * minTrivia.length)];
    }
    else if (selectedTrivia === TriviaType.JIG) {
        return jigTrivia[Math.floor(Math.random() * jigTrivia.length)];
    }
    throw new Error("Error");
};
const print = async (selectedTrivia, player) => {
    let paper = "";
    let content = "";
    let name = "'s §a Award";
    if (selectedTrivia === TriviaType.MIN) {
        paper = "jig_ccomp:trivia_min_paper";
        content = `This certifies that you completed 10 Minecraft Trivia questions in a row!`;
        name = `'s §aMinecraft Award`;
    }
    else if (selectedTrivia === TriviaType.JIG) {
        paper = "jig_ccomp:trivia_jig_paper";
        content = `This certifies that you completed 10 Jigarbov Trivia questions in a row!`;
        name = `'s §aJigarbov Award`;
    }
    return await printContent(player.name + name, content, undefined, player, paper);
};
const getPrize = (selectedTrivia, prizeType, player) => {
    let prize;
    if (selectedTrivia === TriviaType.MIN) {
        if (prizeType === PrizeType.GOOD) {
            prize = minGoodPrize[Math.floor(Math.random() * minGoodPrize.length)];
        }
        else if (prizeType === PrizeType.BAD) {
            prize = minBadPrize[Math.floor(Math.random() * minBadPrize.length)];
        }
    }
    else if (selectedTrivia === TriviaType.JIG) {
        if (prizeType === PrizeType.GOOD) {
            prize = jigGoodPrize[Math.floor(Math.random() * jigGoodPrize.length)];
        }
        else if (prizeType === PrizeType.BAD) {
            prize = jigBadPrize[Math.floor(Math.random() * jigBadPrize.length)];
        }
    }
    player.dimension.runCommand(`give "${player.name}" ${prize}`);
};
class TriviaPhoneApp extends PhoneApp {
    settings;
    phonesettings;
    static COMPONENT_ID = 'trivia';
    constructor(settings, phonesettings) {
        super(TriviaPhoneApp.COMPONENT_ID);
        this.settings = settings;
        this.phonesettings = phonesettings;
    }
    async onSelected(event) {
        const volume = this.phonesettings.getVolume(TriviaPhoneApp.COMPONENT_ID);
        event.player.playSound("jig_ccomp.trivia_start", { volume: volume });
        await this.openApp(event);
    }
    async onAction(event) {
        const volume = this.phonesettings.getVolume(TriviaPhoneApp.COMPONENT_ID);
        event.player.playSound("jig_ccomp.trivia_start", { volume: volume });
        await this.openApp(event);
    }
    async openApp(phoneEvent) {
        phoneEvent.cancel = true;
        const mainEvent = phoneEvent;
        let triviaRecord = {
            triviaSelected: TriviaType.MIN,
            answerCorrects: 0,
            nextTrivia: null,
        };
        await renderLoop(phoneEvent.player, ui$3, {
            close_app: async (event) => {
                phoneEvent.closeApp = true;
            },
            "load_trivia": async (event) => {
                const [answerUser] = event.eventArgs;
                triviaRecord.triviaSelected = answerUser;
                triviaRecord.nextTrivia = nextTrivia(triviaRecord.triviaSelected);
                event.args.set('trivia', triviaRecord.nextTrivia);
            },
            "prize": async (event) => {
                const [kindPrizeUser] = event.eventArgs;
                getPrize(triviaRecord.triviaSelected, kindPrizeUser, phoneEvent.player);
            },
            "print": async (event) => {
                await print(triviaRecord.triviaSelected, phoneEvent.player);
            },
            "reset": async (event) => {
                triviaRecord.answerCorrects = 0;
            },
            "trivia_answer": async (event) => {
                const [answerUser] = event.eventArgs;
                event.args.set('trivia', triviaRecord.nextTrivia);
                const volume = this.phonesettings.getVolume(TriviaPhoneApp.COMPONENT_ID);
                if ((triviaRecord.nextTrivia) && answerUser === triviaRecord.nextTrivia.answer) {
                    triviaRecord.answerCorrects++;
                    if (triviaRecord.answerCorrects >= 10) {
                        mainEvent.player.playSound("jig_ccomp.trivia_start", {
                            location: mainEvent.player.location,
                            volume: volume,
                            pitch: 0.5
                        });
                        const triviaPrizes = adminSettings.getBoolean('triviaPrizes');
                        const nextForm = triviaPrizes ? "view_" + triviaRecord.triviaSelected + '_won' : "view_" + triviaRecord.triviaSelected + '_won_x';
                        event.form = event.loadForm(nextForm, 'multi-button');
                    }
                    else {
                        mainEvent.player.playSound("random.levelup", {
                            location: mainEvent.player.location,
                            volume: volume,
                            pitch: 1
                        });
                        event.form = event.loadForm('view_trivia', 'multi-button');
                        triviaRecord.nextTrivia = triviaRecord.nextTrivia = nextTrivia(triviaRecord.triviaSelected);
                        event.args.set('trivia', triviaRecord.nextTrivia);
                    }
                }
                else {
                    mainEvent.player.playSound("jig_ccomp.trivia_wrong", {
                        location: mainEvent.player.location,
                        volume: volume,
                        pitch: 1
                    });
                    triviaRecord.answerCorrects = 0;
                    const triviaPrizes = adminSettings.getBoolean('triviaPrizes');
                    const nextForm = triviaPrizes ? "view_" + triviaRecord.triviaSelected + "_wrong" : "view_" + triviaRecord.triviaSelected + '_wrong_x';
                    event.form = event.loadForm(nextForm, 'multi-button');
                }
            },
        });
    }
}
const ui$3 = {
    entrypoint: 'main',
    forms: {
        main: {
            type: 'multi-button',
            title: _('jig_ccomp:name.mc_trivia'),
            body: _('jig_ccomp:min_trivia_title', "\n\n", "\n\n"),
            elements: [
                {
                    type: 'button',
                    text: _('jig_ccomp:butt.triv_min'),
                    icon: `textures/jig/ccomp/myui/minecraft`,
                    action: {
                        event: 'load_trivia',
                        eventArgs: [TriviaType.MIN],
                        form: 'view_trivia',
                    },
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:butt.triv_jig'),
                    icon: `textures/jig/ccomp/myui/jigarbov`,
                    action: {
                        event: 'load_trivia',
                        eventArgs: [TriviaType.JIG],
                        form: 'view_trivia',
                    },
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.trivia.close'),
                    action: {
                        event: 'close_app',
                    }
                }
            ]
        },
        view_trivia: {
            type: 'multi-button',
            title: _('jig_ccomp:name.mc_trivia'),
            body: _('{trivia.id}', "\n\n", "\n", "\n"),
            elements: [
                {
                    type: 'button',
                    text: _('jig_ccomp:butt.triv_a'),
                    action: {
                        event: 'trivia_answer',
                        eventArgs: ['a'],
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:butt.triv_b'),
                    action: {
                        event: 'trivia_answer',
                        eventArgs: ['b'],
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:butt.triv_c'),
                    action: {
                        event: 'trivia_answer',
                        eventArgs: ['c'],
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.trivia.close'),
                    action: {
                        event: 'close_app',
                    }
                }
            ]
        },
        view_min_right: {
            type: 'multi-button',
            title: _('jig_ccomp:name.mc_trivia'),
            body: _('jig_ccomp:min_trivia_right', "\n\n", "\n", "\n"),
            elements: [
                {
                    type: 'button',
                    text: _('butt.old_pc_cont'),
                    action: {
                        event: 'continue',
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.trivia.close'),
                    action: {
                        event: 'close_app',
                    }
                }
            ]
        },
        view_min_wrong: {
            type: 'multi-button',
            title: _('jig_ccomp:name.mc_trivia'),
            body: _('jig_ccomp:min_trivia_wrong', "\n\n", "\n", "\n"),
            elements: [
                {
                    type: 'button',
                    text: _('jig_ccomp:min_trivia_prize'),
                    icon: `textures/jig/ccomp/myui/prize_bad`,
                    action: {
                        event: 'prize',
                        eventArgs: [PrizeType.BAD],
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.main'),
                    icon: `textures/jig/ccomp/phone/apps/trivia`,
                    action: {
                        event: "reset",
                        form: 'main',
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.trivia.close'),
                    action: {
                        event: 'close_app',
                    }
                }
            ]
        },
        view_min_won: {
            type: 'multi-button',
            title: _('jig_ccomp:name.mc_trivia'),
            body: _('jig_ccomp:min_trivia_won', "\n\n", "\n", "\n"),
            elements: [
                {
                    type: 'button',
                    text: _('jig_ccomp:min_trivia_prize'),
                    icon: `textures/jig/ccomp/myui/prize_good`,
                    action: {
                        event: 'prize',
                        eventArgs: [PrizeType.GOOD]
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:min_trivia_print'),
                    icon: `textures/jig/ccomp/myui/print_reward`,
                    action: {
                        event: 'print'
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.main'),
                    icon: `textures/jig/ccomp/phone/apps/trivia`,
                    action: {
                        event: "reset",
                        form: 'main',
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.trivia.close'),
                    action: {
                        event: 'close_app',
                    }
                }
            ]
        },
        view_min_wrong_x: {
            type: 'multi-button',
            title: _('jig_ccomp:name.mc_trivia'),
            body: _('jig_ccomp:min_trivia_wrong', "\n\n", "\n", "\n"),
            elements: [
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.main'),
                    icon: `textures/jig/ccomp/phone/apps/trivia`,
                    action: {
                        event: "reset",
                        form: 'main',
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.trivia.close'),
                    action: {
                        event: 'close_app',
                    }
                }
            ]
        },
        view_min_won_x: {
            type: 'multi-button',
            title: _('jig_ccomp:name.mc_trivia'),
            body: _('jig_ccomp:min_trivia_won_x', "\n\n", "\n", "\n"),
            elements: [
                {
                    type: 'button',
                    text: _('jig_ccomp:min_trivia_print'),
                    icon: `textures/jig/ccomp/myui/print_reward`,
                    action: {
                        event: 'print'
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.main'),
                    icon: `textures/jig/ccomp/phone/apps/trivia`,
                    action: {
                        event: "reset",
                        form: 'main',
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.trivia.close'),
                    action: {
                        event: 'close_app',
                    }
                }
            ]
        },
        view_jig_right: {
            type: 'multi-button',
            title: _('jig_ccomp:name.mc_trivia'),
            body: _('jig_ccomp:jig_trivia_right', "\n\n", "\n", "\n"),
            elements: [
                {
                    type: 'button',
                    text: _('butt.old_pc_cont'),
                    action: {
                        event: 'continue',
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.trivia.close'),
                    action: {
                        event: 'close_app',
                    }
                }
            ]
        },
        view_jig_wrong: {
            type: 'multi-button',
            title: _('jig_ccomp:name.mc_trivia'),
            body: _('jig_ccomp:jig_trivia_wrong', "\n\n", "\n", "\n"),
            elements: [
                {
                    type: 'button',
                    text: _('jig_ccomp:jig_trivia_prize'),
                    icon: `textures/jig/ccomp/myui/prize_bad`,
                    action: {
                        event: 'prize',
                        eventArgs: [PrizeType.BAD]
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.main'),
                    icon: `textures/jig/ccomp/phone/apps/trivia`,
                    action: {
                        event: "reset",
                        form: 'main',
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.trivia.close'),
                    action: {
                        event: 'close_app',
                    }
                }
            ]
        },
        view_jig_won: {
            type: 'multi-button',
            title: _('jig_ccomp:name.mc_trivia'),
            body: _('jig_ccomp:jig_trivia_won', "\n\n", "\n", "\n"),
            elements: [
                {
                    type: 'button',
                    text: _('jig_ccomp:jig_trivia_prize'),
                    icon: `textures/jig/ccomp/myui/prize_good`,
                    action: {
                        event: 'prize',
                        eventArgs: [PrizeType.GOOD]
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:jig_trivia_print'),
                    icon: `textures/jig/ccomp/myui/print_reward`,
                    action: {
                        event: 'print'
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.main'),
                    icon: `textures/jig/ccomp/phone/apps/trivia`,
                    action: {
                        event: "reset",
                        form: 'main',
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.trivia.close'),
                    action: {
                        event: 'close_app',
                    }
                }
            ]
        },
        view_jig_wrong_x: {
            type: 'multi-button',
            title: _('jig_ccomp:name.mc_trivia'),
            body: _('jig_ccomp:jig_trivia_wrong_x', "\n\n", "\n", "\n"),
            elements: [
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.main'),
                    icon: `textures/jig/ccomp/phone/apps/trivia`,
                    action: {
                        event: "reset",
                        form: 'main',
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.trivia.close'),
                    action: {
                        event: 'close_app',
                    }
                }
            ]
        },
        view_jig_won_x: {
            type: 'multi-button',
            title: _('jig_ccomp:name.mc_trivia'),
            body: _('jig_ccomp:jig_trivia_won_x', "\n\n", "\n", "\n"),
            elements: [
                {
                    type: 'button',
                    text: _('jig_ccomp:jig_trivia_print'),
                    icon: `textures/jig/ccomp/myui/print_reward`,
                    action: {
                        event: 'print'
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.main'),
                    icon: `textures/jig/ccomp/phone/apps/trivia`,
                    action: {
                        event: "reset",
                        form: 'main',
                    }
                },
                {
                    type: 'button',
                    text: _('jig_ccomp:gui.trivia.close'),
                    action: {
                        event: 'close_app',
                    }
                }
            ]
        },
    }
};

const getDailyPromptIndex = (globalData) => {
    const startDayProp = "jig_ccomp:wouldurather-start-day";
    const currentPromptProp = "jig_ccomp:wouldurather-current-prompt";
    const lastAdvanceDayProp = "jig_ccomp:wouldurather-last-advance-day";
    const today = world.getDay();
    // Initialize start day if not set
    let startDay = GET_RAW_PROP(world, startDayProp);
    if (startDay === undefined) {
        startDay = today;
        SET_RAW_PROP(world, startDayProp, startDay);
        SET_RAW_PROP(world, currentPromptProp, 0);
        SET_RAW_PROP(world, lastAdvanceDayProp, today);
        debug(`[WYR] Initialized: start day ${startDay}, prompt 0`);
        return 0;
    }
    const currentPrompt = GET_RAW_PROP(world, currentPromptProp) ?? 0;
    const lastAdvanceDay = GET_RAW_PROP(world, lastAdvanceDayProp) ?? startDay;
    // Check if we can advance (new day + current prompt has votes)
    if (today > lastAdvanceDay) {
        const currentVotes = globalData.votes[currentPrompt];
        const hasVotes = currentVotes && currentVotes[0] + currentVotes[1] > 0;
        if (hasVotes) {
            const nextPrompt = currentPrompt + 1;
            SET_RAW_PROP(world, currentPromptProp, nextPrompt);
            SET_RAW_PROP(world, lastAdvanceDayProp, today);
            debug(`[WYR] Advanced to prompt ${nextPrompt} on day ${today} (previous had ${currentVotes[0] + currentVotes[1]} votes)`);
            return nextPrompt;
        }
        else {
            debug(`[WYR] Staying at prompt ${currentPrompt} - no votes yet`);
        }
    }
    return currentPrompt;
};
class WouldYouRatherApp extends PhoneApp {
    settings;
    globalSettings;
    static COMPONENT_ID = "wouldurather";
    constructor(settings, globalSettings) {
        super(WouldYouRatherApp.COMPONENT_ID);
        this.settings = settings;
        this.globalSettings = globalSettings;
    }
    getLocal() {
        return this.settings.getData({ voted: {} });
    }
    getGlobal() {
        return this.globalSettings.getData({ votes: {} });
    }
    async onSelected(event) {
        await this.openApp(event);
    }
    async onAction(event) {
        await this.openApp(event);
    }
    vote(promptId, choice) {
        const local = this.getLocal();
        const global = this.getGlobal();
        if (!(promptId in global.votes)) {
            global.votes[promptId] = [0, 0];
        }
        const existing = local.voted[promptId];
        if (existing !== undefined) {
            global.votes[promptId][existing]--;
        }
        global.votes[promptId][choice]++;
        local.voted[promptId] = choice;
        this.settings.setData(local);
        this.globalSettings.setData(global);
    }
    getPromptData(promptId) {
        const promptBase = `jig_ccomp:phone.apps.wyr.prompt.${promptId}`;
        const [a, b] = [`${promptBase}.a`, `${promptBase}.b`];
        const global = this.getGlobal().votes[promptId] ?? [0, 0];
        const total = global[0] + global[1];
        const percent = total > 0 ? [Math.round((global[0] / total) * 100), Math.round((global[1] / total) * 100)] : [0, 0];
        const localVote = this.getLocal().voted[promptId];
        const localVoteText = localVote === 0 ? a : localVote === 1 ? b : "";
        return { a, b, global, percent, localVote, localVoteText, total };
    }
    async openApp(event) {
        event.cancel = true;
        const ui = {
            entrypoint: "main",
            forms: {
                main: {
                    type: "multi-button",
                    title: _("jig_ccomp:phone.apps.wyr.title"),
                    body: _("jig_ccomp:phone.apps.wyr.body"),
                    elements: [
                        {
                            type: "button",
                            text: _("jig_ccomp:phone.apps.wyr.view-today"),
                            icon: "textures/jig/ccomp/phone/apps/wyr_today",
                            action: { event: "load_prompt" },
                        },
                        {
                            type: "button",
                            text: _("jig_ccomp:phone.apps.wyr.view-yesterday"),
                            icon: "textures/jig/ccomp/phone/apps/wyr_yesterday",
                            action: { event: "load_yesterday" },
                        },
                        {
                            type: "button",
                            text: _("jig_ccomp:gui.wyr.close"),
                            action: { event: "close_app" },
                        },
                    ],
                },
                prompt_view: {
                    type: "multi-button",
                    title: _("jig_ccomp:phone.apps.wyr.prompt.title"),
                    body: ["§b", _("{a}"), "§r\n§c", _("{b}"), "§r"],
                    elements: [
                        {
                            type: "button",
                            text: _("{a}"),
                            icon: "textures/jig/ccomp/phone/apps/wyr_a",
                            action: {
                                event: "vote_choice",
                                eventArgs: [0],
                                copyArgs: true,
                                form: "results",
                            },
                        },
                        {
                            type: "button",
                            text: _("{b}"),
                            icon: "textures/jig/ccomp/phone/apps/wyr_b",
                            action: {
                                event: "vote_choice",
                                eventArgs: [1],
                                copyArgs: true,
                                form: "results",
                            },
                        },
                        {
                            type: "button",
                            text: _("jig_ccomp:gui.wyr.main"),
                            icon: "textures/jig/ccomp/phone/apps/wouldurather",
                            action: { form: "main" },
                        },
                        {
                            type: "button",
                            text: _("jig_ccomp:gui.wyr.close"),
                            action: { event: "close_app" },
                        },
                    ],
                },
                results: {
                    type: "multi-button",
                    title: _("Results"),
                    body: [
                        "§b",
                        _("{a}"),
                        " - {percentA}%%§r\n",
                        "§c",
                        _("{b}"),
                        " - {percentB}%%§r\n",
                        "§r",
                        "Total votes: {total}\n\n",
                        "You voted for: ",
                        _("{localVote}"),
                    ],
                    elements: [
                        {
                            type: "button",
                            text: _("jig_ccomp:phone.apps.wyr.change-vote"),
                            icon: "textures/jig/ccomp/phone/apps/wyr_change",
                            action: { form: "prompt_view", copyArgs: true },
                        },
                        {
                            type: "button",
                            text: _("jig_ccomp:gui.wyr.main"),
                            icon: "textures/jig/ccomp/phone/apps/wouldurather",
                            action: { form: "main" },
                        },
                        {
                            type: "button",
                            text: _("jig_ccomp:gui.wyr.close"),
                            action: { event: "close_app" },
                        },
                    ],
                },
                yesterday_results: {
                    type: "multi-button",
                    title: _("jig_ccomp:phone.apps.wyr.view-yesterday"),
                    body: [
                        "§b",
                        _("{a}"),
                        " - {percentA}%%§r\n",
                        "§c",
                        _("{b}"),
                        " - {percentB}%%§r\n",
                        "§r",
                        "Total votes: {total}\n\n",
                        "You voted for: ",
                        _("{localVote}"),
                    ],
                    elements: [
                        {
                            type: "button",
                            text: _("jig_ccomp:gui.wyr.main"),
                            icon: "textures/jig/ccomp/phone/apps/wouldurather",
                            action: { form: "main" },
                        },
                        {
                            type: "button",
                            text: _("jig_ccomp:gui.wyr.close"),
                            action: { event: "close_app" },
                        },
                    ],
                },
                no_yesterday: {
                    type: "multi-button",
                    title: _("No data"),
                    body: _("jig_ccomp:phone.apps.wyr.no-yesterday"),
                    elements: [
                        {
                            type: "button",
                            text: _("jig_ccomp:gui.wyr.main"),
                            icon: "textures/jig/ccomp/phone/apps/wouldurather",
                            action: { form: "main" },
                        },
                        {
                            type: "button",
                            text: _("jig_ccomp:gui.wyr.close"),
                            action: { event: "close_app" },
                        },
                    ],
                },
            },
        };
        await renderLoop(event.player, ui, {
            load_prompt: async (e) => {
                this.getLocal();
                const global = this.getGlobal();
                const id = getDailyPromptIndex(global);
                const prompt = this.getPromptData(id);
                debug(`[WYR] Showing prompt ${id}, local vote: ${prompt.localVote}`);
                e.args.set("promptId", id.toString());
                e.args.set("a", prompt.a);
                e.args.set("b", prompt.b);
                e.args.set("percentA", `${prompt.percent[0]}`);
                e.args.set("percentB", `${prompt.percent[1]}`);
                e.args.set("localVote", prompt.localVoteText);
                e.args.set("total", prompt.total.toString());
                e.form = e.loadForm(prompt.localVote !== undefined ? "results" : "prompt_view");
            },
            vote_choice: async (e) => {
                const promptId = parseInt(e.args.get("promptId"));
                debug(`promptId received: ${promptId}`);
                const [choice] = e.eventArgs;
                this.vote(promptId, choice);
                const updated = this.getPromptData(promptId);
                e.args.set("localVote", updated.localVoteText);
                e.args.set("percentA", `${updated.percent[0]}`);
                e.args.set("percentB", `${updated.percent[1]}`);
                e.args.set("total", updated.total.toString());
                e.form = e.loadForm("results");
            },
            load_yesterday: async (e) => {
                const global = this.getGlobal();
                const currentId = getDailyPromptIndex(global);
                const yesterdayId = currentId - 1;
                if (yesterdayId < 0) {
                    e.form = e.loadForm("no_yesterday");
                    return;
                }
                const prompt = this.getPromptData(yesterdayId);
                e.args.set("a", prompt.a);
                e.args.set("b", prompt.b);
                e.args.set("percentA", `${prompt.percent[0]}`);
                e.args.set("percentB", `${prompt.percent[1]}`);
                e.args.set("localVote", prompt.localVoteText || "jig_ccomp:phone.apps.wyr.prompt.no-vote");
                e.args.set("total", prompt.total.toString());
                e.form = e.loadForm("yesterday_results");
            },
            close_app: async (e) => {
                event.closeApp = true;
            },
        });
    }
}

const makeAchievements = (achievements) => {
    if (achievements) {
        return Object.fromEntries(Object.entries(achievements).map((entry) => {
            return [
                entry[0],
                {
                    ...entry[1],
                    id: entry[0],
                },
            ];
        }));
    }
    return {};
};
const makeItems = (items) => {
    return Object.fromEntries(Object.entries(items).map((entry) => {
        return [
            entry[0],
            {
                ...entry[1],
                id: entry[0],
            },
        ];
    }));
};
const makeTargets = (targets) => {
    return Object.fromEntries(Object.entries(targets).map((entry) => {
        return [
            entry[0],
            {
                ...entry[1],
                id: entry[0],
            },
        ];
    }));
};
const makeExits = (exits) => {
    return Object.fromEntries(Object.entries(exits).map((entry) => {
        return [
            entry[0],
            {
                ...entry[1],
                id: entry[0],
            },
        ];
    }));
};
const makeRooms = (rooms) => {
    return Object.fromEntries(Object.entries(rooms).map((entry) => {
        return [
            entry[0],
            {
                ...entry[1],
                id: entry[0],
                targets: makeTargets(entry[1].targets),
                exits: makeExits(entry[1].exits),
            },
        ];
    }));
};
const mergeRecursive = (obj, overrider) => {
    if (obj && overrider && typeof obj === 'object' && typeof overrider === 'object') {
        const objCopy = { ...obj };
        for (const [key, value] of Object.entries(overrider)) {
            if (key in objCopy) {
                if (value && typeof value === 'object') {
                    objCopy[key] = mergeRecursive({ ...objCopy[key] }, value);
                }
                else {
                    objCopy[key] = value;
                }
            }
            else {
                objCopy[key] = overrider[key];
            }
        }
        return objCopy;
    }
    return obj;
};
const makeTextAdventure = (definition) => {
    return {
        rooms: makeRooms(definition.rooms),
        achievements: (definition.achievements) ? makeAchievements(definition.achievements) : {},
        items: makeItems(definition.items),
        overrides: mergeRecursive({
            ui: {
                achievement: {
                    defaultIcon: "textures/jig/ccomp/myui/locked.png"
                },
                status: {
                    title: "jig_ccomp:minecraft.ui.status.title",
                },
                room: {
                    buttons: {
                        walk: 'jig_ccomp:text-adventure.ui.walk'
                    },
                },
                walk: {
                    title: 'jig_ccomp:text-adventure.ui.walk.title'
                }
            },
            icons: {
                exits: {
                    east: 'textures/jig/ccomp/tadvent/east.png',
                    inside: 'textures/jig/ccomp/tadvent/inside.png',
                    north: 'textures/jig/ccomp/tadvent/north.png',
                    northeast: 'textures/jig/ccomp/tadvent/northeast.png',
                    outside: 'textures/jig/ccomp/tadvent/outside.png',
                    south: 'textures/jig/ccomp/tadvent/south.png',
                    west: 'textures/jig/ccomp/tadvent/west.png',
                    walk: 'textures/jig/ccomp/tadvent/walk.png',
                    up: 'textures/jig/ccomp/tadvent/up.png',
                    down: 'textures/jig/ccomp/tadvent/down.png',
                },
                targets: {
                    look: 'textures/jig/ccomp/tadvent/look.png',
                    talk: 'textures/jig/ccomp/tadvent/talk.png',
                    use: 'textures/jig/ccomp/tadvent/use.png',
                    attack: 'textures/jig/ccomp/tadvent/attack.png',
                    walk: 'textures/jig/ccomp/tadvent/walk.png',
                }
            }
        }, definition.overrides)
    };
};
const makeTargetTemplate = (template) => template;
const makeExitTemplate = (template) => template;
class TextAdventure {
    player;
    definition;
    state;
    constructor(player, definition, state) {
        this.player = player;
        this.definition = definition;
        this.state = state;
    }
    getAchievementsIDs() {
        return Object.keys(this.definition.achievements);
    }
    getAchievements() {
        return this.definition.achievements;
    }
    getAchievement(id) {
        return this.definition.achievements[id];
    }
    getTitle() {
        return this.definition.overrides.ui.status.title;
    }
    hasPendingText() {
        return this.state.nextPrompt.length > 0;
    }
    getPendingText() {
        return this.state.nextPrompt;
    }
    cleanPendingText() {
        this.state.nextPrompt = [];
    }
    isGameover() {
        return this.state.status !== 'playing';
    }
    didLost() {
        return this.state.status === 'lost';
    }
    didWin() {
        return this.state.status === 'won';
    }
    getInventory() {
        return this.state.inventory;
    }
    getCurrentRoom() {
        return this.definition.rooms[this.state.currentRoom];
    }
}

const PROP_TARGET_HIDDEN = (roomId, targetId) => `rooms.${roomId}.targets.${targetId}.hidden`;
const PROP_EXIT_HIDDEN = (roomId, exitId) => `rooms.${roomId}.exits.${exitId}.hidden`;
const PROP_VARIABLE = (prop) => `dev.${prop}`;
const PROP_WON_VARIABLE = (prop) => `won.${prop}`;
const WON_CERTIFICATE_TITLE = 'certificate-title';
const WON_CERTIFICATE_DESCRIPTION = 'certificate-description';
const setTargetHidden = (state, roomId, targetId, hidden) => {
    state.props[PROP_TARGET_HIDDEN(roomId, targetId)] = hidden;
};
const isTargetHidden = (state, roomId, target) => {
    const prop = PROP_TARGET_HIDDEN(roomId, target.id);
    if (prop in state.props) {
        return state.props[prop];
    }
    return !!target.hidden;
};
const isExitHidden = (state, roomId, exit) => {
    const prop = PROP_EXIT_HIDDEN(roomId, exit.id);
    if (prop in state.props) {
        return state.props[prop];
    }
    return !!exit.hidden;
};
const getVariable = (state, variable) => {
    return state.props[PROP_VARIABLE(variable)];
};
const setVariable = (state, variable, value) => {
    state.props[PROP_VARIABLE(variable)] = value;
};
const isVariable = (state, variable, value) => {
    const prop = PROP_VARIABLE(variable);
    return state.props[prop] === value;
};
const isNotVariable = (state, variable, value) => {
    const prop = PROP_VARIABLE(variable);
    return state.props[prop] !== value;
};
const getWonCertificateTitle = (state) => {
    return state.props[PROP_WON_VARIABLE(WON_CERTIFICATE_TITLE)];
};
const getWonCertificateDescription = (state) => {
    return state.props[PROP_WON_VARIABLE(WON_CERTIFICATE_DESCRIPTION)];
};
const setWonCertificateTitle = (state, value) => {
    return state.props[PROP_WON_VARIABLE(WON_CERTIFICATE_TITLE)] = value;
};
const setWonCertificateDescription = (state, value) => {
    return state.props[PROP_WON_VARIABLE(WON_CERTIFICATE_DESCRIPTION)] = value;
};

const SAY = (what) => ({ state }) => {
    state.nextPrompt.push(what);
    state.nextPrompt.push(TEXT("\n"));
};
const DIE = () => ({ state }) => {
    state.status = "lost";
};
const format = (formatString, ...args) => {
    return formatString.replace(/{(\d+)}/g, (match, number) => {
        return typeof args[number] != 'undefined'
            ? args[number]
            : match;
    });
};
const EARN_ACHIEVEMENT = (id) => (context) => {
    if (id in context.game.achievements) {
        if (!context.achievements.includes(id)) {
            context.achievements.push(id);
        }
        else {
            debug(`previously EARN_ACHIEVEMENT ${id}.`);
        }
    }
    else {
        debug(`unknown arg used in EARN_ACHIEVEMENT ${id}.`);
    }
};
const WON = (certificateTitle, certificateDescription, ...args) => (context) => {
    context.state.status = "won";
    const formatArgs = args.map((param) => {
        if (param.startsWith('item:')) {
            const item = param.slice(5);
            return (context.state.inventory.find(i => i.id === item)?.count ?? 0).toString();
        }
        else if (param.startsWith('value:')) {
            const value = param.slice(6);
            return getVariable(context.state, value).toString();
        }
        else if (param === 'player') {
            return context.player;
        }
        else {
            debug(`unknown arg used in WON ${param}. All args: ${JSON.stringify(args)}`);
            return '';
        }
    });
    if (certificateTitle) {
        setWonCertificateTitle(context.state, format(certificateTitle, ...formatArgs));
        if (certificateDescription) {
            setWonCertificateDescription(context.state, format(certificateDescription, ...formatArgs));
        }
    }
};
const GET_ITEM = (itemId, count = 1) => ({ state }) => {
    const item = state.inventory.find((i) => i.id === itemId);
    if (item) {
        item.count += count;
    }
    else {
        state.inventory.push({
            id: itemId,
            count,
        });
    }
};
const CHANGE_LOCATION = (locationId) => ({ state }) => {
    state.currentRoom = locationId;
};
const REMOVE_ITEM = (itemId, count = 1) => ({ state }) => {
    const item = state.inventory.find((i) => i.id === itemId);
    if (item) {
        item.count -= count;
        if (item.count <= 0) {
            state.inventory = state.inventory.filter((i) => i.id !== itemId);
        }
    }
};
const REMOVE_ITEMS = (itemId, count = 1) => ({ state }) => {
    const item = state.inventory.find((i) => i.id === itemId);
    if (item) {
        item.count -= count;
        if (item.count <= 0) {
            state.inventory = state.inventory.filter((i) => i.id !== itemId);
        }
    }
};
const HIDE_TARGET = (targetId) => ({ state, room, ...rest }) => {
    if (targetId !== undefined) {
        setTargetHidden(state, room.id, targetId, true);
    }
    else if (rest.type === "target") {
        setTargetHidden(state, room.id, rest.target.id, true);
    }
};
const SHOW_TARGET = (targetId) => ({ state, room, ...rest }) => {
    if (targetId !== undefined) {
        setTargetHidden(state, room.id, targetId, false);
    }
    else if (rest.type === "target") {
        setTargetHidden(state, room.id, rest.target.id, false);
    }
};
const SET_VALUE = (variable, value) => ({ state }) => {
    setVariable(state, variable, value);
};
const ROLL_AND_SET = (sides, variableName) => ({ state }) => {
    const result = makeRandomNumber(1, sides);
    setVariable(state, variableName, result);
};
const INCREMENT_VALUE = (variable, amount = 1) => ({ state }) => {
    const current = Number(getVariable(state, variable)) || 0;
    setVariable(state, variable, current + amount);
};
const DEBUG_PROP = (key) => (context) => {
    const val = context.state.props[key];
    context.state.nextPrompt.push(TRANSLATE$1(`jig_ccomp:${key}`));
    context.state.nextPrompt.push(TEXT(`${val}\n`));
};

const ALL = (...conditions) => (context) => {
    return conditions.every((c) => c(context));
};
const ANY = (...conditions) => (context) => {
    return conditions.some((c) => c(context));
};
const hasItems = (...items) => (context) => {
    return items.every((i) => hasItem(context.state, i));
};
const doesNotHaveItems = (...items) => (context) => {
    return items.some((i) => !hasItem(context.state, i));
};
const hasItem = (state, item) => {
    if (typeof item === "string") {
        return !!state.inventory.find((i) => i.id === item);
    }
    else {
        return !!state.inventory.find((i) => i.id === item.id && i.count >= item.count);
    }
};
const IS_VALUE = (variable, value) => ({ state }) => {
    return isVariable(state, variable, value);
};
const IS_NOT_VALUE = (variable, value) => ({ state }) => {
    return isNotVariable(state, variable, value);
};
const HAS_ITEM = (item, count) => ({ state }) => {
    return hasItem(state, count !== undefined
        ? {
            id: item,
            count,
        }
        : item);
};
const HAS_LESS_THAN_ITEMS = (item, count) => ({ state }) => {
    const entry = state.inventory.find((i) => i.id === item);
    return !entry || entry.count < count;
};
const HAS_ITEMS = hasItems;
const HAS_ZERO_OR_LESS_VALUE = (key) => ({ state }) => (state.props[key] ?? 0) <= 0;
const THROW_DICE = (sided, ...target) => ({ state }) => {
    const die = makeRandomNumber(1, sided);
    return target.includes(die);
};

const SOUTH$3 = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.duct.exit.south"), type: "south",
});
const NORTH$4 = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.duct.exit.north"), type: "north",
});
const EAST$1 = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.duct.exit.east"), type: "east",
});
const WEST$1 = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.duct.exit.west"), type: "west",
});
const DOWN = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.duct.exit.down"), type: "down",
});
makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.duct.exit.up"),
});
const newDuctAdventureState = () => ({
    version: 1,
    inventory: [
        { id: "usbkey", count: 1 },
    ],
    status: 'playing',
    props: {},
    nextPrompt: [TRANSLATE$1("jig_ccomp:text-adventure.duct.introduction", "\n")],
    currentRoom: "duct1",
});
const newDuctAdventure = () => makeTextAdventure({
    overrides: {
        ui: {
            status: {
                title: "jig_ccomp:text-adventure.ui.select-adventure.adventure.duct",
            }
        }
    },
    rooms: {
        duct1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.duct1", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.duct1.far_description"),
            targets: {},
            exits: {
                north: {
                    ...NORTH$4,
                    room: "duct2",
                },
            },
        },
        duct2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.duct2", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.duct2.far_description"),
            targets: {
                guard_phonecall: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.guard1.phonecall"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.guard1.listen", "\n")),
                        HIDE_TARGET(),
                    ],
                    type: "talk",
                },
                dropdown: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.dropdown"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.room.gameover1", "\n")),
                        DIE(),
                    ],
                }
            },
            exits: {
                north: {
                    ...NORTH$4,
                    room: "duct5",
                },
                east: {
                    ...EAST$1,
                    room: "duct4",
                },
                west: {
                    ...WEST$1,
                    room: "duct3",
                },
                south: {
                    ...SOUTH$3,
                    room: "duct1",
                },
            },
        },
        duct3: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.duct3", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.duct3.far_description"),
            targets: {
                exitCloset: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.dropdown"),
                    actions: [
                        CHANGE_LOCATION("closet"),
                    ],
                }
            },
            exits: {
                east: {
                    ...EAST$1,
                    room: "duct2",
                },
            },
        },
        duct4: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.duct4", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.duct4.far_description"),
            targets: {
                guard_toilet0: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.guard3"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.bathroom0", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("guard_toilet1"),
                    ],
                    type: "look",
                },
                guard_toilet1: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.guard3.more"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.bathroom1", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("guard_toilet2"),
                    ],
                    hidden: true,
                    type: "look",
                },
                guard_toilet2: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.guard3.more"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.bathroom2", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("guard_toilet3"),
                    ],
                    hidden: true,
                    type: "look",
                },
                guard_toilet3: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.guard3.more"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.bathroom3", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("guard_toilet4"),
                    ],
                    hidden: true,
                    type: "look",
                },
                guard_toilet4: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.guard3.more"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.bathroom4", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("guard_toilet5"),
                    ],
                    hidden: true,
                    type: "look",
                },
                guard_toilet5: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.guard3.more"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.bathroom5", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("guard_toilet6"),
                    ],
                    hidden: true,
                    type: "look",
                },
                guard_toilet6: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.guard3.more"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.bathroom6", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("guard_toilet7"),
                    ],
                    hidden: true,
                    type: "look",
                },
                guard_toilet7: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.guard3.more"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.bathroom7", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("guard_toilet8"),
                    ],
                    hidden: true,
                    type: "look",
                },
                guard_toilet8: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.guard3.more"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.bathroom8", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("guard_toilet9"),
                        SET_VALUE("act1.guardname", true),
                    ],
                    hidden: true,
                    type: "look",
                },
                guard_toilet9: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.guard3.complete"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.bathroom9", "\n")),
                        HIDE_TARGET(), EARN_ACHIEVEMENT("ducts_toilet"),
                    ],
                    hidden: true,
                    type: "look",
                },
            },
            exits: {
                west: {
                    ...WEST$1,
                    room: "duct2",
                },
            },
        },
        duct5: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.duct5", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.duct5.far_description"),
            targets: {
                observefan: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.observefan.label"),
                    actions: [
                        {
                            if: {
                                condition: hasItems("wrench"),
                                actions: [
                                    SHOW_TARGET("usewrenchfan"),
                                ],
                            }
                        },
                        {
                            if: {
                                condition: hasItems("mop"),
                                actions: [
                                    SHOW_TARGET("usemopfan"),
                                ],
                            }
                        },
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.observefan", "\n")),
                        SHOW_TARGET("usefan"),
                    ],
                    type: "look",
                },
                usewrenchfan: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.fan.usewrench.label"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.fan.usewrench", "\n")),
                        DIE(),
                    ],
                    hidden: true,
                },
                usemopfan: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.fan.usemop.label"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.fan.usemop", "\n")),
                        CHANGE_LOCATION("duct6"),
                        REMOVE_ITEM("mop"), EARN_ACHIEVEMENT("ducts_fan_stick")
                    ],
                    hidden: true,
                },
                usefan: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.fan.usefan.label"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.fan.usefan", "\n")),
                        DIE(),
                    ],
                    hidden: true,
                },
            },
            exits: {
                east: {
                    ...SOUTH$3,
                    room: "duct2",
                },
            },
        },
        duct6: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.duct6", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.duct6.far_description"),
            targets: {},
            exits: {
                down: {
                    ...DOWN,
                    room: "lab",
                }
            }
        },
        closet: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.closet", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.closet.far_description"),
            targets: {
                exitVent: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.dropdown"),
                    actions: [
                        CHANGE_LOCATION("duct3"),
                    ],
                },
                outfit: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.closet.suit"),
                    actions: [
                        GET_ITEM("outfit"),
                        HIDE_TARGET(),
                    ],
                },
                mop: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.closet.mop"),
                    actions: [
                        GET_ITEM("mop"),
                        HIDE_TARGET(),
                    ],
                },
            },
            exits: {
                east: {
                    ...EAST$1,
                    room: "hallway1",
                },
            },
        },
        hallway1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.hallway1", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.hallway1.far_description"),
            targets: {},
            exits: {
                north: {
                    ...NORTH$4,
                    room: "hallway2",
                },
                west: {
                    ...WEST$1,
                    room: "closet",
                },
            },
        },
        hallway2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.hallway2", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.hallway2.far_description"),
            targets: {},
            exits: {
                north: {
                    ...NORTH$4,
                    room: "hallway3",
                },
                east: {
                    ...EAST$1,
                    room: "office1",
                },
                west: {
                    ...WEST$1,
                    room: "breakroom",
                },
                south: {
                    ...SOUTH$3,
                    room: "hallway1",
                },
            },
        },
        hallway3: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.hallway3", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.hallway3.far_description"),
            targets: {},
            exits: {
                east: {
                    ...EAST$1,
                    room: "hallway4",
                },
                SOUTH: {
                    ...SOUTH$3,
                    room: "hallway2",
                },
            },
        },
        hallway4: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.hallway4", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.hallway4.far_description"),
            targets: {
                lab: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.lab.entry"),
                    actions: [
                        {
                            if: {
                                condition: hasItems("keycard"),
                                actions: [
                                    SHOW_TARGET("usekeycard"),
                                ],
                            }
                        },
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.lab.entry.fail", "\n")),
                        SHOW_TARGET("useusb"),
                    ],
                    type: "look",
                },
                usekeycard: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.lab.usekeycard.label"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.lab.usekeycard", "\n")),
                        CHANGE_LOCATION("lab"),
                        REMOVE_ITEM("keycard"), EARN_ACHIEVEMENT("ducts_idcard")
                    ],
                    hidden: true,
                },
                useusb: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.lab.useusb.label"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.lab.useusb", "\n")),
                        DIE(),
                    ],
                    hidden: true,
                },
                guard2_observe: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.guard2.observe"),
                    actions: [
                        {
                            if: {
                                condition: ALL(doesNotHaveItems("wrench"), hasItems("outfit")),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.guard2.listen", "\n")),
                                ],
                                type: "talk",
                            }
                        },
                        {
                            if: {
                                condition: ALL(hasItems("wrench"), hasItems("outfit")),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.guard2.listen", "\n")),
                                    SHOW_TARGET("fixmachine"),
                                    HIDE_TARGET(),
                                ],
                                type: "talk",
                            }
                        },
                        {
                            if: {
                                condition: ALL(doesNotHaveItems("outfit")),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.room.gameover2", "\n")),
                                    DIE(),
                                ],
                            }
                        }
                    ],
                    type: "look",
                },
                fixmachine: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.fixmachine"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.machinefixed", "\n")),
                        HIDE_TARGET(),
                        SET_VALUE("act1.machinefixed", true), EARN_ACHIEVEMENT("ducts_jigsoda"),
                    ],
                    hidden: true,
                },
            },
            exits: {
                east: {
                    ...EAST$1,
                    room: "hallway5",
                },
                west: {
                    ...WEST$1,
                    room: "hallway3",
                },
            },
        },
        hallway5: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.hallway5", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.hallway5.far_description"),
            targets: {},
            exits: {
                west: {
                    ...WEST$1,
                    room: "hallway4",
                },
                south: {
                    ...SOUTH$3,
                    room: "hallway6",
                },
            },
        },
        hallway6: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.hallway6", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.hallway6.far_description"),
            targets: {},
            exits: {
                north: {
                    ...NORTH$4,
                    room: "hallway5",
                },
            },
        },
        office1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.office1", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.office1.far_description"),
            targets: {
                desk: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.office1.desk"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.office1.desk.say", "\n")),
                        GET_ITEM("keycard"),
                        HIDE_TARGET(),
                    ]
                }
            },
            exits: {
                west: {
                    ...WEST$1,
                    room: "hallway2",
                },
            },
        },
        breakroom: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.breakroom", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.breakroom.far_description"),
            targets: {
                lunchtable: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.targets.breakroom.table", "\n"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.targets.breakroom.table.say", "\n")),
                        SET_VALUE("act1.atesoup", true),
                        HIDE_TARGET(),
                    ]
                },
                microwave: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.targets.breakroom.microwave", "\n"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.targets.breakroom.microwave.say", "\n")),
                        GET_ITEM("wrench"),
                        HIDE_TARGET(),
                    ]
                },
            },
            exits: {
                east: {
                    ...EAST$1,
                    room: "hallway2",
                },
            },
        },
        lab: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.lab", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.lab.far_description"),
            targets: {
                computer: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.pc"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.pc.description", "\n")),
                        SET_VALUE("act1.computer", true),
                        GET_ITEM("filledusbkey"),
                        REMOVE_ITEM("usbkey"),
                        CHANGE_LOCATION("act3lab"),
                    ],
                    type: "use",
                },
                vat0: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat0"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat0.description", "\n")),
                    ],
                    type: "talk",
                },
                vat1: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat1"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat1.description", "\n")),
                    ],
                    type: "talk",
                },
                vat2: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat2"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat2.description", "\n")),
                    ],
                    type: "talk",
                },
                vat3: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat3"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat3.description", "\n")),
                    ],
                    type: "talk",
                },
                vat4: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat4"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat4.description", "\n")),
                    ],
                    type: "talk",
                },
                vat5: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat5"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat5.description", "\n")),
                    ],
                    type: "talk",
                },
                vat6: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat6"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat6.description", "\n")),
                    ],
                    type: "talk",
                },
                vat7: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat7"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat7.description", "\n")),
                    ],
                    type: "talk",
                },
                vat8: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat8"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat8.description", "\n")),
                    ],
                    type: "talk",
                },
                vat9: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat9"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.lab.vat9.description", "\n")),
                    ],
                    type: "talk",
                },
            },
            exits: {
                south: {
                    ...SOUTH$3,
                    room: "hallway4",
                },
            },
        },
        act3lab: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.act3lab", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.act3lab.far_description"),
            targets: {},
            exits: {
                south: {
                    ...SOUTH$3,
                    room: "act3hallway4",
                },
            }
        },
        act3hallway4: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.act3hallway4", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.hallway4.far_description"),
            targets: {},
            exits: {
                east: {
                    ...EAST$1,
                    room: "act3hallway5",
                },
            }
        },
        act3hallway5: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.act3hallway5", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.hallway5.far_description"),
            targets: {},
            exits: {
                south: {
                    ...SOUTH$3,
                    room: "act3end",
                },
            }
        },
        act3end: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.act3end", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.duct.room.end.far_description"),
            targets: {
                timetoleave: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.end.timetoleave"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.end.timetoleave.say", "\n")),
                        WON("The Lab", "{0} escaped with the data!", "player"),
                    ],
                }
            },
            exits: {}
        },
    },
    items: {
        "outfit": {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.item.suit", "\n"),
        },
        "wrench": {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.item.wrench", "\n"),
        },
        "mop": {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.item.mop", "\n"),
        },
        "keycard": {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.item.keycard", "\n"),
        },
        "usbkey": {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.item.usbkey", "\n"),
        },
        "filledusbkey": {
            description: TRANSLATE$1("jig_ccomp:text-adventure.duct.targets.item.filledusbkey", "\n"),
        },
    },
    achievements: Object.fromEntries(["ducts_fan_stick", "ducts_idcard", "ducts_jigsoda", "ducts_toilet"].map((id) => [
        id,
        {
            name: `jig_ccomp:text-adventure.duct.achievement.${id}.name`,
            description: `jig_ccomp:text-adventure.duct.achievement.${id}.description`,
            hint: `jig_ccomp:text-adventure.duct.achievement.${id}.hint`,
            icon: `textures/jig/ccomp/items/art/${id}.png`,
            item: `jig_ccomp:poster_${id}`,
            print_title: "",
            print_content: "",
        },
    ])),
});

const SOUTH$2 = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.exit.south"), type: "south",
});
const NORTH$3 = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.exit.north"), type: "north",
});
const EAST = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.exit.east"), type: "east",
});
const WEST = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.exit.west"), type: "west",
});
const GO = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.exit.go"), type: "inside",
});
const ENTER = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.exit.enter"), type: "inside",
});
makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.exit.down"),
});
makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.exit.up"),
});
const SHORTCUT = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.shortcut_home"),
});
const FISHERMAN = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.fisherman"),
});
const newGrimForestAdventureState = () => ({
    version: 1,
    inventory: [],
    status: 'playing',
    props: { "dev.knows.froggo": false, "dev.quest.merchant": false, "dev.quest.mouse": false, "dev.quest.bbq": false, "dev.found.shortcut": false },
    nextPrompt: [TRANSLATE$1("jig_ccomp:text-adventure.grimforest.introduction", "\n")],
    currentRoom: "firststep",
});
const newGrimForestAdventure = () => makeTextAdventure({
    overrides: {
        ui: {
            status: {
                title: "jig_ccomp:text-adventure.ui.select-adventure.adventure.grimforest",
            }
        }
    },
    rooms: {
        firststep: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.firststep", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.firststep.far_description"),
            targets: {
                memory1: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.remember"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.memory1Speaks", "\n")),
                        HIDE_TARGET(),
                    ],
                    type: "look",
                },
                froggoIntro1: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.shadowyfigure"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.froggoSpeaks1", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("froggoIntro2"),
                        SET_VALUE("knows.froggo", true),
                    ],
                    type: "talk",
                },
                froggoIntro2: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.froggo"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.froggoSpeaks2", "\n")),
                        HIDE_TARGET(),
                    ],
                    type: "talk",
                    hidden: true,
                },
            },
            exits: {
                north: {
                    ...NORTH$3,
                    room: "steep_decline",
                },
                walk: {
                    ...SHORTCUT,
                    room: "home_village",
                    filter: IS_VALUE("found.shortcut", true),
                },
            },
        },
        steep_decline: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.steep_decline", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.steep_decline.far_description"),
            targets: {
                merchantIntro: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.merchant.label"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.merchant.intro", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("merchantHelp"),
                        SHOW_TARGET("merchantRefuse"),
                    ],
                    type: "talk",
                },
                merchantHelp: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.merchant.accept"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.merchant.help", "\n")),
                        HIDE_TARGET(),
                        HIDE_TARGET("merchantRefuse"),
                        SHOW_TARGET("merchantReward"),
                    ],
                    type: "talk",
                    hidden: true,
                },
                merchantRefuse: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.merchant.refuse"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.merchant.refused", "\n")),
                        HIDE_TARGET(),
                        HIDE_TARGET("merchantHelp"),
                    ],
                    type: "talk",
                    hidden: true,
                },
                merchantReward: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.merchant.reward"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.merchant.rewarded", "\n")),
                        HIDE_TARGET(),
                        SET_VALUE("quest.merchant", true),
                    ],
                    type: "talk",
                    hidden: true,
                },
            },
            exits: {
                north: {
                    ...NORTH$3,
                    room: "sleeping_cat",
                },
                south: {
                    ...SOUTH$2,
                    room: "firststep",
                },
            },
        },
        steep_decline_2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.steep_decline_2", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.steep_decline_2.far_description"),
            targets: {
                merchantInfo: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.merchant.info"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.merchant.info.details", "\n")),
                    ],
                    type: "look",
                },
            },
            exits: {
                north: {
                    ...NORTH$3,
                    room: "sleeping_cat",
                },
            },
        },
        sleeping_cat: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.sleeping_cat", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.sleeping_cat.far_description"),
            targets: {
                observecat: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.cat.label"),
                    actions: [
                        {
                            if: {
                                condition: hasItems("milk"),
                                actions: [SHOW_TARGET("usemilk")],
                            },
                        },
                        {
                            if: {
                                condition: ALL(hasItems("mouse"), IS_VALUE("quest.gave_milk", true)),
                                actions: [SHOW_TARGET("usemouse")],
                            },
                        },
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.cat.speak", "\n")),
                    ],
                    type: "look",
                },
                usemilk: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.cat.milk"),
                    actions: [
                        {
                            if: {
                                condition: hasItems("mouse"),
                                actions: [SHOW_TARGET("usemouse")],
                            },
                        },
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.cat.milk.speak", "\n")),
                        HIDE_TARGET(),
                        SET_VALUE("quest.gave_milk", true),
                        REMOVE_ITEM("milk"),
                    ],
                    type: "talk",
                    hidden: true,
                },
                usemouse: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.cat.mouse"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.cat.mouse.speak", "\n")),
                        HIDE_TARGET(),
                        HIDE_TARGET("observecat"),
                        REMOVE_ITEM("mouse"),
                        SET_VALUE("quest.mouse", true), EARN_ACHIEVEMENT("gf_knight"),
                    ],
                    type: "talk",
                    hidden: true,
                },
            },
            exits: {
                north: {
                    ...NORTH$3,
                    room: "river_travel",
                },
            },
        },
        river_travel: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.river_travel", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.river_travel.far_description"),
            targets: {},
            exits: {
                north: {
                    ...NORTH$3,
                    room: "river_travel2",
                }
            },
        },
        river_travel2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.river_travel2", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.river_travel2.far_description"),
            targets: {},
            exits: {
                east: {
                    ...EAST,
                    room: "bbq_lake",
                },
                west: {
                    ...WEST,
                    room: "broken_bridge",
                },
            },
        },
        bbq_lake: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.bbq_lake", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.bbq_lake.far_description"),
            targets: {
                familybbq: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.bbq.label"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.bbq.speak", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("noice"),
                    ],
                    type: "look",
                },
                noice: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.bbq.cook"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.bbq.noice.speak", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("speaktocook"),
                    ],
                    type: "talk",
                    hidden: true,
                },
                "speaktocook": {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.bbq.cook"),
                    actions: [
                        {
                            if: {
                                condition: hasItems("ice"),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.bbq.cook.reward", "\n")),
                                    HIDE_TARGET(),
                                    HIDE_TARGET("speaktocook"),
                                    SET_VALUE("quest.bbq", true),
                                    SHOW_TARGET("travelback"),
                                    REMOVE_ITEM("ice"),
                                    GET_ITEM("milk"),
                                ]
                            },
                        },
                        {
                            if: {
                                condition: IS_VALUE("quest.bbq", false),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.bbq.cook.speak", "\n")),
                                    HIDE_TARGET(),
                                ]
                            }
                        }
                    ],
                    type: "talk",
                    hidden: true,
                },
                checkpointbeach: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.bbq.checkpoint"),
                    actions: [
                        {
                            if: {
                                condition: IS_VALUE("knows.froggo", true),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.bbq.checkpoint.speak", "\n")),
                                ]
                            },
                        },
                        {
                            if: {
                                condition: IS_VALUE("knows.froggo", false),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.bbq.checkpoint.findfroggo", "\n")),
                                    SET_VALUE("knows.froggo", true),
                                    HIDE_TARGET("froggoIntro1"),
                                ]
                            }
                        },
                        HIDE_TARGET(),
                        SHOW_TARGET("checkpointbeach2"),
                    ],
                    type: "look",
                },
                checkpointbeach2: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.bbq.checkpoint2"),
                    actions: [
                        HIDE_TARGET(),
                        HIDE_TARGET("noice"),
                        HIDE_TARGET("familybbq"),
                        SHOW_TARGET("speaktocook"),
                        CHANGE_LOCATION("mountain_top"),
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.bbq.checkpoint2.speak", "\n")),
                    ],
                    type: "talk",
                    hidden: true,
                },
                travelback: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.froggo.travelback"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.froggo.travelback.speak", "\n")),
                        HIDE_TARGET(),
                        CHANGE_LOCATION("firststep"),
                    ],
                    type: "look",
                    hidden: true,
                },
            },
            exits: {
                north: {
                    ...NORTH$3,
                    room: "overgrown_path",
                },
            },
        },
        overgrown_path: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.overgrown_path", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.overgrown_path.far_description"),
            targets: {},
            exits: {
                north: {
                    ...NORTH$3,
                    room: "wide_river",
                },
                south: {
                    ...SOUTH$2,
                    room: "bbq_lake",
                }
            },
        },
        broken_bridge: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.broken_bridge", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.broken_bridge.far_description"),
            targets: {
                remember2: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.remember"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.memory2Speaks", "\n")),
                        HIDE_TARGET(),
                    ],
                    type: "look",
                },
                mouse: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.mouse.label1"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.mouse.speak", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("mouse2"),
                    ],
                    type: "talk",
                },
                mouse2: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.mouse.label2"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.mouse.history1", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("mouse3"),
                    ],
                    type: "talk",
                    hidden: true,
                },
                mouse3: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.mouse.label2"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.mouse.history2", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("mouse4"),
                    ],
                    type: "talk",
                    hidden: true,
                },
                mouse4: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.mouse.label2"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.mouse.history3", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("mouse5"), EARN_ACHIEVEMENT("gf_brokenbridge"),
                    ],
                    type: "talk",
                    hidden: true,
                },
                mouse5: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.mouse.leave"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.mouse.quest", "\n")),
                        HIDE_TARGET(),
                        GET_ITEM("mouse"),
                    ],
                    type: "talk",
                    hidden: true,
                },
            },
            exits: {
                east: {
                    ...EAST,
                    room: "bbq_lake",
                },
            },
        },
        mountain_top: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.mountain_top", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.mountain_top.far_description"),
            targets: {
                ice: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.mountain_top.ice"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.mountain_top.ice.speak", "\n")),
                        HIDE_TARGET(),
                        GET_ITEM("ice"),
                        SHOW_TARGET("leavemountain"),
                    ],
                    type: "look",
                },
                leavemountain: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.mountain_top.leave"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.mountain_top.leave.speak", "\n")),
                        HIDE_TARGET(),
                        CHANGE_LOCATION("bbq_lake"),
                    ],
                    type: "look",
                    hidden: true,
                },
            },
            exits: {},
        },
        wide_river: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.wide_river", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.wide_river.far_description"),
            targets: {
                rivercrossing: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.rivercrossing.label"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.rivercrossing.speak", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("rivercrossing2"),
                    ],
                    type: "talk",
                },
                rivercrossing2: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.rivercrossing.label"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.rivercrossing2.speak", "\n")),
                        HIDE_TARGET(),
                        SET_VALUE("knows.fisherman", true),
                        CHANGE_LOCATION("home_village"),
                    ],
                    type: "talk",
                    hidden: true,
                },
            },
            exits: {
                walk: {
                    ...FISHERMAN,
                    room: "home_village",
                    filter: IS_VALUE("knows.fisherman", true),
                },
            },
        },
        home_village: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.home_village", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.home_village.far_description"),
            targets: {
                finalcheckpoint: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.finalcheckpoint.label"),
                    actions: [
                        {
                            if: {
                                condition: IS_VALUE("knows.froggo", true),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.finalcheckpoint.speak", "\n")),
                                    SHOW_TARGET("finalcheckpoint2"),
                                    HIDE_TARGET(),
                                ]
                            },
                        },
                        {
                            if: {
                                condition: IS_VALUE("knows.froggo", false),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.finalcheckpoint.meetfroggo", "\n")),
                                    SET_VALUE("knows.froggo", true),
                                    SHOW_TARGET("finalcheckpoint2"),
                                    HIDE_TARGET(),
                                ]
                            }
                        },
                    ],
                    type: "look",
                },
                finalcheckpoint2: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.finalcheckpoint.label"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.finalcheckpoint2.speak", "\n")),
                        SET_VALUE("found.shortcut", true),
                        CHANGE_LOCATION("firststep"),
                        HIDE_TARGET("froggoIntro1"),
                    ],
                    type: "look",
                    hidden: true,
                },
            },
            exits: {
                north: {
                    ...NORTH$3,
                    room: "home_village_2",
                },
            },
        },
        home_village_2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.home_village_2", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.home_village_2.far_description"),
            targets: {},
            exits: {
                inside: {
                    ...ENTER,
                    room: "happy_tooth",
                },
                walk: {
                    ...GO,
                    room: "home",
                }
            },
        },
        happy_tooth: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.happy_tooth", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.happy_tooth.far_description"),
            targets: {
                greet: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.happy_tooth.greet"),
                    actions: [
                        {
                            if: {
                                condition: IS_VALUE("quest.bbq", true),
                                actions: [SHOW_TARGET("finalcook")],
                            },
                        },
                        {
                            if: {
                                condition: IS_VALUE("quest.merchant", true),
                                actions: [SHOW_TARGET("finalmerchant")],
                            },
                        },
                        {
                            if: {
                                condition: IS_VALUE("quest.mouse", true),
                                actions: [SHOW_TARGET("finalmouse")],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("quest.mouse", true), IS_VALUE("quest.bbq", true), IS_VALUE("quest.merchant", true)),
                                actions: [SHOW_TARGET("finalfroggo")],
                            },
                        },
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.happy_tooth.greet.speak", "\n")),
                        HIDE_TARGET(),
                    ],
                    type: "look",
                },
                finalcook: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.happy_tooth.cook"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.happy_tooth.cook.speak", "\n")),
                        HIDE_TARGET(),
                        GET_ITEM("finalmeal"),
                    ],
                    type: "talk",
                    hidden: true,
                },
                finalmerchant: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.happy_tooth.merchant"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.happy_tooth.merchant.speak", "\n")),
                        HIDE_TARGET(),
                        GET_ITEM("finalcoin"), EARN_ACHIEVEMENT("gf_cankerforest"),
                    ],
                    type: "talk",
                    hidden: true,
                },
                finalmouse: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.happy_tooth.mouse"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.happy_tooth.mouse.speak", "\n")),
                        HIDE_TARGET(),
                        GET_ITEM("finalcheese"), EARN_ACHIEVEMENT("gf_cheese"),
                    ],
                    type: "talk",
                    hidden: true,
                },
                finalfroggo: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.happy_tooth.froggo"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.happy_tooth.froggo.speak", "\n")),
                        HIDE_TARGET(), EARN_ACHIEVEMENT("gf_froggo"),
                    ],
                    type: "talk",
                    hidden: true,
                },
            },
            exits: {
                outside: {
                    ...GO,
                    room: "home",
                }
            },
        },
        home: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.home", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.home.far_description"),
            targets: {
                sleep: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.home.sleep.label"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.grimforest.home.sleep.speak", "\n")),
                        WON("Grim Forest", "{0} found their way home, after one last grand adventure. Rest now, Slayer of Mucosa; Hero of Gingiva Village.", "player"),
                    ],
                },
            },
            exits: {},
        }
    },
    items: {
        milk: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.item.milk", "\n"),
        },
        mouse: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.item.mouse", "\n"),
        },
        ice: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.item.ice", "\n"),
        },
        finalmeal: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.item.finalmeal", "\n"),
        },
        finalcoin: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.item.finalcoin", "\n"),
        },
        finalcheese: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.grimforest.item.finalcheese", "\n"),
        },
    },
    achievements: Object.fromEntries(["gf_brokenbridge", "gf_cankerforest", "gf_cheese", "gf_froggo", "gf_knight"].map((id) => [
        id,
        {
            name: `jig_ccomp:text-adventure.grimforest.achievement.${id}.name`,
            description: `jig_ccomp:text-adventure.grimforest.achievement.${id}.description`,
            hint: `jig_ccomp:text-adventure.grimforest.achievement.${id}.hint`,
            icon: `textures/jig/ccomp/items/art/${id}.png`,
            item: `jig_ccomp:poster_${id}`,
            print_title: "",
            print_content: "",
        },
    ])),
});

const EXIT1 = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.exit.1"), type: "outside"
});
const EXIT2 = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.exit.2"),
});
const EXIT3 = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.exit.3"),
});
const EXIT4 = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.exit.4"), type: "north"
});
const EXIT5 = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.exit.5"), type: "south"
});
const EXIT6 = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.exit.6"), type: "east"
});
const EXIT7 = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.exit.7"), type: "west"
});
const EXIT8 = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.exit.8"), type: "northeast"
});
const PIGLIN_ENGINEER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.piglin_engineer"),
    actions: [
        {
            if: {
                condition: ALL(doesNotHaveItems("evidence_1"), doesNotHaveItems("evidence_1_submitted")),
                actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.piglin_engineer-response", "\n"))],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.piglin_engineer-response-2", "\n"))],
        },
    ], type: "talk"
});
const BABY_PIGLIN = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.baby_piglin"),
    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.baby_piglin-response", "\n"))],
});
const LEVER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.lever"),
    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.lever-response", "\n"))],
});
const BELL = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.bell"),
    actions: [
        {
            if: {
                condition: ALL(doesNotHaveItems("evidence_1"), doesNotHaveItems("evidence_1_submitted")),
                actions: [GET_ITEM("evidence_1"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.bell-response", "\n"))],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.bell-response-2", "\n"))],
        },
    ],
});
const OBSERVER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.observer"),
    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.observer-response", "\n"))], type: "look"
});
const BLAZE_OPTION_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.blaze_option_1"),
    actions: [HIDE_TARGET(), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.blaze_option_1-response", "\n")), CHANGE_LOCATION("act1_street")], type: "talk"
});
const BLAZE_OPTION_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.blaze_option_2"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.blaze_option_2-response", "\n")),
        CHANGE_LOCATION("act1_blaze_house_2")
    ], type: "talk"
});
const BLAZE_OPTION_3 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.blaze_option_3"),
    actions: [HIDE_TARGET(), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.blaze_option_3-response", "\n")), CHANGE_LOCATION("act1_street")], type: "talk"
});
const BLAZE = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.blaze"),
    actions: [
        {
            if: {
                condition: ALL(doesNotHaveItems("evidence_2"), doesNotHaveItems("evidence_2_submitted")),
                actions: [GET_ITEM("evidence_2"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.blaze-response", "\n"))],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.blaze-response-2", "\n"))],
        },
    ],
});
const SHEEP_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.sheep_1"),
    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.sheep_1-response", "\n"))], type: "walk"
});
const SHEEP_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.sheep_2"),
    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.sheep_2-response", "\n"))], type: "talk"
});
const SHEEP_3 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.sheep_3"),
    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.sheep_3-response", "\n"))], type: "talk"
});
const SHEEP_4 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.sheep_4"),
    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.sheep_4-response", "\n"))], type: "look"
});
const SHEEP_5 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.sheep_5"),
    actions: [
        {
            if: {
                condition: ALL(doesNotHaveItems("evidence_3"), doesNotHaveItems("evidence_3_submitted")),
                actions: [
                    GET_ITEM("evidence_3"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.sheep_5-response", "\n")),
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.sheep_5-response-2", "\n"))],
        },
    ], type: "talk"
});
const SHEEP_6 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.sheep_6"),
    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.sheep_6-response", "\n"))], type: "walk"
});
const SHEEP_7 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.sheep_7"),
    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.sheep_7-response", "\n"))], type: "walk"
});
const STEVE = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.steve"),
    actions: [
        {
            if: {
                condition: ALL(doesNotHaveItems("evidence_1"), doesNotHaveItems("evidence_2"), doesNotHaveItems("evidence_3")),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.steve-response-1", "\n")),
                ],
            },
            elseif: [
                {
                    condition: hasItems("evidence_1", "evidence_2_submitted", "evidence_3_submitted"),
                    actions: [
                        REMOVE_ITEM("evidence_1"),
                        REMOVE_ITEM("evidence_2"),
                        REMOVE_ITEM("evidence_3"),
                        REMOVE_ITEM("evidence_1_submitted"),
                        REMOVE_ITEM("evidence_2_submitted"),
                        REMOVE_ITEM("evidence_3_submitted"),
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.steve-response-5", "\n")),
                        CHANGE_LOCATION("act2_introduction")
                    ],
                },
                {
                    condition: hasItems("evidence_1_submitted", "evidence_2", "evidence_3_submitted"),
                    actions: [
                        REMOVE_ITEM("evidence_1"),
                        REMOVE_ITEM("evidence_2"),
                        REMOVE_ITEM("evidence_3"),
                        REMOVE_ITEM("evidence_1_submitted"),
                        REMOVE_ITEM("evidence_2_submitted"),
                        REMOVE_ITEM("evidence_3_submitted"),
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.steve-response-6", "\n")),
                        CHANGE_LOCATION("act2_introduction")
                    ],
                },
                {
                    condition: hasItems("evidence_1_submitted", "evidence_2_submitted", "evidence_3"),
                    actions: [
                        REMOVE_ITEM("evidence_1"),
                        REMOVE_ITEM("evidence_2"),
                        REMOVE_ITEM("evidence_3"),
                        REMOVE_ITEM("evidence_1_submitted"),
                        REMOVE_ITEM("evidence_2_submitted"),
                        REMOVE_ITEM("evidence_3_submitted"),
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.steve-response-7", "\n")),
                        CHANGE_LOCATION("act2_introduction")
                    ],
                },
                {
                    condition: hasItems("evidence_1"),
                    actions: [
                        GET_ITEM("evidence_1_submitted"),
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.steve-response-2", "\n")),
                        REMOVE_ITEM("evidence_1")
                    ],
                },
                {
                    condition: hasItems("evidence_2"),
                    actions: [
                        GET_ITEM("evidence_2_submitted"),
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.steve-response-3", "\n")),
                        REMOVE_ITEM("evidence_2")
                    ],
                },
                {
                    condition: hasItems("evidence_3"),
                    actions: [
                        GET_ITEM("evidence_3_submitted"),
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.steve-response-4", "\n")),
                        REMOVE_ITEM("evidence_3")
                    ],
                },
            ],
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.steve-response-1", "\n"))],
        },
    ],
});
const IRON_GOLEM = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.iron_golem"),
    actions: [
        {
            if: {
                condition: ALL(doesNotHaveItems("wither_rose"), doesNotHaveItems("dead_bush"), doesNotHaveItems("dead_fire_coral")),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.iron_golem-response", "\n"))
                ],
            },
            elseif: [
                {
                    condition: hasItems("wither_rose", "dead_bush_submitted", "dead_fire_coral_submitted"),
                    actions: [
                        GET_ITEM("letter_of_support"),
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.iron_golem-response-5", "\n")),
                        REMOVE_ITEM("wither_rose"),
                        REMOVE_ITEM("wither_rose_submitted"),
                        REMOVE_ITEM("dead_bush"),
                        REMOVE_ITEM("dead_bush_submitted"),
                        REMOVE_ITEM("dead_fire_coral"),
                        REMOVE_ITEM("dead_fire_coral_submitted"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems("wither_rose_submitted", "dead_bush", "dead_fire_coral_submitted"),
                    actions: [
                        GET_ITEM("letter_of_support"),
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.iron_golem-response-6", "\n")),
                        REMOVE_ITEM("wither_rose"),
                        REMOVE_ITEM("wither_rose_submitted"),
                        REMOVE_ITEM("dead_bush"),
                        REMOVE_ITEM("dead_bush_submitted"),
                        REMOVE_ITEM("dead_fire_coral"),
                        REMOVE_ITEM("dead_fire_coral_submitted"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems("wither_rose_submitted", "dead_bush_submitted", "dead_fire_coral"),
                    actions: [
                        GET_ITEM("letter_of_support"),
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.iron_golem-response-7", "\n")),
                        REMOVE_ITEM("wither_rose"),
                        REMOVE_ITEM("wither_rose_submitted"),
                        REMOVE_ITEM("dead_bush"),
                        REMOVE_ITEM("dead_bush_submitted"),
                        REMOVE_ITEM("dead_fire_coral"),
                        REMOVE_ITEM("dead_fire_coral_submitted"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems("wither_rose"),
                    actions: [
                        GET_ITEM("wither_rose_submitted"),
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.iron_golem-response-2", "\n")),
                        REMOVE_ITEM("wither_rose")
                    ],
                },
                {
                    condition: hasItems("dead_bush"),
                    actions: [
                        GET_ITEM("dead_bush_submitted"),
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.iron_golem-response-3", "\n")),
                        REMOVE_ITEM("dead_bush")
                    ],
                },
                {
                    condition: hasItems("dead_fire_coral"),
                    actions: [
                        GET_ITEM("dead_fire_coral_submitted"),
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.iron_golem-response-4", "\n")),
                        REMOVE_ITEM("dead_fire_coral")
                    ],
                },
            ],
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.iron_golem-response", "\n"))],
        },
    ],
});
const FOUNTAIN = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.fountain"),
    actions: [
        {
            if: {
                condition: ANY(hasItems("empty_bottle"), hasItems("potion_water_breathing"), hasItems("potion_wither")),
                actions: [
                    GET_ITEM("potion_regeneration"), REMOVE_ITEM("empty_bottle"), REMOVE_ITEM("potion_water_breathing"), REMOVE_ITEM("potion_wither"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.fountain-response-2", "\n"))
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.fountain-response", "\n"))],
        },
    ], type: "look"
});
const CAT = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.cat"),
    actions: [
        {
            if: {
                condition: hasItems("potion_wither"),
                actions: [
                    GET_ITEM("letter_of_support"),
                    REMOVE_ITEM("potion_wither"),
                    GET_ITEM("empty_bottle"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.cat-response-2", "\n")),
                    HIDE_TARGET()
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.cat-response", "\n"))],
        },
    ],
});
const WITCH = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.witch"),
    actions: [
        {
            if: {
                condition: ANY(hasItems("empty_bottle"), hasItems("potion_water_breathing"), hasItems("potion_wither"), hasItems("potion_regeneration")),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.witch-response-2", "\n")),
                ],
            },
            else: [GET_ITEM("empty_bottle"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.witch-response", "\n"))],
        },
    ], type: "talk"
});
const ARMORER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.armorer"),
    actions: [
        {
            if: {
                condition: hasItems("stick_arms"),
                actions: [
                    SHOW_TARGET("armorer_option_1"),
                    SHOW_TARGET("armorer_option_2"),
                    SHOW_TARGET("armorer_option_3"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.armorer-response-2", "\n")),
                    HIDE_TARGET()
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.armorer-response", "\n"))],
        },
    ],
});
const ARMORER_OPTION_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.armorer_option_1"),
    actions: [
        REMOVE_ITEM("stick_arms"),
        GET_ITEM("lever_arms"),
        HIDE_TARGET("armorer_option_1"),
        HIDE_TARGET("armorer_option_2"),
        HIDE_TARGET("armorer_option_3"),
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.armorer-response-3", "\n"))
    ], type: "talk"
});
const ARMORER_OPTION_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.armorer_option_2"),
    actions: [
        REMOVE_ITEM("stick_arms"),
        GET_ITEM("lever_arms"),
        HIDE_TARGET("armorer_option_1"),
        HIDE_TARGET("armorer_option_2"),
        HIDE_TARGET("armorer_option_3"),
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.armorer-response-3", "\n"))
    ], type: "talk"
});
const ARMORER_OPTION_3 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.armorer_option_3"),
    actions: [
        REMOVE_ITEM("stick_arms"),
        GET_ITEM("lever_arms"),
        HIDE_TARGET("armorer_option_1"),
        HIDE_TARGET("armorer_option_2"),
        HIDE_TARGET("armorer_option_3"),
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.armorer-response-3", "\n"))
    ], type: "talk"
});
const CREEPER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.creeper"),
    actions: [
        {
            if: {
                condition: hasItems("steve_music_disk"),
                actions: [
                    REMOVE_ITEM("steve_music_disk"),
                    SHOW_TARGET("record"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.creeper-response-2", "\n")),
                    HIDE_TARGET()
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.creeper-response", "\n"))],
        },
    ], type: "walk"
});
const RECORD = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.record"),
    actions: [GET_ITEM("dj_music_disk"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.record-response", "\n")), HIDE_TARGET()],
});
const HOPPER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.hopper"),
    actions: [
        {
            if: {
                condition: hasItems({
                    id: "letter_of_support",
                    count: 8,
                }),
                actions: [
                    REMOVE_ITEM("empty_bucket"),
                    REMOVE_ITEM("ice_bucket"),
                    REMOVE_ITEM("empty_bottle"),
                    REMOVE_ITEM("potion_regeneration"),
                    REMOVE_ITEM("potion_water_breathing"),
                    REMOVE_ITEM("potion_wither"),
                    REMOVE_ITEM("steve_music_disk"),
                    REMOVE_ITEM("dj_music_disk"),
                    REMOVE_ITEM("wither_rose"),
                    REMOVE_ITEM("dead_bush"),
                    REMOVE_ITEM("dead_fire_coral"),
                    REMOVE_ITEM("wither_rose_submitted"),
                    REMOVE_ITEM("dead_bush_submitted"),
                    REMOVE_ITEM("dead_fire_coral_submitted"),
                    REMOVE_ITEM("dead_brain_coral"),
                    REMOVE_ITEM("sponge"),
                    REMOVE_ITEM("lever_arms"),
                    REMOVE_ITEM("stick_arms"),
                    REMOVE_ITEM("letter_of_support", 100),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.hopper-response-2", "\n")),
                    CHANGE_LOCATION("act3_introduction")
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.hopper-response", "\n"))],
        },
    ],
});
const ZOMBIE = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.zombie"),
    actions: [
        {
            if: {
                condition: hasItems("dead_brain_coral"),
                actions: [
                    GET_ITEM("letter_of_support"),
                    REMOVE_ITEM("dead_brain_coral"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.zombie-response-2", "\n")),
                    HIDE_TARGET()
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.zombie-response", "\n"))],
        },
    ],
});
const PUFFERFISH = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.pufferfish"),
    actions: [
        {
            if: {
                condition: hasItems("sponge"),
                actions: [
                    GET_ITEM("letter_of_support"),
                    REMOVE_ITEM("sponge"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.pufferfish-response-2", "\n")),
                    HIDE_TARGET()
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.pufferfish-response", "\n"))],
        },
    ], type: "look"
});
const ENDERMAN = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.enderman"),
    actions: [
        SHOW_TARGET("enderman_option_1"),
        SHOW_TARGET("enderman_option_2"),
        SHOW_TARGET("enderman_option_3"),
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.enderman-response", "\n")),
        HIDE_TARGET()
    ],
});
const ENDERMAN_OPTION_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.enderman_option_1"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.enderman_option_1-response", "\n")),
        HIDE_TARGET(),
    ], type: "talk"
});
const ENDERMAN_OPTION_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.enderman_option_2"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.enderman_option_2-response", "\n")),
        HIDE_TARGET(),
    ], type: "talk"
});
const ENDERMAN_OPTION_3 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.enderman_option_3"),
    actions: [
        HIDE_TARGET("enderman_option_1"),
        HIDE_TARGET("enderman_option_2"),
        HIDE_TARGET("enderman_option_3"),
        SHOW_TARGET("enderman_option_4"),
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.enderman_option_3-response", "\n")),
    ], type: "talk"
});
const ENDERMAN_OPTION_4 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.enderman_option_4"),
    actions: [
        {
            if: {
                condition: hasItems("ice_bucket"),
                actions: [
                    GET_ITEM("letter_of_support"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.enderman_option_4-response-2", "\n")),
                    REMOVE_ITEM("ice_bucket"),
                    HIDE_TARGET()
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.enderman_option_4-response", "\n"))],
        },
    ], type: "talk"
});
const ENDERCHILD_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.enderchild_1"),
    actions: [GET_ITEM("empty_bucket"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.enderchild_1-response", "\n")), HIDE_TARGET()],
});
const ENDERCHILD_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.enderchild_2"),
    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.enderchild_2-response", "\n")), HIDE_TARGET()],
});
const SEA_TURTLE = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.sea_turtle"),
    actions: [GET_ITEM("sponge"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.sea_turtle-response", "\n")), HIDE_TARGET()], type: "talk"
});
const CORAL_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.coral_1"),
    actions: [GET_ITEM("dead_brain_coral"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.coral_1-response", "\n")), HIDE_TARGET()],
});
const CORAL_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.coral_2"),
    actions: [GET_ITEM("dead_fire_coral"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.coral_2-response", "\n")), HIDE_TARGET()],
});
const ALLAY = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.allay"),
    actions: [
        {
            if: {
                condition: hasItems("empty_bucket"),
                actions: [
                    REMOVE_ITEM("empty_bucket"),
                    GET_ITEM("ice_bucket"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.allay-response-2", "\n")),
                    HIDE_TARGET()
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.allay-response", "\n"))],
        },
    ], type: "talk"
});
const POLAR_BEAR = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.polar_bear"),
    actions: [
        {
            if: {
                condition: hasItems("potion_regeneration"),
                actions: [
                    GET_ITEM("letter_of_support"),
                    REMOVE_ITEM("potion_regeneration"),
                    GET_ITEM("empty_bottle"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.polar_bear-response-2", "\n")),
                    HIDE_TARGET()
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.polar_bear-response", "\n"))],
        },
    ],
});
const SNOW_GOLEM = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.snow_golem"),
    actions: [
        {
            if: {
                condition: hasItems("lever_arms"),
                actions: [
                    GET_ITEM("letter_of_support"),
                    REMOVE_ITEM("lever_arms"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.snow_golem-response-3", "\n")),
                    HIDE_TARGET()
                ],
            },
            elseif: {
                condition: hasItems("stick_arms"),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.snow_golem-response-2", "\n")),
                ],
            },
            else: [
                GET_ITEM("stick_arms"),
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.snow_golem-response", "\n"))
            ],
        },
    ], type: "talk"
});
const SPRING = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.spring"),
    actions: [
        {
            if: {
                condition: ANY(hasItems("empty_bottle"), hasItems("potion_regeneration"), hasItems("potion_wither")),
                actions: [
                    GET_ITEM("potion_water_breathing"), REMOVE_ITEM("empty_bottle"), REMOVE_ITEM("potion_regeneration"), REMOVE_ITEM("potion_wither"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.spring-response-2", "\n"))
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.spring-response", "\n"))],
        },
    ],
});
const PARROT = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.parrot"),
    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.parrot-response", "\n"))], type: "walk"
});
const ROSES = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.roses"),
    actions: [GET_ITEM("wither_rose"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.roses-response", "\n")), HIDE_TARGET()],
});
const RIVER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.river"),
    actions: [
        {
            if: {
                condition: ANY(hasItems("empty_bottle"), hasItems("potion_regeneration"), hasItems("potion_water_breathing")),
                actions: [
                    GET_ITEM("potion_wither"), REMOVE_ITEM("empty_bottle"), REMOVE_ITEM("potion_regeneration"), REMOVE_ITEM("potion_water_breathing"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.river-response-2", "\n"))
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.river-response", "\n"))],
        },
    ],
});
const JUKEBOX = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.jukebox"),
    actions: [
        {
            if: {
                condition: hasItems("dj_music_disk"),
                actions: [
                    GET_ITEM("letter_of_support"),
                    REMOVE_ITEM("dj_music_disk"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.jukebox-response-3", "\n")),
                    HIDE_TARGET(),
                    HIDE_TARGET("parrot")
                ],
            },
            elseif: {
                condition: hasItems("steve_music_disk"),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.jukebox-response-2", "\n")),
                ],
            },
            else: [
                GET_ITEM("steve_music_disk"),
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.jukebox-response", "\n"))
            ],
        },
    ],
});
const BEEHIVE = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.beehive"),
    actions: [
        SHOW_TARGET("bee_option_1"),
        SHOW_TARGET("bee_option_2"),
        SHOW_TARGET("bee_option_3"),
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.beehive-response", "\n")),
        HIDE_TARGET()
    ],
});
const BEE_OPTION_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.bee_option_1"),
    actions: [
        GET_ITEM("letter_of_support"),
        HIDE_TARGET("bee_option_1"),
        HIDE_TARGET("bee_option_2"),
        HIDE_TARGET("bee_option_3"),
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.bee_option_1-response", "\n")),
    ], type: "talk"
});
const BEE_OPTION_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.bee_option_2"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.bee_option_2-response", "\n")),
        HIDE_TARGET(),
    ], type: "talk"
});
const BEE_OPTION_3 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.bee_option_3"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.bee_option_3-response", "\n")),
        HIDE_TARGET(),
    ], type: "talk"
});
const ROSE_BUSHES = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.rose_bushes"),
    actions: [GET_ITEM("dead_bush"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.rose_bushes-response", "\n")), HIDE_TARGET()],
});
const STEVE_BASE = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.steve_base"),
    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.steve_base-response", "\n")), CHANGE_LOCATION("act3_round0")], type: "look"
});
const ILLAGERS = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.illagers"),
    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.illagers-response", "\n")), CHANGE_LOCATION("act3_round1")], type: "talk"
});
const ROUND1_OPTION_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round1_option_1"),
    actions: [GET_ITEM("illager_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round1_option_1-response", "\n")), CHANGE_LOCATION("act3_round2")], type: "talk"
});
const ROUND1_OPTION_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round1_option_2"),
    actions: [GET_ITEM("player_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round1_option_2-response", "\n")), CHANGE_LOCATION("act3_round2")], type: "talk"
});
const ROUND1_OPTION_3 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round1_option_3"),
    actions: [GET_ITEM("illager_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round1_option_3-response", "\n")), CHANGE_LOCATION("act3_round2")], type: "talk"
});
const ROUND2_OPTION_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round2_option_1"),
    actions: [GET_ITEM("illager_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round2_option_1-response", "\n")), CHANGE_LOCATION("act3_round3")], type: "talk"
});
const ROUND2_OPTION_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round2_option_2"),
    actions: [GET_ITEM("illager_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round2_option_2-response", "\n")), CHANGE_LOCATION("act3_round3")], type: "talk"
});
const ROUND2_OPTION_3 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round2_option_3"),
    actions: [GET_ITEM("player_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round2_option_3-response", "\n")), CHANGE_LOCATION("act3_round3")], type: "talk"
});
const ROUND3_OPTION_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round3_option_1"),
    actions: [GET_ITEM("player_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round3_option_1-response", "\n")), CHANGE_LOCATION("act3_round4")], type: "talk"
});
const ROUND3_OPTION_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round3_option_2"),
    actions: [GET_ITEM("illager_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round3_option_2-response", "\n")), CHANGE_LOCATION("act3_round4")], type: "talk"
});
const ROUND3_OPTION_3 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round3_option_3"),
    actions: [GET_ITEM("illager_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round3_option_3-response", "\n")), CHANGE_LOCATION("act3_round4")], type: "talk"
});
const ROUND4_OPTION_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round4_option_1"),
    actions: [GET_ITEM("player_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round4_option_1-response", "\n")), CHANGE_LOCATION("act3_round5")], type: "talk"
});
const ROUND4_OPTION_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round4_option_2"),
    actions: [GET_ITEM("illager_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round4_option_2-response", "\n")), CHANGE_LOCATION("act3_round5")], type: "talk"
});
const ROUND4_OPTION_3 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round4_option_3"),
    actions: [GET_ITEM("illager_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round4_option_3-response", "\n")), CHANGE_LOCATION("act3_round5")], type: "talk"
});
const ROUND5_OPTION_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round5_option_1"),
    actions: [
        {
            if: {
                condition: hasItems({
                    id: "illager_point",
                    count: 2,
                }),
                actions: [GET_ITEM("illager_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round5_option_1-response", "\n")), CHANGE_LOCATION("act3_lose")],
            },
            else: [GET_ITEM("illager_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round5_option_1-response", "\n")), CHANGE_LOCATION("act3_win")],
        },
        {
            if: {
                condition: hasItems({
                    id: "illager_point",
                    count: 5,
                }),
                actions: [EARN_ACHIEVEMENT("de_0")],
            }
        },
        {
            if: {
                condition: hasItems({
                    id: "player_point",
                    count: 2,
                }),
                actions: [EARN_ACHIEVEMENT("de_50")],
            }
        },
        {
            if: {
                condition: hasItems({
                    id: "player_point",
                    count: 3,
                }),
                actions: [EARN_ACHIEVEMENT("de_80")],
            }
        },
        {
            if: {
                condition: hasItems({
                    id: "player_point",
                    count: 4,
                }),
                actions: [EARN_ACHIEVEMENT("de_90")],
            }
        },
        {
            if: {
                condition: hasItems({
                    id: "player_point",
                    count: 5,
                }),
                actions: [EARN_ACHIEVEMENT("de_100")],
            }
        },
    ], type: "talk"
});
const ROUND5_OPTION_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round5_option_2"),
    actions: [
        {
            if: {
                condition: hasItems({
                    id: "player_point",
                    count: 2,
                }),
                actions: [GET_ITEM("player_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round5_option_2-response", "\n")), CHANGE_LOCATION("act3_win")],
            },
            else: [GET_ITEM("player_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round5_option_2-response", "\n")), CHANGE_LOCATION("act3_lose")],
        },
        {
            if: {
                condition: hasItems({
                    id: "illager_point",
                    count: 5,
                }),
                actions: [EARN_ACHIEVEMENT("de_0")],
            }
        },
        {
            if: {
                condition: hasItems({
                    id: "player_point",
                    count: 2,
                }),
                actions: [EARN_ACHIEVEMENT("de_50")],
            }
        },
        {
            if: {
                condition: hasItems({
                    id: "player_point",
                    count: 3,
                }),
                actions: [EARN_ACHIEVEMENT("de_80")],
            }
        },
        {
            if: {
                condition: hasItems({
                    id: "player_point",
                    count: 4,
                }),
                actions: [EARN_ACHIEVEMENT("de_90")],
            }
        },
        {
            if: {
                condition: hasItems({
                    id: "player_point",
                    count: 5,
                }),
                actions: [EARN_ACHIEVEMENT("de_100")],
            }
        },
    ], type: "talk"
});
const ROUND5_OPTION_3 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round5_option_3"),
    actions: [
        {
            if: {
                condition: hasItems({
                    id: "illager_point",
                    count: 2,
                }),
                actions: [GET_ITEM("illager_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round5_option_3-response", "\n")), CHANGE_LOCATION("act3_lose")],
            },
            else: [GET_ITEM("illager_point"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.round5_option_3-response", "\n")), CHANGE_LOCATION("act3_win")],
        },
        {
            if: {
                condition: hasItems({
                    id: "illager_point",
                    count: 5,
                }),
                actions: [EARN_ACHIEVEMENT("de_0")],
            }
        },
        {
            if: {
                condition: hasItems({
                    id: "player_point",
                    count: 2,
                }),
                actions: [EARN_ACHIEVEMENT("de_50")],
            }
        },
        {
            if: {
                condition: hasItems({
                    id: "player_point",
                    count: 3,
                }),
                actions: [EARN_ACHIEVEMENT("de_80")],
            }
        },
        {
            if: {
                condition: hasItems({
                    id: "player_point",
                    count: 4,
                }),
                actions: [EARN_ACHIEVEMENT("de_90")],
            }
        },
        {
            if: {
                condition: hasItems({
                    id: "player_point",
                    count: 5,
                }),
                actions: [EARN_ACHIEVEMENT("de_100")],
            }
        },
    ], type: "talk"
});
const STATUE = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.statue"),
    actions: [
        REMOVE_ITEM("illager_point", 5),
        REMOVE_ITEM("player_point", 5),
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.statue-response", "\n")), CHANGE_LOCATION("act3_round1")
    ],
});
const LOUD_NOISES = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.loud_noises"),
    actions: [CHANGE_LOCATION("act3_ending")],
});
const newDownToEarthAdventureState = () => ({
    version: 1,
    inventory: [],
    status: 'playing',
    props: {},
    nextPrompt: [TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.introduction", "\n")],
    currentRoom: "act1_steve_house",
});
const newDownToEarthAdventure = () => makeTextAdventure({
    overrides: {
        ui: {
            status: {
                title: "jig_ccomp:text-adventure.ui.select-adventure.adventure.downtoearth",
            }
        }
    },
    rooms: {
        act1_steve_house: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act1_steve_house.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act1_steve_house.distance_description"),
            targets: {
                steve: {
                    ...STEVE,
                }
            },
            exits: {
                exit1: {
                    ...EXIT1,
                    room: "act1_street",
                },
            },
        },
        act1_street: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act1_street.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act1_street.distance_description"),
            targets: {},
            exits: {
                "exit3-1": {
                    ...EXIT8,
                    room: "act1_blaze_house",
                    filter: ALL(doesNotHaveItems("evidence_2"), doesNotHaveItems("evidence_2_submitted")),
                },
                "exit3-2": {
                    ...EXIT8,
                    room: "act1_blaze_house_2",
                    filter: ANY(hasItems("evidence_2"), hasItems("evidence_2_submitted")),
                },
                exit2: {
                    ...EXIT6,
                    room: "act1_piglin_house",
                },
                exit4: {
                    ...EXIT7,
                    room: "act1_sheep_house",
                },
                exit1: {
                    ...EXIT5,
                    room: "act1_steve_house",
                },
            },
        },
        act1_piglin_house: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act1_piglin_house.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act1_piglin_house.distance_description"),
            targets: {
                piglin_engineer: {
                    ...PIGLIN_ENGINEER,
                },
                baby_piglin: {
                    ...BABY_PIGLIN,
                },
                lever: {
                    ...LEVER,
                },
                bell: {
                    ...BELL,
                },
                observer: {
                    ...OBSERVER,
                }
            },
            exits: {
                exit1: {
                    ...EXIT1,
                    room: "act1_street",
                },
            },
        },
        act1_blaze_house: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act1_blaze_house.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act1_blaze_house.distance_description"),
            targets: {
                blaze_option_1: {
                    ...BLAZE_OPTION_1,
                },
                blaze_option_2: {
                    ...BLAZE_OPTION_2,
                },
                blaze_option_3: {
                    ...BLAZE_OPTION_3,
                },
            },
            exits: {
                exit1: {
                    ...EXIT1,
                    room: "act1_street",
                },
            },
        },
        act1_blaze_house_2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act1_blaze_house_2.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act1_blaze_house_2.distance_description"),
            targets: {
                blaze: {
                    ...BLAZE,
                },
            },
            exits: {
                exit1: {
                    ...EXIT1,
                    room: "act1_street",
                },
            },
        },
        act1_sheep_house: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act1_sheep_house.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act1_sheep_house.distance_description"),
            targets: {
                sheep_1: {
                    ...SHEEP_1,
                },
                sheep_2: {
                    ...SHEEP_2,
                },
                sheep_3: {
                    ...SHEEP_3,
                },
                sheep_4: {
                    ...SHEEP_4,
                },
                sheep_5: {
                    ...SHEEP_5,
                },
                sheep_6: {
                    ...SHEEP_6,
                },
                sheep_7: {
                    ...SHEEP_7,
                }
            },
            exits: {
                exit1: {
                    ...EXIT1,
                    room: "act1_street",
                },
            },
        },
        act2_introduction: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_introduction.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_introduction.distance_description"),
            targets: {},
            exits: {
                exit1: {
                    ...EXIT4,
                    room: "act2_village_entrance",
                },
            },
        },
        act2_village_entrance: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_village_entrance.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_village_entrance.distance_description"),
            targets: {
                iron_golem: {
                    ...IRON_GOLEM,
                }
            },
            exits: {
                exit1: {
                    ...EXIT4,
                    room: "act2_village_plaza",
                },
                exit2: {
                    ...EXIT8,
                    room: "act2_beach",
                },
                exit4: {
                    ...EXIT6,
                    room: "act2_jungle",
                },
                exit5: {
                    ...EXIT7,
                    room: "act2_forest",
                },
                exit3: {
                    ...EXIT5,
                    room: "act2_tundra",
                },
            },
        },
        act2_village_plaza: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_village_plaza.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_village_plaza.distance_description"),
            targets: {
                fountain: {
                    ...FOUNTAIN,
                },
                cat: {
                    ...CAT,
                }
            },
            exits: {
                exit3: {
                    ...EXIT4,
                    room: "act2_village_council",
                },
                exit2: {
                    ...EXIT7,
                    room: "act2_village_market",
                },
                exit1: {
                    ...EXIT5,
                    room: "act2_village_entrance",
                },
            },
        },
        act2_village_market: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_village_market.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_village_market.distance_description"),
            targets: {
                witch: {
                    ...WITCH,
                },
                armorer: {
                    ...ARMORER,
                },
                armorer_option_1: {
                    ...ARMORER_OPTION_1,
                    "hidden": true,
                },
                armorer_option_2: {
                    ...ARMORER_OPTION_2,
                    "hidden": true,
                },
                armorer_option_3: {
                    ...ARMORER_OPTION_3,
                    "hidden": true,
                },
                creeper: {
                    ...CREEPER,
                },
                record: {
                    ...RECORD,
                    "hidden": true,
                }
            },
            exits: {
                exit1: {
                    ...EXIT3,
                    room: "act2_village_plaza",
                },
            },
        },
        act2_village_council: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_village_council.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_village_council.distance_description"),
            targets: {
                hopper: {
                    ...HOPPER,
                },
                zombie: {
                    ...ZOMBIE,
                },
            },
            exits: {
                exit1: {
                    ...EXIT3,
                    room: "act2_village_plaza",
                },
            },
        },
        act2_beach: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_beach.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_beach.distance_description"),
            targets: {
                pufferfish: {
                    ...PUFFERFISH,
                },
                enderman: {
                    ...ENDERMAN,
                },
                enderchild_1: {
                    ...ENDERCHILD_1,
                },
                enderchild_2: {
                    ...ENDERCHILD_2,
                },
                enderman_option_1: {
                    ...ENDERMAN_OPTION_1,
                    "hidden": true,
                },
                enderman_option_2: {
                    ...ENDERMAN_OPTION_2,
                    "hidden": true,
                },
                enderman_option_3: {
                    ...ENDERMAN_OPTION_3,
                    "hidden": true,
                },
                enderman_option_4: {
                    ...ENDERMAN_OPTION_4,
                    "hidden": true,
                },
            },
            exits: {
                "exit2": {
                    ...EXIT4,
                    room: "act2_ocean",
                    filter: hasItems("potion_water_breathing"),
                },
                exit1: {
                    ...EXIT2,
                    room: "act2_village_entrance",
                },
            },
        },
        act2_ocean: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_ocean.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_ocean.distance_description"),
            targets: {
                sea_turtle: {
                    ...SEA_TURTLE,
                },
                coral_1: {
                    ...CORAL_1,
                },
                coral_2: {
                    ...CORAL_2,
                },
            },
            exits: {
                exit1: {
                    ...EXIT5,
                    room: "act2_beach",
                },
            },
        },
        act2_tundra: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_tundra.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_tundra.distance_description"),
            targets: {
                allay: {
                    ...ALLAY,
                },
                polar_bear: {
                    ...POLAR_BEAR,
                },
                snow_golem: {
                    ...SNOW_GOLEM,
                },
                spring: {
                    ...SPRING,
                },
            },
            exits: {
                exit1: {
                    ...EXIT2,
                    room: "act2_village_entrance",
                },
            },
        },
        act2_jungle: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_jungle.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_jungle.distance_description"),
            targets: {
                parrot: {
                    ...PARROT,
                },
                roses: {
                    ...ROSES,
                },
                river: {
                    ...RIVER,
                },
                jukebox: {
                    ...JUKEBOX,
                },
            },
            exits: {
                exit1: {
                    ...EXIT2,
                    room: "act2_village_entrance",
                },
            },
        },
        act2_forest: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_forest.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act2_forest.distance_description"),
            targets: {
                beehive: {
                    ...BEEHIVE,
                },
                bee_option_1: {
                    ...BEE_OPTION_1,
                    "hidden": true,
                },
                bee_option_2: {
                    ...BEE_OPTION_2,
                    "hidden": true,
                },
                bee_option_3: {
                    ...BEE_OPTION_3,
                    "hidden": true,
                },
                rose_bushes: {
                    ...ROSE_BUSHES,
                },
            },
            exits: {
                exit1: {
                    ...EXIT2,
                    room: "act2_village_entrance",
                },
            },
        },
        act3_introduction: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_introduction.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_introduction.distance_description"),
            targets: {
                steve_base: {
                    ...STEVE_BASE,
                },
            },
            exits: {},
        },
        act3_round0: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_round0.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_round0.distance_description"),
            targets: {
                illagers: {
                    ...ILLAGERS,
                },
            },
            exits: {},
        },
        act3_round1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_round1.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_round1.distance_description"),
            targets: {
                round1_option_1: {
                    ...ROUND1_OPTION_1,
                },
                round1_option_2: {
                    ...ROUND1_OPTION_2,
                },
                round1_option_3: {
                    ...ROUND1_OPTION_3,
                },
            },
            exits: {},
        },
        act3_round2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_round2.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_round2.distance_description"),
            targets: {
                round2_option_1: {
                    ...ROUND2_OPTION_1,
                },
                round2_option_2: {
                    ...ROUND2_OPTION_2,
                },
                round2_option_3: {
                    ...ROUND2_OPTION_3,
                },
            },
            exits: {},
        },
        act3_round3: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_round3.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_round3.distance_description"),
            targets: {
                round3_option_1: {
                    ...ROUND3_OPTION_1,
                },
                round3_option_2: {
                    ...ROUND3_OPTION_2,
                },
                round3_option_3: {
                    ...ROUND3_OPTION_3,
                },
            },
            exits: {},
        },
        act3_round4: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_round4.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_round4.distance_description"),
            targets: {
                round4_option_1: {
                    ...ROUND4_OPTION_1,
                },
                round4_option_2: {
                    ...ROUND4_OPTION_2,
                },
                round4_option_3: {
                    ...ROUND4_OPTION_3,
                },
            },
            exits: {},
        },
        act3_round5: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_round5.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_round5.distance_description"),
            targets: {
                round5_option_1: {
                    ...ROUND5_OPTION_1,
                },
                round5_option_2: {
                    ...ROUND5_OPTION_2,
                },
                round5_option_3: {
                    ...ROUND5_OPTION_3,
                },
            },
            exits: {},
        },
        act3_lose: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_lose.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_lose.distance_description"),
            targets: {
                statue: {
                    ...STATUE,
                },
            },
            exits: {},
        },
        act3_win: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_win.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_win.distance_description"),
            targets: {
                loud_noises: {
                    ...LOUD_NOISES,
                },
            },
            exits: {},
        },
        act3_ending: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.targets.loud_noises-response", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_ending.distance_description"),
            targets: {
                epilogue: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_ending.distance_description"),
                    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.room.act3_ending.description", "\n")), WON("Down to Earth", "{0} completed the environmental debate!", "player"),],
                },
            },
            exits: {},
        },
    },
    items: {
        evidence_1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.evidence_1"),
        },
        evidence_2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.evidence_2"),
        },
        evidence_3: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.evidence_3"),
        },
        evidence_1_submitted: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.evidence_1"),
        },
        evidence_2_submitted: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.evidence_2"),
        },
        evidence_3_submitted: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.evidence_3"),
        },
        letter_of_support: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.letter_of_support"),
        },
        empty_bucket: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.empty_bucket"),
        },
        ice_bucket: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.ice_bucket"),
        },
        empty_bottle: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.empty_bottle"),
        },
        potion_water_breathing: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.potion_water_breathing"),
        },
        potion_regeneration: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.potion_regeneration"),
        },
        potion_wither: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.potion_wither"),
        },
        steve_music_disk: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.steve_music_disk"),
        },
        dj_music_disk: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.dj_music_disk"),
        },
        wither_rose: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.wither_rose"),
        },
        dead_bush: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.dead_bush"),
        },
        dead_fire_coral: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.dead_fire_coral"),
        },
        wither_rose_submitted: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.wither_rose_submitted"),
        },
        dead_bush_submitted: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.dead_bush_submitted"),
        },
        dead_fire_coral_submitted: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.dead_fire_coral_submitted"),
        },
        dead_brain_coral: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.dead_brain_coral"),
        },
        sponge: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.sponge"),
        },
        lever_arms: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.lever_arms"),
        },
        stick_arms: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.stick_arms"),
        },
        player_point: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.player_point"),
        },
        illager_point: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.downtoearth.item.illager_point"),
        },
    },
    achievements: Object.fromEntries(["de_100", "de_90", "de_80", "de_50", "de_0"].map((id) => [
        id,
        {
            name: `jig_ccomp:text-adventure.downtoearth.achievement.${id}.name`,
            description: `jig_ccomp:text-adventure.downtoearth.achievement.${id}.description`,
            hint: `jig_ccomp:text-adventure.downtoearth.achievement.${id}.hint`,
            icon: `textures/jig/ccomp/items/art/${id}.png`,
            item: `jig_ccomp:poster_${id}`,
            print_title: "",
            print_content: "",
        },
    ])),
});

const EXITU = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.sandender.exit.u"), type: "up"
});
const EXITD = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.sandender.exit.d"), type: "down"
});
const EXITN = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.sandender.exit.n"), type: "north"
});
const EXITS = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.sandender.exit.s"), type: "south"
});
const EXITE = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.sandender.exit.e"), type: "east"
});
const EXITW = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.sandender.exit.w"), type: "west"
});
const CLASS_FIGHTER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.class_fighter"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.class_fighter-response")),
        GET_ITEM("hp", 30),
        GET_ITEM("strength", 3),
        GET_ITEM("speed", 2),
        GET_ITEM("smart", 1),
        GET_ITEM("sense", 2),
        CHANGE_LOCATION("f2_a2"),
        SET_VALUE("class.fighter", true)
    ], type: "attack"
});
const CLASS_MINER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.class_miner"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.class_miner-response")),
        GET_ITEM("hp", 25),
        GET_ITEM("strength", 1),
        GET_ITEM("speed", 2),
        GET_ITEM("smart", 2),
        GET_ITEM("sense", 3),
        CHANGE_LOCATION("f2_a2"),
        SET_VALUE("class.miner", true)
    ], type: "look"
});
const CLASS_ENCHANTER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.class_enchanter"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.class_enchanter-response")),
        GET_ITEM("hp", 25),
        GET_ITEM("strength", 2),
        GET_ITEM("speed", 1),
        GET_ITEM("smart", 3),
        GET_ITEM("sense", 2),
        CHANGE_LOCATION("f2_a2"),
        SET_VALUE("class.enchanter", true)
    ], type: "talk"
});
const CLASS_SPRINTER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.class_sprinter"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.class_sprinter-response")),
        GET_ITEM("hp", 20),
        GET_ITEM("strength", 2),
        GET_ITEM("speed", 3),
        GET_ITEM("smart", 2),
        GET_ITEM("sense", 1),
        CHANGE_LOCATION("f2_a2"),
        SET_VALUE("class.scout", true)
    ], type: "walk"
});
const DEV_SHORTCUT_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.dev_shortcut_1"),
    actions: [
        CHANGE_LOCATION("f2_a1"),
        GET_ITEM("strength", 3),
        GET_ITEM("speed", 3),
        GET_ITEM("smart", 3),
        GET_ITEM("sense", 3),
        GET_ITEM("ender_eye", 3),
    ],
});
const END_PORTAL = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.end_portal"),
    actions: [
        {
            if: {
                condition: ALL(hasItems({ id: "ender_eye", count: 3, }), IS_VALUE("class.fighter", true)),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.end_portal-response-2")),
                    GET_ITEM("dragon_hp", 50),
                    REMOVE_ITEM("up_door_unlocked", 100),
                    REMOVE_ITEM("down_door_unlocked", 100),
                    REMOVE_ITEM("puzzle_door_unlocked", 100),
                    REMOVE_ITEM("string", 100),
                    REMOVE_ITEM("bone", 100),
                    REMOVE_ITEM("rotten_flesh", 100),
                    REMOVE_ITEM("spider_eye", 100),
                    REMOVE_ITEM("silverfish_scale", 100),
                    REMOVE_ITEM("up_arrow_key", 100),
                    REMOVE_ITEM("down_arrow_key", 100),
                    REMOVE_ITEM("ender_eye", 100),
                    REMOVE_ITEM("tripwire", 100),
                    REMOVE_ITEM("redstone", 100),
                    REMOVE_ITEM("redstone_torch", 100),
                    CHANGE_LOCATION("final_battle"), EARN_ACHIEVEMENT("se_f")
                ],
            },
            elseif: {
                condition: ALL(IS_VALUE("class.fighter", true)),
                actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.end_portal-response"))]
            },
        },
        {
            if: {
                condition: ALL(hasItems({ id: "ender_eye", count: 3, }), IS_VALUE("class.enchanter", true)),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.end_portal-response-2")),
                    GET_ITEM("dragon_hp", 50),
                    REMOVE_ITEM("up_door_unlocked", 100),
                    REMOVE_ITEM("down_door_unlocked", 100),
                    REMOVE_ITEM("puzzle_door_unlocked", 100),
                    REMOVE_ITEM("string", 100),
                    REMOVE_ITEM("bone", 100),
                    REMOVE_ITEM("rotten_flesh", 100),
                    REMOVE_ITEM("spider_eye", 100),
                    REMOVE_ITEM("silverfish_scale", 100),
                    REMOVE_ITEM("up_arrow_key", 100),
                    REMOVE_ITEM("down_arrow_key", 100),
                    REMOVE_ITEM("ender_eye", 100),
                    REMOVE_ITEM("tripwire", 100),
                    REMOVE_ITEM("redstone", 100),
                    REMOVE_ITEM("redstone_torch", 100),
                    CHANGE_LOCATION("final_battle"), EARN_ACHIEVEMENT("se_e")
                ],
            },
            elseif: {
                condition: ALL(IS_VALUE("class.enchanter", true)),
                actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.end_portal-response"))]
            },
        },
        {
            if: {
                condition: ALL(hasItems({ id: "ender_eye", count: 3, }), IS_VALUE("class.miner", true)),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.end_portal-response-2")),
                    GET_ITEM("dragon_hp", 50),
                    REMOVE_ITEM("up_door_unlocked", 100),
                    REMOVE_ITEM("down_door_unlocked", 100),
                    REMOVE_ITEM("puzzle_door_unlocked", 100),
                    REMOVE_ITEM("string", 100),
                    REMOVE_ITEM("bone", 100),
                    REMOVE_ITEM("rotten_flesh", 100),
                    REMOVE_ITEM("spider_eye", 100),
                    REMOVE_ITEM("silverfish_scale", 100),
                    REMOVE_ITEM("up_arrow_key", 100),
                    REMOVE_ITEM("down_arrow_key", 100),
                    REMOVE_ITEM("ender_eye", 100),
                    REMOVE_ITEM("tripwire", 100),
                    REMOVE_ITEM("redstone", 100),
                    REMOVE_ITEM("redstone_torch", 100),
                    CHANGE_LOCATION("final_battle"), EARN_ACHIEVEMENT("se_m")
                ],
            },
            elseif: {
                condition: ALL(IS_VALUE("class.miner", true)),
                actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.end_portal-response"))]
            },
        },
        {
            if: {
                condition: ALL(hasItems({ id: "ender_eye", count: 3, }), IS_VALUE("class.scout", true)),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.end_portal-response-2")),
                    GET_ITEM("dragon_hp", 50),
                    REMOVE_ITEM("up_door_unlocked", 100),
                    REMOVE_ITEM("down_door_unlocked", 100),
                    REMOVE_ITEM("puzzle_door_unlocked", 100),
                    REMOVE_ITEM("string", 100),
                    REMOVE_ITEM("bone", 100),
                    REMOVE_ITEM("rotten_flesh", 100),
                    REMOVE_ITEM("spider_eye", 100),
                    REMOVE_ITEM("silverfish_scale", 100),
                    REMOVE_ITEM("up_arrow_key", 100),
                    REMOVE_ITEM("down_arrow_key", 100),
                    REMOVE_ITEM("ender_eye", 100),
                    REMOVE_ITEM("tripwire", 100),
                    REMOVE_ITEM("redstone", 100),
                    REMOVE_ITEM("redstone_torch", 100),
                    CHANGE_LOCATION("final_battle"), EARN_ACHIEVEMENT("se_s")
                ],
            },
            elseif: {
                condition: ALL(IS_VALUE("class.scout", true)),
                actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.end_portal-response"))]
            },
        },
        {
            if: {
                condition: ALL(hasItems({ id: "ender_eye", count: 3, }), IS_NOT_VALUE("class.fighter", true), IS_NOT_VALUE("class.enchanter", true), IS_NOT_VALUE("class.miner", true), IS_NOT_VALUE("class.scout", true)),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.end_portal-response-2")),
                    GET_ITEM("dragon_hp", 50),
                    REMOVE_ITEM("up_door_unlocked", 100),
                    REMOVE_ITEM("down_door_unlocked", 100),
                    REMOVE_ITEM("puzzle_door_unlocked", 100),
                    REMOVE_ITEM("string", 100),
                    REMOVE_ITEM("bone", 100),
                    REMOVE_ITEM("rotten_flesh", 100),
                    REMOVE_ITEM("spider_eye", 100),
                    REMOVE_ITEM("silverfish_scale", 100),
                    REMOVE_ITEM("up_arrow_key", 100),
                    REMOVE_ITEM("down_arrow_key", 100),
                    REMOVE_ITEM("ender_eye", 100),
                    REMOVE_ITEM("tripwire", 100),
                    REMOVE_ITEM("redstone", 100),
                    REMOVE_ITEM("redstone_torch", 100),
                    CHANGE_LOCATION("final_battle"),
                ],
            },
            elseif: {
                condition: ALL(IS_NOT_VALUE("class.fighter", true), IS_NOT_VALUE("class.enchanter", true), IS_NOT_VALUE("class.miner", true), IS_NOT_VALUE("class.scout", true)),
                actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.end_portal-response"))]
            },
        },
    ],
});
const UP_ARROW_DOOR = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.up_arrow_door"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "up_door_unlocked", count: 1, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.up_arrow_door-response-4")),
                    HIDE_TARGET()
                ],
            },
            elseif: [
                {
                    condition: hasItems({ id: "up_arrow_key", count: 1, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.up_arrow_door-response-2")),
                        GET_ITEM("up_door_unlocked"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "strength", count: 4, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.up_arrow_door-response-3")),
                        GET_ITEM("up_door_unlocked"),
                        HIDE_TARGET()
                    ],
                }
            ],
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.up_arrow_door-response"))],
        },
    ],
});
const DOWN_ARROW_DOOR = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.down_arrow_door"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "down_door_unlocked", count: 1, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.down_arrow_door-response-4")),
                    HIDE_TARGET()
                ],
            },
            elseif: [
                {
                    condition: hasItems({ id: "down_arrow_key", count: 1, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.down_arrow_door-response-2")),
                        GET_ITEM("down_door_unlocked"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "strength", count: 4, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.down_arrow_door-response-3")),
                        GET_ITEM("down_door_unlocked"),
                        HIDE_TARGET()
                    ],
                }
            ],
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.down_arrow_door-response"))],
        },
    ],
});
const UP_ARROW_DOOR_BACK = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.up_arrow_door_back"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "up_door_unlocked", count: 1, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.up_arrow_door_back-response-2")),
                    HIDE_TARGET()
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.up_arrow_door_back-response")),
                GET_ITEM("up_door_unlocked"),
                HIDE_TARGET()
            ],
        },
    ],
});
const DOWN_ARROW_DOOR_BACK = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.down_arrow_door_back"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "down_door_unlocked", count: 1, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.down_arrow_door_back-response-2")),
                    HIDE_TARGET()
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.down_arrow_door_back-response")),
                GET_ITEM("down_door_unlocked"),
                HIDE_TARGET()
            ],
        },
    ],
});
const INSPECT_F2_B2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_f2_b2"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_f2_b2-response")),
    ],
    type: "look",
});
const WALK_F2_B2_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f2_b2"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "silverfish_scale", count: 1, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f2_b2-response-2")),
                    CHANGE_LOCATION("f2_b2_2")
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f2_b2-response")),
                CHANGE_LOCATION("f2_b2_2")
            ],
        },
    ],
    type: "walk",
});
const WALK_F2_B2_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f2_b2"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f2_b2-response-2")),
        CHANGE_LOCATION("f2_b2_1")
    ],
    type: "walk",
});
const INSPECT_F1_C4 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_f1_c4"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_f1_c4-response")),
    ],
    type: "look",
});
const WALK_F1_C4_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f1_c4"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f1_c4-response")),
        CHANGE_LOCATION("f1_c4_2")
    ],
    type: "walk",
});
const WALK_F1_C4_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f1_c4"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f1_c4-response")),
        CHANGE_LOCATION("f1_c4_1")
    ],
    type: "walk",
});
const INSPECT_F1_D2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_f1_d2"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_f1_d2-response")),
    ],
    type: "look",
});
const WALK_F1_D2_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f1_d2"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "strength", count: 3, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f1_d2-response-2")),
                    CHANGE_LOCATION("f1_d2_2")
                ],
            },
            elseif: {
                condition: hasItems({ id: "hp", count: 6, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f1_d2-response")),
                    REMOVE_ITEM("hp", 5),
                    CHANGE_LOCATION("f1_d2_2")
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f1_d2-response")),
                DIE()
            ],
        },
    ],
    type: "walk",
});
const WALK_F1_D2_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f1_d2"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "strength", count: 3, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f1_d2-response-2")),
                    CHANGE_LOCATION("f1_d2_1")
                ],
            },
            elseif: {
                condition: hasItems({ id: "hp", count: 6, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f1_d2-response")),
                    REMOVE_ITEM("hp", 5),
                    CHANGE_LOCATION("f1_d2_1")
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f1_d2-response")),
                DIE()
            ],
        },
    ],
    type: "walk",
});
const INSPECT_F3_A3 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_f3_a3"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "redstone_torch", count: 1, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_f3_a3-response")),
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_f3_a3-response")),
                SHOW_TARGET("modify_redstone")
            ],
        },
    ],
    type: "look",
});
const WALK_F3_A3_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_a3"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "redstone_torch", count: 1, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_a3-response-3")),
                    CHANGE_LOCATION("f3_a3_2")
                ],
            },
            elseif: [
                {
                    condition: hasItems({ id: "speed", count: 3, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_a3-response-2")),
                        CHANGE_LOCATION("f3_a3_2")
                    ],
                },
                {
                    condition: hasItems({ id: "hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_a3-response")),
                        REMOVE_ITEM("hp", 5),
                        CHANGE_LOCATION("f3_a3_2")
                    ],
                }
            ],
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_a3-response")),
                DIE()
            ],
        },
    ],
    type: "walk",
});
const WALK_F3_A3_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_a3"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "redstone_torch", count: 1, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_a3-response-3")),
                    CHANGE_LOCATION("f3_a3_1")
                ],
            },
            elseif: [{
                    condition: hasItems({ id: "speed", count: 3, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_a3-response-2")),
                        CHANGE_LOCATION("f3_a3_1")
                    ],
                },
                {
                    condition: hasItems({ id: "hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_a3-response")),
                        REMOVE_ITEM("hp", 5),
                        CHANGE_LOCATION("f3_a3_1")
                    ],
                }],
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_a3-response")),
                DIE()
            ],
        },
    ],
    type: "walk",
});
const MODIFY_REDSTONE = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.modify_redstone"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "smart", count: 3, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.modify_redstone-response-2")),
                    GET_ITEM("redstone_torch"),
                    HIDE_TARGET()
                ],
            },
            elseif: {
                condition: hasItems({ id: "hp", count: 6, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.modify_redstone-response")),
                    REMOVE_ITEM("hp", 5)
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.modify_redstone-response")),
                DIE()
            ],
        },
    ],
});
const INSPECT_F3_C3 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_f3_c3"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "sense", count: 3, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_f3_c3-response-2")),
                    GET_ITEM("tripwire"),
                    HIDE_TARGET()
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_f3_c3-response")),
            ],
        },
    ],
    type: "look",
});
const WALK_F3_C3_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_c3"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "tripwire", count: 1, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_c3-response-2")),
                    CHANGE_LOCATION("f3_c3_2")
                ],
            },
            elseif: {
                condition: hasItems({ id: "hp", count: 6, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_c3-response")),
                    REMOVE_ITEM("hp", 5),
                    CHANGE_LOCATION("f2_c3")
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_c3-response")),
                DIE()
            ],
        },
    ],
    type: "walk",
});
const WALK_F3_C3_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_c3"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "tripwire", count: 1, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_c3-response-2")),
                    CHANGE_LOCATION("f3_c3_1")
                ],
            },
            elseif: {
                condition: hasItems({ id: "hp", count: 6, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_c3-response")),
                    REMOVE_ITEM("hp", 5),
                    CHANGE_LOCATION("f2_c3")
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.walk_f3_c3-response")),
                DIE()
            ],
        },
    ],
    type: "walk",
});
const ATTEMPT_PARKOUR = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.attempt_parkour"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "speed", count: 3, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.attempt_parkour-response-2")),
                    CHANGE_LOCATION("f3_c2")
                ],
            },
            elseif: {
                condition: hasItems({ id: "hp", count: 6, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.attempt_parkour-response")),
                    REMOVE_ITEM("hp", 5),
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.attempt_parkour-response")),
                DIE()
            ],
        },
    ],
    type: "walk",
});
const ATTEMPT_JUMP = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.attempt_jump"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "speed", count: 3, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.attempt_jump-response-2")),
                    GET_ITEM("smart"),
                    HIDE_TARGET("inspect_jump"),
                    HIDE_TARGET()
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.attempt_jump-response")),
                DIE()
            ],
        },
    ],
    type: "walk",
});
const INSPECT_LOCKED_CHEST = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_locked_chest"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "strength", count: 3, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_locked_chest-response-2")),
                    GET_ITEM("smart"),
                    HIDE_TARGET()
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_locked_chest-response")),
            ],
        },
    ],
    type: "look",
});
const INSPECT_EMPTINESS = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_emptiness"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "sense", count: 3, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_emptiness-response-2")),
                    GET_ITEM("smart"),
                    HIDE_TARGET()
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_emptiness-response")),
            ],
        },
    ],
    type: "look",
});
const USE_SECRET_PASSAGE = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.use_secret_passage"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.use_secret_passage-response")),
        CHANGE_LOCATION("f3_b2")
    ],
});
const INSPECT_TRAPPED_CHEST = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_trapped_chest"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "sense", count: 3, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_trapped_chest-response-2")),
                    GET_ITEM("redstone"),
                    HIDE_TARGET()
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_trapped_chest-response")),
            ],
        },
    ],
    type: "look",
});
const OPEN_TRAPPED_CHEST = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.open_trapped_chest"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "redstone", count: 1, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.open_trapped_chest-response-2")),
                    GET_ITEM("strength"),
                    HIDE_TARGET(),
                    HIDE_TARGET("inspect_trapped_chest")
                ],
            },
            elseif: {
                condition: hasItems({ id: "hp", count: 11, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.open_trapped_chest-response")),
                    REMOVE_ITEM("hp", 10),
                    GET_ITEM("strength"),
                    HIDE_TARGET(),
                    HIDE_TARGET("inspect_trapped_chest")
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.open_trapped_chest-response")),
                DIE()
            ],
        },
    ],
});
const PRESS_BUTTONS = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.press_buttons"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "smart", count: 3, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.press_buttons-response-2")),
                    GET_ITEM("puzzle_door_unlocked"),
                    GET_ITEM("hp", 5),
                    HIDE_TARGET("inspect_buttons"),
                    HIDE_TARGET()
                ],
            },
            elseif: {
                condition: hasItems({ id: "hp", count: 6, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.press_buttons-response")),
                    REMOVE_ITEM("hp", 5),
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.press_buttons-response")),
                DIE()
            ],
        },
    ],
});
const INSPECT_BREWING_STAND = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_brewing_stand"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "smart", count: 3, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_brewing_stand-response-2")),
                    GET_ITEM("sense"),
                    HIDE_TARGET()
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_brewing_stand-response")),
            ],
        },
    ],
    type: "look",
});
const INSPECT_NETHER_WART = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_nether_wart"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "sense", count: 3, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_nether_wart-response-2")),
                    GET_ITEM("ender_eye"),
                    HIDE_TARGET()
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_nether_wart-response")),
            ],
        },
    ],
    type: "look",
});
const PULL_LEVERS = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.pull_levers"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "smart", count: 3, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.pull_levers-response-2")),
                    SHOW_TARGET("open_treasure_f1"),
                    HIDE_TARGET("inspect_circuitry"),
                    HIDE_TARGET()
                ],
            },
            elseif: {
                condition: hasItems({ id: "hp", count: 11, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.pull_levers-response")),
                    REMOVE_ITEM("hp", 10),
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.pull_levers-response")),
                DIE()
            ],
        },
    ],
});
const ATTEMPT_HARD_PARKOUR = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.attempt_hard_parkour"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "speed", count: 4, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.attempt_hard_parkour-response-2")),
                    GET_ITEM("strength"),
                    HIDE_TARGET("inspect_hard_parkour"),
                    HIDE_TARGET()
                ],
            },
            elseif: {
                condition: hasItems({ id: "hp", count: 6, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.attempt_hard_parkour-response")),
                    REMOVE_ITEM("hp", 5),
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.attempt_hard_parkour-response")),
                DIE()
            ],
        },
    ],
    type: "walk",
});
const INSPECT_ENCHANTING_TABLE = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_enchanting_table"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "smart", count: 4, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_enchanting_table-response-2")),
                    GET_ITEM("speed"),
                    HIDE_TARGET()
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_enchanting_table-response")),
            ],
        },
    ],
    type: "look",
});
const INSPECT_LEDGE = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_ledge"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "sense", count: 3, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_ledge-response-2")),
                    GET_ITEM("ender_eye"),
                    HIDE_TARGET()
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_ledge-response")),
            ],
        },
    ],
    type: "look",
});
const OPEN_TREASURE_F1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.open_treasure_f1"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.open_treasure_f1-response")),
        GET_ITEM("strength"),
        HIDE_TARGET()
    ],
});
const OPEN_TREASURE_F2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.open_treasure_f2"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.open_treasure_f2-response")),
        GET_ITEM("ender_eye"),
        GET_ITEM("speed"),
        HIDE_TARGET()
    ],
});
const OPEN_TREASURE_F3 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.open_treasure_f3"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.open_treasure_f3-response")),
        GET_ITEM("sense"),
        HIDE_TARGET()
    ],
});
const INSPECT_SILVERFISH = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_silverfish"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "sense", count: 3, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_silverfish-response-2", "\n")),
                    SHOW_TARGET("use_secret_passage")
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_silverfish-response")),
            ],
        },
    ],
    type: "look",
});
const INSPECT_PARKOUR = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_parkour"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_parkour-response")),
    ],
    type: "look",
});
const INSPECT_GAP = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_gap"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_gap-response")),
    ],
    type: "look",
});
const INSPECT_CELLS = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_cells"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_cells-response")),
    ],
    type: "look",
});
const INSPECT_BUTTONS = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_buttons"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_buttons-response")),
    ],
    type: "look",
});
const INSPECT_SPIDERS = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_spiders"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_spiders-response")),
    ],
    type: "look",
});
const INSPECT_JUMP = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_jump"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_jump-response")),
    ],
    type: "look",
});
const INSPECT_LAVA_FOUNTAIN = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_lava_fountain"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_lava_fountain-response")),
    ],
    type: "look",
});
const INSPECT_CHAIR = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_chair"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_chair-response")),
        GET_ITEM("hp", 5),
        HIDE_TARGET()
    ],
    type: "look",
});
const INSPECT_CIRCUITRY = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_circuitry"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_circuitry-response")),
    ],
    type: "look",
});
const INSPECT_SKELETONS = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_skeletons"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_skeletons-response")),
    ],
    type: "look",
});
const INSPECT_SKULK = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_skulk"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_skulk-response")),
        SHOW_TARGET("take_skulk_sensor"),
    ],
    type: "look",
});
const TAKE_SKULK_SENSOR = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.take_skulk_sensor"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.take_skulk_sensor-response")),
        GET_ITEM("sense"),
        HIDE_TARGET("inspect_skulk"),
        HIDE_TARGET()
    ],
});
const UP_ARROW_KEY = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.up_arrow_key"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.up_arrow_key-response")),
        GET_ITEM("up_arrow_key"),
        HIDE_TARGET()
    ],
});
const DOWN_ARROW_KEY = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.down_arrow_key"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.down_arrow_key-response")),
        GET_ITEM("down_arrow_key"),
        HIDE_TARGET()
    ],
});
const INSPECT_HARD_PARKOUR = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_hard_parkour"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_hard_parkour-response")),
    ],
    type: "look",
});
const INSPECT_WATER_FOUNTAIN = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_water_fountain"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_water_fountain-response")),
        GET_ITEM("hp", 5),
        HIDE_TARGET()
    ],
    type: "look",
});
const INSPECT_SKYLIGHT = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_skylight"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_skylight-response")),
    ],
    type: "look",
});
const INSPECT_ZOMBIES = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_zombies"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_zombies-response")),
    ],
    type: "look",
});
const INSPECT_CREEPER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_creeper"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_creeper-response")),
    ],
    type: "look",
});
const INSPECT_ITEM_FRAME = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_item_frame"),
    actions: [
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.inspect_item_frame-response")),
        GET_ITEM("speed"),
        HIDE_TARGET()
    ],
    type: "look",
});
const FIGHT_SILVERFISH = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_silverfish"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "strength", count: 2, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_silverfish-response")),
                    GET_ITEM("silverfish_scale"),
                    HIDE_TARGET("inspect_silverfish"),
                    HIDE_TARGET()
                ],
            },
            elseif: {
                condition: hasItems({ id: "hp", count: 6, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_silverfish-response-2")),
                    REMOVE_ITEM("hp", 5),
                    GET_ITEM("silverfish_scale"),
                    HIDE_TARGET("inspect_silverfish"),
                    HIDE_TARGET()
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_silverfish-response-2")),
                DIE()
            ],
        },
    ],
    type: "attack",
});
const STRATEGIZE_SPIDERS = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.strategize_spiders"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "smart", count: 3, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.strategize_spiders-response-2")),
                    GET_ITEM("string"),
                    HIDE_TARGET(),
                    HIDE_TARGET("fight_spider_1")
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.strategize_spiders-response")),
            ],
        },
    ],
});
const FIGHT_SPIDER_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_spider_1"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "strength", count: 3, }, { id: "string", count: 1, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_spider_1-response")),
                    GET_ITEM("string"),
                    SHOW_TARGET("open_treasure_f2"),
                    HIDE_TARGET("inspect_spiders"),
                    HIDE_TARGET("strategize_spiders"),
                    HIDE_TARGET()
                ],
            },
            elseif: [{
                    condition: hasItems({ id: "strength", count: 2, }, { id: "string", count: 1, }, { id: "hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_spider_1-response-2")),
                        REMOVE_ITEM("hp", 5),
                        GET_ITEM("string"),
                        SHOW_TARGET("open_treasure_f2"),
                        HIDE_TARGET("inspect_spiders"),
                        HIDE_TARGET("strategize_spiders"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "strength", count: 3, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_spider_1-response")),
                        GET_ITEM("string"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "strength", count: 2, }, { id: "hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_spider_1-response-2")),
                        REMOVE_ITEM("hp", 5),
                        GET_ITEM("string"),
                        HIDE_TARGET()
                    ],
                }],
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.die")),
                DIE(),
            ],
        },
    ],
    type: "attack",
});
const FIGHT_SPIDER_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_spider_2"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "strength", count: 3, }, { id: "string", count: 1, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_spider_2-response")),
                    GET_ITEM("string"),
                    SHOW_TARGET("open_treasure_f2"),
                    HIDE_TARGET("inspect_spiders"),
                    HIDE_TARGET("strategize_spiders"),
                    HIDE_TARGET()
                ],
            },
            elseif: [{
                    condition: hasItems({ id: "strength", count: 2, }, { id: "string", count: 1, }, { id: "hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_spider_2-response-2")),
                        REMOVE_ITEM("hp", 5),
                        GET_ITEM("string"),
                        SHOW_TARGET("open_treasure_f2"),
                        HIDE_TARGET("inspect_spiders"),
                        HIDE_TARGET("strategize_spiders"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "strength", count: 3, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_spider_2-response")),
                        GET_ITEM("string"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "strength", count: 2, }, { id: "hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_spider_2-response-2")),
                        REMOVE_ITEM("hp", 5),
                        GET_ITEM("string"),
                        HIDE_TARGET()
                    ],
                }],
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.die")),
                DIE(),
            ],
        },
    ],
    type: "attack",
});
const FIGHT_ZOMBIE_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_zombie_1"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "strength", count: 3, }, { id: "rotten_flesh", count: 2, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_zombie_1-response")),
                    GET_ITEM("rotten_flesh"),
                    SHOW_TARGET("open_treasure_f3"),
                    HIDE_TARGET("inspect_zombies"),
                    HIDE_TARGET()
                ],
            },
            elseif: [{
                    condition: hasItems({ id: "strength", count: 2, }, { id: "rotten_flesh", count: 2, }, { id: "hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_zombie_1-response-2")),
                        REMOVE_ITEM("hp", 5),
                        GET_ITEM("rotten_flesh"),
                        SHOW_TARGET("open_treasure_f3"),
                        HIDE_TARGET("inspect_zombies"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "strength", count: 3, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_zombie_1-response")),
                        GET_ITEM("rotten_flesh"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "strength", count: 2, }, { id: "hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_zombie_1-response-2")),
                        REMOVE_ITEM("hp", 5),
                        GET_ITEM("rotten_flesh"),
                        HIDE_TARGET()
                    ],
                }],
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.die")),
                DIE()
            ],
        },
    ],
    type: "attack",
});
const FIGHT_ZOMBIE_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_zombie_2"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "strength", count: 3, }, { id: "rotten_flesh", count: 2, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_zombie_2-response")),
                    GET_ITEM("rotten_flesh"),
                    SHOW_TARGET("open_treasure_f3"),
                    HIDE_TARGET("inspect_zombies"),
                    HIDE_TARGET()
                ],
            },
            elseif: [{
                    condition: hasItems({ id: "strength", count: 2, }, { id: "rotten_flesh", count: 2, }, { id: "hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_zombie_2-response-2")),
                        REMOVE_ITEM("hp", 5),
                        GET_ITEM("rotten_flesh"),
                        SHOW_TARGET("open_treasure_f3"),
                        HIDE_TARGET("inspect_zombies"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "strength", count: 3, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_zombie_2-response")),
                        GET_ITEM("rotten_flesh"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "strength", count: 2, }, { id: "hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_zombie_2-response-2")),
                        REMOVE_ITEM("hp", 5),
                        GET_ITEM("rotten_flesh"),
                        HIDE_TARGET()
                    ],
                }],
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.die")),
                DIE()
            ],
        },
    ],
    type: "attack",
});
const FIGHT_ZOMBIE_3 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_zombie_3"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "strength", count: 3, }, { id: "rotten_flesh", count: 2, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_zombie_3-response")),
                    GET_ITEM("rotten_flesh"),
                    SHOW_TARGET("open_treasure_f3"),
                    HIDE_TARGET("inspect_zombies"),
                    HIDE_TARGET()
                ],
            },
            elseif: [{
                    condition: hasItems({ id: "strength", count: 2, }, { id: "rotten_flesh", count: 2, }, { id: "hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_zombie_3-response-2")),
                        REMOVE_ITEM("hp", 5),
                        GET_ITEM("rotten_flesh"),
                        SHOW_TARGET("open_treasure_f3"),
                        HIDE_TARGET("inspect_zombies"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "strength", count: 3, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_zombie_3-response")),
                        GET_ITEM("rotten_flesh"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "strength", count: 2, }, { id: "hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_zombie_3-response-2")),
                        REMOVE_ITEM("hp", 5),
                        GET_ITEM("rotten_flesh"),
                        HIDE_TARGET()
                    ],
                }],
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.die")),
                DIE()
            ],
        },
    ],
    type: "attack",
});
const STRATEGIZE_SKELETONS = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.strategize_skeletons"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "speed", count: 4, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.strategize_skeletons-response-2")),
                    GET_ITEM("bone"),
                    HIDE_TARGET(),
                    HIDE_TARGET("fight_skeleton_1")
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.strategize_skeletons-response")),
            ],
        },
    ],
});
const FIGHT_SKELETON_1 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_skeleton_1"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "strength", count: 4, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_skeleton_1-response")),
                    HIDE_TARGET("inspect_skeletons"),
                    HIDE_TARGET("strategize_skeletons"),
                    GET_ITEM("bone"),
                    HIDE_TARGET()
                ],
            },
            elseif: {
                condition: hasItems({ id: "strength", count: 3, }, { id: "hp", count: 6, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_skeleton_1-response-2")),
                    HIDE_TARGET("inspect_skeletons"),
                    HIDE_TARGET("strategize_skeletons"),
                    REMOVE_ITEM("hp", 5),
                    GET_ITEM("bone"),
                    HIDE_TARGET()
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.die")),
                DIE(),
            ],
        },
    ],
    type: "attack",
});
const FIGHT_SKELETON_2 = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_skeleton_2"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "strength", count: 4, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_skeleton_2-response")),
                    HIDE_TARGET("inspect_skeletons"),
                    HIDE_TARGET("strategize_skeletons"),
                    GET_ITEM("bone"),
                    HIDE_TARGET()
                ],
            },
            elseif: {
                condition: hasItems({ id: "strength", count: 3, }, { id: "hp", count: 6, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_skeleton_2-response-2")),
                    HIDE_TARGET("inspect_skeletons"),
                    HIDE_TARGET("strategize_skeletons"),
                    REMOVE_ITEM("hp", 5),
                    GET_ITEM("bone"),
                    HIDE_TARGET()
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.die")),
                DIE(),
            ],
        },
    ],
    type: "attack",
});
const STRATEGIZE_CREEPER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.strategize_creeper"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "sense", count: 4, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.strategize_creeper-response-2")),
                    HIDE_TARGET(),
                    SHOW_TARGET("inspect_item_frame"),
                    HIDE_TARGET("inspect_creeper"),
                    HIDE_TARGET("fight_creeper")
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.strategize_creeper-response")),
            ],
        },
    ],
});
const FIGHT_CREEPER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_creeper"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "strength", count: 4, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_creeper-response")),
                    SHOW_TARGET("inspect_item_frame"),
                    HIDE_TARGET("inspect_creeper"),
                    HIDE_TARGET("strategize_creeper"),
                    HIDE_TARGET()
                ],
            },
            elseif: {
                condition: hasItems({ id: "hp", count: 21, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_creeper-response-2")),
                    REMOVE_ITEM("hp", 20),
                    SHOW_TARGET("inspect_item_frame"),
                    HIDE_TARGET("inspect_creeper"),
                    HIDE_TARGET("strategize_creeper"),
                    HIDE_TARGET()
                ],
            },
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_creeper-response-2")),
                DIE()
            ],
        },
    ],
    type: "attack",
});
const LOOK_AROUND = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.look_around"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "sense", count: 5, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.look_around-response")),
                    GET_ITEM("broken_crystal", 2),
                    HIDE_TARGET()
                ],
            },
            elseif: [{
                    condition: hasItems({ id: "sense", count: 4, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.look_around-response-2")),
                        GET_ITEM("broken_crystal"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.look_around-response-3")),
                        REMOVE_ITEM("hp", 5),
                        HIDE_TARGET()
                    ],
                }],
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.look_around-response-3")),
                DIE()
            ],
        },
    ],
    type: "look",
});
const CLIMB_TOWER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.climb_tower"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "speed", count: 5, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.climb_tower-response")),
                    GET_ITEM("broken_crystal", 2),
                    HIDE_TARGET()
                ],
            },
            elseif: [{
                    condition: hasItems({ id: "speed", count: 4, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.climb_tower-response-2")),
                        GET_ITEM("broken_crystal"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.climb_tower-response-3")),
                        REMOVE_ITEM("hp", 5),
                        HIDE_TARGET()
                    ],
                }],
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.climb_tower-response-3")),
                DIE()
            ],
        },
    ],
});
const PUNCH_TOWER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.punch_tower"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "strength", count: 5, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.punch_tower-response")),
                    GET_ITEM("broken_crystal", 2),
                    HIDE_TARGET()
                ],
            },
            elseif: [{
                    condition: hasItems({ id: "strength", count: 4, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.punch_tower-response-2")),
                        GET_ITEM("broken_crystal"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.punch_tower-response-3")),
                        REMOVE_ITEM("hp", 5),
                        HIDE_TARGET()
                    ],
                }],
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.punch_tower-response-3")),
                DIE()
            ],
        },
    ],
    type: "attack",
});
const BUILD_REDSTONE = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.build_redstone"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "smart", count: 5, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.build_redstone-response")),
                    GET_ITEM("broken_crystal", 2),
                    HIDE_TARGET()
                ],
            },
            elseif: [
                {
                    condition: hasItems({ id: "smart", count: 4, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.build_redstone-response-2")),
                        GET_ITEM("broken_crystal"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.build_redstone-response-3")),
                        REMOVE_ITEM("hp", 5),
                        HIDE_TARGET()
                    ],
                }
            ],
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.build_redstone-response-3")),
                DIE()
            ],
        },
    ],
});
const FIGHT_DRAGON = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon"),
    actions: [
        {
            if: {
                condition: hasItems({ id: "broken_crystal", count: 8, }, { id: "dragon_hp", count: 13, }),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-9")),
                    REMOVE_ITEM("dragon_hp", 12)
                ],
            },
            elseif: [
                {
                    condition: hasItems({ id: "broken_crystal", count: 8, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-10")),
                        REMOVE_ITEM("dragon_hp", 100),
                        SHOW_TARGET("finisher_strength"),
                        SHOW_TARGET("finisher_speed"),
                        SHOW_TARGET("finisher_smart"),
                        SHOW_TARGET("finisher_sense"),
                        SHOW_TARGET("finisher_generic"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 7, }, { id: "dragon_hp", count: 12, }, { id: "hp", count: 2, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-8")),
                        REMOVE_ITEM("dragon_hp", 11),
                        REMOVE_ITEM("hp", 1)
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 7, }, { id: "dragon_hp", count: 12, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-8")),
                        DIE(),
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 7, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-10")),
                        REMOVE_ITEM("dragon_hp", 100),
                        SHOW_TARGET("finisher_strength"),
                        SHOW_TARGET("finisher_speed"),
                        SHOW_TARGET("finisher_smart"),
                        SHOW_TARGET("finisher_sense"),
                        SHOW_TARGET("finisher_generic"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 6, }, { id: "dragon_hp", count: 11, }, { id: "hp", count: 3, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-7")),
                        REMOVE_ITEM("dragon_hp", 10),
                        REMOVE_ITEM("hp", 2)
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 6, }, { id: "dragon_hp", count: 11, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-7")),
                        DIE(),
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-10")),
                        REMOVE_ITEM("dragon_hp", 100),
                        SHOW_TARGET("finisher_strength"),
                        SHOW_TARGET("finisher_speed"),
                        SHOW_TARGET("finisher_smart"),
                        SHOW_TARGET("finisher_sense"),
                        SHOW_TARGET("finisher_generic"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 5, }, { id: "dragon_hp", count: 10, }, { id: "hp", count: 4, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-6")),
                        REMOVE_ITEM("dragon_hp", 9),
                        REMOVE_ITEM("hp", 3)
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 5, }, { id: "dragon_hp", count: 10, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-6")),
                        DIE(),
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 5, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-10")),
                        REMOVE_ITEM("dragon_hp", 100),
                        SHOW_TARGET("finisher_strength"),
                        SHOW_TARGET("finisher_speed"),
                        SHOW_TARGET("finisher_smart"),
                        SHOW_TARGET("finisher_sense"),
                        SHOW_TARGET("finisher_generic"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 4, }, { id: "dragon_hp", count: 9, }, { id: "hp", count: 5, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-5")),
                        REMOVE_ITEM("dragon_hp", 8),
                        REMOVE_ITEM("hp", 4)
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 4, }, { id: "dragon_hp", count: 9, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-5")),
                        DIE(),
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 4, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-10")),
                        REMOVE_ITEM("dragon_hp", 100),
                        SHOW_TARGET("finisher_strength"),
                        SHOW_TARGET("finisher_speed"),
                        SHOW_TARGET("finisher_smart"),
                        SHOW_TARGET("finisher_sense"),
                        SHOW_TARGET("finisher_generic"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 3, }, { id: "dragon_hp", count: 8, }, { id: "hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-4")),
                        REMOVE_ITEM("dragon_hp", 7),
                        REMOVE_ITEM("hp", 5)
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 3, }, { id: "dragon_hp", count: 8, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-4")),
                        DIE(),
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 3, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-10")),
                        REMOVE_ITEM("dragon_hp", 100),
                        SHOW_TARGET("finisher_strength"),
                        SHOW_TARGET("finisher_speed"),
                        SHOW_TARGET("finisher_smart"),
                        SHOW_TARGET("finisher_sense"),
                        SHOW_TARGET("finisher_generic"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 2, }, { id: "dragon_hp", count: 7, }, { id: "hp", count: 7, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-3")),
                        REMOVE_ITEM("dragon_hp", 6),
                        REMOVE_ITEM("hp", 6)
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 2, }, { id: "dragon_hp", count: 7, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-3")),
                        DIE(),
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 2, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-10")),
                        REMOVE_ITEM("dragon_hp", 100),
                        SHOW_TARGET("finisher_strength"),
                        SHOW_TARGET("finisher_speed"),
                        SHOW_TARGET("finisher_smart"),
                        SHOW_TARGET("finisher_sense"),
                        SHOW_TARGET("finisher_generic"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 1, }, { id: "dragon_hp", count: 6, }, { id: "hp", count: 8, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-2")),
                        REMOVE_ITEM("dragon_hp", 5),
                        REMOVE_ITEM("hp", 7)
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 1, }, { id: "dragon_hp", count: 6, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-2")),
                        DIE(),
                    ],
                },
                {
                    condition: hasItems({ id: "broken_crystal", count: 1, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-10")),
                        REMOVE_ITEM("dragon_hp", 100),
                        SHOW_TARGET("finisher_strength"),
                        SHOW_TARGET("finisher_speed"),
                        SHOW_TARGET("finisher_smart"),
                        SHOW_TARGET("finisher_sense"),
                        SHOW_TARGET("finisher_generic"),
                        HIDE_TARGET()
                    ],
                },
                {
                    condition: hasItems({ id: "dragon_hp", count: 5, }, { id: "hp", count: 9, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response")),
                        REMOVE_ITEM("dragon_hp", 5),
                        REMOVE_ITEM("hp", 7)
                    ],
                },
                {
                    condition: hasItems({ id: "dragon_hp", count: 5, }),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response")),
                        DIE()
                    ],
                },
            ],
            else: [
                SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.fight_dragon-response-10")),
                REMOVE_ITEM("dragon_hp", 100),
                SHOW_TARGET("finisher_strength"),
                SHOW_TARGET("finisher_speed"),
                SHOW_TARGET("finisher_smart"),
                SHOW_TARGET("finisher_sense"),
                SHOW_TARGET("finisher_generic"),
                HIDE_TARGET()
            ],
        },
    ],
    type: "attack",
});
const FINISHER_STRENGTH = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.finisher_strength"),
    actions: [
        REMOVE_ITEM("broken_crystal", 100),
        CHANGE_LOCATION("ending_strength")
    ],
    type: "attack",
});
const FINISHER_SPEED = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.finisher_speed"),
    actions: [
        REMOVE_ITEM("broken_crystal", 100),
        CHANGE_LOCATION("ending_speed")
    ],
    type: "walk",
});
const FINISHER_SMART = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.finisher_smart"),
    actions: [
        REMOVE_ITEM("broken_crystal", 100),
        CHANGE_LOCATION("ending_smart")
    ],
});
const FINISHER_SENSE = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.finisher_sense"),
    actions: [
        REMOVE_ITEM("broken_crystal", 100),
        CHANGE_LOCATION("ending_sense")
    ],
    type: "look",
});
const FINISHER_GENERIC = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.finisher_generic"),
    actions: [
        REMOVE_ITEM("broken_crystal", 100),
        CHANGE_LOCATION("ending_generic")
    ],
    type: "attack",
});
const newSandEnderAdventureState = () => ({
    version: 1,
    inventory: [],
    status: 'playing',
    props: {},
    nextPrompt: [TRANSLATE$1("jig_ccomp:text-adventure.sandender.introduction")],
    currentRoom: "choose_class",
});
const newSandEnderAdventure = () => makeTextAdventure({
    overrides: {
        ui: {
            status: {
                title: "jig_ccomp:text-adventure.ui.select-adventure.adventure.sandender",
            }
        }
    },
    rooms: {
        choose_class: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.choose_class.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.choose_class.distance_description"),
            targets: {
                class_fighter: {
                    ...CLASS_FIGHTER,
                },
                class_sprinter: {
                    ...CLASS_SPRINTER,
                },
                class_enchanter: {
                    ...CLASS_ENCHANTER,
                },
                class_miner: {
                    ...CLASS_MINER,
                },
            },
            exits: {},
        },
        final_battle: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.final_battle.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.final_battle.distance_description"),
            targets: {
                look_around: {
                    ...LOOK_AROUND,
                },
                climb_tower: {
                    ...CLIMB_TOWER,
                },
                punch_tower: {
                    ...PUNCH_TOWER,
                },
                build_redstone: {
                    ...BUILD_REDSTONE,
                },
                fight_dragon: {
                    ...FIGHT_DRAGON,
                },
                finisher_strength: {
                    ...FINISHER_STRENGTH,
                    "hidden": true,
                },
                finisher_speed: {
                    ...FINISHER_SPEED,
                    "hidden": true,
                },
                finisher_smart: {
                    ...FINISHER_SMART,
                    "hidden": true,
                },
                finisher_sense: {
                    ...FINISHER_SENSE,
                    "hidden": true,
                },
                finisher_generic: {
                    ...FINISHER_GENERIC,
                    "hidden": true,
                },
            },
            exits: {},
        },
        ending_strength: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.finisher_strength-response", "\n"),
            targets: {
                ending: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.ending.description.button"),
                    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.ending.description", "\n")), WON("Strongholds & Ender Dragons", "{0} beat the Ender Dragon with strength!", "player"),
                        EARN_ACHIEVEMENT("se_d")],
                },
            },
            exits: {},
        },
        ending_speed: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.finisher_speed-response", "\n"),
            targets: {
                ending: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.ending.description.button"),
                    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.ending.description", "\n")), WON("Strongholds & Ender Dragons", "{0} beat the Ender Dragon with speed!", "player"),
                        EARN_ACHIEVEMENT("se_d")],
                },
            },
            exits: {},
        },
        ending_smart: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.finisher_smart-response", "\n"),
            targets: {
                ending: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.ending.description.button"),
                    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.ending.description", "\n")), WON("Strongholds & Ender Dragons", "{0} beat the Ender Dragon with smarts!", "player"),
                        EARN_ACHIEVEMENT("se_d")],
                },
            },
            exits: {},
        },
        ending_sense: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.finisher_sense-response", "\n"),
            targets: {
                ending: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.ending.description.button"),
                    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.ending.description", "\n")), WON("Strongholds & Ender Dragons", "{0} beat the Ender Dragon with sense!", "player"),
                        EARN_ACHIEVEMENT("se_d")],
                },
            },
            exits: {},
        },
        ending_generic: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.targets.finisher_generic-response", "\n"),
            targets: {
                ending: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.ending.description.button"),
                    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.ending.description", "\n")), WON("Strongholds & Ender Dragons", "{0} beat the Ender Dragon!", "player"),
                        EARN_ACHIEVEMENT("se_d")],
                },
            },
            exits: {},
        },
        f1_b1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_b1.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_b1.distance_description"),
            targets: {
                inspect_skulk: {
                    ...INSPECT_SKULK,
                },
                take_skulk_sensor: {
                    ...TAKE_SKULK_SENSOR,
                    "hidden": true,
                },
            },
            exits: {
                exitn: {
                    ...EXITS,
                    room: "f1_b2",
                },
            },
        },
        f1_b2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_b2.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_b2.distance_description"),
            targets: {
                inspect_skeletons: {
                    ...INSPECT_SKELETONS,
                },
                strategize_skeletons: {
                    ...STRATEGIZE_SKELETONS,
                },
                fight_skeleton_1: {
                    ...FIGHT_SKELETON_1,
                },
                fight_skeleton_2: {
                    ...FIGHT_SKELETON_2,
                },
            },
            exits: {
                "exitn": {
                    ...EXITN,
                    room: "f1_b1",
                    filter: hasItems({ id: "bone", count: 2, }),
                },
                exits: {
                    ...EXITS,
                    room: "f1_b3",
                },
            },
        },
        f1_b3: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_b3.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_b3.distance_description"),
            targets: {
                down_arrow_door_back: {
                    ...DOWN_ARROW_DOOR_BACK,
                },
            },
            exits: {
                exitn: {
                    ...EXITN,
                    room: "f1_b2",
                },
                exits: {
                    ...EXITS,
                    room: "f1_b4",
                },
                exite: {
                    ...EXITE,
                    room: "f1_c3",
                },
                "exitu": {
                    ...EXITU,
                    room: "f2_a3",
                    filter: hasItems("down_door_unlocked"),
                },
            },
        },
        f1_b4: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_b4.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_b4.distance_description"),
            targets: {
                inspect_circuitry: {
                    ...INSPECT_CIRCUITRY,
                },
                pull_levers: {
                    ...PULL_LEVERS,
                },
                open_treasure_f1: {
                    ...OPEN_TREASURE_F1,
                    "hidden": true,
                },
            },
            exits: {
                exitn: {
                    ...EXITN,
                    room: "f1_b3",
                },
                exite: {
                    ...EXITE,
                    room: "f1_c4_2",
                },
            },
        },
        f1_c3: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_c3.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_c3.distance_description"),
            targets: {
                inspect_lava_fountain: {
                    ...INSPECT_LAVA_FOUNTAIN,
                },
                inspect_chair: {
                    ...INSPECT_CHAIR,
                },
            },
            exits: {
                exitw: {
                    ...EXITW,
                    room: "f1_b3",
                },
                exite: {
                    ...EXITE,
                    room: "f1_d3",
                },
            },
        },
        f1_c4_1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_c4_1.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_c4_1.distance_description"),
            targets: {
                inspect_f1_c4: {
                    ...INSPECT_F1_C4,
                },
                walk_f1_c4: {
                    ...WALK_F1_C4_1,
                },
            },
            exits: {
                exite: {
                    ...EXITE,
                    room: "f1_d4",
                },
            },
        },
        f1_c4_2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_c4_2.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_c4_2.distance_description"),
            targets: {
                inspect_f1_c4: {
                    ...INSPECT_F1_C4,
                },
                walk_f1_c4: {
                    ...WALK_F1_C4_2,
                },
            },
            exits: {
                exitw: {
                    ...EXITW,
                    room: "f1_b4",
                },
            },
        },
        f1_d1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_d1.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_d1.distance_description"),
            targets: {
                inspect_jump: {
                    ...INSPECT_JUMP,
                },
                attempt_jump: {
                    ...ATTEMPT_JUMP,
                },
            },
            exits: {
                exits: {
                    ...EXITS,
                    room: "f1_d2_1",
                },
                exitu: {
                    ...EXITU,
                    room: "f2_d1",
                },
            },
        },
        f1_d2_1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_d2_1.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_d2_1.distance_description"),
            targets: {
                inspect_f1_d2: {
                    ...INSPECT_F1_D2,
                },
                walk_f1_d2: {
                    ...WALK_F1_D2_1,
                },
            },
            exits: {
                exitn: {
                    ...EXITN,
                    room: "f1_d1",
                },
            },
        },
        f1_d2_2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_d2_2.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_d2_2.distance_description"),
            targets: {
                inspect_f1_d2: {
                    ...INSPECT_F1_D2,
                },
                walk_f1_d2: {
                    ...WALK_F1_D2_2,
                },
            },
            exits: {
                exits: {
                    ...EXITS,
                    room: "f1_d3",
                },
            },
        },
        f1_d3: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_d3.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_d3.distance_description"),
            targets: {
                inspect_brewing_stand: {
                    ...INSPECT_BREWING_STAND,
                },
            },
            exits: {
                exitn: {
                    ...EXITN,
                    room: "f1_d2_2",
                },
                exitw: {
                    ...EXITW,
                    room: "f1_c3",
                },
                exits: {
                    ...EXITS,
                    room: "f1_d4",
                },
            },
        },
        f1_d4: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_d4.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f1_d4.distance_description"),
            targets: {
                inspect_nether_wart: {
                    ...INSPECT_NETHER_WART,
                },
            },
            exits: {
                exitn: {
                    ...EXITN,
                    room: "f1_d3",
                },
                exitw: {
                    ...EXITW,
                    room: "f1_c4_1",
                },
            },
        },
        f2_a1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_a1.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_a1.distance_description"),
            targets: {
                end_portal: {
                    ...END_PORTAL,
                },
            },
            exits: {
                exits: {
                    ...EXITS,
                    room: "f2_a2",
                },
            },
        },
        f2_a2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_a2.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_a2.distance_description"),
            targets: {
                dev_shortcut_1: {
                    ...DEV_SHORTCUT_1,
                    "hidden": true
                },
            },
            exits: {
                exitn: {
                    ...EXITN,
                    room: "f2_a1",
                },
                exite: {
                    ...EXITE,
                    room: "f2_b2_1",
                },
                exits: {
                    ...EXITS,
                    room: "f2_a3",
                },
            },
        },
        f2_a3: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_a3.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_a3.distance_description"),
            targets: {
                up_arrow_door: {
                    ...UP_ARROW_DOOR,
                },
                down_arrow_door: {
                    ...DOWN_ARROW_DOOR,
                },
            },
            exits: {
                exitn: {
                    ...EXITN,
                    room: "f2_a2",
                },
                "exitu": {
                    ...EXITU,
                    room: "f3_a4",
                    filter: hasItems("up_door_unlocked"),
                },
                "exitd": {
                    ...EXITD,
                    room: "f1_b3",
                    filter: hasItems("down_door_unlocked"),
                },
            },
        },
        f2_b2_1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_b2_1.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_b2_1.distance_description"),
            targets: {
                inspect_f2_b2: {
                    ...INSPECT_F2_B2,
                },
                walk_f2_b2: {
                    ...WALK_F2_B2_1,
                },
            },
            exits: {
                exitw: {
                    ...EXITW,
                    room: "f2_a2",
                },
            },
        },
        f2_b2_2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_b2_2.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_b2_2.distance_description"),
            targets: {
                inspect_f2_b2: {
                    ...INSPECT_F2_B2,
                },
                walk_f2_b2: {
                    ...WALK_F2_B2_2,
                },
                inspect_silverfish: {
                    ...INSPECT_SILVERFISH,
                },
                fight_silverfish: {
                    ...FIGHT_SILVERFISH,
                },
                use_secret_passage: {
                    ...USE_SECRET_PASSAGE,
                    "hidden": true
                },
            },
            exits: {
                "exite": {
                    ...EXITE,
                    room: "f2_c2",
                    filter: hasItems("silverfish_scale"),
                },
            },
        },
        f2_c1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_c1.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_c1.distance_description"),
            targets: {
                inspect_gap: {
                    ...INSPECT_GAP,
                },
                inspect_cells: {
                    ...INSPECT_CELLS,
                },
            },
            exits: {
                exits: {
                    ...EXITS,
                    room: "f2_c2",
                },
            },
        },
        f2_c2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_c2.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_c2.distance_description"),
            targets: {
                inspect_parkour: {
                    ...INSPECT_PARKOUR,
                },
                attempt_parkour: {
                    ...ATTEMPT_PARKOUR,
                },
            },
            exits: {
                exitn: {
                    ...EXITN,
                    room: "f2_c1",
                },
                exitw: {
                    ...EXITW,
                    room: "f2_b2_2",
                },
                exite: {
                    ...EXITE,
                    room: "f2_d2",
                },
                exits: {
                    ...EXITS,
                    room: "f2_c3",
                },
            },
        },
        f2_c3: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_c3.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_c3.distance_description"),
            targets: {
                inspect_emptiness: {
                    ...INSPECT_EMPTINESS,
                },
            },
            exits: {
                exitn: {
                    ...EXITN,
                    room: "f2_c2",
                },
                exite: {
                    ...EXITE,
                    room: "f2_d3",
                },
            },
        },
        f2_d1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_d1.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_d1.distance_description"),
            targets: {
                up_arrow_key: {
                    ...UP_ARROW_KEY,
                },
                inspect_trapped_chest: {
                    ...INSPECT_TRAPPED_CHEST,
                },
                open_trapped_chest: {
                    ...OPEN_TRAPPED_CHEST,
                },
            },
            exits: {
                exitd: {
                    ...EXITD,
                    room: "f1_d1",
                },
                exits: {
                    ...EXITS,
                    room: "f2_d2",
                },
            },
        },
        f2_d2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_d2.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_d2.distance_description"),
            targets: {
                inspect_buttons: {
                    ...INSPECT_BUTTONS,
                },
                press_buttons: {
                    ...PRESS_BUTTONS,
                },
            },
            exits: {
                "exitn": {
                    ...EXITN,
                    room: "f2_d1",
                    filter: hasItems("puzzle_door_unlocked"),
                },
                exitw: {
                    ...EXITW,
                    room: "f2_c2",
                },
                exits: {
                    ...EXITS,
                    room: "f2_d3",
                },
            },
        },
        f2_d3: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_d3.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f2_d3.distance_description"),
            targets: {
                inspect_spiders: {
                    ...INSPECT_SPIDERS,
                },
                strategize_spiders: {
                    ...STRATEGIZE_SPIDERS,
                },
                fight_spider_1: {
                    ...FIGHT_SPIDER_1,
                },
                fight_spider_2: {
                    ...FIGHT_SPIDER_2,
                },
                open_treasure_f2: {
                    ...OPEN_TREASURE_F2,
                    "hidden": true,
                },
            },
            exits: {
                exitn: {
                    ...EXITN,
                    room: "f2_d2",
                },
                exitw: {
                    ...EXITW,
                    room: "f2_c3",
                },
            },
        },
        f3_a1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_a1.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_a1.distance_description"),
            targets: {
                inspect_ledge: {
                    ...INSPECT_LEDGE,
                },
            },
            exits: {
                exits: {
                    ...EXITS,
                    room: "f3_a2",
                },
                exite: {
                    ...EXITE,
                    room: "f3_b1",
                },
            },
        },
        f3_a2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_a2.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_a2.distance_description"),
            targets: {
                inspect_enchanting_table: {
                    ...INSPECT_ENCHANTING_TABLE,
                },
            },
            exits: {
                exitn: {
                    ...EXITN,
                    room: "f3_a1",
                },
                exite: {
                    ...EXITE,
                    room: "f3_b2",
                },
                exits: {
                    ...EXITS,
                    room: "f3_a3_1",
                },
            },
        },
        f3_a3_1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_a3_1.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_a3_1.distance_description"),
            targets: {
                inspect_f3_a3: {
                    ...INSPECT_F3_A3,
                },
                walk_f3_a3: {
                    ...WALK_F3_A3_1,
                },
                modify_redstone: {
                    ...MODIFY_REDSTONE,
                    "hidden": true
                },
            },
            exits: {
                exitn: {
                    ...EXITN,
                    room: "f3_a2",
                },
            },
        },
        f3_a3_2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_a3_2.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_a3_2.distance_description"),
            targets: {
                inspect_f3_a3: {
                    ...INSPECT_F3_A3,
                },
                walk_f3_a3: {
                    ...WALK_F3_A3_2,
                },
                modify_redstone: {
                    ...MODIFY_REDSTONE,
                    "hidden": true
                },
            },
            exits: {
                exits: {
                    ...EXITS,
                    room: "f3_a4",
                },
            },
        },
        f3_a4: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_a4.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_a4.distance_description"),
            targets: {
                inspect_locked_chest: {
                    ...INSPECT_LOCKED_CHEST,
                },
                up_arrow_door_back: {
                    ...UP_ARROW_DOOR_BACK,
                },
            },
            exits: {
                exitn: {
                    ...EXITN,
                    room: "f3_a3_2",
                },
                "exitd": {
                    ...EXITD,
                    room: "f2_a3",
                    filter: hasItems("up_door_unlocked"),
                },
            },
        },
        f3_b1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_b1.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_b1.distance_description"),
            targets: {
                inspect_skylight: {
                    ...INSPECT_SKYLIGHT,
                },
            },
            exits: {
                exitw: {
                    ...EXITW,
                    room: "f3_a1",
                },
                exite: {
                    ...EXITE,
                    room: "f3_c1",
                },
                exits: {
                    ...EXITS,
                    room: "f3_b2",
                },
            },
        },
        f3_b2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_b2.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_b2.distance_description"),
            targets: {
                inspect_water_fountain: {
                    ...INSPECT_WATER_FOUNTAIN,
                },
                down_arrow_key: {
                    ...DOWN_ARROW_KEY,
                },
            },
            exits: {
                exitn: {
                    ...EXITN,
                    room: "f3_b1",
                },
                exitw: {
                    ...EXITW,
                    room: "f3_a2",
                },
                exite: {
                    ...EXITE,
                    room: "f3_c2",
                },
            },
        },
        f3_c1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_c1.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_c1.distance_description"),
            targets: {
                inspect_zombies: {
                    ...INSPECT_ZOMBIES,
                },
                fight_zombie_1: {
                    ...FIGHT_ZOMBIE_1,
                },
                fight_zombie_2: {
                    ...FIGHT_ZOMBIE_2,
                },
                fight_zombie_3: {
                    ...FIGHT_ZOMBIE_3,
                },
                open_treasure_f3: {
                    ...OPEN_TREASURE_F3,
                    "hidden": true,
                },
            },
            exits: {
                exitw: {
                    ...EXITW,
                    room: "f3_b1",
                },
                exits: {
                    ...EXITS,
                    room: "f3_c2",
                },
            },
        },
        f3_c2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_c2.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_c2.distance_description"),
            targets: {
                inspect_hard_parkour: {
                    ...INSPECT_HARD_PARKOUR,
                },
                attempt_hard_parkour: {
                    ...ATTEMPT_HARD_PARKOUR,
                },
            },
            exits: {
                exitn: {
                    ...EXITN,
                    room: "f3_c1",
                },
                exitw: {
                    ...EXITW,
                    room: "f3_b2",
                },
                exits: {
                    ...EXITS,
                    room: "f3_c3_1",
                },
                exitd: {
                    ...EXITD,
                    room: "f2_c2",
                },
            },
        },
        f3_c3_1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_c3_1.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_c3_1.distance_description"),
            targets: {
                inspect_f3_c3: {
                    ...INSPECT_F3_C3,
                },
                walk_f3_c3: {
                    ...WALK_F3_C3_1,
                },
            },
            exits: {
                exitn: {
                    ...EXITN,
                    room: "f3_c2",
                },
            },
        },
        f3_c3_2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_c3_2.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_c3_2.distance_description"),
            targets: {
                inspect_f3_c3: {
                    ...INSPECT_F3_C3,
                },
                walk_f3_c3: {
                    ...WALK_F3_C3_2,
                },
            },
            exits: {
                exits: {
                    ...EXITS,
                    room: "f3_c4",
                },
            },
        },
        f3_c4: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_c4.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.room.f3_c4.distance_description"),
            targets: {
                inspect_creeper: {
                    ...INSPECT_CREEPER,
                },
                strategize_creeper: {
                    ...STRATEGIZE_CREEPER,
                },
                fight_creeper: {
                    ...FIGHT_CREEPER,
                },
                inspect_item_frame: {
                    ...INSPECT_ITEM_FRAME,
                    "hidden": true,
                },
            },
            exits: {
                exitn: {
                    ...EXITN,
                    room: "f3_c3_2",
                },
            },
        },
    },
    items: {
        hp: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.hp"),
        },
        strength: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.strength"),
        },
        speed: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.speed"),
        },
        smart: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.smart"),
        },
        sense: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.sense"),
        },
        up_door_unlocked: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.up_door_unlocked"),
        },
        down_door_unlocked: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.down_door_unlocked"),
        },
        puzzle_door_unlocked: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.puzzle_door_unlocked"),
        },
        string: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.string"),
        },
        bone: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.bone"),
        },
        rotten_flesh: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.rotten_flesh"),
        },
        spider_eye: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.spider_eye"),
        },
        silverfish_scale: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.silverfish_scale"),
        },
        up_arrow_key: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.up_arrow_key"),
        },
        down_arrow_key: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.down_arrow_key"),
        },
        ender_eye: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.ender_eye"),
        },
        tripwire: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.tripwire"),
        },
        redstone: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.redstone"),
        },
        redstone_torch: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.redstone_torch"),
        },
        dragon_hp: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.dragon_hp"),
        },
        broken_crystal: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sandender.item.broken_crystal"),
        },
    },
    achievements: Object.fromEntries(["se_d", "se_f", "se_m", "se_e", "se_s"].map((id) => [
        id,
        {
            name: `jig_ccomp:text-adventure.sandender.achievement.${id}.name`,
            description: `jig_ccomp:text-adventure.sandender.achievement.${id}.description`,
            hint: `jig_ccomp:text-adventure.sandender.achievement.${id}.hint`,
            icon: `textures/jig/ccomp/items/art/${id}.png`,
            item: `jig_ccomp:poster_${id}`,
            print_title: "",
            print_content: "",
        },
    ])),
});

const HALLWAY_TRAVEL_ACTIONS = [
    ROLL_AND_SET(14, "hallway_roll"),
    INCREMENT_VALUE("hallways_travelled"),
    {
        if: {
            condition: ALL(IS_VALUE("hallways_travelled", 100)),
            actions: [EARN_ACHIEVEMENT("eh_hall")],
        },
    },
];
const CHECK_ALL_ROOMS_VISITED = [{
        if: {
            condition: ALL(IS_VALUE("visited.exit", true), IS_VALUE("visited.monster", true), IS_VALUE("visited.key", true), IS_VALUE("visited.sword", true)),
            actions: [
                EARN_ACHIEVEMENT("eh_sword"),
            ],
        },
    }];
const NORTH$2 = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.exit.continue", "\n"),
});
const MONSTER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.targets.monster", "\n"),
    actions: [
        {
            if: {
                condition: hasItems("big_sword"),
                actions: [
                    HIDE_TARGET(),
                    SET_VALUE("killed.ogre", true),
                    GET_ITEM("small_key"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.endless_h.targets.monster.succeed", "\n")),
                    CHANGE_LOCATION("no_monster_hallway"),
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.endless_h.targets.monster.fail", "\n")), DIE()],
        },
    ],
    type: "attack",
});
const SWORDCHEST = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.targets.swordchest", "\n"),
    actions: [
        HIDE_TARGET(),
        SET_VALUE("big_sword.got", true),
        GET_ITEM("big_sword"),
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.endless_h.targets.swordchest-reward", "\n")),
        CHANGE_LOCATION("empty_sword_chest_hallway"),
    ],
});
const KEYCHEST = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.targets.keychest", "\n"),
    actions: [
        {
            if: {
                condition: hasItems("small_key"),
                actions: [
                    HIDE_TARGET(),
                    SET_VALUE("big_key.got", true),
                    REMOVE_ITEM("small_key"),
                    GET_ITEM("big_key"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.endless_h.targets.keychest-reward", "\n")),
                    CHANGE_LOCATION("empty_key_chest_hallway"),
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.endless_h.targets.keychest.fail", "\n")), DIE()],
        },
    ],
});
const EXITDOOR = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.targets.exit_door", "\n"),
    actions: [
        {
            if: {
                condition: hasItems("big_key"),
                actions: [
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.endless_h.targets.exit_door-reward", "\n")),
                    EARN_ACHIEVEMENT("eh_door"),
                    WON("Endless Hallway", "It wasn't endless after all!", "player"),
                    REMOVE_ITEM("big_key"),
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.endless_h.targets.exit_door.fail", "\n")), DIE()],
        },
    ],
});
const newEndlessHAdventureState = () => ({
    version: 1,
    inventory: [],
    status: "playing",
    props: {},
    nextPrompt: [TRANSLATE$1("jig_ccomp:text-adventure.endless_h.introduction", "\n")],
    currentRoom: "first_room",
});
const newEndlessHAdventure = () => makeTextAdventure({
    overrides: {
        ui: {
            status: {
                title: "jig_ccomp:text-adventure.ui.select-adventure.adventure.endless_h",
            },
        },
    },
    rooms: {
        first_room: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.first_room.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.first_room.distance_description", "\n"),
            targets: {},
            exits: {
                north: {
                    ...NORTH$2,
                    room: "a_hallway",
                    actions: [ROLL_AND_SET(10, "hallway_roll")],
                },
            },
        },
        a_hallway: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.a_hallway.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.a_hallway.distance_description", "\n"),
            targets: {},
            exits: {
                loop_back: {
                    ...NORTH$2,
                    room: "a_hallway",
                    filter: ANY(IS_VALUE("hallway_roll", 1), IS_VALUE("hallway_roll", 2), IS_VALUE("hallway_roll", 3), IS_VALUE("hallway_roll", 4), IS_VALUE("hallway_roll", 5), IS_VALUE("hallway_roll", 6)),
                    actions: [...HALLWAY_TRAVEL_ACTIONS],
                },
                loop_back_alt_1: {
                    ...NORTH$2,
                    room: "a_hallway_1",
                    filter: ANY(IS_VALUE("hallway_roll", 7), IS_VALUE("hallway_roll", 8)),
                    actions: [...HALLWAY_TRAVEL_ACTIONS],
                },
                loop_back_alt_2: {
                    ...NORTH$2,
                    room: "a_hallway_2",
                    filter: ANY(IS_VALUE("hallway_roll", 9), IS_VALUE("hallway_roll", 10)),
                    actions: [...HALLWAY_TRAVEL_ACTIONS],
                },
                to_exit: {
                    ...NORTH$2,
                    room: "exit_door",
                    filter: IS_VALUE("hallway_roll", 11),
                    actions: [SET_VALUE("visited.exit", true), ...CHECK_ALL_ROOMS_VISITED,],
                },
                to_monster: {
                    ...NORTH$2,
                    room: "monster_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 12), IS_NOT_VALUE("killed.ogre", true)),
                    actions: [SET_VALUE("visited.monster", true), ...CHECK_ALL_ROOMS_VISITED,],
                },
                to_no_monster: {
                    ...NORTH$2,
                    room: "no_monster_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 12), IS_VALUE("killed.ogre", true)),
                },
                to_key_chest: {
                    ...NORTH$2,
                    room: "key_chest_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 13), IS_NOT_VALUE("big_key.got", true)),
                    actions: [SET_VALUE("visited.key", true), ...CHECK_ALL_ROOMS_VISITED,],
                },
                to_empty_key_chest: {
                    ...NORTH$2,
                    room: "empty_key_chest_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 13), IS_VALUE("big_key.got", true)),
                },
                to_sword_chest: {
                    ...NORTH$2,
                    room: "sword_chest_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 14), IS_NOT_VALUE("big_sword.got", true)),
                    actions: [SET_VALUE("visited.sword", true), ...CHECK_ALL_ROOMS_VISITED,],
                },
                to_no_sword_chest: {
                    ...NORTH$2,
                    room: "empty_sword_chest_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 14), IS_VALUE("big_sword.got", true)),
                },
            },
        },
        a_hallway_1: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.a_hallway_alt_1.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.a_hallway_alt_1.distance_description", "\n"),
            targets: {},
            exits: {
                loop_back: {
                    ...NORTH$2,
                    room: "a_hallway",
                    filter: ANY(IS_VALUE("hallway_roll", 1), IS_VALUE("hallway_roll", 2), IS_VALUE("hallway_roll", 3), IS_VALUE("hallway_roll", 4), IS_VALUE("hallway_roll", 5), IS_VALUE("hallway_roll", 6), IS_VALUE("hallway_roll", 7), IS_VALUE("hallway_roll", 8), IS_VALUE("hallway_roll", 9), IS_VALUE("hallway_roll", 10)),
                    actions: [...HALLWAY_TRAVEL_ACTIONS],
                },
                to_exit: {
                    ...NORTH$2,
                    room: "exit_door",
                    filter: IS_VALUE("hallway_roll", 11),
                    actions: [SET_VALUE("visited.exit", true), ...CHECK_ALL_ROOMS_VISITED,],
                },
                to_monster: {
                    ...NORTH$2,
                    room: "monster_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 12), IS_NOT_VALUE("killed.ogre", true)),
                    actions: [SET_VALUE("visited.monster", true), ...CHECK_ALL_ROOMS_VISITED,],
                },
                to_no_monster: {
                    ...NORTH$2,
                    room: "no_monster_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 12), IS_VALUE("killed.ogre", true)),
                },
                to_key_chest: {
                    ...NORTH$2,
                    room: "key_chest_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 13), IS_NOT_VALUE("big_key.got", true)),
                    actions: [SET_VALUE("visited.key", true), ...CHECK_ALL_ROOMS_VISITED,],
                },
                to_empty_key_chest: {
                    ...NORTH$2,
                    room: "empty_key_chest_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 13), IS_VALUE("big_key.got", true)),
                },
                to_sword_chest: {
                    ...NORTH$2,
                    room: "sword_chest_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 14), IS_NOT_VALUE("big_sword.got", true)),
                    actions: [SET_VALUE("visited.sword", true), ...CHECK_ALL_ROOMS_VISITED,],
                },
                to_no_sword_chest: {
                    ...NORTH$2,
                    room: "empty_sword_chest_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 14), IS_VALUE("big_sword.got", true)),
                },
            },
        },
        a_hallway_2: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.a_hallway_alt_2.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.a_hallway_alt_2.distance_description", "\n"),
            targets: {},
            exits: {
                loop_back: {
                    ...NORTH$2,
                    room: "a_hallway",
                    filter: ANY(IS_VALUE("hallway_roll", 1), IS_VALUE("hallway_roll", 2), IS_VALUE("hallway_roll", 3), IS_VALUE("hallway_roll", 4), IS_VALUE("hallway_roll", 5), IS_VALUE("hallway_roll", 6), IS_VALUE("hallway_roll", 7), IS_VALUE("hallway_roll", 8), IS_VALUE("hallway_roll", 9), IS_VALUE("hallway_roll", 10)),
                    actions: [...HALLWAY_TRAVEL_ACTIONS],
                },
                to_exit: {
                    ...NORTH$2,
                    room: "exit_door",
                    filter: IS_VALUE("hallway_roll", 11),
                    actions: [SET_VALUE("visited.exit", true), ...CHECK_ALL_ROOMS_VISITED,],
                },
                to_monster: {
                    ...NORTH$2,
                    room: "monster_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 12), IS_NOT_VALUE("killed.ogre", true)),
                    actions: [SET_VALUE("visited.monster", true), ...CHECK_ALL_ROOMS_VISITED,],
                },
                to_no_monster: {
                    ...NORTH$2,
                    room: "no_monster_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 12), IS_VALUE("killed.ogre", true)),
                },
                to_key_chest: {
                    ...NORTH$2,
                    room: "key_chest_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 13), IS_NOT_VALUE("big_key.got", true)),
                    actions: [SET_VALUE("visited.key", true), ...CHECK_ALL_ROOMS_VISITED,],
                },
                to_empty_key_chest: {
                    ...NORTH$2,
                    room: "empty_key_chest_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 13), IS_VALUE("big_key.got", true)),
                },
                to_sword_chest: {
                    ...NORTH$2,
                    room: "sword_chest_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 14), IS_NOT_VALUE("big_sword.got", true)),
                    actions: [SET_VALUE("visited.sword", true), ...CHECK_ALL_ROOMS_VISITED,],
                },
                to_no_sword_chest: {
                    ...NORTH$2,
                    room: "empty_sword_chest_hallway",
                    filter: ALL(IS_VALUE("hallway_roll", 14), IS_VALUE("big_sword.got", true)),
                },
            },
        },
        exit_door: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.exit_door.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.exit_door.distance_description", "\n"),
            targets: {
                key_chest: {
                    ...EXITDOOR,
                },
            },
            exits: {
                a_hallway: {
                    ...NORTH$2,
                    room: "a_hallway",
                    actions: [...HALLWAY_TRAVEL_ACTIONS],
                },
            },
        },
        key_chest_hallway: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.key_chest_hallway.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.key_chest_hallway.distance_description", "\n"),
            targets: {
                key_chest: {
                    ...KEYCHEST,
                },
            },
            exits: {
                a_hallway: {
                    ...NORTH$2,
                    room: "a_hallway",
                    actions: [...HALLWAY_TRAVEL_ACTIONS],
                },
            },
        },
        empty_key_chest_hallway: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.empty_key_chest_hallway.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.empty_key_chest_hallway.distance_description", "\n"),
            targets: {},
            exits: {
                a_hallway: {
                    ...NORTH$2,
                    room: "a_hallway",
                    actions: [...HALLWAY_TRAVEL_ACTIONS],
                },
            },
        },
        monster_hallway: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.monster_hallway.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.monster_hallway.distance_description", "\n"),
            targets: {
                monster: {
                    ...MONSTER,
                },
            },
            exits: {
                a_hallway: {
                    ...NORTH$2,
                    room: "a_hallway",
                    actions: [...HALLWAY_TRAVEL_ACTIONS],
                },
            },
        },
        no_monster_hallway: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.no_monster_hallway.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.no_monster_hallway.distance_description", "\n"),
            targets: {},
            exits: {
                a_hallway: {
                    ...NORTH$2,
                    room: "a_hallway",
                    actions: [...HALLWAY_TRAVEL_ACTIONS],
                },
            },
        },
        sword_chest_hallway: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.sword_chest_hallway.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.sword_chest_hallway.distance_description", "\n"),
            targets: {
                sword_chest: {
                    ...SWORDCHEST,
                },
            },
            exits: {
                a_hallway: {
                    ...NORTH$2,
                    room: "a_hallway",
                    actions: [...HALLWAY_TRAVEL_ACTIONS],
                },
            },
        },
        empty_sword_chest_hallway: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.empty_sword_chest_hallway.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.room.empty_sword_chest_hallway.distance_description", "\n"),
            targets: {},
            exits: {
                a_hallway: {
                    ...NORTH$2,
                    room: "a_hallway",
                    actions: [...HALLWAY_TRAVEL_ACTIONS],
                },
            },
        },
    },
    items: {
        small_key: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.item.small_key"),
        },
        big_key: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.item.big_key"),
        },
        big_sword: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.endless_h.item.big_sword"),
        },
    },
    achievements: Object.fromEntries(["eh_door", "eh_sword", "eh_hall"].map((id) => [
        id,
        {
            name: `jig_ccomp:text-adventure.endless_h.achievement.${id}.name`,
            description: `jig_ccomp:text-adventure.endless_h.achievement.${id}.description`,
            hint: `jig_ccomp:text-adventure.endless_h.achievement.${id}.hint`,
            icon: `textures/jig/ccomp/items/art/${id}.png`,
            item: `jig_ccomp:poster_${id}`,
            print_title: "",
            print_content: "",
        },
    ])),
});

// --- Adventure Game: Case of the Missing Mob ---
const CHECK_ALL_SIDE_DONE = [
    {
        if: {
            condition: ALL(IS_VALUE("side.cir.1", true), IS_VALUE("side.cir.2", true), IS_VALUE("side.cir.3", true), IS_VALUE("side.cav.1", true), IS_VALUE("side.cav.2", true), IS_VALUE("side.cav.3", true), IS_VALUE("side.far.1", true), IS_VALUE("side.far.2", true), IS_VALUE("side.far.3", true), IS_VALUE("side.for.1", true), IS_VALUE("side.for.2", true), IS_VALUE("side.for.3", true), IS_VALUE("side.lak.1", true), IS_VALUE("side.lak.2", true), IS_VALUE("side.lak.3", true), IS_VALUE("side.min.1", true), IS_VALUE("side.min.2", true), IS_VALUE("side.min.3", true), IS_VALUE("side.fac.1", true), IS_VALUE("side.fac.2", true), IS_VALUE("side.fac.3", true)),
            actions: [EARN_ACHIEVEMENT("complete_f")],
        },
    },
];
const CHECK_ALL_SIDE_NOT_DONE = [
    {
        if: {
            condition: ALL(IS_NOT_VALUE("side.cir.1", true), IS_NOT_VALUE("side.cir.2", true), IS_NOT_VALUE("side.cir.3", true), IS_NOT_VALUE("side.cav.1", true), IS_NOT_VALUE("side.cav.2", true), IS_NOT_VALUE("side.cav.3", true), IS_NOT_VALUE("side.far.1", true), IS_NOT_VALUE("side.far.2", true), IS_NOT_VALUE("side.far.3", true), IS_NOT_VALUE("side.for.1", true), IS_NOT_VALUE("side.for.2", true), IS_NOT_VALUE("side.for.3", true), IS_NOT_VALUE("side.lak.1", true), IS_NOT_VALUE("side.lak.2", true), IS_NOT_VALUE("side.lak.3", true), IS_NOT_VALUE("side.min.1", true), IS_NOT_VALUE("side.min.2", true), IS_NOT_VALUE("side.min.3", true), IS_NOT_VALUE("side.fac.1", true), IS_NOT_VALUE("side.fac.2", true), IS_NOT_VALUE("side.fac.3", true)),
            actions: [EARN_ACHIEVEMENT("complete_s")],
        },
    },
];
const EXIT_TO_CIRCUS = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.exit.walk_to_circus", "\n"),
});
const EXIT_TO_FARM_B = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.exit.walk_to_farm_b", "\n"),
});
const EXIT_TO_FARM = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.exit.walk_to_farm", "\n"),
});
const EXIT_TO_FOREST = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.exit.walk_to_forest", "\n"),
});
const EXIT_TO_MINESHAFT = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.exit.walk_to_mineshaft", "\n"),
});
const EXIT_TO_CAVE = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.exit.walk_to_cave", "\n"),
});
const EXIT_TO_LAKE = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.exit.walk_to_lake", "\n"),
});
const EXIT_TO_FACTORY = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.exit.walk_to_factory", "\n"),
});
const newCaseOfTheJugAdventureState = () => ({
    version: 1,
    inventory: [{ id: "player_health", count: 10 }],
    status: "playing",
    props: {
        "dev.story_progress": 0,
    },
    nextPrompt: [TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.introduction", "\n")],
    currentRoom: "OFFICE",
});
const newCaseOfTheJugAdventure = () => makeTextAdventure({
    overrides: {
        ui: {
            status: {
                title: "jig_ccomp:caseofthejug.title",
            },
        },
    },
    rooms: {
        OFFICE: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.room.introduction", "\n"),
            targets: {
                investigate: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.targets.office_investigate", "\n"),
                    actions: [
                        {
                            if: {
                                condition: IS_VALUE("story_progress", 2),
                                actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.story.1b"))],
                                hidden: true,
                            },
                        },
                        {
                            if: {
                                condition: IS_VALUE("story_progress", 1),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.story.1a")),
                                    SET_VALUE("story_progress", 2),
                                ],
                                hidden: true,
                            },
                        },
                        {
                            if: {
                                condition: IS_VALUE("story_progress", 0),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.story.0")),
                                    INCREMENT_VALUE("story_progress"),
                                ],
                            },
                        },
                    ],
                    type: "use",
                },
            },
            exits: {
                go_to_circus: { ...EXIT_TO_CIRCUS, room: "CIRCUS", filter: ANY(IS_VALUE("story_progress", 2)) },
            },
        },
        CIRCUS: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.room.circus", "\n"),
            targets: {
                interact: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.targets.case_circus_master", "\n"),
                    actions: [
                        ROLL_AND_SET(3, "side_story_roll"),
                        SET_VALUE("story_beat_occurred", false),
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_VALUE("story_progress", 11)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.story.11")),
                                    INCREMENT_VALUE("story_progress"),
                                    SET_VALUE("story_beat_occurred", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_VALUE("story_progress", 2)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.story.2")),
                                    INCREMENT_VALUE("story_progress"),
                                    SET_VALUE("story_beat_occurred", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_VALUE("story_progress", 4)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.story.4")),
                                    INCREMENT_VALUE("story_progress"),
                                    SET_VALUE("story_beat_occurred", true),
                                    REMOVE_ITEM("item_hay"),
                                    GET_ITEM("item_pickaxe"),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 4), IS_VALUE("side_story_roll", 1)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.circus.1", "\n")),
                                    SET_VALUE("side.cir.1", true),
                                    SET_VALUE("story_beat_occurred", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 4), IS_VALUE("side_story_roll", 2)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.circus.2", "\n")),
                                    SET_VALUE("side.cir.2", true),
                                    SET_VALUE("story_beat_occurred", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 4), IS_VALUE("side_story_roll", 3)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.circus.3", "\n")),
                                    SET_VALUE("side.cir.3", true),
                                    SET_VALUE("story_beat_occurred", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(HAS_ITEM("player_health", 100)),
                                actions: [
                                    EARN_ACHIEVEMENT("health_h")
                                ],
                            },
                        },
                    ],
                    type: "look",
                },
            },
            exits: {
                walk_to_cave: { ...EXIT_TO_CAVE, room: "CAVE" },
                walk_to_factory: {
                    ...EXIT_TO_FACTORY,
                    room: "FACTORY",
                    filter: ANY(IS_VALUE("story_progress", 7), IS_VALUE("story_progress", 8), IS_VALUE("story_progress", 9), IS_VALUE("story_progress", 10)),
                },
                walk_to_farm: {
                    ...EXIT_TO_FARM,
                    room: "FARM",
                    filter: ANY(IS_VALUE("story_progress", 1), IS_VALUE("story_progress", 2), IS_VALUE("story_progress", 3), IS_VALUE("story_progress", 4), IS_VALUE("story_progress", 5), IS_VALUE("story_progress", 6), IS_VALUE("story_progress", 7), IS_VALUE("story_progress", 8), IS_VALUE("story_progress", 9)),
                },
                walk_to_farm_b: { ...EXIT_TO_FARM_B, room: "FARM_B", filter: IS_VALUE("story_progress", 10) },
                walk_to_forest: { ...EXIT_TO_FOREST, room: "FOREST" },
                walk_to_lake: { ...EXIT_TO_LAKE, room: "LAKE" },
                walk_to_mineshaft: { ...EXIT_TO_MINESHAFT, room: "MINESHAFT" },
            },
        },
        CIRCUS_B: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.room.circus_b", "\n"),
            targets: {
                interact: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.targets.case_circus_master", "\n"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.story.11")),
                        INCREMENT_VALUE("story_progress"),
                        SET_VALUE("npc_health_juggler", 10),
                        CHANGE_LOCATION("JUGGLER"),
                    ],
                },
            },
            exits: {},
        },
        CIRCUS_C: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.room.circus_c", "\n"),
            targets: {
                interact: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.targets.case_circus_master", "\n"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.story.12")),
                        EARN_ACHIEVEMENT("complete"),
                        ...CHECK_ALL_SIDE_DONE,
                        ...CHECK_ALL_SIDE_NOT_DONE,
                        WON("Case of the Juggler's Balls", "{0} beat up the Juggler and took his balls!", "player"),
                    ],
                },
            },
            exits: {},
        },
        FARM: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.room.farm", "\n"),
            targets: {
                interact: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.targets.case_farm", "\n"),
                    actions: [
                        ROLL_AND_SET(3, "side_story_roll"),
                        SET_VALUE("story_beat_occurred", false),
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_VALUE("story_progress", 3)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.story.3")),
                                    INCREMENT_VALUE("story_progress"),
                                    SET_VALUE("story_beat_occurred", true),
                                    GET_ITEM("item_hay"),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_VALUE("story_progress", 10)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.story.10")),
                                    INCREMENT_VALUE("story_progress"),
                                    SET_VALUE("story_beat_occurred", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 10), IS_VALUE("side_story_roll", 1)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.farm.1", "\n")),
                                    SET_VALUE("side.far.1", true),
                                    SET_VALUE("story_beat_occurred", true),
                                    REMOVE_ITEMS("player_health", 1),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 10), IS_VALUE("side_story_roll", 2)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.farm.2", "\n")),
                                    SET_VALUE("side.far.2", true),
                                    SET_VALUE("story_beat_occurred", true),
                                    GET_ITEM("player_health", 3),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 10), IS_VALUE("side_story_roll", 3)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.farm.3", "\n")),
                                    SET_VALUE("side.far.3", true),
                                    SET_VALUE("story_beat_occurred", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(HAS_ITEM("player_health", 100)),
                                actions: [
                                    EARN_ACHIEVEMENT("health_h")
                                ],
                            },
                        },
                    ],
                    type: "look",
                },
            },
            exits: {
                walk_to_circus: { ...EXIT_TO_CIRCUS, room: "CIRCUS" },
                walk_to_cave: { ...EXIT_TO_CAVE, room: "CAVE" },
                walk_to_factory: {
                    ...EXIT_TO_FACTORY,
                    room: "FACTORY",
                    filter: ANY(IS_VALUE("story_progress", 7), IS_VALUE("story_progress", 8), IS_VALUE("story_progress", 9), IS_VALUE("story_progress", 10)),
                },
                walk_to_forest: { ...EXIT_TO_FOREST, room: "FOREST" },
                walk_to_lake: { ...EXIT_TO_LAKE, room: "LAKE" },
                walk_to_mineshaft: { ...EXIT_TO_MINESHAFT, room: "MINESHAFT" },
            },
        },
        FARM_B: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.room.farm_b", "\n"),
            targets: {
                interact: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.targets.case_farm_b", "\n"),
                    actions: [
                        ROLL_AND_SET(3, "side_story_roll"),
                        SET_VALUE("story_beat_occurred", false),
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_VALUE("story_progress", 10)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.story.10")),
                                    INCREMENT_VALUE("story_progress"),
                                    SET_VALUE("story_beat_occurred", true),
                                    CHANGE_LOCATION("CIRCUS_B"),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(HAS_ITEM("player_health", 100)),
                                actions: [
                                    EARN_ACHIEVEMENT("health_h")
                                ],
                            },
                        },
                    ],
                    type: "look",
                },
            },
            exits: {
                walk_to_circus: { ...EXIT_TO_CIRCUS, room: "CIRCUS" },
                walk_to_cave: { ...EXIT_TO_CAVE, room: "CAVE" },
                walk_to_factory: {
                    ...EXIT_TO_FACTORY,
                    room: "FACTORY",
                    filter: ANY(IS_VALUE("story_progress", 7), IS_VALUE("story_progress", 8), IS_VALUE("story_progress", 9), IS_VALUE("story_progress", 10)),
                },
                walk_to_forest: { ...EXIT_TO_FOREST, room: "FOREST" },
                walk_to_lake: { ...EXIT_TO_LAKE, room: "LAKE" },
                walk_to_mineshaft: { ...EXIT_TO_MINESHAFT, room: "MINESHAFT" },
            },
        },
        FOREST: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.room.forest", "\n"),
            targets: {
                interact: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.targets.case_forest", "\n"),
                    actions: [
                        ROLL_AND_SET(3, "side_story_roll"),
                        SET_VALUE("story_beat_occurred", false),
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_VALUE("story_progress", 6)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.story.6")),
                                    INCREMENT_VALUE("story_progress"),
                                    SET_VALUE("story_beat_occurred", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 6), IS_VALUE("side_story_roll", 1)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.forest.1", "\n")),
                                    SET_VALUE("side.for.1", true),
                                    SET_VALUE("story_beat_occurred", true),
                                    GET_ITEM("player_health", 1),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 6), IS_VALUE("side_story_roll", 2)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.forest.2", "\n")),
                                    SET_VALUE("side.for.2", true),
                                    SET_VALUE("story_beat_occurred", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 6), IS_VALUE("side_story_roll", 3)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.forest.3", "\n")),
                                    SET_VALUE("side.for.3", true),
                                    SET_VALUE("story_beat_occurred", true),
                                    SET_VALUE("npc_health_zombie", 3),
                                    CHANGE_LOCATION("ZOMBIE"),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(HAS_ITEM("player_health", 100)),
                                actions: [
                                    EARN_ACHIEVEMENT("health_h")
                                ],
                            },
                        },
                    ],
                    type: "look",
                },
            },
            exits: {
                walk_to_circus: { ...EXIT_TO_CIRCUS, room: "CIRCUS" },
                walk_to_cave: { ...EXIT_TO_CAVE, room: "CAVE" },
                walk_to_factory: {
                    ...EXIT_TO_FACTORY,
                    room: "FACTORY",
                    filter: ANY(IS_VALUE("story_progress", 7), IS_VALUE("story_progress", 8), IS_VALUE("story_progress", 9), IS_VALUE("story_progress", 10)),
                },
                walk_to_farm: {
                    ...EXIT_TO_FARM,
                    room: "FARM",
                    filter: ANY(IS_VALUE("story_progress", 1), IS_VALUE("story_progress", 2), IS_VALUE("story_progress", 3), IS_VALUE("story_progress", 4), IS_VALUE("story_progress", 5), IS_VALUE("story_progress", 6), IS_VALUE("story_progress", 7), IS_VALUE("story_progress", 8), IS_VALUE("story_progress", 9)),
                },
                walk_to_farm_b: { ...EXIT_TO_FARM_B, room: "FARM_B", filter: IS_VALUE("story_progress", 10) },
                walk_to_lake: { ...EXIT_TO_LAKE, room: "LAKE" },
                walk_to_mineshaft: { ...EXIT_TO_MINESHAFT, room: "MINESHAFT" },
            },
        },
        MINESHAFT: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.room.mineshaft", "\n"),
            targets: {
                interact: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.targets.case_mineshaft", "\n"),
                    actions: [
                        ROLL_AND_SET(3, "side_story_roll"),
                        SET_VALUE("story_beat_occurred", false),
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_VALUE("story_progress", 5)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.story.5")),
                                    INCREMENT_VALUE("story_progress"),
                                    SET_VALUE("story_beat_occurred", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 5), IS_VALUE("side_story_roll", 1)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.mineshaft.1", "\n")),
                                    SET_VALUE("side.min.1", true),
                                    SET_VALUE("story_beat_occurred", true),
                                    SET_VALUE("npc_health_silver", 1),
                                    CHANGE_LOCATION("SILVER"),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 5), IS_VALUE("side_story_roll", 2)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.mineshaft.2", "\n")),
                                    SET_VALUE("side.min.2", true),
                                    SET_VALUE("story_beat_occurred", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 5), IS_VALUE("side_story_roll", 3)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.mineshaft.3", "\n")),
                                    SET_VALUE("side.min.3", true),
                                    SET_VALUE("story_beat_occurred", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(HAS_ITEM("player_health", 100)),
                                actions: [
                                    EARN_ACHIEVEMENT("health_h")
                                ],
                            },
                        },
                    ],
                    type: "look",
                },
            },
            exits: {
                walk_to_circus: { ...EXIT_TO_CIRCUS, room: "CIRCUS" },
                walk_to_cave: { ...EXIT_TO_CAVE, room: "CAVE" },
                walk_to_factory: {
                    ...EXIT_TO_FACTORY,
                    room: "FACTORY",
                    filter: ANY(IS_VALUE("story_progress", 7), IS_VALUE("story_progress", 8), IS_VALUE("story_progress", 9), IS_VALUE("story_progress", 10)),
                },
                walk_to_farm: {
                    ...EXIT_TO_FARM,
                    room: "FARM",
                    filter: ANY(IS_VALUE("story_progress", 1), IS_VALUE("story_progress", 2), IS_VALUE("story_progress", 3), IS_VALUE("story_progress", 4), IS_VALUE("story_progress", 5), IS_VALUE("story_progress", 6), IS_VALUE("story_progress", 7), IS_VALUE("story_progress", 8), IS_VALUE("story_progress", 9)),
                },
                walk_to_farm_b: { ...EXIT_TO_FARM_B, room: "FARM_B", filter: IS_VALUE("story_progress", 10) },
                walk_to_forest: { ...EXIT_TO_FOREST, room: "FOREST" },
                walk_to_lake: { ...EXIT_TO_LAKE, room: "LAKE" },
            },
        },
        CAVE: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.room.cave", "\n"),
            targets: {
                interact: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.targets.case_cave", "\n"),
                    actions: [
                        ROLL_AND_SET(3, "side_story_roll"),
                        SET_VALUE("story_beat_occurred", false),
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_VALUE("story_progress", 9)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.story.9")),
                                    INCREMENT_VALUE("story_progress"),
                                    SET_VALUE("story_beat_occurred", true),
                                    REMOVE_ITEM("item_pickaxe"),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 9), IS_VALUE("side_story_roll", 1)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.cave.1", "\n")),
                                    SET_VALUE("side.cav.1", true),
                                    SET_VALUE("story_beat_occurred", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 9), IS_VALUE("side_story_roll", 2)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.cave.2", "\n")),
                                    SET_VALUE("side.cav.2", true),
                                    SET_VALUE("story_beat_occurred", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 9), IS_VALUE("side_story_roll", 3)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.cave.3", "\n")),
                                    SET_VALUE("side.cav.3", true),
                                    SET_VALUE("story_beat_occurred", true),
                                    SET_VALUE("npc_health_spider", 2),
                                    CHANGE_LOCATION("SPIDER"),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(HAS_ITEM("player_health", 100)),
                                actions: [
                                    EARN_ACHIEVEMENT("health_h")
                                ],
                            },
                        },
                    ],
                    type: "look",
                },
            },
            exits: {
                walk_to_circus: { ...EXIT_TO_CIRCUS, room: "CIRCUS" },
                walk_to_factory: {
                    ...EXIT_TO_FACTORY,
                    room: "FACTORY",
                    filter: ANY(IS_VALUE("story_progress", 7), IS_VALUE("story_progress", 8), IS_VALUE("story_progress", 9), IS_VALUE("story_progress", 10)),
                },
                walk_to_farm: {
                    ...EXIT_TO_FARM,
                    room: "FARM",
                    filter: ANY(IS_VALUE("story_progress", 1), IS_VALUE("story_progress", 2), IS_VALUE("story_progress", 3), IS_VALUE("story_progress", 4), IS_VALUE("story_progress", 5), IS_VALUE("story_progress", 6), IS_VALUE("story_progress", 7), IS_VALUE("story_progress", 8), IS_VALUE("story_progress", 9)),
                },
                walk_to_farm_b: { ...EXIT_TO_FARM_B, room: "FARM_B", filter: IS_VALUE("story_progress", 10) },
                walk_to_forest: { ...EXIT_TO_FOREST, room: "FOREST" },
                walk_to_lake: { ...EXIT_TO_LAKE, room: "LAKE" },
                walk_to_mineshaft: { ...EXIT_TO_MINESHAFT, room: "MINESHAFT" },
            },
        },
        LAKE: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.room.lake", "\n"),
            targets: {
                interact: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.targets.case_lake", "\n"),
                    actions: [
                        ROLL_AND_SET(3, "side_story_roll"),
                        SET_VALUE("story_beat_occurred", false),
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("got_arms_once", true), ANY(IS_VALUE("story_progress", 9), IS_VALUE("story_progress", 10))),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.story.8")),
                                    SET_VALUE("story_beat_occurred", true),
                                    SET_VALUE("got_arms_once", true),
                                    GET_ITEM("item_robot"),
                                    EARN_ACHIEVEMENT("robot_arms"),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_VALUE("side_story_roll", 1)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.lake.1", "\n")),
                                    SET_VALUE("side.lak.1", true),
                                    SET_VALUE("story_beat_occurred", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_VALUE("side_story_roll", 2), IS_NOT_VALUE("stone_skipped", true)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.lake.2", "\n")),
                                    SET_VALUE("story_beat_occurred", true),
                                    SET_VALUE("stone_skipped", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_VALUE("side_story_roll", 3)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.lake.3", "\n")),
                                    SET_VALUE("side.lak.3", true),
                                    SET_VALUE("story_beat_occurred", true),
                                    GET_ITEM("player_health"),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_VALUE("side_story_roll", 2), IS_VALUE("stone_skipped", true)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.lake.4", "\n")),
                                    SET_VALUE("side.lak.2", true),
                                    SET_VALUE("story_beat_occurred", true),
                                    SET_VALUE("npc_health_drowned", 3),
                                    CHANGE_LOCATION("DROWNED"),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(HAS_ITEM("player_health", 100)),
                                actions: [
                                    EARN_ACHIEVEMENT("health_h")
                                ],
                            },
                        },
                    ],
                    type: "look",
                },
            },
            exits: {
                walk_to_circus: { ...EXIT_TO_CIRCUS, room: "CIRCUS" },
                walk_to_cave: { ...EXIT_TO_CAVE, room: "CAVE" },
                walk_to_factory: {
                    ...EXIT_TO_FACTORY,
                    room: "FACTORY",
                    filter: ANY(IS_VALUE("story_progress", 7), IS_VALUE("story_progress", 8), IS_VALUE("story_progress", 9), IS_VALUE("story_progress", 10)),
                },
                walk_to_farm: {
                    ...EXIT_TO_FARM,
                    room: "FARM",
                    filter: ANY(IS_VALUE("story_progress", 1), IS_VALUE("story_progress", 2), IS_VALUE("story_progress", 3), IS_VALUE("story_progress", 4), IS_VALUE("story_progress", 5), IS_VALUE("story_progress", 6), IS_VALUE("story_progress", 7), IS_VALUE("story_progress", 8), IS_VALUE("story_progress", 9)),
                },
                walk_to_farm_b: { ...EXIT_TO_FARM_B, room: "FARM_B", filter: IS_VALUE("story_progress", 10) },
                walk_to_forest: { ...EXIT_TO_FOREST, room: "FOREST" },
                walk_to_mineshaft: { ...EXIT_TO_MINESHAFT, room: "MINESHAFT" },
            },
        },
        FACTORY: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.room.factory", "\n"),
            targets: {
                interact: {
                    description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.targets.case_factory", "\n"),
                    actions: [
                        ROLL_AND_SET(3, "side_story_roll"),
                        SET_VALUE("story_beat_occurred", false),
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_VALUE("story_progress", 7)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.story.7")),
                                    SET_VALUE("story_beat_occurred", true),
                                    SET_VALUE("story_progress", 9),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 7), IS_VALUE("side_story_roll", 1)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.factory.1", "\n")),
                                    SET_VALUE("side.fac.1", true),
                                    SET_VALUE("story_beat_occurred", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 7), IS_VALUE("side_story_roll", 2)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.factory.2", "\n")),
                                    SET_VALUE("side.fac.2", true),
                                    SET_VALUE("story_beat_occurred", true),
                                    REMOVE_ITEMS("player_health", 1),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(IS_VALUE("story_beat_occurred", false), IS_NOT_VALUE("story_progress", 7), IS_VALUE("side_story_roll", 3)),
                                actions: [
                                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.side_story.factory.3", "\n")),
                                    SET_VALUE("side.fac.2", true),
                                    SET_VALUE("story_beat_occurred", true),
                                ],
                            },
                        },
                        {
                            if: {
                                condition: ALL(HAS_ITEM("player_health", 100)),
                                actions: [
                                    EARN_ACHIEVEMENT("health_h")
                                ],
                            },
                        },
                    ],
                    type: "look",
                },
            },
            exits: {
                walk_to_circus: { ...EXIT_TO_CIRCUS, room: "CIRCUS" },
                walk_to_cave: { ...EXIT_TO_CAVE, room: "CAVE" },
                walk_to_farm: {
                    ...EXIT_TO_FARM,
                    room: "FARM",
                    filter: ANY(IS_VALUE("story_progress", 1), IS_VALUE("story_progress", 2), IS_VALUE("story_progress", 3), IS_VALUE("story_progress", 4), IS_VALUE("story_progress", 5), IS_VALUE("story_progress", 6), IS_VALUE("story_progress", 7), IS_VALUE("story_progress", 8), IS_VALUE("story_progress", 9)),
                },
                walk_to_farm_b: { ...EXIT_TO_FARM_B, room: "FARM_B", filter: IS_VALUE("story_progress", 10) },
                walk_to_forest: { ...EXIT_TO_FOREST, room: "FOREST" },
                walk_to_lake: { ...EXIT_TO_LAKE, room: "LAKE" },
                walk_to_mineshaft: { ...EXIT_TO_MINESHAFT, room: "MINESHAFT" },
            },
        },
        ZOMBIE: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.room.zombie", "\n"),
            targets: {
                attack: makeAttackTarget("npc_health_zombie", "zombie", "FOREST"),
                recover: makeRecoverTarget("npc_health_zombie", "zombie"),
                super: {
                    ...makeSuperTarget("npc_health_zombie", "zombie", "FOREST"),
                    filter: HAS_ITEMS("item_robot"),
                },
            },
            exits: {},
        },
        SILVER: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.room.silver", "\n"),
            targets: {
                attack: makeAttackTarget("npc_health_silver", "silver", "MINESHAFT"),
                recover: makeRecoverTarget("npc_health_silver", "silver"),
                super: {
                    ...makeSuperTarget("npc_health_silver", "silver", "MINESHAFT"),
                    filter: HAS_ITEMS("item_robot"),
                },
            },
            exits: {},
        },
        SPIDER: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.room.spider", "\n"),
            targets: {
                attack: makeAttackTarget("npc_health_spider", "spider", "CAVE"),
                recover: makeRecoverTarget("npc_health_spider", "spider"),
                super: {
                    ...makeSuperTarget("npc_health_spider", "spider", "CAVE"),
                    filter: HAS_ITEMS("item_robot"),
                },
            },
            exits: {},
        },
        DROWNED: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.room.drowned", "\n"),
            targets: {
                attack: makeAttackTarget("npc_health_drowned", "drowned", "LAKE"),
                recover: makeRecoverTarget("npc_health_drowned", "drowned"),
                super: {
                    ...makeSuperTarget("npc_health_drowned", "drowned", "LAKE"),
                    filter: HAS_ITEMS("item_robot"),
                },
            },
            exits: {},
        },
        JUGGLER: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.room.juggler", "\n"),
            targets: {
                attack: makeAttackTarget("npc_health_juggler", "juggler", "CIRCUS_C"),
                recover: makeRecoverTarget("npc_health_juggler", "juggler"),
                super: {
                    ...makeSuperTarget("npc_health_juggler", "juggler", "CIRCUS_C"),
                    filter: HAS_ITEMS("item_robot"),
                },
            },
            exits: {},
        },
    },
    items: {
        player_health: { description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.item.health") },
        item_pickaxe: { description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.item.pickaxe") },
        item_hay: { description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.item.hay") },
        item_robot: { description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.item.robot") },
    },
    achievements: Object.fromEntries(["complete", "complete_f", "complete_s", "kill_all", "robot_arms", "health_h"].map((id) => [
        id,
        {
            name: `jig_ccomp:text-adventure.caseofthejug.achievement.${id}.name`,
            description: `jig_ccomp:text-adventure.caseofthejug.achievement.${id}.description`,
            hint: `jig_ccomp:text-adventure.caseofthejug.achievement.${id}.hint`,
            icon: `textures/jig/ccomp/items/art/jb_${id}.png`,
            item: `jig_ccomp:poster_jb_${id}`,
            print_title: "",
            print_content: "",
        },
    ])),
});
const NPC_ROLL_RANGE = {
    zombie: 2, // Attacks and Idles half the time
    silver: 5, // High dodge rate (4/5 chance to defend)
    spider: 2, // 50/50
    drowned: 3, // 2/3 attack, 1/3 dodge
    juggler: 6, // 3 attack, 2 idle, 1 dodge
};
const NPC_ROLL_BEHAVIOR = {
    zombie: {
        attack: [1],
        defend: [],
        idle: [2],
    },
    silver: {
        attack: [1],
        defend: [2, 3, 4, 5],
        idle: [],
    },
    spider: {
        attack: [1],
        defend: [2],
        idle: [],
    },
    drowned: {
        attack: [1, 2],
        defend: [3],
        idle: [],
    },
    juggler: {
        attack: [1, 2, 3],
        defend: [6],
        idle: [4, 5],
    },
};
const matchRolls = (key, values) => ANY(...values.map((v) => IS_VALUE(key, v)));
const makeAttackTarget = (npcHealthKey, outcomeKeyPrefix, locationReturn) => makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.targets.attack", "\n"),
    actions: [
        SET_VALUE("player_action", "attack"),
        ROLL_AND_SET(NPC_ROLL_RANGE[outcomeKeyPrefix], "npc_roll"),
        // ATTACK
        {
            if: {
                condition: matchRolls("npc_roll", NPC_ROLL_BEHAVIOR[outcomeKeyPrefix].attack),
                actions: [
                    REMOVE_ITEMS("player_health", 3),
                    SAY(TRANSLATE$1(`jig_ccomp:text-adventure.case_juggle.outcome.${outcomeKeyPrefix}_attack_attack`, "\n")),
                    DEBUG_PROP(PROP_VARIABLE(npcHealthKey)),
                ],
            },
        },
        // DEFEND
        {
            if: {
                condition: matchRolls("npc_roll", NPC_ROLL_BEHAVIOR[outcomeKeyPrefix].defend),
                actions: [
                    INCREMENT_VALUE(npcHealthKey, -1),
                    SAY(TRANSLATE$1(`jig_ccomp:text-adventure.case_juggle.outcome.${outcomeKeyPrefix}_attack_defend`, "\n")),
                    DEBUG_PROP(PROP_VARIABLE(npcHealthKey)),
                ],
            },
        },
        // IDLE
        {
            if: {
                condition: matchRolls("npc_roll", NPC_ROLL_BEHAVIOR[outcomeKeyPrefix].idle),
                actions: [
                    INCREMENT_VALUE(npcHealthKey, -2),
                    SAY(TRANSLATE$1(`jig_ccomp:text-adventure.case_juggle.outcome.${outcomeKeyPrefix}_attack_idle`, "\n")),
                    DEBUG_PROP(PROP_VARIABLE(npcHealthKey)),
                ],
            },
        },
        // DEATH & WIN CONDITIONS
        {
            if: {
                condition: HAS_LESS_THAN_ITEMS("player_health", 1),
                actions: [DIE()],
            },
        },
        {
            if: {
                condition: ALL(HAS_ZERO_OR_LESS_VALUE(PROP_VARIABLE(npcHealthKey)), IS_NOT_VALUE("got_arms_once", true)),
                actions: [
                    SAY(TRANSLATE$1(`jig_ccomp:text-adventure.case_juggle.beat_${outcomeKeyPrefix}`, "\n")),
                    SET_VALUE(`killed.${outcomeKeyPrefix}`, true),
                    CHANGE_LOCATION(locationReturn),
                ],
            },
        },
        {
            if: {
                condition: ALL(HAS_ZERO_OR_LESS_VALUE(PROP_VARIABLE(npcHealthKey)), IS_VALUE("got_arms_once", true), HAS_ITEM("item_robot", 1)),
                actions: [
                    SAY(TRANSLATE$1(`jig_ccomp:text-adventure.case_juggle.beat_${outcomeKeyPrefix}`, "\n")),
                    SET_VALUE(`killed.${outcomeKeyPrefix}`, true),
                    CHANGE_LOCATION(locationReturn),
                ],
            },
        },
        {
            if: {
                condition: ALL(HAS_ZERO_OR_LESS_VALUE(PROP_VARIABLE(npcHealthKey)), IS_VALUE("got_arms_once", true), doesNotHaveItems("item_robot")),
                actions: [
                    SAY(TRANSLATE$1(`jig_ccomp:text-adventure.case_juggle.beat_${outcomeKeyPrefix}`, "\n")),
                    GET_ITEM("item_robot", 1),
                    SET_VALUE(`killed.${outcomeKeyPrefix}`, true),
                    CHANGE_LOCATION(locationReturn),
                ],
            },
        },
        {
            if: {
                condition: ALL(IS_VALUE("killed.zombie", true), IS_VALUE("killed.spider", true), IS_VALUE("killed.silver", true), IS_VALUE("killed.drowned", true)),
                actions: [EARN_ACHIEVEMENT("kill_all")],
            },
        },
    ],
    type: "attack",
});
const makeRecoverTarget = (npcHealthKey, outcomeKeyPrefix, locationReturn) => makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.targets.recover", "\n"),
    actions: [
        SET_VALUE("player_action", "recover"),
        ROLL_AND_SET(NPC_ROLL_RANGE[outcomeKeyPrefix], "npc_roll"),
        {
            if: {
                condition: matchRolls("npc_roll", NPC_ROLL_BEHAVIOR[outcomeKeyPrefix].attack),
                actions: [
                    REMOVE_ITEMS("player_health", 1),
                    SAY(TRANSLATE$1(`jig_ccomp:text-adventure.case_juggle.outcome.${outcomeKeyPrefix}_recover_attack`, "\n")),
                    DEBUG_PROP(PROP_VARIABLE(npcHealthKey)),
                ],
            },
        },
        {
            if: {
                condition: matchRolls("npc_roll", NPC_ROLL_BEHAVIOR[outcomeKeyPrefix].defend),
                actions: [
                    GET_ITEM("player_health", 3),
                    SAY(TRANSLATE$1(`jig_ccomp:text-adventure.case_juggle.outcome.${outcomeKeyPrefix}_recover_defend`, "\n")),
                    DEBUG_PROP(PROP_VARIABLE(npcHealthKey)),
                ],
            },
        },
        {
            if: {
                condition: matchRolls("npc_roll", NPC_ROLL_BEHAVIOR[outcomeKeyPrefix].idle),
                actions: [
                    GET_ITEM("player_health", 3),
                    SAY(TRANSLATE$1(`jig_ccomp:text-adventure.case_juggle.outcome.${outcomeKeyPrefix}_recover_idle`, "\n")),
                ],
            },
        },
        {
            if: {
                condition: matchRolls("npc_roll", NPC_ROLL_BEHAVIOR[outcomeKeyPrefix].idle),
                actions: [
                    GET_ITEM("player_health", 3),
                    SAY(TRANSLATE$1(`jig_ccomp:text-adventure.case_juggle.outcome.${outcomeKeyPrefix}_recover_idle`, "\n")),
                ],
            },
        },
        {
            if: {
                condition: HAS_LESS_THAN_ITEMS("player_health", 1),
                actions: [DIE()],
            },
        },
        {
            if: {
                condition: ALL(HAS_ITEM("player_health", 100)),
                actions: [
                    EARN_ACHIEVEMENT("health_h")
                ],
            },
        },
    ],
});
const makeSuperTarget = (npcHealthKey, outcomeKeyPrefix, locationReturn) => makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.case_juggle.targets.super", "\n"),
    actions: [
        SET_VALUE("player_action", "attack"),
        ROLL_AND_SET(NPC_ROLL_RANGE[outcomeKeyPrefix], "npc_roll"),
        {
            if: {
                condition: matchRolls("npc_roll", NPC_ROLL_BEHAVIOR[outcomeKeyPrefix].attack),
                actions: [
                    REMOVE_ITEMS("player_health", 20),
                    REMOVE_ITEMS("item_robot", 1),
                    SAY(TRANSLATE$1(`jig_ccomp:text-adventure.case_juggle.outcome.${outcomeKeyPrefix}_super_attack`, "\n")),
                    DEBUG_PROP(PROP_VARIABLE(npcHealthKey)),
                ],
            },
        },
        {
            if: {
                condition: matchRolls("npc_roll", NPC_ROLL_BEHAVIOR[outcomeKeyPrefix].defend),
                actions: [
                    INCREMENT_VALUE(npcHealthKey, -20),
                    REMOVE_ITEMS("item_robot", 1),
                    SAY(TRANSLATE$1(`jig_ccomp:text-adventure.case_juggle.outcome.${outcomeKeyPrefix}_super_defend`, "\n")),
                    DEBUG_PROP(PROP_VARIABLE(npcHealthKey)),
                ],
            },
        },
        {
            if: {
                condition: matchRolls("npc_roll", NPC_ROLL_BEHAVIOR[outcomeKeyPrefix].idle),
                actions: [
                    INCREMENT_VALUE(npcHealthKey, -20),
                    REMOVE_ITEMS("item_robot", 1),
                    SAY(TRANSLATE$1(`jig_ccomp:text-adventure.case_juggle.outcome.${outcomeKeyPrefix}_super_idle`, "\n")),
                ],
            },
        },
        {
            if: {
                condition: HAS_LESS_THAN_ITEMS("player_health", 1),
                actions: [DIE()],
            },
        },
        {
            if: {
                condition: ALL(HAS_ZERO_OR_LESS_VALUE(PROP_VARIABLE(npcHealthKey)), IS_NOT_VALUE("got_arms_once", true)),
                actions: [
                    SAY(TRANSLATE$1(`jig_ccomp:text-adventure.case_juggle.beat_${outcomeKeyPrefix}`, "\n")),
                    SET_VALUE(`killed.${outcomeKeyPrefix}`, true),
                    CHANGE_LOCATION(locationReturn),
                ],
            },
        },
        {
            if: {
                condition: ALL(HAS_ZERO_OR_LESS_VALUE(PROP_VARIABLE(npcHealthKey)), IS_VALUE("got_arms_once", true), HAS_ITEM("item_robot", 1)),
                actions: [
                    SAY(TRANSLATE$1(`jig_ccomp:text-adventure.case_juggle.beat_${outcomeKeyPrefix}`, "\n")),
                    SET_VALUE(`killed.${outcomeKeyPrefix}`, true),
                    CHANGE_LOCATION(locationReturn),
                ],
            },
        },
        {
            if: {
                condition: ALL(HAS_ZERO_OR_LESS_VALUE(PROP_VARIABLE(npcHealthKey)), IS_VALUE("got_arms_once", true), doesNotHaveItems("item_robot")),
                actions: [
                    SAY(TRANSLATE$1(`jig_ccomp:text-adventure.case_juggle.beat_${outcomeKeyPrefix}`, "\n")),
                    GET_ITEM("item_robot", 1),
                    SET_VALUE(`killed.${outcomeKeyPrefix}`, true),
                    CHANGE_LOCATION(locationReturn),
                ],
            },
        },
        {
            if: {
                condition: ALL(IS_VALUE("killed.zombie", true), IS_VALUE("killed.spider", true), IS_VALUE("killed.silver", true), IS_VALUE("killed.drowned", true)),
                actions: [EARN_ACHIEVEMENT("kill_all")],
            },
        },
    ],
    type: "attack",
});

const NORTH$1 = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.fridge.exit.kitchen_to_dining", "\n"),
});
const SOUTH$1 = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.fridge.exit.dining_to_kitchen", "\n"),
});
const FRIDGE = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.fridge", "\n"),
    actions: [
        ROLL_AND_SET(8, "fridge_roll"),
        {
            if: {
                condition: IS_VALUE("fridge_roll", 1),
                actions: [GET_ITEM("ingredient_bread"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.fridge.bread"))],
            },
        },
        {
            if: {
                condition: IS_VALUE("fridge_roll", 2),
                actions: [GET_ITEM("ingredient_cheese"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.fridge.cheese"))],
            },
        },
        {
            if: {
                condition: IS_VALUE("fridge_roll", 3),
                actions: [GET_ITEM("ingredient_fruit"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.fridge.fruit"))],
            },
        },
        {
            if: {
                condition: IS_VALUE("fridge_roll", 4),
                actions: [GET_ITEM("ingredient_meat"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.fridge.meat"))],
            },
        },
        {
            if: {
                condition: IS_VALUE("fridge_roll", 5),
                actions: [GET_ITEM("ingredient_egg"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.fridge.egg"))],
            },
        },
        {
            if: {
                condition: IS_VALUE("fridge_roll", 6),
                actions: [GET_ITEM("ingredient_lettuce"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.fridge.lettuce"))],
            },
        },
        {
            if: {
                condition: IS_VALUE("fridge_roll", 7),
                actions: [GET_ITEM("ingredient_tomato"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.fridge.tomato"))],
            },
        },
        {
            if: {
                condition: IS_VALUE("fridge_roll", 8),
                actions: [GET_ITEM("ingredient_milk"), SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.fridge.milk"))],
            },
        },
    ],
});
const COUNTER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.counter", "\n"),
    actions: [
        SET_VALUE("made_something", false),
        {
            if: {
                condition: hasItems("ingredient_bread", "ingredient_cheese", "ingredient_meat"),
                actions: [
                    REMOVE_ITEM("ingredient_bread"),
                    REMOVE_ITEM("ingredient_cheese"),
                    REMOVE_ITEM("ingredient_meat"),
                    GET_ITEM("food_sandwich"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.counter.sandwich", "\n")),
                    SET_VALUE("made_something", true),
                    INCREMENT_VALUE("meals_made"),
                ],
            },
        },
        {
            if: {
                condition: hasItems("ingredient_egg", "ingredient_bread", "ingredient_milk"),
                actions: [
                    REMOVE_ITEM("ingredient_egg"),
                    REMOVE_ITEM("ingredient_bread"),
                    REMOVE_ITEM("ingredient_milk"),
                    GET_ITEM("food_pancake"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.counter.pancake", "\n")),
                    SET_VALUE("made_something", true),
                    INCREMENT_VALUE("meals_made"),
                ],
            },
        },
        {
            if: {
                condition: hasItems("ingredient_meat", "ingredient_bread"),
                actions: [
                    REMOVE_ITEM("ingredient_meat"),
                    REMOVE_ITEM("ingredient_bread"),
                    GET_ITEM("food_burger"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.counter.burger", "\n")),
                    SET_VALUE("made_something", true),
                    INCREMENT_VALUE("meals_made"),
                ],
            },
        },
        {
            if: {
                condition: hasItems("ingredient_lettuce", "ingredient_tomato"),
                actions: [
                    REMOVE_ITEM("ingredient_lettuce"),
                    REMOVE_ITEM("ingredient_tomato"),
                    GET_ITEM("food_salad"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.counter.salad", "\n")),
                    SET_VALUE("made_something", true),
                    INCREMENT_VALUE("meals_made"),
                ],
            },
        },
        {
            if: {
                condition: hasItems("ingredient_egg", "ingredient_milk"),
                actions: [
                    REMOVE_ITEM("ingredient_egg"),
                    REMOVE_ITEM("ingredient_milk"),
                    GET_ITEM("food_omelette"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.counter.omelette", "\n")),
                    SET_VALUE("made_something", true),
                    INCREMENT_VALUE("meals_made"),
                ],
            },
        },
        {
            if: {
                condition: hasItems("ingredient_bread", "ingredient_milk"),
                actions: [
                    REMOVE_ITEM("ingredient_bread"),
                    REMOVE_ITEM("ingredient_milk"),
                    GET_ITEM("food_toast"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.counter.toast", "\n")),
                    SET_VALUE("made_something", true),
                    INCREMENT_VALUE("meals_made"),
                ],
            },
        },
        {
            if: {
                condition: hasItems("ingredient_fruit", "ingredient_milk"),
                actions: [
                    REMOVE_ITEM("ingredient_fruit"),
                    REMOVE_ITEM("ingredient_milk"),
                    GET_ITEM("food_milkshake"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.counter.milkshake", "\n")),
                    SET_VALUE("made_something", true),
                    INCREMENT_VALUE("meals_made"),
                ],
            },
        },
        {
            if: {
                condition: hasItems("ingredient_fruit"),
                actions: [
                    REMOVE_ITEM("ingredient_fruit"),
                    GET_ITEM("food_fruit_bowl"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.counter.fruit", "\n")),
                    SET_VALUE("made_something", true),
                    INCREMENT_VALUE("meals_made"),
                ],
            },
        },
        {
            if: {
                condition: IS_VALUE("made_something", false),
                actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.counter.no_items", "\n"))],
            },
        },
    ],
});
const DINER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.diner", "\n"),
    actions: [
        SET_VALUE("served_this_turn", false),
        {
            if: {
                condition: ALL(IS_VALUE("served_this_turn", false), hasItems("food_sandwich")),
                actions: [
                    REMOVE_ITEM("food_sandwich"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.diner.likes_sandwich", "\n")),
                    SET_VALUE("served_this_turn", true),
                    INCREMENT_VALUE("meals_served"), EARN_ACHIEVEMENT("f_sanga")
                ],
            },
        },
        {
            if: {
                condition: ALL(IS_VALUE("served_this_turn", false), hasItems("food_fruit_bowl")),
                actions: [
                    REMOVE_ITEM("food_fruit_bowl"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.diner.likes_fruit", "\n")),
                    SET_VALUE("served_this_turn", true),
                    INCREMENT_VALUE("meals_served"), EARN_ACHIEVEMENT("f_fruit")
                ],
            },
        },
        {
            if: {
                condition: ALL(IS_VALUE("served_this_turn", false), hasItems("food_burger")),
                actions: [
                    REMOVE_ITEM("food_burger"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.diner.likes_burger", "\n")),
                    SET_VALUE("served_this_turn", true),
                    INCREMENT_VALUE("meals_served"), EARN_ACHIEVEMENT("f_burger")
                ],
            },
        },
        {
            if: {
                condition: ALL(IS_VALUE("served_this_turn", false), hasItems("food_pancake")),
                actions: [
                    REMOVE_ITEM("food_pancake"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.diner.likes_pancake", "\n")),
                    SET_VALUE("served_this_turn", true),
                    INCREMENT_VALUE("meals_served"), EARN_ACHIEVEMENT("f_pancake")
                ],
            },
        },
        {
            if: {
                condition: ALL(IS_VALUE("served_this_turn", false), hasItems("food_salad")),
                actions: [
                    REMOVE_ITEM("food_salad"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.diner.likes_salad", "\n")),
                    SET_VALUE("served_this_turn", true),
                    INCREMENT_VALUE("meals_served"), EARN_ACHIEVEMENT("f_salad")
                ],
            },
        },
        {
            if: {
                condition: ALL(IS_VALUE("served_this_turn", false), hasItems("food_toast")),
                actions: [
                    REMOVE_ITEM("food_toast"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.diner.likes_toast", "\n")),
                    SET_VALUE("served_this_turn", true),
                    INCREMENT_VALUE("meals_served"), EARN_ACHIEVEMENT("f_toast")
                ],
            },
        },
        {
            if: {
                condition: ALL(IS_VALUE("served_this_turn", false), hasItems("food_milkshake")),
                actions: [
                    REMOVE_ITEM("food_milkshake"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.diner.likes_milkshake", "\n")),
                    SET_VALUE("served_this_turn", true),
                    INCREMENT_VALUE("meals_served"), EARN_ACHIEVEMENT("f_shake")
                ],
            },
        },
        {
            if: {
                condition: ALL(IS_VALUE("served_this_turn", false), hasItems("food_omelette")),
                actions: [
                    REMOVE_ITEM("food_omelette"),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.diner.likes_omelette", "\n")),
                    SET_VALUE("served_this_turn", true),
                    INCREMENT_VALUE("meals_served"), EARN_ACHIEVEMENT("f_omelette")
                ],
            },
        },
        // WIN CONDITION
        {
            if: {
                condition: IS_VALUE("meals_served", 3),
                actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.win_message", "\n")), WON("The Fridge", "{0} fed the hungry man!", "player")],
            },
        },
        // FALLBACK
        {
            if: {
                condition: IS_VALUE("served_this_turn", false),
                actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.fridge.targets.diner.no_food", "\n"))],
            },
        },
    ],
});
const newTheFridgeAdventureState = () => ({
    version: 1,
    inventory: [],
    status: "playing",
    props: {
        meals_served: 0,
        meals_made: 0,
    },
    nextPrompt: [TRANSLATE$1("jig_ccomp:text-adventure.fridge.introduction", "\n")],
    currentRoom: "kitchen",
});
const newTheFridgeAdventure = () => makeTextAdventure({
    overrides: {
        ui: {
            status: {
                title: "jig_ccomp:text-adventure.ui.select-adventure.adventure.fridge",
            },
        },
    },
    rooms: {
        kitchen: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.room.kitchen.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.room.kitchen.far_description", "\n"),
            targets: {
                fridge: FRIDGE,
                counter: COUNTER,
            },
            exits: {
                north: {
                    ...NORTH$1,
                    room: "dining_room",
                },
            },
        },
        dining_room: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.room.dining.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.room.dining.far_description", "\n"),
            targets: {
                diner: DINER,
            },
            exits: {
                south: {
                    ...SOUTH$1,
                    room: "kitchen",
                },
            },
        },
    },
    items: {
        ingredient_meat: { description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.item.meat") },
        ingredient_egg: { description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.item.egg") },
        ingredient_lettuce: { description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.item.lettuce") },
        ingredient_tomato: { description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.item.tomato") },
        ingredient_milk: { description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.item.milk") },
        ingredient_bread: { description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.item.bread") },
        ingredient_cheese: { description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.item.cheese") },
        ingredient_fruit: { description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.item.fruit") },
        food_sandwich: { description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.item.sandwich") },
        food_fruit_bowl: { description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.item.fruit_bowl") },
        food_burger: { description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.item.burger") },
        food_pancake: { description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.item.pancake") },
        food_salad: { description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.item.salad") },
        food_omelette: { description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.item.omelette") },
        food_toast: { description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.item.toast") },
        food_milkshake: { description: TRANSLATE$1("jig_ccomp:text-adventure.fridge.item.milkshake") },
    },
    achievements: Object.fromEntries(["f_burger", "f_fruit", "f_omelette", "f_pancake", "f_salad", "f_sanga", "f_shake", "f_toast"].map((id) => [
        id,
        {
            name: `jig_ccomp:text-adventure.fridge.achievement.${id}.name`,
            description: `jig_ccomp:text-adventure.fridge.achievement.${id}.description`,
            hint: `jig_ccomp:text-adventure.fridge.achievement.${id}.hint`,
            icon: `textures/jig/ccomp/items/art/${id}.png`,
            item: `jig_ccomp:poster_${id}`,
            print_title: "",
            print_content: "",
        },
    ])),
});

const NORTH = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.exit.continue", "\n"),
});
const SOUTH = makeExitTemplate({
    where: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.exit.go_back", "\n"),
});
const DOOR = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.door", "\n"),
    actions: [
        {
            if: {
                condition: hasItems("crowbar"),
                actions: [
                    SET_VALUE("door.opened", true),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.door.succeed", "\n")),
                    CHANGE_LOCATION("flooded_hallway"),
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.door.fail", "\n"))],
        },
    ],
});
const VAULT = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.vault", "\n"),
    actions: [
        {
            if: {
                condition: ALL(hasItems("vault_code"), IS_VALUE("power.enabled", true)),
                actions: [
                    HIDE_TARGET(),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.vault.succeed", "\n")),
                    GET_ITEM("ancient_artifact"), EARN_ACHIEVEMENT("sv_treasure"),
                    WON("The Sunken Vault", "{0} recovered the ancient artifact!", "player"),
                ],
            },
        },
        {
            if: {
                condition: ALL(doesNotHaveItems("vault_code"), IS_VALUE("power.enabled", true)),
                actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.vault.fail", "\n")), EARN_ACHIEVEMENT("sv_keypad"), DIE()],
            },
        },
        {
            if: {
                condition: ALL(IS_NOT_VALUE("power.enabled", true)),
                actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.vault.fail_power", "\n"))],
            },
        },
    ],
});
const LOCKER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.locker", "\n"),
    actions: [
        HIDE_TARGET(),
        GET_ITEM("vault_code"),
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.locker.succeed", "\n")),
    ],
});
const SUPPLY_BOX = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.supply_box", "\n"),
    actions: [
        HIDE_TARGET(),
        GET_ITEM("crowbar"),
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.supply_box.succeed", "\n")),
    ],
});
const REBREATHER = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.rebreather", "\n"),
    actions: [
        HIDE_TARGET(),
        GET_ITEM("rebreather"),
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.rebreather.succeed", "\n")),
    ],
});
const GLOVES = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.insulated_gloves", "\n"),
    actions: [
        HIDE_TARGET(),
        GET_ITEM("insulated_gloves"),
        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.insulated_gloves.succeed", "\n")),
    ],
});
const PRESSURE_PLATE = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.pressure_plate", "\n"),
    actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.pressure_plate.trigger", "\n")), EARN_ACHIEVEMENT("sv_spikes"), DIE()],
});
const GAS_TRAP = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.gas_vent", "\n"),
    actions: [
        {
            if: {
                condition: hasItems("gas_mask"),
                actions: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.gas_vent.survive", "\n"))],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.gas_vent.fail", "\n")), EARN_ACHIEVEMENT("sv_gas"), DIE()],
        },
    ],
});
const ELECTRIC_PANEL = makeTargetTemplate({
    description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.electric_panel", "\n"),
    actions: [
        {
            if: {
                condition: hasItems("insulated_gloves"),
                actions: [
                    HIDE_TARGET(),
                    SAY(TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.electric_panel.success", "\n")),
                    SET_VALUE("power.enabled", true),
                ],
            },
            else: [SAY(TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.targets.electric_panel.fail", "\n")), EARN_ACHIEVEMENT("sv_eletric"), DIE()],
        },
    ],
});
const newSunkenVaultAdventureState = () => ({
    version: 1,
    inventory: [],
    status: "playing",
    props: {},
    nextPrompt: [TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.introduction", "\n")],
    currentRoom: "entrance",
});
const newSunkenVaultAdventure = () => makeTextAdventure({
    overrides: {
        ui: {
            status: {
                title: "jig_ccomp:text-adventure.ui.select-adventure.adventure.sunken_vault",
            },
        },
    },
    rooms: {
        entrance: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.room.entrance.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.room.entrance.far_description", "\n"),
            targets: {
                supply_box: SUPPLY_BOX,
                rebreather: REBREATHER,
            },
            exits: {
                north: {
                    ...NORTH,
                    room: "sealed_door",
                },
            },
        },
        sealed_door: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.room.sealed_door.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.room.sealed_door.far_description", "\n"),
            targets: {
                door: DOOR,
            },
            exits: {
                south: {
                    ...SOUTH,
                    room: "entrance",
                },
            },
        },
        flooded_hallway: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.room.flooded_hallway.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.room.flooded_hallway.far_description", "\n"),
            targets: {},
            exits: {
                north: {
                    ...NORTH,
                    room: "research_lab",
                    filter: hasItems("rebreather"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.exit.rebreath", "\n"))
                    ],
                },
                waterygrave: {
                    ...NORTH,
                    room: "drowned_self",
                    filter: doesNotHaveItems("rebreather"),
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.exit.drown", "\n")), EARN_ACHIEVEMENT("sv_drowed"),
                        DIE(),
                    ],
                },
                south: {
                    ...SOUTH,
                    room: "sealed_door",
                },
            },
        },
        drowned_self: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.room.drowned_self.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.room.drowned_self.far_description", "\n"),
            targets: {},
            exits: {},
        },
        research_lab: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.room.research_lab.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.room.research_lab.far_description", "\n"),
            targets: {
                gas_vent: GAS_TRAP,
                locker: LOCKER,
            },
            exits: {
                north: {
                    ...NORTH,
                    room: "vault_room",
                    filter: IS_NOT_VALUE("power.enabled", true),
                },
                north_power: {
                    ...NORTH,
                    room: "powered_vault_room",
                    filter: IS_VALUE("power.enabled", true),
                },
                south: {
                    ...SOUTH,
                    room: "flooded_hallway",
                    actions: [
                        SAY(TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.exit.rebreath2", "\n"))
                    ],
                },
            },
        },
        vault_room: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.room.vault_room.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.room.vault_room.far_description", "\n"),
            targets: {
                vault: VAULT,
                pressure_plate: PRESSURE_PLATE,
            },
            exits: {
                north: {
                    ...NORTH,
                    room: "power_room",
                },
                south: {
                    ...SOUTH,
                    room: "research_lab",
                },
            },
        },
        powered_vault_room: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.room.powered_vault_room.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.room.powered_vault_room.far_description", "\n"),
            targets: {
                vault: VAULT,
                pressure_plate: PRESSURE_PLATE,
            },
            exits: {
                north: {
                    ...NORTH,
                    room: "power_room",
                },
                south: {
                    ...SOUTH,
                    room: "research_lab",
                },
            },
        },
        power_room: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.room.power_room.description", "\n"),
            far_description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.room.power_room.far_description", "\n"),
            targets: {
                electric_panel: ELECTRIC_PANEL,
                insulated_gloves: GLOVES,
            },
            exits: {
                south: {
                    ...SOUTH,
                    room: "vault_room",
                    filter: IS_NOT_VALUE("power.enabled", true),
                },
                south_power: {
                    ...SOUTH,
                    room: "powered_vault_room",
                    filter: IS_VALUE("power.enabled", true),
                },
            },
        },
    },
    items: {
        crowbar: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.item.crowbar"),
        },
        rebreather: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.item.rebreather"),
        },
        vault_code: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.item.vault_code"),
        },
        ancient_artifact: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.item.ancient_artifact"),
        },
        gas_mask: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.item.gas_mask"),
        },
        insulated_gloves: {
            description: TRANSLATE$1("jig_ccomp:text-adventure.sunken_vault.item.insulated_gloves"),
        },
    },
    achievements: Object.fromEntries(["sv_treasure", "sv_drowed", "sv_gas", "sv_spikes", "sv_eletric", "sv_keypad"].map((id) => [
        id,
        {
            name: `jig_ccomp:text-adventure.sunken_vault.achievement.${id}.name`,
            description: `jig_ccomp:text-adventure.sunken_vault.achievement.${id}.description`,
            hint: `jig_ccomp:text-adventure.sunken_vault.achievement.${id}.hint`,
            icon: `textures/jig/ccomp/items/art/${id}.png`,
            item: `jig_ccomp:poster_${id}`,
            print_title: "",
            print_content: "",
        },
    ])),
});

const continueGame = () => {
    return multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:text-adventure.ui.continue.title"))
        .setBody(TRANSLATE$1("jig_ccomp:text-adventure.ui.continue.body"))
        .addButton("continue", TRANSLATE$1("jig_ccomp:text-adventure.ui.continue.continue"), "textures/jig/ccomp/myui/game_continue.png")
        .addButton("new", TRANSLATE$1("jig_ccomp:text-adventure.ui.continue.new-game"), "textures/jig/ccomp/myui/game_new.png");
};
const areYouSure = () => {
    return multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:text-adventure.ui.continue-confirm.title"))
        .setBody(TRANSLATE$1("jig_ccomp:text-adventure.ui.continue-confirm.body"))
        .addButton("yes", TRANSLATE$1("jig_ccomp:text-adventure.ui.continue-confirm.yes"))
        .addButton("no", TRANSLATE$1("jig_ccomp:text-adventure.ui.continue-confirm.no"));
};

const evaluateBranchAction = (context, action) => {
    if (action.if.condition(context)) {
        evaluateActions(context, action.if.actions);
        return;
    }
    if (action.elseif) {
        const elseIfs = "length" in action.elseif ? action.elseif : [action.elseif];
        for (const elseif of elseIfs) {
            if (elseif.condition(context)) {
                evaluateActions(context, elseif.actions);
                return;
            }
        }
    }
    if (action.else) {
        evaluateActions(context, action.else);
    }
};
const evaluateFilters = (context, collection) => {
    return collection.filter((what) => {
        if (what.filter) {
            return what.filter(typeof context === "function" ? context(what) : context);
        }
        return true;
    });
};
const evaluateActions = (context, actions) => {
    for (const action of actions) {
        if (typeof action === "function") {
            action(context);
        }
        else {
            evaluateBranchAction(context, action);
        }
    }
};

const inventory = (textAdventure) => {
    const inventory = textAdventure.getInventory();
    if (inventory.length === 0) {
        return TRANSLATE$1("jig_ccomp:text-adventure.ui.no-items");
    }
    return RAW_TEXT(TRANSLATE$1("jig_ccomp:text-adventure.ui.items"), TEXT("\n"), ...inventory.map((i) => RAW_TEXT(TEXT(`- ${i.count}x `), textAdventure.definition.items[i.id].description, TEXT("\n"))));
};
const getFilteredTargets = (textAdventure, room) => {
    const achievements = textAdventure.getAchievementsIDs();
    const filtered = evaluateFilters((target) => ({
        type: "target",
        room,
        target,
        game: textAdventure.definition,
        state: textAdventure.state,
        player: textAdventure.player,
        achievements: achievements
    }), Object.values(room.targets));
    return filtered.filter((t) => !isTargetHidden(textAdventure.state, room.id, t));
};
const getTargets = (targets) => {
    return targets.map((t) => RAW_TEXT(TEXT(" - "), t.description, TEXT("\n")));
};
const getFilteredExits = (textAdventure, room) => {
    const achievements = textAdventure.getAchievementsIDs();
    const filtered = evaluateFilters((exit) => ({
        type: "exit",
        room,
        exit,
        game: textAdventure.definition,
        state: textAdventure.state,
        player: textAdventure.player,
        achievements: achievements
    }), Object.values(room.exits));
    return filtered.filter((t) => !isExitHidden(textAdventure.state, room.id, t));
};
const getExits = (textAdventure, exits) => {
    return exits.map((e) => RAW_TEXT(TEXT(" - "), e.where, TEXT(": "), e.description ?? textAdventure.definition.rooms[e.room].far_description ?? TEXT(""), TEXT("\n")));
};

const status = (textAdventure) => {
    return dualButtonScriptDialogue(TRANSLATE$1(textAdventure.getTitle()), {
        name: "continue",
        text: "jig_ccomp:text-adventure.ui.continue",
    }, {
        name: "close",
        text: "jig_ccomp:text-adventure.ui.close",
    }).setBody(RAW_TEXT(...textAdventure.getPendingText(), TEXT("\n"), textAdventure.didLost() ? TRANSLATE$1("jig_ccomp:text-adventure.ui.status.dead") :
        textAdventure.didWin() ? TRANSLATE$1("jig_ccomp:text-adventure.ui.status.win") :
            inventory(textAdventure)));
};

const room = (textAdventure) => {
    const currentRoom = textAdventure.getCurrentRoom();
    const targets = getFilteredTargets(textAdventure, currentRoom);
    const exits = getFilteredExits(textAdventure, currentRoom);
    let dialogue = multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:text-adventure.ui.room.title")).setBody(RAW_TEXT(currentRoom.description, TEXT("\n"), targets.length > 0
        ? RAW_TEXT(TRANSLATE$1("jig_ccomp:text-adventure.ui.room.targets"), TEXT("\n"), ...getTargets(targets), TEXT("\n"))
        : TEXT(""), exits.length > 0
        ? RAW_TEXT(TRANSLATE$1("jig_ccomp:text-adventure.ui.room.exits"), TEXT("\n"), ...getExits(textAdventure, exits), TEXT("\n"))
        : TEXT(""), inventory(textAdventure)));
    if (targets.length > 0) {
        dialogue = dialogue.addButton("interact", TRANSLATE$1("jig_ccomp:text-adventure.ui.interact"));
    }
    if (exits.length > 0) {
        dialogue = dialogue.addButton("walk", TRANSLATE$1(textAdventure.definition.overrides.ui.room.buttons.walk));
    }
    return dialogue.addButton("close", "jig_ccomp:text-adventure.ui.close");
};

const subRoomInteract = (textAdventure) => {
    const currentRoom = textAdventure.getCurrentRoom();
    getFilteredTargets(textAdventure, currentRoom);
    return multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:text-adventure.ui.interact.title"))
        .setBody("")
        .addButtons(getFilteredTargets(textAdventure, currentRoom).map((t) => ({
        name: t.id,
        text: t.description,
        iconPath: getIconForTarget(textAdventure, t),
    })))
        .addButton("jig:back", TRANSLATE$1("jig_ccomp:text-adventure.ui.interact.back"));
};
const getIconForTarget = (textAdventure, target) => {
    if (target.icon) {
        return target.icon;
    }
    else if (target.type) {
        return textAdventure.definition.overrides.icons.targets[target.type];
    }
    else {
        return textAdventure.definition.overrides.icons.targets.use;
    }
};

const subRoomWalk = (textAdventure) => {
    const currentRoom = textAdventure.getCurrentRoom();
    const exits = getFilteredExits(textAdventure, currentRoom);
    return multiButtonScriptDialogue(TRANSLATE$1(textAdventure.definition.overrides.ui.walk.title))
        .setBody(RAW_TEXT(...getExits(textAdventure, exits)))
        .addButtons(getFilteredExits(textAdventure, currentRoom).map((e) => ({
        name: e.id,
        text: e.where,
        iconPath: getIconForExit(textAdventure, e)
    })))
        .addButton("jig:back", TRANSLATE$1("jig_ccomp:text-adventure.ui.walk.back"));
};
const getIconForExit = (textAdventure, exit) => {
    if (exit.icon) {
        return exit.icon;
    }
    else if (exit.type) {
        return textAdventure.definition.overrides.icons.exits[exit.type];
    }
    else {
        return textAdventure.definition.overrides.icons.exits.walk;
    }
};

const textAdventureGameLoop = async (game, state, player, adventureId, options) => {
    const adventure = new TextAdventure(player.name, game, state);
    while (true) {
        options.save(adventure.state);
        if (adventure.hasPendingText()) {
            const statusResponse = await lockMovementWhile(player, async () => {
                return await status(adventure).open({ ...defaultScriptDialogueOptions, player });
            });
            if (!(statusResponse instanceof ButtonDialogueResponse) || statusResponse.selected === "close") {
                break;
            }
            adventure.cleanPendingText();
        }
        if (adventure.isGameover()) {
            break;
        }
        const response = await lockMovementWhile(player, async () => {
            return await room(adventure).open({ ...defaultScriptDialogueOptions, player });
        });
        if (!(response instanceof ButtonDialogueResponse) || response.selected === "close") {
            break;
        }
        if (response.selected === "interact") {
            const responseInteract = await lockMovementWhile(player, async () => {
                return await subRoomInteract(adventure).open({ ...defaultScriptDialogueOptions, player });
            });
            if (responseInteract instanceof ButtonDialogueResponse) {
                const selected = responseInteract.selected;
                if (selected !== "jig:back") {
                    const room = adventure.getCurrentRoom();
                    const target = room.targets[selected];
                    const achievements = [];
                    evaluateActions({
                        type: "target",
                        state: adventure.state,
                        room,
                        target,
                        game: adventure.definition,
                        player: adventure.player,
                        achievements: achievements,
                    }, target.actions);
                    evaluateEarnAchievements(achievements, options, adventure, adventureId);
                }
            }
        }
        else if (response.selected === "walk") {
            const responseWalk = await lockMovementWhile(player, async () => {
                return await subRoomWalk(adventure).open({ ...defaultScriptDialogueOptions, player });
            });
            if (responseWalk instanceof ButtonDialogueResponse) {
                const selected = responseWalk.selected;
                if (selected !== "jig:back") {
                    evaluateWalk(adventure, adventure.getCurrentRoom().exits[selected], options, adventureId);
                }
            }
        }
    }
    return adventure.state;
};
const evaluateEarnAchievements = (achievements, option, adventure, adventureId) => {
    if (achievements) {
        for (let i = 0; i < achievements.length; i++) {
            const result = option.earnAchievement(achievements[i]);
            if (!result) {
                adventure.state.nextPrompt.push(TRANSLATE$1('jig_ccomp:text-adventure.achievements.unlocked', TRANSLATE$1(`jig_ccomp:text-adventure.${adventureId}.achievement.${achievements[i]}.name`)));
            }
        }
    }
};
const evaluateWalk = (textAdventure, exit, option, adventureId) => {
    const room = textAdventure.getCurrentRoom();
    const achievements = [];
    if (exit.actions) {
        evaluateActions({
            type: "room",
            state: textAdventure.state,
            room,
            game: textAdventure.definition,
            player: textAdventure.player,
            achievements: achievements,
        }, exit.actions);
        evaluateEarnAchievements(achievements, option, textAdventure, adventureId);
    }
    textAdventure.state.currentRoom = exit.room;
};

const wonAdventure = (state, options) => {
    const certificateTitle = getWonCertificateTitle(state);
    let dialog = multiButtonScriptDialogue(TRANSLATE('jig_ccomp:text-adventure.ui.won.title'));
    if (certificateTitle) {
        dialog = dialog.setBody(RAW_TEXT(TRANSLATE('jig_ccomp:text-adventure.ui.won.body-certificate', "\n", certificateTitle), TEXT("\n"), TRANSLATE(`jig_ccomp:text-adventure.achievements.summary`, "" + options.achievementsUnlocked, "" + options.achievementsTotal, "" + certificateTitle)))
            .addButton('print', TRANSLATE('jig_ccomp:text-adventure.ui.won.print'), 'textures/jig/ccomp/myui/print_reward.png');
    }
    else {
        dialog = dialog.setBody(TRANSLATE('jig_ccomp:text-adventure.ui.won.body'));
    }
    dialog = dialog.addButton('achievements', TRANSLATE('jig_ccomp:text-adventure.ui.achievements'), 'textures/jig/ccomp/myui/achievements.png');
    dialog = dialog.addButton('restart', TRANSLATE('jig_ccomp:text-adventure.ui.restart'), "textures/jig/ccomp/myui/game_new.png");
    dialog = dialog.addButton('close', TRANSLATE('jig_ccomp:text-adventure.ui.close'));
    return dialog;
};

const lostAdventure = (state, options) => {
    return multiButtonScriptDialogue(TRANSLATE('jig_ccomp:text-adventure.ui.lost.title'))
        .setBody(RAW_TEXT(TRANSLATE('jig_ccomp:text-adventure.ui.lost.body'), TEXT("\n"), TRANSLATE(`jig_ccomp:text-adventure.achievements.summary.lost`, "" + options.achievementsUnlocked, "" + options.achievementsTotal)))
        .addButton('achievements', TRANSLATE('jig_ccomp:text-adventure.ui.achievements'), 'textures/jig/ccomp/myui/achievements.png')
        .addButton('restart', TRANSLATE('jig_ccomp:text-adventure.ui.restart'), "textures/jig/ccomp/myui/game_new.png")
        .addButton('close', TRANSLATE('jig_ccomp:text-adventure.ui.close'));
};

const newBlockyIslandAdventure = () => makeTextAdventure({
    overrides: { ui: { status: { title: "jig_ccomp:text-adventure.ui.select-adventure.adventure.blockyisland" } } },
    rooms: {
        "act1.crafting": {
            description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.description", "\n"),
            targets: {
                greg1: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.targets.greg1.name", "\n"),
                    actions: [
                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.targets.greg1.5Azqa.text", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("greg2"),
                        SET_VALUE("act1.crafting", true),
                    ],
                    type: "talk",
                },
                greg2: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.targets.greg2.name", "\n"),
                    actions: [
                        {
                            if: {
                                condition: HAS_ITEM("act1.crafting_table"),
                                actions: [
                                    SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.targets.greg2.xWbaQ.text", "\n")),
                                    REMOVE_ITEM("act1.crafting_table"),
                                    GET_ITEM("act1.badge_craft"),
                                    HIDE_TARGET(),
                                    {
                                        if: {
                                            condition: ALL(HAS_ITEM("act1.badge_redstone"), HAS_ITEM("act1.badge_craft"), HAS_ITEM("act1.badge_tame")),
                                            actions: [
                                                SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.targets.greg2.SCVjr.text", "\n")),
                                            ],
                                        },
                                    },
                                ],
                            },
                            elseif: [
                                {
                                    condition: HAS_ITEM("act1.plank"),
                                    actions: [
                                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.targets.greg2.cAGWn.text", "\n")),
                                    ],
                                },
                                {
                                    condition: HAS_ITEM("act1.wood"),
                                    actions: [
                                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.targets.greg2.B10nD.text", "\n")),
                                    ],
                                },
                            ],
                            else: [
                                SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.targets.greg2.QfMvM.text", "\n")),
                            ],
                        },
                    ],
                    hidden: true,
                    type: "talk",
                },
                books: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.targets.books.name", "\n"),
                    actions: [
                        {
                            if: {
                                condition: IS_VALUE("act1.crafting", true),
                                actions: [
                                    SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.targets.books.scGCV.text", "\n")),
                                    SET_VALUE("act1.know_craft_table", true),
                                ],
                            },
                            else: [
                                SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.targets.books.u56V8.text", "\n")),
                            ],
                        },
                    ],
                    type: "look",
                },
                space: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.targets.space.name", "\n"),
                    actions: [
                        {
                            if: {
                                condition: ALL(HAS_ITEM("act1.wood"), IS_VALUE("act1.know_craft_table", true)),
                                actions: [
                                    SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.targets.space.e4PH3.text", "\n")),
                                    REMOVE_ITEM("act1.wood", 4),
                                    GET_ITEM("act1.plank", 4),
                                ],
                            },
                            elseif: [
                                {
                                    condition: HAS_ITEM("act1.plank", 4),
                                    actions: [
                                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.targets.space.L8e6X.text", "\n")),
                                        GET_ITEM("act1.crafting_table"),
                                        REMOVE_ITEM("act1.plank", 4),
                                        HIDE_TARGET(),
                                    ],
                                },
                            ],
                            else: [
                                SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.targets.space.ELanc.text", "\n")),
                            ],
                        },
                    ],
                    filter: IS_VALUE("act1.crafting", true),
                    type: "use",
                },
            },
            exits: {
                outskirt: {
                    room: "act1.outskirt",
                    where: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.exits.outskirt.where", "\n"),
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.crafting.exits.outskirt.description", "\n"),
                    type: "outside",
                },
            },
        },
        "act1.outskirt": {
            description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.outskirt.description", "\n"),
            targets: {
                trees: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.outskirt.targets.trees.name", "\n"),
                    actions: [
                        {
                            if: {
                                condition: IS_VALUE("act1.enough_wood", true),
                                actions: [
                                    SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.outskirt.targets.trees.QTIPy.text", "\n")),
                                ],
                            },
                            elseif: [
                                {
                                    condition: HAS_ITEM("act1.wooden_axe"),
                                    actions: [
                                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.outskirt.targets.trees.7qYSL.text", "\n")),
                                        GET_ITEM("act1.wood"),
                                        SET_VALUE("act1.enough_wood", true),
                                    ],
                                },
                            ],
                            else: [
                                SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.outskirt.targets.trees.QqNzX.text", "\n")),
                                EARN_ACHIEVEMENT("bi_not_very"),
                            ],
                        },
                    ],
                    type: "use",
                },
            },
            exits: {
                town: {
                    room: "act1.town",
                    where: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.outskirt.exits.town.where", "\n"),
                    type: "walk",
                },
                wild: {
                    room: "act1.wild",
                    where: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.outskirt.exits.wild.where", "\n"),
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.outskirt.exits.wild.description", "\n"),
                    type: "walk",
                },
                crafting: {
                    room: "act1.crafting",
                    where: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.outskirt.exits.crafting.where", "\n"),
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.outskirt.exits.crafting.description", "\n"),
                    type: "inside",
                },
            },
        },
        "act1.shore": {
            description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.shore.description", "\n"),
            targets: {
                old_builder: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.shore.targets.old_builder.name", "\n"),
                    actions: [
                        {
                            if: {
                                condition: IS_VALUE("act1.old_man_talked", true),
                                actions: [
                                    SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.shore.targets.old_builder.t3v8G.text", "\n")),
                                ],
                            },
                            else: [
                                SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.shore.targets.old_builder.ryiLr.text", "\n")),
                                SET_VALUE("act1.old_man_talked", true),
                            ],
                        },
                    ],
                    type: "talk",
                },
            },
            exits: {
                town: {
                    room: "act1.town",
                    where: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.shore.exits.town.where", "\n"),
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.shore.exits.town.description", "\n"),
                    filter: IS_VALUE("act1.old_man_talked", true),
                    actions: [
                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.shore.exits.town.ydsEt.text", "\n")),
                    ],
                    type: "walk",
                },
            },
        },
        "act1.tavern": {
            description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.description", "\n"),
            targets: {
                party: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.party.name", "\n"),
                    actions: [
                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.party.J3KEk.text", "\n")),
                        EARN_ACHIEVEMENT("bi_island"),
                        WON("The Secret of Blocky Island", "{0} finished Act I", "player"),
                    ],
                    filter: ALL(HAS_ITEM("act1.badge_redstone"), HAS_ITEM("act1.badge_craft"), HAS_ITEM("act1.badge_tame")),
                    type: "talk",
                },
                keeper1: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.keeper1.name", "\n"),
                    actions: [
                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.keeper1.LGQMd.text", "\n")),
                        {
                            if: {
                                condition: IS_NOT_VALUE("act1.masters", true),
                                actions: [
                                    SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.keeper1.RTJP0.text", "\n")),
                                ],
                            },
                        },
                        SHOW_TARGET("keeper2"),
                        HIDE_TARGET(),
                    ],
                    type: "talk",
                },
                keeper2: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.keeper2.name", "\n"),
                    actions: [
                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.keeper2.BPfMT.text", "\n")),
                    ],
                    hidden: true,
                    type: "talk",
                },
                coal1: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.coal1.name", "\n"),
                    actions: [
                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.coal1.sgH9a.text", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("coal2"),
                        SET_VALUE("act1.masters", true),
                    ],
                    type: "talk",
                },
                coal2: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.coal2.name", "\n"),
                    actions: [
                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.coal2.iYNOA.text", "\n")),
                    ],
                    hidden: true,
                    type: "talk",
                },
                plankton1: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.plankton1.name", "\n"),
                    actions: [
                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.plankton1.Ur5GJ.text", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("plankton2"),
                    ],
                    type: "talk",
                },
                plankton2: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.plankton2.name", "\n"),
                    actions: [
                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.plankton2.IZXZj.text", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("plankton3"),
                        GET_ITEM("act1.wooden_axe"),
                    ],
                    hidden: true,
                    type: "talk",
                },
                plankton3: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.plankton3.name", "\n"),
                    actions: [
                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.plankton3.ze7DJ.text", "\n")),
                    ],
                    hidden: true,
                    type: "talk",
                },
                wilma1: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.wilma1.name", "\n"),
                    actions: [
                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.targets.wilma1.m2qym.text", "\n")),
                        HIDE_TARGET(),
                        GET_ITEM("act1.blueprint_redstone"),
                    ],
                    filter: IS_VALUE("act1.redstone", true),
                    type: "talk",
                },
            },
            exits: {
                town: {
                    room: "act1.town",
                    where: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.tavern.exits.town.where", "\n"),
                    type: "outside",
                },
            },
        },
        "act1.town": {
            description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.town.description", "\n"),
            targets: {},
            exits: {
                tavern: {
                    room: "act1.tavern",
                    where: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.town.exits.tavern.where", "\n"),
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.town.exits.tavern.description", "\n"),
                    type: "inside",
                },
                workshop: {
                    room: "act1.workshop",
                    where: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.town.exits.workshop.where", "\n"),
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.town.exits.workshop.description", "\n"),
                    filter: IS_VALUE("act1.masters", true),
                    type: "inside",
                },
                outskirt: {
                    room: "act1.outskirt",
                    where: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.town.exits.outskirt.where", "\n"),
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.town.exits.outskirt.description", "\n"),
                    filter: IS_VALUE("act1.masters", true),
                    type: "walk",
                },
            },
        },
        "act1.wild": {
            description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.wild.description", "\n"),
            targets: {
                tess1: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.wild.targets.tess1.name", "\n"),
                    actions: [
                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.wild.targets.tess1.FIOWn.text", "\n")),
                        HIDE_TARGET(),
                        SHOW_TARGET("tess2"),
                        SET_VALUE("act1.tame", true),
                    ],
                    type: "talk",
                },
                tess2: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.wild.targets.tess2.name", "\n"),
                    actions: [
                        {
                            if: {
                                condition: HAS_ITEM("act1.horse"),
                                actions: [
                                    SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.wild.targets.tess2.TL1wZ.text", "\n")),
                                    GET_ITEM("act1.badge_tame"),
                                    {
                                        if: {
                                            condition: ALL(HAS_ITEM("act1.badge_redstone"), HAS_ITEM("act1.badge_craft"), HAS_ITEM("act1.badge_tame")),
                                            actions: [
                                                SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.wild.targets.tess2.czGAF.text", "\n")),
                                            ],
                                        },
                                    },
                                    HIDE_TARGET(),
                                ],
                            },
                            else: [
                                SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.wild.targets.tess2.sCDDP.text", "\n")),
                            ],
                        },
                    ],
                    hidden: true,
                    type: "talk",
                },
                horse: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.wild.targets.horse.name", "\n"),
                    actions: [
                        {
                            if: {
                                condition: THROW_DICE(6, 1, 2),
                                actions: [
                                    SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.wild.targets.horse.n40fB.text", "\n")),
                                    GET_ITEM("act1.horse"),
                                    HIDE_TARGET(),
                                ],
                            },
                            elseif: [
                                {
                                    condition: THROW_DICE(4, 1),
                                    actions: [
                                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.wild.targets.horse.Fo6zT.text", "\n")),
                                        EARN_ACHIEVEMENT("bi_cant_die"),
                                    ],
                                },
                            ],
                            else: [
                                SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.wild.targets.horse.LUSK2.text", "\n")),
                            ],
                        },
                    ],
                    filter: IS_VALUE("act1.tame", true),
                    type: "use",
                },
            },
            exits: {
                outskirt: {
                    room: "act1.outskirt",
                    where: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.wild.exits.outskirt.where", "\n"),
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.wild.exits.outskirt.description", "\n"),
                    type: "walk",
                },
            },
        },
        "act1.workshop": {
            description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.workshop.description", "\n"),
            targets: {
                dusty: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.workshop.targets.dusty.name", "\n"),
                    actions: [
                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.workshop.targets.dusty.QMdkx.text", "\n")),
                        HIDE_TARGET(),
                    ],
                    type: "talk",
                },
                pete1: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.workshop.targets.pete1.name", "\n"),
                    actions: [
                        SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.workshop.targets.pete1.qBRvP.text", "\n")),
                        HIDE_TARGET(),
                        SET_VALUE("act1.redstone", true),
                        SHOW_TARGET("pete2"),
                    ],
                    type: "talk",
                },
                pete2: {
                    description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.workshop.targets.pete2.name", "\n"),
                    actions: [
                        {
                            if: {
                                condition: HAS_ITEM("act1.blueprint_redstone"),
                                actions: [
                                    SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.workshop.targets.pete2.qLVE1.text", "\n")),
                                    REMOVE_ITEM("act1.blueprint_redstone"),
                                    GET_ITEM("act1.badge_redstone"),
                                    {
                                        if: {
                                            condition: ALL(HAS_ITEM("act1.badge_redstone"), HAS_ITEM("act1.badge_craft"), HAS_ITEM("act1.badge_tame")),
                                            actions: [
                                                SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.workshop.targets.pete2.bqoL0.text", "\n")),
                                            ],
                                        },
                                    },
                                    SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.workshop.targets.pete2.8KATU.text", "\n")),
                                    HIDE_TARGET(),
                                ],
                            },
                            else: [
                                SAY(TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.workshop.targets.pete2.cSjCe.text", "\n")),
                            ],
                        },
                    ],
                    hidden: true,
                    type: "talk",
                },
            },
            exits: {
                town: {
                    room: "act1.town",
                    where: TRANSLATE("jig_ccomp:text-adventure.blocky_island.rooms.act1.workshop.exits.town.where", "\n"),
                    type: "outside",
                },
            },
        },
    },
    items: {
        "act1.blueprint_redstone": {
            description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.act1.blueprint_redstone.description", "\n"),
        },
        "act1.wooden_axe": {
            description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.act1.wooden_axe.description", "\n"),
        },
        "act1.wood": {
            description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.act1.wood.description", "\n"),
        },
        "act1.plank": {
            description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.act1.plank.description", "\n"),
        },
        "act1.crafting_table": {
            description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.act1.crafting_table.description", "\n"),
        },
        "act1.badge_redstone": {
            description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.act1.badge_redstone.description", "\n"),
        },
        "act1.badge_craft": {
            description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.act1.badge_craft.description", "\n"),
        },
        "act1.badge_tame": {
            description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.act1.badge_tame.description", "\n"),
        },
        "act1.horse": {
            description: TRANSLATE("jig_ccomp:text-adventure.blocky_island.act1.horse.description", "\n"),
        },
    },
    achievements: {
        bi_island: {
            name: "jig_ccomp:text-adventure.blockyisland.achievement.bi_island.name",
            description: "jig_ccomp:text-adventure.blockyisland.achievement.bi_island.description",
            hint: "jig_ccomp:text-adventure.blockyisland.achievement.bi_island.hint",
            item: "jig_ccomp:poster_bi_island",
            icon: "textures/jig/ccomp/items/art/bi_island",
            print_title: "",
            print_content: "",
        },
        bi_cant_die: {
            name: "jig_ccomp:text-adventure.blockyisland.achievement.bi_cant_die.name",
            description: "jig_ccomp:text-adventure.blockyisland.achievement.bi_cant_die.description",
            hint: "jig_ccomp:text-adventure.blockyisland.achievement.bi_cant_die.hint",
            item: "jig_ccomp:poster_bi_cant_die",
            icon: "textures/jig/ccomp/items/art/bi_cant_die",
            print_title: "",
            print_content: "",
        },
        bi_not_very: {
            name: "jig_ccomp:text-adventure.blockyisland.achievement.bi_not_very.name",
            description: "jig_ccomp:text-adventure.blockyisland.achievement.bi_not_very.description",
            hint: "jig_ccomp:text-adventure.blockyisland.achievement.bi_not_very.hint",
            item: "jig_ccomp:poster_bi_not_very",
            icon: "textures/jig/ccomp/items/art/bi_not_very",
            print_title: "",
            print_content: "",
        },
    },
});
const newBlockyIslandAdventureState = () => ({
    version: 1,
    inventory: [],
    status: "playing",
    props: {},
    nextPrompt: [TRANSLATE("jig_ccomp:text-adventure.blocky_island.introduction", "\n")],
    currentRoom: "act1.shore",
});

const data = {
    //minecraft: {
    //    initialState: newMinecraftAdventureState,
    //    build: newMinecraftAdventure,
    //    icon: 'textures/jig/ccomp/myui/a_minecraft.png',
    //},
    fridge: {
        initialState: newTheFridgeAdventureState,
        build: newTheFridgeAdventure,
        icon: 'textures/jig/ccomp/myui/a_fridge.png',
    },
    blockyisland: {
        initialState: newBlockyIslandAdventureState,
        build: newBlockyIslandAdventure,
        icon: 'textures/jig/ccomp/myui/a_minecraft.png',
    },
    duct: {
        initialState: newDuctAdventureState,
        build: newDuctAdventure,
        icon: 'textures/jig/ccomp/myui/a_duct.png',
    },
    downtoearth: {
        initialState: newDownToEarthAdventureState,
        build: newDownToEarthAdventure,
        icon: 'textures/jig/ccomp/myui/a_downtoearth.png',
    },
    //battle: {
    //    initialState: newBattleAdventureState,
    //    build: newBattleAdventure,
    //    icon: 'textures/jig/ccomp/myui/a_the_fridge.png',
    //},
    caseofthejug: {
        initialState: newCaseOfTheJugAdventureState,
        build: newCaseOfTheJugAdventure,
        icon: 'textures/jig/ccomp/myui/a_juggle.png',
    },
    sandender: {
        initialState: newSandEnderAdventureState,
        build: newSandEnderAdventure,
        icon: 'textures/jig/ccomp/myui/a_sandender.png',
    },
    grimforest: {
        initialState: newGrimForestAdventureState,
        build: newGrimForestAdventure,
        icon: 'textures/jig/ccomp/myui/a_grimforest.png',
    },
    sunken_vault: {
        initialState: newSunkenVaultAdventureState,
        build: newSunkenVaultAdventure,
        icon: 'textures/jig/ccomp/myui/a_sunken_vault.png',
    },
    endless_h: {
        initialState: newEndlessHAdventureState,
        build: newEndlessHAdventure,
        icon: 'textures/jig/ccomp/myui/a_endless_h.png',
    },
};
const ACHIEVEMENT_PROP = (adventureId) => `textadventure.${adventureId}.achievements`;
const RESET_ACHIEVEMENTS = 'jig_ccomp:reset-achievements';
const TextAdventureCrossPlatform = async (event) => {
    const adventureMenu = 'jig_ccomp:text-adventure.new';
    let isPhoneVersion = ('cancel' in event) ? true : false;
    const mainEvent = event;
    if (('id' in event && event.id === adventureMenu) || (isPhoneVersion)) {
        const ui = {
            entrypoint: 'adventures',
            forms: {
                adventures: {
                    type: 'multi-button',
                    title: _('jig_ccomp:adventures_title'),
                    body: _('jig_ccomp:text-adventure.ui.select-adventure.body', "\n"),
                    elements: [
                        ...Object.entries(data).map(([key, value]) => ({
                            type: 'button',
                            text: _(`jig_ccomp:text-adventure.ui.select-adventure.adventure.${key}`),
                            icon: value.icon,
                            action: {
                                form: 'adventureOption',
                                setArgs: {
                                    adventureId: key,
                                },
                                copyArgs: true,
                            },
                        })),
                        {
                            type: 'button',
                            text: _('jig_ccomp:gui.close'),
                            action: {
                                event: 'close_app',
                                copyArgs: true,
                            }
                        },
                    ],
                },
                adventureOption: {
                    type: 'multi-button',
                    title: _('jig_ccomp:adventures_options_title'),
                    body: _('jig_ccomp:{adventureId}.information', "\n"),
                    elements: [
                        {
                            type: 'button',
                            text: _(`jig_ccomp:text-adventure.ui.select-play.adventure`),
                            icon: `textures/jig/ccomp/myui/play_adventure`,
                            action: {
                                event: 'start_adventure',
                                copyArgs: true,
                            },
                        },
                        {
                            type: 'button',
                            text: _(`jig_ccomp:text-adventure.ui.select-see.achievement`),
                            icon: `textures/jig/ccomp/myui/achievements`,
                            action: {
                                event: 'achievements',
                                form: 'achievements',
                                copyArgs: true,
                            },
                        },
                        {
                            type: 'button',
                            text: _('jig_ccomp:adventure.back'),
                            action: {
                                form: 'adventures',
                                copyArgs: true,
                            }
                        }
                    ]
                },
                achievements: {
                    type: 'multi-button',
                    title: _('jig_ccomp:achievements_title'),
                    body: _('jig_ccomp:achievements_{adventureId}_body', "\n\n", "\n\n"),
                    elements: []
                },
                achievement_earn: {
                    type: 'multi-button',
                    title: _('{achievement.name}'),
                    body: _('{achievement.description}', "\n\n", "\n\n"),
                    elements: [
                        {
                            type: 'button',
                            text: _('jig_ccomp:achievement.print'),
                            icon: `textures/jig/ccomp/myui/print_achievement`,
                            action: {
                                event: 'print',
                                copyArgs: true
                            },
                        },
                        {
                            type: 'button',
                            text: _('jig_ccomp:butt.back'),
                            action: {
                                event: 'achievements',
                                form: 'achievements',
                                copyArgs: true
                            },
                        },
                    ]
                },
                achievement_unearned: {
                    type: 'multi-button',
                    title: _('{achievement.name}'),
                    body: _('{achievement.hint}', "\n\n", "\n\n"),
                    elements: [
                        {
                            type: 'button',
                            text: _('jig_ccomp:butt.back'),
                            action: {
                                event: 'achievements',
                                form: 'achievements',
                                copyArgs: true
                            },
                        },
                    ]
                }
            }
        };
        await lockMovementWhile(event.player, async () => {
            await renderLoop(event.player, { ...ui, entrypoint: "adventures" }, {
                close_app: async () => {
                    if ('closeApp' in event) {
                        event.closeApp = true;
                    }
                },
                "start_adventure": async (event) => {
                    const adventureId = event.args.get("adventureId");
                    const adventure = await startAdventure(adventureId, mainEvent, ui);
                },
                "achievements": async (event) => {
                    await loadAchievements(event, mainEvent, true);
                },
                "print": async (event) => {
                    await printAchievement(event, mainEvent);
                },
            });
        });
    }
};
const loadAchievements = (event, mainEvent, isFromMain) => {
    event.form = event.loadForm('achievements', 'multi-button');
    const adventureId = event.args.get("adventureId");
    const playerAchievements = GET_PROP$1(mainEvent.player, ACHIEVEMENT_PROP(adventureId), []);
    const adventure = data[adventureId];
    const achievementsGame = adventure.build().achievements;
    const [playerHave, playerDoesNotHave] = categorizeAchievements(achievementsGame, playerAchievements);
    event.form.elements.unshift(...playerDoesNotHave.map(c => ({
        type: 'button',
        text: _(c.name),
        icon: adventure.build().overrides.ui.achievement.defaultIcon,
        action: {
            form: 'achievement_unearned',
            setArgs: {
                achievement: c,
                adventureId: adventureId
            },
            copyArgs: true,
        },
    })));
    event.form.elements.unshift(...playerHave.map(c => ({
        type: 'button',
        text: _(c.name),
        icon: c.icon,
        action: {
            form: 'achievement_earn',
            setArgs: {
                achievement: c,
                adventureId: adventureId
            },
            copyArgs: true,
        },
    })));
    if (isFromMain) {
        event.form.elements.push({
            type: 'button',
            text: _('jig_ccomp:butt.back'),
            action: {
                form: 'adventureOption',
                copyArgs: true,
            },
        });
    }
    else {
        event.form.elements.push({
            type: 'button',
            text: _('jig_ccomp:butt.back'),
        });
    }
};
const printAchievement = async (event, mainEvent) => {
    const adventure = event.args.get("achievement");
    await printContent(adventure.print_title, adventure.print_content, ('computer' in mainEvent) ? mainEvent.computer : undefined, mainEvent.player, adventure.item);
};
const categorizeAchievements = (achievements, playerIds) => {
    return [
        Object.values(achievements).filter(a => playerIds.includes(a.id)),
        Object.values(achievements).filter(a => !playerIds.includes(a.id))
    ];
};
const getTotalAchievementsUnlocked = (mainEvent, adventureId) => {
    const playerAchievements = GET_PROP$1(mainEvent.player, ACHIEVEMENT_PROP(adventureId), []);
    const adventure = data[adventureId];
    const achievementsGame = adventure.build().achievements;
    const [playerHave, playerDoesNotHave] = categorizeAchievements(achievementsGame, playerAchievements);
    const achievementsPlayer = {
        achievementsTotal: playerHave.length + playerDoesNotHave.length,
        achievementsUnlocked: playerHave.length
    };
    return achievementsPlayer;
};
const showAchievements = async (player, screen, ui, adventureId, mainEvent) => {
    await lockMovementWhile(player, async () => {
        await renderLoop(player, { ...ui, entrypoint: { events: screen, initialArgs: { adventureId: adventureId } } }, {
            "achievements": async (event) => {
                await loadAchievements(event, mainEvent, false);
            },
            "print": async (event) => {
                await printAchievement(event, mainEvent);
            },
        });
    });
};
const startAdventure = async (adventureId, event, ui) => {
    if (adventureId && adventureId in data) {
        game: while (true) {
            const adventure = data[adventureId];
            const save = `jig_ccomp:text-adventure.save.${adventureId}`;
            const rawSave = event.player.getDynamicProperty(save);
            const startNewGame = await shouldStartNewGame(rawSave, event.player);
            const state = startNewGame ? adventure.initialState() : JSON.parse(rawSave);
            // Declare `newState` outside the if-else block
            const nextState = await textAdventureGameLoop(adventure.build(), state, event.player, adventureId, {
                save: (s) => {
                    // Set the dynamic property with the new state
                    event.player.setDynamicProperty(save, JSON.stringify(s));
                },
                earnAchievement: (achievement) => {
                    const data = GET_PROP$1(event.player, ACHIEVEMENT_PROP(adventureId), []);
                    const achievementUnlockedBefore = (data.includes(achievement)) ? true : false;
                    data.push(achievement);
                    SET_PROP$1(event.player, ACHIEVEMENT_PROP(adventureId), [...new Set(data)]);
                    return achievementUnlockedBefore;
                }
            });
            switch (nextState.status) {
                case "playing":
                    // No-OP
                    break game;
                case "won":
                    while (true) {
                        //TODO Maybe here we can show how meane have unlocked total
                        const wonResponse = await lockMovementWhile(event.player, async () => {
                            return await wonAdventure(nextState, getTotalAchievementsUnlocked(event, adventureId)).open({ player: event.player });
                        });
                        if (wonResponse instanceof ButtonDialogueResponse) {
                            if (wonResponse.selected === "restart") {
                                event.player.setDynamicProperty(save, undefined);
                            }
                            else if (wonResponse.selected === "close") {
                                break game;
                            }
                            else if (wonResponse.selected === "print") {
                                const printed = await printContent(getWonCertificateTitle(nextState), getWonCertificateDescription(nextState), ('computer' in event) ? event.computer : undefined, event.player, 'jig_ccomp:printed_paper');
                                if (printed) {
                                    event.player.setDynamicProperty(save, undefined);
                                }
                                break game;
                            }
                            else if (wonResponse.selected === "achievements") {
                                await showAchievements(event.player, "achievements", ui, adventureId, event);
                                continue;
                            }
                        }
                        else {
                            break game;
                        }
                        break;
                    }
                    break;
                case "lost":
                    while (true) {
                        event.player.setDynamicProperty(save, undefined);
                        const lostResponse = await lockMovementWhile(event.player, async () => {
                            return await lostAdventure(nextState, getTotalAchievementsUnlocked(event, adventureId)).open({ player: event.player });
                        });
                        if (lostResponse instanceof ButtonDialogueResponse) {
                            if (lostResponse.selected === "close") {
                                break game;
                            }
                            else if (lostResponse.selected === "achievements") {
                                await showAchievements(event.player, "achievements", ui, adventureId, event);
                                continue;
                            }
                            break;
                        }
                        else {
                            break game;
                        }
                    }
                    break;
            }
        }
    }
};
const shouldStartNewGame = async (rawSave, player) => {
    if (rawSave) {
        const response = await lockMovementWhile(player, async () => {
            return await continueGame().open({
                player,
            });
        });
        if (response instanceof ButtonDialogueResponse) {
            if (response.selected === "continue") {
                return false;
            }
            else if (response.selected === "new") {
                const responseConfirm = await lockMovementWhile(player, async () => {
                    return await areYouSure().open({
                        player,
                    });
                });
                if (responseConfirm instanceof ButtonDialogueResponse) {
                    if (responseConfirm.selected === "yes") {
                        return true;
                    }
                }
            }
        }
        else {
            return undefined;
        }
    }
    else {
        return true;
    }
};
const initTextAdventureResetCode = () => {
    system.afterEvents.scriptEventReceive.subscribe((event) => {
        if (event.sourceEntity instanceof Player) {
            if (event.id === RESET_ACHIEVEMENTS) {
                for (const adventureId of Object.keys(data)) {
                    SET_PROP$1(event.sourceEntity, ACHIEVEMENT_PROP(adventureId), undefined);
                }
            }
        }
    });
};

class TextAdventurePhoneApp extends PhoneApp {
    static COMPONENT_ID = 'TextAdventure';
    constructor() {
        super(TextAdventurePhoneApp.COMPONENT_ID);
    }
    async onSelected(event) {
        await this.openApp(event);
    }
    async onAction(event) {
        await this.openApp(event);
    }
    async openApp(event) {
        event.cancel = true;
        await TextAdventureCrossPlatform(event);
    }
}

const subscribeFromComputerNpcDialogue = (callback, options) => {
    system.afterEvents.scriptEventReceive.subscribe((event) => {
        const player = event.initiator;
        const sourceEntity = event.sourceEntity;
        if (player && player instanceof Player && sourceEntity && CraftComputer.isComputer(sourceEntity)) {
            callback({
                id: event.id,
                computer: new CraftComputer(sourceEntity),
                player,
                message: event.message
            });
        }
    }, options);
};
const executeScriptDialogueFromNpcDialogue = (callback) => {
    system.runTimeout(callback, 10);
};

const showMinesweeperSplash = async (event) => {
    const player = event.player;
    const ui = {
        entrypoint: 'minesweeper_splash',
        forms: {
            minesweeper_splash: {
                type: 'multi-button',
                title: _('jig_ccomp:name.sweeper'),
                body: _('jig_ccomp:sweeper_title', "\n\n"),
                elements: [
                    {
                        type: 'button',
                        text: _('jig_ccomp:butt.sweeper_start'),
                        icon: 'textures/jig/ccomp/phone/apps/tnt.png',
                        action: {
                            event: 'start_minesweeper',
                        },
                    },
                    {
                        type: 'button',
                        text: _('jig_ccomp:gui.close'),
                        action: { event: 'close_app' },
                    },
                ],
            },
        },
    };
    await lockMovementWhile(player, () => {
        return renderLoop(player, ui, {
            start_minesweeper: async () => {
                const config = await askForDifficulty(player);
                if (!config)
                    return;
                const { difficulty, multiplier, sizeX, sizeZ } = config;
                await openMineSweeper(player, sizeX, sizeZ, multiplier, undefined, difficulty, event);
            },
            close_app: async () => {
                event.closeApp = true;
            }
        });
    });
};
var MinesweeperOutcome;
(function (MinesweeperOutcome) {
    MinesweeperOutcome["WON"] = "won";
    MinesweeperOutcome["LOST"] = "lost";
    MinesweeperOutcome["PLAYING"] = "playing";
})(MinesweeperOutcome || (MinesweeperOutcome = {}));
var MinesweeperAction;
(function (MinesweeperAction) {
    MinesweeperAction["OPEN"] = "open";
    MinesweeperAction["FLAG"] = "flag";
})(MinesweeperAction || (MinesweeperAction = {}));
class Minesweeper {
    turns;
    /** [row][column]*/
    _board;
    columns;
    rows;
    mines;
    constructor(rows, columns, mines) {
        this.turns = 0;
        this.columns = columns;
        this.rows = rows;
        this._board = [...Array(rows)].map(() => [...Array(columns)].map(() => ({
            isMine: false,
            isOpen: false,
            isFlagged: false,
            minesAround: 0,
        })));
        this.mines = mines;
        this.setupMines(mines);
    }
    get board() {
        return this._board;
    }
    playTurn(row, column, action, player) {
        world.scoreboard.getObjective("jig_ccomp:jig_computer.addon_stats")?.addScore("jig_ccomp:tnt_sweeper_turns", 1);
        this.turns++;
        const cell = this._board[row][column];
        if (cell.isOpen) {
            return MinesweeperOutcome.PLAYING;
        }
        if (action === MinesweeperAction.FLAG) {
            cell.isFlagged = !cell.isFlagged;
        }
        else {
            if (cell.isMine) {
                if (!player.hasTag("jig_ccomp:cheat_sweeper") && !player.hasTag("jig_ccomp:really_cheat_sweeper")) {
                    return MinesweeperOutcome.LOST;
                }
                if (player.hasTag("jig_ccomp:cheat_sweeper") && !player.hasTag("jig_ccomp:really_cheat_sweeper")) {
                    cell.isFlagged = !cell.isFlagged;
                }
                if (player.hasTag("jig_ccomp:really_cheat_sweeper")) {
                    return MinesweeperOutcome.WON;
                }
            }
            this.openValid(row, column);
            if (this.playerWon()) {
                return MinesweeperOutcome.WON;
            }
        }
        return MinesweeperOutcome.PLAYING;
    }
    openValid(row, column) {
        if (row >= 0 && row < this.rows && column >= 0 && column < this.columns) {
            const cell = this._board[row][column];
            if (!cell.isOpen && !cell.isFlagged) {
                cell.isOpen = true;
                if (cell.minesAround === 0) {
                    this.openValid(row - 1, column - 1);
                    this.openValid(row - 1, column);
                    this.openValid(row - 1, column + 1);
                    this.openValid(row, column - 1);
                    this.openValid(row, column + 1);
                    this.openValid(row + 1, column - 1);
                    this.openValid(row + 1, column);
                    this.openValid(row + 1, column + 1);
                }
            }
        }
    }
    playerWon() {
        for (const row of this._board) {
            for (const cell of row) {
                if (!cell.isOpen && !cell.isMine) {
                    return false;
                }
            }
        }
        return true;
    }
    setupMines(mines) {
        let minesCreated = 0;
        while (minesCreated < mines) {
            const i = makeRandomNumber(0, this.rows - 1);
            const j = makeRandomNumber(0, this.columns - 1);
            if (!this._board[i][j].isMine) {
                this._board[i][j].isMine = true;
                this.updateMineCountIfAny(i - 1, j - 1);
                this.updateMineCountIfAny(i - 1, j);
                this.updateMineCountIfAny(i - 1, j + 1);
                this.updateMineCountIfAny(i, j - 1);
                this.updateMineCountIfAny(i, j + 1);
                this.updateMineCountIfAny(i + 1, j - 1);
                this.updateMineCountIfAny(i + 1, j);
                this.updateMineCountIfAny(i + 1, j + 1);
                minesCreated++;
            }
        }
    }
    updateMineCountIfAny(row, column) {
        if (row >= 0 && row < this.rows && column >= 0 && column < this.columns) {
            this._board[row][column].minesAround++;
        }
    }
}
const initMineSweeperCrossPlatform = async (event) => {
    const player = event.player;
    if ('computer' in event) {
        // Came from NPC — skip splash
        const config = await askForDifficulty(player);
        if (!config)
            return;
        const { difficulty, multiplier, sizeX, sizeZ } = config;
        await openMineSweeper(player, sizeX, sizeZ, multiplier, event.computer, difficulty, event);
    }
    else {
        // Came from phone — show splash screen
        await showMinesweeperSplash(event);
    }
};
const initMineSweeper = () => {
    subscribeFromComputerNpcDialogue(async (event) => {
        if (event.id === "jig_ccomp:minesweeper") {
            await initMineSweeperCrossPlatform(event);
        }
    }, {
        namespaces: ["jig_ccomp"],
    });
};
const indexToColumn = (index) => {
    return index + 1;
};
const indexToRow = (index) => {
    return (index + 10).toString(36).toUpperCase();
};
const boardToRawMessage = (minesweeper, printAllBoard) => {
    return [
        TEXT("§8x§0-" +
            [...Array(minesweeper.board[0].length)]
                .map((_, index) => {
                const column = indexToColumn(index);
                let color;
                if (index >= 8) {
                    color = index % 2 === 0 ? "§b" : "§9"; // Use §b for even and §e for odd indices >= 10
                }
                else {
                    color = "§b"; // Use §b for indices < 10
                }
                return index >= 8 ? `${color}${column}` : `${color}${column}§0-`;
            })
                .join("") +
            "§r\n"),
        ...minesweeper.board.flatMap((row, index) => {
            const rowLabel = indexToRow(index);
            const space = rowLabel === "I" ? " " : "";
            const printRow = [TEXT(`§d${space}${rowLabel}§r`)];
            for (const cell of row) {
                printRow.push(TEXT("§0-"));
                if (!printAllBoard && cell.isFlagged) {
                    printRow.push(TEXT("§aF§r"));
                }
                else if (!printAllBoard && !cell.isOpen) {
                    printRow.push(TEXT("§r-"));
                }
                else if (cell.isMine) {
                    printRow.push(TEXT("§cT§r"));
                }
                else if (cell.minesAround) {
                    printRow.push(TEXT(`§6${cell.minesAround}§r`));
                }
                else {
                    printRow.push(TEXT("§70"));
                }
            }
            printRow.push(TEXT("\n"));
            return printRow;
        }),
    ];
};
const askForDifficulty = async (player) => {
    const difficultyConfig = {
        a: { multiplier: 1, sizeX: 3, sizeZ: 3 },
        b: { multiplier: 1, sizeX: 7, sizeZ: 7 },
        c: { multiplier: 1, sizeX: 8, sizeZ: 8 },
        d: { multiplier: 1.5, sizeX: 9, sizeZ: 8 },
        e: { multiplier: 1.5, sizeX: 10, sizeZ: 8 },
        f: { multiplier: 2, sizeX: 11, sizeZ: 8 },
        g: { multiplier: 2.5, sizeX: 12, sizeZ: 8 },
        h: { multiplier: 3, sizeX: 13, sizeZ: 8 },
        i: { multiplier: 4, sizeX: 15, sizeZ: 8 },
    };
    const dropdown = inputDropdown("difficulty", TRANSLATE$1("jig_ccomp:minesweeper.select_difficulty", "\n"))
        .addOption(TRANSLATE$1("jig_ccomp:butt.sweeper_start_0"), "a")
        .addOption(TRANSLATE$1("jig_ccomp:butt.sweeper_start_2"), "b")
        .addOption(TRANSLATE$1("jig_ccomp:butt.sweeper_start_3"), "c")
        .addOption(TRANSLATE$1("jig_ccomp:butt.sweeper_start_4"), "d")
        .addOption(TRANSLATE$1("jig_ccomp:butt.sweeper_start_5"), "e")
        .addOption(TRANSLATE$1("jig_ccomp:butt.sweeper_start_6"), "f")
        .addOption(TRANSLATE$1("jig_ccomp:butt.sweeper_start_7"), "g")
        .addOption(TRANSLATE$1("jig_ccomp:butt.sweeper_start_8"), "h")
        .addOption(TRANSLATE$1("jig_ccomp:butt.sweeper_start_9"), "i");
    const dialogue = inputScriptDialogue(TRANSLATE$1("jig_ccomp:minesweeper.select_difficulty.title"))
        .withSubmitButton(TRANSLATE$1("jig_ccomp:minesweeper.submit_difficulty"))
        .addElement(dropdown);
    const response = await lockMovementWhile(player, async () => {
        return await dialogue.open({ player });
    });
    if (!(response instanceof InputScriptDialogueResponse)) {
        return undefined; // <- return undefined if cancelled
    }
    const difficulty = response.values.difficulty;
    const config = difficultyConfig[difficulty] ?? difficultyConfig["a"];
    return {
        difficulty,
        ...config,
    };
};
const newGame = (sizeX, sizeZ, multiplier) => {
    return new Minesweeper(sizeZ, sizeX, Math.ceil(sizeZ * sizeX * 0.1 * multiplier));
};
const openMineSweeper = async (player, sizeX, sizeZ, multiplier, computer, difficulty, event) => {
    let minesweeper = newGame(sizeX, sizeZ, multiplier);
    while (true) {
        const board = boardToRawMessage(minesweeper, false);
        let rowDropdown = inputDropdown("row", TRANSLATE$1("jig_ccomp:minesweeper.row"));
        for (let i = 0; i < minesweeper.rows; ++i) {
            rowDropdown = rowDropdown.addOption(TEXT(`${indexToRow(i)}`), i);
        }
        const response = await lockMovementWhile(player, async () => {
            return await inputScriptDialogue(TRANSLATE$1(`jig_ccomp:minesweeper.title${multiplier}`))
                .addElement(inputDropdown("action", RAW_TEXT(...board))
                .addOption(TRANSLATE$1("jig_ccomp:minesweeper.action.open"), "open")
                .addOption(TRANSLATE$1("jig_ccomp:minesweeper.action.flag"), "flag")
                .addOption(TRANSLATE$1("jig_ccomp:minesweeper.action.quit"), "quit"))
                .addElement(inputSlider("column", TRANSLATE$1("jig_ccomp:minesweeper.column"), 1, minesweeper.columns, 1, 1))
                .addElement(rowDropdown)
                .open({
                player,
                ...defaultScriptDialogueOptions,
            });
        });
        if (response instanceof InputScriptDialogueResponse) {
            let action;
            if (response.values.action === "open") {
                action = MinesweeperAction.OPEN;
            }
            else if (response.values.action === "flag") {
                action = MinesweeperAction.FLAG;
            }
            else {
                break;
            }
            const outcome = minesweeper.playTurn(response.values.row, response.values.column - 1, action, player);
            let score;
            switch (difficulty) {
                case "a":
                    score = "";
                    break;
                case "b":
                    score = "";
                    break;
                case "c":
                    score = "";
                    break;
                case "d":
                    score = "";
                    break;
                case "e":
                    score = "_u";
                    break;
                case "f":
                    score = "_u";
                    break;
                case "g":
                    score = "_u";
                    break;
                case "h":
                    score = "_u";
                    break;
                case "i":
                    score = "_i";
                    break;
                default:
                    score = "";
                    break;
            }
            if (outcome === MinesweeperOutcome.PLAYING) {
                const worldSoundOptions = {
                    pitch: 1.0,
                    volume: 0.5,
                };
                player.playSound("random.pop2", worldSoundOptions);
                continue;
            }
            else {
                if (outcome === MinesweeperOutcome.LOST) {
                    world.scoreboard
                        .getObjective("jig_ccomp:jig_computer.addon_stats")
                        ?.addScore(`jig_ccomp:tnt_sweeper${score}_lost`, 1);
                    if (computer) {
                        computer.computer.dimension.spawnParticle("minecraft:large_explosion", computer.computer.location);
                        computer.computer.dimension.spawnParticle("minecraft:lava_particle", computer.computer.location);
                    }
                    else {
                        player.dimension.spawnParticle("minecraft:large_explosion", player.location);
                        player.dimension.spawnParticle("minecraft:lava_particle", player.location);
                    }
                    player.playSound("random.explode");
                }
                else {
                    world.scoreboard
                        .getObjective("jig_ccomp:jig_computer.addon_stats")
                        ?.addScore(`jig_ccomp:tnt_sweeper${score}_won`, 1);
                    player.playSound("random.levelup");
                }
                let finishResponse;
                if (outcome === MinesweeperOutcome.WON) {
                    finishResponse = await lockMovementWhile(player, async () => {
                        return await multiButtonScriptDialogue(TRANSLATE$1(`jig_ccomp:minesweeper.finish.title${multiplier}`))
                            .setBody(RAW_TEXT(TRANSLATE$1(`jig_ccomp:minesweeper.finish.body-${outcome}`), TEXT("\n"), ...boardToRawMessage(minesweeper, true)))
                            .addButton("play", TRANSLATE$1("jig_ccomp:minesweeper.finish.play"), "textures/jig/ccomp/phone/apps/tnt.png")
                            .addButton("print", TRANSLATE$1("jig_ccomp:minesweeper.finish.print"), "textures/jig/ccomp/myui/print_reward.png")
                            .addButton("quit", TRANSLATE$1("jig_ccomp:minesweeper.finish.quit"))
                            .open({
                            player,
                            ...defaultScriptDialogueOptions,
                        });
                    });
                }
                else {
                    finishResponse = await lockMovementWhile(player, async () => {
                        return await multiButtonScriptDialogue(TRANSLATE$1(`jig_ccomp:minesweeper.finish.title${multiplier}`))
                            .setBody(RAW_TEXT(TRANSLATE$1(`jig_ccomp:minesweeper.finish.body-${outcome}`), TEXT("\n"), ...boardToRawMessage(minesweeper, true)))
                            .addButton("play", TRANSLATE$1("jig_ccomp:minesweeper.finish.play"), "textures/jig/ccomp/phone/apps/tnt.png")
                            .addButton("quit", TRANSLATE$1("jig_ccomp:minesweeper.finish.quit"))
                            .open({
                            player,
                            ...defaultScriptDialogueOptions,
                        });
                    });
                }
                if (finishResponse instanceof ButtonDialogueResponse) {
                    if (finishResponse.selected === "play") {
                        minesweeper = newGame(sizeX, sizeZ, multiplier);
                        continue;
                    }
                    if (finishResponse.selected === "print") {
                        let paper, message;
                        switch (difficulty) {
                            case "a":
                                paper = "jig_ccomp:printed_paper";
                                message = "Simple, but you did it!";
                                break;
                            case "b":
                                paper = "jig_ccomp:tnt_paper_1";
                                message = "Difficulty: Easy!";
                                break;
                            case "c":
                                paper = "jig_ccomp:tnt_paper_1";
                                message = "Difficulty: Medium!";
                                break;
                            case "d":
                                paper = "jig_ccomp:tnt_paper_1";
                                message = "Difficulty: Hard!";
                                break;
                            case "e":
                                paper = "jig_ccomp:tnt_paper_2";
                                message = "Difficulty: Very Hard!";
                                break;
                            case "f":
                                paper = "jig_ccomp:tnt_paper_2";
                                message = "Difficulty: Extreme!";
                                break;
                            case "g":
                                paper = "jig_ccomp:tnt_paper_2";
                                message = "Difficulty: Ultimate!";
                                break;
                            case "h":
                                paper = "jig_ccomp:tnt_paper_2";
                                message = "Difficulty: Ultimate +!";
                                break;
                            case "i":
                                paper = "jig_ccomp:tnt_paper_3";
                                message = "Difficulty: Impossible!";
                                break;
                            default:
                                paper = "jig_ccomp:tnt_paper_1";
                                message = "Unknown Difficulty!";
                                break;
                        }
                        const printContentError = await printContent(player.name + `'s §eTNT Sweeper Award`, `This certifies that you completed TNT Sweeper! ${message}`, computer, player, paper);
                        if (computer) {
                            computer.computer.runCommand("/event entity @s jig_ccomp:typing");
                        }
                        else if (printContentError === 'quit' && 'closeApp' in event) {
                            event.closeApp = true;
                        }
                        break;
                    }
                    if (finishResponse.selected === "quit") {
                        if ('closeApp' in event) {
                            event.closeApp = true;
                        }
                    }
                }
            }
        }
        break;
    }
};

class MinesweeperPhoneApp extends PhoneApp {
    static COMPONENT_ID = 'tnt';
    constructor() {
        super(MinesweeperPhoneApp.COMPONENT_ID);
    }
    async onSelected(event) {
        await this.openApp(event);
    }
    async onAction(event) {
        await this.openApp(event);
    }
    async openApp(event) {
        event.cancel = true;
        await initMineSweeperCrossPlatform(event);
    }
}

class NoiseMakerPhoneApp extends PhoneApp {
    phonesettings;
    static COMPONENT_ID = "sound";
    constructor(phonesettings) {
        super(NoiseMakerPhoneApp.COMPONENT_ID);
        this.phonesettings = phonesettings;
    }
    async onSelected(event) {
        await this.openApp(event);
    }
    async onAction(event) {
        await this.openApp(event);
    }
    async openApp(phoneEvent) {
        phoneEvent.cancel = true;
        const player = phoneEvent.player;
        await renderLoop(player, noiseMakerUI, {
            close_app: async () => {
                phoneEvent.closeApp = true;
            },
            play_fart: async (event) => {
                this.playSound(player, "jig_common.fart");
                event.form = event.loadForm("main");
            },
            play_suckpop: async (event) => {
                this.playSound(player, "jig_common.suckpop");
                event.form = event.loadForm("main");
            },
            play_alarm: async (event) => {
                this.playSound(player, "jig_common.alarm");
                event.form = event.loadForm("main");
            },
            play_error: async (event) => {
                this.playSound(player, "mob.bat.death", 0.5);
                event.form = event.loadForm("main");
            },
            play_shine: async (event) => {
                this.playSound(player, "jig_common.starnoise");
                event.form = event.loadForm("main");
            },
            play_exit: async (event) => {
                this.playSound(player, "jig_common.beep_down", 0.5);
                event.form = event.loadForm("main");
            },
            play_kb: async (event) => {
                this.playSound(player, "jig_ccomp.typing");
                event.form = event.loadForm("main");
            },
        });
    }
    playSound(player, sound, pitch = 1) {
        const volume = this.phonesettings.getVolume(NoiseMakerPhoneApp.COMPONENT_ID);
        player.dimension.playSound(sound, player.location, { volume: volume, pitch });
        world.scoreboard.getObjective("jig_ccomp:jig_computer.addon_stats")?.addScore("jig_ccomp:sfx_played", 1);
    }
}
const noiseMakerUI = {
    entrypoint: "main",
    forms: {
        main: {
            type: "multi-button",
            title: _("jig_ccomp:name.sound_maker"),
            body: _("jig_ccomp:sound_maker", "\n\n", "\n\n"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:butt.fartx"),
                    icon: "textures/jig/ccomp/phone/apps/sound.png",
                    action: { event: "play_fart" },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:butt.suckp"),
                    icon: "textures/jig/ccomp/phone/apps/sound.png",
                    action: { event: "play_suckpop" },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:butt.alarm"),
                    icon: "textures/jig/ccomp/phone/apps/sound.png",
                    action: { event: "play_alarm" },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:butt.error"),
                    icon: "textures/jig/ccomp/phone/apps/sound.png",
                    action: { event: "play_error" },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:butt.shine"),
                    icon: "textures/jig/ccomp/phone/apps/sound.png",
                    action: { event: "play_shine" },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:butt.comp_exit"),
                    icon: "textures/jig/ccomp/phone/apps/sound.png",
                    action: { event: "play_exit" },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:butt.typing"),
                    icon: "textures/jig/ccomp/phone/apps/sound.png",
                    action: { event: "play_kb" },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:gui.close"),
                    action: { event: "close_app" },
                },
            ],
        },
    },
};

function checkMilestones(local, player, fieldPrefix, value, milestones) {
    for (const [threshold, message] of milestones) {
        const flag = `${fieldPrefix}${threshold}`;
        // Only trigger if the value is EXACTLY the threshold, and hasn't been triggered before
        if (value === threshold && !local[flag]) {
            local[flag] = true;
            sendMessageAppToPlayer("bug_smash", player.name, message);
        }
    }
}
const streakMilestones = [
    [100, "You've hit a 100-bug streak! You're an unstoppable force of bug destruction!"],
    [1000, "1,000 bugs... in one streak. Are you okay? Have you taken a break? Maybe blink?"],
    [10000, "10,000 bugs without missing once. This isn't a game anymore. This is obsession."],
    [100000, "100,000 in a row. That's not reflexes — that's a cry for help. Touch some grass. Please."],
    [1000000, "1 million. In a single streak. Do you even remember who you are anymore?"],
];
const totalMilestones = [
    [100, "Congrats! You've smashed 100 bugs! Keep going!"],
    [1000, "1,000 bugs down. That's... a lot of clicking. Maybe too much?"],
    [10000, "10,000 bugs obliterated. Have you considered talking to someone about this?"],
    [100000, "100,000 dead bugs. You gain nothing from this. You know that, right?"],
    [1000000, "1 million bugs. There's nothing left to prove. The bugs are gone. We're all concerned."],
];
class BugSmashApp extends PhoneApp {
    settings;
    globalSettings;
    phonesettings;
    static COMPONENT_ID = "bug_smash";
    constructor(settings, globalSettings, phonesettings) {
        super(BugSmashApp.COMPONENT_ID);
        this.settings = settings;
        this.globalSettings = globalSettings;
        this.phonesettings = phonesettings;
    }
    async onSelected(event) {
        debug("Opening BugSmash app");
        const volume = this.phonesettings.getVolume(BugSmashApp.COMPONENT_ID);
        event.player.playSound("jig_ccomp.bug_intro", { volume: volume, pitch: 1.5 });
        await this.openApp(event);
    }
    async onAction(event) {
        debug("Reopening BugSmash app");
        const volume = this.phonesettings.getVolume(BugSmashApp.COMPONENT_ID);
        event.player.playSound("jig_ccomp.bug_intro", { volume: volume, pitch: 1.5 });
        await this.openApp(event);
    }
    getData() {
        const data = this.settings.getData({
            allTimeBugsSmashed: 0,
            currentStreakSession: 0,
            currentSide: "left",
            hasHitStreak100: false,
            hasHitStreak1000: false,
            hasHitStreak10000: false,
            hasHitStreak100000: false,
            hasHitStreak1000000: false,
            hasHitTotal100: false,
            hasHitTotal1000: false,
            hasHitTotal10000: false,
            hasHitTotal100000: false,
            hasHitTotal1000000: false,
        });
        return data;
    }
    getGlobalData() {
        return this.globalSettings.getData({
            globalAllTimeBugsSmashed: 0,
            totalPlayers: 0,
        });
    }
    async openApp(event) {
        event.cancel = true;
        const player = event.player;
        const local = this.getData();
        await renderLoop(player, ui$2, {
            splash: async (e) => {
                const updatedGlobal = this.globalSettings.getData({
                    globalAllTimeBugsSmashed: 0,
                    totalPlayers: 0,
                });
                e.args.set("local", local);
                e.args.set("global", updatedGlobal);
                e.form = e.loadForm("splash");
            },
            start_game: async (e) => {
                local.currentStreakSession = 0;
                local.currentSide = "left";
                this.settings.setData(local);
                local.allTimeBugsSmashed++;
                local.currentStreakSession++;
                const updatedGlobal = this.globalSettings.getData({
                    globalAllTimeBugsSmashed: 0,
                    totalPlayers: 0,
                });
                updatedGlobal.globalAllTimeBugsSmashed++;
                if (local.allTimeBugsSmashed === 1) {
                    updatedGlobal.totalPlayers++;
                }
                checkMilestones(local, player, "hasHitTotal", local.allTimeBugsSmashed, totalMilestones);
                checkMilestones(local, player, "hasHitStreak", local.currentStreakSession, streakMilestones);
                this.settings.setData(local);
                this.globalSettings.setData(updatedGlobal);
                // update args
                e.args.set("global", updatedGlobal);
                const volume = this.phonesettings.getVolume(BugSmashApp.COMPONENT_ID);
                player.playSound("jig_ccomp.bug_hit", { volume: volume, pitch: 1.5 });
                e.args.set("local", local);
                e.form = e.loadForm("smash_left");
            },
            smash_bug: async (e) => {
                local.allTimeBugsSmashed++;
                local.currentStreakSession++;
                checkMilestones(local, player, "hasHitTotal", local.allTimeBugsSmashed, totalMilestones);
                checkMilestones(local, player, "hasHitStreak", local.currentStreakSession, streakMilestones);
                this.settings.setData(local);
                const updatedGlobal = this.globalSettings.getData({
                    globalAllTimeBugsSmashed: 0,
                    totalPlayers: 0,
                });
                updatedGlobal.globalAllTimeBugsSmashed++;
                if (local.allTimeBugsSmashed === 1) {
                    updatedGlobal.totalPlayers++;
                }
                this.globalSettings.setData(updatedGlobal);
                // update args
                e.args.set("global", updatedGlobal);
                local.currentSide = local.currentSide === "left" ? "right" : "left";
                this.settings.setData(local);
                const volume = this.phonesettings.getVolume(BugSmashApp.COMPONENT_ID);
                player.playSound("jig_ccomp.bug_hit", { volume: volume });
                e.args.set("local", local);
                e.form = e.loadForm(local.currentSide === "left" ? "smash_left" : "smash_right");
            },
            close_app: async (e) => {
                event.closeApp = true;
            },
        });
    }
}
const ui$2 = {
    entrypoint: "splash",
    forms: {
        splash: {
            type: "multi-button",
            title: _("jig_ccomp:start_bug_smash_infinite.actual.title"),
            body: [
                _("jig_ccomp:start_bug_smash_infinite.title"),
                '§n\n         \\(")/         \\(")/\n         -( )-          -( )-\n         /(_)\\         /(_)\\\n\n§r',
                _("jig_ccomp:start_bug_smash_infinite"),
            ],
            elements: [
                {
                    type: "button",
                    text: "Start Smashing",
                    icon: "textures/jig/ccomp/phone/apps/bug_smash",
                    action: { event: "start_game" },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:gui.close"),
                    action: { event: "close_app" },
                },
            ],
        },
        smash_left: {
            type: "multi-button",
            title: _("jig_ccomp:start_bug_smash_infinite.actual.title"),
            body: [
                '§n\n                           \\(")/\n                           -( )-\n         §4\\@@@/§n          /(_)\\\n§r',
                "\n§aCurrent Streak: {local.currentStreakSession}",
                "\n§cSmashed: {local.allTimeBugsSmashed}",
                "\n§6Global: {global.globalAllTimeBugsSmashed}",
            ],
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:butt.old_pc_hitl"),
                    icon: "textures/jig/ccomp/phone/apps/bug_smash",
                    action: { event: "smash_bug" },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:gui.close"),
                    action: { event: "close_app" },
                },
            ],
        },
        smash_right: {
            type: "multi-button",
            title: _("jig_ccomp:start_bug_smash_infinite.actual.title"),
            body: [
                '§n\n         \\(")/\n         -( )-\n         /(_)\\          §4\\@@@/\n§r',
                "\n§aCurrent Streak: {local.currentStreakSession}",
                "\n§cSmashed: {local.allTimeBugsSmashed}",
                "\n§6Global: {global.globalAllTimeBugsSmashed}",
            ],
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:butt.old_pc_hitl"),
                    icon: "textures/jig/ccomp/phone/apps/bug_smash",
                    action: { event: "smash_bug" },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:gui.close"),
                    action: { event: "close_app" },
                },
            ],
        },
    },
};

const eightBallResponseKeys = [
    "jig_ccomp:eightball.response.1",
    "jig_ccomp:eightball.response.2",
    "jig_ccomp:eightball.response.3",
    "jig_ccomp:eightball.response.4",
    "jig_ccomp:eightball.response.5",
    "jig_ccomp:eightball.response.6",
    "jig_ccomp:eightball.response.7",
    "jig_ccomp:eightball.response.8",
    "jig_ccomp:eightball.response.9",
    "jig_ccomp:eightball.response.10",
    "jig_ccomp:eightball.response.11",
    "jig_ccomp:eightball.response.12",
    "jig_ccomp:eightball.response.13",
    "jig_ccomp:eightball.response.14",
    "jig_ccomp:eightball.response.15",
    "jig_ccomp:eightball.response.16",
    "jig_ccomp:eightball.response.17",
    "jig_ccomp:eightball.response.18",
    "jig_ccomp:eightball.response.19",
    "jig_ccomp:eightball.response.20",
];
class EightBallApp extends PhoneApp {
    settings;
    globalSettings;
    phonesettings;
    static COMPONENT_ID = "eightball";
    constructor(settings, globalSettings, phonesettings) {
        super(EightBallApp.COMPONENT_ID);
        this.settings = settings;
        this.globalSettings = globalSettings;
        this.phonesettings = phonesettings;
    }
    async onSelected(event) {
        await this.openApp(event);
    }
    async onAction(event) {
        await this.openApp(event);
    }
    async openApp(event) {
        event.cancel = true;
        const player = event.player;
        await renderLoop(player, ui$1, {
            splash: async (e) => {
                // Show the splash screen
                e.form = e.loadForm("splash");
            },
            roll_ball: async (e) => {
                // Pick a random translation key from eightBallResponseKeys
                const index = Math.floor(Math.random() * eightBallResponseKeys.length);
                const responseKey = eightBallResponseKeys[index];
                // Store that key under “responseKey” so the form can interpolate it
                e.args.set("responseKey", responseKey);
                // Load the single “result” form (it will use {responseKey} in its body)
                e.form = e.loadForm("result");
            },
            back: async (e) => {
                // Return to splash
                e.form = e.loadForm("splash");
            },
            close_app: async (e) => {
                event.closeApp = true;
            }
        });
    }
}
const ui$1 = {
    entrypoint: "splash",
    forms: {
        // ── SPLASH SCREEN ──
        splash: {
            type: "multi-button",
            title: _("jig_ccomp:eightball.splash.title"),
            body: [
                _("jig_ccomp:eightball.splash.body")
            ],
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:eightball.button.roll"),
                    action: { event: "roll_ball" }
                },
                {
                    type: "button",
                    text: _("jig_ccomp:gui.close"),
                    action: { event: "close_app" }
                }
            ]
        },
        // ── SINGLE RESULT FORM ──
        // Note: we reference {responseKey} inside _("{responseKey}")
        // so that the engine will translate whatever key we stored at runtime.
        result: {
            type: "multi-button",
            title: _("jig_ccomp:eightball.result.title"),
            body: [
                _("{responseKey}")
            ],
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:eightball.button.back"),
                    action: { event: "back" }
                },
                {
                    type: "button",
                    text: _("jig_ccomp:gui.close"),
                    action: { event: "close_app" }
                }
            ]
        }
    }
};

const viewTut_Book_1 = () => {
    return multiButtonScriptDialogue(RAW_TEXT(TRANSLATE$1("jig_ccomp:book.name")))
        .setBody(RAW_TEXT(TRANSLATE$1("jig_ccomp:info_book.intro", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_book.version")))
        .addButton("page_01", TRANSLATE$1("jig_ccomp:guide_book.category_01"), "textures/jig/ccomp/items/comp/ca_egg")
        .addButton("page_02", TRANSLATE$1("jig_ccomp:guide_book.category_02"), "textures/jig/common/items/redstone_circuit")
        .addButton("page_03", TRANSLATE$1("jig_ccomp:guide_book.category_03"), "textures/jig/ccomp/myui/email_unread")
        .addButton("page_04", TRANSLATE$1("jig_ccomp:guide_book.category_04"), "textures/jig/ccomp/myui/print_reward")
        .addButton("page_05", TRANSLATE$1("jig_ccomp:guide_book.category_05"), "textures/jig/ccomp/items/comp/phone_5")
        .addButton("page_07", TRANSLATE$1("jig_ccomp:guide_book.category_07"), "textures/jig/ccomp/phone/apps/settings")
        .addButton("page_08", TRANSLATE$1("jig_ccomp:guide_book.category_08"), "textures/jig/ccomp/myui/jigarbov")
        .addButton("update", TRANSLATE$1("jig_ccomp:butt.recent_update"), "textures/jig/ccomp/items/guide_book_u")
        .addButton("exit", TRANSLATE$1("jig_ccomp:butt.old_pc_exit"));
};
const viewTut_Book_Page = (id) => {
    const contentMap = {
        "01": [
            TRANSLATE$1("jig_ccomp:guide_book.category_01.01", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_01.02", "\n"), TEXT("\n\n"),
        ],
        "02": [
            TRANSLATE$1("jig_ccomp:guide_book.category_02.01", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_02.02", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_02.03", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_02.04", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_02.05", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_02.06", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_02.07", "\n"),
        ],
        "03": [
            TRANSLATE$1("jig_ccomp:guide_book.category_03.01", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_03.02", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_03.03", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_03.04", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_03.05", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_03.06", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_03.07", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_03.08", "\n"),
        ],
        "04": [
            TRANSLATE$1("jig_ccomp:guide_book.category_04.01", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_04.02", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_04.03", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_04.04", "\n"),
        ],
        "05": [
            TRANSLATE$1("jig_ccomp:guide_book.category_05.01", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_05.02", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_05.03", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_05.04", "\n"), TEXT("\n\n"),
            TRANSLATE$1("jig_ccomp:guide_book.category_05.05", "\n"),
        ],
        "07": [
            TRANSLATE$1("jig_ccomp:guide_book.category_07.01", "\n"),
        ],
        "08": [
            TRANSLATE$1("jig_ccomp:guide_book.category_08.01", "\n"),
        ],
    };
    return multiButtonScriptDialogue(RAW_TEXT(TRANSLATE$1(`jig_ccomp:guide_book.category_${id}`)))
        .setBody(RAW_TEXT(...contentMap[id]))
        .addButton("back", TRANSLATE$1("jig_ccomp:butt.back_to_menu"));
};
const viewTut_Book_2 = () => {
    return multiButtonScriptDialogue(RAW_TEXT(TRANSLATE$1("item.jig_ccomp:guide_book_u")))
        .setBody(RAW_TEXT(TRANSLATE$1("jig_ccomp:info_u.page_b1", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b2", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b3", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b4", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b5", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b6", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b7", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b8", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b9", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b10", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b11", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b12", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b13", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b14", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b15", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b16", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b17", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b18", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b19", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b20", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_b21", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_a1", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_a2", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_a3", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_a4", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_a5", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_a6", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_01", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_02", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_03", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_04", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_05", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_06", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_07", "\n"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:info_u.page_09", "\n")))
        .addButton("exit", TRANSLATE$1("jig_ccomp:butt.old_pc_exit"));
};

const GUIDE_BOOK = "jig_ccomp:guide_book";
const GUIDE_BOOK_U = "jig_ccomp:guide_book_u";
const initTut_Book = () => {
    world.afterEvents.itemUse.subscribe(async (event) => {
        const player = event.source;
        const { itemStack } = event;
        if (itemStack.typeId === GUIDE_BOOK) {
            await openTutorialIndex(player);
        }
        if (itemStack.typeId === GUIDE_BOOK_U) {
            player.playSound("jig_common.beeps.say");
            const response = await viewTut_Book_2().open({ ...defaultScriptDialogueOptions, player });
            if (response instanceof InputScriptDialogueResponse) {
                player.playSound("jig_common.beeps.say");
            }
        }
    });
};
async function openTutorialIndex(player) {
    player.playSound("jig_common.beeps.say");
    const response = await viewTut_Book_1().open({ ...defaultScriptDialogueOptions, player });
    if (response instanceof ButtonDialogueResponse) {
        player.playSound("jig_common.beeps.say");
        if (response.selected === "update") {
            await viewTut_Book_2().open({ ...defaultScriptDialogueOptions, player });
        }
        else if (response.selected?.startsWith("page_")) {
            const id = response.selected.replace("page_", "");
            await openTutorialPage(player, id);
        }
    }
}
async function openTutorialPage(player, id) {
    const response = await viewTut_Book_Page(id).open({ ...defaultScriptDialogueOptions, player });
    if (response instanceof ButtonDialogueResponse && response.selected === "back") {
        await openTutorialIndex(player);
    }
}
class TutBookPhoneApp extends PhoneApp {
    static COMPONENT_ID = "tut_book";
    constructor() {
        super(TutBookPhoneApp.COMPONENT_ID);
    }
    async onSelected(event) {
        await this.openApp(event);
    }
    async onAction(event) {
        await this.openApp(event);
    }
    async openApp(phoneEvent) {
        phoneEvent.cancel = true;
        await this.openTutorialIndex(phoneEvent.player, phoneEvent);
    }
    async openTutorialIndex(player, phoneEvent) {
        const response = await viewTut_Book_1().open({ ...defaultScriptDialogueOptions, player });
        if (response instanceof ButtonDialogueResponse) {
            if (response.selected === "update") {
                await viewTut_Book_2().open({ ...defaultScriptDialogueOptions, player });
            }
            else if (response.selected?.startsWith("page_")) {
                const id = response.selected.replace("page_", "");
                await this.openTutorialPage(player, id, phoneEvent);
            }
            else if (response.selected === "exit") {
                phoneEvent.closeApp = true;
            }
        }
    }
    async openTutorialPage(player, id, phoneEvent) {
        const response = await viewTut_Book_Page(id).open({ ...defaultScriptDialogueOptions, player });
        if (response instanceof ButtonDialogueResponse && response.selected === "back") {
            await this.openTutorialIndex(player, phoneEvent);
        }
    }
}

const AVAILABLE_APPS = [
    BankingApp.COMPONENT_ID,
    BugSmashApp.COMPONENT_ID,
    //ForumPhoneApp.COMPONENT_ID,
    TutBookPhoneApp.COMPONENT_ID,
    EightBallApp.COMPONENT_ID,
    MessageApp.COMPONENT_ID,
    JokeApp.COMPONENT_ID,
    NotesApp.COMPONENT_ID,
    NoiseMakerPhoneApp.COMPONENT_ID,
    TextAdventurePhoneApp.COMPONENT_ID,
    MinesweeperPhoneApp.COMPONENT_ID,
    TriviaPhoneApp.COMPONENT_ID,
    WouldYouRatherApp.COMPONENT_ID,
];
const UNAVAILABLE_APPS_COMPUTER = [
    MinesweeperPhoneApp.COMPONENT_ID,
    TriviaPhoneApp.COMPONENT_ID,
    TextAdventurePhoneApp.COMPONENT_ID,
    NoiseMakerPhoneApp.COMPONENT_ID,
];
class AppStore extends PhoneApp {
    settings;
    fromComputer;
    static COMPONENT_ID = "appstore";
    constructor(settings, fromComputer = false) {
        super(AppStore.COMPONENT_ID);
        this.settings = settings;
        this.fromComputer = fromComputer;
    }
    async onSelected(event) {
        while (true) {
            const installed = this.settings.getAppIds();
            let apps = AVAILABLE_APPS;
            if (this.fromComputer) {
                apps = AVAILABLE_APPS.filter((app) => !UNAVAILABLE_APPS_COMPUTER.includes(app) && !installed.includes(app));
            }
            else {
                apps = apps.filter((app) => !installed.includes(app));
            }
            const response = await appStore(event.player, apps);
            if (response instanceof ButtonDialogueResponse) {
                if (response.selected === "close") {
                    event.closeApp = true;
                    break;
                }
                else {
                    if (this.settings.addApp(response.selected)) {
                        const responseDownloaded = await downloaded(event.player, response.selected);
                        if (responseDownloaded instanceof ButtonDialogueResponse) {
                            if (responseDownloaded.selected === "store") {
                                event.closeApp = true;
                                continue;
                            }
                            else if (responseDownloaded.selected === "main") {
                                event.closeApp = true;
                                break;
                            }
                        }
                    }
                }
            }
            else if (response instanceof DialogueCanceledResponse) {
                event.closeApp = true;
                break;
            }
        }
    }
}
const appStore = async (player, apps) => {
    return await multiButtonScriptDialogue(TRANSLATE("jig_ccomp:phone.app.appstore.main.title"))
        .setBody(TRANSLATE("jig_ccomp:phone.app.appstore.main.body"))
        .addButtons(apps.map((app) => ({
        name: app,
        text: TRANSLATE(`jig_ccomp:phone.app.${app}.name`),
        iconPath: `textures/jig/ccomp/phone/apps/dl_${app}`,
    })))
        .addButton("close", TRANSLATE("jig_ccomp:gui.close"))
        .open({ player });
};
const downloaded = async (player, app) => {
    return await multiButtonScriptDialogue(TRANSLATE("jig_ccomp:phone.app.appstore.main.title"))
        .setBody(RAW_TEXT({ text: "\n" }, { translate: "jig_ccomp:phone.app.downloaded.main.body" }, { translate: `jig_ccomp:phone.app.${app}.name` }, { translate: "jig_ccomp:phone.app.downloaded.main.body_second" }, { text: "\n\n" }))
        .addButton("store", TRANSLATE("jig_ccomp:phone.app.store"), `textures/jig/ccomp/phone/apps/appstore`)
        .addButton("main", TRANSLATE("jig_ccomp:phone.app.main.menu"))
        .open({ player });
};

const PREFILLED_SUBJECT_PREFIX = 'jig_ccomp:jig.prefilled_il.subj_';
const PREFILLED_SUBJECT_COUNT = 12;
const PREFILLED_MESSAGE_PREFIX = 'jig_ccomp:jig.prefilled_il.body_';
const PREFILLED_MESSAGE_COUNT = 72;
const sendEmailDialogue = (targets, attachments, to, subject, usePredefinedContent) => {
    let toElement = inputDropdown("to", TRANSLATE$1("jig_ccomp:pc-email-send.inputs.to.label"));
    targets.forEach(t => {
        toElement = toElement.addOption(t.name, t.id);
    });
    const toIndex = targets.findIndex(t => t.id === to);
    toElement = toElement.setDefaultValueIndex(toIndex === -1 ? 0 : toIndex);
    let attachmentElement = inputDropdown("attachment", TRANSLATE$1("jig_ccomp:pc-email-send.inputs.attachment.label"));
    attachmentElement = attachmentElement.addOption(TRANSLATE$1("jig_ccomp:pc-email-send.inputs.attachment.none"), "none");
    attachments.forEach((t, index) => {
        attachmentElement = attachmentElement.addOption(RAW_TEXT(t.item.nameTag ? TEXT(t.item.nameTag) : ITEM(t.item), TEXT(` ${t.item.isStackable ? `x${t.item.amount}` : ''}`.trimEnd())), index.toString());
    });
    attachmentElement = attachmentElement.setDefaultValueIndex(0);
    let subjectDropdown = inputDropdown("subject", TRANSLATE$1("jig_ccomp:pc-email-send.inputs.subject.label"));
    for (let i = 0; i < PREFILLED_SUBJECT_COUNT; ++i) {
        const key = PREFILLED_SUBJECT_PREFIX + i.toString().padStart(2, "0");
        subjectDropdown = subjectDropdown.addOption(TRANSLATE$1(key), key);
    }
    let messageDropdown = inputDropdown("message", TRANSLATE$1("jig_ccomp:pc-email-send.inputs.message.label"));
    for (let i = 0; i < PREFILLED_MESSAGE_COUNT; ++i) {
        const key = PREFILLED_MESSAGE_PREFIX + i.toString().padStart(2, "0");
        messageDropdown = messageDropdown.addOption(TRANSLATE$1(key), key);
    }
    return inputScriptDialogue(TRANSLATE$1("jig_ccomp:pc-email-send.title"))
        .addElement(toElement)
        .addElement(attachmentElement)
        .addElement(usePredefinedContent ? subjectDropdown :
        inputText("subject", TRANSLATE$1("jig_ccomp:pc-email-send.inputs.subject.label"), TRANSLATE$1("jig_ccomp:pc-email-send.inputs.subject.placeholder"), subject))
        .addElement(usePredefinedContent ? messageDropdown :
        inputText("message", TRANSLATE$1("jig_ccomp:pc-email-send.inputs.message.label"), TRANSLATE$1("jig_ccomp:pc-email-send.inputs.message.placeholder")));
};

const readEmailDialogue = (emails, player, computer) => {
    return multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:pc-email-read.title"))
        .setBody(TRANSLATE$1("jig_ccomp:pc-email-read.body"))
        .addButtons(emails.map(e => ({
        name: e.id,
        text: RAW_TEXT(TEXT_OR_RAW_TEXT(e.from_player), TEXT(": "), TEXT_OR_RAW_TEXT(e.subject)),
        iconPath: emailIcon(e),
        callback: async (selected) => {
            computer.computer.triggerEvent('jig_ccomp:typing');
            const response = await dualButtonScriptDialogue(RAW_TEXT(TEXT("Subject: "), TEXT_OR_RAW_TEXT(e.subject)), {
                name: "more",
                text: TRANSLATE$1("jig_ccomp:pc-email-read.button.more"),
                callback: async (selected) => {
                    computer.computer.triggerEvent('jig_ccomp:typing');
                    const buttons = [];
                    if (e.sender_type !== "script" && e.sender_type !== "system") {
                        buttons.push({
                            name: "reply-custom",
                            text: TRANSLATE$1("jig_ccomp:pc-email-read-more.button.reply-custom"),
                            iconPath: "textures/jig/ccomp/myui/reply.png"
                        });
                        buttons.push({
                            name: "reply",
                            text: TRANSLATE$1("jig_ccomp:pc-email-read-more.button.reply"),
                            iconPath: "textures/jig/ccomp/myui/reply.png"
                        });
                    }
                    if (e.printable) {
                        buttons.push({
                            name: "print",
                            text: TRANSLATE$1("jig_ccomp:pc-email-read-more.button.print"),
                            iconPath: "textures/jig/ccomp/myui/print.png"
                        });
                    }
                    if (e.attachment !== undefined && e.attachment !== -1) {
                        buttons.push({
                            name: "download",
                            text: TRANSLATE$1("jig_ccomp:pc-email-read-more.button.download"),
                            iconPath: "textures/jig/ccomp/myui/attachment.png"
                        });
                    }
                    buttons.push({
                        name: "delete",
                        text: TRANSLATE$1("jig_ccomp:pc-email-read-more.button.delete"),
                        iconPath: "textures/jig/ccomp/myui/trash.png"
                    });
                    if (isEmailBlockeable(e)) {
                        buttons.push({
                            name: "block",
                            text: TRANSLATE$1("jig_ccomp:pc-email-read-more.button.block"),
                            iconPath: "textures/jig/ccomp/myui/block.png"
                        });
                    }
                    buttons.push({
                        name: "close",
                        text: TRANSLATE$1("jig_ccomp:pc-email-read.button.close")
                    });
                    const moreResponse = await multiButtonScriptDialogue(RAW_TEXT(TEXT("Subject: "), TEXT_OR_RAW_TEXT(e.subject)))
                        .setBody(TRANSLATE$1("jig_ccomp:pc-email-read-more.body"))
                        .addButtons(buttons)
                        .open({
                        ...defaultScriptDialogueOptions,
                        player
                    });
                    if (moreResponse instanceof ButtonDialogueResponse) {
                        return moreResponse.selected;
                    }
                }
            }, {
                name: "close",
                text: TRANSLATE$1("jig_ccomp:pc-email-read.button.close")
            })
                .setBody(RAW_TEXT(TRANSLATE$1("jig_ccomp:email.from"), TEXT(": "), TEXT_OR_RAW_TEXT(e.from_player), TEXT("\n"), TRANSLATE$1("jig_ccomp:email.mailed-by"), TEXT(": "), TEXT_OR_RAW_TEXT(e.from_computer_name), TEXT("\n"), ...getAttachmentContent(e), TEXT("\n"), TEXT_OR_RAW_TEXT(e.message)))
                .open({
                ...defaultScriptDialogueOptions,
                player
            });
            if (response instanceof ButtonDialogueResponse) {
                return response.callback;
            }
        }
    })));
};
const getAttachmentContent = (email) => {
    switch (email.attachment) {
        case undefined:
            return [];
        case -1:
            return [TRANSLATE$1('jig_ccomp:email.attachment-downloaded')];
        default:
            return [TRANSLATE$1('jig_ccomp:email.attachment')];
    }
};
const emailIcon = (email) => {
    const hasAttachment = email.attachment !== undefined && email.attachment >= 0;
    if (email.isRead) {
        if (hasAttachment) {
            return "textures/jig/ccomp/myui/email_read_a.png";
        }
        return "textures/jig/ccomp/myui/email_read.png";
    }
    if (hasAttachment) {
        return "textures/jig/ccomp/myui/email_unread_a.png";
    }
    return "textures/jig/ccomp/myui/email_unread.png";
};
const isEmailBlockeable = (email) => {
    if (email.sender_type === "system") {
        return false;
    }
    if (email.sender_type === "npc") {
        if (email.from_player_id === Config.JigarBoxNpcId) {
            return false;
        }
    }
    return true;
};

//dont fix my formatting, it makes it easier to copy and paste all the strings of the messages
const npcRecipients = { Sword_PC: { name: TRANSLATE$1("entity.villager.weapon"), introduction: { message: TRANSLATE$1("jig_ccomp:weapon.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:weapon.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:weapon.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:weapon.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:weapon.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:weapon.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:weapon.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:weapon.randomx.0.message") },
            { message: TRANSLATE$1("jig_ccomp:weapon.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:weapon.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:weapon.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:weapon.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:weapon.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:weapon.message.0.message") },
            { message: TRANSLATE$1("jig_ccomp:weapon.message.1.message"), attachment: ["minecraft:coal", 8] },
            { message: TRANSLATE$1("jig_ccomp:weapon.message.2.message"), attachment: ["minecraft:stone_axe", 1] },
            { message: TRANSLATE$1("jig_ccomp:weapon.message.3.message") },
            { message: TRANSLATE$1("jig_ccomp:weapon.message.4.message"), attachment: ["minecraft:stone_shovel", 1] },
            { message: TRANSLATE$1("jig_ccomp:weapon.message.5.message") },
            { message: TRANSLATE$1("jig_ccomp:weapon.message.6.message") },
            { message: TRANSLATE$1("jig_ccomp:weapon.message.7.message") },
            { message: TRANSLATE$1("jig_ccomp:weapon.message.8.message"), attachment: ["minecraft:diamond_sword", 1] },
        ] }, Moobile_Device: { name: TRANSLATE$1("entity.cow.name"), introduction: { message: TRANSLATE$1("jig_ccomp:cowxxx.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:cowxxx.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:cowxxx.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:cowxxx.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:cowxxx.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:cowxxx.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:cowxxx.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:cowxxx.randomx.0.message") },
            { message: TRANSLATE$1("jig_ccomp:cowxxx.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:cowxxx.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:cowxxx.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:cowxxx.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:cowxxx.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:cowxxx.message.0.message") },
            { message: TRANSLATE$1("jig_ccomp:cowxxx.message.1.message") },
            { message: TRANSLATE$1("jig_ccomp:cowxxx.message.2.message"), attachment: ["minecraft:milk_bucket", 1] },
            { message: TRANSLATE$1("jig_ccomp:cowxxx.message.3.message") },
            { message: TRANSLATE$1("jig_ccomp:cowxxx.message.4.message") },
            { message: TRANSLATE$1("jig_ccomp:cowxxx.message.5.message") },
            { message: TRANSLATE$1("jig_ccomp:cowxxx.message.6.message") },
            { message: TRANSLATE$1("jig_ccomp:cowxxx.message.7.message") },
            { message: TRANSLATE$1("jig_ccomp:cowxxx.message.8.message"), attachment: ["minecraft:beef", 3] },
        ] }, brAinMD: { name: TRANSLATE$1("entity.zombie.name"), introduction: { message: TRANSLATE$1("jig_ccomp:zombie.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:zombie.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:zombie.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:zombie.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:zombie.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:zombie.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:zombie.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:zombie.randomx.0.message") },
            { message: TRANSLATE$1("jig_ccomp:zombie.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:zombie.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:zombie.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:zombie.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:zombie.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:zombie.message.0.message") },
            { message: TRANSLATE$1("jig_ccomp:zombie.message.1.message"), attachment: ["minecraft:rotten_flesh", 1] },
            { message: TRANSLATE$1("jig_ccomp:zombie.message.2.message") },
            { message: TRANSLATE$1("jig_ccomp:zombie.message.3.message") },
            { message: TRANSLATE$1("jig_ccomp:zombie.message.4.message") },
            { message: TRANSLATE$1("jig_ccomp:zombie.message.5.message") },
            { message: TRANSLATE$1("jig_ccomp:zombie.message.6.message"), attachment: ["minecraft:iron_shovel", 1] },
            { message: TRANSLATE$1("jig_ccomp:zombie.message.7.message") },
            { message: TRANSLATE$1("jig_ccomp:zombie.message.8.message") },
        ] }, SuperHot: { name: TRANSLATE$1("entity.blaze.name"), introduction: { message: TRANSLATE$1("jig_ccomp:blazex.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:blazex.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:blazex.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:blazex.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:blazex.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:blazex.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:blazex.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:blazex.randomx.0.message"), attachment: ["minecraft:blaze_rod", 1] },
            { message: TRANSLATE$1("jig_ccomp:blazex.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:blazex.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:blazex.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:blazex.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:blazex.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:blazex.message.0.message") },
            { message: TRANSLATE$1("jig_ccomp:blazex.message.1.message") },
            { message: TRANSLATE$1("jig_ccomp:blazex.message.2.message"), attachment: ["minecraft:sugar", 1] },
            { message: TRANSLATE$1("jig_ccomp:blazex.message.3.message") },
            { message: TRANSLATE$1("jig_ccomp:blazex.message.4.message") },
            { message: TRANSLATE$1("jig_ccomp:blazex.message.5.message"), attachment: ["minecraft:bread", 4] },
            { message: TRANSLATE$1("jig_ccomp:blazex.message.6.message"), attachment: ["minecraft:cooked_cod", 1] },
            { message: TRANSLATE$1("jig_ccomp:blazex.message.7.message") },
            { message: TRANSLATE$1("jig_ccomp:blazex.message.8.message"), attachment: ["minecraft:cooked_porkchop", 2] },
        ] }, PigC: { name: TRANSLATE$1("entity.piglin.name"), introduction: { message: TRANSLATE$1("jig_ccomp:piglin.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:piglin.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:piglin.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:piglin.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:piglin.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:piglin.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:piglin.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:piglin.randomx.0.message") },
            { message: TRANSLATE$1("jig_ccomp:piglin.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:piglin.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:piglin.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:piglin.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:piglin.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:piglin.message.0.message") },
            { message: TRANSLATE$1("jig_ccomp:piglin.message.1.message") },
            { message: TRANSLATE$1("jig_ccomp:piglin.message.2.message"), attachment: ["minecraft:gold_nugget", 1] },
            { message: TRANSLATE$1("jig_ccomp:piglin.message.3.message") },
            { message: TRANSLATE$1("jig_ccomp:piglin.message.4.message"), attachment: ["minecraft:golden_sword", 1] },
            { message: TRANSLATE$1("jig_ccomp:piglin.message.5.message"), attachment: ["minecraft:golden_boots", 1] },
            { message: TRANSLATE$1("jig_ccomp:piglin.message.6.message"), attachment: ["minecraft:gilded_blackstone", 3] },
            { message: TRANSLATE$1("jig_ccomp:piglin.message.7.message") },
            { message: TRANSLATE$1("jig_ccomp:piglin.message.8.message") },
        ] }, xXBuffagerXx: { name: TRANSLATE$1("entity.pillager.name"), introduction: { message: TRANSLATE$1("jig_ccomp:illage.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:illage.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:illage.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:illage.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:illage.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:illage.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:illage.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:illage.randomx.0.message") },
            { message: TRANSLATE$1("jig_ccomp:illage.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:illage.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:illage.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:illage.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:illage.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:illage.message.0.message"), attachment: ["minecraft:saddle", 1] },
            { message: TRANSLATE$1("jig_ccomp:illage.message.1.message"), attachment: ["minecraft:iron_sword", 1] },
            { message: TRANSLATE$1("jig_ccomp:illage.message.2.message") },
            { message: TRANSLATE$1("jig_ccomp:illage.message.3.message") },
            { message: TRANSLATE$1("jig_ccomp:illage.message.4.message"), attachment: ["minecraft:flower_banner_pattern", 1] },
            { message: TRANSLATE$1("jig_ccomp:illage.message.5.message") },
            { message: TRANSLATE$1("jig_ccomp:illage.message.6.message"), attachment: ["minecraft:bell", 1] },
            { message: TRANSLATE$1("jig_ccomp:illage.message.7.message") },
            { message: TRANSLATE$1("jig_ccomp:illage.message.8.message"), attachment: ["minecraft:totem_of_undying", 1] },
        ] }, ManeFrame: { name: TRANSLATE$1("entity.horse.name"), introduction: { message: TRANSLATE$1("jig_ccomp:horsex.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:horsex.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:horsex.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:horsex.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:horsex.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:horsex.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:horsex.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:horsex.randomx.0.message") },
            { message: TRANSLATE$1("jig_ccomp:horsex.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:horsex.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:horsex.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:horsex.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:horsex.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:horsex.message.0.message") },
            { message: TRANSLATE$1("jig_ccomp:horsex.message.1.message"), attachment: ["minecraft:sugar", 1] },
            { message: TRANSLATE$1("jig_ccomp:horsex.message.2.message"), attachment: ["minecraft:apple", 5] },
            { message: TRANSLATE$1("jig_ccomp:horsex.message.3.message") },
            { message: TRANSLATE$1("jig_ccomp:horsex.message.4.message") },
            { message: TRANSLATE$1("jig_ccomp:horsex.message.5.message"), attachment: ["minecraft:hay_block", 10] },
            { message: TRANSLATE$1("jig_ccomp:horsex.message.6.message"), attachment: ["minecraft:saddle", 1] },
            { message: TRANSLATE$1("jig_ccomp:horsex.message.7.message"), attachment: ["minecraft:wheat", 15] },
            { message: TRANSLATE$1("jig_ccomp:horsex.message.8.message"), attachment: ["minecraft:leather_horse_armor", 1] },
        ] }, RuggedPC: { name: TRANSLATE$1("entity.llama.name"), introduction: { message: TRANSLATE$1("jig_ccomp:llamax.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:llamax.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:llamax.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:llamax.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:llamax.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:llamax.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:llamax.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:llamax.randomx.0.message") },
            { message: TRANSLATE$1("jig_ccomp:llamax.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:llamax.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:llamax.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:llamax.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:llamax.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:llamax.message.0.message"), attachment: ["minecraft:red_carpet", 1] },
            { message: TRANSLATE$1("jig_ccomp:llamax.message.1.message"), attachment: ["minecraft:chest", 1] },
            { message: TRANSLATE$1("jig_ccomp:llamax.message.2.message"), attachment: ["minecraft:emerald", 2] },
            { message: TRANSLATE$1("jig_ccomp:llamax.message.3.message") },
            { message: TRANSLATE$1("jig_ccomp:llamax.message.4.message"), attachment: ["minecraft:hay_block", 1] },
            { message: TRANSLATE$1("jig_ccomp:llamax.message.5.message") },
            { message: TRANSLATE$1("jig_ccomp:llamax.message.6.message"), attachment: ["minecraft:lead", 1] },
            { message: TRANSLATE$1("jig_ccomp:llamax.message.7.message") },
            { message: TRANSLATE$1("jig_ccomp:llamax.message.8.message"), attachment: ["minecraft:acacia_fence", 1] },
        ] }, WaterCooled: { name: TRANSLATE$1("entity.camel.name"), introduction: { message: TRANSLATE$1("jig_ccomp:camelx.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:camelx.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:camelx.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:camelx.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:camelx.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:camelx.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:camelx.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:camelx.randomx.0.message") },
            { message: TRANSLATE$1("jig_ccomp:camelx.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:camelx.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:camelx.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:camelx.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:camelx.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:camelx.message.0.message") },
            { message: TRANSLATE$1("jig_ccomp:camelx.message.1.message"), attachment: ["minecraft:cactus", 2] },
            { message: TRANSLATE$1("jig_ccomp:camelx.message.2.message") },
            { message: TRANSLATE$1("jig_ccomp:camelx.message.3.message"), attachment: ["minecraft:saddle", 1] },
            { message: TRANSLATE$1("jig_ccomp:camelx.message.4.message"), attachment: ["minecraft:lead", 1] },
            { message: TRANSLATE$1("jig_ccomp:camelx.message.5.message") },
            { message: TRANSLATE$1("jig_ccomp:camelx.message.6.message") },
            { message: TRANSLATE$1("jig_ccomp:camelx.message.7.message"), attachment: ["minecraft:bamboo_fence", 1] },
            { message: TRANSLATE$1("jig_ccomp:camelx.message.8.message") },
        ] }, Croak102: { name: TRANSLATE$1("entity.frog.name"), introduction: { message: TRANSLATE$1("jig_ccomp:frogxx.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:frogxx.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:frogxx.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:frogxx.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:frogxx.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:frogxx.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:frogxx.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:frogxx.randomx.0.message") },
            { message: TRANSLATE$1("jig_ccomp:frogxx.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:frogxx.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:frogxx.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:frogxx.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:frogxx.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:frogxx.message.0.message") },
            { message: TRANSLATE$1("jig_ccomp:frogxx.message.1.message") },
            { message: TRANSLATE$1("jig_ccomp:frogxx.message.2.message"), attachment: ["minecraft:slime_ball", 1] },
            { message: TRANSLATE$1("jig_ccomp:frogxx.message.3.message"), attachment: ["minecraft:waterlily", 1] },
            { message: TRANSLATE$1("jig_ccomp:frogxx.message.4.message"), attachment: ["minecraft:big_dropleaf", 1] },
            { message: TRANSLATE$1("jig_ccomp:frogxx.message.5.message") },
            { message: TRANSLATE$1("jig_ccomp:frogxx.message.6.message"), attachment: ["minecraft:verdant_froglight", 1] },
            { message: TRANSLATE$1("jig_ccomp:frogxx.message.7.message") },
            { message: TRANSLATE$1("jig_ccomp:frogxx.message.8.message"), attachment: ["minecraft:bucket", 1] },
        ] }, Newton: { name: TRANSLATE$1("entity.axolotl.name"), introduction: { message: TRANSLATE$1("jig_ccomp:axolot.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:axolot.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:axolot.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:axolot.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:axolot.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:axolot.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:axolot.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:axolot.randomx.0.message") },
            { message: TRANSLATE$1("jig_ccomp:axolot.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:axolot.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:axolot.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:axolot.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:axolot.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:axolot.message.0.message"), attachment: ["minecraft:glow_berries", 1] },
            { message: TRANSLATE$1("jig_ccomp:axolot.message.1.message"), attachment: ["minecraft:water_bucket", 1] },
            { message: TRANSLATE$1("jig_ccomp:axolot.message.2.message") },
            { message: TRANSLATE$1("jig_ccomp:axolot.message.3.message"), attachment: ["minecraft:tropical_fish_bucket", 1] },
            { message: TRANSLATE$1("jig_ccomp:axolot.message.4.message") },
            { message: TRANSLATE$1("jig_ccomp:axolot.message.5.message"), attachment: ["minecraft:trident", 1] },
            { message: TRANSLATE$1("jig_ccomp:axolot.message.6.message") },
            { message: TRANSLATE$1("jig_ccomp:axolot.message.7.message") },
            { message: TRANSLATE$1("jig_ccomp:axolot.message.8.message") },
        ] }, DeditatedRAM: { name: TRANSLATE$1("entity.sheep.name"), introduction: { message: TRANSLATE$1("jig_ccomp:sheepx.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:sheepx.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:sheepx.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:sheepx.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:sheepx.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:sheepx.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:sheepx.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:sheepx.randomx.0.message") },
            { message: TRANSLATE$1("jig_ccomp:sheepx.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:sheepx.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:sheepx.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:sheepx.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:sheepx.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:sheepx.message.0.message"), attachment: ["minecraft:white_wool", 1] },
            { message: TRANSLATE$1("jig_ccomp:sheepx.message.1.message"), attachment: ["minecraft:cyan_dye", 1] },
            { message: TRANSLATE$1("jig_ccomp:sheepx.message.2.message") },
            { message: TRANSLATE$1("jig_ccomp:sheepx.message.3.message"), attachment: ["minecraft:wheat", 1] },
            { message: TRANSLATE$1("jig_ccomp:sheepx.message.4.message"), attachment: ["minecraft:shears", 1] },
            { message: TRANSLATE$1("jig_ccomp:sheepx.message.5.message"), attachment: ["minecraft:name_tag", 1] },
            { message: TRANSLATE$1("jig_ccomp:sheepx.message.6.message") },
            { message: TRANSLATE$1("jig_ccomp:sheepx.message.7.message") },
            { message: TRANSLATE$1("jig_ccomp:sheepx.message.8.message") },
        ] }, FeatherLite: { name: TRANSLATE$1("entity.villager.fletcher"), introduction: { message: TRANSLATE$1("jig_ccomp:fletch.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:fletch.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:fletch.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:fletch.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:fletch.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:fletch.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:fletch.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:fletch.randomx.0.message") },
            { message: TRANSLATE$1("jig_ccomp:fletch.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:fletch.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:fletch.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:fletch.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:fletch.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:fletch.message.0.message") },
            { message: TRANSLATE$1("jig_ccomp:fletch.message.1.message"), attachment: ["minecraft:feather", 10] },
            { message: TRANSLATE$1("jig_ccomp:fletch.message.2.message"), attachment: ["minecraft:arrow", 20] },
            { message: TRANSLATE$1("jig_ccomp:fletch.message.3.message") },
            { message: TRANSLATE$1("jig_ccomp:fletch.message.4.message"), attachment: ["minecraft:bow", 1] },
            { message: TRANSLATE$1("jig_ccomp:fletch.message.5.message") },
            { message: TRANSLATE$1("jig_ccomp:fletch.message.6.message") },
            { message: TRANSLATE$1("jig_ccomp:fletch.message.7.message"), attachment: ["minecraft:string", 1] },
            { message: TRANSLATE$1("jig_ccomp:fletch.message.8.message") },
        ] }, CoMooter: { name: TRANSLATE$1("entity.mooshroom.name"), introduction: { message: TRANSLATE$1("jig_ccomp:mooshr.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:mooshr.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:mooshr.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:mooshr.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:mooshr.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:mooshr.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:mooshr.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:mooshr.randomx.0.message") },
            { message: TRANSLATE$1("jig_ccomp:mooshr.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:mooshr.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:mooshr.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:mooshr.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:mooshr.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:mooshr.message.0.message") },
            { message: TRANSLATE$1("jig_ccomp:mooshr.message.1.message") },
            { message: TRANSLATE$1("jig_ccomp:mooshr.message.2.message"), attachment: ["minecraft:milk_bucket", 1] },
            { message: TRANSLATE$1("jig_ccomp:mooshr.message.3.message") },
            { message: TRANSLATE$1("jig_ccomp:mooshr.message.4.message"), attachment: ["minecraft:brown_mushroom", 2] },
            { message: TRANSLATE$1("jig_ccomp:mooshr.message.5.message"), attachment: ["minecraft:red_mushroom", 2] },
            { message: TRANSLATE$1("jig_ccomp:mooshr.message.6.message") },
            { message: TRANSLATE$1("jig_ccomp:mooshr.message.7.message") },
            { message: TRANSLATE$1("jig_ccomp:mooshr.message.8.message"), attachment: ["minecraft:suspicious_stew", 1] },
        ] }, Egg86: { name: TRANSLATE$1("entity.chicken.name"), introduction: { message: TRANSLATE$1("jig_ccomp:chicke.introducn.message"), attachment: ["minecraft:egg", 1] }, too_many: { message: TRANSLATE$1("jig_ccomp:chicke.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:chicke.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:chicke.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:chicke.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:chicke.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:chicke.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:chicke.randomx.0.message") },
            { message: TRANSLATE$1("jig_ccomp:chicke.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:chicke.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:chicke.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:chicke.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:chicke.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:chicke.message.0.message"), attachment: ["minecraft:egg", 1] },
            { message: TRANSLATE$1("jig_ccomp:chicke.message.1.message"), attachment: ["minecraft:egg", 1] },
            { message: TRANSLATE$1("jig_ccomp:chicke.message.2.message"), attachment: ["minecraft:egg", 1] },
            { message: TRANSLATE$1("jig_ccomp:chicke.message.3.message"), attachment: ["minecraft:egg", 1] },
            { message: TRANSLATE$1("jig_ccomp:chicke.message.4.message"), attachment: ["minecraft:egg", 1] },
            { message: TRANSLATE$1("jig_ccomp:chicke.message.5.message"), attachment: ["minecraft:egg", 1] },
            { message: TRANSLATE$1("jig_ccomp:chicke.message.6.message"), attachment: ["minecraft:egg", 1] },
            { message: TRANSLATE$1("jig_ccomp:chicke.message.7.message"), attachment: ["minecraft:egg", 1] },
            { message: TRANSLATE$1("jig_ccomp:chicke.message.8.message"), attachment: ["minecraft:egg", 1] },
        ] }, BoomBox: { name: TRANSLATE$1("entity.creeper.name"), introduction: { message: TRANSLATE$1("jig_ccomp:creepe.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:creepe.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:creepe.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:creepe.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:creepe.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:creepe.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:creepe.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:creepe.randomx.0.message"), attachment: ["minecraft:gunpowder", 1] },
            { message: TRANSLATE$1("jig_ccomp:creepe.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:creepe.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:creepe.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:creepe.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:creepe.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:creepe.message.0.message") },
            { message: TRANSLATE$1("jig_ccomp:creepe.message.1.message") },
            { message: TRANSLATE$1("jig_ccomp:creepe.message.2.message") },
            { message: TRANSLATE$1("jig_ccomp:creepe.message.3.message") },
            { message: TRANSLATE$1("jig_ccomp:creepe.message.4.message") },
            { message: TRANSLATE$1("jig_ccomp:creepe.message.5.message") },
            { message: TRANSLATE$1("jig_ccomp:creepe.message.6.message") },
            { message: TRANSLATE$1("jig_ccomp:creepe.message.7.message") },
            { message: TRANSLATE$1("jig_ccomp:creepe.message.8.message"), attachment: ["minecraft:gunpowder", 5] },
        ] }, PortBox: { name: TRANSLATE$1("entity.enderman.name"), introduction: { message: TRANSLATE$1("jig_ccomp:endman.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:endman.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:endman.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:endman.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:endman.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:endman.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:endman.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:endman.randomx.0.message"), attachment: ["minecraft:ender_pearl", 1] },
            { message: TRANSLATE$1("jig_ccomp:endman.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:endman.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:endman.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:endman.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:endman.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:endman.message.0.message") },
            { message: TRANSLATE$1("jig_ccomp:endman.message.1.message") },
            { message: TRANSLATE$1("jig_ccomp:endman.message.2.message") },
            { message: TRANSLATE$1("jig_ccomp:endman.message.3.message") },
            { message: TRANSLATE$1("jig_ccomp:endman.message.4.message"), attachment: ["minecraft:carved_pumpkin", 1] },
            { message: TRANSLATE$1("jig_ccomp:endman.message.5.message") },
            { message: TRANSLATE$1("jig_ccomp:endman.message.6.message") },
            { message: TRANSLATE$1("jig_ccomp:endman.message.7.message") },
            { message: TRANSLATE$1("jig_ccomp:endman.message.8.message"), attachment: ["minecraft:ender_pearl", 2] },
        ] }, MiteyMac: { name: TRANSLATE$1("entity.endermite.name"), introduction: { message: TRANSLATE$1("jig_ccomp:endmit.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:endmit.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:endmit.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:endmit.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:endmit.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:endmit.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:endmit.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:endmit.randomx.0.message") },
            { message: TRANSLATE$1("jig_ccomp:endmit.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:endmit.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:endmit.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:endmit.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:endmit.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:endmit.message.0.message") },
            { message: TRANSLATE$1("jig_ccomp:endmit.message.1.message") },
            { message: TRANSLATE$1("jig_ccomp:endmit.message.2.message") },
            { message: TRANSLATE$1("jig_ccomp:endmit.message.3.message") },
            { message: TRANSLATE$1("jig_ccomp:endmit.message.4.message") },
            { message: TRANSLATE$1("jig_ccomp:endmit.message.5.message") },
            { message: TRANSLATE$1("jig_ccomp:endmit.message.6.message") },
            { message: TRANSLATE$1("jig_ccomp:endmit.message.7.message") },
            { message: TRANSLATE$1("jig_ccomp:endmit.message.8.message"), attachment: ["minecraft:ender_eye", 5] },
        ] }, AMBee: { name: TRANSLATE$1("entity.bee.name"), introduction: { message: TRANSLATE$1("jig_ccomp:beexxx.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:beexxx.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:beexxx.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:beexxx.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:beexxx.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:beexxx.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:beexxx.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:beexxx.randomx.0.message") },
            { message: TRANSLATE$1("jig_ccomp:beexxx.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:beexxx.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:beexxx.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:beexxx.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:beexxx.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:beexxx.message.0.message") },
            { message: TRANSLATE$1("jig_ccomp:beexxx.message.1.message") },
            { message: TRANSLATE$1("jig_ccomp:beexxx.message.2.message") },
            { message: TRANSLATE$1("jig_ccomp:beexxx.message.3.message") },
            { message: TRANSLATE$1("jig_ccomp:beexxx.message.4.message") },
            { message: TRANSLATE$1("jig_ccomp:beexxx.message.5.message"), attachment: ["minecraft:honey_bottle", 2] },
            { message: TRANSLATE$1("jig_ccomp:beexxx.message.6.message") },
            { message: TRANSLATE$1("jig_ccomp:beexxx.message.7.message") },
            { message: TRANSLATE$1("jig_ccomp:beexxx.message.8.message"), attachment: ["minecraft:honeycomb", 1] },
        ] }, PurpBox: { name: TRANSLATE$1("entity.shulker.name"), introduction: { message: TRANSLATE$1("jig_ccomp:shulke.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:shulke.toomanyem.message") }, favoriteMailResponses: [
            TRANSLATE$1("jig_ccomp:shulke.favorit.0.message"),
        ], forum: [{
                subject: TRANSLATE$1('jig_ccomp:shulke.forum_m.0.subject'),
                message: TRANSLATE$1('jig_ccomp:shulke.forum_m.0.message')
            }, {
                subject: TRANSLATE$1('jig_ccomp:shulke.forum_m.1.subject'),
                message: TRANSLATE$1('jig_ccomp:shulke.forum_m.1.message')
            }], random: [
            { message: TRANSLATE$1("jig_ccomp:shulke.randomx.0.message"), attachment: ["minecraft:shulker_shell", 1] },
            { message: TRANSLATE$1("jig_ccomp:shulke.randomx.1.message") },
        ], attachmentResponses: [
            TRANSLATE$1("jig_ccomp:shulke.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:shulke.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:shulke.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:shulke.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:shulke.message.0.message"), attachment: ["minecraft:shulker_shell", 1] },
            { message: TRANSLATE$1("jig_ccomp:shulke.message.1.message") },
            { message: TRANSLATE$1("jig_ccomp:shulke.message.2.message") },
            { message: TRANSLATE$1("jig_ccomp:shulke.message.3.message") },
            { message: TRANSLATE$1("jig_ccomp:shulke.message.4.message") },
            { message: TRANSLATE$1("jig_ccomp:shulke.message.5.message") },
            { message: TRANSLATE$1("jig_ccomp:shulke.message.6.message"), attachment: ["minecraft:shulker_shell", 1] },
            { message: TRANSLATE$1("jig_ccomp:shulke.message.7.message") },
            { message: TRANSLATE$1("jig_ccomp:shulke.message.8.message") },
            { message: TRANSLATE$1("jig_ccomp:shulke.message.9.message") },
        ] }, [Config.JigarBoxNpcId]: { name: TRANSLATE$1("jig_ccomp:jignet_desk.name"), introduction: { message: TRANSLATE$1("jig_ccomp:helpds.introducn.message") }, too_many: { message: TRANSLATE$1("jig_ccomp:helpds.toomanyem.message") }, attachmentResponses: [
            TRANSLATE$1("jig_ccomp:helpds.attachm.0.message"),
            TRANSLATE$1("jig_ccomp:helpds.attachm.1.message"),
        ], inventoryFullResponses: [
            TRANSLATE$1("jig_ccomp:helpds.invfull.0.message"),
            TRANSLATE$1("jig_ccomp:helpds.invfull.1.message"),
        ], responses: [
            { message: TRANSLATE$1("jig_ccomp:helpds.message.0.message"), attachment: ["jig_common:wrench", 1] },
            { message: TRANSLATE$1("jig_ccomp:helpds.message.1.message") },
            { message: TRANSLATE$1("jig_ccomp:helpds.message.2.message"), attachment: ["minecraft:apple", 1] },
            { message: TRANSLATE$1("jig_ccomp:helpds.message.3.message") },
            { message: TRANSLATE$1("jig_ccomp:helpds.message.4.message") },
            { message: TRANSLATE$1("jig_ccomp:helpds.message.5.message") },
            { message: TRANSLATE$1("jig_ccomp:helpds.message.6.message") },
            { message: TRANSLATE$1("jig_ccomp:helpds.message.7.message") },
            { message: TRANSLATE$1("jig_ccomp:helpds.message.8.message") },
            { message: TRANSLATE$1("jig_ccomp:helpds.message.9.message") },
            { message: TRANSLATE$1("jig_ccomp:helpds.message.10.message") },
        ] }
};

const NPCS = 'jig_ccomp:NPCS';
const JIGARBOX = Config.JigarBoxNpcId;
const MAXFAVORITEEMAILS = 10;
const defaultNpcData = {
    [JIGARBOX]: {
        nextResponse: -1,
        acceptsEmails: true,
        pendingEmail: false
    }
};
const addNpc = (player, npc, acceptsEmails) => {
    const npcs = getNpcs(player);
    if (!(npc in npcs)) {
        npcs[npc] = {
            nextResponse: -1,
            acceptsEmails,
            pendingEmail: false
        };
    }
    else if (acceptsEmails) {
        npcs[npc].acceptsEmails = acceptsEmails;
    }
    player.setDynamicProperty(NPCS, JSON.stringify(npcs));
};
const saveFavoriteEmail = (player, npc, subject, message) => {
    const npcs = getNpcs(player);
    if (!npcs[npc].favoriteEmails) {
        npcs[npc].favoriteEmails = [];
    }
    const favoriteEmail = npcs[npc].favoriteEmails;
    favoriteEmail.push({ subject, message });
    if (favoriteEmail.length > MAXFAVORITEEMAILS) {
        favoriteEmail.shift();
    }
    player.setDynamicProperty(NPCS, JSON.stringify(npcs));
};
const incrementNpcResponse = (player, npc) => {
    const npcs = getNpcs(player);
    npcs[npc].nextResponse++;
    player.setDynamicProperty(NPCS, JSON.stringify(npcs));
};
const markPendingEmail = (player, npc, pendingEmail) => {
    const npcs = getNpcs(player);
    npcs[npc].pendingEmail = pendingEmail;
    player.setDynamicProperty(NPCS, JSON.stringify(npcs));
};
const enableNpcMails = (player, npc) => {
    const npcs = getNpcs(player);
    npcs[npc].acceptsEmails = true;
    npcs[npc].pendingEmail = false;
    player.setDynamicProperty(NPCS, JSON.stringify(npcs));
};
const getEmaileableNpcs = (player) => {
    const npcs = getNpcs(player);
    return Object.fromEntries(Object.entries(npcs).filter(e => e[1].acceptsEmails));
};
const getNpcs = (player) => {
    return JSON.parse(player.getDynamicProperty(NPCS) ?? JSON.stringify(defaultNpcData));
};
const clearNpcs = (player) => {
    player.setDynamicProperty(NPCS, undefined);
};

const blockNpc = (npc) => {
    return multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:block-npc.title"))
        .setBody(RAW_TEXT(TRANSLATE$1("jig_ccomp:block-npc.body", "\n\n"), TEXT_OR_RAW_TEXT(npc), TRANSLATE$1("jig_ccomp:block-npc.body2", "\n\n")))
        .addButton("yes", TRANSLATE$1("jig_ccomp:yes"))
        .addButton("no", TRANSLATE$1("jig_ccomp:no"));
};

const blockPlayer = (player, computer) => {
    return multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:block-player.title"))
        .setBody(RAW_TEXT(TRANSLATE$1("jig_ccomp:block-player.body", "\n\n")))
        .addButton("player", RAW_TEXT(TRANSLATE$1("jig_ccomp:block-player"), TEXT_OR_RAW_TEXT(player)))
        .addButton("computer", RAW_TEXT(TRANSLATE$1("jig_ccomp:block-computer"), TEXT_OR_RAW_TEXT(computer)))
        .addButton("both", TRANSLATE$1("jig_ccomp:block-both"))
        .addButton("no", TRANSLATE$1("jig_ccomp:cancel"));
};

const blockScript = (script, computer) => {
    return multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:block-script.title"))
        .setBody(TRANSLATE$1("jig_ccomp:block-script.body", "\n\n"))
        .addButton("script", RAW_TEXT(TRANSLATE$1("jig_ccomp:block-script"), TEXT_OR_RAW_TEXT(script)))
        .addButton("computer", RAW_TEXT(TRANSLATE$1("jig_ccomp:block-scriptcomputer"), TEXT_OR_RAW_TEXT(computer)))
        .addButton("no", TRANSLATE$1("jig_ccomp:cancel"));
};

const PLAYER = TRANSLATE$1("jig_ccomp:player");
const COMPUTER = TRANSLATE$1("jig_ccomp:computer");
const SCRIPT = TRANSLATE$1("jig_ccomp:script");
const NPC = TRANSLATE$1("jig_ccomp:npc");
const unblock = (blocked) => {
    return multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:unblock-player.title"))
        .setBody(RAW_TEXT(TRANSLATE$1("jig_ccomp:unblock-player.body", "\n\n", "\n"), RAW_TEXT(getLabel(blocked), blocked.data.name), TEXT("?")))
        .addButton("yes", TRANSLATE$1("jig_ccomp:yes"))
        .addButton("no", TRANSLATE$1("jig_ccomp:no"));
};
const unblockList = (blocked) => {
    return multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:unblock-pc.title"))
        .setBody(TRANSLATE$1("jig_ccomp:unblock-pc.body"))
        .addButtons(blocked.map(b => ({
        name: b.id,
        text: RAW_TEXT(getLabel(b), TEXT(": "), b.data.name)
    })));
};
const getLabel = (block) => {
    if (block.block_type === "player") {
        if (block.sender_type === "npc") {
            return NPC;
        }
        else if (block.sender_type === "script") {
            return SCRIPT;
        }
        return PLAYER;
    }
    return COMPUTER;
};

const deleteEmailsDialogue = (emails) => {
    return multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:pc-delete-email.title"))
        .setBody(TRANSLATE$1("jig_ccomp:pc-delete-email.body", "\n"))
        .addButton('cancel', TRANSLATE$1("jig_ccomp:pc-delete-email.cancel"))
        .addButtons(emails.map(e => ({
        name: e.id,
        text: RAW_TEXT(TEXT("§4"), TEXT_OR_RAW_TEXT(e.from_player), TEXT(": "), TEXT_OR_RAW_TEXT(e.subject)),
    }), 'textures/jig/ccomp/myui/trash.png'));
};

const computerNotOnline = () => {
    return multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:pc-offline.title"))
        .setBody(TRANSLATE$1("jig_ccomp:pc-offline.body", "\n"))
        .addButton("ok", TRANSLATE$1("jig_ccomp:pc-offline.ok"));
};

const RANDOM_PC_ID = "jig_ccomp:random-pc";
const NPC_PREFIX = "npc:";
const PLAYER_PREFIX = "player:";
const OFFLINE_COMPUTER = "offline:";
const initEmail = () => {
    subscribeFromComputerNpcDialogue((event) => {
        if (event.id === 'jig_ccomp:send_email') {
            const { use_predefined_content: usePredefinedContent } = JSON.parse(event.message);
            executeScriptDialogueFromNpcDialogue(() => sendEmail(event.player, event.computer, usePredefinedContent));
        }
        else if (event.id === 'jig_ccomp:read_emails') {
            executeScriptDialogueFromNpcDialogue(() => readEmails(event.player, event.computer));
        }
        else if (event.id === 'jig_ccomp:computer_blocks') {
            executeScriptDialogueFromNpcDialogue(() => unblockEmails(event.player, event.computer));
        }
        else if (event.id === 'jig_ccomp:delete_emails') {
            executeScriptDialogueFromNpcDialogue(() => deleteEmails(event.player, event.computer));
        }
    }, {
        namespaces: ['jig_ccomp']
    });
    system.afterEvents.scriptEventReceive.subscribe((event) => {
        if (event.id === 'jig_ccomp:clear_player_npc' && event.sourceEntity instanceof Player) {
            if (event.sourceEntity.hasTag("debug")) {
                clearNpcs(event.sourceEntity);
            }
        }
        else if (event.id === 'jig_ccomp:email_broadcast') {
            const broadcast = JSON.parse(event.message);
            const errors = [];
            // Validate fields before sending:
            if (typeof broadcast.addon !== "string") {
                errors.push(`addon needs to be string`);
            }
            if (typeof broadcast.computer !== "string") {
                errors.push(`computer needs to be string`);
            }
            try {
                if (broadcast.attachment) {
                    new ItemStack(broadcast.attachment, broadcast.attachmentCount ?? 1);
                }
            }
            catch (e) {
                errors.push(`Error while loading item ${broadcast.attachment} x${broadcast.attachmentCount ?? 1}`);
            }
            if (typeof broadcast.addon_name !== "object") {
                errors.push(`addon_name needs a RawMessage`);
            }
            const typeofComputerName = typeof broadcast.computer_name;
            if (typeofComputerName !== "string" && typeofComputerName !== "object") {
                errors.push(`computer_name needs to be string or RawMessage`);
            }
            const typeofSubject = typeof broadcast.subject;
            if (typeofSubject !== "string" && typeofSubject !== "object") {
                errors.push(`subject needs to be string or RawMessage`);
            }
            const typeofMessage = typeof broadcast.message;
            if (typeofMessage !== "string" && typeofMessage !== "object") {
                errors.push(`message needs to be string or RawMessage`);
            }
            if (errors.length > 0) {
                debug(`Found errors while sending a broadcast message. Aborting the message.\n Received: ${JSON.stringify(broadcast, undefined, 2)} \n Errors:\n- ${errors.join("\n- ")}`);
                return;
            }
            // All seems well, prefix the computer with the addon
            broadcast.computer = `${broadcast.addon}:${broadcast.computer}`;
            craftComputers.broadcastEmail(broadcast);
        }
    }, {
        namespaces: ['jig_ccomp']
    });
    const getPlayerByName = (name) => {
        if (name === undefined) {
            return undefined;
        }
        const players = world.getPlayers({
            name
        });
        if (players.length > 0) {
            return players[0];
        }
        return undefined;
    };
    world.afterEvents.entitySpawn.subscribe((event) => {
        if (CraftComputer.isComputer(event.entity)) {
            const computer = new CraftComputer(event.entity);
            const creator = getPlayerByName(computer.getCreator());
            if (creator) {
                const playerAlreadyContacted = GET_RAW_PROP(creator, Config.player.jignetContacted);
                if (typeof playerAlreadyContacted === "boolean") {
                    computer.setWelcomeSent(playerAlreadyContacted);
                }
            }
            if (!computer.getWelcomeSent()) {
                system.runTimeout(() => {
                    if (computer.computer.isValid()) {
                        if (creator?.isValid() === true && GET_RAW_PROP(creator, Config.player.jignetContacted) === true) {
                            computer.setWelcomeSent(true);
                            return;
                        }
                        void sendEmailFromJigarBox(computer);
                        computer.setWelcomeSent(true);
                        if (creator) {
                            SET_RAW_PROP(creator, Config.player.jignetContacted, true);
                        }
                    }
                }, 20 * 30);
            }
        }
    });
    system.runInterval(async () => {
        const allowMobsPost = adminSettings.getBoolean("mobPosting");
        if (allowMobsPost) {
            const availableNpcs = Object.keys(Object.fromEntries(Object.entries(npcRecipients)
                .filter(e => hasUnpostedForumEntries(e[0], e[1]))));
            if (availableNpcs.length > 0) {
                const chosenNpc = availableNpcs[makeRandomNumber(0, availableNpcs.length - 1)];
                const npc = npcRecipients[chosenNpc];
                if (npc.forum) {
                    const postIndex = makeRandomNumber(0, npc.forum.length - 1);
                    makeNpcPost(chosenNpc, npc.name, npc.forum[postIndex]);
                    markForumPosted(chosenNpc, postIndex);
                }
            }
        }
    }, Config.forum.random_npc_post_ticks);
};
const sendEmail = async (player, computer, usePredefinedContent, sendEmailOptions) => {
    if (!computer.getCreator()) {
        computer.setCreator(player.name);
    }
    // Todo: Add input handling, show a message and redraw with whatever the user had
    //  if additional input is needed
    const playerInventory = player.getComponent(EntityInventoryComponent.componentId);
    const emailAttachments = [];
    if (playerInventory?.container) {
        const container = playerInventory.container;
        // Get all inventory except equipped
        for (let i = 0; i < container.size; ++i) {
            const item = container.getItem(i);
            if (item) {
                emailAttachments.push({
                    item,
                    index: i,
                    container
                });
            }
        }
        computer.computer.triggerEvent('jig_ccomp:typing');
    }
    const allowMobs = adminSettings.getBoolean("mobEmails");
    const connectedComputers = craftComputers.getComputers().filter(c => c.getId() !== computer.getId());
    const connectedNpcs = allowMobs ? Object.keys(getEmaileableNpcs(player)).filter(npc => npc in npcRecipients) : [Config.JigarBoxNpcId];
    const storedComputers = craftComputers.getReachableStoredComputerRecipients();
    if (sendEmailOptions?.to) {
        if (connectedComputers.find(c => c.getId() === sendEmailOptions.to)) {
            sendEmailOptions.to = `${PLAYER_PREFIX}${sendEmailOptions.to}`;
        }
        else if (connectedNpcs.find(npc => npc === sendEmailOptions.to)) {
            sendEmailOptions.to = `${NPC_PREFIX}${sendEmailOptions.to}`;
        }
        else if (storedComputers.find(c => c.id === sendEmailOptions.to)) {
            sendEmailOptions.to = `${OFFLINE_COMPUTER}${sendEmailOptions.to}`;
        }
        else {
            // Receiver is not online
            await lockMovementWhile(player, async () => {
                return await computerNotOnline().open({ ...defaultScriptDialogueOptions, player });
            });
            return;
        }
    }
    const sortEmailRecipientByName = (p1, p2) => {
        const name1 = typeof p1.name === "string" ? p1.name.toLowerCase() : p1.name;
        const name2 = typeof p2.name === "string" ? p2.name.toLowerCase() : p2.name;
        if (name1 < name2) {
            return -1;
        }
        else if (name1 > name2) {
            return 1;
        }
        return 0;
    };
    const sortEmailRecipientById = (p1, p2) => {
        if (p1.id < p2.id) {
            return -1;
        }
        else if (p1.id > p2.id) {
            return 1;
        }
        return 0;
    };
    const emailRecipients = connectedComputers.map(c => ({
        name: `${c.getName()} (${c.getId().substring(0, 4)})`,
        id: `${PLAYER_PREFIX}${c.getId()}`,
    })).sort(sortEmailRecipientByName);
    const storedReachableComputers = craftComputers.getReachableStoredComputerRecipients();
    if (storedReachableComputers.length > 0) {
        emailRecipients.push(...storedReachableComputers.map(c => ({
            id: `${OFFLINE_COMPUTER}${c.id}`,
            name: `${c.name} (${c.id.substring(0, 4)})`
        })));
    }
    if (allowMobs) {
        if (getUnknownNpcs(player).length > 0) {
            emailRecipients.push({
                id: `${NPC_PREFIX}${RANDOM_PC_ID}`,
                name: TRANSLATE$1("jig_ccomp:random-pc"),
            });
        }
    }
    emailRecipients.push(...connectedNpcs.map(npc => ({
        id: `${NPC_PREFIX}${npc}`,
        name: npcRecipients[npc].name,
    })).sort(sortEmailRecipientById));
    const response = await lockMovementWhile(player, async () => {
        return await sendEmailDialogue(emailRecipients, emailAttachments, sendEmailOptions?.to, sendEmailOptions?.subject, usePredefinedContent).open({ ...defaultScriptDialogueOptions, player });
        ;
    });
    computer.computer.triggerEvent('jig_ccomp:typing');
    if (response instanceof InputScriptDialogueResponse) {
        const { to, subject, message, attachment } = response.values;
        const emailSubject = usePredefinedContent ? TRANSLATE$1(subject) : subject;
        const emailMessage = usePredefinedContent ? TRANSLATE$1(message) : message;
        let itemToAttach;
        if (attachment !== 'none') {
            itemToAttach = emailAttachments[parseInt(attachment)];
            world.scoreboard.getObjective('jig_ccomp:jig_computer.addon_stats')?.addScore('jig_ccomp:attachments_sent', 1);
        }
        if (to.startsWith(NPC_PREFIX)) {
            const target = to.substring(NPC_PREFIX.length);
            sendNpcEmail(target, player, computer, emailSubject, emailMessage, itemToAttach);
        }
        else {
            let target;
            let isOnline;
            if (to.startsWith(PLAYER_PREFIX)) {
                target = to.substring(PLAYER_PREFIX.length);
                isOnline = true;
            }
            else {
                target = to.substring(OFFLINE_COMPUTER.length);
                isOnline = false;
            }
            let emailSent;
            const targetEmail = {
                sender_type: 'player',
                from_computer_id: computer.getId(),
                from_computer_name: computer.getName(),
                from_player_id: player.name,
                from_player: player.name,
                subject: emailSubject,
                message: emailMessage,
                printable: !usePredefinedContent,
                isRead: false,
            };
            if (isOnline) {
                const targetComputer = craftComputers.getComputer(target);
                emailSent = targetComputer.addEmail(targetEmail, itemToAttach);
            }
            else {
                if (itemToAttach) {
                    computer.addEmail({
                        sender_type: 'system',
                        from_computer_id: 'jig_ccomp:system',
                        from_computer_name: TRANSLATE$1("jig_ccomp:system_email_computer"),
                        from_player_id: 'jig_ccomp:system',
                        from_player: TRANSLATE$1("jig_ccomp:system_email_player"),
                        subject: TRANSLATE$1("jig_ccomp:system_offline.subject"),
                        message: TRANSLATE$1("jig_ccomp:system_offline.message"),
                        printable: false,
                        isRead: false
                    });
                    return;
                }
                const blocks = GET_PROP$1(world, PROP(IDENTIFIER_BLOCKS(target)), []);
                if (evaluateBlocks(blocks, targetEmail)) {
                    emailSent = 'blocked';
                }
                else {
                    SET_PROP$1(world, IDENTIFIER_EMAILS(target), [
                        ...GET_PROP$1(world, IDENTIFIER_EMAILS(target), []),
                        {
                            ...targetEmail,
                            id: makeRandomId()
                        }
                    ]);
                    SET_RAW_PROP(world, IDENTIFIER_TRIGGER_EMAIL_NOTIFICATION(target), true);
                    emailSent = true;
                }
            }
            if (emailSent === 'blocked') {
                computer.addEmail({
                    sender_type: 'system',
                    from_computer_id: 'jig_ccomp:system',
                    from_computer_name: TRANSLATE$1("jig_ccomp:system_email_computer"),
                    from_player_id: 'jig_ccomp:system',
                    from_player: TRANSLATE$1("jig_ccomp:system_email_player"),
                    subject: TRANSLATE$1("jig_ccomp:system_blocked.subject"),
                    message: TRANSLATE$1("jig_ccomp:system_blocked.message"),
                    printable: false,
                    isRead: false
                });
            }
            if (emailSent === false) {
                computer.addEmail({
                    sender_type: 'system',
                    from_computer_id: 'jig_ccomp:system',
                    from_computer_name: TRANSLATE$1("jig_ccomp:system_email_computer"),
                    from_player_id: 'jig_ccomp:system',
                    from_player: TRANSLATE$1("jig_ccomp:system_email_player"),
                    subject: TRANSLATE$1("jig_ccomp:system_full.subject"),
                    message: TRANSLATE$1("jig_ccomp:system_full.message"),
                    printable: false,
                    isRead: false
                });
            }
            if (emailSent) {
                world.scoreboard.getObjective('jig_ccomp:jig_computer.addon_stats')?.addScore('jig_ccomp:emails_sent', 1);
                player.playSound('jig_ccomp.email_send');
                computer.computer.triggerEvent('jig_ccomp:screen_emas');
                computer.computer.triggerEvent('jig_ccomp:typing');
                if (isOnline) {
                    debug(`Player ${player.name} sent an email from computer ${computer.getName()} to computer ${craftComputers.getComputer(target).getName()} with the subject: ${subject}`);
                }
                else {
                    debug(`Player ${player.name} sent an email from computer ${computer.getName()} to offline computer identified by id ${target} with the subject: ${subject}`);
                }
            }
        }
    }
};
const readEmails = async (player, computer) => {
    if (!computer.getCreator()) {
        computer.setCreator(player.name);
    }
    let emails = computer.getEmails().reverse();
    const paper = "jig_ccomp:printed_paper";
    if (emails.length > 0) {
        while (true) {
            emails = computer.getEmails().reverse();
            // We don't have any other email
            if (emails.length === 0) {
                computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_nome`);
                break;
            }
            computer.computer.triggerEvent('jig_ccomp:typing');
            const response = await lockMovementWhile(player, async () => {
                return await readEmailDialogue(emails, player, computer).open({ ...defaultScriptDialogueOptions, player });
            });
            computer.computer.triggerEvent('jig_ccomp:typing');
            if (response instanceof ButtonDialogueResponse) {
                computer.markAsRead(response.selected);
                const email = computer.getEmailById(response.selected);
                const unknownNpcs = getUnknownNpcs(player);
                if (unknownNpcs.includes(email.from_computer_id)) {
                    debug(`Adding npc: ${email.from_computer_id}`);
                    addNpc(player, email.from_computer_id, true);
                }
            }
            // Todo: Add helper method to make it easier to get nested data
            if (response instanceof ButtonDialogueResponse && response.callback) { // Select action
                const selectedEmail = response.selected;
                const selectionAction = response.callback;
                if (selectionAction === "download") {
                    if (computer.downloadAttachment(selectedEmail, player)) {
                        debug(`File downloaded from computer: ${computer.getName()} to player: ${player.name}`);
                    }
                    break;
                }
                else if (selectionAction === "delete") {
                    computer.deleteEmail(selectedEmail);
                    debug(`Email deleted from computer: ${computer.getName()}`);
                    player.playSound('jig_ccomp.email_delete');
                    computer.computer.triggerEvent('jig_ccomp:typing');
                    continue;
                }
                else if (selectionAction === "print") {
                    const email = computer.getEmails().find(e => e.id === selectedEmail);
                    printContent(`Email from: ${email.from_player}`, `${email.subject}\n\n${email.message}`, computer, player, paper);
                    player.playSound('jig_common.pcbloop');
                    computer.computer.triggerEvent('jig_ccomp:typing');
                    break;
                }
                else if (selectionAction === "reply" || selectionAction === "reply-custom") {
                    const useTemplates = selectionAction === "reply";
                    player.playSound('jig_common.pcbloop');
                    const email = computer.getEmails().find(e => e.id === selectedEmail);
                    await sendEmail(player, computer, useTemplates, {
                        to: email.from_computer_id,
                        subject: prependToStringOrRawMessage(email.subject, 'RE:', false)
                    });
                    computer.computer.triggerEvent('jig_ccomp:typing');
                    break;
                }
                else if (selectionAction === "block") {
                    const email = computer.getEmails().find(e => e.id === selectedEmail);
                    let blocked = undefined;
                    switch (email.sender_type) {
                        case "player":
                        case "script":
                            blocked = computer.getBlocked(email.sender_type, "computer", email.from_computer_id)
                                || computer.getBlocked(email.sender_type, "player", email.from_player_id);
                            break;
                        case "npc":
                            blocked = computer.getBlocked(email.sender_type, "player", email.from_player_id);
                    }
                    if (blocked) {
                        const constBlocked = blocked;
                        const unblockResponse = await lockMovementWhile(player, async () => {
                            return await unblock(constBlocked).open({ player });
                        });
                        if (unblockResponse instanceof ButtonDialogueResponse) {
                            if (unblockResponse.selected === "yes") {
                                computer.removeBlock(blocked.id);
                                computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_ulkg`);
                            }
                        }
                    }
                    else {
                        if (email.sender_type === "player") {
                            const blockReply = await lockMovementWhile(player, async () => {
                                return await blockPlayer(email.from_player, email.from_computer_name).open({
                                    ...defaultScriptDialogueOptions,
                                    player
                                });
                            });
                            if (blockReply instanceof ButtonDialogueResponse) {
                                switch (blockReply.selected) {
                                    case "both":
                                        computer.addPlayerBlock(email);
                                        computer.addComputerBlock(email);
                                        computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_blkb`);
                                        break;
                                    case "computer":
                                        computer.addComputerBlock(email);
                                        computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_blkc`);
                                        break;
                                    case "player":
                                        computer.addPlayerBlock(email);
                                        computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_blkp`);
                                        break;
                                }
                            }
                        }
                        else if (email.sender_type === "npc") {
                            const blockReply = await lockMovementWhile(player, async () => {
                                return await blockNpc(TEXT_OR_RAW_TEXT(email.from_player)).open({
                                    ...defaultScriptDialogueOptions,
                                    player
                                });
                            });
                            if (blockReply instanceof ButtonDialogueResponse) {
                                if (blockReply.selected === "yes") {
                                    computer.addPlayerBlock(email);
                                    computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_blkn`);
                                }
                            }
                        }
                        else if (email.sender_type === "script") {
                            const blockReply = await lockMovementWhile(player, async () => {
                                return await blockScript(TEXT_OR_RAW_TEXT(email.from_player), TEXT_OR_RAW_TEXT(email.from_computer_name)).open({
                                    ...defaultScriptDialogueOptions,
                                    player
                                });
                            });
                            if (blockReply instanceof ButtonDialogueResponse) {
                                switch (blockReply.selected) {
                                    case "computer":
                                        computer.addComputerBlock(email);
                                        computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_blkc`);
                                        break;
                                    case "script":
                                        computer.addPlayerBlock(email);
                                        computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_blks`);
                                        break;
                                }
                            }
                        }
                    }
                }
            }
            computer.computer.triggerEvent('jig_ccomp:typing');
            computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_emai`);
            break;
        }
    }
    else {
        computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_noem`);
    }
};
const sendNpcEmail = (target, player, computer, originalSubject, message, attachment) => {
    if (target === RANDOM_PC_ID) {
        // Pick one from the not know list
        const npcs = getUnknownNpcs(player);
        target = npcs[makeRandomNumber(0, npcs.length - 1)];
        addNpc(player, target, false);
        debug(`Sending email to random mob.`);
    }
    debug(`Selected npc is ${target}`);
    world.scoreboard.getObjective('jig_ccomp:jig_computer.addon_stats')?.addScore('jig_ccomp:emails_sent', 1);
    player.playSound('jig_ccomp.email_send');
    computer.computer.triggerEvent('jig_ccomp:screen_emas');
    computer.computer.triggerEvent('jig_ccomp:typing');
    let responseDelay = makeRandomNumber(2000, 8000);
    if (player.hasTag("jig_ccomp:fast-emails")) {
        responseDelay = 20;
    }
    if (attachment) {
        responseDelay *= 0.5;
        if (attachment.container && attachment.index !== undefined) {
            attachment.container.setItem(attachment.index);
        }
    }
    const replier = npcRecipients[target];
    const npcs = getNpcs(player);
    const pendingEmail = npcs[target].pendingEmail;
    const email = {
        sender_type: 'npc',
        from_computer_name: target,
        from_computer_id: target,
        from_player_id: target,
        from_player: replier.name,
        subject: prependToStringOrRawMessage(originalSubject, "RE: ", true),
        message: '',
        printable: false,
        isRead: false,
        isTooFastEmail: false,
    };
    if (pendingEmail) {
        // Fetch the future operations, if it is a "isNotTooFastEmail" return
        // Else we need to fetch the future operations and patch it to send a too fast email
        const operations = getOperations(computer.computer);
        const operation = operations.find(o => {
            if (o.operation === "send-email-mob" /* FutureOperationType.COMPUTER_SEND_EMAIL_FROM_MOB */) {
                const [operation_target, _playerName, _email, _attachment] = o.params;
                if (target === operation_target) {
                    return true;
                }
            }
            return false;
        });
        if (operation) {
            const [_target, playerName, email, _attachment] = operation.params;
            if (email.isTooFastEmail) {
                // all is set, nothing to do
                return;
            }
            else {
                // patch the operation
                system.clearRun(operation.timerId);
                removeOperation(computer.computer, operation);
                const craftEmail = email;
                craftEmail.isTooFastEmail = true;
                const npcMessage = npcRecipients[target].too_many;
                craftEmail.message = npcMessage.message;
                operation.params = [target, playerName, craftEmail, npcMessage.attachment];
                addOperation(computer.computer, operation);
                runPendingOperations(computer.computer);
                return;
            }
        }
    }
    else {
        markPendingEmail(player, target, true);
    }
    const npcMessage = getNextMessage(target, player);
    const emailMessage = [npcMessage.message];
    const npcRecipient = npcRecipients[target];
    let favoriteEmailOfNPC;
    if (npcMessage.attachment && npcMessage.attachment[0] == Config.favoriteEmailAttachtment) {
        favoriteEmailOfNPC = getFavoriteEmailOfNPC(target, player);
    }
    if (attachment) {
        if (npcRecipient.attachmentResponses && npcRecipient.attachmentResponses.length > 0) {
            emailMessage.unshift(npcRecipient.attachmentResponses[makeRandomNumber(0, npcRecipient.attachmentResponses.length - 1)], TEXT("\n"));
        }
    }
    if (typeof message === "string" && message && typeof originalSubject === "string" && originalSubject) {
        saveFavoriteEmail(player, target, originalSubject, message);
    }
    email.message = RAW_TEXT(...emailMessage);
    const playerName = player.name;
    scheduleOperation(computer.computer, {
        operation: "send-email-mob" /* FutureOperationType.COMPUTER_SEND_EMAIL_FROM_MOB */,
        timeFromNow: responseDelay,
        params: [target, playerName, email, npcMessage.attachment, favoriteEmailOfNPC]
    });
    scheduleOperation(player, {
        operation: "enable-npc" /* FutureOperationType.PLAYER_ENABLE_NPC */,
        timeFromNow: responseDelay,
        params: [target]
    });
};
const sendEmailFromJigarBox = async (computer) => {
    const target = Config.JigarBoxNpcId;
    const replier = npcRecipients[target];
    const email = {
        sender_type: 'npc',
        from_computer_name: target,
        from_computer_id: target,
        from_player_id: target,
        from_player: replier.name,
        subject: TRANSLATE$1('jig_ccomp:helpds.subject.xx.message'),
        message: TRANSLATE$1('jig_ccomp:helpds.message.xx.message'),
        printable: false,
        isRead: false,
        isTooFastEmail: false,
    };
    computer.addEmail(email);
};
const unblockEmails = async (player, computer) => {
    const blocks = computer.getEmailBlocks();
    if (blocks.length > 0) {
        const response = await lockMovementWhile(player, async () => {
            return await unblockList(computer.getEmailBlocks()).open({
                ...defaultScriptDialogueOptions,
                player
            });
        });
        if (response instanceof ButtonDialogueResponse) {
            computer.removeBlock(response.selected);
            computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_ulkg`);
        }
    }
    else {
        computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_ulkx`);
    }
};
const deleteEmails = async (player, computer) => {
    // First check
    computer.computer.triggerEvent('jig_ccomp:typing');
    if (computer.getEmails().length === 0) {
        computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_noem`);
        return;
    }
    while (player.isValid()) {
        const emails = computer.getEmails();
        if (emails.length === 0) {
            computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_nome`);
            break;
        }
        const response = await lockMovementWhile(player, async () => {
            return await deleteEmailsDialogue(emails).open({
                player,
                ...defaultScriptDialogueOptions
            });
        });
        if (response instanceof ButtonDialogueResponse) {
            computer.computer.triggerEvent('jig_ccomp:typing');
            if (response.selected === "cancel") {
                break;
            }
            else {
                player.playSound('jig_ccomp.email_delete');
                computer.deleteEmail(response.selected);
            }
        }
        else {
            break;
        }
    }
};
const getFavoriteEmailOfNPC = (from, player) => {
    const npcs = getNpcs(player);
    const npc = npcs[from];
    if (npc.favoriteEmails && npc.favoriteEmails.length > 0) {
        return npc.favoriteEmails[makeRandomNumber(0, npc.favoriteEmails.length - 1)];
    }
};
const getNextMessage = (from, player) => {
    const npcs = getNpcs(player);
    const npc = npcs[from];
    const npcRecipient = npcRecipients[from];
    if (npc.nextResponse === -1) {
        incrementNpcResponse(player, from);
        return npcRecipient.introduction;
    }
    else if (npc.nextResponse >= npcRecipient.responses.length) {
        if (npc.favoriteEmails && npc.favoriteEmails.length > 0) {
            let sendFavoriteEmail = (makeRandomNumber(0, 100) > 80) ? true : false;
            if (sendFavoriteEmail) {
                if (npcRecipient.favoriteMailResponses && npcRecipient.favoriteMailResponses.length > 0) {
                    return {
                        attachment: [Config.favoriteEmailAttachtment, 0],
                        message: npcRecipient.favoriteMailResponses[makeRandomNumber(0, npcRecipient.favoriteMailResponses.length - 1)]
                    };
                }
            }
        }
        if (npcRecipient.random && npcRecipient.random.length > 0) {
            return npcRecipient.random[makeRandomNumber(0, npcRecipient.random.length - 1)];
        }
        else {
            return npcRecipient.responses[makeRandomNumber(0, npcRecipient.responses.length - 1)];
        }
    }
    else {
        incrementNpcResponse(player, from);
        return npcRecipient.responses[npc.nextResponse];
    }
};
const getUnknownNpcs = (player) => {
    const knowNpcs = Object.keys(getNpcs(player));
    return Object.keys(npcRecipients).filter(r => !knowNpcs.includes(r));
};
const prependToStringOrRawMessage = (stringOrRawMessage, prepend, usePrefill) => {
    if (typeof stringOrRawMessage === 'string') {
        return prepend + stringOrRawMessage;
    }
    else {
        if (usePrefill) { // Once we lift this requirement, we can remove this path
            return RAW_TEXT(TEXT(prepend), stringOrRawMessage);
        }
        else {
            return 'RE: Template';
        }
    }
};
const prependToStringOrRawMessageThread = (stringOrRawMessage, prepend, usePrefill) => {
    if (typeof stringOrRawMessage === 'string') {
        return prepend + stringOrRawMessage;
    }
    else {
        {
            return 'RE: Forum Thread';
        }
    }
};
const operationSendEmailFromMob = (entity, params) => {
    const [target, playerName, email, attachment, favoriteEmail] = params;
    const computer = new CraftComputer(entity);
    debug(`Npc ${target} just answered to ${playerName}!`);
    let emailAttachment = undefined;
    if (attachment) {
        if (attachment[0] === Config.favoriteEmailAttachtment && favoriteEmail) {
            const paper = "jig_ccomp:printed_paper";
            const printedPaper = printContentFavoriteEmail(`Email from: ${playerName}`, `${favoriteEmail.subject}\n\n${favoriteEmail.message}`, computer, paper);
            emailAttachment = {
                item: printedPaper
            };
        }
        else {
            emailAttachment = {
                item: new ItemStack(attachment[0], attachment[1])
            };
        }
    }
    const emailSent = computer.addEmail(email, emailAttachment, false);
    if (emailSent === false) {
        let message = TRANSLATE$1("jig_ccomp:npc_full_inventory_default.message");
        const npcRecipient = npcRecipients[target];
        if (npcRecipient.inventoryFullResponses && npcRecipient.inventoryFullResponses.length > 0) {
            message = npcRecipient.inventoryFullResponses[makeRandomNumber(0, npcRecipient.inventoryFullResponses.length - 1)];
        }
        email.message = message;
        computer.addEmail(email, emailAttachment);
    }
};
const operationEnableNpc = (entity, params) => {
    const [npc] = params;
    enableNpcMails(entity, npc);
};
const getNpcUsedProp = (npcId) => PROP('npc-used-forum', npcId);
const hasUnpostedForumEntries = (npcId, data) => {
    if (data.forum && data.forum.length > 0) {
        const used = GET_PROP$1(world, getNpcUsedProp(npcId), []);
        return data.forum.some((_v, index) => !used.includes(index));
    }
    return false;
};
const markForumPosted = (npcId, postIndex) => {
    const used = GET_PROP$1(world, getNpcUsedProp(npcId), []);
    used.push(postIndex);
    SET_PROP$1(world, getNpcUsedProp(npcId), used);
};

var Email = /*#__PURE__*/Object.freeze({
  __proto__: null,
  getUnknownNpcs: getUnknownNpcs,
  initEmail: initEmail,
  operationEnableNpc: operationEnableNpc,
  operationSendEmailFromMob: operationSendEmailFromMob,
  prependToStringOrRawMessage: prependToStringOrRawMessage,
  prependToStringOrRawMessageThread: prependToStringOrRawMessageThread,
  sendEmail: sendEmail
});

// Used in both players and world
const POST_KEY = "jig_ccomp:posts";
const initForum = () => {
    subscribeFromComputerNpcDialogue(async (event) => {
        if (event.id === "jig_ccomp:forum") {
            await initForumCrossPlatform(event);
        }
    });
};
const initForumCrossPlatform = async (event) => {
    const player = event.player;
    const computer = 'computer' in event ? event.computer : undefined;
    if (computer) {
        computer.computer.triggerEvent('jig_ccomp:typing');
        if (!computer.getCreator()) {
            computer.setCreator(player.name);
        }
    }
    cleanupPlayerData(player);
    forum: while (true) {
        const playerData = getPlayerData(player);
        const posts = getPlayerPosts(playerData, computer?.getEmailBlocks() ?? []);
        const response = await lockMovementWhile(player, async () => {
            return await openForumDialogue(player, posts, playerData);
        });
        if (response instanceof ButtonDialogueResponse) {
            computer?.computer.triggerEvent('jig_ccomp:typing');
            let postId;
            if (response.selected === "post") {
                if (!computer)
                    break; // posting only supported with a computer
                postId = await makePost(player, computer);
            }
            else {
                postId = response.selected;
            }
            if (postId) {
                while (true) {
                    const viewPostResponse = await viewPost(player, computer, getPostById(postId, player, computer));
                    if (viewPostResponse === "back")
                        continue;
                    if (viewPostResponse === "forum")
                        continue forum;
                    break;
                }
            }
        }
        break;
    }
    if ('closeApp' in event) {
        event.closeApp = true;
    }
};
const makePost = async (player, computer) => {
    const response = await lockMovementWhile(player, async () => {
        return await openMakePostDialogue(player);
    });
    if (response instanceof InputScriptDialogueResponse) {
        computer.computer.triggerEvent('jig_ccomp:typing');
        const postId = makeRandomId();
        addPost({
            id: postId,
            op_id: player.name,
            op_name: TEXT(player.name),
            op_type: 'player',
            op_computer_id: computer.getId(),
            title: response.values.subject,
            message: response.values.message,
            replies: [],
            last_update: world.getAbsoluteTime(),
        });
        return postId;
    }
    return undefined;
};
const makeNpcPost = (npcId, npcName, npcPostForum) => {
    const postId = makeRandomId();
    addPost({
        id: postId,
        op_id: npcId,
        op_name: npcName,
        op_type: 'npc',
        op_computer_id: npcId,
        title: npcPostForum.subject,
        message: npcPostForum.message,
        replies: [],
        last_update: world.getAbsoluteTime(),
    });
    return postId;
};
const viewPost = async (player, computer, post) => {
    if (post === undefined) {
        if (await lockMovementWhile(player, async () => {
            return await openPostNotFound(player);
        })) {
            return "forum";
        }
    }
    else {
        if (post.op_type === "npc") {
            const unknownNpcs = getUnknownNpcs(player);
            if (unknownNpcs.includes(post.op_id)) {
                debug(`Adding npc: ${post.op_id}`);
                addNpc(player, post.op_id, true);
            }
        }
        updatePlayerDataReadPost(player, post.id);
        const response = await lockMovementWhile(player, async () => {
            return await openReadPostDialogue(player, post);
        });
        if (response instanceof ButtonDialogueResponse) {
            computer.computer.triggerEvent('jig_ccomp:typing');
            if (response.selected === "more") {
                return await optionsPost(player, computer, post);
            }
            else {
                return "forum";
            }
        }
    }
    return undefined;
};
const optionsPost = async (player, computer, post) => {
    const response = await lockMovementWhile(player, async () => {
        return await openPostOptions(player, post.op_id);
    });
    if (response instanceof ButtonDialogueResponse) {
        computer.computer.triggerEvent('jig_ccomp:typing');
        switch (response.selected) {
            case "reply":
                {
                    const replyResponse = await lockMovementWhile(player, async () => {
                        return await openReplyPostDialogue(player);
                    });
                    if (replyResponse instanceof InputScriptDialogueResponse) {
                        computer.computer.triggerEvent('jig_ccomp:typing');
                        addReply(post.id, {
                            title: replyResponse.values.subject,
                            message: replyResponse.values.message,
                            op_name: TEXT(player.name),
                            op_id: player.name
                        });
                        return "back";
                    }
                }
                break;
            case "reply-op":
                {
                    // Check if op's computer exists
                    let shouldSendEmail = false;
                    if (post.op_type === "player") {
                        if (craftComputers.isComputerAvailable(post.op_computer_id)) {
                            shouldSendEmail = true;
                        }
                    }
                    else if (post.op_type === "npc") {
                        shouldSendEmail = true;
                    }
                    if (shouldSendEmail) {
                        await sendEmail(player, computer, false, {
                            subject: prependToStringOrRawMessageThread(post.title, 'RE: '),
                            to: post.op_computer_id
                        });
                        return "back";
                    }
                    else {
                        const notFoundResponse = await lockMovementWhile(player, async () => {
                            return await openComputerNotFound(player);
                        });
                        if (notFoundResponse instanceof ButtonDialogueResponse) {
                            computer.computer.triggerEvent('jig_ccomp:typing');
                            return notFoundResponse.selected;
                        }
                    }
                }
                break;
            case "hide":
                {
                    updatePlayerDataHidePost(player, post.id);
                    return "forum";
                }
            case "block":
                {
                    const users = [];
                    users.push({
                        id: post.op_id,
                        name: post.op_name,
                        type: post.op_type,
                    });
                    users.push(...post.replies.map(r => ({
                        id: r.op_id,
                        name: r.op_name,
                        type: "player", // Only players can reply
                    })));
                    const blockedUsers = computer.getEmailBlocks().filter(block => block.sender_type === 'player');
                    const usersToDisplay = users
                        .filter((user, i) => { return users.findIndex(u => u.id == user.id) === i; }) // Only the first match will stay
                        .filter(user => user.id !== player.name) // Exclude the player
                        .filter(user => !blockedUsers.some(block => block.data.id === user.id)); // Exclude blocked users
                    const blockedReply = await lockMovementWhile(player, async () => {
                        return await openBlock(player, usersToDisplay);
                    });
                    if (blockedReply instanceof ButtonDialogueResponse) {
                        computer.computer.triggerEvent('jig_ccomp:typing');
                        if (blockedReply.selected === "back") {
                            return "back";
                        }
                        const blocked = users.find(u => u.id === blockedReply.selected);
                        let block = false;
                        if (blocked.type === "npc") {
                            const blockNpcResponse = await lockMovementWhile(player, async () => {
                                return await blockNpc(blocked.name).open({
                                    player,
                                    ...defaultScriptDialogueOptions
                                });
                            });
                            if (blockNpcResponse instanceof ButtonDialogueResponse) {
                                computer.computer.triggerEvent('jig_ccomp:typing');
                                if (blockNpcResponse.selected === "yes") {
                                    block = true;
                                }
                                else if (blockNpcResponse.selected === "no") {
                                    return "back";
                                }
                            }
                        }
                        else {
                            block = true;
                        }
                        if (block) {
                            computer.addBlock({
                                id: makeRandomId(),
                                sender_type: blocked.type,
                                block_type: 'player',
                                data: {
                                    id: blocked.id,
                                    name: TEXT_OR_RAW_TEXT(blocked.name),
                                }
                            });
                            if (blocked.type === "npc") {
                                computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_blkn`);
                            }
                            else if (blocked.type === "player") {
                                computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_blkp`);
                            }
                            else if (blocked.type === "script") {
                                computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_blks`);
                            }
                        }
                        return undefined;
                    }
                }
                break;
            case "back":
                return "back";
        }
    }
};
const openForumDialogue = async (player, posts, playerData) => {
    return await multiButtonScriptDialogue(TRANSLATE$1('jig_ccomp:forum.title'))
        .setBody(TRANSLATE$1('jig_ccomp:forum.body'))
        .addButton('post', TRANSLATE$1('jig_ccomp:forum.make_title'), 'textures/jig/ccomp/myui/reply-thread.png')
        .addButtons(posts.map(p => ({
        name: p.id,
        text: p.title,
        iconPath: postIsRead(p, playerData) ? "textures/jig/ccomp/myui/post-old.png" : "textures/jig/ccomp/myui/post-new.png"
    }))).open({
        player,
        ...defaultScriptDialogueOptions
    });
};
const openMakePostDialogue = async (player) => {
    return await inputScriptDialogue(TRANSLATE$1('jig_ccomp:forum.make-post.title'))
        .addElement(inputText("subject", TRANSLATE$1("jig_ccomp:forum.make-post.subject.label"), TRANSLATE$1("jig_ccomp:forum.make-post.subject.placeholder"), ''))
        .addElement(inputText("message", TRANSLATE$1("jig_ccomp:forum.make-post.message.label"), TRANSLATE$1("jig_ccomp:forum.make-post.message.placeholder")))
        .open({
        player,
        ...defaultScriptDialogueOptions
    });
};
const openReplyPostDialogue = async (player) => {
    return await inputScriptDialogue(TRANSLATE$1('jig_ccomp:forum.reply-post.title'))
        .addElement(inputText("message", TRANSLATE$1("jig_ccomp:forum.reply-post.message.label"), TRANSLATE$1("jig_ccomp:forum.reply-post.message.placeholder")))
        .addElement(inputDropdown("subject", TRANSLATE$1("jig_ccomp:forum.reply-post.subject.label"))
        .addOption(':)', ':)')
        .addOption(':(', ':(')
        .addOption(':/', ':/')
        .addOption(":'(", ":'(")
        .addOption(":D", ":D")
        .addOption("XD", "XD")
        .addOption("^_^", "^_^")
        .addOption("-.-", "-.-")
        .addOption("o.O", "o.O")
        .addOption("OwO", "OwO"))
        .open({
        player,
        ...defaultScriptDialogueOptions
    });
};
const openReadPostDialogue = async (player, post) => {
    return await dualButtonScriptDialogue(TRANSLATE$1('jig_ccomp:read-post.title'), {
        name: 'more',
        text: TRANSLATE$1('jig_ccomp:read-post.more')
    }, {
        name: 'back',
        text: TRANSLATE$1('jig_ccomp:read-post.back')
    })
        .setBody(RAW_TEXT(
    //TRANSLATE('jig_ccomp:read-post.body-title'),
    //TEXT("\n"),
    TRANSLATE$1('jig_ccomp:read-post.body-subject'), TEXT_OR_RAW_TEXT(post.title), TEXT("§r\n"), 
    //TRANSLATE('jig_ccomp:read-post.body-message'),
    TEXT_OR_RAW_TEXT(post.message), TEXT("\n"), TRANSLATE$1('jig_ccomp:read-post.body-author'), post.op_name, ...post.replies.map(r => {
        if (r.playerBlocked) {
            return RAW_TEXT(TEXT("\n§8  -----   §r\n"), TEXT("§r"), TRANSLATE$1("jig_ccomp:read-post.blocked-reply"));
        }
        return RAW_TEXT(TEXT("\n§8  -----   §r\n"), TEXT("§r"), 
        //TRANSLATE('jig_ccomp:read-post.reply-body'),
        TEXT(r.message), TEXT("\n§r"), TEXT("§7"), r.op_name, TEXT("    §e§l"), TEXT(r.title));
    })))
        .open({
        player,
        ...defaultScriptDialogueOptions
    });
};
// This is an edge case - if the player is viewing forums titles, and clicks on and old
// post that has been deleted it won't load.
// I think the same could happen in computer emails, but less probable as the content is
// not as widely shared.
const openPostNotFound = async (player) => {
    return await multiButtonScriptDialogue(TRANSLATE$1('jig_ccomp:post-not-found.title'))
        .addButton("back", TRANSLATE$1("jig_ccomp:post-not-found.back"))
        .setBody(TRANSLATE$1("jig_ccomp:post-not-found.body"))
        .open({
        player,
        ...defaultScriptDialogueOptions
    });
};
const openComputerNotFound = async (player) => {
    return await multiButtonScriptDialogue(TRANSLATE$1('jig_ccomp:computer-not-found.title'))
        .addButton("back", TRANSLATE$1("jig_ccomp:computer-not-found.back"))
        .setBody(TRANSLATE$1("jig_ccomp:computer-not-found.body"))
        .open({
        player,
        ...defaultScriptDialogueOptions
    });
};
const openPostOptions = async (player, opId) => {
    let dialogue = multiButtonScriptDialogue(TRANSLATE$1('jig_ccomp:post-options.title'))
        .setBody(TRANSLATE$1('jig_ccomp:post-options.body'))
        .addButton('reply', TRANSLATE$1('jig_ccomp:post-options.reply-thread'), 'textures/jig/ccomp/myui/reply-thread.png');
    if (player.name !== opId) {
        dialogue = dialogue.addButton('reply-op', TRANSLATE$1('jig_ccomp:post-options.reply-op'), 'textures/jig/ccomp/myui/reply.png');
    }
    return await dialogue
        .addButton('hide', TRANSLATE$1('jig_ccomp:post-options.hide'), 'textures/jig/ccomp/myui/hide.png')
        .addButton('block', TRANSLATE$1('jig_ccomp:post-options.block'), 'textures/jig/ccomp/myui/block.png')
        .addButton('back', TRANSLATE$1('jig_ccomp:post-options.back'))
        .open({
        player,
        ...defaultScriptDialogueOptions
    });
};
const openBlock = async (player, users) => {
    return await multiButtonScriptDialogue(TRANSLATE$1('jig_ccomp:post-block.title'))
        .setBody(users.length === 0 ? TRANSLATE$1('jig_ccomp:post-block.body-empty') : TRANSLATE$1('jig_ccomp:post-block.body'))
        .addButtons(users.map(u => ({
        name: u.id,
        text: u.name,
        iconPath: 'textures/jig/ccomp/myui/block.png'
    })))
        .addButton('back', TRANSLATE$1('jig_ccomp:post-block.back'))
        .open({
        player,
        ...defaultScriptDialogueOptions
    });
};
//const openBlock = async (player: Player, users: Array<ForumUser>) => {
//
//	const unblockedUsers = users.filter(user => !isPlayerBlocked('player', user.id, blocks));
//
//	return await multiButtonScriptDialogue(TRANSLATE('jig_ccomp:post-block.title'))
//	  .setBody(unblockedUsers.length === 0 ? TRANSLATE('jig_ccomp:post-block.body-empty') : TRANSLATE('jig_ccomp:post-block.body'))
//	  .addButtons(unblockedUsers.map(u => ({
//		name: u.id,
//		text: u.name
//	  }),'textures/jig/ccomp/myui/block.png'))
//	  .addButton('back', TRANSLATE('jig_ccomp:post-block.back'))
//	  .open({
//		player,
//		...defaultScriptDialogueOptions
//	  });
// }
const getPosts = () => {
    return GET_PROP$1(world, POST_KEY, []);
};
const getPlayerPosts = (playerData, blocks) => {
    return getPosts().filter(p => {
        if (playerData.hidden_posts.includes(p.id)) {
            return false;
        }
        if (isPlayerBlocked(p.op_type, p.op_id, blocks)) {
            return false;
        }
        return true;
    });
};
const getPostById = (postId, player, computer) => {
    getPlayerData(player);
    const post = getPosts().find(p => p.id === postId);
    if (post) {
        post.replies = post.replies.map(r => {
            // replies are from players for now
            r.playerBlocked = isPlayerBlocked('player', r.op_id, computer.getEmailBlocks());
            return r;
        });
    }
    return post;
};
const getPlayerData = (player) => {
    return GET_PROP$1(player, POST_KEY, {
        hidden_posts: [],
        last_reads: {}
    });
};
const updatePlayerDataReadPost = (player, postId) => {
    const playerData = getPlayerData(player);
    playerData.last_reads[postId] = world.getAbsoluteTime();
    SET_PROP$1(player, POST_KEY, playerData);
};
const updatePlayerDataHidePost = (player, postId) => {
    const playerData = getPlayerData(player);
    playerData.hidden_posts.push(postId);
    SET_PROP$1(player, POST_KEY, playerData);
};
const postIsRead = (post, data) => {
    if (post.id in data.last_reads) {
        return post.last_update <= data.last_reads[post.id];
    }
    return false;
};
const addPost = (post) => {
    const posts = getPosts();
    posts.unshift(post);
    if (posts.length > Config.forum.post_capacity) {
        posts.splice(posts.length - 1, posts.length - Config.forum.post_capacity);
    }
    SET_PROP$1(world, POST_KEY, posts);
};
const addReply = (postId, reply) => {
    // Update updated time
    const posts = getPosts();
    const index = posts.findIndex(p => p.id === postId);
    if (index >= 0) {
        const post = posts[index];
        post.last_update = world.getAbsoluteTime();
        post.replies.push(reply);
        posts.splice(index, 1);
        posts.unshift(post);
        SET_PROP$1(world, POST_KEY, posts);
    }
};
const cleanupPlayerData = (player) => {
    const postIds = getPosts().map(p => p.id);
    const playerData = getPlayerData(player);
    for (const lastReadId of Object.keys(playerData.last_reads)) {
        if (!postIds.includes(lastReadId)) {
            delete playerData.last_reads[lastReadId];
        }
    }
    playerData.hidden_posts.filter(hiddenPostId => postIds.includes(hiddenPostId));
    SET_PROP$1(player, POST_KEY, playerData);
};

class ForumPhoneApp extends PhoneApp {
    static COMPONENT_ID = 'forum';
    constructor() {
        super(ForumPhoneApp.COMPONENT_ID);
    }
    async onSelected(event) {
        await this.openApp(event);
    }
    async onAction(event) {
        await this.openApp(event);
    }
    async openApp(event) {
        event.cancel = true;
        await initForumCrossPlatform(event);
    }
}

const createGlobalSettingsSerializer = (appId, world) => {
    return new GlobalSettings(new GlobalSettingsSerializer(appId, world));
};
const openAdminConfig = async (appId, player) => {
    switch (appId) {
        case BankingApp.COMPONENT_ID:
            await new BankingApp(createGlobalSettingsSerializer(appId, world)).configure(player);
    }
};
const canUninstall = (appId) => {
    return ![AppStore.COMPONENT_ID].includes(appId);
};
const phoneAppFactory = (appId, player, phoneSlot, fromComputer = false) => {
    switch (appId) {
        case AppStore.COMPONENT_ID:
            return new AppStore(new PhoneSettings(new PhoneSettingsSerializer(phoneSlot)), fromComputer);
        case NotesApp.COMPONENT_ID:
            return new NotesApp(new AppSettings(new AppSettingsSerializer(appId, player)));
        case JokeApp.COMPONENT_ID:
            return new JokeApp(new AppSettings(new AppSettingsSerializer(appId, player)), createGlobalSettingsSerializer(appId, world), new PhoneSettings(new PhoneSettingsSerializer(phoneSlot)));
        case BankingApp.COMPONENT_ID:
            return new BankingApp(createGlobalSettingsSerializer(appId, world));
        case BugSmashApp.COMPONENT_ID:
            return new BugSmashApp(new AppSettings(new AppSettingsSerializer(appId, player)), createGlobalSettingsSerializer(appId, world), new PhoneSettings(new PhoneSettingsSerializer(phoneSlot)));
        case TriviaPhoneApp.COMPONENT_ID:
            return new TriviaPhoneApp(new AppSettings(new AppSettingsSerializer(appId, player)), new PhoneSettings(new PhoneSettingsSerializer(phoneSlot)));
        case TextAdventurePhoneApp.COMPONENT_ID:
            return new TextAdventurePhoneApp();
        case WouldYouRatherApp.COMPONENT_ID:
            return new WouldYouRatherApp(new AppSettings(new AppSettingsSerializer(appId, player)), createGlobalSettingsSerializer(appId, world));
        case EightBallApp.COMPONENT_ID:
            return new EightBallApp(new AppSettings(new AppSettingsSerializer(appId, player)), createGlobalSettingsSerializer(appId, world), new PhoneSettings(new PhoneSettingsSerializer(phoneSlot)));
        case MinesweeperPhoneApp.COMPONENT_ID:
            return new MinesweeperPhoneApp();
        case ForumPhoneApp.COMPONENT_ID:
            return new ForumPhoneApp();
        case NoiseMakerPhoneApp.COMPONENT_ID:
            return new NoiseMakerPhoneApp(new PhoneSettings(new PhoneSettingsSerializer(phoneSlot)));
        case TutBookPhoneApp.COMPONENT_ID:
            return new TutBookPhoneApp();
        case MessageApp.COMPONENT_ID:
            return new MessageApp(new NamespacedGlobalSettings(new GlobalNamespacedSettingsSerializer(appId, world)), new PhoneSettings(new PhoneSettingsSerializer(phoneSlot)));
    }
    throw new Error(`Invalid phone app with id: ${appId}`);
};

const ADMIN_SETTINGS_KEY = 'jig_ccomp:admin-menu';
const SettingsTemplate = {
    radar: {
        kind: 'toggle',
        value: true,
    },
    weather: {
        kind: 'toggle',
        value: true,
    },
    triviaPrizes: {
        kind: 'toggle',
        value: true,
    },
    mobEmails: {
        kind: 'toggle',
        value: true,
    },
    mobPosting: {
        kind: 'toggle',
        value: true,
    },
    configureBankApp: {
        kind: 'external',
    }
};
// Todo: ensure we are using the same settings or migrate over the old ones
const adminSettings = new Settings$1(world, "jig_ccomp:admin-settings", SettingsTemplate, {
    onOpen: (player, settings) => {
        // stuff that happens when opening
    },
    onSave: (player, settings) => {
        // stuff that happens when saving
        player.sendMessage(TRANSLATE$1("jig_ccomp:guide.settings_updated_message"));
    },
    shouldOpenSubmenu: (submenu, player, currentSettings) => {
        return true;
    },
    async openExternal(player, key) {
        if (key === 'configureBankApp') {
            await openAdminConfig(BankingApp.COMPONENT_ID, player);
        }
    },
});
const initAdminConfigMenu = () => {
    system.afterEvents.scriptEventReceive.subscribe((event) => {
        if (event.sourceEntity instanceof Player) {
            if (event.id === ADMIN_SETTINGS_KEY) {
                adminSettings.open(event.sourceEntity);
            }
        }
    });
};
const disabledAdminDialogue = async (key, player) => {
    return multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:admin-menu.disabled.title"))
        .setBody(TRANSLATE$1("jig_ccomp:admin-menu.disabled.body", TEXT("\n\n"), TRANSLATE$1(`jig_ccomp:admin-menu.disabled.${key}`)))
        .addButton("back", TRANSLATE$1("jig_ccomp:admin-menu.disabled.back"))
        .open({
        player,
    });
};

const MOB_PAPER = "jig_ccomp:mob_paper";
const MOBN_PAPER = "jig_ccomp:mobn_paper";
const MOBE_PAPER = "jig_ccomp:mobe_paper";
const GOOD_BUG_PAPER = "jig_ccomp:good_bug_paper";
const OK_BUG_PAPER = "jig_ccomp:ok_bug_paper";
const OLD_BUG_PAPER = "jig_ccomp:old_bug_paper";
const TRIVIA_JIG_PAPER = "jig_ccomp:trivia_jig_paper";
const TRIVIA_MIN_PAPER = "jig_ccomp:trivia_min_paper";
const TNT_SWEEPER_1 = "jig_ccomp:tnt_paper_1";
const TNT_SWEEPER_2 = "jig_ccomp:tnt_paper_2";
const TNT_SWEEPER_3 = "jig_ccomp:tnt_paper_3";
const validPaperTypes = [MOB_PAPER, MOBN_PAPER, MOBE_PAPER];
const particleradar = "radar";
const particleradarn = "radarn";
const particleradare = "radare";
let radarchoice = particleradar;
let PAPERCHOICE = MOB_PAPER;
const initRadars = () => {
    world.afterEvents.itemUse.subscribe((event) => {
        let player = event.source;
        const { source, itemStack } = event;
        if (validPaperTypes.includes(itemStack.typeId)) {
            for (const line of itemStack.getLore()) {
                if (line.startsWith("Dimension: ")) {
                    const dimensionName = line.substring("Dimension: ".length);
                    if (`minecraft:${dimensionName}` !== player.dimension.id) {
                        player.runCommandAsync(`/playsound jig_ccomp.radar @a ~ ~ ~ 0.5 0.5`);
                        player.runCommandAsync(`/tellraw @s {"rawtext":[{"text":"§e${itemStack.getLore()[0]} was in the §a${dimensionName}"}]}`);
                        break;
                    }
                }
                if (line.startsWith("x:")) {
                    const indexOfY = line.indexOf("y:");
                    const indexOfZ = line.indexOf("z:");
                    const x = parseInt(line.substring("x:".length, indexOfY - 2));
                    const y = parseInt(line.substring(indexOfY + 2, indexOfZ - 2));
                    const z = parseInt(line.substring(indexOfZ + 2));
                    const target = {
                        x,
                        y,
                        z
                    };
                    getDistance(target, event.source.location);
                    const verdistance = getVerDistance(target, event.source.location);
                    const hordistance = getHorDistance(target, event.source.location);
                    const direction = getDirection(event.source.location, target);
                    let directionString = '';
                    if (direction.includes(0 /* Direction.NEXT_TO_YOU */)) {
                        directionString = 'Next to you!';
                    }
                    else {
                        if (direction.includes(5 /* Direction.ABOVE */)) {
                            if (directionString !== "") {
                                directionString += " and ";
                            }
                            directionString += verdistance + " blocks above you";
                        }
                        if (direction.includes(6 /* Direction.BELOW */)) {
                            if (directionString !== "") {
                                directionString += " and ";
                            }
                            directionString += verdistance + " blocks below you";
                        }
                        if (hordistance >= 4) {
                            let and = "";
                            if (itemStack.typeId === MOB_PAPER) {
                                radarchoice = particleradar;
                            }
                            else if (itemStack.typeId === MOBN_PAPER) {
                                radarchoice = particleradarn;
                            }
                            else if (itemStack.typeId === MOBE_PAPER) {
                                radarchoice = particleradare;
                            }
                            if ((verdistance < 0 && verdistance <= -2) || (verdistance > 0 && verdistance >= 5)) {
                                and = " and ";
                            }
                            directionString += and + hordistance + " blocks to the ";
                            if (direction.includes(1 /* Direction.NORTH */)) {
                                directionString += "north";
                                if (direction.includes(4 /* Direction.EAST */)) {
                                    player.runCommandAsync("/particle jig_ccomp:" + radarchoice + "_ne");
                                }
                                else if (direction.includes(3 /* Direction.WEST */)) {
                                    player.runCommandAsync("/particle jig_ccomp:" + radarchoice + "_nw");
                                }
                                else {
                                    player.runCommandAsync("/particle jig_ccomp:" + radarchoice + "_n");
                                }
                            }
                            if (direction.includes(2 /* Direction.SOUTH */)) {
                                directionString += "south";
                                if (direction.includes(4 /* Direction.EAST */)) {
                                    player.runCommandAsync("/particle jig_ccomp:" + radarchoice + "_se");
                                }
                                else if (direction.includes(3 /* Direction.WEST */)) {
                                    player.runCommandAsync("/particle jig_ccomp:" + radarchoice + "_sw");
                                }
                                else {
                                    player.runCommandAsync("/particle jig_ccomp:" + radarchoice + "_s");
                                }
                            }
                            if (direction.includes(3 /* Direction.WEST */)) {
                                directionString += "west";
                                if (direction.includes(1 /* Direction.NORTH */)) {
                                    player.runCommandAsync("/particle jig_ccomp:" + radarchoice + "_nw");
                                }
                                else if (direction.includes(2 /* Direction.SOUTH */)) {
                                    player.runCommandAsync("/particle jig_ccomp:" + radarchoice + "_sw");
                                }
                                else {
                                    player.runCommandAsync("/particle jig_ccomp:" + radarchoice + "_w");
                                }
                            }
                            if (direction.includes(4 /* Direction.EAST */)) {
                                directionString += "east";
                                if (direction.includes(1 /* Direction.NORTH */)) {
                                    player.runCommandAsync("/particle jig_ccomp:" + radarchoice + "_ne");
                                }
                                else if (direction.includes(2 /* Direction.SOUTH */)) {
                                    player.runCommandAsync("/particle jig_ccomp:" + radarchoice + "_se");
                                }
                                else {
                                    player.runCommandAsync("/particle jig_ccomp:" + radarchoice + "_e");
                                }
                            }
                        }
                    }
                    player.runCommandAsync(`/tellraw @s {"rawtext":[{"text":"§e${itemStack.getLore()[0]} was at: \n§a${line}. \n§6Direction: §r${directionString}."}]}`);
                    player.runCommandAsync(`/playsound jig_ccomp.radar @a ~ ~ ~ 0.5 1.5`);
                    break;
                }
            }
        }
        else if (itemStack.typeId === GOOD_BUG_PAPER) {
            for (const line of itemStack.getLore()) {
                player.playSound("jig_ccomp.bug_scorecard");
            }
        }
        else if (itemStack.typeId === OK_BUG_PAPER) {
            for (const line of itemStack.getLore()) {
                player.playSound("jig_ccomp.bug_hit");
            }
        }
        else if (itemStack.typeId === OLD_BUG_PAPER) {
            for (const line of itemStack.getLore()) {
                player.playSound("jig_ccomp.bug_lose");
            }
        }
        else if (itemStack.typeId === TRIVIA_JIG_PAPER) {
            for (const line of itemStack.getLore()) {
                player.playSound("jig_common.dojig");
            }
        }
        else if (itemStack.typeId === TRIVIA_MIN_PAPER) {
            for (const line of itemStack.getLore()) {
                player.playSound("jig_ccomp.trivia_start");
            }
        }
        else if (itemStack.typeId === TNT_SWEEPER_1) {
            for (const line of itemStack.getLore()) {
                player.playSound("mob.creeper.say");
            }
        }
        else if (itemStack.typeId === TNT_SWEEPER_2) {
            for (const line of itemStack.getLore()) {
                player.dimension.spawnParticle("minecraft:large_explosion", player.location);
                player.dimension.spawnParticle("minecraft:lava_particle", player.location);
                player.playSound("random.explode");
            }
        }
        else if (itemStack.typeId === TNT_SWEEPER_3) {
            for (const line of itemStack.getLore()) {
                player.playSound("random.levelup");
            }
        }
    });
    system.afterEvents.scriptEventReceive.subscribe((event) => {
        const player = event.initiator;
        const sourceEntity = event.sourceEntity;
        if (player && player instanceof Player && sourceEntity && CraftComputer.isComputer(sourceEntity)) {
            if (event.id === 'jig_ccomp:show_radar') {
                let playerSoundOptions = {
                    pitch: makeRandomNumberDecimal(1, 1.5),
                    volume: 1.0,
                };
                player.playSound('jig_ccomp.radar', playerSoundOptions);
                sourceEntity?.runCommand("/event entity @s jig_ccomp:typing");
                system.runTimeout(async () => {
                    if (!adminSettings.getBoolean("radar")) {
                        disabledAdminDialogue("radar", player);
                        return;
                    }
                    while (true) {
                        const response = await lockMovementWhile(player, async () => {
                            return await viewSelectRadar().open({ ...defaultScriptDialogueOptions, player });
                        });
                        if (response instanceof InputScriptDialogueResponse) {
                            let playerSoundOptions = {
                                pitch: makeRandomNumberDecimal(1, 1.5),
                                volume: 1.0,
                            };
                            player.playSound('jig_ccomp.radar', playerSoundOptions);
                            sourceEntity?.runCommand("/event entity @s jig_ccomp:typing");
                            const { radar, sort, count } = response.values;
                            const selectedRadar = radar;
                            let radarEntries;
                            switch (selectedRadar) {
                                case "computer":
                                    radarEntries = getComputers(sourceEntity, count);
                                    break;
                                case "everything":
                                    radarEntries = getEverything(sourceEntity, count);
                                    break;
                                case "item":
                                    radarEntries = getItems(sourceEntity, count);
                                    break;
                                case "mob":
                                    radarEntries = getMob(sourceEntity, count);
                                    break;
                                case "monster":
                                    radarEntries = getMonsters(sourceEntity, count);
                                    break;
                                case "tamed":
                                    radarEntries = getTamed(sourceEntity, count);
                                    break;
                                case "villager":
                                    radarEntries = getVillager(sourceEntity, count);
                                    break;
                                case "rideable":
                                    radarEntries = getRidable(sourceEntity, count);
                                    break;
                                case "playercheck":
                                    radarEntries = getPlayers(sourceEntity, count);
                                    break;
                                default:
                                    radarEntries = [];
                            }
                            if (sort === true) {
                                radarEntries = radarEntries.reverse();
                            }
                            const innerResponse = await lockMovementWhile(player, async () => {
                                return await viewRadar(selectedRadar, radarEntries, player).open({
                                    ...defaultScriptDialogueOptions,
                                    player
                                });
                            });
                            if (innerResponse instanceof ButtonDialogueResponse) {
                                sourceEntity?.runCommand("/event entity @s jig_ccomp:typing");
                                if (innerResponse.selected === "more-options") {
                                    let playerSoundOptions = {
                                        pitch: makeRandomNumberDecimal(1, 1.5),
                                        volume: 1.0,
                                    };
                                    player.playSound('jig_ccomp.radar', playerSoundOptions);
                                    if (innerResponse.callback && "selectedOther" in innerResponse.callback) {
                                        continue;
                                    }
                                    else if (innerResponse.callback && "selectedPrintEntry" in innerResponse.callback) {
                                        sourceEntity?.runCommand("/event entity @s jig_ccomp:typing");
                                        if (player.dimension.id === "minecraft:nether") {
                                            PAPERCHOICE = MOB_PAPER;
                                        }
                                        if (player.dimension.id === "minecraft:nether") {
                                            PAPERCHOICE = MOBN_PAPER;
                                        }
                                        if (player.dimension.id === "minecraft:the_end") {
                                            PAPERCHOICE = MOBE_PAPER;
                                        }
                                        const entryToPrint = radarEntries[parseInt(innerResponse.callback.selectedPrintEntry)];
                                        printContent(`Radar Result`, `Entity ID ${entryToPrint.id.split(":")[1]} ${entryToPrint.item ? getEntryItemPrint(entryToPrint.item) : ''}\nDimension: ${player.dimension.id.replace("minecraft:", "")}\nx: ${Math.ceil(entryToPrint.location.x)}, y: ${Math.ceil(entryToPrint.location.y)}, z: ${Math.ceil(entryToPrint.location.z)}`, new CraftComputer(sourceEntity), player, PAPERCHOICE);
                                    }
                                }
                            }
                        }
                        break;
                    }
                }, 10);
            }
        }
    }, {
        namespaces: ['jig_ccomp']
    });
};
const getEntryItemPrint = (item) => {
    let itemPrint = item.typeId.split(":")[1];
    if (item.isStackable) {
        itemPrint += ` x${item.amount}`;
    }
    return itemPrint;
};
const resolveItem = (entity) => {
    const itemComponent = entity.getComponent(EntityItemComponent.componentId);
    if (itemComponent) {
        return itemComponent.itemStack;
    }
    return undefined;
};
const isProtected = (entity) => {
    if (entity.hasTag(Config.radar.tags.chain_protect)) {
        return true;
    }
    if (entity.hasComponent(EntityEquippableComponent.componentId)) {
        const equipment = entity.getComponent(EntityEquippableComponent.componentId);
        if (equipment) {
            const items = [
                equipment.getEquipment(EquipmentSlot.Chest)?.typeId ?? '',
                equipment.getEquipment(EquipmentSlot.Feet)?.typeId ?? '',
                equipment.getEquipment(EquipmentSlot.Head)?.typeId ?? '',
                equipment.getEquipment(EquipmentSlot.Legs)?.typeId ?? ''
            ];
            return items.some(item => item.includes('chainmail'));
        }
    }
    return false;
};
const toRadarEntry = (entity, fromEntity) => {
    if (entity.typeId == "jig_ccomp:computer_old" || entity.typeId == "jig_ccomp:computer_ok" || entity.typeId == "jig_ccomp:computer_good" || entity.typeId == "jig_ccomp:computer_lap" || entity.typeId == "jig_ccomp:portable") {
        return {
            id: entity.typeId,
            item: undefined,
            nametag: "",
            health: entity.getComponent(EntityHealthComponent.componentId).currentValue,
            dimension: entity.dimension.id,
            location: entity.location,
            distance: getDistance(entity.location, fromEntity.location),
            protected: isProtected(entity)
        };
    }
    else
        return {
            id: entity.typeId,
            item: resolveItem(entity),
            nametag: entity.nameTag,
            health: entity.getComponent(EntityHealthComponent.componentId)?.currentValue,
            dimension: entity.dimension.id,
            location: entity.location,
            distance: getDistance(entity.location, fromEntity.location),
            protected: isProtected(entity)
        };
};
const getComputers = (fromEntity, closest) => {
    const entities = getEntities(fromEntity, {
        location: fromEntity.location,
        families: ['jig_ccomp:computer'],
    }, closest);
    return entities.map(entity => {
        const radarEntry = toRadarEntry(entity, fromEntity);
        return radarEntry;
    });
};
const getEverything = (fromEntity, closest) => {
    const entities = getEntities(fromEntity, {
        location: fromEntity.location,
    }, closest);
    return entities.map(entity => {
        const radarEntry = toRadarEntry(entity, fromEntity);
        return radarEntry;
    });
};
const getMob = (fromEntity, closest) => {
    const entities = getEntities(fromEntity, {
        location: fromEntity.location,
        families: ['mob'],
    }, closest);
    return entities.map(entity => {
        const radarEntry = toRadarEntry(entity, fromEntity);
        return radarEntry;
    });
};
const getMonsters = (fromEntity, closest) => {
    const entities = getEntities(fromEntity, {
        location: fromEntity.location,
        families: ['monster'],
    }, closest);
    return entities.map(entity => {
        const radarEntry = toRadarEntry(entity, fromEntity);
        return radarEntry;
    });
};
const getVillager = (fromEntity, closest) => {
    const entitiesVillager = getEntities(fromEntity, {
        location: fromEntity.location,
        families: ['villager'],
    }, closest);
    const entitiesWanderingTrader = getEntities(fromEntity, {
        location: fromEntity.location,
        families: ['wandering_trader'],
    }, closest);
    const allEntities = [...entitiesVillager, ...entitiesWanderingTrader];
    return allEntities.map(entity => {
        const radarEntry = toRadarEntry(entity, fromEntity);
        return radarEntry;
    });
};
const getTamed = (fromEntity, count) => {
    const entities = getEntities(fromEntity, {
        location: fromEntity.location
    });
    const tamedEntities = [];
    for (const entity of entities) {
        if (entity.hasComponent(EntityIsTamedComponent.componentId)) {
            const radarEntry = toRadarEntry(entity, fromEntity);
            tamedEntities.push(radarEntry);
            if (tamedEntities.length >= count) {
                return tamedEntities;
            }
        }
    }
    return tamedEntities;
};
const getRidable = (fromEntity, count) => {
    const entities = getEntities(fromEntity, {
        location: fromEntity.location,
        excludeTypes: ['player'],
        excludeFamilies: ['monster'],
    });
    const ridableEntities = [];
    const componentId = "minecraft:rideable";
    for (const entity of entities) {
        if (entity.hasComponent(componentId)) {
            const radarEntry = toRadarEntry(entity, fromEntity);
            ridableEntities.push(radarEntry);
            if (ridableEntities.length >= count) {
                return ridableEntities;
            }
        }
    }
    return ridableEntities;
};
const getPlayers = (fromEntity, closest) => {
    const entities = getEntities(fromEntity, {
        location: fromEntity.location,
        families: ['player'],
    }, closest);
    return entities.map(entity => {
        const radarEntry = toRadarEntry(entity, fromEntity);
        return radarEntry;
    });
};
const getItems = (fromEntity, closest) => {
    const entities = getEntities(fromEntity, {
        location: fromEntity.location,
        type: "minecraft:item",
    }, closest);
    return entities.map(entity => toRadarEntry(entity, fromEntity));
};
/**
 * Gets the entities, performing additional filter on the dimension.
 * This is due to a possible bug in minecraft Dimension#getEntities where it finds stuff in any dimension.
 * @param fromEntity
 * @param options
 * @param max
 */
const getEntities = (fromEntity, options, max) => {
    let entities = fromEntity.dimension.getEntities({
        ...options,
        excludeTags: [
            ...(options.excludeTags ?? []),
            Config.radar.tags.radar_protect
        ]
    });
    // Only entities in the dimension
    entities = entities.filter(e => e.dimension === fromEntity.dimension);
    if (max) {
        entities = entities.slice(0, max);
    }
    return entities;
};

const WEATHER_KEYS = {
    [WeatherType.Clear]: "jig_ccomp:weather.clear",
    [WeatherType.Rain]: "jig_ccomp:weather.raining",
    [WeatherType.Thunder]: "jig_ccomp:weather.thunder",
};
const MOON_PHASE_KEYS = {
    [MoonPhase.FullMoon]: "jig_ccomp:moon.full-moon",
    [MoonPhase.WaningGibbous]: "jig_ccomp:moon.waning-gibbous",
    [MoonPhase.FirstQuarter]: "jig_ccomp:moon.first-quarter",
    [MoonPhase.WaningCrescent]: "jig_ccomp:moon.waning-crescent",
    [MoonPhase.NewMoon]: "jig_ccomp:moon.new-moon",
    [MoonPhase.WaxingCrescent]: "jig_ccomp:moon.waxing-crescent",
    [MoonPhase.LastQuarter]: "jig_ccomp:moon.last-quarter",
    [MoonPhase.WaxingGibbous]: "jig_ccomp:moon.waxing-gibbous",
};
const viewWeatherForecast = (options) => {
    const baseOptions = RAW_TEXT(TEXT("\n"), TRANSLATE$1("jig_ccomp:view-weather-forecast.subtitle"), TEXT("\n\n"), TRANSLATE$1("jig_ccomp:view-weather-forecast.moon-phase"), TEXT("\n"), getMoonPhaseLabel(options.time), TEXT("\n"), TRANSLATE$1(MOON_PHASE_KEYS[options.moonPhase]), TEXT("\n"), TEXT("\n"));
    if (options.allowUpdates) {
        return inputScriptDialogue(TRANSLATE$1("jig_ccomp:view-weather-forecast.title"))
            .addElement(inputDropdown("future", RAW_TEXT(baseOptions, TRANSLATE$1("jig_ccomp:view-weather-forecast.future"))).addOption(TRANSLATE$1(WEATHER_KEYS[WeatherType.Clear]), WeatherType.Clear)
            .addOption(TRANSLATE$1(WEATHER_KEYS[WeatherType.Rain]), WeatherType.Rain)
            .addOption(TRANSLATE$1(WEATHER_KEYS[WeatherType.Thunder]), WeatherType.Thunder)
            .setDefaultValueIndex(0));
    }
    else {
        return multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:view-weather-forecast.title"))
            .setBody(baseOptions)
            .addButton("close", TRANSLATE$1("jig_ccomp:view-weather-forecast.close"));
    }
};
const getMoonPhaseLabel = (time) => {
    if (time < 11834) {
        return TRANSLATE$1("jig_ccomp:view-weather-forecast.tonight");
    }
    else {
        return TRANSLATE$1("jig_ccomp:view-weather-forecast.current");
    }
};

const initWeather = () => {
    system.afterEvents.scriptEventReceive.subscribe((event) => {
        const player = event.initiator;
        const sourceEntity = event.sourceEntity;
        if (player && player instanceof Player && sourceEntity && CraftComputer.isComputer(sourceEntity)) {
            if (event.id === 'jig_ccomp:show_weather') {
                {
                    player.playSound('ambient.weather.thunder');
                }
                sourceEntity?.runCommand("/event entity @s jig_ccomp:typing");
                system.runTimeout(async () => {
                    const response = await viewWeatherForecast({
                        moonPhase: world.getMoonPhase(),
                        time: world.getTimeOfDay(),
                        allowUpdates: adminSettings.getBoolean("weather")
                    }).open({ ...defaultScriptDialogueOptions, player });
                    if (response instanceof InputScriptDialogueResponse) {
                        sourceEntity?.runCommand("/event entity @s jig_ccomp:typing");
                        const { future } = response.values;
                        if (future == 'Clear') {
                            player.playSound('jig_common.starnoise');
                        }
                        if (future == 'Rain') {
                            player.playSound('bucket.fill_water');
                        }
                        if (future == 'Thunder') {
                            player.playSound('ambient.weather.thunder');
                        }
                        player.dimension.setWeather(future);
                    }
                }, 10);
            }
        }
    }, {
        namespaces: [
            "jig_ccomp"
        ]
    });
};

const viewPortableOptions = (options) => {
    return inputScriptDialogue(TRANSLATE$1("jig_ccomp:portable.options.title"))
        // .addElement(inputToggle("name_tag", TRANSLATE("jig_ccomp:portable.options.name_tag"), options.name_tag))
        .addElement(inputToggle("coordinates", TRANSLATE$1("jig_ccomp:portable.options.coordinates"), options.coordinates))
        .addElement(inputToggle("biome", TRANSLATE$1("jig_ccomp:portable.options.biome"), options.biome))
        .addElement(inputToggle("light_level", TRANSLATE$1("jig_ccomp:portable.options.light_level"), options.light_level))
        .addElement(inputToggle("chunk", TRANSLATE$1("jig_ccomp:portable.options.chunk_border"), options.chunk))
        .addElement(inputToggle("schunk", TRANSLATE$1("jig_ccomp:portable.options.schunk_border"), options.schunk))
        .addElement(inputToggle("entityparticles", TRANSLATE$1("jig_ccomp:portable.options.entityparticles", "\n"), options.entityparticles));
};

const initPortable = () => {
    world.beforeEvents.playerInteractWithEntity.subscribe(event => {
        if (event.target.typeId === "jig_ccomp:portable") {
            const player = event.player;
            const target = event.target;
            system.run(async () => {
                if (!player.isValid() || !target.isValid) {
                    return;
                }
                //const initial_name_tag = target.getProperty("jig_ccomp:name_tag") as boolean;
                const initial_coordinates = target.getProperty("jig_ccomp:show_coordinates");
                const initial_light_level = target.getProperty("jig_ccomp:show_lightlevel");
                const initial_biome = target.getProperty("jig_ccomp:show_biome");
                const initial_chunk_border = target.getProperty("jig_ccomp:show_chunk_border");
                const initial_schunk_border = target.getProperty("jig_ccomp:show_schunk_border");
                const initial_entity_particles = target.getProperty("jig_ccomp:show_entity_particles");
                player.playSound('jig_common.beeps.say');
                const response = await lockMovementWhile(player, async () => {
                    return await viewPortableOptions({
                        // name_tag: initial_name_tag
                        biome: initial_biome,
                        coordinates: initial_coordinates,
                        light_level: initial_light_level,
                        chunk: initial_chunk_border,
                        schunk: initial_schunk_border,
                        entityparticles: initial_entity_particles
                    }).open({ ...defaultScriptDialogueOptions, player });
                });
                if (response instanceof InputScriptDialogueResponse) {
                    player.playSound('jig_common.beeps.say');
                    const { 
                    //name_tag,
                    coordinates, light_level, biome, chunk, schunk, entityparticles } = response.values;
                    //target.setProperty("jig_ccomp:name_tag", name_tag.value as boolean);
                    target.setProperty("jig_ccomp:show_coordinates", coordinates);
                    target.setProperty("jig_ccomp:show_lightlevel", light_level);
                    target.setProperty("jig_ccomp:show_biome", biome);
                    target.setProperty("jig_ccomp:show_chunk_border", chunk);
                    target.setProperty("jig_ccomp:show_schunk_border", schunk);
                    target.setProperty("jig_ccomp:show_entity_particles", entityparticles);
                    //if(name_tag.value as boolean === true){target.triggerEvent("jig_ccomp:always_show")}else{target.triggerEvent("jig_ccomp:sometimes_show")}
                }
            });
        }
    });
};

const viewCreativeProtect = () => {
    return dualButtonScriptDialogue(RAW_TEXT(TRANSLATE$1("jig_ccomp:new_view-creative-protect.title", "\n")), {
        name: "fix-it",
        text: TRANSLATE$1("jig_ccomp:new_fix-game-mode", "\n")
    }, {
        name: "do-nothing",
        text: TRANSLATE$1("jig_ccomp:new_do-nothing", "\n"),
    }).setBody(RAW_TEXT(TRANSLATE$1("jig_ccomp:new_view-creative-protect.body", "\n")));
};

const APPS_WITH_SOUND = [
    TriviaPhoneApp.COMPONENT_ID,
    BugSmashApp.COMPONENT_ID,
    NoiseMakerPhoneApp.COMPONENT_ID,
    JokeApp.COMPONENT_ID,
];
class Phone {
    player;
    phoneSlot;
    settings;
    fromComputer;
    constructor(player, phoneSlot, settings, fromComputer = false) {
        this.player = player;
        this.phoneSlot = phoneSlot;
        this.settings = settings;
        this.fromComputer = fromComputer;
    }
    open(appId) {
        const app = phoneAppFactory(appId, this.player, this.phoneSlot, this.fromComputer);
        this.settings.setActiveApp(app.componentId);
        return app;
    }
    async usePhone() {
        const volume = this.settings.getVolume("phone-menu");
        let playerSoundOptions = {
            pitch: makeRandomNumberDecimal(0.8, 1.2),
            volume: volume,
        };
        debug("phone menu volume is:" + volume);
        this.player.playSound("jig_ccomp.phone_dial", playerSoundOptions);
        // Use the app if active
        const usePhoneEvent = this.createEvent();
        let app = this.getApp();
        if (app) {
            await app.onAction(usePhoneEvent);
        }
        if (app && usePhoneEvent.closeApp) {
            this.close();
            app = undefined;
            usePhoneEvent.cancel = false;
        }
        if (!usePhoneEvent.cancel) {
            while (true) {
                let shouldBreak = true;
                await renderLoop(usePhoneEvent.player, ui, {
                    load_main: async (event) => {
                        const fromComputer = this.fromComputer ? "v" : "";
                        event.form = event.loadForm("main", "multi-button");
                        event.form.title = _("jig_ccomp:phone.main.title" + fromComputer);
                        // Modify "Manage" button text based on source
                        event.form.elements = [
                            {
                                type: "button",
                                text: _("jig_ccomp:gui.phone.manage" + fromComputer),
                                icon: "textures/jig/ccomp/phone/apps/settings",
                                action: {
                                    event: "load_manage_phone",
                                },
                            },
                            {
                                type: "button",
                                text: _("jig_ccomp:gui.phone.close" + fromComputer),
                                action: {
                                    event: "close",
                                },
                            },
                        ];
                        // Add app buttons
                        let apps = this.settings.getAppIds();
                        event.form.elements.unshift(...apps.map((app) => ({
                            type: "button",
                            text: _(`jig_ccomp:phone.app.${app}.name`),
                            icon: `textures/jig/ccomp/phone/apps/${app}`,
                            action: {
                                event: "load_app",
                                eventArgs: [app],
                            },
                        })));
                    },
                    load_delete: async (event) => {
                        event.form = event.loadForm("delete", "multi-button");
                        event.form.elements.unshift(...this.settings
                            .getAppIds()
                            .filter(canUninstall)
                            .map((app) => ({
                            type: "button",
                            text: _(`jig_ccomp:phone.app.${app}.name`),
                            icon: `textures/jig/ccomp/phone/apps/${app}`,
                            action: {
                                form: "delete_confirm",
                                setArgs: {
                                    delete_app: app,
                                },
                            },
                        })));
                    },
                    delete_app: async (event) => {
                        this.settings.removeApp(event.args.get("delete_app"));
                    },
                    load_manage_phone: async (event) => {
                        const fromComputer = this.fromComputer ? "v" : "";
                        event.form = event.loadForm("manage_phone", "multi-button");
                        event.form.title = _("jig_ccomp:phone.manage.title" + fromComputer);
                        let apps = this.settings.getAppIds();
                        if (apps.includes(MessageApp.COMPONENT_ID)) {
                            event.form.elements.splice(2, 0, {
                                type: "button",
                                text: _("jig_ccomp:gui.phone.manage.messages"),
                                icon: "textures/jig/ccomp/phone/apps/messages",
                                action: {
                                    form: "load_messages",
                                    event: "load_messages",
                                },
                            });
                        }
                    },
                    load_app: async (event) => {
                        app = this.open(event.eventArgs[0]);
                        if (app) {
                            const onSelectedEvent = this.createEvent();
                            await app.onSelected(onSelectedEvent);
                            if (onSelectedEvent.closeApp) {
                                this.close();
                                app = undefined;
                                shouldBreak = false;
                            }
                        }
                    },
                    load_messages: async (event) => {
                        event.form = event.loadForm("load_messages", "input");
                        const currentValue = this.settings.getMessages(MessageApp.COMPONENT_ID) ?? 20;
                        event.form.elements.unshift({
                            type: "dropdown",
                            name: "messages",
                            text: _("jig_ccomp:phone.settings.messages.display.title"),
                            defaultValue: currentValue,
                            options: [
                                { text: "5", value: 5 },
                                { text: "10", value: 10 },
                                { text: "20", value: 20 },
                                { text: "50", value: 50 },
                                { text: "100", value: 100 },
                                { text: _("jig_ccomp:phone.settings.messages.show_all"), value: 0 },
                            ],
                        });
                    },
                    load_messages_saved: async (event) => {
                        const args = event.args.getAll();
                        for (const [appID, messages] of Object.entries(args)) {
                            this.settings.setMessages(messages, appID);
                        }
                        event.form = event.loadForm("manage_phone", "multi-button");
                    },
                    load_volume: async (event) => {
                        event.form = event.loadForm("load_volume", "input");
                        const apps = APPS_WITH_SOUND.filter((x) => this.settings.getAppIds().includes(x));
                        apps.unshift("phone-menu");
                        event.form.elements.unshift(...apps.map((app) => ({
                            type: "slider",
                            name: app,
                            text: _(`jig_ccomp:phone.app.${app}.name`),
                            min: 0,
                            max: 100,
                            step: 1,
                            defaultValue: this.settings.getVolume(app) * 100,
                        })));
                    },
                    load_volume_saved: async (event) => {
                        const args = event.args.getAll();
                        for (const [appID, volume] of Object.entries(args)) {
                            this.settings.setVolume(volume, appID);
                        }
                        event.form = event.loadForm("manage_phone", "multi-button");
                    },
                });
                if (shouldBreak) {
                    break;
                }
            }
        }
    }
    close() {
        this.settings.setActiveApp(undefined);
    }
    createEvent() {
        return {
            cancel: false,
            closeApp: false,
            player: this.player,
        };
    }
    getApp() {
        const appId = this.settings.getActiveApp();
        if (appId) {
            return phoneAppFactory(appId, this.player, this.phoneSlot);
        }
        return undefined;
    }
}
const initPhone = () => {
    world.beforeEvents.itemUse.subscribe(async (event) => {
        const mainHand = event.source.getComponent(EntityEquippableComponent.componentId)?.getEquipmentSlot(EquipmentSlot.Mainhand);
        if (mainHand && isPhone(event.itemStack) && isPhone(mainHand) && event.itemStack.typeId === mainHand.typeId) {
            event.cancel = true;
            system.run(() => {
                lockMovementWhile(event.source, async () => {
                    await new Phone(event.source, mainHand, new PhoneSettings(new PhoneSettingsSerializer(mainHand))).usePhone();
                });
            });
        }
    });
    subscribeFromComputerNpcDialogue((event) => {
        if (event.id === "jig_ccomp:phone_apps") {
            if (event.computer) {
                system.run(() => {
                    event.computer.computer.triggerEvent("jig_ccomp:typing");
                    lockMovementWhile(event.player, async () => {
                        await new Phone(event.player, event.computer.computer, new PhoneSettings(new PhoneSettingsSerializer(event.computer.computer)), true).usePhone();
                    });
                });
            }
        }
    }, {
        namespaces: ["jig_ccomp"],
    });
};
const ui = {
    entrypoint: {
        events: "load_main",
    },
    forms: {
        main: {
            type: "multi-button",
            title: _("jig_ccomp:phone.main.title"),
            body: _("jig_ccomp:phone.main.body"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:gui.phone.manage"),
                    icon: "textures/jig/ccomp/phone/apps/settings",
                    action: {
                        event: "load_manage_phone",
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:gui.phone.close"),
                    action: {
                        event: "close",
                    },
                },
            ],
        },
        manage_phone: {
            type: "multi-button",
            title: _("jig_ccomp:phone.manage.title"),
            body: _("jig_ccomp:phone.manage.body"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:gui.phone.manage.delete"),
                    icon: "textures/jig/ccomp/phone/apps/delete",
                    action: {
                        event: "load_delete",
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:gui.phone.manage.sound"),
                    icon: "textures/jig/ccomp/phone/apps/volume",
                    action: {
                        form: "load_volume",
                        event: "load_volume",
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:gui.back"),
                    action: {
                        event: "load_main",
                    },
                },
            ],
        },
        delete: {
            type: "multi-button",
            title: _("jig_ccomp:phone.manage.delete.title"),
            body: _("jig_ccomp:phone.manage.delete.body"),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:gui.back"),
                    action: {
                        event: "load_main",
                    },
                },
            ],
        },
        delete_confirm: {
            type: "multi-button",
            title: _("jig_ccomp:phone.manage.delete.confirm.title", _("jig_ccomp:phone.app.{delete_app}.name")),
            body: _("jig_ccomp:phone.manage.delete.confirm.body", _("jig_ccomp:phone.app.{delete_app}.name")),
            elements: [
                {
                    type: "button",
                    text: _("jig_ccomp:yes"),
                    icon: "textures/jig/ccomp/phone/apps/delete",
                    action: {
                        copyArgs: true,
                        event: [
                            {
                                event: "delete_app",
                            },
                            {
                                event: "load_delete",
                            },
                        ],
                    },
                },
                {
                    type: "button",
                    text: _("jig_ccomp:no"),
                    action: {
                        event: "load_delete",
                    },
                },
            ],
        },
        load_messages: {
            type: "input",
            title: _("jig_ccomp:phone.settings.messages.title"),
            submit: _("jig_ccomp:phone.settings.messages.submit"),
            elements: [],
            action: {
                event: [{
                        event: "load_messages_saved"
                    }, {
                        event: "load_manage_phone"
                    }],
            },
        },
        load_volume: {
            type: "input",
            title: _("jig_ccomp:phone.settings.sound.title"),
            submit: _("jig_ccomp:phone.settings.sound.submit"),
            elements: [],
            action: {
                event: [
                    {
                        event: "load_volume_saved"
                    }, {
                        event: "load_manage_phone"
                    }
                ]
            },
        },
    },
};

const initCreativeProtect = () => {
    world.beforeEvents.playerInteractWithEntity.subscribe((event) => {
        const player = event.player;
        const target = event.target;
        if (!player || !target)
            return;
        if (player.getGameMode() !== GameMode.creative)
            return;
        if (!CraftComputer.isComputer(target))
            return;
        // Cancel default interaction (e.g. NPC screen)
        event.cancel = true;
        // Show the creative mode warning first
        system.run(async () => {
            const response = await lockMovementWhile(player, async () => {
                return await viewCreativeProtect().open({
                    ...defaultScriptDialogueOptions,
                    player,
                });
            });
            if (response instanceof ButtonDialogueResponse && response.selected === "fix-it") {
                player.runCommand("/gamemode survival");
                return; // Do not open the UI if they switched to survival
            }
            // Otherwise show the phone UI from the computer
            system.run(() => {
                target.triggerEvent("jig_ccomp:typing");
                target.triggerEvent("jig_ccomp:screen_phon");
                player.playSound("jig_ccomp.phone_dial", {
                    pitch: Math.random() * 0.4 + 0.8,
                    volume: 1,
                });
                lockMovementWhile(player, async () => {
                    await new Phone(player, target, new PhoneSettings(new PhoneSettingsSerializer(target)), true // fromComputer = true
                    ).usePhone();
                });
            });
        });
    });
};

const viewPcIdDialogue = (current_name, current_player) => {
    return multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:pc-id-view.title"))
        .setBody(RAW_TEXT(TRANSLATE$1("jig_ccomp:pc-id-view.body", "\n\n"), TEXT(`\n\n`), TEXT(`"${current_name}"`), TEXT(`\n\n`), TRANSLATE$1("jig_ccomp:computer_id_player"), TEXT(`\n\n`), TEXT(`"${current_player}"`)))
        .addButtons([
        {
            name: "close",
            text: TRANSLATE$1("jig_ccomp:pc-email-read.button.close")
        }
    ]);
};

const viewBugScoreDialogue = (bug_score) => {
    return multiButtonScriptDialogue(TRANSLATE$1("jig_ccomp:bug-score-view.title"))
        .setBody(RAW_TEXT(TEXT(`§a`), TRANSLATE$1("jig_ccomp:bug-score-view.body"), TEXT(`§r\n\n`), TEXT(`§q\\(")/              §n\\(")/              §u\\(")/`), TEXT(`\n`), TEXT(`§q-( )-               §n-( )-              §u-( )-`), TEXT(`\n`), TEXT(`§q/(_)\\              §n/(_)\\              §u/(_)\\`), TEXT(`\n`), TEXT(`\n`), TRANSLATE$1("jig_ccomp:bug-score-view.your-score"), TEXT(`${bug_score}`), TEXT(`\n\n`)
    //,TEXT(`\n\n`), TRANSLATE("jig_ccomp:bug-score-view.high-score"),TEXT(`: ${high_score}`)
    ))
        .addButtons([
        {
            name: "close",
            text: TRANSLATE$1("jig_ccomp:pc-email-read.button.close")
        }
    ]);
};

const viewComputerOptionsDialogue = (options) => {
    return inputScriptDialogue(TRANSLATE$1("jig_ccomp:pc-settings.title"))
        .addElement(inputToggle("startup", TRANSLATE$1("jig_ccomp:pc-settings.startup"), options.startup))
        .addElement(inputToggle("shutdown", TRANSLATE$1("jig_ccomp:pc-settings.shutdow"), options.shutdown))
        .addElement(inputToggle("notification", TRANSLATE$1("jig_ccomp:pc-settings.notific"), options.notification))
        .addElement(inputToggle("typing_sound", TRANSLATE$1("jig_ccomp:pc-settings.typing_sound"), options.typing_sound))
        .addElement(inputToggle("typing_animation", TRANSLATE$1("jig_ccomp:pc-settings.typing_animation"), options.typing_animation));
};

const initTextAdventures = () => {
    subscribeFromComputerNpcDialogue(async (event) => {
        await TextAdventureCrossPlatform(event);
    });
};

disableCameraLocking();
const light_level_update = "jig_ccomp:update_light_level";
const random_print = "jig_ccomp:random_print";
const bug_smash_print = "jig_ccomp:bug_smash_print";
const id_print = "jig_ccomp:id_print";
const trivia_jig_print = "jig_ccomp:trivia_jig_print";
const trivia_min_print = "jig_ccomp:trivia_min_print";
const tnt_print_1 = "jig_ccomp:tnt_print_1";
const tnt_print_2 = "jig_ccomp:tnt_print_2";
const tnt_print_3 = "jig_ccomp:tnt_print_3";
function spawnSubchunkEdgeParticles(center, dimension) {
    const chunkSize = 16;
    const interval = 8;
    const chunkX = Math.floor(center.x / chunkSize) * chunkSize;
    const chunkY = Math.floor(center.y / chunkSize) * chunkSize;
    const chunkZ = Math.floor(center.z / chunkSize) * chunkSize;
    for (let x = 0; x < chunkSize; x += interval) {
        for (let z = 0; z < chunkSize; z += interval) {
            dimension.spawnParticle("jig_ccomp:digital_purple", { x: chunkX + x, y: chunkY, z: chunkZ + z });
            dimension.spawnParticle("jig_ccomp:digital_purple", {
                x: chunkX + x,
                y: chunkY + chunkSize - 0.001,
                z: chunkZ + z,
            });
        }
    }
}
function spawnChunkEdgeParticles(center, dimension) {
    const chunkSize = 16;
    const verticalInterval = 5;
    const horizontalInterval = 8;
    const chunkX = Math.floor(center.x / chunkSize) * chunkSize;
    const chunkY = Math.floor(center.y / chunkSize) * chunkSize;
    const chunkZ = Math.floor(center.z / chunkSize) * chunkSize;
    // X-direction edges (Z-min and Z-max) → use light_blue_x
    for (let x = 0; x < chunkSize; x += horizontalInterval) {
        for (let y = 0; y < chunkSize; y += verticalInterval) {
            dimension.spawnParticle("jig_ccomp:digital_light_blue_x", { x: chunkX + x, y: chunkY + y, z: chunkZ });
            dimension.spawnParticle("jig_ccomp:digital_light_blue_x", {
                x: chunkX + x,
                y: chunkY + y,
                z: chunkZ + chunkSize - 0.001,
            });
        }
    }
    // Z-direction edges (X-min and X-max) → use light_blue_z
    for (let z = 0; z < chunkSize; z += horizontalInterval) {
        for (let y = 0; y < chunkSize; y += verticalInterval) {
            dimension.spawnParticle("jig_ccomp:digital_light_blue_z", { x: chunkX, y: chunkY + y, z: chunkZ + z });
            dimension.spawnParticle("jig_ccomp:digital_light_blue_z", {
                x: chunkX + chunkSize - 0.001,
                y: chunkY + y,
                z: chunkZ + z,
            });
        }
    }
}
world.afterEvents.playerSpawn.subscribe(async (event) => {
    event.player.runCommand("function jig/ccomp/init");
    event.player.runCommand("function jig/ccomp/book_giver");
});
system.afterEvents.scriptEventReceive.subscribe(function (event) {
    if (event.id === random_print) {
        const player = event.sourceEntity;
        const sourceEntity = event.sourceEntity;
        if (player && player instanceof Player && sourceEntity && CraftComputer.isComputer(sourceEntity)) {
            const computer = new CraftComputer(sourceEntity);
            let paper = "jig_ccomp:printed_paper";
            let item_name = "This is a test";
            let item_lore = "This is a lore test, does this work even if it isnt done through the stuff? but also, what determines if its a subject line or the email body";
            printContent(`fg` + item_name, `fdg` + item_lore, computer, player, paper);
        }
    }
    if (event.id === id_print) {
        const player = event.initiator;
        const sourceEntity = event.sourceEntity;
        if (player && player instanceof Player && sourceEntity && CraftComputer.isComputer(sourceEntity)) {
            sourceEntity.id;
            let paper = "jig_ccomp:printed_paper";
            const computer = new CraftComputer(sourceEntity);
            printContent(`Computer ID Printout`, `${computer.getName()}`, computer, player, paper);
        }
    }
    if (event.id === bug_smash_print) {
        const player = event.initiator;
        const sourceEntity = event.sourceEntity;
        if (player && player instanceof Player && sourceEntity && CraftComputer.isComputer(sourceEntity)) {
            let this_game = world.scoreboard.getObjective("jig_ccomp:bug_smash")?.getScore(player) || 0;
            let paper = "jig_ccomp:printed_paper";
            let s = "";
            if (this_game !== 1) {
                s = "s";
            }
            if (this_game < 10) {
                paper = "jig_ccomp:old_bug_paper";
            }
            if (this_game >= 10 && this_game <= 99) {
                paper = "jig_ccomp:ok_bug_paper";
            }
            if (this_game >= 100) {
                paper = "jig_ccomp:good_bug_paper";
            }
            const computer = new CraftComputer(sourceEntity);
            printContent(player.name + `'s §bBug Smash§f Scorecard`, `You §csmashed§5 §l` + this_game + `§r§o§5 bug` + s + `!`, computer, player, paper);
        }
    }
    if (event.id === trivia_jig_print) {
        const player = event.initiator;
        const sourceEntity = event.sourceEntity;
        if (player && player instanceof Player && sourceEntity && CraftComputer.isComputer(sourceEntity)) {
            let paper = "jig_ccomp:trivia_jig_paper";
            const computer = new CraftComputer(sourceEntity);
            printContent(player.name + `'s §aJigarbov Award`, `This certifies that you completed 10 Jigarbov Trivia questions in a row!`, computer, player, paper);
        }
    }
    if (event.id === trivia_min_print) {
        const player = event.initiator;
        const sourceEntity = event.sourceEntity;
        if (player && player instanceof Player && sourceEntity && CraftComputer.isComputer(sourceEntity)) {
            let paper = "jig_ccomp:trivia_min_paper";
            const computer = new CraftComputer(sourceEntity);
            printContent(player.name + `'s §eMinecraft Award`, `This certifies that you completed 10 Minecraft Trivia questions in a row!`, computer, player, paper);
        }
    }
    if (event.id === tnt_print_1) {
        const player = event.initiator;
        const sourceEntity = event.sourceEntity;
        const difficulty = event.message;
        if (player && player instanceof Player && sourceEntity && CraftComputer.isComputer(sourceEntity)) {
            let paper = "jig_ccomp:tnt_paper_1";
            const computer = new CraftComputer(sourceEntity);
            printContent(player.name + `'s §eTNT Sweeper Award`, `This certifies that you completed the ${difficulty} difficulty!`, computer, player, paper);
        }
    }
    if (event.id === tnt_print_2) {
        const player = event.initiator;
        const sourceEntity = event.sourceEntity;
        const difficulty = event.message;
        if (player && player instanceof Player && sourceEntity && CraftComputer.isComputer(sourceEntity)) {
            let paper = "jig_ccomp:tnt_paper_2";
            const computer = new CraftComputer(sourceEntity);
            printContent(player.name + `'s §eTNT Sweeper Ultimate Award`, `This certifies that you completed the ${difficulty} difficulty!`, computer, player, paper);
        }
    }
    if (event.id === tnt_print_3) {
        const player = event.initiator;
        const sourceEntity = event.sourceEntity;
        const difficulty = event.message;
        if (player && player instanceof Player && sourceEntity && CraftComputer.isComputer(sourceEntity)) {
            let paper = "jig_ccomp:tnt_paper_3";
            const computer = new CraftComputer(sourceEntity);
            printContent(player.name + `'s §eTNT Sweeper Impossible Award`, `This certifies that you completed the ${difficulty} difficulty!`, computer, player, paper);
        }
    }
    if (event.id === light_level_update) {
        if (event.sourceEntity instanceof Entity) {
            const round = (value) => {
                return Math.round(value * 100) / 100;
            };
            let showcoordinates = event.sourceEntity.getProperty("jig_ccomp:show_coordinates");
            let showlightlevel = event.sourceEntity.getProperty("jig_ccomp:show_lightlevel");
            let showbiome = event.sourceEntity.getProperty("jig_ccomp:show_biome");
            let showChunkBorder = event.sourceEntity.getProperty("jig_ccomp:show_chunk_border");
            let showSChunkBorder = event.sourceEntity.getProperty("jig_ccomp:show_schunk_border");
            let showEntityParticles = event.sourceEntity.getProperty("jig_ccomp:show_entity_particles");
            let coordinates = event.sourceEntity.location;
            if (showEntityParticles) {
                // Determine target entities based on areaEffect flag
                const targetEntities = event.sourceEntity.dimension.getEntities({
                    location: event.sourceEntity.location,
                    maxDistance: 20,
                    excludeFamilies: ["player"],
                });
                const targetPlayers = event.sourceEntity.dimension.getEntities({
                    location: event.sourceEntity.location,
                    maxDistance: 20,
                    families: ["player"],
                });
                // Apply effects to targeted entities
                for (const entity of targetEntities) {
                    entity.dimension.spawnParticle("jig_ccomp:digital", entity.location);
                }
                // Apply effects to targeted entities
                for (const other of targetPlayers) {
                    other.dimension.spawnParticle("jig_ccomp:digital_red", other.location);
                }
            }
            if (showChunkBorder) {
                spawnChunkEdgeParticles(coordinates, event.sourceEntity.dimension);
            }
            if (showSChunkBorder) {
                spawnSubchunkEdgeParticles(coordinates, event.sourceEntity.dimension);
            }
            let light_level = event.sourceEntity.getProperty("jig_ccomp:light_level");
            let biome = event.sourceEntity.getProperty("jig_ccomp:biome");
            switch (biome) {
                //all of these should be rawtext strings too
                case 0:
                    biome = "Unknown";
                    break;
                case 1:
                    biome = "Basalt Delta";
                    break;
                case 2:
                    biome = "Beach";
                    break;
                case 3:
                    biome = "Birch";
                    break;
                case 4:
                    biome = "Caves";
                    break;
                case 5:
                    biome = "Cherry Grove";
                    break;
                case 6:
                    biome = "Crimson Forest";
                    break;
                case 7:
                    biome = "Dark Oak Forest";
                    break;
                case 8:
                    biome = "Deep Ocean";
                    break;
                case 9:
                    biome = "Deep Dark";
                    break;
                case 10:
                    biome = "Desert";
                    break;
                case 11:
                    biome = "Dripstone Caves";
                    break;
                case 12:
                    biome = "Edge";
                    break;
                case 13:
                    biome = "Extreme Hills";
                    break;
                case 14:
                    biome = "Flower Forest";
                    break;
                case 15:
                    biome = "Forest";
                    break;
                case 16:
                    biome = "Frozen";
                    break;
                case 17:
                    biome = "Frozen Peaks";
                    break;
                case 18:
                    biome = "Grove";
                    break;
                case 19:
                    biome = "Hills";
                    break;
                case 20:
                    biome = "Ice";
                    break;
                case 21:
                    biome = "Ice Plains";
                    break;
                case 22:
                    biome = "Jagged Peaks";
                    break;
                case 23:
                    biome = "Jungle";
                    break;
                case 24:
                    biome = "Lakes";
                    break;
                case 25:
                    biome = "Lush Cave";
                    break;
                case 26:
                    biome = "Mangrove Swamp";
                    break;
                case 27:
                    biome = "Mega";
                    break;
                case 28:
                    biome = "Mesa";
                    break;
                case 29:
                    biome = "Mooshroom Island";
                    break;
                case 30:
                    biome = "Mountain";
                    break;
                case 31:
                    biome = "Mutated Biome";
                    break;
                case 32:
                    biome = "Nether";
                    break;
                case 33:
                    biome = "Nether Wastes";
                    break;
                case 34:
                    biome = "Netherwart Forest";
                    break;
                case 35:
                    biome = "Ocean";
                    break;
                case 36:
                    biome = "Plains";
                    break;
                case 37:
                    biome = "Plateau";
                    break;
                case 38:
                    biome = "River";
                    break;
                case 39:
                    biome = "Roofed Forest";
                    break;
                case 40:
                    biome = "Savanna";
                    break;
                case 41:
                    biome = "Shore";
                    break;
                case 42:
                    biome = "Snowy Slopes";
                    break;
                case 43:
                    biome = "Soulsand Valley";
                    break;
                case 44:
                    biome = "Stone Beach";
                    break;
                case 45:
                    biome = "Swamp";
                    break;
                case 46:
                    biome = "Taiga";
                    break;
                case 47:
                    biome = "The End";
                    break;
                case 48:
                    biome = "Warped Forest";
                    break;
            }
            let key = "";
            if (showcoordinates) {
                key = key + `x: ${round(coordinates.x)}, y: ${round(coordinates.y)}, z: ${round(coordinates.z)}`;
            }
            if (showbiome) {
                key = key + "\nBiome: " + biome;
            }
            if (showlightlevel) {
                key = key + "\nLight Level: " + light_level;
            }
            if (showChunkBorder) {
                key = key + "\nChunk Borders ON";
            }
            if (showSChunkBorder) {
                key = key + "\nSubchunk Borders ON ";
            }
            event.sourceEntity.nameTag = key;
        }
    }
});
// Split initialization
system.runTimeout(() => {
    initWorldInfo();
    initRadars();
    initWeather();
    initEmail();
    initPortable();
}, 1);
system.runTimeout(() => {
    initCreativeProtect();
    initTut_Book();
    initComputers();
    initForum();
    initAdminConfigMenu();
}, 1);
system.runTimeout(() => {
    initMineSweeper();
    initTextAdventures();
    initTextAdventureResetCode();
}, 1);
world.afterEvents.entitySpawn.subscribe((event) => {
    craftComputers.addComputer(event.entity);
});
world.afterEvents.entityLoad.subscribe((event) => {
    craftComputers.addComputer(event.entity);
});
world.beforeEvents.entityRemove.subscribe((event) => {
    craftComputers.removeComputer(event.removedEntity);
});
const viewBugScore = async (player, computer) => {
    computer.computer.triggerEvent("jig_ccomp:typing");
    let this_game = world.scoreboard.getObjective("jig_ccomp:bug_smash")?.getScore(player) || 0;
    await viewBugScoreDialogue(this_game).open({ ...defaultScriptDialogueOptions, player });
    computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:bug_smash_miss`);
};
const viewComputerOptions = async (player, computer) => {
    computer.computer.triggerEvent("jig_ccomp:typing");
    const initial_startup = computer.computer.hasTag("jig_ccomp.mute_startup") || false;
    const initial_shutdown = computer.computer.hasTag("jig_ccomp.mute_shutdown") || false;
    const initial_notification = computer.computer.hasTag("jig_ccomp.mute_notification") || false;
    const initial_typing_sound = computer.computer.hasTag("jig_ccomp.mute_typing_sound") || false;
    const initial_typing_animation = computer.computer.getProperty("jig_ccomp:mute_keyboard_jiggle") || false;
    player.playSound("jig_common.beeps.say");
    const response = await viewComputerOptionsDialogue({
        startup: !initial_startup,
        shutdown: !initial_shutdown,
        notification: !initial_notification,
        typing_sound: !initial_typing_sound,
        typing_animation: !initial_typing_animation,
    }).open({ ...defaultScriptDialogueOptions, player });
    if (response instanceof InputScriptDialogueResponse) {
        player.playSound("jig_common.beeps.say");
        const { startup, shutdown, notification, typing_sound, typing_animation } = response.values;
        if (startup === false) {
            computer.computer.addTag("jig_ccomp.mute_startup");
        }
        else {
            computer.computer.removeTag("jig_ccomp.mute_startup");
        }
        if (shutdown === false) {
            computer.computer.addTag("jig_ccomp.mute_shutdown");
        }
        else {
            computer.computer.removeTag("jig_ccomp.mute_shutdown");
        }
        if (notification === false) {
            computer.computer.addTag("jig_ccomp.mute_notification");
        }
        else {
            computer.computer.removeTag("jig_ccomp.mute_notification");
        }
        if (typing_sound === false) {
            computer.computer.addTag("jig_ccomp.mute_typing_sound");
        }
        else {
            computer.computer.removeTag("jig_ccomp.mute_typing_sound");
        }
        if (typing_animation === false) {
            computer.computer.setProperty("jig_ccomp:mute_keyboard_jiggle", true);
        }
        else {
            computer.computer.setProperty("jig_ccomp:mute_keyboard_jiggle", false);
        }
    }
    computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_pc_pcid`);
};
const viewComputerId = async (player, computer) => {
    computer.computer.triggerEvent("jig_ccomp:typing");
    if (!computer.getCreator()) {
        computer.setCreator(player.name);
    }
    await viewPcIdDialogue(computer.getName(), computer.getCreator() ?? "undefined").open({
        ...defaultScriptDialogueOptions,
        player,
    });
    computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_ac_pcid`);
};
const setComputerId = async (player, computer) => {
    computer.computer.triggerEvent("jig_ccomp:typing");
    const response = await setPcIdDialogue(computer.getName()).open({ ...defaultScriptDialogueOptions, player });
    if (response instanceof InputScriptDialogueResponse) {
        const name = response.values["name"];
        if (name.length > 0) {
            debug(`Setting PC name to ${name} for computer ${computer.getId()}`);
            computer.setName(name);
            computer.computer.triggerEvent("jig_ccomp:typing");
            await viewPcIdDialogue(computer.getName(), computer.getCreator() ?? "undefined").open({
                ...defaultScriptDialogueOptions,
                player,
            });
            computer.computer.runCommand(`/dialogue open @s "${player.name}" jig_ccomp:old_ac_pcid`);
        }
    }
};
// Process dialogue scriptevents
system.afterEvents.scriptEventReceive.subscribe(async (event) => {
    const player = event.initiator;
    const sourceEntity = event.sourceEntity;
    if (player && player instanceof Player && sourceEntity && CraftComputer.isComputer(sourceEntity)) {
        const computer = new CraftComputer(sourceEntity);
        if (event.id === "jig_ccomp:view_pc_id") {
            executeScriptDialogueFromNpcDialogue(() => viewComputerId(player, computer));
        }
        else if (event.id === "jig_ccomp:set_pc_id") {
            executeScriptDialogueFromNpcDialogue(() => setComputerId(player, computer));
        }
        else if (event.id === "jig_ccomp:bug_smash_view") {
            executeScriptDialogueFromNpcDialogue(() => viewBugScore(player, computer));
        }
        else if (event.id === "jig_ccomp:computer_options") {
            executeScriptDialogueFromNpcDialogue(() => viewComputerOptions(player, computer));
        }
    }
});
system.afterEvents.scriptEventReceive.subscribe((event) => {
    if (event.sourceEntity && event.initiator) {
        if (event.id.endsWith("trivia_wrong")) {
            const triviaPrizes = adminSettings.getBoolean("triviaPrizes");
            const nextNpcDialogue = triviaPrizes ? event.id : event.id + "_x";
            event.sourceEntity.runCommand(`dialogue open @s "${event.initiator.nameTag}" ${nextNpcDialogue}`);
        }
        else if (event.id.endsWith("_trivia_next")) {
            // Check if we wont or we want to display the next question
            const triviaId = event.id.slice(0, event.id.length - "_next".length);
            if (getScoreOr(triviaId, event.initiator, 0) >= 10) {
                // won!
                const wonBase = triviaId + "_won";
                const triviaPrizes = adminSettings.getBoolean("triviaPrizes");
                const nextNpcDialogue = triviaPrizes ? wonBase : wonBase + "_x";
                event.sourceEntity.runCommand(`dialogue open @s "${event.initiator.nameTag}" ${nextNpcDialogue}`);
            }
            else {
                // Assumes all trivia have 50 questions - This can be updated to be different per trivia
                const nextTrivia = makeRandomNumber(1, 50);
                const nextTriviaString = nextTrivia < 10 ? `0${nextTrivia}` : `${nextTrivia}`;
                event.sourceEntity.runCommand(`dialogue open @s "${event.initiator.nameTag}" ${triviaId}_${nextTriviaString}`);
            }
        }
    }
}, {
    namespaces: ["jig_ccomp"],
});
world.beforeEvents.playerInteractWithEntity.subscribe((event) => {
    const player = event.player;
    const entity = event.target;
    const heldItem = event.itemStack;
    if (!entity || !heldItem)
        return;
    if (entity.typeId !== "jig_ccomp:printer_laser")
        return;
    const id = heldItem.typeId;
    const isCopyable = id !== "minecraft:paper" && (id.includes("poster") || id.includes("paper") || id.includes("sticker"));
    if (!isCopyable)
        return;
    // Cancel interaction immediately to block UI
    event.cancel = true;
    // Defer logic to next tick so we can write to nameTag/lore
    system.run(() => {
        const inventory = entity.getComponent("minecraft:inventory")?.container;
        if (!inventory)
            return;
        // Find paper slot
        let paperSlot = -1;
        for (let i = 0; i < inventory.size; i++) {
            const item = inventory.getItem(i);
            if (item?.typeId === "minecraft:paper" && item.amount > 0) {
                paperSlot = i;
                break;
            }
        }
        if (paperSlot === -1) {
            player.sendMessage(TRANSLATE$1("jig_ccomp:printer_laser_no_paper"));
            return;
        }
        // Find empty slot
        let targetSlot = -1;
        for (let i = 0; i < inventory.size; i++) {
            if (!inventory.getItem(i)) {
                targetSlot = i;
                break;
            }
        }
        if (targetSlot === -1) {
            player.sendMessage(TRANSLATE$1("jig_ccomp:printer_laser_no_space"));
            return;
        }
        // Create clone and copy name/lore
        const copy = new ItemStack(heldItem.typeId, 1);
        copy.nameTag = heldItem.nameTag;
        copy.setLore(heldItem.getLore());
        inventory.setItem(targetSlot, copy);
        // Remove 1 paper
        const paper = inventory.getItem(paperSlot);
        if (paper.amount === 1) {
            inventory.setItem(paperSlot, undefined);
        }
        else {
            paper.amount -= 1;
            inventory.setItem(paperSlot, paper);
        }
        entity.triggerEvent("jig_ccomp:printing");
        entity.triggerEvent("jig_ccomp:has_printout");
    });
});
const viewComputerNetworkStats = () => {
    const onlineComputers = craftComputers.getComputers();
    const onlineOwners = new Set(onlineComputers.map((c) => c.getCreator()));
    const recentlyItemized = craftComputers.getReachableStoredComputerRecipients();
    const allStoredIds = world
        .getDynamicPropertyIds()
        .filter((id) => id.startsWith("COMP:") && id.endsWith(":ITEMIZED_ON"))
        .map((id) => id.split(":")[1]);
    const recentlyItemizedIds = new Set(recentlyItemized.map((c) => c.id));
    const fullyOfflineIds = allStoredIds.filter((id) => !recentlyItemizedIds.has(id) && !craftComputers.getComputer(id));
    return dualButtonScriptDialogue(TRANSLATE$1("jig_ccomp:dialogue.network_stats.title"), // "Computer Network Status"
    {
        name: "ok",
        text: TRANSLATE$1("jig_ccomp:router.button_1"),
    }, {
        name: "noop",
        text: TRANSLATE$1("jig_ccomp:router.button_2"),
    }).setBody(RAW_TEXT(TRANSLATE$1(`jig_ccomp:router.title`), TEXT(`\n\n`), TRANSLATE$1(`jig_ccomp:router.online`), TEXT(`${onlineComputers.length}`), TEXT(`\n`), TRANSLATE$1(`jig_ccomp:router.owner`), TEXT(` ${onlineOwners.size}`), TEXT(`\n\n`), TRANSLATE$1(`jig_ccomp:router.inactive`), TEXT(` ${recentlyItemized.length}`), TEXT(`\n`), TRANSLATE$1(`jig_ccomp:router.offline`), TEXT(`${fullyOfflineIds.length}`)));
};
world.afterEvents.itemUse.subscribe(async (event) => {
    const player = event.source;
    const item = event.itemStack;
    if (!(player instanceof Player))
        return;
    if (item?.typeId !== "jig_common:wrench")
        return;
    system.run(() => {
        const viewDir = player.getViewDirection();
        const start = player.getHeadLocation();
        ({
            x: start.x + viewDir.x * 5,
            y: start.y + viewDir.y * 5,
            z: start.z + viewDir.z * 5,
        });
        const blockHit = player.dimension.getBlockFromRay(start, viewDir, { maxDistance: 5 });
        if (!blockHit)
            return;
        if (blockHit.block?.typeId !== "jig_ccomp:router")
            return;
        player.playSound("jig_common.beeps.say");
        viewComputerNetworkStats()
            .open({ ...defaultScriptDialogueOptions, player })
            .then((response) => {
            if (response instanceof ButtonDialogueResponse) {
                player.playSound("jig_common.beeps.say");
            }
        });
    });
});
//world.afterEvents.playerInteractWithBlock.subscribe(async (event) => {
//	const { block, itemStack, player } = event;
//
//	if (block.typeId === "jig_ccomp:router" && itemStack === undefined) {
//		player.playSound("jig_common.beeps.say");
//
//		const response = await viewConnectedComputers().open({ ...defaultScriptDialogueOptions, player });
//
//		if (response instanceof ButtonDialogueResponse) {
//			player.playSound("jig_common.beeps.say");
//		}
//	}
//});
const initDimension = (dimension) => {
    try {
        craftComputers.init(world.getDimension(dimension));
    }
    catch (e) {
        debug(`Error initializing computers on dimension ${dimension}: ${e}`);
    }
};
system.runTimeout(() => {
    initDimension("overworld");
    initDimension("nether");
    initDimension("the_end");
    world.afterEvents.playerSpawn.subscribe((event) => {
        if (event.initialSpawn && event.player.isValid()) {
            runPendingOperations(event.player);
        }
    });
    world.afterEvents.entityLoad.subscribe((event) => {
        if (event.entity.isValid()) {
            runPendingOperations(event.entity);
        }
    });
    craftComputers.getComputers().forEach((c) => {
        runPendingOperations(c.computer);
    });
    world
        .getPlayers()
        .filter((p) => p.isValid())
        .forEach((p) => {
        runPendingOperations(p);
    });
}, 50);
// Init world
if (GET_RAW_PROP(world, Config.world.installedTime) === undefined) {
    SET_RAW_PROP(world, Config.world.installedTime, world.getAbsoluteTime());
}
initPhone();

export { viewComputerNetworkStats };
//# sourceMappingURL=main.js.map
