'use client'

import React, { useState, useRef } from 'react';
import Link from 'next/link';
import { motion, AnimatePresence } from 'framer-motion';
import {
  ArrowRight,
  AudioLines,
  Check,
  ChevronRight,
  Ear,
  GraduationCap,
  Loader2,
  MessageCircle,
  Mic,
  RefreshCw,
  Search,
  Star,
  Target,
  Volume2,
  X,
} from 'lucide-react';
import { useAuth } from '@/lib/AuthContext';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { getApiPath } from '@/lib/basePath';
import CVHeader from '@/components/layout/CVHeader';
import CVFooter from '@/components/layout/CVFooter';
import ToolAccessGate from '@/components/tools/ToolAccessGate';
import OralDrillSeoSections from './OralDrillSeoSections';
import { oralDrillJsonLd } from './oralDrillSeoData';

const IPA_FONT_STACK = '"Noto Sans IPA","Doulos SIL","Charis SIL","Segoe UI","Arial Unicode MS",sans-serif';
const DICTIONARY_API = getApiPath('/api/oral-drill/dictionary');
const ANALYZE_API = getApiPath('/api/oral-drill/analyze');
const ORAL_DRILL_PLATFORM = 'tools';

const IPA_MOJIBAKE_MAP = {
  'É™': 'ə',
  'É›': 'ɛ',
  'ÉœË': 'ɜː',
  'É‘': 'ɒ',
};

function fixIpaMojibake(text) {
  let output = String(text || '');
  Object.entries(IPA_MOJIBAKE_MAP).forEach(([bad, good]) => {
    output = output.split(bad).join(good);
  });
  return output.trim();
}

function safeJsonParse(value) {
  if (!value) return null;
  if (typeof value !== 'string') return value;
  const text = value.trim();
  if (!text) return null;
  try {
    return JSON.parse(text);
  } catch (error) {
    return null;
  }
}

function parseJsonDeep(value, maxDepth = 2) {
  let current = value;
  for (let i = 0; i < maxDepth; i += 1) {
    if (typeof current !== 'string') break;
    const parsed = safeJsonParse(current);
    if (parsed === null) break;
    current = parsed;
  }
  return current;
}

function extractAnswerPayload(value) {
  const parsed = parseJsonDeep(value, 2);
  if (parsed && typeof parsed === 'object' && !Array.isArray(parsed) && 'answer' in parsed) {
    return parseJsonDeep(parsed.answer, 2);
  }
  return parsed;
}

function normalizeDefinitions(value) {
  if (!value) return [];
  if (Array.isArray(value)) return value.filter(Boolean);
  if (typeof value === 'string') {
    return value
      .split(/\n+/)
      .map((line) => line.trim())
      .filter(Boolean);
  }
  if (typeof value === 'object') return [value];
  return [];
}

function normalizeSynonyms(value) {
  if (!value) return '';
  if (Array.isArray(value)) return value.filter(Boolean).join(', ');
  if (typeof value === 'object') {
    return Object.values(value)
      .flatMap((entry) => (Array.isArray(entry) ? entry : [entry]))
      .map((entry) => String(entry || '').trim())
      .filter(Boolean)
      .join(', ');
  }
  return String(value || '').trim();
}

function normalizePhonemes(value) {
  if (!value) return [];
  let list = [];
  if (Array.isArray(value)) {
    list = value
      .map((item) => {
        if (typeof item === 'string') return { symbol: item };
        if (item && typeof item === 'object') {
          return { symbol: item.symbol || item.sound || item.phoneme || '' };
        }
        return null;
      })
      .filter(Boolean);
  } else if (typeof value === 'string') {
    list = value
      .split(/[\s,|/]+/)
      .map((item) => item.trim())
      .filter(Boolean)
      .map((symbol) => ({ symbol }));
  }

  return list
    .map((item) => ({
      symbol: fixIpaMojibake(item.symbol),
      correct: null,
    }))
    .filter((item) => item.symbol);
}

function hasRealExample(value) {
  const text = String(value || '').trim();
  return text && text.toLowerCase() !== 'example not available.';
}

function normalizeWordData(raw, fallbackWord) {
  const payload = extractAnswerPayload(raw) || {};
  const word = String(payload.word || fallbackWord || '').trim();
  return {
    word,
    phonetic: fixIpaMojibake(payload.phonetic || payload.ipa || ''),
    definition: normalizeDefinitions(payload.definition || payload.definitions),
    synonyms: normalizeSynonyms(payload.synonyms),
    example: String(payload.example || payload.examples || '').trim(),
    phonemes: normalizePhonemes(payload.phonemes),
  };
}

function normalizeScore(score) {
  const n = Number(score);
  if (!Number.isFinite(n)) return null;
  if (n <= 1) return Math.round(n * 100);
  return Math.round(n);
}

function normalizePhonemeToken(token) {
  return String(token || '')
    .replace(/[\/\[\]\(\)\{\}]/g, '')
    .replace(/[ˈˌ]/g, '')
    .trim()
    .toLowerCase();
}

function tokenizeIpa(ipa) {
  const cleaned = normalizePhonemeToken(ipa);
  if (!cleaned) return [];
  if (cleaned.indexOf(' ') !== -1) {
    return cleaned.split(/\s+/).filter(Boolean);
  }
  const combos = ['oʊ', 'aɪ', 'eɪ', 'ɔɪ', 'aʊ', 'ju', 'tʃ', 'dʒ', 'ər', 'ɚ', 'iː', 'uː', 'ɔː'];
  const tokens = [];
  let i = 0;
  while (i < cleaned.length) {
    let matched = '';
    for (let c = 0; c < combos.length; c += 1) {
      const combo = combos[c];
      if (cleaned.substr(i, combo.length) === combo) {
        matched = combo;
        break;
      }
    }
    if (matched) {
      tokens.push(matched);
      i += matched.length;
      continue;
    }
    tokens.push(cleaned.charAt(i));
    i += 1;
  }
  return tokens.filter(Boolean);
}

function getStringFromKeys(obj, keys) {
  if (!obj || typeof obj !== 'object') return '';
  for (let i = 0; i < keys.length; i += 1) {
    const value = obj[keys[i]];
    if (typeof value === 'string' && value.trim() !== '') return value.trim();
  }
  return '';
}

function getNumberFromKeys(obj, keys) {
  if (!obj || typeof obj !== 'object') return null;
  for (let i = 0; i < keys.length; i += 1) {
    const value = Number(obj[keys[i]]);
    if (Number.isFinite(value)) return value;
  }
  return null;
}

function parsePhonemeItem(item) {
  if (!item) return null;
  if (typeof item === 'string') {
    const token = normalizePhonemeToken(item);
    if (!token) return null;
    return { token, correct: true };
  }
  if (typeof item !== 'object') return null;

  const target = getStringFromKeys(item, [
    'phoneme', 'phone', 'symbol', 'target', 'expected', 'expected_ipa', 'ipa', 'text',
  ]);
  const spoken = getStringFromKeys(item, [
    'spoken', 'actual', 'recognized', 'you_said', 'predicted', 'response',
  ]);
  const token = normalizePhonemeToken(target || spoken);
  if (!token) return null;

  let correct = null;
  if (typeof item.correct === 'boolean') {
    correct = item.correct;
  } else if (typeof item.is_correct === 'boolean') {
    correct = item.is_correct;
  } else {
    const score = getNumberFromKeys(item, [
      'score', 'accuracy', 'quality', 'pronunciation', 'pronunciation_score', 'phoneme_score',
    ]);
    if (score !== null) {
      correct = normalizeScore(score) >= 70;
    }
  }

  return { token, correct: correct === null ? true : correct };
}

function findPhonemeList(node, depth = 0) {
  if (depth > 10 || !node) return [];

  if (Array.isArray(node)) {
    const parsed = node.map(parsePhonemeItem).filter(Boolean);
    if (parsed.length >= 2) return parsed;
    for (let i = 0; i < node.length; i += 1) {
      const nested = findPhonemeList(node[i], depth + 1);
      if (nested.length >= 2) return nested;
    }
    return [];
  }

  if (typeof node === 'object') {
    const directKeys = ['phonemes', 'phones', 'phone_scores', 'phoneme_scores', 'phone_details', 'phoneme_details'];
    for (let i = 0; i < directKeys.length; i += 1) {
      const direct = findPhonemeList(node[directKeys[i]], depth + 1);
      if (direct.length >= 2) return direct;
    }
    for (const key of Object.keys(node)) {
      const nested = findPhonemeList(node[key], depth + 1);
      if (nested.length >= 2) return nested;
    }
  }

  return [];
}

function buildPhonemeFallback(expectedIpa, spokenIpa, score) {
  const expected = tokenizeIpa(expectedIpa);
  const spoken = tokenizeIpa(spokenIpa);
  const scoreOk = normalizeScore(score);
  if (expected.length === 0 && spoken.length === 0) return [];
  const base = expected.length > 0 ? expected : spoken;
  return base.map((token, idx) => {
    const expectedToken = expected[idx] || token;
    const spokenToken = spoken[idx] || '';
    let correct = true;
    if (spoken.length > 0) {
      correct = normalizePhonemeToken(expectedToken) === normalizePhonemeToken(spokenToken || expectedToken);
    } else if (scoreOk !== null) {
      correct = scoreOk >= 70;
    }
    return { token: expectedToken, correct };
  });
}

async function postForm(url, formData) {
  const response = await fetch(url, { method: 'POST', body: formData });
  let data = {};
  try {
    data = await response.json();
  } catch (err) {
    data = { status: 'error', message: 'Invalid response.' };
  }
  return { ok: response.ok, status: response.status, data };
}

function getAudioExtension(type) {
  const blobType = String(type || '').toLowerCase();
  if (blobType.includes('ogg') || blobType.includes('opus')) return 'ogg';
  if (blobType.includes('wav')) return 'wav';
  if (blobType.includes('mpeg') || blobType.includes('mp3')) return 'mp3';
  if (blobType.includes('mp4') || blobType.includes('m4a')) return 'mp4';
  return 'webm';
}

export default function OralDrill({ workspaceOnly = false }) {
  const { user } = useAuth();
  const [searchTerm, setSearchTerm] = useState('');
  const [currentWord, setCurrentWord] = useState(null);
  const [step, setStep] = useState(1);
  const [isRecording, setIsRecording] = useState(false);
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [showResults, setShowResults] = useState(false);
  const [score, setScore] = useState(null);
  const [attemptCount, setAttemptCount] = useState(0);
  const [showThankYou, setShowThankYou] = useState(false);
  const [isLoadingWord, setIsLoadingWord] = useState(false);
  const [audioBlob, setAudioBlob] = useState(null);
  const [searchMessage, setSearchMessage] = useState('');
  const [analysisMessage, setAnalysisMessage] = useState('');
  const [dictionaryRaw, setDictionaryRaw] = useState(null);
  const [dictionaryAudioUk, setDictionaryAudioUk] = useState('');
  
  const mediaRecorderRef = useRef(null);
  const audioChunksRef = useRef([]);
  const listenAudioRef = useRef(null);

  const handleSearch = async () => {
    if (!searchTerm.trim()) return;

    setIsLoadingWord(true);
    setSearchMessage('');
    setAnalysisMessage('');
    try {
      const fd = new FormData();
      fd.append('word', searchTerm.trim());
      const response = await postForm(DICTIONARY_API, fd);

      if (response.status === 401) {
        setSearchMessage('Oral Drill is temporarily unavailable. Please try again.');
        return;
      }

      if (!response.ok || response.data.status !== 'ok') {
        setSearchMessage(response.data.message || 'Word not found.');
        return;
      }

      const data = response.data || {};
      const definitions = Array.isArray(data.definitions)
        ? data.definitions.map((item) => {
            if (typeof item === 'string') return item;
            if (item && typeof item === 'object') {
              return {
                part_of_speech: item.partOfSpeech || item.part_of_speech || '',
                definition: item.definition || '',
              };
            }
            return '';
          }).filter(Boolean)
        : [];

      const normalized = {
        word: data.word || searchTerm.trim(),
        phonetic: fixIpaMojibake(data.ipa || ''),
        definition: definitions,
        synonyms: Array.isArray(data.synonyms) ? data.synonyms.join(', ') : (data.synonyms || ''),
        example: data.example || '',
        phonemes: [],
      };

      setCurrentWord(normalized);
      setDictionaryRaw(data.raw || data);
      setDictionaryAudioUk(typeof data.audio_uk === 'string' ? data.audio_uk : '');
      setStep(1);
      setShowResults(false);
      setScore(null);
      setAnalysisMessage('');
    } catch (error) {
      console.error('Error fetching word:', error);
      setSearchMessage('Failed to fetch word data. Please try again.');
    } finally {
      setIsLoadingWord(false);
    }
  };

  const handleListen = () => {
    if (!currentWord?.word) {
      setSearchMessage('Search a word first before listening.');
      return;
    }

    const stopCurrentAudio = () => {
      if (!listenAudioRef.current) return;
      try {
        listenAudioRef.current.pause();
        listenAudioRef.current.currentTime = 0;
      } catch (err) {
        // ignore
      }
      listenAudioRef.current = null;
    };

    const speakWithBrowser = () => {
      if (!('speechSynthesis' in window)) {
        setSearchMessage('Text-to-speech not supported in this browser.');
        return;
      }
      window.speechSynthesis.cancel();
      const utterance = new SpeechSynthesisUtterance(currentWord.word);
      utterance.lang = 'en-GB';
      utterance.rate = 0.95;
      window.speechSynthesis.speak(utterance);
    };

    stopCurrentAudio();

    if (dictionaryAudioUk) {
      try {
        const audio = new Audio(dictionaryAudioUk);
        listenAudioRef.current = audio;
        audio.addEventListener('ended', () => {
          listenAudioRef.current = null;
        }, { once: true });
        audio.addEventListener('error', () => {
          listenAudioRef.current = null;
          speakWithBrowser();
        }, { once: true });
        const playPromise = audio.play();
        if (playPromise && typeof playPromise.catch === 'function') {
          playPromise.catch(() => {
            listenAudioRef.current = null;
            speakWithBrowser();
          });
        }
        return;
      } catch (err) {
        listenAudioRef.current = null;
      }
    }

    speakWithBrowser();
  };

  const handleRecord = async () => {
    if (isRecording) {
      // Stop recording
      if (mediaRecorderRef.current && mediaRecorderRef.current.state === 'recording') {
        mediaRecorderRef.current.stop();
      }
      return;
    }

    // Start recording
    try {
      if (!currentWord?.word) {
        setAnalysisMessage('Search a word first.');
        return;
      }
      setAnalysisMessage('');
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      const mediaRecorder = new MediaRecorder(stream);
      mediaRecorderRef.current = mediaRecorder;
      audioChunksRef.current = [];

      mediaRecorder.ondataavailable = (event) => {
        if (event.data.size > 0) {
          audioChunksRef.current.push(event.data);
        }
      };

      mediaRecorder.onstop = async () => {
        const mimeType = mediaRecorderRef.current?.mimeType || 'audio/webm';
        const audioBlob = new Blob(audioChunksRef.current, { type: mimeType });
        setAudioBlob(audioBlob);
        setIsRecording(false);
        
        // Stop all tracks
        stream.getTracks().forEach(track => track.stop());
        
        // Analyze pronunciation
        await analyzePronunciation(audioBlob);
      };

      mediaRecorder.start();
      setIsRecording(true);

      // Auto-stop after 3 seconds
      setTimeout(() => {
        if (mediaRecorderRef.current && mediaRecorderRef.current.state === 'recording') {
          mediaRecorderRef.current.stop();
          setIsRecording(false);
        }
      }, 3000);

    } catch (error) {
      console.error('Error accessing microphone:', error);
      alert('Could not access microphone. Please grant permission and try again.');
    }
  };

  const analyzePronunciation = async (audioBlob) => {
    setIsAnalyzing(true);
    setAnalysisMessage('');
    setShowResults(false);

    try {
      if (!currentWord?.word) {
        setAnalysisMessage('Search a word first.');
        return;
      }

      const fd = new FormData();
      fd.append('word', currentWord.word);
      fd.append('platform', ORAL_DRILL_PLATFORM);
      fd.append('userId', user?.id ? String(user.id) : '');
      fd.append('dictionary_response', JSON.stringify(dictionaryRaw || {}));
      const extension = getAudioExtension(audioBlob?.type);
      fd.append('audio', audioBlob, `oral-drill.${extension}`);

      const response = await postForm(ANALYZE_API, fd);

      if (response.status === 401) {
        setAnalysisMessage('Pronunciation analysis is temporarily unavailable. Please try again.');
        return;
      }

      if (!response.ok || response.data.status !== 'ok') {
        setAnalysisMessage(response.data.message || 'Speech analysis failed.');
        return;
      }

      const data = response.data || {};
      const scoreValue = normalizeScore(data.score);
      const expectedIpa = currentWord.phonetic || '';
      const spokenIpa = data.you_said_ipa || '';

      let phonemeRows = findPhonemeList(data.response || {}, 0);
      if (!phonemeRows || phonemeRows.length === 0) {
        phonemeRows = buildPhonemeFallback(expectedIpa, spokenIpa, scoreValue);
      }

      const updatedPhonemes = phonemeRows.map((row) => ({
        symbol: row.token,
        correct: row.correct !== false,
      }));

      setCurrentWord((prev) => ({
        ...prev,
        phonemes: updatedPhonemes,
      }));

      if (scoreValue !== null) {
        setScore(scoreValue);
      }
      setShowResults(true);

      const newAttemptCount = attemptCount + 1;
      setAttemptCount(newAttemptCount);
      if (newAttemptCount >= 3) {
        setTimeout(() => {
          setShowThankYou(true);
        }, 2000);
      }
    } catch (error) {
      console.error('Error analyzing pronunciation:', error);
      setAnalysisMessage('Failed to analyze pronunciation. Please try again.');
    } finally {
      setIsAnalyzing(false);
    }
  };

  return (
    <>
      {!workspaceOnly && (
        <>
          <script
            type="application/ld+json"
            dangerouslySetInnerHTML={{ __html: JSON.stringify(oralDrillJsonLd).replace(/</g, '\\u003c') }}
          />
          <CVHeader showPromotion={false} />
        </>
      )}
      <main className={`min-h-screen overflow-x-hidden text-[#380F17] ${workspaceOnly ? 'bg-[#F6EEE8]' : 'bg-[#FAF5F0]'}`}>
        {!workspaceOnly && (
        <section className="relative overflow-hidden bg-[#380F17] text-white">
          <div className="absolute inset-y-0 right-0 w-1/3 border-l border-white/10 bg-[#4A1429]" aria-hidden="true" />
          <div className="relative mx-auto grid max-w-6xl gap-8 px-5 py-12 sm:px-6 lg:grid-cols-[1.12fr_0.88fr] lg:px-8 lg:py-16">
            <div className="max-w-3xl">
              <nav aria-label="Breadcrumb" className="mb-8 flex flex-wrap items-center gap-2 text-sm text-white/70">
                <Link href="/" className="transition-colors hover:text-white">Home</Link>
                <ChevronRight className="h-4 w-4" aria-hidden="true" />
                <Link href="/tools" className="transition-colors hover:text-white">Veritas Tools</Link>
                <ChevronRight className="h-4 w-4" aria-hidden="true" />
                <span className="text-[#F2D77F]">Oral Drill</span>
              </nav>
              <p className="mb-5 inline-flex items-center gap-2 rounded-full border border-[#D4AF37]/60 bg-white/5 px-4 py-2 text-xs font-extrabold uppercase tracking-[0.2em] text-[#F2D77F]">
                <AudioLines className="h-4 w-4" aria-hidden="true" />
                Listen · Repeat · Review
              </p>
              <h1 className="max-w-4xl text-3xl font-black leading-[1.1] tracking-tight sm:text-4xl lg:text-5xl">
                English Pronunciation Practice Online – Oral Drill
              </h1>
              <p className="mt-5 max-w-2xl text-base leading-7 text-white/80 sm:text-lg">
                Practise difficult English words through focused listening, repetition and phoneme-level feedback. Build clearer, more confident speech one word at a time.
              </p>
              <div className="mt-8 flex flex-col gap-3 sm:flex-row">
                <Link
                  href="/tools-dashboard/oral-drill"
                  className="inline-flex min-h-12 items-center justify-center gap-2 rounded-xl bg-[#D4AF37] px-6 py-3 text-sm font-black text-[#380F17] transition-colors hover:bg-[#E2C45E] sm:text-base"
                >
                  Start Pronunciation Practice
                  <ArrowRight className="h-5 w-5" aria-hidden="true" />
                </Link>
                <Link
                  href="/tools/accent-enhancer"
                  className="inline-flex min-h-12 items-center justify-center gap-2 rounded-xl border border-white/35 px-6 py-3 text-sm font-bold text-white transition-colors hover:bg-white/10 sm:text-base"
                >
                  Explore the 44 English Sounds
                </Link>
              </div>
            </div>

            <div className="grid content-center gap-4 sm:grid-cols-2" aria-label="Oral Drill benefits">
              {[
                [Ear, 'Hear the model', 'Listen closely before you speak.'],
                [Mic, 'Record your word', 'Use your microphone for a short attempt.'],
                [Target, 'Review the sounds', 'See which phonemes need more attention.'],
                [RefreshCw, 'Repeat with purpose', 'Adjust and try the word again.'],
              ].map(([Icon, title, text]) => (
                <div key={title} className="rounded-2xl border border-white/15 bg-white/5 p-4 backdrop-blur-sm">
                  <div className="mb-3 flex h-10 w-10 items-center justify-center rounded-xl bg-[#D4AF37] text-[#380F17]">
                    <Icon className="h-5 w-5" aria-hidden="true" />
                  </div>
                  <h2 className="text-base font-black">{title}</h2>
                  <p className="mt-1 text-sm leading-6 text-white/70">{text}</p>
                </div>
              ))}
            </div>
          </div>
        </section>
        )}

      {workspaceOnly && (
      <section id="oral-drill-practice" className="scroll-mt-8 border-b border-[#E7DCD5] bg-[#F6EEE8]">
      <div className="mx-auto max-w-5xl px-5 py-10 sm:px-6 lg:px-8 lg:py-14">
        <div className="mx-auto mb-7 max-w-3xl text-center">
          <p className="text-xs font-extrabold uppercase tracking-[0.2em] text-[#9A7417]">Free pronunciation tool</p>
          <h2 className="mt-3 text-2xl font-black tracking-tight text-[#380F17] sm:text-3xl">
            Practise Difficult English Words One at a Time
          </h2>
          <p className="mt-3 text-base leading-7 text-[#755661]">
            Search for a word, listen to the model and record your own pronunciation. Focus on clear, intelligible speech rather than trying to erase your accent.
          </p>
        </div>
        <ToolAccessGate toolKey="pronunciation-drill" toolName="Oral Drill" limit={10}>
          <>
        {/* Search Section */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="mb-8"
        >
          <div className="rounded-2xl border border-[#E5DDD5] bg-white p-6 shadow-md">
            <h2 className="mb-4 flex items-center justify-center gap-2 text-center text-xl font-bold text-[#4A1429]">
              Type the word you&apos;d like to practice!
            </h2>
            <div className="flex max-w-2xl flex-col gap-4 mx-auto sm:flex-row">
              <Input
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                placeholder="Search a word you want to learn"
                className="h-14 flex-1 rounded-lg border-2 border-[#E5DDD5] bg-white px-5 text-base focus:border-[#D4A853]"
              />
              <Button
                onClick={handleSearch}
                disabled={isLoadingWord}
                className="h-14 w-full rounded-lg bg-[#4A1429] px-7 text-base font-bold text-white shadow-md hover:bg-[#3A1020] disabled:opacity-50 sm:w-auto"
              >
                {isLoadingWord ? (
                  <>
                    <Loader2 className="mr-2 h-5 w-5 animate-spin" aria-hidden="true" />
                    Loading...
                  </>
                ) : (
                  <>
                    <Search className="w-5 h-5 mr-2" />
                    Search
                  </>
                )}
              </Button>
            </div>
            {searchMessage && (
              <p className="text-center text-sm mt-4 text-red-600">{searchMessage}</p>
            )}
          </div>
        </motion.div>

        {/* Steps Section */}
        {currentWord && (
          <div className="mb-8 grid gap-6 md:grid-cols-2">
            {/* Step 1: Search and Listen */}
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              className="bg-white rounded-2xl shadow-md border border-[#E5DDD5] overflow-hidden"
            >
              <div className="border-b-4 border-[#D4A853] bg-[#4A1429] p-4">
                <h3 className="text-center text-xl font-bold text-white">Step 1</h3>
                <p className="text-center text-white/90 mt-1">Search a word and listen</p>
              </div>

              <div className="p-6">
                {/* Word Display */}
                <div className="mb-6">
                  <div className="bg-[#FAF5F0] rounded-lg p-4 mb-4 border border-[#E5DDD5]">
                    <div className="flex items-center gap-3 mb-2">
                      <div className="w-10 h-10 bg-[#D4A853] rounded-lg flex items-center justify-center">
                        <Volume2 className="w-5 h-5 text-white" />
                      </div>
                      <div>
                        <h4 className="text-2xl font-bold text-[#4A1429]">{currentWord.word}</h4>
                        <p
                          className="text-lg text-[#6B5D52] font-mono"
                          style={{ fontFamily: IPA_FONT_STACK }}
                        >
                          {currentWord.phonetic}
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* Definition */}
                  <div className="mb-4 bg-[#FAF5F0] rounded-lg p-4 border border-[#E5DDD5]">
                    <h5 className="font-bold text-[#4A1429] mb-2">Definition:</h5>
                    <div className="space-y-1">
                      {currentWord.definition.map((def, i) => (
                        <p key={i} className="text-sm text-[#6B5D52]">
                          {typeof def === 'string' ? def : `(${def.part_of_speech}) ${def.definition}`}
                        </p>
                      ))}
                    </div>
                  </div>

                  {/* Synonyms */}
                  <div className="mb-4 bg-[#FAF5F0] rounded-lg p-4 border border-[#E5DDD5]">
                    <h5 className="font-bold text-[#4A1429] mb-2">Synonyms:</h5>
                    <p className="text-sm text-[#6B5D52]">{currentWord.synonyms}</p>
                  </div>

                  {hasRealExample(currentWord.example) && (
                    <div className="bg-[#FAF5F0] rounded-lg p-4 border border-[#E5DDD5]">
                      <h5 className="font-bold text-[#4A1429] mb-2">Example:</h5>
                      <p className="text-sm text-[#6B5D52] italic">{currentWord.example}</p>
                    </div>
                  )}
                </div>

                {/* Listen Button */}
                <Button
                  onClick={handleListen}
                  className="h-14 w-full rounded-lg bg-[#4A1429] text-base font-bold text-white shadow-md hover:bg-[#3A1020]"
                >
                  <Volume2 className="w-6 h-6 mr-2" />
                  Tap to listen
                </Button>
              </div>
            </motion.div>

            {/* Step 2: Analyze Pronunciation */}
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              className="bg-white rounded-2xl shadow-md border border-[#E5DDD5] overflow-hidden"
            >
              <div className="border-b-4 border-[#D4A853] bg-[#4A1429] p-4">
                <h3 className="text-center text-xl font-bold text-white">Step 2</h3>
                <p className="text-center text-white/90 mt-1">Analyze your pronunciation</p>
              </div>

              <div className="p-6">
                {/* Speak Button */}
                <div className="min-h-[400px] flex flex-col">
                   <div className="mb-5 rounded-lg border-2 border-[#D4A853] bg-[#FAF5F0] p-6 text-center">
                    <div className="flex items-center justify-center gap-4 mb-4">
                       <h4 className="text-2xl font-bold text-[#4A1429]">{currentWord.word}</h4>
                      {score !== null && (
                        <motion.div
                          initial={{ scale: 0 }}
                          animate={{ scale: 1 }}
                          className="px-4 py-2 bg-[#D4A853] rounded-full"
                        >
                          <span className="text-white font-bold text-lg">{score}%</span>
                        </motion.div>
                      )}
                    </div>
                     <div className="mx-auto flex h-20 w-20 items-center justify-center rounded-full bg-[#4A1429] shadow-lg">
                       <Mic className="h-10 w-10 text-white" />
                    </div>
                  </div>

                  <div className="space-y-2 text-sm text-[#6B5D52] mb-6 bg-[#FAF5F0] rounded-lg p-4 border border-[#E5DDD5]">
                    <p>- Tap the button and pronounce the word clearly</p>
                    <p>- AI will analyze your pronunciation instantly</p>
                    <p>- Review your results and practice again</p>
                  </div>
                  {analysisMessage && (
                    <p className="text-center text-sm mb-4 text-red-600">{analysisMessage}</p>
                  )}

                  <Button
                    onClick={handleRecord}
                    disabled={isAnalyzing}
                     className="h-14 w-full rounded-lg bg-[#4A1429] text-base font-bold text-white shadow-md hover:bg-[#3A1020] disabled:opacity-50"
                  >
                    {isRecording ? (
                      <div className="flex items-center justify-center">
                        <div className="w-3 h-3 bg-red-500 rounded-full animate-pulse mr-3"></div>
                        Recording... (tap to stop)
                      </div>
                    ) : (
                      <>
                        <Mic className="w-6 h-6 mr-2" />
                        {showResults ? 'Tap to Retry' : 'Hold & Speak (3s max)'}
                      </>
                    )}
                  </Button>
                </div>

                {/* Phoneme Analysis */}
                <AnimatePresence>
                  {showResults && (
                    <motion.div
                      initial={{ opacity: 0, height: 0 }}
                      animate={{ opacity: 1, height: 'auto' }}
                      exit={{ opacity: 0, height: 0 }}
                      className="border-t-2 border-[#E5DDD5] pt-6"
                    >
                      <h5 className="font-bold text-[#4A1429] mb-4 text-center">Phoneme Analysis</h5>
                      <div className="bg-[#FAF5F0] rounded-lg p-6 border border-[#E5DDD5]">
                        <div className="flex flex-wrap gap-3 justify-center mb-4">
                          {currentWord.phonemes.map((phoneme, i) => (
                            <motion.div
                              key={i}
                              initial={{ opacity: 0, scale: 0.8 }}
                              animate={{ opacity: 1, scale: 1 }}
                              transition={{ delay: i * 0.1 }}
                              className={`flex items-center gap-2 px-4 py-3 rounded-lg font-mono text-lg font-bold border-2 ${
                                phoneme.correct
                                  ? 'bg-green-50 border-green-500 text-green-700'
                                  : 'bg-red-50 border-red-500 text-red-700'
                              }`}
                              style={{ fontFamily: IPA_FONT_STACK }}
                            >
                              {phoneme.correct ? (
                                <Check className="w-5 h-5" />
                              ) : (
                                <X className="w-5 h-5" />
                              )}
                              {phoneme.symbol}
                            </motion.div>
                          ))}
                        </div>
                        
                        <div className="grid grid-cols-2 gap-4 text-sm">
                          <div className="flex items-center gap-2">
                            <div className="w-4 h-4 bg-green-500 rounded"></div>
                            <span className="text-[#6B5D52]">Correctly Spoken</span>
                          </div>
                          <div className="flex items-center gap-2">
                            <div className="w-4 h-4 bg-red-500 rounded"></div>
                            <span className="text-[#6B5D52]">Needs Improvement</span>
                          </div>
                        </div>
                      </div>
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            </motion.div>
          </div>
        )}

        {/* CTA Banner */}
        {currentWord && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.3 }}
            className="mt-8"
          >
            <div className="rounded-2xl border-2 border-[#D4A853] bg-[#4A1429] p-7 text-white shadow-lg sm:p-8">
              <div className="mb-6 text-center">
                <h3 className="mb-2 text-2xl font-bold">Want to Build Clearer Speech Beyond One Word?</h3>
                <p className="mx-auto max-w-2xl text-base leading-7 text-white/90 sm:text-lg">
                  Move from individual sounds to confident speaking with structured voice and accent training.
                </p>
              </div>
              
              <div className="mx-auto mb-6 grid max-w-3xl gap-4 md:grid-cols-2">
                <Link
                  href="/voice-and-accent-classes"
                  className="inline-flex h-14 items-center justify-center rounded-lg bg-white px-5 text-base font-bold text-[#4A1429] shadow-md transition-colors hover:bg-[#FAF5F0]"
                >
                  <GraduationCap className="w-6 h-6 mr-3" />
                  Explore Voice &amp; Accent Classes
                </Link>
                
                <Button
                  onClick={() => window.open('https://wa.me/918068212576', '_blank')}
                  className="h-14 rounded-lg bg-[#25D366] text-base font-bold text-white shadow-md hover:bg-[#20BA5A]"
                >
                  <MessageCircle className="w-6 h-6 mr-3" />
                  Chat with Counselor
                </Button>
              </div>

              <div className="flex flex-wrap justify-center gap-x-6 gap-y-3 text-sm">
                <div className="flex items-center gap-2">
                  <Check className="w-5 h-5 text-[#D4A853]" />
                  <span>AI-Powered Analysis</span>
                </div>
                <div className="flex items-center gap-2">
                  <Check className="w-5 h-5 text-[#D4A853]" />
                  <span>Instant Feedback</span>
                </div>
                <div className="flex items-center gap-2">
                  <Check className="w-5 h-5 text-[#D4A853]" />
                  <span>Repeatable Word Practice</span>
                </div>
                <div className="flex items-center gap-2">
                  <Check className="w-5 h-5 text-[#D4A853]" />
                  <span>Professional Learning Pathways</span>
                </div>
              </div>
            </div>
          </motion.div>
        )}
          </>
        </ToolAccessGate>
      </div>
      </section>
      )}

      {!workspaceOnly && <OralDrillSeoSections />}

      {/* Analyzing Modal */}
      <AnimatePresence>
        {isAnalyzing && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-6"
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              className="bg-white rounded-3xl p-12 max-w-md w-full shadow-2xl"
            >
              <div className="text-center">
                <div className="w-32 h-32 mx-auto mb-6 relative">
                  <div className="w-32 h-32 bg-[#4A1429] rounded-full animate-pulse flex items-center justify-center">
                    <Mic className="w-16 h-16 text-white" />
                  </div>
                </div>
                
                <h3 className="text-2xl font-bold text-[#4A1429] mb-3">Analyzing Pronunciation</h3>
                <p className="text-[#6B5D52] mb-6">
                  Our AI is analyzing your speech patterns...
                </p>
                
                <div className="space-y-3">
                  {['Detecting phonemes', 'Comparing with the model pronunciation', 'Generating feedback'].map((text, i) => (
                    <motion.div
                      key={i}
                      initial={{ opacity: 0, x: -20 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ delay: i * 0.3 }}
                      className="flex items-center gap-3 text-sm text-[#6B5D52]"
                    >
                      <div className="w-2 h-2 bg-[#D4A853] rounded-full"></div>
                      {text}
                    </motion.div>
                  ))}
                </div>

                <div className="mt-8 h-2 bg-[#FAF5F0] rounded-full overflow-hidden border border-[#E5DDD5]">
                  <motion.div
                    initial={{ width: '0%' }}
                    animate={{ width: '100%' }}
                    transition={{ duration: 2.5, ease: 'linear' }}
                    className="h-full bg-[#D4A853]"
                  />
                </div>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Thank You / Join Course Modal */}
      <AnimatePresence>
        {showThankYou && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/70 backdrop-blur-md z-50 flex items-center justify-center p-6"
            onClick={() => setShowThankYou(false)}
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0, y: 20 }}
              animate={{ scale: 1, opacity: 1, y: 0 }}
              exit={{ scale: 0.9, opacity: 0, y: 20 }}
              onClick={(e) => e.stopPropagation()}
              className="bg-white rounded-2xl p-12 max-w-2xl w-full shadow-lg border-2 border-[#D4A853]"
            >
              <div className="text-center">
                {/* Header */}
                <motion.div
                  initial={{ scale: 0 }}
                  animate={{ scale: 1 }}
                  transition={{ delay: 0.2, type: 'spring' }}
                  className="w-24 h-24 bg-[#4A1429] rounded-full flex items-center justify-center mx-auto mb-6 shadow-lg"
                >
                  <GraduationCap className="w-12 h-12 text-white" />
                </motion.div>

                <h2 className="text-4xl font-bold text-[#4A1429] mb-4">
                  Continue Learning with Expert Support
                </h2>
                
                <p className="text-lg text-[#6B5D52] mb-8 leading-relaxed max-w-xl mx-auto">
                  Build on your pronunciation practice with structured voice and accent training, guided learning and professional feedback from Cambridge Veritas.
                </p>

                {/* Certification Badge */}
                <div className="bg-white rounded-lg p-6 mb-8 border-2 border-[#D4A853] shadow-md">
                  <h3 className="text-2xl font-bold text-[#4A1429] mb-2">
                    Voice and Accent Certification Program
                  </h3>
                  <p className="text-lg text-[#6B5D52] mb-3">by Cambridge Veritas</p>
                  <div className="flex items-center justify-center gap-2">
                    {[...Array(5)].map((_, i) => (
                      <motion.div
                        key={i}
                        initial={{ opacity: 0, scale: 0 }}
                        animate={{ opacity: 1, scale: 1 }}
                        transition={{ delay: 0.5 + i * 0.1 }}
                      >
                        <Star className="h-8 w-8 fill-current text-[#D4A853]" aria-hidden="true" />
                      </motion.div>
                    ))}
                  </div>
                  <p className="text-sm text-[#6B5D52] mt-2">5-star rating on verified Google reviews</p>
                </div>

                <p className="text-lg text-[#4A1429] font-semibold mb-6">
                  Tap below to either join the course or WhatsApp our counselor
                </p>

                {/* CTA Buttons */}
                <div className="grid md:grid-cols-2 gap-4">
                  <Link
                    href="/voice-and-accent-classes"
                    className="inline-flex h-16 items-center justify-center rounded-lg bg-[#4A1429] px-5 text-lg font-bold text-white shadow-md transition-colors hover:bg-[#3A1020]"
                  >
                    <GraduationCap className="w-6 h-6 mr-2" />
                    Explore Classes
                  </Link>
                  
                  <Button
                    onClick={() => window.open('https://wa.me/918068212576', '_blank')}
                    className="h-16 bg-[#25D366] hover:bg-[#20BA5A] text-white font-bold rounded-lg shadow-md text-lg"
                  >
                    <MessageCircle className="w-6 h-6 mr-2" />
                    WhatsApp Counselor
                  </Button>
                </div>

                {/* Close link */}
                <button
                  onClick={() => setShowThankYou(false)}
                  className="mt-6 text-[#6B5D52] hover:text-[#4A1429] underline text-sm transition-colors"
                >
                  Continue practicing
                </button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
      </main>
      {!workspaceOnly && <CVFooter />}
    </>
  );
}
