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

// Map: bike item id -> bike entity id
const BIKE_MAP = {
  "pr:bicycle_gen1": "pr:bicycle_gen1",
  "pr:bicycle_gen2": "pr:bicycle_gen2",
  "pr:bicycle_gen3": "pr:bicycle_gen3",
  "pr:bicycle_gen4": "pr:bicycle_gen4",
  "pr:bicycle_gen5": "pr:bicycle_gen5",
  "pr:bicycle_gen6": "pr:bicycle_gen6",
  "pr:acro_bike": "pr:acro_bike",
  "pr:mach_bike": "pr:mach_bike",
  "pr:rotom_bike": "pr:rotom_bike"
};



// Track bikes with no rider so we can despawn them cleanly.
const noRiderTicks = new Map(); // entityId -> ticks without riders

function actionbar(player, msg) {
  try { player.onScreenDisplay.setActionBar(msg); return; } catch {}
  try { player.sendMessage(msg); } catch {}
}

function safeKill(entity) {
  try { entity.triggerEvent?.("despawn"); return; } catch {}
  try { entity.kill?.(); } catch {}
  try { entity.remove?.(); } catch {}
}

world.afterEvents.itemUse.subscribe((ev) => {
  try {
    const player = ev.source;
    const item = ev.itemStack;
    if (!player || player.typeId !== "minecraft:player" || !item) return;
    const entityId = BIKE_MAP[item.typeId];
    if (!entityId) return;

    // If already riding something, don't spawn another bike.
    try {
      const riding = player.getComponent?.("minecraft:riding");
      const mount = riding?.entityRidingOn ?? riding?.getEntityRidingOn?.();
      if (mount) {
        actionbar(player, "§cYou're already riding something. Use §f!dismount§c first.");
        return;
      }
    } catch {}

    const dim = player.dimension;
    const loc = player.location;

    const bike = dim.spawnEntity(entityId, { x: loc.x, y: loc.y, z: loc.z });
    try { bike.addTag?.("pr_bike"); } catch {}

    // Start riding next tick so the entity is fully initialized.
    system.run(() => {
      try {
        const ok = player.startRiding?.(bike);
        if (!ok) {
          // fallback
          player.runCommandAsync?.(`ride @s start_riding @e[type=${entityId},tag=pr_bike,c=1]`);
        }
        actionbar(player, "§aRiding bike. Use §f!dismount§a to get off.");
      } catch (e) {
        actionbar(player, "§cCouldn't start riding the bike.");
        safeKill(bike);
      }
    });
  } catch {}
});

// Cleanup loop: despawn bikes left behind after 5 seconds without riders.
system.runInterval(() => {
  try {
    for (const dim of world.dimensions) {
      let bikes = [];
      try { bikes = dim.getEntities({ tags: ["pr_bike"] }); }
      catch { try { bikes = dim.getEntities(); } catch { bikes = []; } }

      for (const b of bikes) {
        if (!b) continue;
        if (!b.hasTag?.("pr_bike")) continue;

        let riders = [];
        try {
          const rideable = b.getComponent?.("minecraft:rideable");
          riders = (rideable?.getRiders?.() ?? rideable?.riders ?? []);
        } catch {}

        if (riders && riders.length > 0) {
          noRiderTicks.delete(b.id);
          continue;
        }

        const t = (noRiderTicks.get(b.id) ?? 0) + 20;
        noRiderTicks.set(b.id, t);

        if (t >= 100) { // ~5 seconds if interval is 20 ticks
          safeKill(b);
          noRiderTicks.delete(b.id);
        }
      }
    }
  } catch {}
}, 20);