/*
 * 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.client;

import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.math.Axis;
import com.remains_cave.RemainsCaveMod;
import com.remains_cave.entity.projectile.CustomArrowEntity;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.entity.EntityRendererProvider;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.Mth;
import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.NotNull;
import software.bernie.geckolib.model.DefaultedEntityGeoModel;
import software.bernie.geckolib.renderer.GeoEntityRenderer;

public class TombArrowRenderer extends GeoEntityRenderer<CustomArrowEntity> {
    public TombArrowRenderer(EntityRendererProvider.Context renderManager) {
        super(renderManager, new DefaultedEntityGeoModel<>(
                ResourceLocation.fromNamespaceAndPath(RemainsCaveMod.MODID, "tomb_arrow")
        ));
    }

    @Override
    public void render(CustomArrowEntity entity, float entityYaw, float partialTick, PoseStack poseStack,
                       @NotNull MultiBufferSource bufferSource, int packedLight) {
        poseStack.pushPose();

        // 获取运动向量
        Vec3 motion = entity.getDeltaMovement();
        float yRot, xRot;

        if (motion.lengthSqr() > 1e-4) {
            // 根据运动方向计算旋转
            yRot = (float) (Math.atan2(motion.z, motion.x) * 180.0F / Math.PI) - 90.0F;
            xRot = (float) (Math.atan2(motion.y, motion.horizontalDistance()) * 180.0F / Math.PI);
        } else {
            // 静止时使用实体本身的旋转
            yRot = entity.getYRot();
            xRot = entity.getXRot();
        }

        // 应用旋转（顺序：先 Y 轴，后 X 轴）
        poseStack.mulPose(Axis.YP.rotationDegrees(180 - yRot));
        poseStack.mulPose(Axis.XP.rotationDegrees(xRot));

        // 抖动效果（当箭插在地上时）
        if (entity.isInGround() && entity.getShakeTime() > 0) {
            float amplitude = Math.min(entity.getShakeTime(), 10) * 0.75F;
            float t = (entity.tickCount + partialTick) * 2F;
            float shakeY = amplitude * Mth.sin(t);
            float shakeX = amplitude * 0.3F * Mth.cos(t * 1.3F);
            poseStack.mulPose(Axis.YP.rotationDegrees(shakeY));
            poseStack.mulPose(Axis.XP.rotationDegrees(shakeX));
        }

        // 调用父类渲染
        super.render(entity, entityYaw, partialTick, poseStack, bufferSource, packedLight);

        poseStack.popPose();
    }
}