import { world, Player, system, ItemStack } from "@minecraft/server";

const vehicles = [
  "pb_plane:plane_air_tractor",
  "pb_plane:plane_airtrike",
  "pb_plane:plane_biplane",
  "pb_plane:plane_skyhawk",
  "pb_plane:plane_cadanair",
  "pb_plane:plane_cruiser",
  "pb_plane:plane_ember_120",
  "pb_plane:plane_magister",
  "pb_plane:plane_gilbert",
  "pb_plane:plane_glider",
  "pb_plane:plane_galapagos",
  "pb_plane:plane_lockheed_12a",
  "pb_plane:plane_northstar",
  "pb_plane:plane_wooden",
  "pb_plane:plane_lightning",
  "pb_plane:plane_passenger_jet",
  "pb_plane:plane_ricarde",
  "pb_plane:plane_seaplane",
  "pb_plane:plane_marine",
  "pb_plane:plane_triplane",
  "pb_plane:plane_vampire",
  "pb_plane:heli_cargo",
  "pb_plane:heli_leopard",
  "pb_plane:heli_remedy",
  "pb_plane:drone_passenger",
  "pb_plane:blimp_zeppelin",
  "pb_plane:speed_boat",
  "pb_plane:car_sports",
  "pb_plane:car_police",
  "pb_plane:car_fire",
  "pb_plane:car_fire_large",
];

const crates = ["pb_plane:cargo_crate", "pb_plane:item_crate"];
const vehicleHitData = new Map();

world.afterEvents.entityHitEntity.subscribe(({ damagingEntity, hitEntity }) => {
  if (
    !vehicles.includes(hitEntity.typeId) &&
    !crates.includes(hitEntity.typeId)
  )
    return;
  if (damagingEntity instanceof Player) {
    if (vehicles.includes(hitEntity.typeId)) {
      if (hitEntity.isOnGround || hitEntity.isInWater) {
        const driver = hitEntity?.getComponent("rideable").getRiders()[0];
        if (driver) return;
        // Get all data for item drop
        let hitData = vehicleHitData.get(hitEntity);
        const vehicleType = hitEntity.typeId.split(":")[1];
        const patternType = hitEntity.getProperty("pb_plane:pattern") + 1;

        const itemToDrop = new ItemStack(
          `pb_plane:${vehicleType}_${patternType}`,
          1
        );
        // Track hits within 2 seconds - 4 hits drops the vehicle
        if (!hitData) {
          hitData = {
            hits: 0,
            requiredHits: 4,
          };
          vehicleHitData.set(hitEntity, hitData);
        }
        hitEntity.playAnimation("animation.pb_plane.vehicle_shake", {
          blendOutTime: 1,
          stopExpression: "query.any_animation_finished",
        });
        hitData.hits++;
        system.runTimeout(() => {
          hitData.hits = 0;
        }, 40);

        // If enough hits within time
        if (hitData.hits >= hitData.requiredHits) {
          hitEntity.triggerEvent("pb_plane:drop");
          hitEntity.addEffect("invisibility", 20, {
            amplifier: 1,
            showParticles: false,
          });
          system.runTimeout(() => {
            dropVehicleItem(hitEntity, itemToDrop);
          }, 2);
        }
      }
    }
    if (crates.includes(hitEntity.typeId)) {
      let hitData = vehicleHitData.get(hitEntity);

      const crateType = hitEntity.typeId.split(":")[1];
      const itemToDrop = new ItemStack(`pb_plane:${crateType}`, 1);
      if (!hitData) {
        hitData = {
          hits: 0,
          requiredHits: 4,
        };
        vehicleHitData.set(hitEntity, hitData);
      }
      hitEntity.playAnimation("animation.pb_plane.vehicle_shake", {
        blendOutTime: 1,
        stopExpression: "query.any_animation_finished",
      });
      hitData.hits++;
      system.runTimeout(() => {
        hitData.hits = 0;
      }, 40);
      if (hitData.hits >= hitData.requiredHits) {
        hitEntity.addEffect("invisibility", 20, {
          amplifier: 1,
          showParticles: false,
        });
        system.runTimeout(() => {
          dropVehicleItem(hitEntity, itemToDrop);
        }, 2);
      }
    }
  }
});

function dropVehicleItem(hitEntity, itemToDrop) {
  const lore = [];

  // Convert normalized RGB values to hex and add them to the lore
  if (hitEntity.getProperty("pb_plane:colored_1")) {
    const red1 = hitEntity.getProperty("pb_plane:red_1") * 255;
    const green1 = hitEntity.getProperty("pb_plane:green_1") * 255;
    const blue1 = hitEntity.getProperty("pb_plane:blue_1") * 255;
    const alpha1 = hitEntity.getProperty("pb_plane:alpha_1"); // Get alpha property
    const hex1 = rgbToHex(red1, green1, blue1, alpha1);
    lore.push(`Layer 1: ${hex1}`);
  }

  if (hitEntity.getProperty("pb_plane:colored_2")) {
    const red2 = hitEntity.getProperty("pb_plane:red_2") * 255;
    const green2 = hitEntity.getProperty("pb_plane:green_2") * 255;
    const blue2 = hitEntity.getProperty("pb_plane:blue_2") * 255;
    const alpha2 = hitEntity.getProperty("pb_plane:alpha_2"); // Get alpha property
    const hex2 = rgbToHex(red2, green2, blue2, alpha2);
    lore.push(`Layer 2: ${hex2}`);
  }

  if (hitEntity.typeId == "pb_plane:cargo_crate") {
    hitEntity?.getComponent("minecraft:rideable").ejectRiders();
  }

  // Set the generated lore on the item
  itemToDrop.setLore(lore);

  // Spawn the item at the entity's location
  hitEntity.dimension.spawnItem(itemToDrop, hitEntity.location);
  hitEntity.kill(); // Remove the entity
  hitEntity.teleport({
    x: hitEntity.location.x,
    y: hitEntity.location.y - 1000,
    z: hitEntity.location.z,
  }); // Ensure the entity is effectively removed
  vehicleHitData.delete(hitEntity);
}

// Helper function to convert RGB to hex (with optional alpha)
function rgbToHex(r, g, b, alpha = 1) {
  const alphaHex = Math.round(alpha * 255)
    .toString(16)
    .padStart(2, "0"); // Convert alpha to hex
  return (
    "#" +
    [r, g, b]
      .map((v) => {
        const clamped = Math.max(0, Math.min(255, Math.round(v))); // Clamp and round values
        const hex = clamped.toString(16); // Convert to hex
        return hex.length === 1 ? "0" + hex : hex; // Ensure 2-character hex
      })
      .join("") +
    alphaHex // Add alpha as the last two digits
  );
}
