'use client'

import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { ArrowLeft, ChevronDown, ChevronUp, Info, Mic, TrendingUp, MessageCircle, BookOpen, Award, ArrowRight, Play, X, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useNavigate } from '@/lib/nextRouterAdapter';

const internationalTests = [
  { name: 'IELTS', label: 'Speaking score predictor', value: '8.5', min: 0, max: 9, percent: 94, status: 'Outstanding', color: '#DC2626' },
  { name: 'TOEFL', label: 'Speaking score predictor', value: '28', min: 0, max: 30, percent: 93, status: 'Outstanding', color: '#059669' },
  { name: 'CEFR', label: 'Speaking score predictor', value: 'C2', min: 'A1', max: 'C2', percent: 100, status: 'Proficient', color: '#2563EB' },
  { name: 'Pearson PTE', label: 'Speaking score predictor', value: '87', min: 0, max: 90, percent: 97, status: 'Mastery', color: '#7C3AED' },
  { name: 'Duolingo', label: 'Speaking score predictor', value: '120', min: 10, max: 160, percent: 75, status: 'Advanced', color: '#059669' },
];

const skillTabs = [
  { id: 'pronunciation', label: 'Pronunciation', level: 'Proficient', color: '#A73121', icon: Mic },
  { id: 'intonation', label: 'Intonation', level: 'Proficient', color: '#D4B038', icon: TrendingUp },
  { id: 'fluency', label: 'Fluency', level: 'Proficient', color: '#2563EB', icon: MessageCircle },
  { id: 'grammar', label: 'Grammar', level: 'Advanced', color: '#059669', icon: BookOpen },
  { id: 'vocabulary', label: 'Vocabulary', level: 'Advanced', color: '#7C3AED', icon: Award },
];

const phonemeSkills = ['/z/', '/æ/', '/w/', '/p/'];

const transcript = [
  { time: '00:00:00', text: 'One of my good friends is Sasha. She is, um, an amazing lady. She recently got married. We met at an audition. Uh, she matters to me because' },
  { time: '00:00:13', text: 'she is very open-minded and she speaks her mind.' },
  { time: '00:00:18', text: "And she's very honest with me and most importantly, she gives me the space to be myself. Um, we have gone on, uh, a lot of coffee dates with each other and, uh," },
  { time: '00:00:30', text: "I particularly like this person because she inspires me to be a good human being every single day of my life." },
];

function SpeedometerGauge({ wpm = 137 }) {
  const [animated, setAnimated] = React.useState(false);

  React.useEffect(() => {
    const t = setTimeout(() => setAnimated(true), 300);
    return () => clearTimeout(t);
  }, []);

  // Gauge goes from 60 to 240 wpm, mapped to -90deg..+90deg (180deg arc)
  const min = 60, max = 240;
  const clampedWpm = Math.min(Math.max(wpm, min), max);
  const angleDeg = -90 + ((clampedWpm - min) / (max - min)) * 180;
  const needleAngle = animated ? angleDeg : -90;

  // Arc segments colours: red(60-80), orange(80-100), yellow(100-120), green(120-180), yellow(180-200), orange(200-220), red(220-240)
  const cx = 100, cy = 90, r = 70;
  const segments = [
    { from: 60,  to: 80,  color: '#DC2626' },
    { from: 80,  to: 100, color: '#F97316' },
    { from: 100, to: 120, color: '#EAB308' },
    { from: 120, to: 180, color: '#16A34A' },
    { from: 180, to: 200, color: '#EAB308' },
    { from: 200, to: 220, color: '#F97316' },
    { from: 220, to: 240, color: '#DC2626' },
  ];

  const toRad = (deg) => (deg * Math.PI) / 180;
  const wpmToAngle = (w) => -180 + ((w - min) / (max - min)) * 180; // -180 to 0 (left to right semicircle)

  const arcPath = (fromWpm, toWpm, radius) => {
    const a1 = toRad(wpmToAngle(fromWpm));
    const a2 = toRad(wpmToAngle(toWpm));
    const x1 = cx + radius * Math.cos(a1);
    const y1 = cy + radius * Math.sin(a1);
    const x2 = cx + radius * Math.cos(a2);
    const y2 = cy + radius * Math.sin(a2);
    const largeArc = toWpm - fromWpm > (max - min) / 2 ? 1 : 0;
    return `M ${x1} ${y1} A ${radius} ${radius} 0 ${largeArc} 1 ${x2} ${y2}`;
  };

  const tickLabels = [60, 80, 100, 120, 140, 160, 180, 200, 220, 240];

  return (
    <svg viewBox="0 0 200 110" className="w-full max-w-[220px]">
      {/* Segments */}
      {segments.map((seg, i) => (
        <path
          key={i}
          d={arcPath(seg.from, seg.to, r)}
          fill="none"
          stroke={seg.color}
          strokeWidth="14"
          strokeLinecap="butt"
        />
      ))}

      {/* Tick labels */}
      {tickLabels.map((w) => {
        const angle = toRad(wpmToAngle(w));
        const lx = cx + (r + 14) * Math.cos(angle);
        const ly = cy + (r + 14) * Math.sin(angle);
        return (
          <text key={w} x={lx} y={ly} textAnchor="middle" dominantBaseline="middle" fontSize="7" fill="#6B5D52" fontWeight="600">
            {w}
          </text>
        );
      })}

      {/* Needle */}
      <g style={{ transformOrigin: `${cx}px ${cy}px`, transform: `rotate(${needleAngle}deg)`, transition: 'transform 1.4s cubic-bezier(0.34,1.56,0.64,1)' }}>
        <line x1={cx} y1={cy} x2={cx + r - 8} y2={cy} stroke="#1F2937" strokeWidth="2.5" strokeLinecap="round" />
        <circle cx={cx} cy={cy} r="5" fill="#1F2937" />
      </g>
    </svg>
  );
}

const cefrLevels = [
  { level: 'C2', percent: 1,  color: '#1E40AF' },
  { level: 'C1', percent: 2,  color: '#3B82F6' },
  { level: 'B2', percent: 8,  color: '#60A5FA' },
  { level: 'B1', percent: 8,  color: '#93C5FD' },
  { level: 'A2', percent: 17, color: '#BFDBFE' },
  { level: 'A1', percent: 60, color: '#DBEAFE' },
];

function VocabularyHighlights({ onVideoClick }) {
  return (
    <div className="flex flex-col md:flex-row gap-4">
      {/* Score box */}
      <div className="flex flex-col items-center justify-center border-2 border-[#7C3AED] rounded-xl p-6 bg-[#F5F3FF] md:w-48 flex-shrink-0">
        <div className="w-20 h-20 bg-[#7C3AED] rounded-xl flex items-center justify-center mb-3 shadow-md">
          <span className="text-2xl font-extrabold text-white">85%</span>
        </div>
        <div className="text-sm font-bold text-[#6B5D52]">Your Level</div>
        <div className="text-base font-extrabold text-[#7C3AED] mt-1">Advanced</div>
      </div>

      {/* CEFR Distribution */}
      <div className="flex-1 bg-[#FAF5F0] rounded-xl border border-[#E5DDD5] p-4">
        <div className="flex items-center gap-1.5 mb-1">
          <h4 className="text-sm font-extrabold text-[#4A1429]">Vocabulary Distribution</h4>
          <Info className="w-3.5 h-3.5 text-[#6B5D52]" />
        </div>
        <p className="text-xs text-[#6B5D52] mb-3 leading-relaxed">
          Using advanced Vocabulary (CEFR levels B2, C1 and C2) adds colour and flair to your delivery.
        </p>
        <div className="flex items-start gap-4">
          <div className="text-center">
            <div className="text-2xl font-extrabold text-[#3B82F6]">6%</div>
            <div className="text-[10px] text-[#6B5D52] font-medium">Advanced<br/>Vocabulary</div>
          </div>
          <div className="flex-1 space-y-1.5">
            {cefrLevels.map((item) => (
              <div key={item.level} className="flex items-center gap-2">
                <div className="w-7 h-7 rounded-full flex items-center justify-center text-white text-[10px] font-bold flex-shrink-0" style={{ backgroundColor: item.color }}>
                  {item.level}
                </div>
                <div className="flex-1 h-5 bg-gray-100 rounded-full overflow-hidden relative">
                  <motion.div
                    initial={{ width: 0 }}
                    animate={{ width: `${item.percent}%` }}
                    transition={{ duration: 0.9, ease: 'easeOut', delay: cefrLevels.indexOf(item) * 0.08 }}
                    className="h-full rounded-full flex items-center justify-end pr-1.5"
                    style={{ backgroundColor: item.color, minWidth: item.percent > 0 ? '1.5rem' : 0 }}
                  >
                    <span className="text-[9px] font-bold" style={{ color: item.level === 'A2' || item.level === 'A1' ? '#1E40AF' : '#fff' }}>
                      {item.percent}%
                    </span>
                  </motion.div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Suggestions */}
      <div className="flex-1 bg-[#FAF5F0] rounded-xl border border-[#E5DDD5] p-4">
        <h4 className="text-sm font-extrabold text-[#4A1429] mb-2">Suggestions for Improvement</h4>
        <p className="text-xs text-[#6B5D52] mb-3 leading-relaxed">
          Exploring high-level synonyms will help you expand your Active Vocabulary Bank.
        </p>
        <div onClick={() => onVideoClick('NsVKkTVfxCE')} className="flex items-center gap-3 bg-white rounded-xl border border-[#E5DDD5] p-2 cursor-pointer hover:bg-[#F5EFE7] transition-colors">
          <div className="w-12 h-9 rounded-lg overflow-hidden flex-shrink-0 bg-gray-200 relative">
            <img src="https://images.unsplash.com/photo-1519791883288-dc8bd696e667?w=100&h=70&fit=crop" alt="Vocabulary tutorial" className="w-full h-full object-cover" />
            <div className="absolute inset-0 flex items-center justify-center bg-black/30"><Play className="w-3 h-3 text-white" /></div>
          </div>
          <span className="text-xs font-semibold text-[#4A1429]">Vocabulary tutorial</span>
        </div>
      </div>
    </div>
  );
}

function GrammarHighlights() {
  const suggestions = [
    'Using a mix of both simple and complex grammatical structures will allow you to express complex ideas with clarity while remaining direct and impactful!',
    'Use the active voice as often as possible. This will add punch and clarity to your speech!',
  ];

  return (
    <div className="flex flex-col md:flex-row gap-4">
      {/* Score box */}
      <div className="flex flex-col items-center justify-center border-2 border-[#059669] rounded-xl p-6 bg-[#F0FDF4] md:w-48 flex-shrink-0">
        <div className="w-20 h-20 bg-[#059669] rounded-xl flex items-center justify-center mb-3 shadow-md">
          <span className="text-2xl font-extrabold text-white">80%</span>
        </div>
        <div className="text-sm font-bold text-[#6B5D52]">Your Level</div>
        <div className="text-base font-extrabold text-[#059669] mt-1">Advanced</div>
      </div>

      {/* Suggestions */}
      <div className="flex-1 bg-[#FAF5F0] rounded-xl border border-[#E5DDD5] p-5">
        <h4 className="text-sm font-extrabold text-[#4A1429] mb-3">Suggestions for Improvement</h4>
        <div className="space-y-3">
          {suggestions.map((s, i) => (
            <div key={i} className="flex items-start gap-2 text-xs text-[#6B5D52] leading-relaxed">
              <div className="w-4 h-4 rounded-full border-2 border-[#059669] flex-shrink-0 mt-0.5" />
              <span>{s}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function AnimatedNumber({ target, suffix = '' }) {
  const [value, setValue] = React.useState(0);

  React.useEffect(() => {
    setValue(0);
    const duration = 1200;
    const steps = 40;
    const increment = target / steps;
    let current = 0;
    const timer = setInterval(() => {
      current += increment;
      if (current >= target) {
        setValue(target);
        clearInterval(timer);
      } else {
        setValue(Math.floor(current));
      }
    }, duration / steps);
    return () => clearInterval(timer);
  }, [target]);

  return <span>{value}{suffix}</span>;
}

function FluencyHighlights({ onVideoClick }) {
  return (
    <div className="flex flex-col md:flex-row gap-4">
      {/* Score box */}
      <div className="flex flex-col items-center justify-center border-2 border-[#16A34A] rounded-xl p-6 bg-[#F0FDF4] md:w-48 flex-shrink-0">
        <div className="w-20 h-20 bg-[#16A34A] rounded-xl flex items-center justify-center mb-3 shadow-md">
          <span className="text-2xl font-extrabold text-white">90%</span>
        </div>
        <div className="text-sm font-bold text-[#6B5D52]">Your Level</div>
        <div className="text-base font-extrabold text-[#16A34A] mt-1">Proficient</div>
      </div>

      {/* Pace Score gauge */}
      <div className="flex-1 flex flex-col items-center justify-center bg-[#FAF5F0] rounded-xl border border-[#E5DDD5] p-4 text-center">
        <div className="text-sm font-extrabold text-[#4A1429] mb-1">Pace Score</div>
        <SpeedometerGauge wpm={137} />
        <div className="text-xl font-extrabold text-[#4A1429] -mt-1">137 wpm</div>
        <div className="text-sm font-extrabold text-[#16A34A]">Good Pace</div>
      </div>

      {/* Suggestions */}
      <div className="flex-1 bg-[#FAF5F0] rounded-xl border border-[#E5DDD5] p-4">
        <h4 className="text-sm font-extrabold text-[#4A1429] mb-1">Suggestions for Improvement</h4>
        <p className="text-xs text-[#6B5D52] mb-3 leading-relaxed">
          Maintaining your pace between 120 wpm and 180 wpm will help you keep your audience engaged.
        </p>
        <div onClick={() => onVideoClick('-oQXdfyA9JI')} className="flex items-center gap-3 bg-white rounded-xl border border-[#E5DDD5] p-2 cursor-pointer hover:bg-[#F5EFE7] transition-colors">
          <div className="w-12 h-9 rounded-lg overflow-hidden flex-shrink-0 bg-gray-200 relative">
            <img src="https://images.unsplash.com/photo-1508700115892-45ecd05ae2ad?w=100&h=70&fit=crop" alt="Video tutorial" className="w-full h-full object-cover" />
            <div className="absolute inset-0 flex items-center justify-center bg-black/30"><Play className="w-3 h-3 text-white" /></div>
          </div>
          <span className="text-xs font-semibold text-[#4A1429]">Video tutorial for Fluency skill</span>
        </div>
      </div>
    </div>
  );
}

const rephrasedText = "One of my closest friends is Sasha — a truly remarkable woman who recently celebrated her wedding. We first crossed paths at an audition, and she has since become someone I deeply cherish. She is open-minded, honest, and encourages me to be my most authentic self. We have shared countless coffee outings, and I admire her deeply because she consistently inspires me to be a better human being.";

function TranscriptWithRephrase({ transcript }) {
  const [isLoading, setIsLoading] = useState(false);
  const [rephrased, setRephrased] = useState(false);
  const [displayedWords, setDisplayedWords] = useState([]);

  const handleRephrase = () => {
    if (rephrased || isLoading) return;
    setIsLoading(true);
    setTimeout(() => {
      setIsLoading(false);
      setRephrased(true);
      const words = rephrasedText.split(' ');
      let i = 0;
      const interval = setInterval(() => {
        setDisplayedWords(words.slice(0, i + 1));
        i++;
        if (i >= words.length) clearInterval(interval);
      }, 60);
    }, 1200);
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: 0.35 }}
      className="bg-white rounded-2xl shadow-md border border-[#E5DDD5] overflow-hidden"
    >
      <div className="bg-gradient-to-r from-[#4A1429] to-[#5A1839] px-6 py-4">
        <h3 className="text-base font-extrabold text-white">📝 Transcript</h3>
      </div>
      <div className="p-6 grid md:grid-cols-2 gap-6">
        <div className="space-y-4">
          {transcript.map((entry, i) => (
            <div key={i}>
              <div className="text-xs font-mono text-[#6B5D52] mb-1 flex items-center gap-1">
                <span className="text-[#D4B038]">⏱</span> {entry.time}
              </div>
              <p className="text-sm text-[#4A1429] leading-relaxed">{entry.text}</p>
            </div>
          ))}
        </div>
        <div className="flex flex-col items-start bg-[#FAF5F0] rounded-xl border border-[#E5DDD5] p-6 gap-4 min-h-[180px]">
          {!rephrased && !isLoading && (
            <>
              <div className="flex items-center gap-3 w-full">
                <div className="w-10 h-10 bg-[#4A1429] rounded-full flex items-center justify-center flex-shrink-0">
                  <span className="text-[#D4B038] font-extrabold text-sm">CV</span>
                </div>
                <p className="text-sm text-[#6B5D52] leading-relaxed">
                  Your speech could be better with the help of Cambridge Veritas. Click below to get a rephrased version.
                </p>
              </div>
              <Button onClick={handleRephrase} className="bg-[#4A1429] hover:bg-[#3A1020] text-white font-bold px-6 py-2 rounded-lg shadow-md text-sm w-full">
                Rephrase my speech
              </Button>
            </>
          )}
          {isLoading && (
            <div className="flex flex-col items-center justify-center w-full h-full gap-3 py-4">
              <Loader2 className="w-8 h-8 text-[#4A1429] animate-spin" />
              <p className="text-sm text-[#6B5D52] font-medium">AI is rephrasing your speech...</p>
            </div>
          )}
          {rephrased && (
            <div className="w-full">
              <div className="flex items-center gap-2 mb-3">
                <div className="w-7 h-7 bg-[#4A1429] rounded-full flex items-center justify-center flex-shrink-0">
                  <span className="text-[#D4B038] font-extrabold text-xs">CV</span>
                </div>
                <span className="text-xs font-bold text-[#4A1429]">Cambridge Veritas Suggestion</span>
              </div>
              <p className="text-sm text-[#4A1429] leading-relaxed break-words whitespace-pre-wrap max-w-full">
                {displayedWords.map((word, i) => (
                  <motion.span
                    key={i}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    className="mr-1"
                  >
                    {word}
                  </motion.span>
                ))}
                {displayedWords.length < rephrasedText.split(' ').length && (
                  <span className="inline-block w-0.5 h-4 bg-[#4A1429] animate-pulse ml-0.5 align-middle" />
                )}
              </p>
            </div>
          )}
        </div>
      </div>
    </motion.div>
  );
}

function YouTubeModal({ videoId, onClose }) {
  return (
    <AnimatePresence>
      {videoId && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4"
          onClick={onClose}
        >
          <motion.div
            initial={{ scale: 0.9 }}
            animate={{ scale: 1 }}
            exit={{ scale: 0.9 }}
            className="relative w-full max-w-2xl bg-black rounded-2xl overflow-hidden shadow-2xl"
            onClick={e => e.stopPropagation()}
          >
            <button onClick={onClose} className="absolute top-3 right-3 z-10 w-8 h-8 bg-black/60 hover:bg-black rounded-full flex items-center justify-center text-white">
              <X className="w-4 h-4" />
            </button>
            <div className="aspect-video">
              <iframe
                src={`https://www.youtube.com/embed/${videoId}?autoplay=1`}
                className="w-full h-full"
                allow="autoplay; encrypted-media"
                allowFullScreen
              />
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}

export default function ResultPage() {
  const navigate = useNavigate();
  const [showComparison, setShowComparison] = useState(false);
  const [activeSkill, setActiveSkill] = useState('pronunciation');
  const [youtubeVideoId, setYoutubeVideoId] = useState(null);
  const overallScore = 87;

  return (
    <div className="min-h-screen bg-[#FAF5F0]">
      <YouTubeModal videoId={youtubeVideoId} onClose={() => setYoutubeVideoId(null)} />
      {/* Header */}
      <div className="bg-gradient-to-r from-[#4A1429] to-[#5A1839] text-white sticky top-0 z-20 shadow-xl border-b-4 border-[#D4B038]">
        <div className="max-w-4xl mx-auto px-4 py-4 flex items-center justify-between">
          <button
            onClick={() => navigate(-1)}
            className="flex items-center gap-2 text-white/80 hover:text-white transition-colors"
          >
            <ArrowLeft className="w-5 h-5" />
            <span className="font-medium text-sm">Back</span>
          </button>
          <div className="text-xl font-extrabold text-[#D4B038]">Your Results</div>
          <div className="w-16" />
        </div>
      </div>

      <div className="max-w-4xl mx-auto px-4 py-6 space-y-6">

        {/* Overall Score Card */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-white rounded-2xl shadow-md border border-[#E5DDD5] p-6 flex flex-col md:flex-row items-center gap-6"
        >
          {/* Circle */}
          <div className="relative flex-shrink-0" style={{ width: 140, height: 140 }}>
            <svg className="w-full h-full -rotate-90" viewBox="0 0 140 140">
              <circle cx="70" cy="70" r="58" fill="none" stroke="#F5EFE7" strokeWidth="14" />
              <motion.circle
                cx="70" cy="70" r="58"
                fill="none" stroke="#4A1429" strokeWidth="14"
                strokeLinecap="round"
                strokeDasharray={2 * Math.PI * 58}
                initial={{ strokeDashoffset: 2 * Math.PI * 58 }}
                animate={{ strokeDashoffset: 2 * Math.PI * 58 * (1 - overallScore / 100) }}
                transition={{ duration: 1.2, ease: 'easeOut' }}
              />
            </svg>
            <div className="absolute inset-0 flex flex-col items-center justify-center">
              <div className="text-xs font-bold text-[#6B5D52] mb-0.5">Proficient</div>
              <div className="text-3xl font-extrabold text-[#4A1429]">{overallScore}%</div>
            </div>
          </div>

          {/* Text */}
          <div className="flex-1 text-center md:text-left">
            <h2 className="text-xl font-extrabold text-[#4A1429] mb-1">Overall Speaking Score</h2>
            <p className="text-[#D4B038] font-bold text-base mb-2">Your level is Proficient. You're moving up in the world!</p>
            <p className="text-sm text-[#6B5D52] leading-relaxed">
              Ever wonder how your Overall Speaking Score relates to other scoring systems? The collapsible section below has all the answers you're looking for! Our English Speaking Score Predictor helps you compare your performance with other recognised scoring systems for English proficiency. Check it out! 👇
            </p>
          </div>
        </motion.div>

        {/* Compare Score Section */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="bg-white rounded-2xl shadow-md border border-[#E5DDD5] overflow-hidden"
        >
          <button
            onClick={() => setShowComparison(!showComparison)}
            className="w-full flex items-center justify-between px-6 py-4 hover:bg-[#FAF5F0] transition-colors"
          >
            <div className="flex items-center gap-2">
              <h3 className="text-base font-extrabold text-[#4A1429]">Compare your score with other international tests</h3>
              <Info className="w-4 h-4 text-[#6B5D52]" />
            </div>
            {showComparison ? <ChevronUp className="w-5 h-5 text-[#4A1429]" /> : <ChevronDown className="w-5 h-5 text-[#4A1429]" />}
          </button>

          <AnimatePresence>
            {showComparison && (
              <motion.div
                initial={{ height: 0, opacity: 0 }}
                animate={{ height: 'auto', opacity: 1 }}
                exit={{ height: 0, opacity: 0 }}
                className="overflow-hidden border-t border-[#E5DDD5]"
              >
                <div className="p-4 grid grid-cols-2 md:grid-cols-5 gap-3">
                  {internationalTests.map((test, i) => (
                    <motion.div
                      key={test.name}
                      initial={{ opacity: 0, scale: 0.9 }}
                      animate={{ opacity: 1, scale: 1 }}
                      transition={{ delay: i * 0.07 }}
                      className="bg-[#FAF5F0] rounded-xl p-3 border border-[#E5DDD5] text-center"
                    >
                      <div className="text-xs font-bold text-[#6B5D52] mb-0.5">{test.name}</div>
                      <div className="text-[10px] text-[#6B5D52] mb-2">{test.label}</div>
                      <div className="text-2xl font-extrabold mb-1" style={{ color: test.color }}>{test.value}</div>
                      <div className="flex justify-between text-[9px] text-[#6B5D52] mb-1">
                        <span>{test.min}</span><span>{test.max}</span>
                      </div>
                      <div className="h-1.5 bg-gray-100 rounded-full overflow-hidden mb-2">
                        <div className="h-full rounded-full" style={{ width: `${test.percent}%`, backgroundColor: test.color }} />
                      </div>
                      <div className="text-xs font-bold" style={{ color: test.color }}>{test.status}</div>
                    </motion.div>
                  ))}
                </div>
              </motion.div>
            )}
          </AnimatePresence>
        </motion.div>

        {/* Score Breakdown */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="bg-white rounded-2xl shadow-md border border-[#E5DDD5] overflow-hidden"
        >
          <div className="px-6 py-4 border-b border-[#E5DDD5] flex items-center justify-between">
            <div>
              <h3 className="text-base font-extrabold text-[#4A1429]">Score Breakdown</h3>
              <p className="text-xs text-[#6B5D52] mt-0.5">Focus on your Intonation to sound more natural when you speak.</p>
            </div>
            <button
              onClick={() => navigate('/tools/score-details')}
              className="flex items-center gap-1 text-[#D4B038] hover:text-[#BFA030] font-bold text-sm transition-colors whitespace-nowrap"
            >
              Click to see details <ArrowRight className="w-4 h-4" />
            </button>
          </div>

          {/* Skill Tabs */}
          <div className="flex overflow-x-auto border-b border-[#E5DDD5]">
            {skillTabs.map((skill) => {
              const Icon = skill.icon;
              const isActive = activeSkill === skill.id;
              return (
                <button
                  key={skill.id}
                  onClick={() => setActiveSkill(skill.id)}
                  className={`flex items-center gap-2 px-4 py-3 text-sm whitespace-nowrap transition-all border-b-2 flex-1 justify-center ${
                    isActive ? 'border-[#4A1429] text-[#4A1429] font-bold bg-[#FAF5F0]' : 'border-transparent text-[#6B5D52] hover:bg-[#FAF5F0]'
                  }`}
                >
                  <Icon className="w-3.5 h-3.5" style={{ color: isActive ? skill.color : undefined }} />
                  <div className="text-left">
                    <div className="font-semibold text-xs">{skill.label}</div>
                    <div className="text-[10px]" style={{ color: skill.color }}>{skill.level}</div>
                  </div>
                </button>
              );
            })}
          </div>

          {/* Tab Content */}
          <div className="p-6">
            {activeSkill === 'fluency' ? (
              <FluencyHighlights onVideoClick={setYoutubeVideoId} />
            ) : activeSkill === 'grammar' ? (
              <GrammarHighlights />
            ) : activeSkill === 'vocabulary' ? (
              <VocabularyHighlights onVideoClick={setYoutubeVideoId} />
            ) : activeSkill === 'intonation' ? (
              /* Intonation Highlights */
              <div className="flex flex-col md:flex-row gap-4">
                {/* Score box */}
                <div className="flex flex-col items-center justify-center border-2 border-[#D4B038] rounded-xl p-6 bg-[#FFFBEB] md:w-48 flex-shrink-0">
                  <div className="w-20 h-20 bg-[#D4B038] rounded-xl flex items-center justify-center mb-3 shadow-md">
                    <span className="text-2xl font-extrabold text-white">90%</span>
                  </div>
                  <div className="text-sm font-bold text-[#6B5D52]">Your Level</div>
                  <div className="text-base font-extrabold text-[#D4B038] mt-1">Proficient</div>
                </div>

                {/* Pitch variation + suggestions */}
                <div className="flex-1 flex flex-col md:flex-row gap-4">
                  {/* Average Pitch */}
                  <div className="flex-1 flex flex-col items-center justify-center bg-[#FAF5F0] rounded-xl border border-[#E5DDD5] p-4 text-center">
                    <div className="flex items-center gap-1.5 mb-2">
                      <span className="text-sm font-extrabold text-[#4A1429]">Average Pitch Variation</span>
                      <Info className="w-3.5 h-3.5 text-[#6B5D52]" />
                    </div>
                    <div className="text-3xl font-extrabold text-[#D4B038] mb-2"><AnimatedNumber target={37} suffix=" Hz" /></div>
                    <div className="flex items-end gap-0.5 mb-2 h-10">
                      {[4,6,8,12,10,14,16,18,14,12,16,20,18,16,14,12,10,8,10,14].map((h, i) => (
                        <div key={i} className="w-1.5 rounded-sm" style={{ height: `${h * 2}px`, backgroundColor: '#D4B038', opacity: 0.8 }} />
                      ))}
                    </div>
                    <div className="text-sm font-extrabold text-[#D4B038]">Monotonous</div>
                  </div>

                  {/* Suggestions */}
                  <div className="flex-1 bg-[#FAF5F0] rounded-xl border border-[#E5DDD5] p-4">
                    <h4 className="text-sm font-extrabold text-[#4A1429] mb-1">Suggestions for Improvement</h4>
                    <p className="text-xs text-[#6B5D52] mb-3 leading-relaxed">
                      For optimal results, make sure your pitch variation is between 50Hz and 150Hz.
                    </p>
                    <div onClick={() => setYoutubeVideoId('zp0TGDymBb0')} className="flex items-center gap-3 bg-white rounded-xl border border-[#E5DDD5] p-2 cursor-pointer hover:bg-[#F5EFE7] transition-colors">
                      <div className="w-12 h-9 rounded-lg overflow-hidden flex-shrink-0 bg-gray-200 relative">
                        <img src="https://images.unsplash.com/photo-1516450360452-9312f5e86fc7?w=100&h=70&fit=crop" alt="Video tutorial" className="w-full h-full object-cover" />
                        <div className="absolute inset-0 flex items-center justify-center bg-black/30"><Play className="w-3 h-3 text-white" /></div>
                      </div>
                      <span className="text-xs font-semibold text-[#4A1429]">Video tutorial 'Intonation'</span>
                    </div>
                  </div>
                </div>
              </div>
            ) : (
              /* Default: Pronunciation by skill */
              <div className="grid md:grid-cols-3 gap-4">
                <div className="flex flex-col items-center justify-center border-2 border-[#A73121] rounded-xl p-6 bg-[#FFF5F5]">
                  <div className="w-20 h-20 bg-[#A73121] rounded-xl flex items-center justify-center mb-3 shadow-md">
                    <span className="text-2xl font-extrabold text-white">92%</span>
                  </div>
                  <div className="text-sm font-bold text-[#6B5D52]">Your Level</div>
                  <div className="text-base font-extrabold text-[#A73121] mt-1">Proficient</div>
                </div>

                <div className="md:col-span-2">
                  <div className="flex items-center gap-2 mb-3">
                    <h4 className="text-sm font-extrabold text-[#4A1429]">Pronunciation by skill</h4>
                    <Info className="w-3.5 h-3.5 text-[#6B5D52]" />
                  </div>
                  <div className="space-y-2">
                    {phonemeSkills.map((skill, i) => (
                      <div key={i} className="flex items-center gap-3">
                        <div className="w-16 text-xs font-bold text-[#4A1429]">Skill : {skill}</div>
                        <div className="flex-1 bg-[#FAF5F0] rounded-lg px-4 py-2 border border-[#E5DDD5] flex items-center gap-3">
                          <div className="w-8 h-8 bg-[#4A1429] rounded-lg flex items-center justify-center flex-shrink-0">
                            <Mic className="w-4 h-4 text-[#D4B038]" />
                          </div>
                          <span className="text-xs text-[#6B5D52] font-medium">Tutorial for : {skill}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}
          </div>
        </motion.div>

        {/* Audio Player */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.3 }}
          className="bg-white rounded-2xl shadow-md border border-[#E5DDD5] p-4 flex flex-col items-center gap-2"
        >
          <div className="flex items-center gap-4">
            <button className="w-10 h-10 rounded-full bg-[#FAF5F0] border border-[#E5DDD5] flex items-center justify-center text-[#4A1429] hover:bg-[#F5EFE7] transition-colors">
              ⏮
            </button>
            <button className="w-12 h-12 rounded-full bg-[#4A1429] flex items-center justify-center text-white hover:bg-[#3A1020] transition-colors shadow-md">
              <Play className="w-5 h-5 ml-0.5" />
            </button>
            <button className="w-10 h-10 rounded-full bg-[#FAF5F0] border border-[#E5DDD5] flex items-center justify-center text-[#4A1429] hover:bg-[#F5EFE7] transition-colors">
              ⏭
            </button>
          </div>
          <div className="text-xs text-[#6B5D52] font-mono">00:00:00 / 00:00:34</div>
          <div className="w-full h-1.5 bg-[#FAF5F0] rounded-full border border-[#E5DDD5]">
            <div className="w-0 h-full bg-[#4A1429] rounded-full" />
          </div>
        </motion.div>

        {/* Transcript */}
        <TranscriptWithRephrase transcript={transcript} />

        {/* CTA: See Score Details */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.4 }}
          className="sticky bottom-4"
        >
          <Button
            onClick={() => navigate('/tools/score-details')}
            className="w-full h-14 bg-[#D4B038] hover:bg-[#BFA030] text-[#4A1429] font-extrabold text-lg rounded-2xl shadow-xl flex items-center justify-center gap-3"
          >
            Click to see Score Details
            <ArrowRight className="w-5 h-5" />
          </Button>
        </motion.div>

      </div>
    </div>
  );
}
