<template>
  <view class="lesson">
    <view class="content-area">
      <text class="lesson-title">{{ lesson.title }}</text>
      <view class="lesson-content">
        <text>{{ lesson.content }}</text>
      </view>
      <button class="btn-complete" @tap="markComplete" v-if="!lesson.completed">标记完成</button>
      <text class="completed-text" v-else>✅ 已完成</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { api } from '../../api/index'

const lesson = ref<any>({})

onMounted(async () => {
  const instance = (uni as any).getCurrentInstance()
  const lessonId = Number(instance?.router?.params?.id || '')
  const courseId = Number(instance?.router?.params?.courseId || '')
  try {
    const course: any = await api.courses.detail(courseId)
    for (const ch of course.chapters || []) {
      for (const les of ch.lessons || []) {
        if (les.id === lessonId) {
          lesson.value = { ...les, courseId }
          return
        }
      }
    }
  } catch (e) {
    uni.showToast({ title: '加载失败', icon: 'none' })
  }
})

async function markComplete() {
  try {
    await api.courses.updateProgress(lesson.value.courseId, lesson.value.id, { completed: true })
    lesson.value.completed = true
    uni.showToast({ title: '已完成', icon: 'success' })
  } catch (e) {
    uni.showToast({ title: '操作失败', icon: 'none' })
  }
}
</script>

<style scoped>
.lesson { padding: 30rpx; }
.content-area { background: var(--card); border-radius: 16rpx; padding: 40rpx; }
.lesson-title { font-size: 36rpx; font-weight: bold; display: block; margin-bottom: 30rpx; }
.lesson-content { font-size: 28rpx; color: var(--foreground); line-height: 1.8; }
.btn-complete {
  background: var(--brand); color: var(--card); border-radius: 12rpx; padding: 24rpx;
  font-size: 28rpx; text-align: center; margin-top: 40rpx; border: none;
}
.completed-text { display: block; text-align: center; font-size: 28rpx; color: #52c41a; margin-top: 40rpx; }
</style>
