// server_scripts/offensive_logic.js

const COOLDOWN_TICKS = 7
const PROJECTILE_SPEED = 0.8
const SINGLE_DAMAGE = 4.0
const XP_COST = 5
const LIFETIME = 80
const PHOTON_EFFECT = 'photon fx photon:offensive_mk1 entity @s'

const lastShotTick = new Map()
let shotCounter = 0
const arrowData = new Map() // tag -> { dx, dy, dz }

ItemEvents.rightClicked(event => {
    const { player, item, level } = event
    if (item.id !== 'kubejs:offensive_mk1') return
    if (level.isClientSide()) return

    // 冷却
    const now = player.tickCount
    const last = lastShotTick.get(player.uuid.toString()) || 0
    if (now - last < COOLDOWN_TICKS) return
    lastShotTick.set(player.uuid.toString(), now)

    // 经验
    if (player.xp < XP_COST) {
        player.displayClientMessage(Component.red(`§c经验不足，需要 ${XP_COST} 点经验`), false)
        return
    }
    player.giveExperiencePoints(-XP_COST)

    // 方向
    const look = player.lookAngle
    const dx = look.x() * PROJECTILE_SPEED
    const dy = look.y() * PROJECTILE_SPEED
    const dz = look.z() * PROJECTILE_SPEED

    // 生成位置
    const eyeX = player.x
    const eyeY = player.y + Number(player.eyeHeight)
    const eyeZ = player.z
    const spawnX = eyeX + look.x() * 0.7 + (Math.random() - 0.5) * 1.0
    const spawnY = eyeY + look.y() * 0.7 + (Math.random() - 0.5) * 1.0
    const spawnZ = eyeZ + look.z() * 0.7 + (Math.random() - 0.5) * 1.0

    const tag = `off_mk1_${++shotCounter}`
    arrowData.set(tag, { dx: dx, dy: dy, dz: dz })

    // 生成箭：伤害设为 1.0 确保 hurt 事件触发（之后会由我们劫持）
    const cmd = `execute positioned ${spawnX} ${spawnY} ${spawnZ} run summon minecraft:arrow ~ ~ ~ {Motion:[${dx.toFixed(3)}d,${dy.toFixed(3)}d,${dz.toFixed(3)}d],NoGravity:1b,Silent:1b,Invisible:1b,damage:4.0,Tags:["${tag}"]}`
    const success = level.runCommandSilent(cmd)
    if (!success) {
        player.displayClientMessage(Component.red('§c生成失败'), false)
        arrowData.delete(tag)
        return
    }

    // 特效挂载
    event.server.scheduleInTicks(1, () => {
        level.runCommandSilent(`execute as @e[type=arrow,tag=${tag},limit=1] at @s run ${PHOTON_EFFECT}`)
    })

    // 生命周期自动清除
    event.server.scheduleInTicks(LIFETIME, () => {
        level.runCommandSilent(`kill @e[type=arrow,tag=${tag},limit=1]`)
        arrowData.delete(tag)
    })
})

// 恒速维持
ServerEvents.tick(event => {
    arrowData.forEach((motion, tag) => {
        event.server.runCommandSilent(`data merge entity @e[type=arrow,tag=${tag},limit=1] {Motion:[${motion.dx.toFixed(3)}d,${motion.dy.toFixed(3)}d,${motion.dz.toFixed(3)}d]}`)
    })
})

// 穿透与自定义伤害
EntityEvents.hurt(event => {
    const { source, entity } = event
    if (source.getImmediate() !== 'arrow') return

    const arrow = source.getImmediateEntity()
    if (!arrow || arrow.type !== 'minecraft:arrow') return
    if (!arrow.tags || !arrow.tags.contains('off_mk1_')) return

    // 取消原版伤害（包括箭的消失行为）
    event.cancel()
    const shooter = source.getPlayer()
    if (shooter) {
        entity.attack(DamageSource.playerAttack(shooter), SINGLE_DAMAGE)
    }
})