import React from 'react'
import { sfx } from '../utils/audio'
import { reward, toast } from './Toasts'
import { getLS, setLS, KEYS, getQuestionsMap } from '../utils/storage'

export default function CoursePlayer({ course }) {
  const key = `${KEYS.progress}:${course.id}`
  const [progress, setProgress] = React.useState(() => getLS(key, course.progress || 0))
  const [active, setActive] = React.useState(0)
  const modules = (course.modules && Array.isArray(course.modules) && course.modules.length
    ? course.modules
    : Array.from({ length: 5 }).map((_, i) => ({ title: `Bab ${i + 1}`, dur: 6 + i }))
  )
  const xrUrl = course.xrUrl || 'http://localhost/landingpage1/lomba/'
  const playHref = (modules[active] && modules[active].playUrl) || xrUrl

  const prepareQuestionsForXR = () => {
    try {
      if (!course?.id) return
      const key = `${course.id}:mod:${active}`
      const map = getQuestionsMap()
      if (map[key]) {
        localStorage.setItem('customQuestions', JSON.stringify(map[key]))
      }
    } catch { }
  }

  React.useEffect(() => { setLS(key, progress) }, [progress])

  const done = () => { const p = Math.min(100, progress + 20); setProgress(p); toast('+10 XP', 'success'); reward(); sfx.play('success') }

  return (
    <div className="grid lg:grid-cols-3 gap-4">
      <div className="lg:col-span-2 bg-white border-2 border-onme-softBlue rounded-2xl p-4">
        <h3 className="heading text-onme-blue text-xl mb-2">{modules[active].title}</h3>
        {(modules[active].image || true) && (
          <img
            src={modules[active].image || `https://picsum.photos/seed/kkm${active}/800/450`}
            alt={modules[active].title}
            className="w-full aspect-video object-cover rounded-xl mb-3"
          />
        )}
        <p className="ui mb-3">{modules[active].desc || 'Deskripsi materi akan ditampilkan di sini.'}</p>
        <a
          href={playHref}
          target="_blank"
          rel="noopener noreferrer"
          onClick={() => { prepareQuestionsForXR(); sfx.play('success') }}
          className="ui inline-block rounded-full bg-onme-lime text-black font-bold px-6 py-3 mb-3"
        >
          Play
        </a>
      </div>
      <aside className="bg-white border-2 border-onme-softBlue rounded-2xl p-4">
        <h4 className="ui font-bold mb-2">Modul (5–10 menit)</h4>
        <ol className="space-y-2">
          {modules.map((m, i) => (
            <li key={i}>
              <button onClick={() => { setActive(i); sfx.play('click') }} className={`ui w-full text-left px-3 py-2 rounded-lg border ${i === active ? 'bg-onme-blue text-onme-whiteSoft border-onme-blue' : 'bg-white border-onme-softBlue'}`}>{m.title} · {m.dur}m</button>
            </li>
          ))}
        </ol>
        <div className="mt-4">
          <div className="h-2 bg-onme-softBlue/50 rounded-full">
            <div className="h-2 bg-onme-blue rounded-full transition-all" style={{ width: progress + '%' }} />
          </div>
          <p className="ui text-sm mt-1">Progress: {progress}%</p>
        </div>
      </aside>
    </div>
  )
}
