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

import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.remains_cave.entity.AuraBearer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.LivingEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.bernie.geckolib.animatable.GeoAnimatable;
import software.bernie.geckolib.cache.object.BakedGeoModel;
import software.bernie.geckolib.renderer.GeoRenderer;
import software.bernie.geckolib.renderer.layer.GeoRenderLayer;

public class KingsAuraRenderLayer<T extends LivingEntity & GeoAnimatable & AuraBearer> extends GeoRenderLayer<T> {
    private final KingsAuraModel model = new KingsAuraModel();
    private static final int FULL_BRIGHT = 0xF000F0; // 全亮光照值
    public KingsAuraRenderLayer(GeoRenderer<T> entityRenderer) {
        super(entityRenderer);
    }

    @Override
    public void render(PoseStack poseStack, T animatable, BakedGeoModel bakedModel,
                       RenderType renderType, MultiBufferSource bufferSource, VertexConsumer buffer,
                       float partialTick, int packedLight, int packedOverlay) {

        if (!animatable.hasAura()) {
            return;
        }

        poseStack.pushPose();

        // 基础位置：头顶上方
        float height = animatable.getBbHeight();
        poseStack.translate(0, height + 0.125, 0);

        // 1. 旋转动画（绕 Y 轴）
        float angle = (animatable.level().getGameTime() + partialTick) * 4 % 360;
        poseStack.mulPose(com.mojang.math.Axis.YP.rotationDegrees(angle));

        // 2. 上下浮动（基于正弦函数）
        float floatOffset = (float) ((float) Math.sin((animatable.level().getGameTime() + partialTick) * 0.2) * 0.1); // 幅度 0.1 格，周期约 31 秒
        poseStack.translate(0, floatOffset, 0);

        // 渲染模型
        ResourceLocation modelLoc = model.getModelResource(animatable);
        ResourceLocation textureLoc = model.getTextureResource(animatable);
        BakedGeoModel auraModel = model.getBakedModel(modelLoc);
        RenderType auraRenderType = RenderType.entityCutoutNoCull(textureLoc);
        VertexConsumer auraBuffer = bufferSource.getBuffer(auraRenderType);

        getRenderer().reRender(auraModel, poseStack, bufferSource, animatable, auraRenderType,
                auraBuffer, partialTick, FULL_BRIGHT, packedOverlay, 0xFFFFFFFF);

        poseStack.popPose();
    }
}