import React from 'react'
import { sfx } from '../utils/audio'

function genTiles(){
  // 15 pseudo color tiles; can be upgraded later
  const hues = Array.from({length:15}).map((_,i)=> Math.round(360*i/15))
  return hues.map((h,i)=>({ id: 't'+(i+1), color:`hsl(${h},80%,60%)` }))
}

export default function ColorTestD15({ onDone }){
  const [tiles,setTiles] = React.useState(()=> genTiles())
  const [pick,setPick] = React.useState(null)

  const choose = (i)=>{
    if(pick===null){ setPick(i) }
    else {
      const arr = tiles.slice()
      const tmp = arr[pick]; arr[pick]=arr[i]; arr[i]=tmp
      setTiles(arr); setPick(null); sfx.play('click')
    }
  }

  const finish = ()=>{
    const order = tiles.map(t=>t.id)
    onDone?.({ order })
    sfx.play('success')
  }

  return (
    <div className="fixed inset-0 z-50">
      <div className="absolute inset-0 bg-black/40" />
      <div className="absolute inset-0 grid place-items-center p-4">
        <div className="w-full max-w-3xl bg-white border-2 border-onme-softBlue rounded-2xl shadow-xl p-4">
          <h3 className="heading text-onme-blue text-xl mb-2">Tes Farnsworth D15</h3>
          <p className="ui mb-3">Susun 15 keping warna dari kiri ke kanan hingga transisinya halus. Klik dua keping untuk menukar posisinya. Jika sudah, klik Selesai.</p>
          <div className="grid grid-cols-5 sm:grid-cols-8 gap-2 mb-4">
            {tiles.map((t,i)=> (
              <button key={t.id} onClick={()=>choose(i)} className={`h-12 rounded-md border-2 ${pick===i?'border-onme-blue':'border-onme-softBlue'}`} style={{background:t.color}} aria-label={`tile ${i+1}`} />
            ))}
          </div>
          <div className="flex justify-end">
            <button onClick={finish} className="ui rounded-full bg-onme-blue text-onme-whiteSoft px-4 py-2">Selesai</button>
          </div>
        </div>
      </div>
    </div>
  )
}
