'use client';

import React, { useEffect, useRef, useState } from 'react';
import Link from 'next/link';
import { motion, AnimatePresence } from 'framer-motion';
import { useAuth } from '@/lib/AuthContext';
import { getApiPath } from '@/lib/basePath';
import CVHeader from '@/components/layout/CVHeader';
import CVFooter from '@/components/layout/CVFooter';
import ToolAccessGate from '@/components/tools/ToolAccessGate';
import {
  Mic,
  Camera,
  ArrowRight,
  ChevronRight,
  AlertTriangle,
  BookOpen,
  Sparkles,
  RotateCcw,
  Loader2,
  StopCircle,
  AudioLines,
  Brain,
  CheckCircle2,
  Clock3,
  Eye,
  GraduationCap,
  Languages,
  Lightbulb,
  ListChecks,
  LockKeyhole,
  RefreshCw,
  ShieldCheck,
  Target,
  UsersRound,
} from 'lucide-react';
import {
  DESCRIPTION_STEPS,
  GLOSSARY,
  GRAMMAR_POINTS,
  HOW_IT_WORKS,
  PHOTO_MODE_FAQS,
  PHRASE_GROUPS,
  PRACTICE_LEVELS,
  SPEAKING_SKILLS,
  photoModeJsonLd,
} from './photoModeSeoData';

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: 'English picture-description speaking prompt 1' },
  { url: '/photo-mode/AI_image_02.jpg', alt: 'English picture-description speaking prompt 2' },
  { url: '/photo-mode/AI_image_03.jpg', alt: 'English picture-description speaking prompt 3' },
  { url: '/photo-mode/AI_image_04.jpg', alt: 'English picture-description speaking prompt 4' },
  { url: '/photo-mode/AI_image_05.jpg', alt: 'English picture-description speaking prompt 5' },
];

const MIN_WORDS = 20;
const MAX_RECORD_SECONDS = 150;

export default function PhotoMode({ workspaceOnly = false }) {
  const { user } = useAuth();
  const [level, setLevel] = useState('b1');
  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 streamRef = useRef(null);
  const isRecordingRef = useRef(false);
  const recordingStartedAtRef = useRef(0);

  const wordCount = transcript.trim().split(/\s+/).filter(Boolean).length;
  const displayIndex = photoIndex < 0 ? 0 : photoIndex;
  const selectedLevel = PRACTICE_LEVELS.find((item) => item.id === level) || PRACTICE_LEVELS[2];

  useEffect(() => {
    if (user?.id) loadRandomPhoto();
    return () => {
      clearRecordingTimer();
      isRecordingRef.current = false;
      if (mediaRecorderRef.current && mediaRecorderRef.current.state !== 'inactive') {
        mediaRecorderRef.current.stop();
      }
      streamRef.current?.getTracks().forEach((track) => track.stop());
    };
  }, [user?.id]);

  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: `English picture-description speaking prompt ${nextIndex + 1}`,
          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 clearRecordingTimer = () => {
    if (timerRef.current) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
  };

  const startRecording = async () => {
    if (!navigator?.mediaDevices?.getUserMedia || typeof MediaRecorder === 'undefined') {
      setMediaError('Audio recording is not supported in this browser.');
      return;
    }

    setMediaError('');
    setTranscript('');
    setFeedback(null);
    setSpeechScores(null);
    setSpeechError('');
    chunksRef.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'
      : MediaRecorder.isTypeSupported('audio/webm')
        ? 'audio/webm'
        : '';
    const mr = mimeType ? new MediaRecorder(stream, { mimeType }) : new MediaRecorder(stream);
    mediaRecorderRef.current = mr;
    streamRef.current = stream;

    mr.ondataavailable = (event) => {
      if (event.data.size > 0) {
        chunksRef.current.push(event.data);
      }
    };

    mr.onstop = async () => {
      stream.getTracks().forEach((t) => t.stop());
      streamRef.current = null;
      const blob = new Blob(chunksRef.current, { type: mr.mimeType || 'audio/webm' });
      mediaRecorderRef.current = null;
      setStage('processing');

      if (!blob.size) {
        setMediaError('No audio was captured. Please try recording again.');
        setStage('transcript');
        return;
      }

      fetchSpeechScores(blob);
      try {
        const text = await transcribeAudio(blob);
        setTranscript(text.trim());
        setStage('transcript');
      } catch (error) {
        setMediaError(error?.message || 'Could not transcribe audio. Please try again.');
        setStage('transcript');
      }
    };

    isRecordingRef.current = true;
    recordingStartedAtRef.current = Date.now();
    timerRef.current = setInterval(() => {
      const elapsed = Math.min(
        MAX_RECORD_SECONDS,
        Math.floor((Date.now() - recordingStartedAtRef.current) / 1000)
      );
      setRecordingSeconds(elapsed);
      if (elapsed >= MAX_RECORD_SECONDS) {
        stopRecording();
      }
    }, 250);
    mr.start();
    setStage('recording');
  };

  function stopRecording() {
    if (!isRecordingRef.current && mediaRecorderRef.current?.state !== 'recording') return;
    clearRecordingTimer();
    isRecordingRef.current = false;
    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-recording'), { 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="flex min-h-screen flex-col overflow-x-hidden bg-[#FAF5F0] text-[#4A1429]">
      {!workspaceOnly && (
        <>
          <script
            type="application/ld+json"
            dangerouslySetInnerHTML={{ __html: JSON.stringify(photoModeJsonLd).replace(/</g, '\\u003c') }}
          />
          <CVHeader showPromotion={false} />
        </>
      )}
      <main className="flex-1">
        {!workspaceOnly && (
        <section className="relative overflow-hidden bg-[#380F17] text-white">
          <div className="relative mx-auto max-w-7xl px-5 py-14 sm:px-8 sm:py-16 lg:px-10 lg:py-20">
            <nav aria-label="Breadcrumb" className="mb-8 flex items-center gap-2 text-xs font-bold text-[#E6D3B1]/75">
              <Link href="/" className="transition hover:text-[#D4AF37]">Home</Link>
              <ChevronRight className="h-3.5 w-3.5" aria-hidden="true" />
              <span>Tools</span>
              <ChevronRight className="h-3.5 w-3.5" aria-hidden="true" />
              <span className="text-[#D4AF37]">Photo Mode</span>
            </nav>

            <motion.div initial={{ opacity: 0, y: 14 }} animate={{ opacity: 1, y: 0 }} className="grid gap-10 lg:grid-cols-[1.08fr_0.92fr] lg:items-center">
              <div className="min-w-0">
                <div className="inline-flex max-w-full items-center gap-2 rounded-2xl border border-[#D4AF37]/45 bg-[#D4AF37]/10 px-4 py-2 sm:rounded-full">
                  <Camera className="h-4 w-4 shrink-0 text-[#D4AF37]" aria-hidden="true" />
                  <span className="text-[10px] font-extrabold uppercase leading-5 tracking-[0.16em] text-[#E6D3B1] sm:text-[11px] sm:tracking-[0.2em]">Free A1–B2 English speaking practice</span>
                </div>
                <h1 className="mt-6 max-w-4xl text-4xl font-black leading-[1.03] tracking-[-0.04em] sm:text-5xl lg:text-6xl">
                  Picture Description <span className="text-[#D4AF37]">Speaking Practice</span> in English
                </h1>
                <p className="mt-6 max-w-3xl text-base leading-8 text-[#F5E9E0]/82 sm:text-lg">
                  Improve your English by describing real-life pictures aloud. Organise your ideas, speak with confidence and receive useful feedback on your vocabulary, grammar and fluency.
                </p>
                <Link href="/tools-dashboard/photo-mode" className="mt-8 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] shadow-[0_14px_32px_rgba(212,175,55,0.2)] transition hover:-translate-y-0.5 hover:bg-[#E0BE50]">
                  Start picture practice <ArrowRight className="h-4 w-4" aria-hidden="true" />
                </Link>
              </div>

              <div className="grid gap-3 sm:grid-cols-2">
                {[
                  [AudioLines, 'Speak naturally', 'Build spontaneous, connected English'],
                  [Languages, 'Use better language', 'Practise vocabulary and grammar in context'],
                  [Target, 'Choose your level', 'Clear A1, A2, B1 and B2 targets'],
                  [Sparkles, 'Review and improve', 'Turn every attempt into focused practice'],
                ].map(([Icon, title, text]) => (
                  <div key={title} className="rounded-2xl border border-white/12 bg-white/[0.07] p-5 backdrop-blur-sm">
                    <Icon className="h-6 w-6 text-[#D4AF37]" aria-hidden="true" />
                    <p className="mt-4 font-black">{title}</p>
                    <p className="mt-1 text-sm leading-6 text-[#F5E9E0]/70">{text}</p>
                  </div>
                ))}
              </div>
            </motion.div>
          </div>
        </section>
        )}

        {workspaceOnly && (
        <section id="photo-mode-practice" className="scroll-mt-8 border-b border-[#E7DCD5] bg-[#F6EEE8]">
          <ToolAccessGate toolKey="photo-description" toolName="Photo Mode" limit={10}>
          <div className="mx-auto max-w-7xl px-5 py-16 sm:px-8 lg:px-10 lg:py-20">
            <div className="mb-8 flex flex-col justify-between gap-5 lg:flex-row lg:items-end">
              <div className="max-w-3xl">
                <p className="text-xs font-extrabold uppercase tracking-[0.2em] text-[#9A7417]">Interactive Photo Mode</p>
                <h2 className="mt-3 text-3xl font-black tracking-[-0.03em] text-[#4A1429] sm:text-4xl">Choose your practice level</h2>
                <p className="mt-3 text-sm leading-7 text-[#6B4455] sm:text-base">Select a speaking target, study the photo and record a connected English description.</p>
              </div>
              <div className="inline-flex items-center gap-2 rounded-xl border border-[#E0D1C8] bg-white px-4 py-3 text-sm font-bold text-[#6B4455]">
                <Clock3 className="h-4 w-4 text-[#B48C24]" aria-hidden="true" /> Target: {selectedLevel.seconds}
              </div>
            </div>

            <div className="mb-6 grid grid-cols-2 gap-3 lg:grid-cols-4" aria-label="Choose your English practice level">
              {PRACTICE_LEVELS.map((item) => {
                const active = item.id === level;
                return (
                  <button
                    key={item.id}
                    type="button"
                    onClick={() => setLevel(item.id)}
                    aria-pressed={active}
                    className={`rounded-2xl border p-4 text-left transition ${active ? 'border-[#D4AF37] bg-[#4A1429] text-white shadow-[0_12px_28px_rgba(74,20,41,0.16)]' : 'border-[#E2D6CF] bg-white text-[#4A1429] hover:border-[#C8A83E]'}`}
                  >
                    <span className={`text-xs font-black uppercase tracking-[0.16em] ${active ? 'text-[#D4AF37]' : 'text-[#9A7417]'}`}>{item.label}</span>
                    <span className="mt-2 block text-sm font-black">{item.title}</span>
                    <span className={`mt-1 block text-xs leading-5 ${active ? 'text-white/65' : 'text-[#806471]'}`}>{item.target}</span>
                  </button>
                );
              })}
            </div>

            <div className="rounded-[2rem] border border-[#E1D4CC] bg-white p-4 shadow-[0_24px_70px_rgba(74,20,41,0.09)] sm:p-6 lg:p-8">
              <div className="flex flex-col gap-6 lg:flex-row lg: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="aspect-[4/3] overflow-hidden rounded-3xl shadow-xl ring-2 ring-[#D4B038] ring-offset-4 ring-offset-white"
            >
              {/* The generic alt preserves the exercise instead of revealing the scene. */}
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={photo.url} alt={photo.alt} className="h-full w-full object-cover" fetchPriority="high" />
            </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-3 flex flex-wrap items-center justify-between gap-2 text-xs font-semibold text-[#8B6B7A]">
              <span>Aim for {selectedLevel.seconds} and at least {MIN_WORDS} words.</span>
              <button type="button" onClick={nextPhoto} className="inline-flex items-center gap-1.5 rounded-lg px-2 py-1 text-[#4A1429] transition hover:bg-[#F6EEE8]">
                <RefreshCw className="h-3.5 w-3.5" aria-hidden="true" /> Try another picture
              </button>
            </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' }}>
                      Study the picture, organise your ideas, then press the microphone button and 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: '#4A1429',
                        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: '#4A1429' }}
                  >
                    <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 flex flex-col items-center justify-center text-center" style={{ minHeight: 280 }}>
                    <div className="relative mb-6 flex h-28 w-28 items-center justify-center">
                      <motion.div
                        className="absolute inset-0 rounded-full"
                        style={{ border: '2px solid rgba(212,176,56,0.42)' }}
                        animate={{ scale: [1, 1.18, 1], opacity: [0.65, 0.2, 0.65] }}
                        transition={{ repeat: Infinity, duration: 1.6, ease: 'easeInOut' }}
                      />
                      <div
                        className="relative z-10 flex h-20 w-20 items-center justify-center rounded-full"
                        style={{ background: 'rgba(74,20,41,0.08)', color: '#4A1429' }}
                      >
                        <Mic className="h-9 w-9" />
                      </div>
                    </div>

                    <p className="text-xs font-bold uppercase tracking-widest mb-3" style={{ color: '#8B6B7A' }}>
                      Listening
                    </p>
                    <div className="mb-5 flex h-12 items-end justify-center gap-1.5">
                      {Array.from({ length: 16 }).map((_, i) => (
                        <motion.span
                          key={i}
                          className="w-1.5 rounded-full"
                          style={{ background: i % 3 === 0 ? '#4A1429' : '#D4B038' }}
                          animate={{ height: [12, 34 - (i % 4) * 4, 14] }}
                          transition={{
                            repeat: Infinity,
                            duration: 0.72 + (i % 5) * 0.08,
                            delay: i * 0.04,
                            ease: 'easeInOut',
                          }}
                        />
                      ))}
                    </div>
                    <p className="text-sm font-semibold" style={{ color: '#6B4455' }}>
                      Recording audio. Your full transcription will appear after this step.
                    </p>
                  </div>

                  <div className="px-6 pb-6 flex items-center justify-between">
                    <div className="text-sm font-semibold" style={{ color: '#8B6B7A' }}>
                      {fmtTime(Math.max(0, MAX_RECORD_SECONDS - recordingSeconds))} remaining
                    </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: '#D4B038', color: '#3D0F22' }}
                    >
                      <StopCircle className="w-4 h-4" />
                      Stop and Transcribe
                    </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' }}>
                    Preparing your transcription, grammar, vocabulary, and fluency review. 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: '#FAF5F0', 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 }}>
                    {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>
                    )}
                    <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: '#4A1429', 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: '#4A1429' }}>
                    <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: '#D4B038', color: '#3D0F22' }}
                    >
                      Next Picture
                      <ChevronRight className="w-4 h-4" />
                    </motion.button>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        </div>
            </div>
          </div>
          </ToolAccessGate>
        </section>
        )}

        {!workspaceOnly && (
        <>
        <section className="bg-white">
          <div className="mx-auto max-w-7xl px-5 py-20 sm:px-8 lg:px-10 lg:py-24">
            <div className="mx-auto max-w-3xl text-center">
              <p className="text-xs font-extrabold uppercase tracking-[0.2em] text-[#9A7417]">A simple repeatable routine</p>
              <h2 className="mt-4 text-3xl font-black tracking-[-0.03em] text-[#4A1429] sm:text-4xl">How Photo Mode works</h2>
              <p className="mt-4 leading-8 text-[#735763]">Move from visual observation to connected speech in five focused steps. You can repeat the process with each new picture and compare how your language develops.</p>
            </div>
            <ol className="mt-12 grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
              {HOW_IT_WORKS.map(([title, text], index) => (
                <li key={title} className="relative rounded-2xl border border-[#E7DCD5] bg-[#FCF9F7] p-5">
                  <span className="flex h-9 w-9 items-center justify-center rounded-full bg-[#4A1429] text-xs font-black text-[#D4AF37]">{index + 1}</span>
                  <h3 className="mt-5 text-lg font-black text-[#4A1429]">{title}</h3>
                  <p className="mt-2 text-sm leading-6 text-[#735763]">{text}</p>
                </li>
              ))}
            </ol>
          </div>
        </section>

        <section className="bg-[#4A1429] text-white">
          <div className="mx-auto max-w-7xl px-5 py-20 sm:px-8 lg:px-10 lg:py-24">
            <div className="grid gap-10 lg:grid-cols-[0.72fr_1.28fr] lg:items-start">
              <div className="lg:sticky lg:top-24">
                <p className="text-xs font-extrabold uppercase tracking-[0.2em] text-[#D4AF37]">Practise with a purpose</p>
                <h2 className="mt-4 text-3xl font-black tracking-[-0.03em] sm:text-4xl">What skills does picture description improve?</h2>
                <p className="mt-5 leading-8 text-white/72">Describing pictures combines language knowledge with real-time communication. It helps learners turn vocabulary and grammar into an organised spoken response.</p>
              </div>
              <div className="grid gap-4 sm:grid-cols-2">
                {SPEAKING_SKILLS.map(([title, text], index) => {
                  const icons = [AudioLines, Languages, CheckCircle2, ListChecks, Eye, Brain];
                  const Icon = icons[index];
                  return (
                    <div key={title} className="rounded-2xl border border-white/12 bg-white/[0.07] p-6">
                      <Icon className="h-6 w-6 text-[#D4AF37]" aria-hidden="true" />
                      <h3 className="mt-4 text-lg font-black">{title}</h3>
                      <p className="mt-2 text-sm leading-7 text-white/68">{text}</p>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        </section>

        <section className="bg-[#F6EEE8]">
          <div className="mx-auto max-w-7xl px-5 py-20 sm:px-8 lg:px-10 lg:py-24">
            <div className="max-w-3xl">
              <p className="text-xs font-extrabold uppercase tracking-[0.2em] text-[#9A7417]">Step-by-step speaking framework</p>
              <h2 className="mt-4 text-3xl font-black tracking-[-0.03em] text-[#4A1429] sm:text-4xl">How to describe a picture in English</h2>
              <p className="mt-4 leading-8 text-[#735763]">A strong picture description is easier to follow when it moves from the overall scene to specific evidence. Use this six-part framework whenever you practise.</p>
            </div>
            <div className="mt-12 grid gap-5 md:grid-cols-2 lg:grid-cols-3">
              {DESCRIPTION_STEPS.map(([number, title, text, example]) => (
                <article key={number} className="rounded-3xl border border-[#E2D5CD] bg-white p-6 shadow-[0_14px_38px_rgba(74,20,41,0.06)]">
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-black tracking-[0.16em] text-[#B48C24]">{number}</span>
                    <CheckCircle2 className="h-5 w-5 text-[#8B1C1C]" aria-hidden="true" />
                  </div>
                  <h3 className="mt-5 text-xl font-black text-[#4A1429]">{title}</h3>
                  <p className="mt-3 text-sm leading-7 text-[#735763]">{text}</p>
                  <p className="mt-5 rounded-xl bg-[#F8F1EC] px-4 py-3 text-sm font-semibold italic leading-6 text-[#4A1429]">“{example}”</p>
                </article>
              ))}
            </div>
          </div>
        </section>

        <section className="bg-white">
          <div className="mx-auto grid max-w-7xl gap-8 px-5 py-20 sm:px-8 lg:grid-cols-2 lg:px-10 lg:py-24">
            <div className="rounded-[2rem] border border-[#E4D8D1] bg-[#FCF9F7] p-6 sm:p-8">
              <div className="flex items-center gap-3">
                <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-[#4A1429] text-[#D4AF37]"><Languages className="h-5 w-5" aria-hidden="true" /></div>
                <div>
                  <p className="text-xs font-extrabold uppercase tracking-[0.18em] text-[#9A7417]">Speak more confidently</p>
                  <h2 className="mt-1 text-2xl font-black text-[#4A1429]">Useful picture-description phrases</h2>
                </div>
              </div>
              <div className="mt-8 space-y-5">
                {PHRASE_GROUPS.map(([title, phrases]) => (
                  <div key={title} className="border-b border-[#E8DDD7] pb-5 last:border-0 last:pb-0">
                    <h3 className="font-black text-[#4A1429]">{title}</h3>
                    <div className="mt-3 flex flex-wrap gap-2">
                      {phrases.map((phrase) => <span key={phrase} className="rounded-full border border-[#E1D4CC] bg-white px-3 py-1.5 text-xs font-semibold text-[#6B4455]">{phrase}</span>)}
                    </div>
                  </div>
                ))}
              </div>
            </div>

            <div className="rounded-[2rem] border border-[#D4AF37]/45 bg-[#4A1429] p-6 text-white shadow-[0_22px_60px_rgba(74,20,41,0.18)] sm:p-8">
              <div className="flex items-center gap-3">
                <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-[#D4AF37] text-[#4A1429]"><BookOpen className="h-5 w-5" aria-hidden="true" /></div>
                <div>
                  <p className="text-xs font-extrabold uppercase tracking-[0.18em] text-[#D4AF37]">Language in context</p>
                  <h2 className="mt-1 text-2xl font-black">Grammar for describing pictures</h2>
                </div>
              </div>
              <div className="mt-8 space-y-5">
                {GRAMMAR_POINTS.map(([title, text]) => (
                  <div key={title} className="flex gap-3 border-b border-white/10 pb-5 last:border-0 last:pb-0">
                    <CheckCircle2 className="mt-0.5 h-5 w-5 shrink-0 text-[#D4AF37]" aria-hidden="true" />
                    <div>
                      <h3 className="font-black">{title}</h3>
                      <p className="mt-1 text-sm leading-6 text-white/68">{text}</p>
                    </div>
                  </div>
                ))}
              </div>
              <Link href="/grammar" className="mt-8 inline-flex items-center gap-2 text-sm font-black text-[#D4AF37] hover:underline">Explore English grammar lessons <ArrowRight className="h-4 w-4" /></Link>
            </div>
          </div>
        </section>

        <section className="border-y border-[#E5D8D0] bg-[#F2E9E3]">
          <div className="mx-auto max-w-7xl px-5 py-20 sm:px-8 lg:px-10 lg:py-24">
            <div className="mx-auto max-w-3xl text-center">
              <p className="text-xs font-extrabold uppercase tracking-[0.2em] text-[#9A7417]">Progress at your level</p>
              <h2 className="mt-4 text-3xl font-black tracking-[-0.03em] text-[#4A1429] sm:text-4xl">Picture speaking practice from A1 to B2</h2>
              <p className="mt-4 leading-8 text-[#735763]">Use a realistic speaking target rather than trying to produce the same kind of answer at every stage.</p>
            </div>
            <div className="mt-12 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
              {PRACTICE_LEVELS.map((item) => (
                <article key={item.id} className={`rounded-3xl border p-6 ${item.id === 'b1' ? 'border-[#D4AF37] bg-[#4A1429] text-white shadow-[0_20px_48px_rgba(74,20,41,0.16)]' : 'border-[#E1D4CC] bg-white text-[#4A1429]'}`}>
                  <div className="flex items-center justify-between">
                    <span className={`text-3xl font-black ${item.id === 'b1' ? 'text-[#D4AF37]' : 'text-[#8B1C1C]'}`}>{item.label}</span>
                    {item.id === 'b1' ? <span className="rounded-full bg-[#D4AF37] px-2.5 py-1 text-[10px] font-black uppercase tracking-wider text-[#4A1429]">Popular</span> : null}
                  </div>
                  <h3 className="mt-5 text-lg font-black">{item.title}</h3>
                  <p className={`mt-2 text-sm leading-6 ${item.id === 'b1' ? 'text-white/68' : 'text-[#735763]'}`}>{item.target}. Aim to speak for {item.seconds}.</p>
                </article>
              ))}
            </div>

            <div className="mt-8 grid overflow-hidden rounded-[2rem] border border-[#D4AF37]/50 bg-white shadow-[0_20px_55px_rgba(74,20,41,0.08)] lg:grid-cols-[0.8fr_1.2fr]">
              <div className="bg-[#4A1429] p-7 text-white sm:p-9">
                <GraduationCap className="h-8 w-8 text-[#D4AF37]" aria-hidden="true" />
                <p className="mt-6 text-xs font-extrabold uppercase tracking-[0.2em] text-[#D4AF37]">B1 focus mode</p>
                <h3 className="mt-3 text-2xl font-black">Practise a one-minute description</h3>
              </div>
              <div className="p-7 sm:p-9">
                <p className="leading-8 text-[#6B4455]">B1 learners can practise describing one photograph for approximately one minute. Focus on people, places, activities, objects and clear organisation. Try to connect your sentences instead of producing a list of isolated words.</p>
                <div className="mt-5 flex items-start gap-3 rounded-xl bg-[#F8F1EC] p-4 text-sm leading-6 text-[#6B4455]">
                  <ShieldCheck className="mt-0.5 h-5 w-5 shrink-0 text-[#9A7417]" aria-hidden="true" />
                  <p>Cambridge Veritas Photo Mode is an independent English-practice resource and is not an official Cambridge English assessment.</p>
                </div>
              </div>
            </div>
          </div>
        </section>

        <section className="bg-white">
          <div className="mx-auto max-w-7xl px-5 py-20 sm:px-8 lg:px-10 lg:py-24">
            <div className="grid gap-10 lg:grid-cols-[0.78fr_1.22fr] lg:items-start">
              <div>
                <p className="text-xs font-extrabold uppercase tracking-[0.2em] text-[#9A7417]">Key speaking vocabulary</p>
                <h2 className="mt-4 text-3xl font-black tracking-[-0.03em] text-[#4A1429] sm:text-4xl">Picture-description glossary</h2>
                <p className="mt-4 leading-8 text-[#735763]">Learn the terms that help you organise a visual description and understand feedback about your speaking.</p>
              </div>
              <dl className="overflow-hidden rounded-3xl border border-[#E2D6CF] bg-[#FCF9F7]">
                {GLOSSARY.map(([term, definition]) => (
                  <div key={term} className="grid gap-1 border-b border-[#E8DDD7] px-5 py-4 last:border-0 sm:grid-cols-[180px_1fr] sm:gap-6 sm:px-6">
                    <dt className="font-black text-[#4A1429]">{term}</dt>
                    <dd className="text-sm leading-6 text-[#735763]">{definition}</dd>
                  </div>
                ))}
              </dl>
            </div>
          </div>
        </section>

        <section className="bg-[#4A1429] text-white">
          <div className="mx-auto grid max-w-7xl gap-8 px-5 py-20 sm:px-8 lg:grid-cols-2 lg:px-10 lg:py-24">
            <div className="rounded-[2rem] border border-white/12 bg-white/[0.07] p-7 sm:p-9">
              <UsersRound className="h-8 w-8 text-[#D4AF37]" aria-hidden="true" />
              <p className="mt-6 text-xs font-extrabold uppercase tracking-[0.2em] text-[#D4AF37]">For teachers and trainees</p>
              <h2 className="mt-3 text-3xl font-black">An adaptable ESL speaking activity</h2>
              <p className="mt-5 leading-8 text-white/72">Use Photo Mode as a classroom warm-up, vocabulary prompt, pair-speaking task, homework activity or informal fluency check. Teachers can adapt the target time, language focus and follow-up questions to suit different learners.</p>
              <ul className="mt-6 grid gap-3 text-sm text-white/78 sm:grid-cols-2">
                {['Low-preparation speaking prompts', 'CEFR-level target setting', 'Grammar in a visual context', 'Repeatable reflection and feedback'].map((item) => <li key={item} className="flex items-start gap-2"><CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0 text-[#D4AF37]" />{item}</li>)}
              </ul>
              <Link href="/certifications/cambridge-veritas-certificate-in-TESOL" className="mt-8 inline-flex items-center gap-2 font-black text-[#D4AF37] hover:underline">Explore the 120-hour CVTE® TESOL programme <ArrowRight className="h-4 w-4" /></Link>
            </div>

            <div className="rounded-[2rem] border border-[#D4AF37]/35 bg-[#310B15] p-7 sm:p-9">
              <Lightbulb className="h-8 w-8 text-[#D4AF37]" aria-hidden="true" />
              <p className="mt-6 text-xs font-extrabold uppercase tracking-[0.2em] text-[#D4AF37]">Methodology</p>
              <h2 className="mt-3 text-3xl font-black">Developed for meaningful speaking practice</h2>
              <p className="mt-5 leading-8 text-white/72">The activity supports lexical retrieval, present continuous, prepositions, discourse organisation, spontaneous speaking, description and paraphrasing. It is designed to help learners notice language they can reuse in future conversations.</p>
              <div className="mt-7 border-t border-white/10 pt-6">
                <p className="font-black">Reviewed by Dr. Krishnatrya</p>
                <p className="mt-1 text-sm text-white/62">Lead Teacher Trainer & Programme Coordinator · Last reviewed October 2026</p>
                <a href="https://www.linkedin.com/in/krishnatrya" target="_blank" rel="noreferrer" className="mt-4 inline-flex items-center gap-2 text-sm font-black text-[#D4AF37] hover:underline">View professional profile <ArrowRight className="h-4 w-4" /></a>
              </div>
            </div>
          </div>
        </section>

        <section className="bg-[#F6EEE8]">
          <div className="mx-auto max-w-7xl px-5 py-20 sm:px-8 lg:px-10 lg:py-24">
            <div className="mx-auto max-w-3xl text-center">
              <p className="text-xs font-extrabold uppercase tracking-[0.2em] text-[#9A7417]">Keep developing your English</p>
              <h2 className="mt-4 text-3xl font-black tracking-[-0.03em] text-[#4A1429] sm:text-4xl">Continue practising</h2>
            </div>
            <div className="mt-12 grid gap-5 md:grid-cols-3">
              {[
                [AudioLines, 'Speech Analyser', 'Get detailed feedback on your pronunciation, fluency and spoken communication.', '/tools/speech-analyser', 'Analyse your speaking'],
                [BookOpen, 'Free English resources', 'Explore English activities, grammar support and practical resources for learners and teachers.', '/free-resources', 'Browse free resources'],
                [GraduationCap, 'CVTE® TESOL', 'Build methodology, lesson-planning and practical teaching skills through live professional training.', '/certifications/cambridge-veritas-certificate-in-TESOL', 'Explore TESOL training'],
              ].map(([Icon, title, text, href, label]) => (
                <article key={title} className="flex flex-col rounded-3xl border border-[#E2D6CF] bg-white p-6 shadow-[0_14px_36px_rgba(74,20,41,0.05)]">
                  <Icon className="h-7 w-7 text-[#9A7417]" aria-hidden="true" />
                  <h3 className="mt-5 text-xl font-black text-[#4A1429]">{title}</h3>
                  <p className="mt-3 flex-1 text-sm leading-7 text-[#735763]">{text}</p>
                  <Link href={href} className="mt-6 inline-flex items-center gap-2 text-sm font-black text-[#8B1C1C] hover:underline">{label} <ArrowRight className="h-4 w-4" /></Link>
                </article>
              ))}
            </div>

            <div className="mt-8 flex items-start gap-4 rounded-2xl border border-[#E0D1C8] bg-white p-5 sm:p-6">
              <LockKeyhole className="mt-0.5 h-6 w-6 shrink-0 text-[#9A7417]" aria-hidden="true" />
              <div>
                <h3 className="font-black text-[#4A1429]">Microphone and privacy</h3>
                <p className="mt-2 text-sm leading-7 text-[#735763]">Photo Mode requests microphone permission only when you start recording. Your audio is sent securely for transcription and speaking analysis so the tool can prepare feedback. Do not record sensitive personal information. See our <Link href="/privacy-policy" className="font-bold text-[#8B1C1C] underline underline-offset-2">Privacy Policy</Link> for information about processing and your data rights.</p>
              </div>
            </div>
          </div>
        </section>

        <section className="bg-white">
          <div className="mx-auto max-w-4xl px-5 py-20 sm:px-8 lg:px-10 lg:py-24">
            <div className="text-center">
              <p className="text-xs font-extrabold uppercase tracking-[0.2em] text-[#9A7417]">Picture-description FAQs</p>
              <h2 className="mt-4 text-3xl font-black tracking-[-0.03em] text-[#4A1429] sm:text-4xl">Questions learners and teachers ask</h2>
            </div>
            <div className="mt-12 space-y-3">
              {PHOTO_MODE_FAQS.map(({ question, answer }, index) => (
                <details key={question} className="group rounded-2xl border border-[#E4D8D1] bg-[#FCF9F7] open:border-[#D4AF37] open:bg-white" open={index === 0}>
                  <summary className="flex cursor-pointer list-none items-center justify-between gap-4 px-5 py-5 font-black text-[#4A1429] sm:px-6">
                    {question}
                    <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[#F0E5DF] text-[#8B1C1C] transition group-open:rotate-45">+</span>
                  </summary>
                  <p className="px-5 pb-6 text-sm leading-7 text-[#735763] sm:px-6">{answer}</p>
                </details>
              ))}
            </div>
          </div>
        </section>

        <section className="border-t border-[#D4AF37]/25 bg-[#380F17] text-white">
          <div className="mx-auto flex max-w-7xl flex-col items-start justify-between gap-7 px-5 py-14 sm:px-8 lg:flex-row lg:items-center lg:px-10">
            <div className="max-w-3xl">
              <p className="text-xs font-extrabold uppercase tracking-[0.2em] text-[#D4AF37]">Ready for another attempt?</p>
              <h2 className="mt-3 text-3xl font-black tracking-[-0.03em]">Choose a picture and speak for one minute.</h2>
              <p className="mt-3 text-sm leading-7 text-white/68">Use the framework above, record your response and turn the feedback into one clear improvement goal.</p>
            </div>
            <Link href="/tools-dashboard/photo-mode" className="inline-flex min-h-12 shrink-0 items-center justify-center gap-2 rounded-xl bg-[#D4AF37] px-6 py-3 text-sm font-black text-[#380F17] transition hover:bg-[#E0BE50]">Open Photo Mode <ArrowRight className="h-4 w-4" /></Link>
          </div>
        </section>
        </>
        )}
      </main>

      {!workspaceOnly && <CVFooter />}
    </div>
  );
}
