/*
 * 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.SkeletonKingEntity;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.goal.Goal;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;

public class KingAttackGoal extends Goal {
    private final SkeletonKingEntity king;
    private final double speedModifier;
    private final int baseAttackCooldown;       // 基础攻击冷却（ticks）
    private final int attackDelay;               // 动画挥砍延迟（ticks）
    private int ticksSinceLastAttack;             // 距离上次攻击经过的 tick 数
    private int animationRemaining;               // 动画剩余时间
    private boolean attackTriggered;              // 是否已触发动画
    private int damageDelayCounter;                // 伤害延迟计数器
    private LivingEntity target;
    private float attackYaw; // 记录攻击动画触发时的身体朝向
    // 扇形攻击角度：225° 前方扇形，半角 112.5°
    private static final float HALF_ANGLE = 112.5f;
    private Vec3 attackForward;  // 新增：记录攻击瞬间的前向向量
    public KingAttackGoal(SkeletonKingEntity king, double speedModifier, int attackCooldownTicks, int attackDelayTicks) {
        this.king = king;
        this.speedModifier = speedModifier;
        this.baseAttackCooldown = attackCooldownTicks;
        this.attackDelay = attackDelayTicks;
        this.ticksSinceLastAttack = baseAttackCooldown;
        this.animationRemaining = 0;
        this.attackTriggered = false;
        this.damageDelayCounter = 0;
        this.setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK));
    }

    private int getCurrentCooldown() {
        int cooldown = baseAttackCooldown;
        if (king.isEnraged()) {
            cooldown = (int) (cooldown * 0.75);
        }
        return cooldown;
    }

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

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

    @Override
    public void tick() {
        // 冷却递减（不变）
        if (ticksSinceLastAttack < getCurrentCooldown()) {
            ticksSinceLastAttack++;
        }
        if (animationRemaining > 0) {
            animationRemaining--;
        }

        // 伤害延迟处理
        if (damageDelayCounter > 0) {
            damageDelayCounter--;
            if (damageDelayCounter == 0) {
                double reach = king.getBbWidth() * 2.0F + 1.0;
                double reachSq = reach * reach;
                AABB area = king.getBoundingBox().inflate(reach);
                List<LivingEntity> entities = king.level().getEntitiesOfClass(LivingEntity.class, area,
                        e -> e != king && e.isAlive() && !king.isAlliedTo(e) && king.distanceToSqr(e) <= reachSq && king.hasLineOfSight(e));

                // 扇形半角112.5°对应的余弦值
                double cosHalfAngle = Math.cos(Math.toRadians(112.5)); // ≈ -0.382683

                List<LivingEntity> affectedEntities = new ArrayList<>();
                for (LivingEntity entity : entities) {
                    Vec3 toTarget = entity.position().subtract(king.position());
                    // 只考虑水平方向，忽略垂直分量
                    toTarget = new Vec3(toTarget.x, 0, toTarget.z).normalize();
                    double dot = this.attackForward.dot(toTarget);
                    if (dot >= cosHalfAngle) {
                        affectedEntities.add(entity);
                    }
                }

                if (!affectedEntities.isEmpty()) {
                    int count = affectedEntities.size();
                    float baseDamage = 20.0f;
                    // 衰减函数：每个目标受到的伤害 = 基础伤害 / sqrt(目标数量)
                    float damagePerTarget = (float) (baseDamage / Math.sqrt(count));
                    for (LivingEntity entity : affectedEntities) {
                        entity.hurt(king.damageSources().mobAttack(king), damagePerTarget);
                        king.level().playSound(null, entity.getX(), entity.getY(), entity.getZ(),
                                SoundEvents.PLAYER_ATTACK_CRIT, entity.getSoundSource(), 1.0F, 1.0F);
                    }
                }
                attackTriggered = false;
            }
        }

        // 原有移动与攻击触发逻辑（保持不变）
        if (target == null) return;

        king.getLookControl().setLookAt(target, 30.0F, 30.0F);
        double distanceSq = king.distanceToSqr(target);
        double attackReachSq = getAttackReachSq(target);

        if (distanceSq <= attackReachSq) {
            king.getNavigation().stop();
            if (ticksSinceLastAttack >= getCurrentCooldown() && !attackTriggered && animationRemaining == 0) {
                // 正确计算前向向量
                float yaw = king.getYRot();
                double rad = Math.toRadians(yaw);
                // Minecraft 中 yaw=0 向南 (0,0,1)，所以前向向量为 (-sin, 0, cos)
                this.attackForward = new Vec3(-Math.sin(rad), 0, Math.cos(rad)).normalize();
                king.triggerAttackAnim();
                attackTriggered = true;
                animationRemaining = getCurrentCooldown();
                damageDelayCounter = attackDelay;
                ticksSinceLastAttack = 0;
            }
        } else {
            king.getNavigation().moveTo(target, speedModifier);
        }
    }

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

    private double getAttackReachSq(LivingEntity target) {
        double reach = king.getBbWidth() * 2.0F + target.getBbWidth();
        return reach * reach;
    }
}