import React from 'react'
import { api } from '../api/mock'
import { Link } from 'react-router-dom'
import { sfx } from '../utils/audio'

export default function CourseGrid({ query }) {
  const [courses, setCourses] = React.useState([])
  React.useEffect(() => {
    (async () => {
      const list = await api.getCourses()
      const order = { 'Matematika': 0, 'Bahasa Inggris': 1, 'Bahasa Indonesia': 2 }
      list.sort((a, b) => (order[a.title] ?? 99) - (order[b.title] ?? 99))
      setCourses(list)
    })()
  }, [])

  const filtered = courses.filter(c => !query || c.title.toLowerCase().includes(query.toLowerCase()))

  return (
    <section aria-label="Rekomendasi Kelas" className="mt-4">
      <h2 className="heading text-onme-blue text-xl mb-3">
        {query ? `Hasil Pencarian: "${query}"` : 'Kelas Rekomendasi'}
      </h2>
      {filtered.length === 0 && query && (
        <p className="text-gray-500 italic">Tidak ada kelas yang ditemukan.</p>
      )}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        {filtered.map(c => <CourseCard key={c.id} c={c} />)}
      </div>
    </section>
  )
}

function CourseCard({ c }) {
  return (
    <div className="bg-white rounded-2xl border-2 border-onme-softBlue overflow-hidden hover:shadow-lg focus-within:shadow-glow transition-transform duration-200 hover:-translate-y-1">
      <img src={c.thumbnail} alt="thumbnail" className="w-full h-40 object-cover" loading="lazy" />
      <div className="p-3">
        <h3 className="ui font-bold text-lg mb-1">{c.title}</h3>
        <p className="text-sm text-gray-600 mb-2">Level: {c.level} · ⭐ {c.rating}</p>
        <div className="h-2 bg-onme-softBlue/50 rounded-full mb-2">
          <div className="h-2 bg-onme-blue rounded-full" style={{ width: c.progress + '%' }} />
        </div>
        <Link to={`/course/${c.id}`} className="ui inline-flex items-center justify-center w-full rounded-full font-bold py-2 bg-onme-blue text-onme-whiteSoft" onClick={() => sfx.play('click')}>
          {c.progress > 0 ? 'Continue' : 'Start'}
        </Link>
      </div>
    </div>
  )
}
