/*
 * 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.effect.ModEffects;
import com.remains_cave.entity.SkeletonArcherEntity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.goal.Goal;
import net.minecraft.world.entity.ai.util.DefaultRandomPos;
import net.minecraft.world.phys.Vec3;

public class ArcherAvoidTargetGoal extends Goal {
    private final SkeletonArcherEntity archer;
    private LivingEntity target;
    private static final double SAFE_DISTANCE = 12.0;
    private static final double DANGER_DISTANCE = 6.0;
    private static final double SPEED_MODIFIER = 1.2;

    public ArcherAvoidTargetGoal(SkeletonArcherEntity archer) {
        this.archer = archer;
    }

    @Override
    public boolean canUse() {
        // 攻击中不逃离
        if (archer.isAttacking()) return false;
        if (!archer.hasEffect(ModEffects.KINGS_AURA)) return false;
        target = archer.getTarget();
        if (target == null || !target.isAlive()) return false;
        double distSq = archer.distanceToSqr(target);
        return distSq < DANGER_DISTANCE * DANGER_DISTANCE;
    }

    @Override
    public boolean canContinueToUse() {
        if (archer.isAttacking()) return false;
        if (!archer.hasEffect(ModEffects.KINGS_AURA)) return false;
        if (target == null || !target.isAlive()) return false;
        double distSq = archer.distanceToSqr(target);
        return distSq < SAFE_DISTANCE * SAFE_DISTANCE;
    }

    @Override
    public void tick() {
        if (target == null) return;
        Vec3 awayDir = archer.position().subtract(target.position()).normalize();
        Vec3 fleePos = DefaultRandomPos.getPosAway(archer, 10, 7, target.position());
        if (fleePos == null) {
            fleePos = archer.position().add(awayDir.scale(10));
        }
        archer.getNavigation().moveTo(fleePos.x, fleePos.y, fleePos.z, SPEED_MODIFIER);
    }

    @Override
    public void stop() {
        archer.getNavigation().stop();
    }
}