'use client';

import React, { useEffect, useRef, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useAuth } from '@/lib/AuthContext';
import { getApiPath } from '@/lib/basePath';
import {
  Mic,
  Camera,
  ArrowRight,
  ChevronRight,
  AlertTriangle,
  BookOpen,
  Sparkles,
  RotateCcw,
  Volume2,
  Loader2,
  StopCircle,
} from 'lucide-react';

const PROMPTS = [
  'Describe what you see - the people, the food, the atmosphere.',
  'Describe this natural landscape - what can you see, feel, and imagine?',
  'Describe this city scene - the buildings, the people, the mood.',
  'Describe what is happening in this classroom or learning environment.',
  'Describe this market scene - the colours, the products, the people.',
];

const FALLBACK_PHOTOS = [
  { url: '/photo-mode/AI_image_01.jpg', alt: 'Photo mode scene 1' },
  { url: '/photo-mode/AI_image_02.jpg', alt: 'Photo mode scene 2' },
  { url: '/photo-mode/AI_image_03.jpg', alt: 'Photo mode scene 3' },
  { url: '/photo-mode/AI_image_04.jpg', alt: 'Photo mode scene 4' },
  { url: '/photo-mode/AI_image_05.jpg', alt: 'Photo mode scene 5' },
];

const MIN_WORDS = 10;
const CHUNK_MS = 45000;

export default function PhotoMode() {
  const { user } = useAuth();
  const [photoIndex, setPhotoIndex] = useState(-1);
  const [photo, setPhoto] = useState({
    id: null,
    url: FALLBACK_PHOTOS[0].url,
    alt: FALLBACK_PHOTOS[0].alt,
    prompt: PROMPTS[0],
  });
  const [stage, setStage] = useState('idle');
  const [transcript, setTranscript] = useState('');
  const [feedback, setFeedback] = useState(null);
  const [recordingSeconds, setRecordingSeconds] = useState(0);
  const [mediaError, setMediaError] = useState('');
  const [speechScores, setSpeechScores] = useState(null);
  const [speechError, setSpeechError] = useState('');

  const mediaRecorderRef = useRef(null);
  const chunksRef = useRef([]);
  const timerRef = useRef(null);
  const recognitionRef = useRef(null);
  const finalTranscriptRef = useRef('');
  const isRecordingRef = useRef(false);
  const liveTranscriptRef = useRef('');
  const transcriptRef = useRef('');
  const transcriptionQueueRef = useRef([]);
  const isChunkTranscribingRef = useRef(false);

  const wordCount = transcript.trim().split(/\s+/).filter(Boolean).length;
  const displayIndex = photoIndex < 0 ? 0 : photoIndex;

  useEffect(() => {
    loadRandomPhoto();
    return () => {
      clearInterval(timerRef.current);
      if (recognitionRef.current) recognitionRef.current.abort();
      if (mediaRecorderRef.current && mediaRecorderRef.current.state !== 'inactive') {
        mediaRecorderRef.current.stop();
      }
    };
  }, []);

  useEffect(() => {
    transcriptRef.current = transcript;
  }, [transcript]);

  const loadRandomPhoto = async () => {
    try {
      const res = await fetch(getApiPath('/api/photo-mode/random-image'), { method: 'POST' });
      if (!res.ok) throw new Error('Failed to fetch image');
      const data = await res.json();
      setPhotoIndex((prev) => {
        const nextIndex = (prev + 1) % PROMPTS.length;
        setPhoto({
          id: data?.id ?? null,
          url: data.image_url || FALLBACK_PHOTOS[nextIndex].url,
          alt: data.alt || FALLBACK_PHOTOS[nextIndex].alt,
          prompt: data.prompt || PROMPTS[nextIndex],
        });
        return nextIndex;
      });
    } catch {
      setPhotoIndex((prev) => {
        const nextIndex = (prev + 1) % FALLBACK_PHOTOS.length;
        setPhoto({
          id: null,
          url: FALLBACK_PHOTOS[nextIndex].url,
          alt: FALLBACK_PHOTOS[nextIndex].alt,
          prompt: PROMPTS[nextIndex],
        });
        return nextIndex;
      });
    }
  };

  const waitForTranscriptionQueue = async () => {
    let guard = 0;
    while ((transcriptionQueueRef.current.length > 0 || isChunkTranscribingRef.current) && guard < 1200) {
      guard += 1;
      await new Promise((resolve) => setTimeout(resolve, 200));
    }
  };

  const enqueueTranscription = async (blob) => {
    if (!blob || !blob.size) return;
    transcriptionQueueRef.current.push(blob);
    if (isChunkTranscribingRef.current) return;

    isChunkTranscribingRef.current = true;
    while (transcriptionQueueRef.current.length > 0) {
      const nextChunk = transcriptionQueueRef.current.shift();
      try {
        const text = await transcribeAudio(nextChunk);
        if (text) {
          finalTranscriptRef.current = `${finalTranscriptRef.current} ${text}`.trim();
          const serverWords = finalTranscriptRef.current.split(/\s+/).filter(Boolean).length;
          const currentWords = transcriptRef.current.split(/\s+/).filter(Boolean).length;
          if (serverWords >= currentWords) {
            setTranscript(finalTranscriptRef.current);
          }
        }
      } catch (error) {
        setMediaError(error?.message || 'Could not transcribe audio. Please try again.');
      }
    }
    isChunkTranscribingRef.current = false;
  };

  const startRecording = async () => {
    setMediaError('');
    setTranscript('');
    setFeedback(null);
    setSpeechScores(null);
    setSpeechError('');
    chunksRef.current = [];
    finalTranscriptRef.current = '';
    liveTranscriptRef.current = '';
    transcriptionQueueRef.current = [];
    setRecordingSeconds(0);

    let stream;
    try {
      stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    } catch {
      setMediaError('Microphone access denied. Please allow microphone access and try again.');
      return;
    }

    const mimeType = MediaRecorder.isTypeSupported('audio/webm;codecs=opus')
      ? 'audio/webm;codecs=opus'
      : 'audio/webm';
    const mr = new MediaRecorder(stream, { mimeType });
    mediaRecorderRef.current = mr;

    mr.ondataavailable = (event) => {
      if (event.data.size > 0) {
        chunksRef.current.push(event.data);
        enqueueTranscription(event.data);
      }
    };

    mr.onstop = async () => {
      stream.getTracks().forEach((t) => t.stop());
      const blob = new Blob(chunksRef.current, { type: mr.mimeType || 'audio/webm' });
      setStage('processing');

      fetchSpeechScores(blob);
      await waitForTranscriptionQueue();
      if (finalTranscriptRef.current.trim()) {
        setTranscript(finalTranscriptRef.current.trim());
      } else if (liveTranscriptRef.current.trim()) {
        setTranscript(liveTranscriptRef.current.trim());
      }
      setStage('transcript');
    };

    mr.start(CHUNK_MS);

    const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (SR) {
      const rec = new SR();
      rec.lang = 'en-GB';
      rec.continuous = true;
      rec.interimResults = true;
      rec.onresult = (ev) => {
        let interim = '';
        let finalSegment = '';
        for (let i = ev.resultIndex; i < ev.results.length; i++) {
          const chunk = ev.results[i][0]?.transcript || '';
          if (ev.results[i].isFinal) finalSegment += chunk + ' ';
          else interim += chunk;
        }
        if (finalSegment) {
          liveTranscriptRef.current += finalSegment;
        }
        setTranscript((liveTranscriptRef.current + interim).trim());
      };
      rec.onend = () => {
        if (isRecordingRef.current) rec.start();
      };
      rec.start();
      recognitionRef.current = rec;
    }

    isRecordingRef.current = true;
    timerRef.current = setInterval(() => setRecordingSeconds((s) => s + 1), 1000);
    setStage('recording');
  };

  const stopRecording = () => {
    clearInterval(timerRef.current);
    isRecordingRef.current = false;
    if (recognitionRef.current) {
      recognitionRef.current.stop();
      recognitionRef.current = null;
    }
    if (mediaRecorderRef.current && mediaRecorderRef.current.state !== 'inactive') {
      mediaRecorderRef.current.stop();
    }
  };

  const transcribeAudio = async (blob) => {
    const formData = new FormData();
    formData.append('audio', blob, 'audio.webm');
    const res = await fetch(getApiPath('/api/photo-mode/transcribe'), { method: 'POST', body: formData });
    const data = await res.json();
    if (!res.ok) {
      throw new Error(data?.message || 'Transcription failed');
    }
    return data?.transcript || '';
  };

  const fetchSpeechScores = async (blob) => {
    try {
      const formData = new FormData();
      formData.append('audio', blob, 'audio.webm');
      formData.append('prompt', photo.prompt);
      const res = await fetch(getApiPath('/api/photo-mode/superspeech'), { method: 'POST', body: formData });
      const data = await res.json();
      if (!res.ok) throw new Error(data?.message || 'SpeechSuper failed');
      setSpeechScores(data.scores);
    } catch {
      setSpeechError('Speech analysis unavailable.');
    }
  };

  const submitForFeedback = async () => {
    if (wordCount < MIN_WORDS) return;
    setStage('processing');
    try {
      const res = await fetch(getApiPath('/api/photo-mode/feedback'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          message: transcript,
          imageId: photo.id ?? null,
          userId: user?.id ?? null,
          speechScores: speechScores ?? null,
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data?.message || 'Feedback failed');
      setFeedback(data?.api_response || data || null);
      setStage('feedback');
    } catch (error) {
      setMediaError(error?.message || 'Unable to submit feedback right now.');
      setStage('transcript');
    }
  };

  const nextPhoto = () => {
    setStage('idle');
    setTranscript('');
    setFeedback(null);
    setSpeechScores(null);
    setSpeechError('');
    setRecordingSeconds(0);
    setMediaError('');
    loadRandomPhoto();
  };

  const fmtTime = (s) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;
  const corrections = Array.isArray(feedback?.feedback)
    ? feedback.feedback
    : Array.isArray(feedback?.errors)
      ? feedback.errors
      : [];
  const correctedText = feedback?.corrected || feedback?.corrected_text || feedback?.correctedText || '';
  const overallFeedback = feedback?.overall_feedback || feedback?.overallFeedback || '';
  const vocabHighlights = Array.isArray(feedback?.vocabulary_highlights)
    ? feedback.vocabulary_highlights
    : Array.isArray(feedback?.vocabularyHighlights)
      ? feedback.vocabularyHighlights
      : [];

  return (
    <div className="min-h-screen" style={{ background: '#FAF5F0' }}>
      <div className="max-w-4xl mx-auto px-4 sm:px-6 pt-8 pb-4">
        <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} className="flex flex-col items-center text-center">
          <div
            className="inline-flex items-center gap-2 rounded-full border px-3.5 py-1.5 mb-3"
            style={{ background: 'rgba(212,176,56,0.12)', borderColor: 'rgba(212,176,56,0.4)' }}
          >
            <Camera className="w-3 h-3" style={{ color: '#B8942A' }} />
            <span className="text-[11px] font-bold uppercase tracking-widest" style={{ color: '#8B6914' }}>
              Photo Mode - Picture Description Practice
            </span>
          </div>
          <h1 className="text-2xl sm:text-3xl font-black leading-tight mb-1" style={{ color: '#4A1429' }}>
            Describe the Picture
          </h1>
          <p className="text-sm" style={{ color: '#6B4455' }}>
            Look at the image, press the mic button, and describe what you see in at least {MIN_WORDS} words.
          </p>
        </motion.div>
      </div>

      <div className="max-w-5xl mx-auto px-4 sm:px-6 pb-12">
        <div className="flex flex-col lg:flex-row gap-6 items-start">
          <div className="w-full lg:w-[45%] shrink-0">
            <motion.div
              key={photo.url}
              initial={{ opacity: 0, scale: 0.97 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ duration: 0.4 }}
              className="rounded-3xl overflow-hidden shadow-xl"
              style={{ border: '3px solid #D4B038' }}
            >
              <img src={photo.url} alt={photo.alt} className="w-full object-cover" style={{ height: 420 }} />
            </motion.div>

            <div
              className="mt-3 rounded-2xl px-5 py-3.5 flex items-center justify-between"
              style={{ background: 'white', border: '1px solid #E5DDD5' }}
            >
              <div className="flex items-center gap-2">
                <BookOpen className="w-4 h-4" style={{ color: '#8B6B7A' }} />
                <span className="text-sm font-semibold" style={{ color: '#6B4455' }}>{photo.prompt}</span>
              </div>
              <span
                className="text-xs font-black px-2.5 py-1 rounded-full ml-3 shrink-0"
                style={{ background: 'rgba(212,176,56,0.15)', color: '#8B6914' }}
              >
                {displayIndex + 1} / {PROMPTS.length}
              </span>
            </div>

            <div className="mt-2 text-center">
              <span className="text-xs font-semibold" style={{ color: '#8B6B7A' }}>
                You must use at least {MIN_WORDS} words.
              </span>
            </div>
          </div>

          <div className="w-full lg:flex-1">
            <AnimatePresence mode="wait">
              {stage === 'idle' && (
                <motion.div
                  key="idle"
                  initial={{ opacity: 0, y: 16 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -8 }}
                  className="rounded-3xl p-8 flex flex-col items-center text-center"
                  style={{ background: 'white', border: '2px solid #E5DDD5', minHeight: 480 }}
                >
                  <div className="flex-1 flex flex-col items-center justify-center">
                    <div
                      className="w-24 h-24 rounded-full flex items-center justify-center mb-6"
                      style={{ background: 'rgba(74,20,41,0.08)', border: '2px dashed #D4B038' }}
                    >
                      <Mic className="w-10 h-10" style={{ color: '#4A1429' }} />
                    </div>
                    <h2 className="text-xl font-black mb-2" style={{ color: '#4A1429' }}>Ready to Describe?</h2>
                    <p className="text-sm leading-relaxed mb-8 max-w-sm" style={{ color: '#6B4455' }}>
                      Look at the picture on the left, then press the mic button below to start speaking. Describe what you see in detail.
                    </p>

                    {mediaError && (
                      <div
                        className="mb-4 px-4 py-3 rounded-xl text-sm font-semibold flex items-center gap-2"
                        style={{ background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.2)', color: '#DC2626' }}
                      >
                        <AlertTriangle className="w-4 h-4 shrink-0" /> {mediaError}
                      </div>
                    )}

                    <motion.button
                      onClick={startRecording}
                      whileHover={{ scale: 1.05 }}
                      whileTap={{ scale: 0.95 }}
                      className="flex items-center gap-3 px-8 py-4 rounded-2xl font-extrabold text-base transition-all"
                      style={{
                        background: 'linear-gradient(135deg, #4A1429, #6B1E3D)',
                        color: 'white',
                        boxShadow: '0 8px 28px rgba(74,20,41,0.35)',
                      }}
                    >
                      <Mic className="w-5 h-5" />
                      Start Recording
                    </motion.button>
                  </div>
                </motion.div>
              )}

              {stage === 'recording' && (
                <motion.div
                  key="recording"
                  initial={{ opacity: 0, y: 16 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -8 }}
                  className="rounded-3xl overflow-hidden"
                  style={{ background: 'white', border: '2px solid #D4B038', minHeight: 480 }}
                >
                  <div
                    className="flex items-center justify-between px-6 py-4"
                    style={{ background: 'linear-gradient(135deg, #4A1429, #6B1E3D)' }}
                  >
                    <div className="flex items-center gap-3">
                      <motion.div
                        animate={{ scale: [1, 1.3, 1] }}
                        transition={{ repeat: Infinity, duration: 1.2 }}
                        className="w-3 h-3 rounded-full bg-red-400"
                      />
                      <span className="text-white font-black text-sm tracking-wide">RECORDING</span>
                    </div>
                    <span className="font-mono font-black text-lg" style={{ color: '#D4B038' }}>
                      {fmtTime(recordingSeconds)}
                    </span>
                  </div>

                  <div className="p-6 flex-1" style={{ minHeight: 280 }}>
                    <p className="text-xs font-bold uppercase tracking-widest mb-3" style={{ color: '#8B6B7A' }}>
                      Live Transcript
                    </p>
                    {transcript ? (
                      <p className="text-base leading-relaxed font-medium" style={{ color: '#2D0F1C' }}>
                        {transcript}
                      </p>
                    ) : (
                      <div className="flex items-center gap-2" style={{ color: '#8B6B7A' }}>
                        <motion.div animate={{ opacity: [0.4, 1, 0.4] }} transition={{ repeat: Infinity, duration: 1.5 }}>
                          <Volume2 className="w-4 h-4" />
                        </motion.div>
                        <span className="text-sm italic">Listening... start speaking now</span>
                      </div>
                    )}
                  </div>

                  <div className="px-6 pb-6 flex items-center justify-between">
                    <div
                      className="text-sm font-semibold"
                      style={{ color: wordCount >= MIN_WORDS ? '#16A34A' : '#8B6B7A' }}
                    >
                      {wordCount} / {MIN_WORDS} words minimum
                      {wordCount >= MIN_WORDS && <span className="ml-2">OK</span>}
                    </div>
                    <motion.button
                      onClick={stopRecording}
                      whileHover={{ scale: 1.04 }}
                      whileTap={{ scale: 0.96 }}
                      className="flex items-center gap-2 px-6 py-3 rounded-xl font-extrabold text-sm"
                      style={{ background: 'linear-gradient(135deg, #D4B038, #B8942A)', color: '#3D0F22' }}
                    >
                      <StopCircle className="w-4 h-4" />
                      Stop and Submit
                    </motion.button>
                  </div>
                </motion.div>
              )}

              {stage === 'processing' && (
                <motion.div
                  key="processing"
                  initial={{ opacity: 0, scale: 0.97 }}
                  animate={{ opacity: 1, scale: 1 }}
                  exit={{ opacity: 0 }}
                  className="rounded-3xl p-8 flex flex-col items-center justify-center text-center"
                  style={{ background: 'white', border: '2px solid #E5DDD5', minHeight: 480 }}
                >
                  <div className="relative mb-6">
                    <div
                      className="w-20 h-20 rounded-full flex items-center justify-center"
                      style={{ background: 'rgba(212,176,56,0.12)', border: '2px solid rgba(212,176,56,0.3)' }}
                    >
                      <motion.div
                        animate={{ rotate: 360 }}
                        transition={{ repeat: Infinity, duration: 1.2, ease: 'linear' }}
                      >
                        <Loader2 className="w-9 h-9" style={{ color: '#D4B038' }} />
                      </motion.div>
                    </div>
                  </div>

                  <h2 className="text-xl font-black mb-2" style={{ color: '#4A1429' }}>Analyzing your response...</h2>
                  <p className="text-sm leading-relaxed max-w-xs" style={{ color: '#6B4455' }}>
                    Our AI is reviewing your grammar, vocabulary, and fluency. This takes just a moment.
                  </p>

                  <div className="flex gap-2 mt-6">
                    {[0, 1, 2].map((i) => (
                      <motion.div
                        key={i}
                        animate={{ y: [0, -8, 0] }}
                        transition={{ repeat: Infinity, duration: 0.9, delay: i * 0.2 }}
                        className="w-2.5 h-2.5 rounded-full"
                        style={{ background: '#D4B038' }}
                      />
                    ))}
                  </div>
                </motion.div>
              )}

              {stage === 'transcript' && (
                <motion.div
                  key="transcript"
                  initial={{ opacity: 0, y: 16 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -8 }}
                  className="rounded-3xl overflow-hidden"
                  style={{ background: 'white', border: '2px solid #E5DDD5', minHeight: 480 }}
                >
                  <div
                    className="px-6 py-4"
                    style={{ background: 'linear-gradient(135deg, #FAF5F0, #F5EDE8)', borderBottom: '1px solid #E5DDD5' }}
                  >
                    <p className="text-xs font-black uppercase tracking-widest mb-0.5" style={{ color: '#8B6B7A' }}>Your Description</p>
                    <h2 className="text-lg font-black" style={{ color: '#4A1429' }}>Review before submitting</h2>
                  </div>

                  <div className="p-6" style={{ minHeight: 240 }}>
                    <p className="text-base leading-relaxed font-medium" style={{ color: '#2D0F1C' }}>
                      {transcript || (
                        <span className="italic" style={{ color: '#8B6B7A' }}>No speech detected. Please try again.</span>
                      )}
                    </p>
                  </div>

                  <div className="px-6 pb-2">
                    <div className="flex justify-between text-xs font-semibold mb-1" style={{ color: '#8B6B7A' }}>
                      <span>{wordCount} words used</span>
                      <span>Min. {MIN_WORDS} words</span>
                    </div>
                    <div className="h-1.5 rounded-full" style={{ background: '#F0E8E0' }}>
                      <div
                        className="h-1.5 rounded-full transition-all"
                        style={{
                          width: `${Math.min(100, (wordCount / MIN_WORDS) * 100)}%`,
                          background: wordCount >= MIN_WORDS ? '#16A34A' : '#D4B038',
                        }}
                      />
                    </div>
                  </div>

                  <div className="px-6 pb-6 mt-4 flex items-center gap-3">
                    <button
                      onClick={() => setStage('idle')}
                      className="flex items-center gap-2 px-5 py-3 rounded-xl font-bold text-sm transition-all hover:bg-gray-50"
                      style={{ border: '1.5px solid #E5DDD5', color: '#6B4455' }}
                    >
                      <RotateCcw className="w-4 h-4" /> Try Again
                    </button>
                    <motion.button
                      onClick={submitForFeedback}
                      disabled={wordCount < MIN_WORDS}
                      whileHover={{ scale: wordCount >= MIN_WORDS ? 1.03 : 1 }}
                      whileTap={{ scale: wordCount >= MIN_WORDS ? 0.97 : 1 }}
                      className="flex-1 flex items-center justify-center gap-2 py-3 rounded-xl font-extrabold text-sm transition-all disabled:opacity-40"
                      style={{ background: 'linear-gradient(135deg, #4A1429, #6B1E3D)', color: 'white' }}
                    >
                      <Sparkles className="w-4 h-4" />
                      Get AI Feedback
                      <ArrowRight className="w-4 h-4" />
                    </motion.button>
                  </div>
                </motion.div>
              )}

              {stage === 'feedback' && feedback && (
                <motion.div
                  key="feedback"
                  initial={{ opacity: 0, y: 16 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -8 }}
                  className="rounded-3xl overflow-hidden"
                  style={{ background: 'white', border: '2px solid #E5DDD5' }}
                >
                  <div className="px-6 py-4" style={{ background: 'linear-gradient(135deg, #4A1429, #6B1E3D)' }}>
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="text-white/60 text-xs font-bold uppercase tracking-widest mb-0.5">AI Analysis Complete</p>
                        <h2 className="text-lg font-black text-white">Your Feedback</h2>
                      </div>
                    </div>
                  </div>

                  <div className="p-6 space-y-5 overflow-y-auto" style={{ maxHeight: 520 }}>
                    <div className="grid grid-cols-3 gap-3">
                      {[
                        { label: 'Grammar', key: 'grammar' },
                        { label: 'Vocabulary', key: 'vocabulary' },
                        { label: 'Fluency', key: 'fluency' },
                      ].map(({ label, key }) => (
                        <div
                          key={label}
                          className="rounded-2xl p-3 text-center"
                          style={{ background: '#FAF5F0', border: '1px solid #E5DDD5' }}
                        >
                          <div className="text-2xl font-black mb-0.5" style={{ color: '#D4B038' }}>
                            {speechScores?.[key] ?? '--'}<span className="text-sm font-bold">/10</span>
                          </div>
                          <div className="text-[11px] font-bold uppercase tracking-wide" style={{ color: '#8B6B7A' }}>
                            {label}
                          </div>
                        </div>
                      ))}
                    </div>

                    {speechError && (
                      <div
                        className="rounded-2xl px-4 py-3"
                        style={{ background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.2)' }}
                      >
                        <p className="text-sm font-semibold" style={{ color: '#DC2626' }}>{speechError}</p>
                      </div>
                    )}

                    {overallFeedback && (
                      <div
                        className="rounded-2xl px-4 py-3.5"
                        style={{ background: 'rgba(212,176,56,0.08)', border: '1px solid rgba(212,176,56,0.25)' }}
                      >
                        <p className="text-xs font-black uppercase tracking-widest mb-1.5" style={{ color: '#8B6914' }}>
                          Overall Feedback
                        </p>
                        <p className="text-sm leading-relaxed font-medium" style={{ color: '#4A1429' }}>
                          {overallFeedback}
                        </p>
                      </div>
                    )}

                    <div className="rounded-2xl overflow-hidden" style={{ border: '1px solid #E5DDD5' }}>
                      <div className="px-4 py-2.5" style={{ background: '#F5EDE8', borderBottom: '1px solid #E5DDD5' }}>
                        <p className="text-xs font-black uppercase tracking-widest" style={{ color: '#4A1429' }}>Your Description</p>
                      </div>
                      <div className="px-4 py-3">
                        <p className="text-[11px] font-bold uppercase tracking-wide mb-1" style={{ color: '#8B6B7A' }}>Original:</p>
                        <p className="text-sm leading-relaxed mb-3" style={{ color: '#2D0F1C' }}>{feedback.original || transcript}</p>
                        <p className="text-[11px] font-bold uppercase tracking-wide mb-1" style={{ color: '#16A34A' }}>Corrected:</p>
                        <p className="text-sm leading-relaxed" style={{ color: '#2D0F1C' }}>{correctedText || transcript}</p>
                      </div>
                    </div>

                    {corrections.length > 0 && (
                      <div>
                        <p className="text-xs font-black uppercase tracking-widest mb-3" style={{ color: '#4A1429' }}>
                          Corrections ({corrections.length})
                        </p>
                        <div className="space-y-2.5">
                          {corrections.map((err, i) => (
                            <div
                              key={i}
                              className="rounded-2xl px-4 py-3.5"
                              style={{ background: 'rgba(239,68,68,0.04)', border: '1px solid rgba(239,68,68,0.15)' }}
                            >
                              <div className="flex items-start gap-2 mb-1.5">
                                <AlertTriangle className="w-3.5 h-3.5 mt-0.5 shrink-0 text-red-500" />
                                <span className="text-sm font-bold text-red-600">Error: </span>
                                <span className="text-sm" style={{ color: '#2D0F1C' }}>{err.error}</span>
                              </div>
                              <div className="ml-5 space-y-0.5">
                                <p className="text-xs">
                                  <span className="font-bold" style={{ color: '#16A34A' }}>Suggestion: </span>
                                  <span style={{ color: '#2D0F1C' }}>{err.suggestion}</span>
                                </p>
                                <p className="text-xs leading-relaxed" style={{ color: '#6B4455' }}>
                                  <span className="font-bold">Explanation: </span>{err.explanation}
                                </p>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}

                    {vocabHighlights.length > 0 && (
                      <div>
                        <p className="text-xs font-black uppercase tracking-widest mb-2.5" style={{ color: '#4A1429' }}>
                          Good Vocabulary Used
                        </p>
                        <div className="flex flex-wrap gap-2">
                          {vocabHighlights.map((word, i) => (
                            <span
                              key={`${word}-${i}`}
                              className="px-3 py-1.5 rounded-full text-xs font-extrabold"
                              style={{
                                background: 'rgba(22,163,74,0.1)',
                                border: '1px solid rgba(22,163,74,0.25)',
                                color: '#16A34A',
                              }}
                            >
                              ? {word}
                            </span>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>

                  <div className="px-6 py-4 flex items-center gap-3" style={{ borderTop: '1px solid #E5DDD5' }}>
                    <button
                      onClick={() => setStage('idle')}
                      className="flex items-center gap-2 px-5 py-3 rounded-xl font-bold text-sm transition-all hover:bg-gray-50"
                      style={{ border: '1.5px solid #E5DDD5', color: '#6B4455' }}
                    >
                      <RotateCcw className="w-4 h-4" /> Retry This
                    </button>
                    <motion.button
                      onClick={nextPhoto}
                      whileHover={{ scale: 1.03 }}
                      whileTap={{ scale: 0.97 }}
                      className="flex-1 flex items-center justify-center gap-2 py-3 rounded-xl font-extrabold text-sm"
                      style={{ background: 'linear-gradient(135deg, #D4B038, #B8942A)', color: '#3D0F22' }}
                    >
                      Next Picture
                      <ChevronRight className="w-4 h-4" />
                    </motion.button>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        </div>
      </div>
    </div>
  );
}
