/*
 * Copyright (c) 2026 盐灯水母
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

package com.remains_cave.entity.ai;

import com.remains_cave.entity.SkeletonWarriorEntity;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.PathfinderMob;
import net.minecraft.world.entity.ai.goal.Goal;

import java.util.EnumSet;

public class CustomAttackGoal extends Goal {
    private final PathfinderMob mob;
    private final double speedModifier;
    private final int attackCooldown;       // 总攻击间隔（ticks）
    private final int attackDelayTicks;      // 动画挥砍前的延迟（ticks）

    private int ticksSinceLastAttack;        // 距离上次攻击经过的 tick 数
    private int delayCounter;                 // 伤害延迟剩余 ticks
    private boolean attackTriggered;           // 是否已触发动画（等待伤害）
    private LivingEntity target;

    public CustomAttackGoal(PathfinderMob mob, double speedModifier, int attackCooldownTicks, int attackDelayTicks) {
        this.mob = mob;
        this.speedModifier = speedModifier;
        this.attackCooldown = attackCooldownTicks;
        this.attackDelayTicks = attackDelayTicks;
        this.ticksSinceLastAttack = attackCooldown; // 初始允许攻击
        this.delayCounter = 0;
        this.attackTriggered = false;
        this.setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK));
    }

    @Override
    public boolean canUse() {
        LivingEntity target = this.mob.getTarget();
        if (target == null || !target.isAlive()) return false;
        this.target = target;
        return true;
    }

    @Override
    public boolean canContinueToUse() {
        return target != null && target.isAlive() && mob.isAlive() && mob.distanceToSqr(target) < 100.0;
    }

    @Override
    public void tick() {
        // 如果主人是骷髅战士且处于眩晕状态，则重置攻击状态，不执行攻击逻辑
        if (mob instanceof SkeletonWarriorEntity warrior && warrior.isStunned()) {
            attackTriggered = false;
            delayCounter = 0;
            return;
        }
        if (ticksSinceLastAttack < attackCooldown) ticksSinceLastAttack++;

        // 延迟伤害处理
        if (attackTriggered) {
            if (delayCounter > 0) {
                delayCounter--;
            } else {
                if (target != null && target.isAlive() && mob.distanceToSqr(target) <= getAttackReachSq(target)) {
                    mob.doHurtTarget(target);
                    // 播放攻击音效（服务端触发，客户端自动同步）
                    mob.level().playSound(null, mob.getX(), mob.getY(), mob.getZ(),
                            SoundEvents.PLAYER_ATTACK_STRONG, mob.getSoundSource(), 1.0F, 1.0F);
                }
                attackTriggered = false;
            }
        }

        if (target == null) return;

        mob.getLookControl().setLookAt(target, 30.0F, 30.0F);
        double distanceSq = mob.distanceToSqr(target);

        if (distanceSq <= getAttackReachSq(target)) {
            // 在攻击范围内，停止移动
            mob.getNavigation().stop();

            // 冷却结束且未在等待伤害 → 发起新攻击
            if (ticksSinceLastAttack >= attackCooldown && !attackTriggered) {
                if (mob instanceof SkeletonWarriorEntity warrior) {
                    warrior.triggerAttackAnim();
                    attackTriggered = true;
                    delayCounter = attackDelayTicks;   // 设置伤害延迟
                    ticksSinceLastAttack = 0;           // 重置冷却
                }
            }
        } else {
            // 不在攻击范围内，向目标移动
            mob.getNavigation().moveTo(target, speedModifier);
        }
    }

    @Override
    public void stop() {
        target = null;
        mob.getNavigation().stop();
        attackTriggered = false;
    }

    // 辅助方法：计算攻击距离平方
    private double getAttackReachSq(LivingEntity target) {
        double extraRange = 0.25; // 额外增加的距离
        double reach = mob.getBbWidth() * 2.0F + target.getBbWidth() + extraRange;
        return reach * reach;
    }
}