import { world, system, MolangVariableMap } from "@minecraft/server";
import { VEHICLES } from "./VehiclesRoot.js";
import { handleAmmoReload, AMMO_ITEMS } from "./AmmoSystem.js";

const dimensions = [
    world.getDimension("minecraft:overworld"),
    world.getDimension("minecraft:nether"),
    world.getDimension("minecraft:the_end"),
];

function handleFuelConsumption() {
    for (const dimension of dimensions) {
        for (const [vehicleType, config] of Object.entries(VEHICLES)) {
            const vehicles = dimension.getEntities({ type: config.identifier });
           
            for (const vehicle of vehicles) {
                if (!vehicle.hasComponent("minecraft:movement")) continue;

                const velocity = vehicle.getVelocity();
                const isMoving = Math.abs(velocity.x) > 0.01 || Math.abs(velocity.z) > 0.01;

                if (isMoving) {
                    const currentFuel = vehicle.getDynamicProperty("fuel_value") || 0;
                    const newFuel = Math.max(0, currentFuel - 1);
                    vehicle.setDynamicProperty("fuel_value", newFuel);

                    if (newFuel === 0) {
                        vehicle.triggerEvent("out_of_fuel");
                    }
                }
            }
        }
    }
}

world.afterEvents.playerInteractWithEntity.subscribe((event) => {
    const { player, target } = event;
    const mainHandItem = player.getComponent("minecraft:equippable")?.getEquipment("Mainhand");

    
    const config = Object.values(VEHICLES).find(v => v.identifier === target.typeId);
    if (!config) return;

    
    if (mainHandItem && Object.values(AMMO_ITEMS).includes(mainHandItem.typeId)) {
        handleAmmoReload(player, target, mainHandItem.typeId);
        return;
    }

    
    const restrictedItems = [
        config.controllerItem,
        config.mainGunItem,
        config.subGunItem,
        config.flareGunItem,
        config.refuelItem
    ];

    const isHoldingRestrictedItem = mainHandItem && restrictedItems.includes(mainHandItem.typeId);
    const isRiding = target.getComponent("minecraft:rideable")?.getRiders().length > 0;

    
    if (!isHoldingRestrictedItem) {
        if (!player.isSneaking) {
            player.playSound("ttavTankDoorOpen_close", { pitch: 1.0, volume: 1.0 });
            
            const effectOptions = {
                amplifier: 3,
                showParticles: false
            };
    
            player.addEffect("fire_resistance", 20000000, effectOptions);
            player.addEffect("instant_health", 20000000, effectOptions);
            player.addEffect("resistance", 20000000, effectOptions);
            player.addEffect("water_breathing", 20000000, effectOptions);
        }
    }
    

    if (!isRiding && !isHoldingRestrictedItem) {
        if (player.isSneaking) {
            player.playSound("ttavTankDoorOpen", { pitch: 1.0, volume: 1.0 });
        }
    }

    
    for (const [vehicleType, config] of Object.entries(VEHICLES)) {
        if (target.typeId === config.identifier && mainHandItem?.typeId === config.refuelItem) {
            const currentFuel = target.getDynamicProperty("fuel_value") || 0;
            const newFuel = Math.min(config.fuelLevels.max, currentFuel + config.refuelAmount);
           
            if (currentFuel < config.fuelLevels.max) {
                target.setDynamicProperty("fuel_value", newFuel);
                player.runCommand(`clear @s ${config.refuelItem} 1`);
                target.triggerEvent("refueled");
                player.playSound("ttavRefuel", { pitch: 1.0, volume: 1.0 });
               
                const addedFuel = newFuel - currentFuel;
                player.onScreenDisplay.setActionBar(`§a添加燃料! §f(§e${Math.floor((newFuel/config.fuelLevels.max)*100)}%§f)`);
               
                target.dimension.spawnParticle("ttav:tank_interact_fx",
                    { x: target.location.x, y: target.location.y, z: target.location.z },
                    new MolangVariableMap()
                );
            } else {
                player.onScreenDisplay.setActionBar("§c燃油箱已满!");
                player.playSound("note.bass", { pitch: 1.0, volume: 1.0 });
            }
        }
    }
});

system.runInterval(handleFuelConsumption, 20);
