import { world, system } from "@minecraft/server";
import { getMainAmmo, getSubAmmo, getFlareAmmo } from "./AmmoSystem.js";
import { VEHICLES } from "./VehiclesRoot.js";

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

function getVehicleConfig(vehicle) {
    return Object.values(VEHICLES).find(v => v.identifier === vehicle.typeId);
}

function getHudPrefix(vehicle) {
    const vehicleConfig = getVehicleConfig(vehicle);
    const modelType = vehicleConfig?.modelType;

    switch(modelType) {
        case "TANK":
            return {
                left: "hud:ttav_left_tank_info:",
                right: "hud:ttav_right_tank_info:",
                top: "hud:ttav_top_tank_info:"
            };
        case "ARTILLERY":
            return {
                left: "hud:ttav_left_artillery_info:",
                right: "hud:ttav_right_artillery_info:",
                top: "hud:ttav_top_artillery_info:"
            };
        case "MLRS":
            return {
                left: "hud:ttav_left_mlrs_info:",
                right: "hud:ttav_right_mlrs_info:",
                top: "hud:ttav_top_mlrs_info:"
            };    
        case "APV_ROCKET":
            return {
                left: "hud:ttav_left_apv_rocket_info:",
                right: "hud:ttav_right_apv_rocket_info:",
                top: "hud:ttav_top_apv_rocket_info:"
            };
        case "IFV_ROCKET":
            return {
                left: "hud:ttav_left_ifv_rocket_info:",
                right: "hud:ttav_right_ifv_rocket_info:",
                top: "hud:ttav_top_ifv_rocket_info:"
            };
        case "IFV":
            return {
                left: "hud:ttav_left_ifv_rocket_info:",
                right: "hud:ttav_right_ifv_rocket_info:",
                top: "hud:ttav_top_ifv_rocket_info:"
            };          
            default:
                return;
        }
    }
    
    function getColoredFuelStatus(fuel, config) {
        if (!config || !config.fuelLevels) return "§c";
        
        let color = "§c";
        if (fuel >= config.fuelLevels.green) {
            color = "§a";
        } else if (fuel >= config.fuelLevels.yellow) {
            color = "§e";
        }
        return color;
    }
    
    function displayLeftStatus(vehicle, rider) {
        const config = getVehicleConfig(vehicle);
        if (!config || !config.fuelLevels) return;
    
        const fuel = vehicle.getDynamicProperty("fuel_value") || 0;
        const fuelColor = getColoredFuelStatus(fuel, config);
        const fuelPercentage = Math.floor((fuel / config.fuelLevels.max) * 100);
        const engineStatus = vehicle.getDynamicProperty("ttav:engine") ? "§aON" : "§cOFF";
        const velocity = vehicle.getVelocity();
        const isMoving = Math.abs(velocity.x) > 0.01 || Math.abs(velocity.z) > 0.01;
        const speed = isMoving ? Math.floor(Math.random() * 30) + 30 : 0;
    
        const prefix = getHudPrefix(vehicle);
        const message1 =
            `§6\n${fuelColor}${fuelPercentage}%\n` +
            `§6\n\n${engineStatus}\n` +
            `§6\n\n${speed}\n`;
    
        rider.runCommand(`titleraw @s title {"rawtext":[{"text":"${prefix.left}${message1}"}]}`);
    }
    
    function displayRightStatus(vehicle, rider) {
        const mainAmmo = getMainAmmo(vehicle);
        const subAmmo = getSubAmmo(vehicle);
        const flareAmmo = getFlareAmmo(vehicle);
        
        const healthComponent = vehicle.getComponent("minecraft:health");
        const currentHealth = healthComponent.currentValue;
        const maxHealth = healthComponent.value;
    
        const prefix = getHudPrefix(vehicle);
        const message2 =
            `§6\n${mainAmmo}\n` +
            `§6\n\n${subAmmo}\n` +
            `§6\n\n${flareAmmo}\n` +
            `§6\n\n${Math.floor(currentHealth)}`;    
    
        rider.runCommand(`titleraw @s title {"rawtext":[{"text":"${prefix.right}${message2}"}]}`);
    }
    
    function getDirectionString(rotation) {
        const directions = ['S', 'SW', 'W', 'NW', 'N', 'NE', 'E', 'SE'];
        let index = Math.floor(((rotation + 180) % 360) / 45);
        if (index < 0) index += 8;
        
        const current = directions[index];
        const prev2 = directions[(index + 6) % 8];
        const prev1 = directions[(index + 7) % 8];
        const next1 = directions[(index + 1) % 8];
        const next2 = directions[(index + 2) % 8];
    
        return `§6${prev2}            §6${prev1}            §e${current}        §6${next1}          §6${next2}`;
    }
    
    function displayCompass(vehicle, rider) {
        const rotation = rider.getRotation().y;
        const compassMessage = getDirectionString(rotation);
        const prefix = getHudPrefix(vehicle);
        rider.runCommand(`titleraw @s title {"rawtext":[{"text":"${prefix.top}${compassMessage}"}]}`);
    }
    
    function updateLeftHUD() {
        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) {
                    const engineOn = vehicle.getDynamicProperty("ttav:engine");
                    if (!engineOn) continue;
                    const rideableComponent = vehicle.getComponent("minecraft:rideable");
                    if (!rideableComponent) continue;
                    const riders = rideableComponent.getRiders();
                    if (riders.length === 0) continue;
                    for (const rider of riders) {
                        displayLeftStatus(vehicle, rider);
                    }
                }
            }
        }
    }
    
    function updateRightHUD() {
        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) {
                    const engineOn = vehicle.getDynamicProperty("ttav:engine");
                    if (!engineOn) continue;
                    const rideableComponent = vehicle.getComponent("minecraft:rideable");
                    if (!rideableComponent) continue;
                    const riders = rideableComponent.getRiders();
                    if (riders.length === 0) continue;
                    for (const rider of riders) {
                        displayRightStatus(vehicle, rider);
                    }
                }
            }
        }
    }
    
    function updateCompassHUD() {
        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) {
                    const engineOn = vehicle.getDynamicProperty("ttav:engine");
                    if (!engineOn) continue;
                    const rideableComponent = vehicle.getComponent("minecraft:rideable");
                    if (!rideableComponent) continue;
                    const riders = rideableComponent.getRiders();
                    if (riders.length === 0) continue;
                    for (const rider of riders) {
                        displayCompass(vehicle, rider);
                    }
                }
            }
        }
    }
    
    let tickCounter = 0;
    
    function updateHUD() {
        switch (tickCounter % 3) {
            case 0:
                updateLeftHUD();
                break;
            case 1:
                updateRightHUD();
                break;
            case 2:
                updateCompassHUD();
                break;
        }
        tickCounter++;
    }
    
    system.runInterval(updateHUD, 1);