import { world, system, EquipmentSlot } from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
import "./form";

//================ DUST ===================

//world.afterEvents.itemUse.subscribe(data => {
//    const { source, itemStack } = data;
//    if (itemStack.typeId == 'rl_cr:music_off') {
//        source.runCommandAsync('function music_on');
//        source.runCommandAsync('say on');
//        source.runCommandAsync('replaceitem entity @s slot.hotbar 0 rl_cr:music_oon 1 1 {"item_lock": {"mode": "lock_in_slot"}}');
//        source.runCommandAsync('clear @a rl_cr:music_off 0 1');
//    } if (itemStack.typeId == 'rl_cr:music_on') {
//        source.runCommandAsync('function music_off');
//        source.runCommandAsync('say off');
//        source.runCommandAsync('replaceitem entity @s slot.hotbar 0 rl_cr:music_off 1 1 {"item_lock": {"mode": "lock_in_slot"}}');
//        source.runCommandAsync('clear @a rl_cr:music_on 0 1');
//    }
//});

const cooldownPlayers = new Set();

world.afterEvents.itemUse.subscribe(data => {
    const { source, itemStack } = data;
    if (cooldownPlayers.has(source.id)) return;
    cooldownPlayers.add(source.id);
    system.runTimeout(() => {
        cooldownPlayers.delete(source.id);
    }, 20);

    if (itemStack.typeId === 'rl_cr:music_off') {
        source.setProperty("rl_cr:music_switch", true);

        source.sendMessage("[Music On] The background music has been activated for you");
        source.runCommandAsync(`replaceitem entity @s slot.hotbar 0 rl_cr:music_on 1 1 {"item_lock": {"mode": "lock_in_slot"}}`);
        source.runCommandAsync('clear @a rl_cr:music_off 0 1');
    }

    if (itemStack.typeId === 'rl_cr:music_on') {
        source.setProperty("rl_cr:music_switch", false);
        source.sendMessage("[Music Off] The background music has been disabled for you");
        source.runCommandAsync(`replaceitem entity @s slot.hotbar 0 rl_cr:music_off 1 1 {"item_lock": {"mode": "lock_in_slot"}}`);
        source.runCommandAsync('clear @a rl_cr:music_on 0 1');
    }
});

const typeToDust = new Map([
    ["minecraft:oak_planks", 1],
    ["minecraft:spruce_planks", 1],
    ["minecraft:birch_planks", 1],
    ["minecraft:oak_stairs", 1],
    ["minecraft:spruce_stairs", 1],
    ["minecraft:birch_stairs", 1],
    ["minecraft:oak_slab", 1],
    ["minecraft:spruce_slab", 1],
    ["minecraft:birch_slab", 1],
    ["minecraft:stone", 1],
    ["minecraft:andesite", 1],
    ["minecraft:stone_bricks", 1],
    ["minecraft:gray_concrete", 1],
    ["minecraft:smooth_stone", 1],
    ["minecraft:dirt", 2],
    ["minecraft:dirt_with_roots", 2],
    ["minecraft:grass_block", 3],
    ["minecraft:ice", 4],
    ["minecraft:prismarine", 4],
    ["minecraft:packed_ice", 4],
    ["minecraft:polished_blackstone", 5],
    ["minecraft:blackstone", 5],
    ["minecraft:sand", 6],
    ["minecraft:sandstone", 6],
    ["minecraft:stripped_birch_wood", 6],
    ["minecraft:end_bricks", 6],
    ["minecraft:end_stone", 6]
]);

system.runInterval(() => {
    for (const entity of world.getDimension("overworld").getEntities({ families: ["car_dust"] })) {
        const dimension = entity.dimension;
        const entityLocation = entity.location;
        const currentDust = entity.getProperty("rl_cr:dust") ?? 0;

        const blockBelow = dimension.getBlock({
            x: Math.floor(entityLocation.x),
            y: Math.floor(entityLocation.y) - 1,
            z: Math.floor(entityLocation.z)
        });

        if (blockBelow) {
            const newDust = typeToDust.get(blockBelow.typeId) ?? 0;
            if (newDust !== currentDust) {
                entity.setProperty("rl_cr:dust", newDust);
            }
        }
    }
}, 20);



system.runInterval(() => {
    const dimension = world.getDimension("overworld");
    let systemEntity;
    for (const entity of dimension.getEntities()) {
        if (entity.typeId === "rl_cr:system") {
            systemEntity = entity;
            break;
        }
    }
    if (!systemEntity) return;

    const gameState = systemEntity.getProperty("rl_cr:game_state") || "none";
    const gamemode = systemEntity.getProperty("rl_cr:gamemode") || "normal";

    const waitObj = world.scoreboard.getObjective("wait");
    const countObj = world.scoreboard.getObjective("count_registered");
    const countOngameObj = world.scoreboard.getObjective("count_ongame");
    const countExplodeObj = world.scoreboard.getObjective("count_explode");
    const timerExplodeObj = world.scoreboard.getObjective("timer_explode");
    const progressObj = world.scoreboard.getObjective("progress");
    const lapObj = world.scoreboard.getObjective("lap");

    if (!waitObj || !countObj || !countOngameObj || !timerExplodeObj || !progressObj || !lapObj) return;

    if (gameState === "wait" || gameState === "none") {
        const wait = waitObj.getScore(systemEntity) || 0;
        const count = countObj.getScore(systemEntity) || 0;
        const map = systemEntity.getProperty("rl_cr:map") || "iceberg";

        const maps = {
            "iceberg": "translate.text.w_iceberg",
            "oasis": "translate.text.w_oasis",
            "jungle": "translate.text.w_jungle",
            "dimensions": "translate.text.w_dimensions"
        };
        const modes = {
            "normal": "translate.text.w_normal",
            "explode": "translate.text.w_explode",
            "collect": "translate.text.w_collect"
        };

        const mapText = maps[map] || maps["iceberg"];
        const modeText = modes[gamemode] || modes["normal"];

        const command = `titleraw @a actionbar {"rawtext":[{"translate":"translate.text.w_timer"},{"score":{"name":"@e[type=rl_cr:system]","objective":"wait"}},{"text":"\\n"},{"translate":"${mapText}"},{"text":"\\n"},{"translate":"${modeText}"},{"text":"\\n"},{"translate":"translate.text.w_registered"},{"score":{"name":"@e[type=rl_cr:system]","objective":"count_registered"}},{"text":"/8"}]}`;
        systemEntity.runCommandAsync(command);
    }

    else if (gameState === "ongame" && systemEntity.hasTag("ongame")) {
        const countOngame = countExplodeObj.getScore(systemEntity);
        if (countOngame < 1) return;

        if (gamemode === "explode") {

            const removeUltimoTag = `execute as @e[family=player,scores={place=..${countOngame - 1}}] run tag @s remove ultimo`;
            const addUltimoTag = `execute as @e[family=player,scores={place=${countOngame}}] run tag @s add ultimo`;
            let rawtext = [
                { "translate": "translate.text.explode_in" },
                { "score": { "name": "@e[family=system]", "objective": "timer_explode" } },
                { "text": "\n" }
            ];

            for (let i = 1; i <= countOngame; i++) {
                const label = (i === countOngame) ? "" : `${i}`;
                rawtext.push({ "text": ` ${label}: ` });
                rawtext.push({ "selector": `@e[c=1,family=player,scores={place=${i}}]` });
                if (i < countOngame) rawtext.push({ "text": "\n" });
            }

            const command = `execute as @a[tag=ongame] at @s run titleraw @s actionbar ${JSON.stringify({ rawtext })}`;
            const command2 = `execute as @a[tag=finished] at @s run titleraw @s actionbar ${JSON.stringify({ rawtext })}`;
            systemEntity.runCommandAsync(command);
            systemEntity.runCommandAsync(command2);
            systemEntity.runCommandAsync(addUltimoTag);
            systemEntity.runCommandAsync(removeUltimoTag);
        }

        else if (gamemode === "collect") {
            let rawtext = [{ "text": "Points: " }];

            for (let i = 1; i <= countOngame; i++) {
                rawtext.push({ "text": `\nx` });
                rawtext.push({ "score": { "name": `@e[scores={place=${i}},family=player]`, "objective": "progress" } });
                rawtext.push({ "text": " " });
                rawtext.push({ "selector": `@e[c=1,family=player,scores={place=${i}}]` });
            }

            const command = `execute as @a[tag=ongame] at @s run titleraw @s actionbar ${JSON.stringify({ rawtext })}`;
            const command2 = `execute as @a[tag=finished] at @s run titleraw @s actionbar ${JSON.stringify({ rawtext })}`;
            systemEntity.runCommandAsync(command);
            systemEntity.runCommandAsync(command2);
        }

        else if (gamemode === "normal") {
            let rawtext = [
                { "text": " LAP: " },
                { "score": { "name": "@s", "objective": "lap" } },
                { "text": "/3\n" }
            ];

            for (let i = 1; i <= countOngame; i++) {
                rawtext.push({ "text": ` ${i}: ` });
                rawtext.push({ "selector": `@e[c=1,family=player,scores={place=${i}}]` });
                if (i < countOngame) rawtext.push({ "text": "\n" });
            }

            const command = `execute as @a[tag=ongame] at @s run titleraw @s actionbar ${JSON.stringify({ rawtext })}`;
            const command2 = `execute as @a[tag=finished] at @s run titleraw @s actionbar ${JSON.stringify({ rawtext })}`;
            systemEntity.runCommandAsync(command);
            systemEntity.runCommandAsync(command2);
        }
    }

}, 4);
system.runInterval(() => {
    const dimension = world.getDimension("overworld");
    const rankTags = [
        "one", "two", "three", "four",
        "five", "six", "seven", "eight"
    ];
    const maxRanks = rankTags.length;

    const progressObjective = world.scoreboard.getObjective("progress");
    const rankPlaceObjective = world.scoreboard.getObjective("place");
    const placeTimerObjective = world.scoreboard.getObjective("place_timer");

    if (!progressObjective || !rankPlaceObjective || !placeTimerObjective) return;

    const playerEntities = dimension.getEntities({ families: ["player"], tags: ["ongame"] });

    const playersWithScores = playerEntities.map(entity => {
        const progress = progressObjective.getScore(entity) ?? -1;
        const timer = placeTimerObjective.getScore(entity) ?? -1;
        return { entity, progress, timer };
    });

    playersWithScores.sort((a, b) => {
        if (b.progress !== a.progress) {
            return b.progress - a.progress;
        }
        return b.timer - a.timer;
    });

    for (const { entity } of playersWithScores) {
        for (const tag of rankTags) {
            if (entity.hasTag(tag)) entity.removeTag(tag);
        }
        rankPlaceObjective.setScore(entity, 0);
    }

    for (let i = 0; i < playersWithScores.length && i < maxRanks; i++) {
        const { entity } = playersWithScores[i];
        const tag = rankTags[i];
        entity.addTag(tag);
        rankPlaceObjective.setScore(entity, i + 1);
    }

}, 1);



system.runInterval(() => {
    const count_registered_all = "count_registered";
    const count_bots_registered = "bots_registered";
    const count_players_registered = "player_registered";
    const count_explode = "count_explode";
    const count_ongame = "count_ongame";
    const count_players = "count_players";
    const count_one_duplicated = "one_duplicated_count";
    const count_two_duplicated = "two_duplicated_count";
    const count_three_duplicated = "three_duplicated_count";
    const count_four_duplicated = "four_duplicated_count";
    const count_five_duplicated = "five_duplicated_count";
    const count_six_duplicated = "six_duplicated_count";
    const count_seven_duplicated = "seven_duplicated_count";
    const count_eight_duplicated = "eight_duplicated_count";
    const count_finished = "count_finished";

    const scoreboardAll = world.scoreboard.getObjective(count_registered_all);
    const scoreboardBots = world.scoreboard.getObjective(count_bots_registered);
    const scoreboardPlayers = world.scoreboard.getObjective(count_players_registered);
    const scoreboardExplode = world.scoreboard.getObjective(count_explode);
    const scoreboardOngame = world.scoreboard.getObjective(count_ongame);
    const scoreboardCountPlayers = world.scoreboard.getObjective(count_players);
    const scoreboardOneDuplicated = world.scoreboard.getObjective(count_one_duplicated);
    const scoreboardTwoDuplicated = world.scoreboard.getObjective(count_two_duplicated);
    const scoreboardThreeDuplicated = world.scoreboard.getObjective(count_three_duplicated);
    const scoreboardFourDuplicated = world.scoreboard.getObjective(count_four_duplicated);
    const scoreboardFiveDuplicated = world.scoreboard.getObjective(count_five_duplicated);
    const scoreboardSixDuplicated = world.scoreboard.getObjective(count_six_duplicated);
    const scoreboardSevenDuplicated = world.scoreboard.getObjective(count_seven_duplicated);
    const scoreboardEightDuplicated = world.scoreboard.getObjective(count_eight_duplicated);
    const scoreboardFinished = world.scoreboard.getObjective(count_finished);

    const registeredAll = world.getDimension("overworld").getEntities({ tags: ["registered"] });
    const entityCountAll = registeredAll.length;

    const registeredBots = world.getDimension("overworld").getEntities({
        tags: ["registered"],
        families: ["player_bot"]
    });
    const registeredPlayers = world.getDimension("overworld").getEntities({
        tags: ["registered"],
        type: "player"
    });
    const botCount = registeredBots.length;
    const playerCount = registeredPlayers.length;

    const explodePlayers = world.getDimension("overworld").getEntities({
        tags: ["explode_off"],
        families: ["player"]
    });
    const explodeCount = explodePlayers.length;

    const ongamePlayers = world.getDimension("overworld").getEntities({
        tags: ["ongame"],
        families: ["player"]
    });
    const ongameCount = ongamePlayers.length;
    const allPlayers = world.getDimension("overworld").getEntities({
        type: "player"
    });
    const totalPlayersCount = allPlayers.length;

    const oneDuplicatedPlayers = world.getDimension("overworld").getEntities({
        tags: ["ongame"],
        families: ["player"],
        scoreOptions: [{ objective: "place", minScore: 1, maxScore: 1 }]
    });
    const twoDuplicatedPlayers = world.getDimension("overworld").getEntities({
        tags: ["ongame"],
        families: ["player"],
        scoreOptions: [{ objective: "place", minScore: 2, maxScore: 2 }]
    });
    const threeDuplicatedPlayers = world.getDimension("overworld").getEntities({
        tags: ["ongame"],
        families: ["player"],
        scoreOptions: [{ objective: "place", minScore: 3, maxScore: 3 }]
    });
    const fourDuplicatedPlayers = world.getDimension("overworld").getEntities({
        tags: ["ongame"],
        families: ["player"],
        scoreOptions: [{ objective: "place", minScore: 4, maxScore: 4 }]
    });
    const fiveDuplicatedPlayers = world.getDimension("overworld").getEntities({
        tags: ["ongame"],
        families: ["player"],
        scoreOptions: [{ objective: "place", minScore: 5, maxScore: 5 }]
    });
    const sixDuplicatedPlayers = world.getDimension("overworld").getEntities({
        tags: ["ongame"],
        families: ["player"],
        scoreOptions: [{ objective: "place", minScore: 6, maxScore: 6 }]
    });
    const sevenDuplicatedPlayers = world.getDimension("overworld").getEntities({
        tags: ["ongame"],
        families: ["player"],
        scoreOptions: [{ objective: "place", minScore: 7, maxScore: 7 }]
    });
    const eightDuplicatedPlayers = world.getDimension("overworld").getEntities({
        tags: ["ongame"],
        families: ["player"],
        scoreOptions: [{ objective: "place", minScore: 8, maxScore: 8 }]
    });

    const finishedEntities = world.getDimension("overworld").getEntities({
        tags: ["finished"]
    });

    const finishedCount = finishedEntities.length;
    const oneDuplicatedCount = oneDuplicatedPlayers.length;
    const twoDuplicatedCount = twoDuplicatedPlayers.length;
    const threeDuplicatedCount = threeDuplicatedPlayers.length;
    const fourDuplicatedCount = fourDuplicatedPlayers.length;
    const fiveDuplicatedCount = fiveDuplicatedPlayers.length;
    const sixDuplicatedCount = sixDuplicatedPlayers.length;
    const sevenDuplicatedCount = sevenDuplicatedPlayers.length;
    const eightDuplicatedCount = eightDuplicatedPlayers.length;

    let systemEntity = null;
    for (const entity of world.getDimension("overworld").getEntities()) {
        if (entity.typeId === "rl_cr:system") {
            systemEntity = entity;
            break;
        }
    }

    if (systemEntity) {
        scoreboardAll.setScore(systemEntity, entityCountAll);
        scoreboardBots.setScore(systemEntity, botCount);
        scoreboardPlayers.setScore(systemEntity, playerCount);
        scoreboardExplode.setScore(systemEntity, explodeCount);
        scoreboardOngame.setScore(systemEntity, ongameCount);
        scoreboardCountPlayers.setScore(systemEntity, totalPlayersCount);
        scoreboardOneDuplicated.setScore(systemEntity, oneDuplicatedCount);
        scoreboardTwoDuplicated.setScore(systemEntity, twoDuplicatedCount);
        scoreboardThreeDuplicated.setScore(systemEntity, threeDuplicatedCount);
        scoreboardFourDuplicated.setScore(systemEntity, fourDuplicatedCount);
        scoreboardFiveDuplicated.setScore(systemEntity, fiveDuplicatedCount);
        scoreboardSixDuplicated.setScore(systemEntity, sixDuplicatedCount);
        scoreboardSevenDuplicated.setScore(systemEntity, sevenDuplicatedCount);
        scoreboardEightDuplicated.setScore(systemEntity, eightDuplicatedCount);
        scoreboardFinished.setScore(systemEntity, finishedCount);
    }
}, 1);

world.afterEvents.entityHitEntity.subscribe((eventData) => {
    const hitEntity = eventData.hitEntity
    const damagingEntity = eventData.damagingEntity

    const ride = damagingEntity.getComponent("minecraft:riding");

    if (ride && ride.entityRidingOn && hitEntity.typeId === "rl_cr:car") {
        hitEntity.runCommand(`function horn`);
    }
    if (ride && ride.entityRidingOn && hitEntity.typeId === "rl_cr:car_test") {
        hitEntity.runCommand(`function horn`);
    }
    if (hitEntity.typeId === "rl_cr:edit_game") {
        damagingEntity.runCommand(`execute as @s at @s if entity @e[has_property={rl_cr:main=false}] if entity @e[has_property={rl_cr:game_state="none"}] run tag @s add edit_game`);
        damagingEntity.runCommand(`execute as @s at @s if  entity @e[has_property={rl_cr:main=true}] run titleraw @s subtitle {\"rawtext\":[ {\"text\":\"\n\n\n\n\n\"},{\"translate\":\"translate.text.edit_true\"} ]}`);
    }
});


const blockComponentConfigs = [
    {
        id: 'rl_cr:false_block',
        interval: 10,
        onTick(e) {
            const block = e.block;
            const state = block.permutation.getState('rl_cr:sand_false');
            const typeId = block.typeId;

            const transitions = {
                'rl_cr:sand_false': { 'break': 'visible' },
                'rl_cr:sandstone_false': { 'breaking': 'break', 'break': 'visible' },
                'rl_cr:magma_false': { 'visible': 'fall', 'fall': 'visible' },
                'rl_cr:ice_peak': { 'visible': 'fall', 'fall': 'visible' }
            };

            if (typeId in transitions && state in transitions[typeId]) {
                block.setPermutation(block.permutation.withState('rl_cr:sand_false', transitions[typeId][state]));
                if (typeId === 'rl_cr:sandstone_false' && state === 'breaking') particleSand(block.location);
                if (typeId === 'rl_cr:magma_false' && state === 'visible') magma(block.location);
                if (typeId === 'rl_cr:ice_peak' && block.permutation.getState('minecraft:block_face') === 'down' && state === 'visible') icePeak(block.location);
            }
        }
    },
    {
        id: 'rl_cr:coins',
        interval: 20,
        onTick(e) {
            if (e.block.typeId === 'rl_cr:coins_spawner') coin(e.block.location);
        }
    },
    {
        id: 'rl_cr:target',
        onPlayerInteract(e) {
            const map = {
                "minecraft:stone": "stone",
                "minecraft:spruce_planks": "spruce_planks",
                "minecraft:packed_mud": "packed_mud",
                "minecraft:podzol": "podzol",
                "minecraft:grass_block": "grass_block",
                "minecraft:packed_ice": "packed_ice",
                "minecraft:stripped_birch_wood": "stripped_birch_wood",
                "minecraft:birch_planks": "birch_planks",
                "minecraft:sandstone": "sandstone",
                "minecraft:dirt_with_roots": "dirt_with_roots",
                "minecraft:deepslate": "deepslate",
                "minecraft:polished_blackstone": "polished_blackstone",
                "minecraft:end_bricks": "end_bricks",
                "minecraft:obsidian": "obsidian"
            };

            const mainItem = e.player.getComponent("minecraft:equippable")?.getEquipment(EquipmentSlot.Mainhand);
            const newMode = map[mainItem?.typeId];
            if (newMode) e.block.setPermutation(e.block.permutation.withState('rl_cr:mode', newMode));
        }
    },
    {
        id: 'rl_cr:villager_block',
        onPlayerInteract(e) {
            const block = e.block;
            const currentState = block.permutation.getState('rl_cr:skin');

            const currentModeNumber = parseInt(currentState.replace('mode', ''), 10);

            const nextModeNumber = currentModeNumber === 8 ? 1 : currentModeNumber + 1;

            const nextMode = `mode${nextModeNumber}`;

            block.setPermutation(block.permutation.withState('rl_cr:skin', nextMode));
        }
    }
];

world.beforeEvents.worldInitialize.subscribe(eventData => {
    for (const config of blockComponentConfigs) {
        eventData.blockComponentRegistry.registerCustomComponent(config.id, config);
    }
});

function particleSand(location) {
    let command = `/execute positioned ${location.x + 0.5} ${location.y} ${location.z + 0.5} run particle rl_cr:sand_break`;
    let command2 = `/execute positioned ${location.x + 0.5} ${location.y} ${location.z + 0.5} run playsound dig.sand @a[r=10]`;
    world.getDimension("overworld").runCommand(command);
    world.getDimension("overworld").runCommand(command2);
}
function magma(location) {
    let command = `/execute positioned ${location.x + 0.5} ${location.y} ${location.z + 0.5} run summon rl_cr:magma ~~-1~ ~~`;
    world.getDimension("overworld").runCommand(command);
}
function coin(location) {
    let command = `/execute positioned ${location.x + 0.5} ${location.y} ${location.z + 0.5} if entity @e[family=system,has_property={rl_cr:gamemode="collect",rl_cr:game_state="ongame"}] run summon rl_cr:coin ~~-1~ ~~`;
    world.getDimension("overworld").runCommand(command);
}
function icePeak(location) {
    let command = `/execute positioned ${location.x + 0.5} ${location.y} ${location.z + 0.5} run summon rl_cr:ice_peak_entity`;
    world.getDimension("overworld").runCommand(command);
}



const scoreList = ["paint", "wheel", "bumper", "hood", "roof", "spoiler", "exhaust", "vinyl", "glass", "horn"];
const carTypes = ["rl_cr:car", "rl_cr:car2", "rl_cr:car_test"];

system.runInterval(() => {
    for (const player of world.getPlayers()) {
        try {
            const ride = player.getComponent("minecraft:riding");
            if (!ride || !ride.entityRidingOn) continue;

            const ridingEntity = ride.entityRidingOn;
            if (!carTypes.includes(ridingEntity.typeId)) continue;

            for (const score of scoreList) {
                const scoreObj = world.scoreboard.getObjective(score);
                if (!scoreObj) continue;
                const playerScore = scoreObj.getScore(player);
                if (playerScore !== undefined) scoreObj.setScore(ridingEntity, playerScore);
            }

            if (ridingEntity.typeId === "rl_cr:car") {
                const tagsToCheck = ['one_id', 'two_id', 'three_id', 'four_id', 'five_id', 'six_id', 'seven_id', 'eight_id'];
                for (const tag of tagsToCheck) {
                    if (player.hasTag(tag)) {
                        ridingEntity.runCommandAsync(`tag @s[tag=!spectator] add ${tag}`);
                    }
                }

                if (player.hasTag('explotado')) {
                    ridingEntity.runCommandAsync("tag @s add explotado");
                    ridingEntity.runCommandAsync("effect @s slowness 9999 100 true");
                    ridingEntity.runCommandAsync("tp @s ~~~ ~~");
                    player.runCommandAsync("inputpermission set @s movement disabled");
                }
                if (player.hasTag('finished')) {
                    ridingEntity.runCommandAsync("effect @s slowness 9999 50 true");
                    ridingEntity.runCommandAsync("tp @s ~~~ ~~");
                    player.runCommandAsync("inputpermission set @s movement disabled");
                }

                if (player.hasTag('ultimo')) {
                    ridingEntity.runCommandAsync("tag @s add ultimo");
                } else {
                    ridingEntity.runCommandAsync("tag @s remove ultimo");
                }
            }
        } catch { }
    }
}, 10);


//system.runInterval(() => {
//    for (const player of world.getAllPlayers()) {
//        if (player.hasTag('one_id')) {
//            player.runCommandAsync("ride @s start_riding @e[type=rl_cr:car,tag=one_id,c=1]");
//        }
//        if (player.hasTag('two_id')) {
//            player.runCommandAsync("ride @s start_riding @e[type=rl_cr:car,tag=two_id,c=1]");
//        }
//        if (player.hasTag('three_id')) {
//            player.runCommandAsync("ride @s start_riding @e[type=rl_cr:car,tag=three_id,c=1]");
//        }
//        if (player.hasTag('four_id')) {
//            player.runCommandAsync("ride @s start_riding @e[type=rl_cr:car,tag=four_id,c=1]");
//        }
//        if (player.hasTag('five_id')) {
//            player.runCommandAsync("ride @s start_riding @e[type=rl_cr:car,tag=five_id,c=1]");
//        }
//        if (player.hasTag('six_id')) {
//            player.runCommandAsync("ride @s start_riding @e[type=rl_cr:car,tag=six_id,c=1]");
//        }
//        if (player.hasTag('seven_id')) {
//            player.runCommandAsync("ride @s start_riding @e[type=rl_cr:car,tag=seven_id,c=1]");
//        }
//        if (player.hasTag('eight_id')) {
//            player.runCommandAsync("ride @s start_riding @e[type=rl_cr:car,tag=eight_id,c=1]");
//        }
//    }
//}, 1);



system.runInterval(() => {
    const entityType = "rl_cr:car2";

    const scorePropertyPairs = [
        { score: "paint", property: "rl_cr:paint" },
        { score: "wheel", property: "rl_cr:wheel" },
        { score: "bumper", property: "rl_cr:bumper" },
        { score: "hood", property: "rl_cr:hood" },
        { score: "roof", property: "rl_cr:roof" },
        { score: "spoiler", property: "rl_cr:spoiler" },
        { score: "exhaust", property: "rl_cr:exhaust" },
        { score: "vinyl", property: "rl_cr:vinyl" },
        { score: "glass", property: "rl_cr:glass" },
        { score: "horn", property: "rl_cr:horn" }
    ];

    let entities = world.getDimension("overworld").getEntities({
        type: entityType
    });

    for (let entity of entities) {
        for (let pair of scorePropertyPairs) {
            let entityScore = world.scoreboard.getObjective(pair.score)?.getScore(entity);

            if (entityScore !== undefined) {
                entity.setProperty(pair.property, entityScore);
            }
        }
    }
}, 4);
system.runInterval(() => {
    const dimension = world.getDimension("overworld");
    const scoreObjective = world.scoreboard.getObjective("place");
    if (!scoreObjective) return;

    for (const player of world.getPlayers()) {
        try {
            const riding = player.getComponent("minecraft:riding");
            const ridingEntity = riding?.entityRidingOn;
            if (!ridingEntity || ridingEntity.typeId !== "rl_cr:car") continue;

            const score = scoreObjective.getScore(player);
            if (score >= 3 && score <= 8) {
                ridingEntity.runCommandAsync(`/execute as @s at @s unless entity @e[type=rl_cr:car_bot,r=10,scores={place=..2}] run effect @s speed 1 0 true`);
                ridingEntity.runCommandAsync(`/execute as @s at @s if entity @e[type=rl_cr:car_bot,r=10,scores={place=..2}] run effect @s speed 0 0 true`);
            }
        } catch (e) {
        }
    }
}, 20);