<script setup>
import { ref, computed, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";

import {
  GRS_API_KEY,
  VARIANT_API_URL,
  VARIANT_MODEL,
  VARIANT_TEMPERATURE,
  VARIANT_MAX_TOKENS,
  QUESTION_VARIANT_PROMPT,
} from "@/config/index.js";

const router = useRouter();

const API_KEY = GRS_API_KEY;
const API_URL = VARIANT_API_URL;

// ── 状态 ──
const status = ref("idle"); // 'idle' | 'generating' | 'done' | 'error'
const textInput = ref("");
const variantCount = ref(3); // 默认3题，范围1-5
const errorMsg = ref("");
const rawContent = ref("");
const cancelTokenSource = ref(null);

// ── 数量选项 ──
const COUNT_OPTIONS = [
  { value: 1, label: "1 题" },
  { value: 2, label: "2 题" },
  { value: 3, label: "3 题" },
  { value: 4, label: "4 题" },
  { value: 5, label: "5 题" },
];

// ── 解析原题分析 ──
const originalAnalysis = computed(() => {
  const raw = rawContent.value;
  const match = raw.match(/###\s*原题分析([\s\S]*?)(?=###\s*变式题|$)/);
  if (!match) return null;

  const content = match[1].trim();
  return {
    type: extractField(content, "题型"),
    knowledge: extractField(content, "考查知识点"),
    difficulty: extractField(content, "难度等级"),
    features: extractField(content, "题目特点"),
  };
});

// ── 解析变式题列表 ──
const variantQuestions = computed(() => {
  const raw = rawContent.value;
  const result = [];

  // 匹配所有变式题块
  const regex = /###\s*变式题\s*(\d+)([\s\S]*?)(?=###\s*变式题|$)/g;
  let match;

  while ((match = regex.exec(raw)) !== null) {
    const index = parseInt(match[1]);
    const content = match[2].trim();

    result.push({
      index,
      type: extractField(content, "题目类型"),
      difficulty: extractField(content, "难度等级"),
      content: extractField(content, "题目内容"),
      options: extractOptions(content),
      answer: extractField(content, "正确答案"),
      explanation: extractField(content, "详细解析"),
      knowledge: extractField(content, "考查知识点"),
    });
  }

  return result;
});

// ── 提取选项 ──
function extractOptions(text) {
  const options = [];
  // 匹配题目内容中的选项 A. xxx B. xxx C. xxx D. xxx
  const contentMatch = text.match(
    /\*\*题目内容\*\*[：:]\s*([\s\S]*?)(?=\*\*正确答案\*\*|$)/i
  );
  if (!contentMatch) return options;

  const contentBlock = contentMatch[1];
  const lines = contentBlock.split("\n");

  for (const line of lines) {
    const match = line.match(/^([A-D])[\.．。:：]\s*(.+)$/i);
    if (match) {
      options.push({
        label: match[1].toUpperCase(),
        content: match[2].trim(),
      });
    }
  }

  return options;
}

// ── 提取字段值 ──
function extractField(text, fieldName) {
  const regex = new RegExp(
    `\\*\\*${fieldName}\\*\\*[：:]\\s*([\\s\\S]*?)(?=\\n\\*\\*|$)`,
    "i"
  );
  const match = text.match(regex);
  return match ? match[1].trim() : "";
}

// ── 构建请求体 ──
const buildRequestBody = () => {
  return {
    model: VARIANT_MODEL,
    messages: [
      { role: "system", content: QUESTION_VARIANT_PROMPT },
      {
        role: "user",
        content: `请分析以下试题，并生成 ${variantCount.value} 道变式题：\n\n${textInput.value}`,
      },
    ],
    temperature: VARIANT_TEMPERATURE,
    max_tokens: VARIANT_MAX_TOKENS,
    stream: true,
  };
};

// ── 提取 SSE delta 文本 ──
const extractTextDelta = (chunk) => {
  let result = "";
  const lines = chunk.split("\n");
  for (const line of lines) {
    if (!line.startsWith("data: ")) continue;
    const jsonStr = line.slice(6).trim();
    if (!jsonStr || jsonStr === "[DONE]") continue;
    try {
      const data = JSON.parse(jsonStr);
      const text = data?.choices?.[0]?.delta?.content;
      if (text) result += text;
    } catch {
      // 忽略解析失败的行
    }
  }
  return result;
};

// ── 过滤思考块 ──
const filterThinkBlocks = (text) => {
  let filtered = text.replace(/<think>[\s\S]*?<\/think>/g, "");
  filtered = filtered.replace(/<think>[\s\S]*$/, "");
  return filtered;
};

// ── 开始生成 ──
const canGenerate = computed(() => {
  return status.value !== "generating" && textInput.value.trim().length > 0;
});

const startGeneration = async () => {
  if (!canGenerate.value) return;
  status.value = "generating";
  errorMsg.value = "";
  rawContent.value = "";

  cancelTokenSource.value = axios.CancelToken.source();
  let lastLength = 0;

  await axios
    .post(API_URL, buildRequestBody(), {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${API_KEY}`,
      },
      responseType: "text",
      cancelToken: cancelTokenSource.value.token,
      onDownloadProgress: (event) => {
        const text = (event.target || event.event?.target)?.responseText || "";
        if (!text) return;
        const newChunk = text.slice(lastLength);
        lastLength = text.length;
        const delta = extractTextDelta(newChunk);
        if (delta) {
          rawContent.value = filterThinkBlocks(rawContent.value + delta);
        }
      },
    })
    .then(() => {
      status.value = "done";
    })
    .catch((err) => {
      if (axios.isCancel(err)) return;
      console.error(err);
      errorMsg.value =
        err?.response?.data?.error?.message ||
        err.message ||
        "请求失败，请稍后重试";
      status.value = "error";
    });
};

const cancelGeneration = () => {
  if (cancelTokenSource.value) {
    cancelTokenSource.value.cancel("用户取消");
    status.value = "idle";
    rawContent.value = "";
  }
};

const resetAll = () => {
  status.value = "idle";
  rawContent.value = "";
  errorMsg.value = "";
};

// ── Markdown 渲染 ──
const renderContent = (text) => {
  return text
    .replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>")
    .replace(/\n/g, "<br>");
};

// ── 难度颜色映射 ──
const getDifficultyColor = (difficulty) => {
  const colors = {
    容易: "#10b981",
    较易: "#34d399",
    适中: "#f59e0b",
    较难: "#f97316",
    困难: "#ef4444",
  };
  return colors[difficulty] || "#6366f1";
};

const goBack = () => router.back();

onUnmounted(() => {
  if (cancelTokenSource.value)
    cancelTokenSource.value.cancel("组件卸载，取消请求");
});
</script>

<template>
  <div class="page-container">
    <!-- Nav Bar -->
    <div class="nav-bar">
      <button class="back-btn" @click="goBack">
        <svg
          width="20"
          height="20"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2.2"
          stroke-linecap="round"
          stroke-linejoin="round"
        >
          <polyline points="15 18 9 12 15 6" />
        </svg>
        <span>返回</span>
      </button>
      <h1 class="nav-title">题目变式生成</h1>
      <div style="width: 72px"></div>
    </div>

    <!-- Error Banner -->
    <div v-if="errorMsg" class="error-banner">
      <span>{{ errorMsg }}</span>
      <button class="error-close" @click="errorMsg = ''">✕</button>
    </div>

    <!-- Main Layout -->
    <div class="main-layout">
      <!-- Left Panel: Input -->
      <div class="left-panel">
        <div class="input-card">
          <div class="card-header">
            <div class="header-icon">
              <svg
                width="20"
                height="20"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              >
                <path
                  d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"
                />
                <polyline points="14 2 14 8 20 8" />
                <line x1="16" y1="13" x2="8" y2="13" />
                <line x1="16" y1="17" x2="8" y2="17" />
              </svg>
            </div>
            <h2 class="header-title">输入原始试题</h2>
          </div>

          <div class="input-content">
            <div class="input-row">
              <button
                class="example-btn"
                @click="
                  textInput =
                    'He ______ to school every day.\nA. go  B. goes  C. going  D. went。'
                "
              >
                示例试题
              </button>
            </div>

            <textarea
              v-model="textInput"
              class="text-area"
              placeholder="请粘贴原始试题内容...&#10;&#10;例如：&#10;Choose the best answer:&#10;The teacher asked the students _____ they had finished their homework.&#10;A. that  B. if  C. what  D. whether"
              :disabled="status === 'generating'"
            ></textarea>
            <div class="char-count">{{ textInput.length }} 字符</div>
          </div>
        </div>

        <!-- Config Card -->
        <div class="config-card">
          <div class="config-header">
            <div class="header-icon">
              <svg
                width="20"
                height="20"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              >
                <circle cx="12" cy="12" r="3" />
                <path
                  d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"
                />
              </svg>
            </div>
            <h2 class="header-title">生成配置</h2>
          </div>

          <div class="config-content">
            <div class="config-item">
              <label class="config-label">变式题数量</label>
              <div class="count-selector">
                <button
                  v-for="opt in COUNT_OPTIONS"
                  :key="opt.value"
                  class="count-btn"
                  :class="{ active: variantCount === opt.value }"
                  @click="variantCount = opt.value"
                  :disabled="status === 'generating'"
                >
                  {{ opt.value }}
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- Action Buttons -->
        <div class="action-area">
          <button
            v-if="status !== 'generating'"
            class="generate-btn"
            :disabled="!canGenerate"
            @click="startGeneration"
          >
            <svg
              width="20"
              height="20"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" />
            </svg>
            <span>生成变式题</span>
          </button>
          <button v-else class="cancel-btn" @click="cancelGeneration">
            <span class="btn-spinner"></span>
            <span>生成中，点击取消</span>
          </button>
          <button
            v-if="status === 'done' || status === 'error'"
            class="reset-btn"
            @click="resetAll"
          >
            重新生成
          </button>
        </div>
      </div>

      <!-- Right Panel: Result -->
      <div class="right-panel">
        <!-- Empty State -->
        <div v-if="status === 'idle'" class="empty-state">
          <div class="empty-icon">
            <svg
              width="48"
              height="48"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.2"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" />
            </svg>
          </div>
          <p class="empty-title">等待生成</p>
          <p class="empty-hint">
            在左侧输入试题内容，选择数量后点击「生成变式题」
          </p>
        </div>

        <!-- Generating State -->
        <div
          v-else-if="status === 'generating' && !rawContent"
          class="empty-state loading-state"
        >
          <div class="loading-spinner">
            <div class="spinner-ring"></div>
          </div>
          <p class="empty-title">AI 正在分析题目...</p>
          <p class="empty-hint">正在识别题型、考点和难度</p>
        </div>

        <!-- Result Area -->
        <div
          v-else-if="status === 'generating' || status === 'done'"
          class="result-area"
        >
          <div class="result-header">
            <div class="result-title-wrap">
              <div
                class="result-dot"
                :class="{ pulse: status === 'generating' }"
              ></div>
              <span class="result-title">{{
                status === "generating" ? "AI 正在生成..." : "生成完成"
              }}</span>
            </div>
          </div>

          <!-- Original Analysis -->
          <div v-if="originalAnalysis" class="analysis-card">
            <div class="analysis-header">
              <svg
                width="18"
                height="18"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              >
                <circle cx="11" cy="11" r="8" />
                <path d="m21 21-4.35-4.35" />
              </svg>
              <span>原题分析</span>
            </div>
            <div class="analysis-body">
              <div class="analysis-item" v-if="originalAnalysis.type">
                <span class="analysis-label">题型</span>
                <span class="analysis-value">{{ originalAnalysis.type }}</span>
              </div>
              <div class="analysis-item" v-if="originalAnalysis.knowledge">
                <span class="analysis-label">考查知识点</span>
                <span class="analysis-value">{{
                  originalAnalysis.knowledge
                }}</span>
              </div>
              <div class="analysis-item" v-if="originalAnalysis.difficulty">
                <span class="analysis-label">难度等级</span>
                <span
                  class="analysis-value"
                  :style="{
                    color: getDifficultyColor(originalAnalysis.difficulty),
                  }"
                >
                  {{ originalAnalysis.difficulty }}
                </span>
              </div>
              <div class="analysis-item" v-if="originalAnalysis.features">
                <span class="analysis-label">题目特点</span>
                <span class="analysis-value">{{
                  originalAnalysis.features
                }}</span>
              </div>
            </div>
          </div>

          <!-- Variant Questions -->
          <div class="variants-section">
            <div class="variants-header">
              <svg
                width="18"
                height="18"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              >
                <path
                  d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"
                />
                <polyline points="14 2 14 8 20 8" />
                <line x1="16" y1="13" x2="8" y2="13" />
                <line x1="16" y1="17" x2="8" y2="17" />
              </svg>
              <span>变式题目</span>
              <span
                class="variant-count-badge"
                v-if="variantQuestions.length > 0"
              >
                已生成 {{ variantQuestions.length }} 题
              </span>
            </div>

            <div
              v-for="(question, idx) in variantQuestions"
              :key="question.index"
              class="question-card"
              :style="{ animationDelay: `${idx * 0.1}s` }"
            >
              <div class="question-header">
                <div class="question-number">
                  <span class="number-badge">第 {{ question.index }} 题</span>
                </div>
                <div class="question-tags">
                  <span class="tag type-tag">{{
                    question.type || "未知题型"
                  }}</span>
                  <span
                    class="tag difficulty-tag"
                    :style="{
                      backgroundColor:
                        getDifficultyColor(question.difficulty) + '18',
                      color: getDifficultyColor(question.difficulty),
                      borderColor:
                        getDifficultyColor(question.difficulty) + '40',
                    }"
                  >
                    {{ question.difficulty || "未知难度" }}
                  </span>
                </div>
              </div>

              <div class="question-body">
                <!-- 题目内容 -->
                <div
                  class="question-section content-section"
                  v-if="question.content"
                >
                  <div class="section-header">
                    <svg
                      width="14"
                      height="14"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                    >
                      <circle cx="12" cy="12" r="10" />
                      <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3" />
                      <line x1="12" y1="17" x2="12.01" y2="17" />
                    </svg>
                    <span>题目内容</span>
                  </div>
                  <div
                    class="section-content content-text"
                    v-html="renderContent(question.content)"
                  ></div>
                </div>

                <!-- 选项网格 -->
                <div
                  v-if="question.options && question.options.length > 0"
                  class="options-grid"
                >
                  <div
                    v-for="opt in question.options"
                    :key="opt.label"
                    class="option-item"
                    :class="{
                      'correct-option':
                        question.answer &&
                        question.answer.toUpperCase().includes(opt.label),
                    }"
                  >
                    <span class="option-label">{{ opt.label }}.</span>
                    <span class="option-text">{{ opt.content }}</span>
                  </div>
                </div>

                <!-- 正确答案 -->
                <div
                  class="question-section answer-section"
                  v-if="question.answer"
                >
                  <div class="answer-row">
                    <div class="answer-icon">
                      <svg
                        width="16"
                        height="16"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2.5"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                      >
                        <polyline points="20 6 9 17 4 12" />
                      </svg>
                    </div>
                    <span class="answer-label">正确答案</span>
                    <span
                      class="answer-value"
                      v-html="renderContent(question.answer)"
                    ></span>
                  </div>
                </div>

                <!-- 详细解析 -->
                <div
                  class="question-section explanation-section"
                  v-if="question.explanation"
                >
                  <div class="section-header">
                    <svg
                      width="14"
                      height="14"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                    >
                      <path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z" />
                      <path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z" />
                    </svg>
                    <span>详细解析</span>
                  </div>
                  <div
                    class="section-content explanation-text"
                    v-html="renderContent(question.explanation)"
                  ></div>
                </div>

                <!-- 考查知识点 -->
                <div class="knowledge-section" v-if="question.knowledge">
                  <div class="knowledge-icon">
                    <svg
                      width="12"
                      height="12"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                    >
                      <polygon
                        points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"
                      />
                    </svg>
                  </div>
                  <span class="knowledge-label">考查知识点</span>
                  <span class="knowledge-value">{{ question.knowledge }}</span>
                </div>
              </div>
            </div>

            <!-- Loading placeholder for next question -->
            <div v-if="status === 'generating'" class="loading-card">
              <div class="loading-dots">
                <span class="dot"></span>
                <span class="dot"></span>
                <span class="dot"></span>
              </div>
              <p class="loading-text">正在生成变式题，请稍候...</p>
            </div>
          </div>
        </div>

        <!-- Error State -->
        <div v-else-if="status === 'error'" class="empty-state error-state">
          <div class="empty-icon error-icon">
            <svg
              width="48"
              height="48"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.2"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <circle cx="12" cy="12" r="10" />
              <line x1="12" y1="8" x2="12" y2="12" />
              <line x1="12" y1="16" x2="12.01" y2="16" />
            </svg>
          </div>
          <p class="empty-title">生成失败</p>
          <p class="empty-hint">请检查网络连接后重试</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.page-container {
  height: 100vh;
  overflow: hidden;
  background: var(--bg);
  display: flex;
  flex-direction: column;
  font-family: "Inter", "PingFang SC", -apple-system, sans-serif;
}

/* Nav */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1rem 1.5rem;
  background: rgba(255, 255, 255, 0.03);
  border-bottom: 1px solid var(--card-border);
  backdrop-filter: blur(12px);
  position: sticky;
  top: 0;
  z-index: 10;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 0.35rem;
  background: none;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  font-size: 0.95rem;
  padding: 0.4rem 0.75rem;
  border-radius: 8px;
  transition: all 0.2s;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.07);
  color: var(--text-primary);
}

.nav-title {
  font-size: 1.2rem;
  font-weight: 600;
  margin: 0;
  background: linear-gradient(135deg, #8b5cf6, #6366f1);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* Main Layout */
.main-layout {
  flex: 1;
  min-height: 0;
  display: flex;
  overflow: hidden;
}

/* Left Panel */
.left-panel {
  width: 420px;
  min-width: 320px;
  max-width: 480px;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  padding: 1.5rem;
  border-right: 1px solid var(--card-border);
  overflow-y: auto;
  flex-shrink: 0;
}

/* Right Panel */
.right-panel {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
}

.right-panel::-webkit-scrollbar {
  width: 8px;
}

.right-panel::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  margin: 4px 0;
}

.right-panel::-webkit-scrollbar-thumb {
  background: rgba(139, 92, 246, 0.3);
  border-radius: 4px;
  transition: background 0.2s;
}

.right-panel::-webkit-scrollbar-thumb:hover {
  background: rgba(139, 92, 246, 0.5);
}

/* Empty State */
.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 0.75rem;
  color: var(--text-secondary);
  opacity: 0.5;
}

.empty-icon {
  color: var(--text-secondary);
  opacity: 0.4;
}

.empty-title {
  font-size: 1rem;
  font-weight: 600;
  margin: 0;
  color: var(--text-primary);
}

.empty-hint {
  font-size: 0.875rem;
  margin: 0;
  text-align: center;
}

.error-state {
  opacity: 1;
}

.error-icon {
  color: #f87171;
  opacity: 1;
}

.error-state .empty-title {
  color: #fca5a5;
}

/* Loading State */
.loading-state {
  opacity: 1;
}

.loading-spinner {
  width: 48px;
  height: 48px;
  position: relative;
}

.spinner-ring {
  width: 100%;
  height: 100%;
  border: 3px solid rgba(139, 92, 246, 0.2);
  border-top-color: #8b5cf6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* Error Banner */
.error-banner {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: rgba(239, 68, 68, 0.12);
  border: 1px solid rgba(239, 68, 68, 0.3);
  padding: 0.75rem 1.5rem;
  color: #fca5a5;
  font-size: 0.9rem;
  animation: fadeInUp 0.2s ease;
  flex-shrink: 0;
}

.error-close {
  background: none;
  border: none;
  color: #fca5a5;
  cursor: pointer;
  font-size: 1rem;
  opacity: 0.7;
  transition: opacity 0.2s;
}

.error-close:hover {
  opacity: 1;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(-8px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* Input Card */
.input-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 280px;
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid var(--card-border);
  border-radius: 20px;
  overflow: hidden;
  backdrop-filter: blur(12px);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 1rem 1.25rem;
  border-bottom: 1px solid var(--card-border);
  background: rgba(0, 0, 0, 0.1);
}

.header-icon {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(
    135deg,
    rgba(139, 92, 246, 0.2),
    rgba(99, 102, 241, 0.2)
  );
  border-radius: 8px;
  color: #a78bfa;
}

.header-title {
  font-size: 0.95rem;
  font-weight: 600;
  margin: 0;
  color: var(--text-primary);
}

.input-content {
  padding: 1rem 1.25rem;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.input-row {
  display: flex;
  align-items: center;
  margin-bottom: 0.75rem;
}

.example-btn {
  display: flex;
  align-items: center;
  gap: 0.35rem;
  background: rgba(139, 92, 246, 0.1);
  border: 1px solid rgba(139, 92, 246, 0.25);
  color: #a78bfa;
  border-radius: 8px;
  padding: 0.35rem 0.85rem;
  font-size: 0.85rem;
  cursor: pointer;
  transition: all 0.2s;
}

.example-btn:hover {
  background: rgba(139, 92, 246, 0.2);
  transform: translateY(-1px);
}

.text-area {
  width: 100%;
  flex: 1;
  min-height: 180px;
  background: rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 12px;
  color: var(--text-primary);
  font-size: 0.95rem;
  line-height: 1.7;
  padding: 1rem;
  resize: none;
  outline: none;
  transition: border-color 0.2s, box-shadow 0.2s;
  box-sizing: border-box;
  font-family: inherit;
}

.text-area::placeholder {
  color: var(--text-secondary);
  opacity: 0.6;
}

.text-area:focus {
  border-color: rgba(139, 92, 246, 0.5);
  box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.1);
}

.text-area:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.char-count {
  text-align: right;
  font-size: 0.8rem;
  color: var(--text-secondary);
  margin-top: 0.5rem;
  opacity: 0.6;
}

/* Config Card */
.config-card {
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid var(--card-border);
  border-radius: 20px;
  overflow: hidden;
  backdrop-filter: blur(12px);
}

.config-header {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 1rem 1.25rem;
  border-bottom: 1px solid var(--card-border);
  background: rgba(0, 0, 0, 0.1);
}

.config-content {
  padding: 1rem 1.25rem;
}

.config-item {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.config-label {
  font-size: 0.875rem;
  color: var(--text-secondary);
}

.count-selector {
  display: flex;
  gap: 0.5rem;
}

.count-btn {
  flex: 1;
  padding: 0.6rem 0;
  background: rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 10px;
  color: var(--text-secondary);
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.2s;
}

.count-btn:hover:not(.active):not(:disabled) {
  background: rgba(255, 255, 255, 0.05);
  color: var(--text-primary);
}

.count-btn.active {
  background: linear-gradient(
    135deg,
    rgba(139, 92, 246, 0.3),
    rgba(99, 102, 241, 0.3)
  );
  border-color: rgba(139, 92, 246, 0.5);
  color: #a78bfa;
}

.count-btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
}

/* Action Area */
.action-area {
  display: flex;
  gap: 0.75rem;
}

.generate-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  padding: 1rem;
  background: linear-gradient(135deg, #8b5cf6, #6366f1);
  border: none;
  border-radius: 14px;
  color: white;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.25s;
}

.generate-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(139, 92, 246, 0.35);
}

.generate-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

.cancel-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  padding: 1rem;
  background: rgba(239, 68, 68, 0.15);
  border: 1px solid rgba(239, 68, 68, 0.3);
  border-radius: 14px;
  color: #fca5a5;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-btn:hover {
  background: rgba(239, 68, 68, 0.25);
}

.btn-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

.reset-btn {
  padding: 1rem 1.5rem;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 14px;
  color: var(--text-secondary);
  font-size: 0.95rem;
  cursor: pointer;
  transition: all 0.2s;
}

.reset-btn:hover {
  background: rgba(255, 255, 255, 0.08);
  color: var(--text-primary);
}

/* Result Area */
.result-area {
  display: flex;
  flex-direction: column;
  gap: 1.25rem;
}

.result-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.result-title-wrap {
  display: flex;
  align-items: center;
  gap: 0.6rem;
}

.result-dot {
  width: 10px;
  height: 10px;
  background: #10b981;
  border-radius: 50%;
}

.result-dot.pulse {
  animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {
  0%,
  100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.5;
    transform: scale(1.2);
  }
}

.result-title {
  font-size: 1rem;
  font-weight: 600;
  color: var(--text-primary);
}

/* Analysis Card */
.analysis-card {
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid var(--card-border);
  border-radius: 16px;
  overflow: hidden;
  backdrop-filter: blur(12px);
}

.analysis-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.9rem 1.25rem;
  background: rgba(0, 0, 0, 0.15);
  border-bottom: 1px solid var(--card-border);
  color: #14b8a6;
  font-weight: 600;
  font-size: 0.9rem;
}

.analysis-body {
  padding: 1rem 1.25rem;
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.analysis-item {
  display: flex;
  gap: 0.75rem;
}

.analysis-label {
  min-width: 80px;
  font-size: 0.85rem;
  color: var(--text-secondary);
}

.analysis-value {
  font-size: 0.85rem;
  color: var(--text-primary);
}

/* Variants Section */
.variants-section {
  display: flex;
  flex-direction: column;
  gap: 1.25rem;
}

.variants-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding-bottom: 0.75rem;
  border-bottom: 1px solid var(--card-border);
  color: #a78bfa;
  font-weight: 600;
  font-size: 0.95rem;
}

.variant-count-badge {
  margin-left: auto;
  background: rgba(139, 92, 246, 0.15);
  color: #a78bfa;
  padding: 0.35rem 1rem;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 600;
}

/* Question Card */
.question-card {
  background: rgba(255, 255, 255, 0.02);
  border: 1px solid var(--card-border);
  border-radius: 16px;
  overflow: hidden;
  backdrop-filter: blur(12px);
  animation: fadeInUp 0.4s ease both;
  transition: all 0.25s;
}

.question-card:hover {
  border-color: rgba(139, 92, 246, 0.3);
  box-shadow: 0 4px 20px rgba(139, 92, 246, 0.1);
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(15px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.question-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1rem 1.25rem;
  background: linear-gradient(
    135deg,
    rgba(139, 92, 246, 0.08),
    rgba(99, 102, 241, 0.05)
  );
  border-bottom: 1px solid var(--card-border);
}

.question-number {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.number-badge {
  font-size: 1rem;
  font-weight: 600;
  color: var(--text-primary);
  background: linear-gradient(
    135deg,
    rgba(139, 92, 246, 0.15),
    rgba(99, 102, 241, 0.1)
  );
  padding: 0.35rem 0.85rem;
  border-radius: 8px;
  border: 1px solid rgba(139, 92, 246, 0.2);
}

.question-tags {
  display: flex;
  gap: 0.5rem;
}

.tag {
  padding: 0.3rem 0.75rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 500;
  border: 1px solid transparent;
}

.type-tag {
  background: rgba(99, 102, 241, 0.15);
  color: #a5b4fc;
  border-color: rgba(99, 102, 241, 0.25);
}

.difficulty-tag {
  font-weight: 600;
  border: 1px solid;
}

.question-body {
  padding: 0;
  display: flex;
  flex-direction: column;
}

.question-section {
  padding: 1.25rem;
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #a78bfa;
  font-weight: 600;
  font-size: 0.85rem;
}

.section-content {
  font-size: 0.9rem;
  color: var(--text-primary);
  line-height: 1.75;
}

.content-text {
  white-space: pre-wrap;
  color: var(--text-primary);
  font-size: 0.95rem;
}

/* Options Grid */
.options-grid {
  padding: 0 1.25rem 1.25rem;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0.75rem;
}

.option-item {
  display: flex;
  gap: 0.5rem;
  padding: 0.85rem 1rem;
  background: rgba(255, 255, 255, 0.02);
  border: 1px solid rgba(255, 255, 255, 0.06);
  border-radius: 10px;
  transition: all 0.2s;
}

.option-item:hover {
  background: rgba(255, 255, 255, 0.04);
  border-color: rgba(139, 92, 246, 0.2);
}

.option-item.correct-option {
  background: rgba(16, 185, 129, 0.08);
  border-color: rgba(16, 185, 129, 0.3);
}

.option-label {
  font-weight: 600;
  color: #a78bfa;
  flex-shrink: 0;
  min-width: 22px;
}

.option-text {
  color: var(--text-primary);
  font-size: 0.9rem;
  line-height: 1.5;
}

.correct-option .option-label {
  color: #10b981;
}

/* Answer Section */
.answer-section {
  background: linear-gradient(
    135deg,
    rgba(16, 185, 129, 0.08),
    rgba(16, 185, 129, 0.04)
  );
  border-top: 1px solid rgba(16, 185, 129, 0.15);
  border-bottom: 1px solid rgba(16, 185, 129, 0.15);
}

.answer-row {
  display: flex;
  align-items: center;
  gap: 0.6rem;
}

.answer-icon {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(16, 185, 129, 0.15);
  border-radius: 6px;
  color: #10b981;
}

.answer-label {
  font-size: 0.9rem;
  font-weight: 600;
  color: var(--text-secondary);
}

.answer-value {
  font-size: 0.95rem;
  font-weight: 600;
  color: #10b981;
}

/* Explanation Section */
.explanation-section {
  background: rgba(255, 255, 255, 0.01);
  border-top: 1px solid var(--card-border);
}

.explanation-text {
  color: var(--text-secondary);
  font-size: 0.9rem;
  line-height: 1.75;
}

/* Knowledge Section */
.knowledge-section {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.85rem 1.25rem;
  background: rgba(251, 191, 36, 0.05);
  border-top: 1px solid rgba(251, 191, 36, 0.15);
}

.knowledge-icon {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fbbf24;
}

.knowledge-label {
  font-size: 0.8rem;
  font-weight: 600;
  color: var(--text-secondary);
}

.knowledge-value {
  font-size: 0.85rem;
  color: #fbbf24;
  font-weight: 500;
}

/* Loading Card */
.loading-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 3rem;
  background: rgba(255, 255, 255, 0.02);
  border: 1px dashed rgba(139, 92, 246, 0.3);
  border-radius: 16px;
}

.loading-dots {
  display: flex;
  gap: 8px;
  margin-bottom: 1rem;
}

.dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: rgba(139, 92, 246, 0.5);
  animation: bounce 1.2s ease-in-out infinite;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
}

.loading-text {
  font-size: 0.9rem;
  color: var(--text-secondary);
  margin: 0;
}

@keyframes bounce {
  0%,
  80%,
  100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-8px);
  }
}
</style>
