/*
 *  Copyright 2025-2026 R3944Realms
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package top.r3944realms.eroticdungeongame.client.gui.screens;

import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*;
import com.mojang.math.Axis;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.world.level.block.entity.BlockEntity;
import org.jetbrains.annotations.NotNull;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
import top.r3944realms.eroticdungeongame.client.gui.components.DungeonCheckBox;
import top.r3944realms.eroticdungeongame.client.gui.components.DungeonSliderButton;
import top.r3944realms.eroticdungeongame.client.gui.components.PreviewControlButton;
import top.r3944realms.eroticdungeongame.client.gui.components.PreviewToolbar;
import top.r3944realms.eroticdungeongame.content.block.blockentity.LoveMachineBlockEntity;
import top.r3944realms.eroticdungeongame.core.network.EDGNetworkHandler;
import top.r3944realms.eroticdungeongame.core.network.toServer.OffsetConfigPacket;

import java.text.DecimalFormat;

public class OffsetConfigScreen extends Screen {
    private static final int GUI_WIDTH = 400;
    private static final int GUI_HEIGHT = 220;

    private final BlockPos blockPos;

    private static final int PREVIEW_WIDTH = 100;
    private static final int PREVIEW_HEIGHT = 100;

    // 预览相关变量
    private PreviewToolbar previewToolbar;
    private float previewZoom = 1.0f;
    private float previewRotationX = 45.0f;
    private float previewRotationY = 45.0f;
    private boolean showGrid = true;
    private boolean showAxes = true;
    private boolean showPlanes = false;
    private boolean isDragging = false;
    private int lastMouseX = 0;
    private int lastMouseY = 0;
    private int previewLeft = 0;
    private int previewTop = 0;

    // UI 组件
    private DungeonSliderButton speedSlider;
    private DungeonSliderButton offsetXSlider;
    private DungeonSliderButton offsetYSlider;
    private DungeonSliderButton offsetZSlider;
    private DungeonCheckBox enableOffsetCheckbox;
    private Button applyButton;
    private Button resetButton;
    private Button closeButton;

    // 当前值
    private float currentSpeed = 0.05f;
    private float currentOffsetX = 0.5f;
    private float currentOffsetY = 0.0f;
    private float currentOffsetZ = 0.5f;
    private boolean currentOffsetEnabled = true;

    // 标签
    private final Component title = Component.translatable("gui.eroticdungeon.offset_config.title");
    private final Component speedLabel = Component.translatable("gui.eroticdungeon.offset_config.speed");
    private final Component offsetXLabel = Component.translatable("gui.eroticdungeon.offset_config.offset_x");
    private final Component offsetYLabel = Component.translatable("gui.eroticdungeon.offset_config.offset_y");
    private final Component offsetZLabel = Component.translatable("gui.eroticdungeon.offset_config.offset_z");
    private final Component enableOffsetLabel = Component.translatable("gui.eroticdungeon.offset_config.enable_offset");
    private final Component applyLabel = Component.translatable("gui.eroticdungeon.offset_config.apply");
    private final Component resetLabel = Component.translatable("gui.eroticdungeon.offset_config.reset");
    private final Component closeLabel = Component.translatable("gui.eroticdungeon.offset_config.close");

    private final DecimalFormat decimalFormat = new DecimalFormat("0.00");

    public OffsetConfigScreen(BlockPos blockPos) {
        super(Component.empty());
        this.blockPos = blockPos;
    }

    @Override
    protected void init() {
        super.init();
        int guiLeft = (this.width - GUI_WIDTH) / 2;
        int guiTop = (this.height - GUI_HEIGHT) / 2;

        // 计算预览区域位置（右侧）
        previewLeft = guiLeft + GUI_WIDTH - PREVIEW_WIDTH - 10;
        previewTop = guiTop + 30;

        // 创建3D预览工具栏
        previewToolbar = new PreviewToolbar(
                guiLeft + GUI_WIDTH - 260, // 工具栏在GUI右侧
                guiTop - 10,               // 工具栏在GUI上方
                2                         // 按钮间距
        );
        previewToolbar.setOnButtonClick(this::handlePreviewControl);
        previewToolbar.setGridVisible(showGrid);
        previewToolbar.setAxesVisible(showAxes);
        previewToolbar.setPlanesVisible(showPlanes);
        addRenderableWidget(previewToolbar);

        // 速度滑块 (0.001 - 0.1)
        this.speedSlider = new DungeonSliderButton(guiLeft + 10, guiTop + 40, 150, 20,
                Component.empty(), 0.0) {

            @Override
            public void updateMessage() {
                setMessage(Component.literal(speedLabel.getString() + ": " +
                        decimalFormat.format(getValue() * 0.099 + 0.001)));
            }

            @Override
            protected void applyValue() {
                currentSpeed = (float) (value * 0.099 + 0.001);
            }
        };
        speedSlider.setValue((currentSpeed - 0.001f) / 0.099f);

        // X轴偏移滑块 (0.0 - 1.0)
        this.offsetXSlider = new DungeonSliderButton(guiLeft + 10, guiTop + 70, 150, 20,
                Component.empty(), 0.0) {

            @Override
            public void updateMessage() {
                setMessage(Component.literal(offsetXLabel.getString() + ": " +
                        decimalFormat.format(value)));
            }

            @Override
            protected void applyValue() {
                currentOffsetX = (float) value;
            }
        };
        offsetXSlider.setValue(currentOffsetX);

        // Y轴偏移滑块 (0.0 - 1.0)
        this.offsetYSlider = new DungeonSliderButton(guiLeft + 10, guiTop + 100, 150, 20,
                Component.empty(), 0.0) {

            @Override
            public void updateMessage() {
                setMessage(Component.literal(offsetYLabel.getString() + ": " +
                        decimalFormat.format(value)));
            }

            @Override
            protected void applyValue() {
                currentOffsetY = (float) value;
            }
        };
        offsetYSlider.setValue(currentOffsetY);

        // Z轴偏移滑块 (0.0 - 1.0)
        this.offsetZSlider = new DungeonSliderButton(guiLeft + 10, guiTop + 130, 150, 20,
                Component.empty(), 0.0) {

            @Override
            public void updateMessage() {
                setMessage(Component.literal(offsetZLabel.getString() + ": " +
                        decimalFormat.format(value)));
            }

            @Override
            protected void applyValue() {
                currentOffsetZ = (float) value;
            }
        };
        offsetZSlider.setValue(currentOffsetZ);

        // 启用偏移复选框
        this.enableOffsetCheckbox = new DungeonCheckBox(guiLeft + 10, guiTop + 160, 150, 20,
                enableOffsetLabel, currentOffsetEnabled);

        // 应用按钮
        this.applyButton = Button.builder(applyLabel, button -> applyChanges())
                .bounds(guiLeft + 10, guiTop + 185, 50, 20)
                .build();

        // 重置按钮
        this.resetButton = Button.builder(resetLabel, button -> resetToDefault())
                .bounds(guiLeft + 65, guiTop + 185, 50, 20)
                .build();

        // 关闭按钮
        this.closeButton = Button.builder(closeLabel, button -> onClose())
                .bounds(guiLeft + 120, guiTop + 185, 50, 20)
                .build();

        // 添加所有组件
        addRenderableWidget(speedSlider);
        addRenderableWidget(offsetXSlider);
        addRenderableWidget(offsetYSlider);
        addRenderableWidget(offsetZSlider);
        addRenderableWidget(enableOffsetCheckbox);
        addRenderableWidget(applyButton);
        addRenderableWidget(resetButton);
        addRenderableWidget(closeButton);

        ClientLevel level = Minecraft.getInstance().level;
        if (level != null) {
            BlockEntity blockEntity = level.getBlockEntity(blockPos);
            if (blockEntity instanceof LoveMachineBlockEntity machineBlock) {
                // 加载现有值
                currentSpeed = machineBlock.getSpeed();
                currentOffsetX = machineBlock.getOffsetX();
                currentOffsetY = machineBlock.getOffsetY();
                currentOffsetZ = machineBlock.getOffsetZ();
                currentOffsetEnabled = machineBlock.isOffsetEnabled();

                // 更新UI组件
                speedSlider.setValue((currentSpeed - 0.001f) / 0.099f);
                offsetXSlider.setValue(currentOffsetX);
                offsetYSlider.setValue(currentOffsetY);
                offsetZSlider.setValue(currentOffsetZ);
                enableOffsetCheckbox.setSelected(currentOffsetEnabled);
            }
        }

        // 更新滑块文本
        speedSlider.updateMessage();
        offsetXSlider.updateMessage();
        offsetYSlider.updateMessage();
        offsetZSlider.updateMessage();
    }

    /**
     * 处理3D预览控制按钮点击
     */
    private void handlePreviewControl(PreviewControlButton.@NotNull ControlType type) {
        switch (type) {
            case ROTATE_LEFT -> previewRotationY -= 15.0f;
            case ROTATE_RIGHT -> previewRotationY += 15.0f;
            case ROTATE_UP -> previewRotationX = Math.max(-90, previewRotationX - 15.0f);
            case ROTATE_DOWN -> previewRotationX = Math.min(90, previewRotationX + 15.0f);
            case RESET_VIEW -> {
                previewRotationX = 45.0f;
                previewRotationY = 45.0f;
                previewZoom = 1.0f;
            }
            case ZOOM_IN -> previewZoom = Math.min(2.0f, previewZoom * 1.2f);
            case ZOOM_OUT -> previewZoom = Math.max(0.5f, previewZoom / 1.2f);
            case TOGGLE_GRID -> {
                showGrid = !showGrid;
                previewToolbar.setGridVisible(showGrid);
            }
            case TOGGLE_AXES -> {
                showAxes = !showAxes;
                previewToolbar.setAxesVisible(showAxes);
            }
            case TOGGLE_PLANES -> {
                showPlanes = !showPlanes;
                previewToolbar.setPlanesVisible(showPlanes);
            }
            case PERSPECTIVE_TOP -> {
                previewRotationX = 90.0f;
                previewRotationY = 0.0f;
            }
            case PERSPECTIVE_FRONT -> {
                previewRotationX = 0.0f;
                previewRotationY = 0.0f;
            }
            case PERSPECTIVE_SIDE -> {
                previewRotationX = 0.0f;
                previewRotationY = 90.0f;
            }
            case PERSPECTIVE_ISO -> {
                previewRotationX = 45.0f;
                previewRotationY = 45.0f;
            }
        }
    }

    private void applyChanges() {
        // 发送网络包到服务端
        OffsetConfigPacket packet = new OffsetConfigPacket(
                blockPos,
                currentSpeed,
                currentOffsetX,
                currentOffsetY,
                currentOffsetZ,
                enableOffsetCheckbox.selected()
        );

        // 发送网络包
        EDGNetworkHandler.CHANNEL.sendToServer(packet);

        // 关闭屏幕
        this.onClose();
    }

    private void resetToDefault() {
        currentSpeed = 0.05f;
        currentOffsetX = 0.5f;
        currentOffsetY = 0.0f;
        currentOffsetZ = 0.5f;

        speedSlider.setValue((currentSpeed - 0.001f) / 0.099f);
        offsetXSlider.setValue(currentOffsetX);
        offsetYSlider.setValue(currentOffsetY);
        offsetZSlider.setValue(currentOffsetZ);
        enableOffsetCheckbox.setSelected(true);

        speedSlider.updateMessage();
        offsetXSlider.updateMessage();
        offsetYSlider.updateMessage();
        offsetZSlider.updateMessage();
    }

    @Override
    public void render(@NotNull GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {
        // 渲染半透明背景
        this.renderBackground(guiGraphics);

        // 渲染GUI背景
        int guiLeft = (this.width - GUI_WIDTH) / 2;
        int guiTop = (this.height - GUI_HEIGHT) / 2;

        // 绘制GUI背景框
        guiGraphics.fill(guiLeft, guiTop, guiLeft + GUI_WIDTH, guiTop + GUI_HEIGHT, 0x80000000);
        guiGraphics.renderOutline(guiLeft, guiTop, GUI_WIDTH, GUI_HEIGHT, 0xFF555555);

        // 渲染标题
        guiGraphics.drawCenteredString(this.font, title, this.width / 2, guiTop + 10, 0xFFFFFF);

        // 渲染标签
        guiGraphics.drawString(this.font, speedLabel, guiLeft + 10, guiTop + 30, 0x404040, false);
        guiGraphics.drawString(this.font, offsetXLabel, guiLeft + 10, guiTop + 60, 0x404040, false);
        guiGraphics.drawString(this.font, offsetYLabel, guiLeft + 10, guiTop + 90, 0x404040, false);
        guiGraphics.drawString(this.font, offsetZLabel, guiLeft + 10, guiTop + 120, 0x404040, false);

        // 渲染三维坐标预览
        render3DPreview(guiGraphics, previewLeft, previewTop);

        // 渲染简单的预览指示器
        renderSimplePreview(guiGraphics, guiLeft + 165, guiTop + 40, 30, 120);

        super.render(guiGraphics, mouseX, mouseY, partialTick);
    }

    /**
     * 简化的2D预览（用于对比）
     */
    private void renderSimplePreview(@NotNull GuiGraphics guiGraphics, int x, int y, int width, int height) {
        // 绘制预览背景
        guiGraphics.fill(x, y, x + width, y + height, 0xFF202020);
        guiGraphics.hLine(x, x + width, y, 0xFF505050);
        guiGraphics.hLine(x, x + width, y + height, 0xFF505050);
        guiGraphics.vLine(x, y, y + height, 0xFF505050);
        guiGraphics.vLine(x + width, y, y + height, 0xFF505050);

        // 计算中心点
        int centerX = x + width / 2;
        int centerY = y + height / 2;

        // 绘制原点
        guiGraphics.fill(centerX - 1, centerY - 1, centerX + 1, centerY + 1, 0xFFFFFFFF);

        // 根据偏移值计算位置
        int offsetX = centerX + (int)((currentOffsetX - 0.5f) * (width - 10));
        int offsetY = centerY - (int)((currentOffsetY - 0.5f) * (height - 10));

        // 绘制偏移点
        guiGraphics.fill(offsetX - 2, offsetY - 2, offsetX + 2, offsetY + 2, 0xFFFFFF00);

        // 绘制Z轴深度指示（圆圈大小）
        float zScale = 0.5f + currentOffsetZ * 0.5f;
        int zIndicatorSize = (int)(5 * zScale);
        guiGraphics.hLine(offsetX - zIndicatorSize, offsetX + zIndicatorSize,
                offsetY - zIndicatorSize, 0xFF0000FF);
        guiGraphics.hLine(offsetX - zIndicatorSize, offsetX + zIndicatorSize,
                offsetY + zIndicatorSize, 0xFF0000FF);
        guiGraphics.vLine(offsetX - zIndicatorSize,
                offsetY - zIndicatorSize, offsetY + zIndicatorSize, 0xFF0000FF);
        guiGraphics.vLine(offsetX + zIndicatorSize,
                offsetY - zIndicatorSize, offsetY + zIndicatorSize, 0xFF0000FF);
    }

    /**
     * 渲染三维坐标预览
     */
    private void render3DPreview(@NotNull GuiGraphics guiGraphics, int x, int y) {
        // 绘制预览背景
        guiGraphics.fill(x, y, x + PREVIEW_WIDTH, y + PREVIEW_HEIGHT, 0xFF1E1E1E);
        guiGraphics.renderOutline(x, y, PREVIEW_WIDTH, PREVIEW_HEIGHT, 0xFF555555);

        // 保存当前的渲染状态
        RenderSystem.getModelViewStack().pushPose();

        // 设置渲染状态
        RenderSystem.setShader(GameRenderer::getPositionColorShader);
        RenderSystem.enableBlend();
        RenderSystem.defaultBlendFunc();
        RenderSystem.enableDepthTest();
        RenderSystem.depthFunc(GL11.GL_LEQUAL);
        RenderSystem.depthMask(true);
        RenderSystem.disableCull();

        // 准备PoseStack进行3D渲染
        PoseStack poseStack = guiGraphics.pose();
        poseStack.pushPose();

        // 移动到预览区域中心
        poseStack.translate(x + PREVIEW_WIDTH / 2.0, y + PREVIEW_HEIGHT / 2.0, 50);

        // 应用缩放（注意Z轴缩放）
        float scale = 0.6f * previewZoom;
        poseStack.scale(scale, scale, scale);

        // 应用旋转
        poseStack.mulPose(Axis.XP.rotationDegrees(previewRotationX));
        poseStack.mulPose(Axis.YP.rotationDegrees(previewRotationY));

        // 获取渲染器
        Tesselator tesselator = Tesselator.getInstance();
        BufferBuilder buffer = tesselator.getBuilder();

        // 根据设置绘制元素 - 按正确顺序绘制
        if (showAxes) {
            drawCoordinateAxes(tesselator, poseStack, buffer);
        }

        if (showGrid) {
            drawGrid(tesselator, poseStack, buffer);
        }

        if (showPlanes) {
            drawCoordinatePlanes(tesselator, poseStack, buffer);
        }

        // 最后绘制偏移点（在最前面）
        drawOffsetPoint(tesselator, poseStack, buffer);

        poseStack.popPose();

        // 恢复渲染状态
        RenderSystem.getModelViewStack().popPose();
        RenderSystem.enableCull();
        RenderSystem.depthMask(true);
        RenderSystem.disableBlend();
        RenderSystem.disableDepthTest();

        // 在屏幕空间绘制标签
        drawScreenSpaceLabels(guiGraphics, x, y);

        // 在预览区域上方显示说明
        guiGraphics.drawString(font,
                Component.translatable("gui.eroticdungeon.preview.hint"),
                x, y - 12, 0xFFFFFF, false);
    }

    /**
     * 绘制网格背景
     */
    private void drawGrid(Tesselator tesselator, @NotNull PoseStack poseStack, @NotNull BufferBuilder buffer) {
        PoseStack.Pose pose = poseStack.last();
        Matrix4f matrix = pose.pose();

        RenderSystem.setShader(GameRenderer::getPositionColorShader);
        buffer.begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR);

        // 减小网格大小
        float gridSize = 35.0f; // 从50减小到35
        float gridStep = 7.0f;  // 从10减小到7
        int gridAlpha = 0x20;   // 降低透明度

        // XZ平面网格
        for (float i = -gridSize; i <= gridSize; i += gridStep) {
            // 平行于Z轴的线
            buffer.vertex(matrix, i, 0, -gridSize).color(0x80, 0x80, 0x80, gridAlpha).endVertex();
            buffer.vertex(matrix, i, 0, gridSize).color(0x80, 0x80, 0x80, gridAlpha).endVertex();

            // 平行于X轴的线
            buffer.vertex(matrix, -gridSize, 0, i).color(0x80, 0x80, 0x80, gridAlpha).endVertex();
            buffer.vertex(matrix, gridSize, 0, i).color(0x80, 0x80, 0x80, gridAlpha).endVertex();
        }

        tesselator.end();
    }

    /**
     * 绘制坐标轴
     */
    private void drawCoordinateAxes(@NotNull Tesselator tesselator, @NotNull PoseStack poseStack, @NotNull BufferBuilder buffer) {
        PoseStack.Pose pose = poseStack.last();
        Matrix4f matrix = pose.pose();

        RenderSystem.setShader(GameRenderer::getPositionColorShader);
        buffer.begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR);

        float axisLength = 30.0f;

        // X轴 (红色)
        buffer.vertex(matrix, 0, 0, 0).color(1.0f, 0.0f, 0.0f, 1.0f).endVertex();
        buffer.vertex(matrix, axisLength, 0, 0).color(1.0f, 0.0f, 0.0f, 1.0f).endVertex();

        // X轴负方向
        buffer.vertex(matrix, 0, 0, 0).color(0.8f, 0.0f, 0.0f, 0.6f).endVertex();
        buffer.vertex(matrix, -axisLength, 0, 0).color(0.8f, 0.0f, 0.0f, 0.6f).endVertex();

        // Y轴 (绿色)
        buffer.vertex(matrix, 0, 0, 0).color(0.0f, 1.0f, 0.0f, 1.0f).endVertex();
        buffer.vertex(matrix, 0, axisLength, 0).color(0.0f, 1.0f, 0.0f, 1.0f).endVertex();

        // Y轴负方向
        buffer.vertex(matrix, 0, 0, 0).color(0.0f, 0.8f, 0.0f, 0.6f).endVertex();
        buffer.vertex(matrix, 0, -axisLength, 0).color(0.0f, 0.8f, 0.0f, 0.6f).endVertex();

        // Z轴 (蓝色)
        buffer.vertex(matrix, 0, 0, 0).color(0.0f, 0.0f, 1.0f, 1.0f).endVertex();
        buffer.vertex(matrix, 0, 0, axisLength).color(0.0f, 0.0f, 1.0f, 1.0f).endVertex();

        // Z轴负方向
        buffer.vertex(matrix, 0, 0, 0).color(0.0f, 0.0f, 0.8f, 0.6f).endVertex();
        buffer.vertex(matrix, 0, 0, -axisLength).color(0.0f, 0.0f, 0.8f, 0.6f).endVertex();

        tesselator.end();
    }

    /**
     * 绘制偏移点
     */
    private void drawOffsetPoint(@NotNull Tesselator tesselator, @NotNull PoseStack poseStack, @NotNull BufferBuilder buffer) {
        PoseStack.Pose pose = poseStack.last();
        Matrix4f matrix = pose.pose();

        // 将偏移值映射到预览空间 (0-1 映射到 -20 到 20)
        float previewX = (currentOffsetX - 0.5f) * 40.0f;
        float previewY = (currentOffsetY - 0.5f) * 40.0f;
        float previewZ = (currentOffsetZ - 0.5f) * 40.0f;

        float pointSize = 3.0f;
        float x1 = previewX - pointSize;
        float x2 = previewX + pointSize;
        float y1 = previewY - pointSize;
        float y2 = previewY + pointSize;
        float z1 = previewZ - pointSize;
        float z2 = previewZ + pointSize;

        // 绘制偏移点（立方体）- 完整6个面
        RenderSystem.setShader(GameRenderer::getPositionColorShader);
        buffer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);

        // 前面 (Z+方向) - 黄色
        buffer.vertex(matrix, x1, y1, z2).color(1.0f, 1.0f, 0.0f, 1.0f).endVertex();
        buffer.vertex(matrix, x2, y1, z2).color(1.0f, 1.0f, 0.0f, 1.0f).endVertex();
        buffer.vertex(matrix, x2, y2, z2).color(1.0f, 1.0f, 0.0f, 1.0f).endVertex();
        buffer.vertex(matrix, x1, y2, z2).color(1.0f, 1.0f, 0.0f, 1.0f).endVertex();

        // 后面 (Z-方向)
        buffer.vertex(matrix, x2, y1, z1).color(1.0f, 1.0f, 0.0f, 0.8f).endVertex();
        buffer.vertex(matrix, x1, y1, z1).color(1.0f, 1.0f, 0.0f, 0.8f).endVertex();
        buffer.vertex(matrix, x1, y2, z1).color(1.0f, 1.0f, 0.0f, 0.8f).endVertex();
        buffer.vertex(matrix, x2, y2, z1).color(1.0f, 1.0f, 0.0f, 0.8f).endVertex();

        // 左面 (X-方向)
        buffer.vertex(matrix, x1, y1, z1).color(1.0f, 1.0f, 0.0f, 0.9f).endVertex();
        buffer.vertex(matrix, x1, y1, z2).color(1.0f, 1.0f, 0.0f, 0.9f).endVertex();
        buffer.vertex(matrix, x1, y2, z2).color(1.0f, 1.0f, 0.0f, 0.9f).endVertex();
        buffer.vertex(matrix, x1, y2, z1).color(1.0f, 1.0f, 0.0f, 0.9f).endVertex();

        // 右面 (X+方向)
        buffer.vertex(matrix, x2, y1, z2).color(1.0f, 1.0f, 0.0f, 0.9f).endVertex();
        buffer.vertex(matrix, x2, y1, z1).color(1.0f, 1.0f, 0.0f, 0.9f).endVertex();
        buffer.vertex(matrix, x2, y2, z1).color(1.0f, 1.0f, 0.0f, 0.9f).endVertex();
        buffer.vertex(matrix, x2, y2, z2).color(1.0f, 1.0f, 0.0f, 0.9f).endVertex();

        // 上面 (Y+方向)
        buffer.vertex(matrix, x1, y2, z2).color(1.0f, 1.0f, 0.0f, 0.7f).endVertex();
        buffer.vertex(matrix, x2, y2, z2).color(1.0f, 1.0f, 0.0f, 0.7f).endVertex();
        buffer.vertex(matrix, x2, y2, z1).color(1.0f, 1.0f, 0.0f, 0.7f).endVertex();
        buffer.vertex(matrix, x1, y2, z1).color(1.0f, 1.0f, 0.0f, 0.7f).endVertex();

        // 下面 (Y-方向)
        buffer.vertex(matrix, x1, y1, z1).color(1.0f, 1.0f, 0.0f, 0.7f).endVertex();
        buffer.vertex(matrix, x2, y1, z1).color(1.0f, 1.0f, 0.0f, 0.7f).endVertex();
        buffer.vertex(matrix, x2, y1, z2).color(1.0f, 1.0f, 0.0f, 0.7f).endVertex();
        buffer.vertex(matrix, x1, y1, z2).color(1.0f, 1.0f, 0.0f, 0.7f).endVertex();

        tesselator.end();

        // 绘制从原点到偏移点的连接线
        RenderSystem.setShader(GameRenderer::getPositionColorShader);
        buffer.begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR);

        // 白色虚线效果
        buffer.vertex(matrix, 0, 0, 0).color(1.0f, 1.0f, 1.0f, 0.8f).endVertex();
        buffer.vertex(matrix, previewX, previewY, previewZ).color(1.0f, 1.0f, 1.0f, 0.8f).endVertex();

        tesselator.end();
    }

    /**
     * 绘制坐标平面
     */
    private void drawCoordinatePlanes(@NotNull Tesselator tesselator, @NotNull PoseStack poseStack, @NotNull BufferBuilder buffer) {
        PoseStack.Pose pose = poseStack.last();
        Matrix4f matrix = pose.pose();

        float planeSize = 20.0f;

        // XY平面 (绿色) - 在 Z=0
        RenderSystem.setShader(GameRenderer::getPositionColorShader);
        buffer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);

        float alpha = 0.4f; // 透明度

        // XY平面（绿色，Z=0）
        buffer.vertex(matrix, -planeSize, -planeSize, 0).color(0.0f, 1.0f, 0.0f, alpha).endVertex();
        buffer.vertex(matrix, planeSize, -planeSize, 0).color(0.0f, 1.0f, 0.0f, alpha).endVertex();
        buffer.vertex(matrix, planeSize, planeSize, 0).color(0.0f, 1.0f, 0.0f, alpha).endVertex();
        buffer.vertex(matrix, -planeSize, planeSize, 0).color(0.0f, 1.0f, 0.0f, alpha).endVertex();

        tesselator.end();

        // XZ平面 (红色) - 在 Y=0
        buffer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);

        buffer.vertex(matrix, -planeSize, 0, -planeSize).color(1.0f, 0.0f, 0.0f, alpha).endVertex();
        buffer.vertex(matrix, planeSize, 0, -planeSize).color(1.0f, 0.0f, 0.0f, alpha).endVertex();
        buffer.vertex(matrix, planeSize, 0, planeSize).color(1.0f, 0.0f, 0.0f, alpha).endVertex();
        buffer.vertex(matrix, -planeSize, 0, planeSize).color(1.0f, 0.0f, 0.0f, alpha).endVertex();

        tesselator.end();

        // YZ平面 (蓝色) - 在 X=0
        buffer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);

        buffer.vertex(matrix, 0, -planeSize, -planeSize).color(0.0f, 0.0f, 1.0f, alpha).endVertex();
        buffer.vertex(matrix, 0, planeSize, -planeSize).color(0.0f, 0.0f, 1.0f, alpha).endVertex();
        buffer.vertex(matrix, 0, planeSize, planeSize).color(0.0f, 0.0f, 1.0f, alpha).endVertex();
        buffer.vertex(matrix, 0, -planeSize, planeSize).color(0.0f, 0.0f, 1.0f, alpha).endVertex();

        tesselator.end();
    }

    /**
     * 在屏幕空间绘制坐标轴标签 - 不会被裁剪
     */
    private void drawScreenSpaceLabels(@NotNull GuiGraphics guiGraphics, int previewX, int previewY) {
        int centerX = previewX + PREVIEW_WIDTH / 2;
        int centerY = previewY + PREVIEW_HEIGHT / 2;

        // 计算标签位置（基于旋转角度）
        float radY = (float) Math.toRadians(previewRotationY);
        float radX = (float) Math.toRadians(previewRotationX);

        // 计算标签偏移量
        int offset = 35;

        // X轴标签 - 根据Y旋转计算位置
        int xOffset = (int)(Math.cos(radY) * offset);
        int yOffsetX = (int)(Math.sin(radX) * 10);
        guiGraphics.drawString(font, "X",
                centerX + xOffset - 3,
                centerY + yOffsetX - 4,
                0xFF0000, false);

        // Y轴标签 - 根据X旋转计算位置
        int yOffset = (int)(Math.sin(radX) * offset);
        int xOffsetY = (int)(Math.cos(radY) * 10);
        guiGraphics.drawString(font, "Y",
                centerX + xOffsetY - 3,
                centerY - yOffset - 4,
                0x00FF00, false);

        // Z轴标签 - 根据Y旋转计算位置
        int zOffset = (int)(Math.sin(radY) * offset);
        int yOffsetZ = (int)(Math.cos(radX) * 10);
        guiGraphics.drawString(font, "Z",
                centerX - zOffset - 3,
                centerY + yOffsetZ - 4,
                0x0000FF, false);

        // 在预览区域右下角显示当前坐标值
        String coordText = String.format("X:%.2f Y:%.2f Z:%.2f",
                currentOffsetX, currentOffsetY, currentOffsetZ);
        guiGraphics.drawString(font, coordText,
                previewX + 5, previewY + PREVIEW_HEIGHT + 5, 0xFFFFFF, false);
    }

    @Override
    public boolean mouseClicked(double mouseX, double mouseY, int button) {
        // 检查是否点击了预览区域
        if (isMouseOverPreview(mouseX, mouseY) && button == 0) {
            isDragging = true;
            lastMouseX = (int) mouseX;
            lastMouseY = (int) mouseY;
            return true;
        }
        return super.mouseClicked(mouseX, mouseY, button);
    }

    @Override
    public boolean mouseReleased(double mouseX, double mouseY, int button) {
        if (button == 0) {
            isDragging = false;
        }
        return super.mouseReleased(mouseX, mouseY, button);
    }

    @Override
    public boolean mouseDragged(double mouseX, double mouseY, int button, double dragX, double dragY) {
        if (isDragging && button == 0) {
            // 计算鼠标移动距离
            int deltaX = (int) mouseX - lastMouseX;
            int deltaY = (int) mouseY - lastMouseY;

            // 更新旋转角度
            previewRotationY += deltaX * 0.5f;
            previewRotationX += deltaY * 0.5f;

            // 限制X轴旋转角度
            previewRotationX = Math.max(-90, Math.min(90, previewRotationX));

            // 更新鼠标位置
            lastMouseX = (int) mouseX;
            lastMouseY = (int) mouseY;

            return true;
        }
        return super.mouseDragged(mouseX, mouseY, button, dragX, dragY);
    }

    /**
     * 检查鼠标是否在预览区域上
     */
    private boolean isMouseOverPreview(double mouseX, double mouseY) {
        return mouseX >= previewLeft && mouseX <= previewLeft + PREVIEW_WIDTH &&
                mouseY >= previewTop && mouseY <= previewTop + PREVIEW_HEIGHT;
    }

    @Override
    public boolean isPauseScreen() {
        return false;
    }

    @Override
    public void onClose() {
        super.onClose();
    }
}