<script setup>
import { ref, computed, onUnmounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import {
  DOUBAO_APP_ID,
  DOUBAO_ACCESS_TOKEN,
  DOUBAO_RESOURCE_ID,
  DOUBAO_TTS_API_PATH,
  DOUBAO_AUDIO_FORMAT,
  DOUBAO_SAMPLE_RATE,
  PROBLEM_API_URL,
  PROBLEM_MODEL,
  PROBLEM_API_KEY,
} from "@/config/index.js";
import pako from "pako";

const router = useRouter();

// ── 状态管理 ──
const inputText = ref("");
const wordList = ref([]);
const currentWordIndex = ref(null);
const currentWord = computed(() =>
  currentWordIndex.value !== null
    ? wordList.value[currentWordIndex.value]
    : null
);

// ── TTS 状态 ──
const isPlaying = ref(false);
const playingIndex = ref(null);
let currentAudioInstance = null;
const blobUrls = [];

// ── 录音状态 ──
const isRecording = ref(false);
const asrStatus = ref(""); // 'connecting' | 'recording' | 'error' | ''
let asrWs = null;
let asrAudioContext = null;
let asrScriptProcessor = null;
let asrMediaStream = null;
let recognizedText = ref("");

// ── 评测结果 ──
const evaluationResult = ref(null);
const isEvaluating = ref(false);

// ── 音色选择 ──
const selectedVoice = ref("en_female_dacey_uranus_bigtts");
const voiceOptions = [
  { id: "en_female_dacey_uranus_bigtts", name: "Dacey (美音女)" },
  { id: "en_male_tim_uranus_bigtts", name: "Tim (美音男)" },
  { id: "en_female_stokie_uranus_bigtts", name: "Stokie (美音女)" },
  { id: "zh_female_yingyujiaoxue_uranus_bigtts", name: "Tina (英音女)" },
];

// ── 语速选择 ──
const playbackRate = ref(1.0);
const speedOptions = [
  { value: 0.5, label: "0.5x" },
  { value: 0.75, label: "0.75x" },
  { value: 1.0, label: "1.0x" },
  { value: 1.25, label: "1.25x" },
  { value: 1.5, label: "1.5x" },
  { value: 2.0, label: "2.0x" },
];

// ── 工具函数 ──
const generateUUID = () => {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0;
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

// ── 文本解析 ──
const parseText = () => {
  const text = inputText.value.trim();
  if (!text) {
    wordList.value = [];
    return;
  }

  // 支持逗号、顿号、换行符分隔
  const items = text
    .split(/[,，、\n]+/)
    .map((item) => item.trim())
    .filter((item) => item.length > 0);

  // 去重
  wordList.value = [...new Set(items)];
};

// ── TTS 语音合成 ──
const synthesizeAndPlay = async (text) => {
  if (!text || !text.trim()) return;

  const payload = {
    user: { uid: "eval_" + Date.now() },
    req_params: {
      text,
      speaker: selectedVoice.value,
      audio_params: {
        format: DOUBAO_AUDIO_FORMAT,
        sample_rate: DOUBAO_SAMPLE_RATE,
      },
    },
  };

  try {
    const response = await fetch(DOUBAO_TTS_API_PATH, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Api-App-Id": DOUBAO_APP_ID,
        "X-Api-Access-Key": DOUBAO_ACCESS_TOKEN,
        "X-Api-Resource-Id": DOUBAO_RESOURCE_ID,
        "X-Api-Request-Id": generateUUID(),
      },
      body: JSON.stringify(payload),
    });

    if (!response.ok) throw new Error(`TTS HTTP ${response.status}`);

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = "";
    const audioChunks = [];

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split("\n");
      buffer = lines.pop();
      for (const line of lines) {
        if (!line.trim()) continue;
        try {
          const resData = JSON.parse(line);
          if (resData.code === 0 && resData.data) {
            const bin = window.atob(resData.data);
            const bytes = new Uint8Array(bin.length);
            for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
            audioChunks.push(bytes);
          }
        } catch (e) {}
      }
    }

    if (audioChunks.length === 0) return;

    const totalLen = audioChunks.reduce((a, v) => a + v.length, 0);
    const allBytes = new Uint8Array(totalLen);
    let offset = 0;
    for (const chunk of audioChunks) {
      allBytes.set(chunk, offset);
      offset += chunk.length;
    }

    const blob = new Blob([allBytes], { type: "audio/mp3" });
    const url = URL.createObjectURL(blob);
    blobUrls.push(url);

    playAudio(url);
  } catch (err) {
    console.error("TTS error:", err);
  }
};

const playAudio = (url) => {
  if (currentAudioInstance) {
    currentAudioInstance.pause();
    currentAudioInstance = null;
  }

  const audio = new Audio(url);
  audio.playbackRate = playbackRate.value;
  currentAudioInstance = audio;
  isPlaying.value = true;

  audio.onended = () => {
    isPlaying.value = false;
    playingIndex.value = null;
    currentAudioInstance = null;
  };

  audio.onerror = () => {
    isPlaying.value = false;
    playingIndex.value = null;
  };

  audio.play().catch((err) => {
    console.error("Playback failed:", err);
    isPlaying.value = false;
  });
};

const handleWordClick = (index) => {
  currentWordIndex.value = index;
  playingIndex.value = index;
  evaluationResult.value = null; // 清空之前的评测结果
  synthesizeAndPlay(wordList.value[index]);
};

// ── ASR 语音识别 ──
const float32ToInt16Bytes = (float32Array) => {
  const int16 = new Int16Array(float32Array.length);
  for (let i = 0; i < float32Array.length; i++) {
    const s = Math.max(-1, Math.min(1, float32Array[i]));
    int16[i] = s < 0 ? s * 0x8000 : s * 0x7fff;
  }
  return new Uint8Array(int16.buffer);
};

const buildFrame = (
  messageType,
  flags,
  serialization,
  compression,
  payload
) => {
  const header = new Uint8Array([
    (0x01 << 4) | 0x01,
    (messageType << 4) | flags,
    (serialization << 4) | compression,
    0x00,
  ]);
  const sizeView = new DataView(new ArrayBuffer(4));
  sizeView.setUint32(0, payload.length, false);
  const frame = new Uint8Array(4 + 4 + payload.length);
  frame.set(header, 0);
  frame.set(new Uint8Array(sizeView.buffer), 4);
  frame.set(payload, 8);
  return frame;
};

const parseServerFrame = (buffer) => {
  const view = new DataView(buffer);
  const byte1 = view.getUint8(1);
  const byte2 = view.getUint8(2);
  const msgType = (byte1 >> 4) & 0x0f;
  const flags = byte1 & 0x0f;
  const compression = byte2 & 0x0f;

  if (msgType === 0x0f) {
    const errCode = view.getUint32(4, false);
    const errMsgSize = view.getUint32(8, false);
    const errMsg = new TextDecoder().decode(
      new Uint8Array(buffer, 12, errMsgSize)
    );
    return { msgType, flags, error: true, code: errCode, message: errMsg };
  }

  const sequence = view.getInt32(4, false);
  const payloadSize = view.getUint32(8, false);
  const payloadBytes = new Uint8Array(buffer, 12, payloadSize);

  let jsonStr;
  if (compression === 0x01) {
    jsonStr = new TextDecoder().decode(pako.ungzip(payloadBytes));
  } else {
    jsonStr = new TextDecoder().decode(payloadBytes);
  }

  return { msgType, flags, sequence, data: JSON.parse(jsonStr) };
};

const stopRecording = async () => {
  isRecording.value = false;
  asrStatus.value = "";

  if (asrScriptProcessor) {
    asrScriptProcessor.disconnect();
    asrScriptProcessor = null;
  }
  if (asrAudioContext) {
    asrAudioContext.close().catch(() => {});
    asrAudioContext = null;
  }
  if (asrMediaStream) {
    asrMediaStream.getTracks().forEach((t) => t.stop());
    asrMediaStream = null;
  }
  if (asrWs) {
    if (asrWs.readyState === WebSocket.OPEN) {
      try {
        const emptyGzip = pako.gzip(new Uint8Array(0));
        const endFrame = buildFrame(0x02, 0x02, 0x00, 0x01, emptyGzip);
        asrWs.send(endFrame);

        // 等待最终识别结果
        await new Promise((resolve) => {
          asrWs.onclose = () => {
            asrWs = null;
            resolve();
          };
          setTimeout(resolve, 800);
        });
      } catch (e) {}
    }
    asrWs = null;
  }

  // 识别完成后进行评测
  if (recognizedText.value && currentWord.value) {
    await evaluatePronunciation();
  }
};

const startRecording = async () => {
  if (isRecording.value) {
    await stopRecording();
    return;
  }

  if (!currentWord.value) {
    alert("请先点击要评测的单词或句子");
    return;
  }

  if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
    alert("您的浏览器不支持麦克风录音功能");
    return;
  }

  asrStatus.value = "connecting";
  recognizedText.value = "";

  try {
    const wsProtocol = import.meta.env.DEV ? "ws" : "wss";
    const wsUrl = `${wsProtocol}://${location.host}/asr-ws/api/v3/sauc/bigmodel`;
    const ws = new WebSocket(wsUrl);
    ws.binaryType = "arraybuffer";
    asrWs = ws;

    await new Promise((resolve, reject) => {
      ws.onopen = () => resolve();
      ws.onerror = () => reject(new Error("WebSocket 连接失败"));
      setTimeout(() => reject(new Error("WebSocket 连接超时")), 8000);
    });

    const initPayload = {
      user: { uid: "eval_asr_" + Date.now() },
      audio: {
        format: "pcm",
        rate: 16000,
        bits: 16,
        channel: 1,
      },
      request: {
        model_name: "bigmodel",
        enable_punc: true,
        enable_itn: true,
      },
    };
    const compressedInit = pako.gzip(JSON.stringify(initPayload));
    ws.send(buildFrame(0x01, 0x00, 0x01, 0x01, compressedInit));

    ws.onmessage = (event) => {
      try {
        const parsed = parseServerFrame(event.data);

        if (parsed.error) {
          console.error("ASR server error:", parsed.code, parsed.message);
          return;
        }

        const { data } = parsed;
        if (data?.code && data.code !== 20000000) {
          console.error("ASR error code:", data.code, data.message);
          return;
        }

        const result = data?.result;
        if (!result) return;

        const text = result.text || "";
        if (!text) return;

        const hasFinal = result.utterances?.some((u) => u.definite === true);
        if (hasFinal) {
          recognizedText.value = text;
        }
      } catch (e) {
        console.error("ASR parse error:", e);
      }
    };

    ws.onerror = () => {
      console.error("ASR WebSocket error");
      stopRecording();
      asrStatus.value = "error";
      setTimeout(() => {
        asrStatus.value = "";
      }, 3000);
    };

    ws.onclose = () => {
      if (isRecording.value) stopRecording();
    };

    const stream = await navigator.mediaDevices.getUserMedia({
      audio: {
        sampleRate: 16000,
        channelCount: 1,
        echoCancellation: true,
        noiseSuppression: true,
      },
    });
    asrMediaStream = stream;

    const AudioContextClass =
      window.AudioContext || window["webkitAudioContext"];
    const audioCtx = new AudioContextClass({ sampleRate: 16000 });
    asrAudioContext = audioCtx;

    const source = audioCtx.createMediaStreamSource(stream);
    const processor = audioCtx.createScriptProcessor(2048, 1, 1);
    asrScriptProcessor = processor;

    processor.onaudioprocess = (e) => {
      if (!isRecording.value || !asrWs || asrWs.readyState !== WebSocket.OPEN)
        return;
      const pcmBytes = float32ToInt16Bytes(e.inputBuffer.getChannelData(0));
      const compressed = pako.gzip(pcmBytes);
      asrWs.send(buildFrame(0x02, 0x00, 0x00, 0x01, compressed));
    };

    source.connect(processor);
    processor.connect(audioCtx.destination);

    isRecording.value = true;
    asrStatus.value = "recording";
  } catch (err) {
    console.error("ASR start error:", err);
    stopRecording();
    asrStatus.value = "error";
    setTimeout(() => {
      asrStatus.value = "";
    }, 3000);
    if (err.name === "NotAllowedError") {
      alert("麦克风权限被拒绝，请在浏览器设置中允许访问麦克风");
    }
  }
};

// ── AI 评测 ──
const evaluatePronunciation = async () => {
  if (!currentWord.value || !recognizedText.value) return;

  isEvaluating.value = true;
  evaluationResult.value = null;

  try {
    const prompt = `评测发音（JSON格式，仅输出JSON）：
标准：${currentWord.value}
实际：${recognizedText.value}
输出：{"overallScore":0-100,"accuracy":0-100,"fluency":0-100,"errors":[{"word":"","expected":"","actual":"","type":"spelling/pronunciation/missing/extra"}],"suggestions":"简短建议"}`;

    const response = await fetch(PROBLEM_API_URL, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${PROBLEM_API_KEY}`,
      },
      body: JSON.stringify({
        model: PROBLEM_MODEL,
        messages: [
          {
            role: "system",
            content: "英语发音评测专家，仅输出JSON。",
          },
          { role: "user", content: prompt },
        ],
        max_tokens: 500,
      }),
    });

    if (!response.ok) throw new Error(`评测 API 错误: ${response.status}`);

    const data = await response.json();
    let resultText = data.choices[0].message.content.trim();

    // 提取 JSON
    const jsonMatch = resultText.match(/\{[\s\S]*\}/);
    if (jsonMatch) {
      evaluationResult.value = JSON.parse(jsonMatch[0]);
    } else {
      throw new Error("无法解析评测结果");
    }
  } catch (err) {
    console.error("评测失败:", err);
    evaluationResult.value = {
      overallScore: 0,
      accuracy: 0,
      fluency: 0,
      errors: [],
      suggestions: "评测失败，请重试",
    };
  } finally {
    isEvaluating.value = false;
  }
};

// ── 清理资源 ──
onUnmounted(() => {
  if (currentAudioInstance) {
    currentAudioInstance.pause();
    currentAudioInstance = null;
  }
  blobUrls.forEach((url) => URL.revokeObjectURL(url));
  blobUrls.length = 0;
  stopRecording();
});
</script>

<template>
  <div class="page-container">
    <!-- 顶部导航 -->
    <nav class="nav-bar">
      <button @click="router.push('/')" class="back-btn">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          fill="none"
          viewBox="0 0 24 24"
          stroke-width="2"
          stroke="currentColor"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            d="M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18"
          />
        </svg>
        返回首页
      </button>
      <div class="nav-title">听读评测</div>
      <div class="nav-controls">
        <div class="speed-select-wrap">
          <label class="speed-label">语速</label>
          <select v-model="playbackRate" class="speed-select">
            <option v-for="s in speedOptions" :key="s.value" :value="s.value">
              {{ s.label }}
            </option>
          </select>
        </div>
        <div class="voice-select-wrap">
          <select v-model="selectedVoice" class="voice-select">
            <option v-for="v in voiceOptions" :key="v.id" :value="v.id">
              {{ v.name }}
            </option>
          </select>
        </div>
      </div>
    </nav>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 左侧输入区 -->
      <div class="left-panel">
        <div class="input-section">
          <h3 class="section-title">输入单词或句子</h3>
          <textarea
            v-model="inputText"
            @input="parseText"
            class="input-textarea"
            placeholder="输入单词或句子列表，支持逗号、顿号或换行分隔&#10;例如：apple, banana, orange&#10;或每行一个单词"
            rows="12"
          ></textarea>
          <div class="input-footer">
            <span class="word-count">{{ wordList.length }} 项</span>
            <button
              @click="
                inputText = '';
                wordList = [];
              "
              class="clear-btn"
            >
              清空
            </button>
          </div>
        </div>
      </div>

      <!-- 右侧展示和评测区 -->
      <div class="right-panel">
        <!-- 内容卡片展示 -->
        <div class="cards-section">
          <h3 class="section-title">点击卡片听发音</h3>
          <div v-if="wordList.length === 0" class="empty-hint">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
              stroke-width="1.5"
              stroke="currentColor"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                d="M12 18.75a6 6 0 006-6v-1.5m-6 7.5a6 6 0 01-6-6v-1.5m6 7.5v3.75m-3.75 0h7.5M12 15.75a3 3 0 01-3-3V4.5a3 3 0 116 0v8.25a3 3 0 01-3 3z"
              />
            </svg>
            <p>请在左侧输入单词或句子</p>
          </div>
          <div v-else class="cards-grid">
            <div
              v-for="(word, index) in wordList"
              :key="index"
              class="word-card"
              :class="{
                active: currentWordIndex === index,
                playing: playingIndex === index,
              }"
              @click="handleWordClick(index)"
            >
              <div class="card-content">{{ word }}</div>
              <div v-if="playingIndex === index" class="wave-animation">
                <span></span><span></span><span></span><span></span>
              </div>
            </div>
          </div>
        </div>

        <!-- 评测操作区 -->
        <div class="evaluation-section">
          <div v-if="currentWord" class="current-word-display">
            <span class="label">当前评测：</span>
            <span class="word">{{ currentWord }}</span>
          </div>

          <button
            class="record-btn"
            :class="{
              recording: isRecording,
              connecting: asrStatus === 'connecting',
              error: asrStatus === 'error',
            }"
            :disabled="!currentWord || isEvaluating"
            @mousedown="startRecording"
            @mouseup="stopRecording"
            @mouseleave="isRecording && stopRecording()"
            @touchstart.prevent="startRecording"
            @touchend.prevent="stopRecording"
          >
            <div v-if="asrStatus === 'connecting'" class="btn-spinner"></div>
            <div v-else-if="isRecording" class="recording-content">
              <div class="pulse-ring"></div>
              <svg
                xmlns="http://www.w3.org/2000/svg"
                fill="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  d="M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4zm0 2a2 2 0 0 0-2 2v6a2 2 0 0 0 4 0V5a2 2 0 0 0-2-2zm-1 14.93V20H9v2h6v-2h-2v-2.07A7.001 7.001 0 0 0 19 11h-2a5 5 0 0 1-10 0H5a7.001 7.001 0 0 0 6 6.93z"
                />
              </svg>
              <span>录音中...</span>
            </div>
            <template v-else>
              <svg
                xmlns="http://www.w3.org/2000/svg"
                fill="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  d="M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4zm0 2a2 2 0 0 0-2 2v6a2 2 0 0 0 4 0V5a2 2 0 0 0-2-2zm-1 14.93V20H9v2h6v-2h-2v-2.07A7.001 7.001 0 0 0 19 11h-2a5 5 0 0 1-10 0H5a7.001 7.001 0 0 0 6 6.93z"
                />
              </svg>
              <span>按住跟读评测</span>
            </template>
          </button>

          <!-- 评测结果 -->
          <div v-if="isEvaluating" class="result-loading">
            <div class="loading-spinner"></div>
            <span>评测中...</span>
          </div>

          <div v-else-if="evaluationResult" class="result-section">
            <div class="score-display">
              <div class="score-circle">
                <svg class="score-svg" viewBox="0 0 100 100">
                  <circle cx="50" cy="50" r="45" class="score-bg"></circle>
                  <circle
                    cx="50"
                    cy="50"
                    r="45"
                    class="score-progress"
                    :style="{
                      strokeDashoffset:
                        283 - (283 * evaluationResult.overallScore) / 100,
                    }"
                  ></circle>
                </svg>
                <div class="score-value">
                  {{ evaluationResult.overallScore }}
                </div>
              </div>
              <div class="score-label">综合评分</div>
            </div>

            <div class="detail-scores">
              <div class="detail-item">
                <span class="detail-label">准确度</span>
                <div class="detail-bar">
                  <div
                    class="detail-fill"
                    :style="{ width: evaluationResult.accuracy + '%' }"
                  ></div>
                </div>
                <span class="detail-value">{{
                  evaluationResult.accuracy
                }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">流利度</span>
                <div class="detail-bar">
                  <div
                    class="detail-fill"
                    :style="{ width: evaluationResult.fluency + '%' }"
                  ></div>
                </div>
                <span class="detail-value">{{ evaluationResult.fluency }}</span>
              </div>
            </div>

            <div
              v-if="
                evaluationResult.errors && evaluationResult.errors.length > 0
              "
              class="errors-section"
            >
              <h4>错误标注</h4>
              <div class="errors-list">
                <div
                  v-for="(error, idx) in evaluationResult.errors"
                  :key="idx"
                  class="error-item"
                >
                  <span class="error-word">{{ error.word }}</span>
                  <span class="error-type">{{ error.type }}</span>
                  <span class="error-detail"
                    >预期: {{ error.expected }} | 实际: {{ error.actual }}</span
                  >
                </div>
              </div>
            </div>

            <div
              v-if="evaluationResult.suggestions"
              class="suggestions-section"
            >
              <h4>改进建议</h4>
              <p>{{ evaluationResult.suggestions }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
* {
  box-sizing: border-box;
}

.page-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 2rem;
  min-height: 100vh;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 2rem;
  gap: 1rem;
}

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

.back-btn:hover {
  background: var(--card-bg);
  color: var(--text-primary);
}

.back-btn svg {
  width: 20px;
  height: 20px;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--text-primary);
}

.nav-controls {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.speed-select-wrap {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

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

.speed-select {
  appearance: none;
  -webkit-appearance: none;
  background: var(--card-bg)
    url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23a0a0b8' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E")
    no-repeat right 0.6rem center;
  border: 1px solid var(--card-border);
  color: var(--text-primary);
  padding: 0.5rem 2rem 0.5rem 0.75rem;
  border-radius: 8px;
  font-size: 0.875rem;
  cursor: pointer;
  outline: none;
  min-width: 90px;
  transition: border-color 0.2s;
}

.speed-select:hover {
  border-color: var(--accent-1);
}

.speed-select option {
  background: #1e1e2e;
  color: var(--text-primary);
}

.voice-select-wrap {
  min-width: 180px;
}

.voice-select {
  appearance: none;
  -webkit-appearance: none;
  background: var(--card-bg)
    url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23a0a0b8' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E")
    no-repeat right 0.6rem center;
  border: 1px solid var(--card-border);
  color: var(--text-primary);
  padding: 0.5rem 2rem 0.5rem 0.75rem;
  border-radius: 8px;
  font-size: 0.875rem;
  cursor: pointer;
  outline: none;
  width: 100%;
  transition: border-color 0.2s;
}

.voice-select:hover {
  border-color: var(--accent-1);
}

.voice-select option {
  background: #1e1e2e;
  color: var(--text-primary);
}

/* 主内容区 */
.main-content {
  display: grid;
  grid-template-columns: 350px 1fr;
  gap: 2rem;
  min-height: calc(100vh - 180px);
}

/* 左侧面板 */
.left-panel {
  display: flex;
  flex-direction: column;
}

.input-section {
  background: var(--card-bg);
  border: 1px solid var(--card-border);
  border-radius: 16px;
  padding: 1.5rem;
}

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

.input-textarea {
  width: 100%;
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid var(--card-border);
  border-radius: 12px;
  padding: 1rem;
  color: var(--text-primary);
  font-family: inherit;
  font-size: 1rem;
  line-height: 1.6;
  resize: none;
  outline: none;
  transition: border-color 0.2s;
}

.input-textarea:focus {
  border-color: var(--accent-1);
}

.input-textarea::placeholder {
  color: var(--text-secondary);
}

.input-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 0.75rem;
}

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

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

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

/* 右侧面板 */
.right-panel {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

/* 卡片展示区 */
.cards-section {
  background: var(--card-bg);
  border: 1px solid var(--card-border);
  border-radius: 16px;
  padding: 1.5rem;
  min-height: 300px;
}

.empty-hint {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: var(--text-secondary);
  gap: 1rem;
}

.empty-hint svg {
  width: 48px;
  height: 48px;
  opacity: 0.5;
}

.empty-hint p {
  margin: 0;
  font-size: 1rem;
}

.cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 1rem;
}

.word-card {
  background: rgba(255, 255, 255, 0.03);
  border: 2px solid rgba(255, 255, 255, 0.08);
  border-radius: 12px;
  padding: 1.25rem 1rem;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 80px;
}

.word-card:hover {
  background: rgba(255, 255, 255, 0.06);
  border-color: rgba(99, 102, 241, 0.3);
  transform: translateY(-2px);
}

.word-card.active {
  border-color: var(--accent-1);
  background: rgba(99, 102, 241, 0.1);
}

.word-card.playing {
  border-color: var(--accent-1);
  background: rgba(99, 102, 241, 0.15);
}

.card-content {
  font-size: 1.125rem;
  font-weight: 500;
  color: var(--text-primary);
  text-align: center;
  word-break: break-word;
}

.wave-animation {
  display: flex;
  gap: 3px;
  margin-top: 0.5rem;
  height: 16px;
  align-items: center;
}

.wave-animation span {
  width: 3px;
  background: var(--accent-1);
  border-radius: 2px;
  animation: wave 0.6s infinite alternate;
}

.wave-animation span:nth-child(2) {
  animation-delay: 0.15s;
}

.wave-animation span:nth-child(3) {
  animation-delay: 0.3s;
}

.wave-animation span:nth-child(4) {
  animation-delay: 0.45s;
}

@keyframes wave {
  from {
    height: 6px;
  }
  to {
    height: 16px;
  }
}

/* 评测操作区 */
.evaluation-section {
  background: var(--card-bg);
  border: 1px solid var(--card-border);
  border-radius: 16px;
  padding: 1.5rem;
}

.current-word-display {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 1.5rem;
  padding: 1rem;
  background: rgba(99, 102, 241, 0.1);
  border: 1px solid rgba(99, 102, 241, 0.2);
  border-radius: 12px;
}

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

.current-word-display .word {
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--accent-1);
}

.record-btn {
  width: 100%;
  height: 64px;
  background: linear-gradient(135deg, var(--accent-1), #7c3aed);
  border: none;
  border-radius: 12px;
  color: white;
  font-size: 1.125rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.75rem;
  position: relative;
  overflow: hidden;
}

.record-btn:hover:not(:disabled) {
  transform: scale(1.02);
  box-shadow: 0 8px 24px rgba(99, 102, 241, 0.4);
}

.record-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.record-btn svg {
  width: 24px;
  height: 24px;
}

.record-btn.recording {
  background: linear-gradient(135deg, #ef4444, #dc2626);
}

.recording-content {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  position: relative;
  z-index: 1;
}

.pulse-ring {
  position: absolute;
  inset: -20px;
  border-radius: 12px;
  background: rgba(239, 68, 68, 0.2);
  animation: pulse 1.2s ease-out infinite;
}

@keyframes pulse {
  0% {
    transform: scale(0.9);
    opacity: 0.8;
  }
  70% {
    transform: scale(1.1);
    opacity: 0;
  }
  100% {
    transform: scale(0.9);
    opacity: 0;
  }
}

.record-btn.connecting {
  background: linear-gradient(135deg, #fbbf24, #f59e0b);
}

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

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

/* 结果加载 */
.result-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.75rem;
  margin-top: 1.5rem;
  padding: 2rem;
  color: var(--text-secondary);
}

.loading-spinner {
  width: 24px;
  height: 24px;
  border: 3px solid rgba(99, 102, 241, 0.3);
  border-top-color: var(--accent-1);
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

/* 评测结果 */
.result-section {
  margin-top: 1.5rem;
  animation: slideIn 0.4s ease-out;
}

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

.score-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 1.5rem;
}

.score-circle {
  width: 120px;
  height: 120px;
  position: relative;
}

.score-svg {
  width: 100%;
  height: 100%;
  transform: rotate(-90deg);
}

.score-bg {
  fill: none;
  stroke: rgba(255, 255, 255, 0.1);
  stroke-width: 8;
}

.score-progress {
  fill: none;
  stroke: var(--accent-1);
  stroke-width: 8;
  stroke-linecap: round;
  stroke-dasharray: 283;
  transition: stroke-dashoffset 1s ease-out;
}

.score-value {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 2.5rem;
  font-weight: 700;
  color: var(--text-primary);
}

.score-label {
  margin-top: 0.5rem;
  font-size: 0.875rem;
  color: var(--text-secondary);
}

.detail-scores {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.detail-label {
  min-width: 60px;
  font-size: 0.875rem;
  color: var(--text-secondary);
}

.detail-bar {
  flex: 1;
  height: 8px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  overflow: hidden;
}

.detail-fill {
  height: 100%;
  background: linear-gradient(90deg, var(--accent-1), #8b5cf6);
  border-radius: 4px;
  transition: width 0.6s ease-out;
}

.detail-value {
  min-width: 32px;
  text-align: right;
  font-size: 0.875rem;
  font-weight: 600;
  color: var(--text-primary);
}

.errors-section,
.suggestions-section {
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 12px;
  padding: 1rem;
  margin-bottom: 1rem;
}

.errors-section h4,
.suggestions-section h4 {
  margin: 0 0 0.75rem;
  font-size: 0.875rem;
  font-weight: 600;
  color: var(--text-primary);
}

.errors-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.error-item {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem;
  background: rgba(239, 68, 68, 0.1);
  border-radius: 8px;
}

.error-word {
  font-weight: 600;
  color: #ef4444;
}

.error-type {
  font-size: 0.75rem;
  padding: 0.125rem 0.5rem;
  background: rgba(239, 68, 68, 0.2);
  border-radius: 4px;
  color: #fca5a5;
}

.error-detail {
  font-size: 0.75rem;
  color: var(--text-secondary);
}

.suggestions-section p {
  margin: 0;
  font-size: 0.875rem;
  line-height: 1.6;
  color: var(--text-secondary);
}

/* 响应式 */
@media (max-width: 1024px) {
  .main-content {
    grid-template-columns: 1fr;
  }

  .left-panel {
    order: 1;
  }

  .right-panel {
    order: 2;
  }
}

@media (max-width: 768px) {
  .page-container {
    padding: 0.75rem;
  }

  .nav-bar {
    flex-wrap: wrap;
    gap: 0.75rem;
    margin-bottom: 1rem;
  }

  .nav-title {
    font-size: 1.125rem;
    order: -1;
    width: 100%;
    text-align: center;
    margin-bottom: 0.5rem;
  }

  .back-btn {
    padding: 0.6rem;
    font-size: 0.875rem;
  }

  .back-btn svg {
    width: 18px;
    height: 18px;
  }

  .nav-controls {
    flex: 1;
    display: flex;
    flex-direction: row;
    gap: 0.5rem;
    justify-content: flex-end;
  }

  .speed-select-wrap {
    flex: 0 0 auto;
  }

  .speed-label {
    display: none;
  }

  .speed-select {
    min-width: 80px;
    padding: 0.6rem 1.8rem 0.6rem 0.6rem;
    font-size: 0.875rem;
  }

  .voice-select-wrap {
    flex: 0 0 auto;
    min-width: 120px;
  }

  .voice-select {
    padding: 0.6rem 1.8rem 0.6rem 0.6rem;
    font-size: 0.875rem;
  }

  .input-section,
  .cards-section,
  .evaluation-section {
    padding: 1rem;
  }

  .section-title {
    font-size: 1rem;
    margin-bottom: 0.75rem;
  }

  .input-textarea {
    font-size: 16px; /* 防止iOS自动缩放 */
    padding: 0.875rem;
    line-height: 1.5;
  }

  .cards-grid {
    grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
    gap: 0.75rem;
  }

  .word-card {
    min-height: 70px;
    padding: 1rem 0.75rem;
  }

  .card-content {
    font-size: 1rem;
  }

  .current-word-display {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
    padding: 0.875rem;
  }

  .current-word-display .label {
    font-size: 0.8125rem;
  }

  .current-word-display .word {
    font-size: 1.125rem;
  }

  .record-btn {
    height: 56px;
    font-size: 1rem;
  }

  .record-btn svg {
    width: 20px;
    height: 20px;
  }

  .score-circle {
    width: 100px;
    height: 100px;
  }

  .score-value {
    font-size: 2rem;
  }

  .score-label {
    font-size: 0.8125rem;
  }

  .detail-label {
    min-width: 50px;
    font-size: 0.8125rem;
  }

  .detail-value {
    font-size: 0.8125rem;
  }

  .errors-section h4,
  .suggestions-section h4 {
    font-size: 0.8125rem;
  }

  .error-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .error-word {
    font-size: 0.875rem;
  }

  .suggestions-section p {
    font-size: 0.8125rem;
  }
}

@media (max-width: 480px) {
  .page-container {
    padding: 0.5rem;
  }

  .nav-bar {
    margin-bottom: 0.75rem;
  }

  .back-btn {
    padding: 0.5rem 0.6rem;
    font-size: 0.8125rem;
  }

  .back-btn span {
    display: none;
  }

  .nav-title {
    font-size: 1rem;
  }

  .nav-controls {
    gap: 0.4rem;
  }

  .speed-select {
    min-width: 70px;
    padding: 0.5rem 1.5rem 0.5rem 0.5rem;
    font-size: 0.8125rem;
  }

  .voice-select-wrap {
    min-width: 100px;
  }

  .voice-select {
    padding: 0.5rem 1.5rem 0.5rem 0.5rem;
    font-size: 0.8125rem;
  }

  .input-section,
  .cards-section,
  .evaluation-section {
    padding: 0.75rem;
    border-radius: 12px;
  }

  .section-title {
    font-size: 0.9375rem;
  }

  .input-textarea {
    padding: 0.75rem;
    border-radius: 8px;
  }

  .input-footer {
    margin-top: 0.5rem;
  }

  .word-count {
    font-size: 0.8125rem;
  }

  .clear-btn {
    padding: 0.4rem 0.75rem;
    font-size: 0.8125rem;
  }

  .cards-grid {
    grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
    gap: 0.5rem;
  }

  .word-card {
    min-height: 65px;
    padding: 0.875rem 0.6rem;
    border-radius: 8px;
  }

  .card-content {
    font-size: 0.9375rem;
  }

  .wave-animation {
    height: 14px;
  }

  .wave-animation span {
    width: 2px;
  }

  @keyframes wave {
    from {
      height: 5px;
    }
    to {
      height: 14px;
    }
  }

  .evaluation-section {
    min-height: auto;
  }

  .current-word-display {
    padding: 0.75rem;
  }

  .record-btn {
    height: 52px;
    font-size: 0.9375rem;
    border-radius: 10px;
  }

  .result-loading {
    padding: 1.5rem;
    font-size: 0.875rem;
  }

  .result-section {
    margin-top: 1rem;
  }

  .score-display {
    margin-bottom: 1rem;
  }

  .score-circle {
    width: 90px;
    height: 90px;
  }

  .score-value {
    font-size: 1.75rem;
  }

  .detail-scores {
    gap: 0.75rem;
    margin-bottom: 1rem;
  }

  .detail-item {
    gap: 0.75rem;
  }

  .detail-label {
    min-width: 45px;
    font-size: 0.75rem;
  }

  .detail-bar {
    height: 6px;
  }

  .detail-value {
    min-width: 28px;
    font-size: 0.75rem;
  }

  .errors-section,
  .suggestions-section {
    padding: 0.75rem;
    margin-bottom: 0.75rem;
    border-radius: 8px;
  }

  .errors-section h4,
  .suggestions-section h4 {
    font-size: 0.75rem;
    margin-bottom: 0.5rem;
  }

  .errors-list {
    gap: 0.4rem;
  }

  .error-item {
    padding: 0.4rem;
  }

  .error-word {
    font-size: 0.8125rem;
  }

  .error-type {
    font-size: 0.6875rem;
  }

  .error-detail {
    font-size: 0.6875rem;
  }

  .suggestions-section p {
    font-size: 0.75rem;
    line-height: 1.5;
  }
}

/* 添加触摸优化 */
@media (hover: none) and (pointer: coarse) {
  .word-card {
    -webkit-tap-highlight-color: transparent;
  }

  .word-card:active {
    transform: scale(0.98);
  }

  .record-btn:active:not(:disabled) {
    transform: scale(0.98);
  }

  .back-btn:active {
    transform: scale(0.95);
  }

  .clear-btn:active {
    transform: scale(0.95);
  }
}
</style>
