"use client"

import { useState } from "react"
import { motion, Reorder } from "framer-motion"
import { speak } from "@/lib/speech"
import { GatoMascota } from "@/components/child/gato-mascota"
import type { Exercise } from "@/curriculum/types"

interface Props {
  exercise: Exercise
  onComplete: (correct: boolean) => void
}

export default function EjercicioSecuencia({ exercise, onComplete }: Props) {
  const { content } = exercise
  const sequence = content.sequence || []

  const [items, setItems] = useState(() =>
    [...sequence].sort(() => Math.random() - 0.5),
  )

  const handleReorder = (newOrder: string[]) => {
    setItems(newOrder)
    if (newOrder.every((item, i) => item === sequence[i])) {
      if (content.audioText) speak(content.audioText)
      onComplete(true)
    }
  }

  return (
    <div className="flex flex-col items-center gap-6">
      <GatoMascota mood="coach" message={content.instruction} size="sm" />

      <Reorder.Group
        axis="y"
        values={items}
        onReorder={handleReorder}
        className="flex flex-col gap-3 max-w-xs w-full"
      >
        {items.map((item) => (
          <Reorder.Item
            key={item}
            value={item}
            className="touch-target-lg rounded-2xl px-6 py-4 text-xl font-display font-bold bg-white shadow-md cursor-grab active:cursor-grabbing text-center"
          >
            {item}
          </Reorder.Item>
        ))}
      </Reorder.Group>

      <p className="text-sm text-foreground/40">Arrastrá para ordenar</p>
    </div>
  )
}
