import { View, Text, Image, Button } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { getVBCourses } from '../../api'
import './index.scss'

export default function CourseIndex() {
  const [courseList, setCourseList] = useState<any[]>([])
  const [loading, setLoading] = useState(true)

  useLoad(() => {
    fetchCourses()
  })

  const fetchCourses = async () => {
    try {
      const res: any = await getVBCourses()
      setCourseList(res.results || res)
    } catch (err) {
      console.error(err)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  const goDetail = (id: number) => {
    Taro.navigateTo({ url: `/pages/courses/detail?id=${id}` })
  }

  if (loading) return <View className='page-container'><Text style={{color:'#fff'}}>Loading...</Text></View>

  return (
    <View className='page-container'>
      <View className='bg-decoration' />
      
      <View className='header'>
        <Text className='title'>VB <Text className='highlight'>COURSES</Text></Text>
        <Text className='desc'>探索 VB 编程课程</Text>
      </View>

      <View className='ar-grid'>
        {courseList.length === 0 ? (
           <View style={{ width: '100%', textAlign: 'center', color: '#666', marginTop: 50 }}>
             <Text>暂无 VB 课程内容</Text>
           </View>
        ) : (
          courseList.map((item) => (
            <View key={item.id} className='ar-card' onClick={() => goDetail(item.id)}>
              <View className='cover-box'>
                {item.cover_image_url ? (
                  <Image src={item.cover_image_url} className='cover-img' mode='aspectFill' />
                ) : (
                  <Text className='placeholder-icon'>VB</Text>
                )}
              </View>
              <View className='content'>
                <Text className='item-title'>{item.title}</Text>
                <Text className='item-desc'>{item.description}</Text>
                <Button className='btn-start' onClick={(e) => { e.stopPropagation(); goDetail(item.id) }}>报名课程</Button>
              </View>
            </View>
          ))
        )}
      </View>
    </View>
  )
}
