'use client';

import { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import { ArrowLeft, Mic, Volume2, Check, RotateCcw, Star } from 'lucide-react';
import Mascot from '../Mascot';
import DemoBadge from '../DemoBadge';
import { speak } from '@/lib/tts';
import { createStt, isSttSupported, type SttController } from '@/lib/stt';
import { bn } from '@/lib/bn';
import { playCorrect, playWrong } from '@/lib/sound';

const WORDS = [
  { word: 'আম', emoji: '🥭' },
  { word: 'বই', emoji: '📕' },
  { word: 'ফুল', emoji: '🌼' },
  { word: 'মাছ', emoji: '🐟' },
  { word: 'পাখি', emoji: '🐦' },
  { word: 'গাছ', emoji: '🌳' },
  { word: 'চাঁদ', emoji: '🌙' },
  { word: 'হাতি', emoji: '🐘' },
];

function normalise(s: string): string {
  return s.replace(/[\s।,.?!]/g, '').toLowerCase();
}

type Verdict = 'idle' | 'listening' | 'correct' | 'retry';

export default function AiPronounce() {
  const router = useRouter();
  const [index, setIndex] = useState(0);
  const [verdict, setVerdict] = useState<Verdict>('idle');
  const [heard, setHeard] = useState('');
  const [score, setScore] = useState(0);
  const [sttOk, setSttOk] = useState(true);
  const sttRef = useRef<SttController | null>(null);
  const scoredThis = useRef(false);

  const current = WORDS[index];

  useEffect(() => {
    setSttOk(isSttSupported());
  }, []);

  function nextWord() {
    setIndex((i) => (i + 1) % WORDS.length);
    setVerdict('idle');
    setHeard('');
    scoredThis.current = false;
  }

  function listen() {
    if (!sttOk) return;
    setHeard('');
    const ctrl = createStt({
      onResult: (t) => {
        setHeard(t);
        const ok = normalise(t).includes(normalise(current.word)) || normalise(current.word).includes(normalise(t));
        if (ok) {
          playCorrect();
          setVerdict('correct');
          if (!scoredThis.current) {
            scoredThis.current = true;
            setScore((s) => s + 1);
          }
        } else {
          playWrong();
          setVerdict('retry');
        }
      },
      onEnd: () => setVerdict((v) => (v === 'listening' ? 'idle' : v)),
      onError: () => setVerdict('idle'),
    });
    if (ctrl) {
      sttRef.current = ctrl;
      setVerdict('listening');
      ctrl.start();
    }
  }

  return (
    <div className="min-h-dvh pb-24 lg:pb-0 lg:pl-24">
      <header className="sticky top-0 z-30 bg-cream/90 px-4 pb-3 pt-4 backdrop-blur sm:px-6">
        <div className="mx-auto flex max-w-2xl items-center gap-3">
          <button
            onClick={() => router.push('/app/ai')}
            aria-label="ফিরে যাও"
            className="rounded-full p-2 text-ink-soft transition hover:bg-cream-200"
          >
            <ArrowLeft className="h-5 w-5" />
          </button>
          <h1 className="font-heading text-xl font-extrabold text-ink">উচ্চারণ কোচ</h1>
          <span className="ml-auto flex items-center gap-1 rounded-full bg-sun-100 px-3 py-1.5 text-sm font-bold text-sun-600">
            <Star className="h-4 w-4 fill-sun-500 text-sun-500" /> {bn(score)}
          </span>
        </div>
      </header>

      <main className="mx-auto flex max-w-2xl flex-col items-center px-4 pt-4 text-center sm:px-6">
        <div className="flex items-center gap-3 self-stretch">
          <Mascot mood={verdict === 'correct' ? 'happy' : verdict === 'retry' ? 'sad' : 'idle'} size={48} />
          <p className="rounded-2xl bg-white px-4 py-2 text-sm font-medium text-ink-soft shadow-card">
            শব্দটা শুনে, তারপর মাইক চেপে বলো!
          </p>
        </div>

        {!sttOk && (
          <p className="mt-4 rounded-2xl bg-mango-50 px-4 py-3 text-sm text-mango-700">
            এই ব্রাউজারে ভয়েস চেনা যায় না। Chrome দিয়ে চেষ্টা করো।
          </p>
        )}

        {/* word card */}
        <motion.div
          key={current.word}
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          className="mt-6 flex w-full max-w-sm flex-col items-center rounded-4xl bg-white p-8 shadow-card"
        >
          <div className="text-7xl" aria-hidden>
            {current.emoji}
          </div>
          <div className="mt-3 font-heading text-6xl font-extrabold text-ink">{current.word}</div>
          <button
            onClick={() => speak(current.word)}
            className="mt-4 flex items-center gap-2 rounded-full bg-leaf-100 px-4 py-2 text-sm font-bold text-leaf-600 transition active:scale-95"
          >
            <Volume2 className="h-4 w-4" /> শুনে নাও
          </button>
        </motion.div>

        {/* mic */}
        <button
          onClick={listen}
          disabled={!sttOk || verdict === 'listening'}
          className={`mt-6 flex h-20 w-20 items-center justify-center rounded-full text-white shadow-pop transition active:scale-90 disabled:opacity-70 ${
            verdict === 'listening' ? 'animate-pulse bg-mango-500' : 'bg-mango-500'
          }`}
          aria-label="বলো"
        >
          <Mic className="h-9 w-9" />
        </button>
        <p className="mt-2 text-sm text-ink-faint">
          {verdict === 'listening' ? 'শুনছি…' : 'মাইক চেপে বলো'}
        </p>

        {/* feedback */}
        {verdict === 'correct' && (
          <motion.div
            initial={{ opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            className="mt-4 flex items-center gap-2 rounded-2xl bg-leaf-50 px-5 py-3 font-bold text-leaf-700"
          >
            <Check className="h-5 w-5" /> দারুণ বলেছ! 🎉
          </motion.div>
        )}
        {verdict === 'retry' && (
          <motion.div
            initial={{ opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            className="mt-4 rounded-2xl bg-sun-50 px-5 py-3 text-center font-semibold text-sun-600"
          >
            আরেকবার চেষ্টা করো!{heard ? ` (শুনলাম: “${heard}”)` : ''}
          </motion.div>
        )}

        <button
          onClick={nextWord}
          className="mt-6 flex items-center gap-2 rounded-2xl bg-cream-200 px-6 py-3 font-bold text-ink-soft transition active:scale-[0.98]"
        >
          <RotateCcw className="h-5 w-5" /> পরের শব্দ
        </button>
      </main>
    </div>
  );
}
