<template>
  <div class="textbook-detail">
    <!-- 顶部导航栏 -->
    <SubPageHeader>
      <template #center>
        <span class="header-title">{{ bookTitle }}</span>
      </template>
    </SubPageHeader>

    <!-- 主体内容 -->
    <div class="detail-body">
      <div class="content-panel">

        <!-- 左侧：目录 -->
        <div class="toc-panel" :class="{ 'toc-panel--collapsed': tocCollapsed }">
          <div class="panel-header">
            <span v-if="!tocCollapsed" class="panel-title">目录</span>
            <button class="toc-collapse-btn" :title="tocCollapsed ? '展开目录' : '折叠目录'" @click="toggleToc">
              <img :src="zhankaiIcon" alt="展开目录" />
            </button>
          </div>

          <div class="toc-list">
            <div v-for="unit in units" :key="unit.id" class="unit-item">
              <!-- Unit 标题行 -->
              <button
                class="unit-row"
                :class="{ expanded: unit.expanded }"
                @click="toggleUnit(unit)"
              >
                <span class="unit-name">{{ tocCollapsed ? getShortUnitName(unit.name) : unit.name }}</span>
                <svg
                  class="unit-arrow"
                  :class="{ 'arrow-up': unit.expanded }"
                  viewBox="0 0 24 24"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path d="M6 9l6 6 6-6" stroke="#999" stroke-width="2"
                    stroke-linecap="round" stroke-linejoin="round" />
                </svg>
              </button>

              <!-- Lessons 列表 -->
              <div v-if="unit.expanded" class="lesson-list">
                <button
                  v-for="lesson in unit.lessons"
                  :key="lesson.id"
                  class="lesson-row"
                  :class="{ active: activeLessonId === lesson.id }"
                  @click="selectLesson(lesson)"
                >
                  {{ tocCollapsed ? getShortLessonName(lesson.name) : lesson.name }}
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：练习记录 -->
        <div class="record-panel">
          <div class="panel-header">
            <span class="panel-title">练习记录</span>
            <div class="sort-btns">
              <button
                class="sort-btn"
                :class="{ active: sortBy === 'time' }"
                @click="sortBy = 'time'"
              >按时间</button>
              <button
                class="sort-btn"
                :class="{ active: sortBy === 'accuracy' }"
                @click="sortBy = 'accuracy'"
              >按正确率</button>
            </div>
          </div>

          <div class="record-content">
            <!-- 暂无练习记录 -->
            <LoadingState
              v-if="records.length === 0"
              status="empty"
              empty-text="暂无练习记录"
            />

            <!-- 练习记录列表（有数据时显示） -->
            <div v-else class="record-list" :class="{ 'record-list--wide': tocCollapsed }">
              <PracticeRecordCard
                v-for="record in sortedRecords"
                :key="record.id"
                :record="record"
              />
            </div>
          </div>

          <div class="record-footer">
            <button
              class="lx-btn lx-btn--lg lx-btn--primary"
              type="button"
              @click="handleStartPractice"
            >
              开始练习
            </button>
          </div>
        </div>

      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRoute } from 'vue-router'
import SubPageHeader from '@/components/layout/SubPageHeader.vue'
import LoadingState from '@/components/loading/LoadingState.vue'
import zhankaiIcon from '@/assets/subjects/zhankai.svg'
import PracticeRecordCard, { type PracticeRecord } from './components/PracticeRecordCard.vue'

const route = useRoute()

// ---- 书本标题 ----
const bookName = computed(() => String(route.query.name || ''))
const bookSubtitle = computed(() => String(route.query.subtitle || ''))
const bookTitle = computed(() =>
  bookName.value && bookSubtitle.value
    ? `${bookName.value}${bookSubtitle.value}`
    : bookName.value || '教材详情',
)

// ---- 目录数据 ----
interface Lesson {
  id: number
  name: string
}
interface Unit {
  id: number
  name: string
  expanded: boolean
  lessons: Lesson[]
}

const units = ref<Unit[]>([
  {
    id: 1,
    name: 'Unit 1 New school, new beginning!',
    expanded: true,
    lessons: [
      { id: 101, name: 'Lesson 1 Hello!' },
      { id: 102, name: 'Lesson 2 Let me show you around!' },
      { id: 103, name: 'Lesson 3 Look at the photo!' },
    ],
  },
  {
    id: 2,
    name: 'Unit 2 Learning English is fun!',
    expanded: false,
    lessons: [
      { id: 201, name: 'Lesson 4 I love English!' },
      { id: 202, name: 'Lesson 5 My English book' },
      { id: 203, name: 'Lesson 6 Lets sing a song!' },
    ],
  },
  {
    id: 3,
    name: 'Unit 3 All about me',
    expanded: false,
    lessons: [
      { id: 301, name: 'Lesson 7 My family' },
      { id: 302, name: 'Lesson 8 I have a pet' },
      { id: 303, name: 'Lesson 9 Review' },
    ],
  },
])

const activeLessonId = ref<number>(101)

// ---- 目录折叠 ----
const tocCollapsed = ref(false)

function toggleToc() {
  tocCollapsed.value = !tocCollapsed.value
}

/** 缩写 Unit 名称：取前两个单词，如 "Unit 1 New school..." → "Unit 1" */
function getShortUnitName(name: string): string {
  const match = name.match(/^(\S+\s+\d+)/)
  return match ? match[1] : name
}

/** 缩写 Lesson 名称：如 "Lesson 1 Hello!" → "Les.1" */
function getShortLessonName(name: string): string {
  const match = name.match(/^Lesson\s+(\d+)/i)
  return match ? `Les.${match[1]}` : name
}

function toggleUnit(unit: Unit) {
  unit.expanded = !unit.expanded
}

function collapseAll() {
  units.value.forEach((u: Unit) => (u.expanded = false))
}

function selectLesson(lesson: Lesson) {
  activeLessonId.value = lesson.id
}

// ---- 练习记录 ----
const commonTags = [
  { label: '英语', type: 'blue' },
  { label: '单选题', type: 'blue' },
  { label: '中等', type: 'orange' },
]

const records = ref<PracticeRecord[]>([
  { id: 1, title: 'There is no ______ trying to pers...', count: 1, accuracy: 100, tags: commonTags, time: '今天 10:30' },
  { id: 2, title: 'There is no ______ trying to pers...', count: 5, accuracy: 60, tags: commonTags, time: '昨天 10:30' },
  { id: 3, title: 'There is no ______ trying to pers...', count: 1, accuracy: 0, tags: commonTags, time: '04/24 10:30' },
  { id: 4, title: 'There is no ______ trying to pers...', count: 2, accuracy: 50, tags: commonTags, time: '04/24 10:30' },
  { id: 5, title: 'There is no ______ trying to pers...', count: 1, accuracy: 100, tags: commonTags, time: '今天 10:30' },
  { id: 6, title: 'There is no ______ trying to pers...', count: 5, accuracy: 60, tags: commonTags, time: '昨天 10:30' },
  { id: 7, title: 'There is no ______ trying to pers...', count: 3, accuracy: 33, tags: commonTags, time: '04/23 09:00' },
  { id: 8, title: 'There is no ______ trying to pers...', count: 4, accuracy: 75, tags: commonTags, time: '04/22 15:00' },
])

const sortBy = ref<'time' | 'accuracy'>('time')

const sortedRecords = computed(() => {
  const list = [...records.value]
  if (sortBy.value === 'accuracy') {
    list.sort((a, b) => b.accuracy - a.accuracy)
  }
  return list
})

function handleStartPractice() {
  // TODO: 跳转到练习页
}
</script>

<style scoped lang="scss">
@use '@/styles/variate.scss' as *;

.textbook-detail {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
}

// 顶部标题
.header-title {
  font-size: var(--font-size-title-s);
  color: var(--color-text-title);
}

// 主体
.detail-body {
  flex: 1;
  min-height: 0;
  padding: 0 64px 32px;
  overflow: hidden;
  display: flex;
}

.content-panel {
  width: 100%;
  max-width: 1792px;
  margin: 0 auto;
  display: flex;
  gap: 0;
  background: var(--color-bg-1);
  border: 2px solid rgba(255, 255, 255, 0.7);
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06);
}

// ---- 公共面板头部 ----
.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 28px 32px 20px;
  flex-shrink: 0;
//   border-bottom: 1.5px solid rgba(0, 0, 0, 0.06);
}

.panel-title {
  font-size: var(--font-size-body);
  font-weight: var(--font-weight-medium);
  color: var(--color-text-title);
}

// ---- 左侧目录 ----
.toc-panel {
  width: 700px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  border-right: 1.5px solid #fff;
  overflow: hidden;
  background: #F5F7FA;
  border-radius: 20px;
  transition: width 0.3s ease;

  &--collapsed {
    width: 174px;

    .panel-header {
      justify-content: center;
      padding: 28px 16px 20px;
    }

    .unit-name {
      font-size: 22px;
    }

    .unit-row {
      padding: 14px 20px;
    }

    .lesson-row {
      padding: 12px 20px 12px 28px;
      font-size: 20px;
    }
  }
}

.toc-collapse-btn {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: transparent;
  border: none;
  cursor: pointer;
  border-radius: 6px;
  transition: background 0.2s;

  svg {
    width: 22px;
    height: 22px;
  }

  &:hover {
    background: rgba(0, 0, 0, 0.05);
  }
}

.toc-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px 0;
  scrollbar-width: none;

  &::-webkit-scrollbar {
    display: none;
  }
}

.unit-item {
  display: flex;
  flex-direction: column;
}

.unit-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 32px;
  background: transparent;
  border: none;
  cursor: pointer;
  text-align: left;
  transition: background 0.15s;

  &:hover {
    background: rgba(0, 0, 0, 0.03);
  }
}

.unit-name {
  font-size: var(--font-size-body-s);
  font-weight: var(--font-weight-medium);
  color: var(--color-text-primary);
  line-height: 1.4;
  flex: 1;
  padding-right: 12px;
}

.unit-arrow {
  width: 20px;
  height: 20px;
  flex-shrink: 0;
  transition: transform 0.2s;

  &.arrow-up {
    transform: rotate(180deg);
  }
}

.lesson-list {
  display: flex;
  flex-direction: column;
}

.lesson-row {
  padding: 14px 32px 14px 40px;
  background: transparent;
  border: none;
  border-left: 3px solid transparent;
  cursor: pointer;
  text-align: left;
  font-size: var(--font-size-caption);
  color: var(--color-text-tertiary);
  transition: background 0.15s, color 0.15s, border-color 0.15s;

  &:hover {
    background: var(--color-brand-10);
    color: var(--color-text-secondary);
  }

  &.active {
    color: var(--color-text-brand);
    border-left-color: var(--color-text-brand);
    background: var(--color-brand-10);
  }
}

// ---- 右侧练习记录 ----
.record-panel {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sort-btns {
  display: flex;
  align-items: center;
  background: #EBEBEB;
  border-radius: 99px;
  padding: 4px;
  gap: 0;
}

.sort-btn {
  padding: 8px 28px;
  border-radius: 99px;
  border: none;
  background: transparent;
  font-size: var(--font-size-caption);
  color: var(--color-text-secondary);
  cursor: pointer;
  transition: background 0.2s, color 0.2s, box-shadow 0.2s;

  &:hover {
    color: var(--color-text-primary);
  }

  &.active {
    background: var(--color-bg-1);
    color: var(--color-text-primary);
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.12);
  }
}

.record-content {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  scrollbar-width: none;

  &::-webkit-scrollbar {
    display: none;
  }
}

.record-list {
  padding: 24px 28px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  align-content: start;

  &--wide {
    grid-template-columns: repeat(3, 1fr);
  }
}

.record-footer {
  padding: 24px 32px;
  display: flex;
  justify-content: center;
  flex-shrink: 0;
//   border-top: 1.5px solid rgba(0, 0, 0, 0.04);
}

</style>
