<template>
  <div class="page-wrapper">
    <!-- 顶部标题 -->
    <header class="page-header">
      <h1>几何题图形交互功能演示（3D 版）</h1>
    </header>

    <main class="main-container">
      <!-- 左侧画布 -->
      <section class="canvas-area">
        <div id="ggbApplet"></div>
      </section>

      <!-- 右侧控制面板 -->
      <aside class="control-panel">
        <div class="glass-card">
          <!-- 案例按钮 -->
          <div class="btn-row">
            <button
              v-for="btn in exampleBtns"
              :key="btn.id"
              :class="btn.cls"
              @click="loadExample(btn.content)"
            >
              {{ btn.label }}
            </button>
          </div>

          <!-- 指令输入 -->
          <textarea
            v-model="commandText"
            class="cmd-textarea"
            placeholder="请输入 GeoGebra 3D 指令运行"
          ></textarea>

          <!-- 操作按钮 -->
          <div class="action-row">
            <button class="btn-success" @click="execCommands">执行指令</button>
            <button class="btn-info" @click="loadAiDemo">AI 解析示例</button>
            <button class="btn-danger" @click="clearCanvas">清空画布</button>
          </div>
        </div>
      </aside>
    </main>
  </div>
</template>

<script setup>
/* ========= 逻辑部分与原 HTML 完全一致 ========= */
import { ref, onMounted, onBeforeUnmount } from "vue";
import "@/assets/js/deployggb.js"; // 把原来的 deployggb.js 放到 src/assets 并引入

const commandText = ref("");
let ggbApi = null;

const exampleBtns = [
  { id: 1, label: "矩形旋转一周", cls: "btn-blue", content: rectRotate },
  { id: 2, label: "直角三角形旋转", cls: "btn-orange", content: triRotate },
  { id: 3, label: "梯形旋转一周", cls: "btn-purple", content: trapRotate },
  { id: 4, label: "棱柱展开图", cls: "btn-green", content: prismNet },
  { id: 5, label: "棱锥展开图", cls: "btn-red", content: pyramidNet },
];

onMounted(initGGB);
onBeforeUnmount(() => ggbApi && ggbApi.remove());

function initGGB() {
  // 等待DOM完全渲染
  setTimeout(() => {
    const container = document.getElementById("ggbApplet");
    const rect = container.getBoundingClientRect();

    const params = {
      appName: "3d",
      language: "zh_CN",
      locale: "zh_CN",
      country: "CN",
      useBrowserLocale: false,
      useBrowserForJS: true,
      width: Math.floor(rect.width), // 使用实际像素值
      height: Math.floor(rect.height), // 使用实际像素值
      showToolBar: true,
      showAlgebraInput: true,
      showMenuBar: true,
      appletOnLoad(api) {
        ggbApi = api;
      },
    };

    console.log("GeoGebra容器尺寸:", rect.width, "x", rect.height);
    new window.GGBApplet(params, true).inject("ggbApplet");
  }, 100);
}

function loadExample(fn) {
  commandText.value = fn();
}
function loadAiDemo() {
  commandText.value = aiDemo();
}
function clearCanvas() {  
  if (!window.confirm("确定要清空画布吗？")) return;
  ggbApi && ggbApi.newConstruction();
  commandText.value = ''
}
function execCommands() {
  if (!ggbApi) return alert("GeoGebra 未加载完成");
  ggbApi && ggbApi.newConstruction();
  const lines = commandText.value
    .split("\n")
    .map((l) => l.replace(/#.*$/, "").trim())
    .filter(Boolean);
  if (!lines.length) return alert("请输入至少一条指令");
  let ok = 0,
    err = 0,
    fails = [];
  lines.forEach((cmd, idx) => {
    try {
      ggbApi.evalCommand(cmd);
      ok++;
    } catch (e) {
      err++;
      fails.push(`${idx + 1}: ${cmd} (${e.message})`);
    }
  });
  if (err) alert(`成功 ${ok} 条，失败 ${err} 条\n${fails.join("\n")}`);
}

/* ========== 示例脚本 ========== */
function rectRotate() {
  return `# 构造三维坐标的矩形
q1 = Polygon((0,0,0),(1,0,0),(1,0,3),(0,0,3))
# 创建滑动条
α = Slider(0°, 360°)
# 至于将矩形旋转一周，可当做是逐渐产生一系列绕着z轴的矩形
l1 = Sequence(Rotate(q1,k,zAxis),k,0°,α,0.5°)`;
}
function triRotate() {
  return `# 创建直角三角形顶点（直角在原点B）
B = (0, 0, 0)       # 直角顶点（原点）
A = (4, 0, 0)       # X轴上的顶点（AB为直角边）
C = (0, 0, 7)       # Z轴上的顶点（BC为直角边）
# 构建直角三角形（确保直角在B点）
tri = Polygon(A, B, C)
# 创建旋转控制滑动条 (0-360度)
θ = Slider(0°, 360°)
# 创建绕Z轴旋转序列（步长0.6°）
rotatedTris = Sequence(Rotate(tri, k, zAxis), k, 0°, θ, 0.6°)`;
}
function trapRotate() {
  return `# 定义直角梯形顶点（在XZ平面，Y=0）
A = (0, 0, 0)       # 原点（直角顶点）
B = (6, 0, 0)       # X轴上的点（下底长度=6）
C = (4, 0, 4)       # 斜边顶点（X=4，Z=4）
D = (0, 0, 4)       # Z轴上的点（上底长度=4，高度=4）
# 创建直角梯形（顶点顺序：A→B→C→D）
trapezoid = Polygon(A, B, C, D)
# 创建旋转控制滑动条 (0-360度)
θ = Slider(0°, 360°)
# 创建绕Z轴旋转序列（步长0.6°）
rotatedTrapezoids = Sequence(Rotate(trapezoid, k, zAxis), k, 0°, θ, 0.6°)`;
}
function prismNet() {
  return `# 创建边数滑动条（3-8边）
n = Slider(3, 8, 1)
# 创建高度滑动条
 h = Slider(3, 8)
# 创建展开控制滑动条
 k = Slider(0, 1)
# 构造棱柱（基于正多边形）
a = Prism(Polygon((-1, 0, 0), (1, 0, 0), n), h)
# 生成展开图
Net(a, k)`;
}
function pyramidNet() {
  return `# 创建边数滑动条（3-8边）
n = Slider(3, 8, 1)
# 创建高度滑动条
 h = Slider(3, 8)
# 创建展开控制滑动条
 k = Slider(0, 1)
# 构造棱锥（基于正多边形）
a = Pyramid(Polygon((-1, 0, 0), (1, 0, 0), n), h)
# 生成展开图
Net(a, k)
`;
}
function aiDemo() {
  return `# 3D 示例：四面体
A=(0,0,0)
B=(4,0,0)
C=(2,3,0)
D=(2,1,4)
Segment(A,B)
Segment(B,C)
Segment(C,A)
Segment(A,D)
Segment(B,D)
Segment(C,D)`;
}
</script>

<style scoped>
/* ========= 布局 ========= */
html,
body {
  margin: 0;
  height: 100%;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    "Helvetica Neue", Arial, "Noto Sans", sans-serif;
}
.page-wrapper {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #0f0f11;
  color: #e4e4e4;
}
.page-header {
  flex-shrink: 0;
  padding: 0 30px;
  height: 70px;
  display: flex;
  align-items: center;
  background: #000000;
  border-bottom: 1px solid #2a2a2e;
}
.page-header h1 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  letter-spacing: 0.5px;
  background: linear-gradient(90deg, #00c6ff, #0072ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
.main-container {
  flex: 1;
  display: flex;
  overflow: hidden;
}
.canvas-area {
  flex: 1;
  position: relative;
  background: #0a0a0c;
}
#ggbApplet {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
}

/* ========= 右侧面板 ========= */
.control-panel {
  flex-shrink: 0;
  width: 500px;
  padding: 20px;
  overflow-y: auto;
  background: #000000;
}
.glass-card {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 16px;
  padding: 20px;
  backdrop-filter: blur(12px);
}
.btn-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 18px;
}
.btn-row button {
  flex: 1 1 45%;
  padding: 8px 0;
  font-size: 13px;
  border: none;
  border-radius: 6px;
  font-weight: 600;
  color: #fff;
  cursor: pointer;
  transition: all 0.25s;
  outline: none;
}
.btn-blue {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}
.btn-orange {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}
.btn-purple {
  background: linear-gradient(135deg, #a18cd1 0%, #fbc2eb 100%);
}
.btn-green {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}
.btn-red {
  background: linear-gradient(135deg, #ff6b6b 0%, #ffa8a8 100%);
}
.btn-row button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.35);
}
.cmd-textarea {
  width: 100%;
  min-height: 350px;
  font-family: Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace;
  font-size: 14px;
  line-height: 1.4;
  color: #e4e4e4;
  background: rgba(255, 255, 255, 0.06);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 10px;
  resize: vertical;
  outline: none;
}
.cmd-textarea::placeholder {
  color: #8a8a8a;
}
.action-row {
  display: flex;
  gap: 10px;
  margin-top: 18px;
}
.action-row button {
  flex: 1;
  padding: 10px 0;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  font-size: 14px;
  color: #fff;
  cursor: pointer;
  transition: all 0.25s;
}
.btn-success {
  background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
}
.btn-info {
  background: linear-gradient(135deg, #36d1dc 0%, #5b86e5 100%);
}
.btn-danger {
  background: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%);
}
.action-row button:hover {
  opacity: 0.9;
  transform: translateY(-1px);
}
</style>
