'use client'

import React, { useState, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { ArrowLeft, Play, Pause, ChevronDown, ChevronUp, Info, Award, Mic, BookOpen, MessageCircle, TrendingUp } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useNavigate } from '@/lib/nextRouterAdapter';

const skillTabs = [
  { id: 'pronunciation', label: 'Pronunciation', score: 75, level: 'Upper Intermediate', color: '#A73121', bgColor: '#F5E6E0', icon: Mic },
  { id: 'intonation', label: 'Intonation', score: 77, level: 'Advanced', color: '#D4B038', bgColor: '#FEF3DC', icon: TrendingUp },
  { id: 'fluency', label: 'Fluency', score: 84, level: 'Advanced', color: '#2563EB', bgColor: '#EFF6FF', icon: MessageCircle },
  { id: 'grammar', label: 'Grammar', score: 79, level: 'Advanced', color: '#059669', bgColor: '#ECFDF5', icon: BookOpen },
  { id: 'vocabulary', label: 'Vocabulary', score: 65, level: 'Intermediate', color: '#7C3AED', bgColor: '#F5F3FF', icon: Award },
];

export default function ScoreDetails() {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState('pronunciation');
  const [expandedSections, setExpandedSections] = useState({});

  const toggleSection = (section) => {
    setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
  };

  const activeSkill = skillTabs.find(s => s.id === activeTab);
  const overallScore = Math.round(skillTabs.reduce((sum, s) => sum + s.score, 0) / skillTabs.length);

  return (
    <div className="min-h-screen bg-[#FAF5F0]">
      {/* 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-6xl mx-auto px-4 py-4">
          <div className="flex items-center justify-between mb-4">
            <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 to Results</span>
            </button>
            <div className="text-center">
              <div className="text-2xl font-extrabold text-[#D4B038]">Score Details</div>
              <div className="text-xs text-white/60">AI-Powered Analysis</div>
            </div>
            <div className="flex items-center gap-2 bg-white/10 rounded-full px-4 py-2">
              <div className="text-2xl font-extrabold text-[#D4B038]">{overallScore}%</div>
              <div className="text-xs text-white/70 leading-tight">Overall<br/>Score</div>
            </div>
          </div>

          {/* Skill Tabs */}
          <div className="flex gap-2 overflow-x-auto pb-1 scrollbar-hide">
            {skillTabs.map((skill) => {
              const Icon = skill.icon;
              const isActive = activeTab === skill.id;
              return (
                <button
                  key={skill.id}
                  onClick={() => setActiveTab(skill.id)}
                  className={`flex items-center gap-2 px-4 py-2.5 rounded-xl transition-all whitespace-nowrap flex-shrink-0 ${
                    isActive
                      ? 'bg-[#D4B038] text-[#4A1429] shadow-lg font-bold'
                      : 'bg-white/10 text-white/80 hover:bg-white/20'
                  }`}
                >
                  <Icon className="w-4 h-4" />
                  <span className="text-sm font-semibold">{skill.label}</span>
                  <span className={`text-xs px-2 py-0.5 rounded-full font-bold ${isActive ? 'bg-[#4A1429] text-[#D4B038]' : 'bg-white/20 text-white'}`}>
                    {skill.score}%
                  </span>
                </button>
              );
            })}
          </div>
        </div>
      </div>

      {/* Content */}
      <div className="max-w-6xl mx-auto px-4 py-6">
        <AnimatePresence mode="wait">
          <motion.div
            key={activeTab}
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -16 }}
            transition={{ duration: 0.25 }}
          >
            {activeTab === 'pronunciation' && <PronunciationDetails skill={activeSkill} />}
            {activeTab === 'intonation' && <IntonationDetails skill={activeSkill} />}
            {activeTab === 'fluency' && <FluencyDetails skill={activeSkill} />}
            {activeTab === 'grammar' && <GrammarDetails skill={activeSkill} toggleSection={toggleSection} expandedSections={expandedSections} />}
            {activeTab === 'vocabulary' && <VocabularyDetails skill={activeSkill} toggleSection={toggleSection} expandedSections={expandedSections} />}
          </motion.div>
        </AnimatePresence>

        {/* Transcript */}
        <TranscriptSection />
      </div>
    </div>
  );
}

function ScoreCircle({ score, color, bgColor, label, size = 'lg' }) {
  const r = size === 'lg' ? 70 : 50;
  const cx = size === 'lg' ? 80 : 60;
  const circumference = 2 * Math.PI * r;
  const offset = circumference - (circumference * score) / 100;
  const dim = size === 'lg' ? 160 : 120;

  return (
    <div className="flex flex-col items-center">
      <div className="relative" style={{ width: dim, height: dim }}>
        <svg className="w-full h-full transform -rotate-90" viewBox={`0 0 ${dim} ${dim}`}>
          <circle cx={cx} cy={cx} r={r} fill="none" stroke={bgColor} strokeWidth="12" />
          <circle
            cx={cx} cy={cx} r={r}
            fill="none" stroke={color} strokeWidth="12"
            strokeLinecap="round"
            strokeDasharray={circumference}
            strokeDashoffset={offset}
          />
        </svg>
        <div className="absolute inset-0 flex flex-col items-center justify-center">
          <div className="text-3xl font-extrabold" style={{ color }}>{score}%</div>
          {label && <div className="text-xs text-[#6B5D52] font-medium text-center px-2">{label}</div>}
        </div>
      </div>
    </div>
  );
}

function SectionHeader({ skill }) {
  return (
    <div className="flex flex-col md:flex-row items-start md:items-center gap-6 mb-8 p-6 rounded-2xl border-l-4" style={{ backgroundColor: skill.bgColor, borderColor: skill.color }}>
      <ScoreCircle score={skill.score} color={skill.color} bgColor={`${skill.bgColor}`} label={skill.level} />
      <div className="flex-1">
        <div className="flex items-center gap-2 mb-2">
          <h2 className="text-2xl font-extrabold text-[#4A1429]">{skill.label} Score</h2>
          <span className="px-3 py-1 rounded-full text-white text-xs font-bold" style={{ backgroundColor: skill.color }}>
            {skill.level}
          </span>
        </div>
        <p className="text-[#4A1429] font-semibold mb-2">
          Your {skill.label.toLowerCase()} level is <strong>{skill.level}</strong>. {skill.score >= 80 ? 'Excellent work!' : 'Keep practicing to improve!'}
        </p>
        <div className="w-full h-3 bg-white rounded-full overflow-hidden shadow-inner">
          <motion.div
            initial={{ width: 0 }}
            animate={{ width: `${skill.score}%` }}
            transition={{ duration: 1, ease: 'easeOut' }}
            className="h-full rounded-full"
            style={{ backgroundColor: skill.color }}
          />
        </div>
        <div className="text-xs text-[#6B5D52] mt-1">{skill.score}/100 points</div>
      </div>
    </div>
  );
}

function PronunciationDetails({ skill }) {
  const errors = [
    { sound: '/ə/', example: 'a /ə/', words: 'You said /—/ instead of /ə/', tip: 'Schwa sound. Relax tongue in mid-central position.' },
    { sound: '/h/', example: 'her /hɜː/', words: 'You forgot to pronounce /h/', tip: 'Breathe out gently through the vocal folds.' },
    { sound: '/t/', example: 'at /æt/', words: 'You said /r/ instead of /t/', tip: 'Press tongue to alveolar ridge, release with a burst.' },
    { sound: '/d/', example: 'decided', words: 'Pronunciation needs work', tip: 'Similar to /t/ but with vocal cord vibration.' },
    { sound: '/ɛ s/', example: 'recipes', words: 'You said /iz/ instead of /ɛs/', tip: 'Pay attention to plural endings.' },
    { sound: '/ɑ/', example: 'wanted', words: 'Needs improvement', tip: 'Drop jaw and pull tongue back.' },
  ];

  return (
    <div className="space-y-6">
      <SectionHeader skill={skill} />

      <div className="bg-white rounded-2xl shadow-md border border-[#E5DDD5] overflow-hidden">
        <div className="px-6 py-4 border-b-2 border-[#F5E6E0]" style={{ backgroundColor: skill.bgColor }}>
          <h3 className="text-lg font-extrabold text-[#4A1429]">🎯 Top Errors & Improvement Tips</h3>
        </div>
        <div className="p-6 grid md:grid-cols-2 lg:grid-cols-3 gap-4">
          {errors.map((error, i) => (
            <motion.div
              key={i}
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ delay: i * 0.05 }}
              className="bg-[#FAF5F0] rounded-xl p-4 border-2 border-[#E5DDD5] hover:border-[#A73121] transition-colors"
            >
              <div className="flex items-center gap-2 mb-3">
                <div className="px-3 py-1.5 rounded-lg font-mono text-base font-extrabold text-white" style={{ backgroundColor: skill.color }}>
                  {error.sound}
                </div>
                <span className="text-xs text-[#6B5D52] font-medium">{error.example}</span>
              </div>
              <div className="text-sm text-[#DC2626] font-semibold mb-2">{error.words}</div>
              <div className="text-xs text-[#6B5D52] leading-relaxed border-t border-[#E5DDD5] pt-2">
                <span className="font-bold text-[#4A1429]">Fix: </span>{error.tip}
              </div>
            </motion.div>
          ))}
        </div>
      </div>
    </div>
  );
}

// w = type: 'over' (big red, over-emphasised), 'under' (small red, needs emphasis), 'correct' (black, correct)
const intonationTranscriptData = [
  {
    time: '00:00:00',
    words: [
      { text: 'One', type: 'normal' }, { text: 'of', type: 'normal' }, { text: 'my', type: 'normal' },
      { text: 'good', type: 'normal' }, { text: 'friends', type: 'normal' }, { text: 'is', type: 'normal' },
      { text: 'Sasha.', type: 'correct' }, { text: 'She', type: 'correct' }, { text: 'is,', type: 'normal' },
      { text: 'um,', type: 'normal' }, { text: 'an', type: 'normal' }, { text: 'amazing', type: 'correct' },
      { text: 'lady.', type: 'normal' }, { text: 'She', type: 'normal' }, { text: 'recently', type: 'correct' },
      { text: 'got', type: 'normal' }, { text: 'married.', type: 'correct' }, { text: 'We', type: 'normal' },
      { text: 'met', type: 'correct' }, { text: 'at', type: 'normal' }, { text: 'an', type: 'normal' },
      { text: 'audition.', type: 'normal' }, { text: 'Uh,', type: 'normal' }, { text: 'she', type: 'normal' },
      { text: 'matters', type: 'correct' }, { text: 'to', type: 'normal' }, { text: 'me', type: 'normal' },
      { text: 'because', type: 'normal' },
    ],
  },
  {
    time: '00:00:13',
    words: [
      { text: 'she', type: 'over', tooltip: 'You incorrectly emphasized this word. Say it softly next time!' },
      { text: 'is', type: 'normal' }, { text: 'very', type: 'normal' },
      { text: 'open-minded', type: 'over', tooltip: 'You incorrectly emphasized this word. Say it softly next time!' },
      { text: 'and', type: 'normal' }, { text: 'she', type: 'normal' },
      { text: 'speaks', type: 'under', tooltip: 'Make sure you say this word with more energy. It was too soft!' },
      { text: 'her', type: 'normal' }, { text: 'mind.', type: 'normal' },
    ],
  },
  {
    time: '00:00:18',
    words: [
      { text: 'And', type: 'normal' },
      { text: "she's", type: 'over', tooltip: 'You incorrectly emphasized this word. Say it softly next time!' },
      { text: 'very', type: 'normal' }, { text: 'honest', type: 'normal' }, { text: 'with', type: 'normal' },
      { text: 'me', type: 'normal' }, { text: 'and', type: 'normal' },
      { text: 'most', type: 'correct' },
      { text: 'importantly,', type: 'under', tooltip: 'Make sure you say this word with more energy. It was too soft!' },
      { text: 'she', type: 'normal' }, { text: 'gives', type: 'normal' }, { text: 'me', type: 'normal' },
      { text: 'the', type: 'normal' },
      { text: 'space', type: 'correct' }, { text: 'to', type: 'normal' }, { text: 'be', type: 'normal' },
      { text: 'myself.', type: 'correct' }, { text: 'Um,', type: 'normal' }, { text: 'we', type: 'normal' },
      { text: 'have', type: 'normal' }, { text: 'gone', type: 'normal' }, { text: 'on,', type: 'normal' },
      { text: 'uh,', type: 'normal' }, { text: 'a', type: 'normal' }, { text: 'lot', type: 'normal' },
      { text: 'of', type: 'normal' },
      { text: 'coffee', type: 'correct' }, { text: 'dates', type: 'correct' }, { text: 'with', type: 'normal' },
      { text: 'each', type: 'correct' }, { text: 'other', type: 'normal' }, { text: 'and,', type: 'normal' },
      { text: 'uh,', type: 'normal' },
    ],
  },
  {
    time: '00:00:30',
    words: [
      { text: 'I', type: 'normal' },
      { text: 'particularly', type: 'correct' },
      { text: 'like', type: 'normal' }, { text: 'this', type: 'normal' }, { text: 'person', type: 'normal' },
      { text: 'because', type: 'normal' },
      { text: 'she', type: 'over', tooltip: 'You incorrectly emphasized this word. Say it softly next time!' },
      { text: 'inspires', type: 'correct' },
      { text: 'me', type: 'normal' }, { text: 'to', type: 'normal' }, { text: 'be', type: 'normal' },
      { text: 'a', type: 'normal' }, { text: 'good', type: 'normal' }, { text: 'human', type: 'normal' },
      { text: 'being', type: 'normal' }, { text: 'every', type: 'under', tooltip: 'Make sure you say this word with more energy. It was too soft!' },
      { text: 'single', type: 'over', tooltip: 'You incorrectly emphasized this word. Say it softly next time!' },
      { text: 'day', type: 'normal' }, { text: 'of', type: 'normal' }, { text: 'my', type: 'normal' },
      { text: 'life.', type: 'normal' },
    ],
  },
];

function IntonationWord({ word }) {
  const [tooltip, setTooltip] = React.useState(false);

  const isOver = word.type === 'over';
  const isUnder = word.type === 'under';
  const isCorrect = word.type === 'correct';
  const isClickable = isOver || isUnder;

  const style = isOver
    ? { color: '#DC2626', fontSize: '1.2em', fontWeight: '700', cursor: 'pointer' }
    : isUnder
    ? { color: '#DC2626', fontSize: '0.8em', fontWeight: '600', cursor: 'pointer' }
    : isCorrect
    ? { color: '#111827', fontSize: '1.15em', fontWeight: '700' }
    : { color: '#374151', fontSize: '0.95em' };

  return (
    <span className="relative inline-block mr-1">
      <span
        style={style}
        onClick={() => isClickable && setTooltip(!tooltip)}
        onMouseLeave={() => setTooltip(false)}
      >
        {word.text}
      </span>
      <AnimatePresence>
        {tooltip && word.tooltip && (
          <motion.div
            initial={{ opacity: 0, y: -4 }}
            animate={{ opacity: 1, y: -8 }}
            exit={{ opacity: 0, y: -4 }}
            className="absolute bottom-full left-1/2 -translate-x-1/2 mb-1 z-30 w-56 bg-white border border-gray-200 rounded-xl shadow-xl px-3 py-2 text-xs text-gray-700 leading-snug pointer-events-none"
          >
            {word.tooltip}
            <div className="absolute top-full left-1/2 -translate-x-1/2 w-2 h-2 bg-white border-r border-b border-gray-200 rotate-45 -mt-1" />
          </motion.div>
        )}
      </AnimatePresence>
    </span>
  );
}

function IntonationDetails({ skill }) {
  const [youtubeVideoId, setYoutubeVideoId] = React.useState(null);
  return (
    <div className="space-y-6">
      {youtubeVideoId && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4" onClick={() => setYoutubeVideoId(null)}>
          <div className="relative w-full max-w-2xl bg-black rounded-2xl overflow-hidden shadow-2xl" onClick={e => e.stopPropagation()}>
            <button onClick={() => setYoutubeVideoId(null)} 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 text-lg">✕</button>
            <div className="aspect-video"><iframe src={`https://www.youtube.com/embed/${youtubeVideoId}?autoplay=1`} className="w-full h-full" allow="autoplay; encrypted-media" allowFullScreen /></div>
          </div>
        </div>
      )}
      <SectionHeader skill={skill} />

      {/* Intonation Highlights — 3-column layout matching screenshot */}
      <div className="bg-white rounded-2xl shadow-md border border-[#E5DDD5] overflow-hidden">
        <div className="px-6 py-3 border-b border-[#E5DDD5]">
          <h3 className="text-base font-extrabold text-[#4A1429]">Intonation Highlights</h3>
        </div>
        <div className="flex flex-col md:flex-row divide-y md:divide-y-0 md:divide-x divide-[#E5DDD5]">
          {/* Left: Score */}
          <div className="md:w-48 flex-shrink-0 p-6 flex flex-col items-center justify-center">
            <div className="w-32 h-32 rounded-xl border-2 border-[#16a34a] bg-[#16a34a] flex flex-col items-center justify-center mb-3">
              <span className="text-4xl font-extrabold text-white">90%</span>
            </div>
            <div className="text-sm text-[#6B5D52] font-medium">Your Level</div>
            <div className="text-base font-extrabold text-[#16a34a] mt-0.5">Proficient</div>
          </div>

          {/* Middle: Average Pitch Variation */}
          <div className="flex-1 p-6 flex flex-col items-center justify-center">
            <div className="flex items-center gap-1.5 mb-3 self-start">
              <span className="text-sm font-extrabold text-[#4A1429]">Average Pitch Variation</span>
              <span className="w-4 h-4 rounded-full border border-[#6B5D52] text-[#6B5D52] text-[10px] flex items-center justify-center font-bold cursor-help" title="Pitch variation measures how much your voice rises and falls. Aim for 50–150 Hz.">ⓘ</span>
            </div>
            <div className="text-4xl font-extrabold text-[#D4B038] mb-3">37 Hz</div>
            {/* Waveform bars */}
            <div className="flex items-end gap-0.5 mb-2 h-12">
              {[4,6,8,12,10,14,16,18,14,12,16,20,18,16,14,12,10,8,10,14,16,18,20,16,14,12,10,8,6,8].map((h, i) => (
                <div key={i} className="w-1.5 rounded-sm" style={{ height: `${h * 2.2}px`, backgroundColor: '#D4B038', opacity: 0.8 }} />
              ))}
            </div>
            <div className="text-base font-extrabold text-[#D4B038]">Monotonous</div>
          </div>

          {/* Right: Suggestions */}
          <div className="flex-1 p-6">
            <h4 className="text-sm font-extrabold text-[#4A1429] mb-2">Suggestions for Improvement</h4>
            <p className="text-xs text-[#6B5D52] mb-4 leading-relaxed">
              For optimal results, make sure your pitch variation is between 50Hz and 150Hz.
            </p>
            <div onClick={() => setYoutubeVideoId('dQw4w9WgXcQ')} className="flex items-center gap-3 bg-[#FAF5F0] rounded-xl border border-[#E5DDD5] p-3 cursor-pointer hover:bg-[#F5EFE7] transition-colors">
              <div className="w-14 h-10 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-sm font-semibold text-[#4A1429]">Video tutorial 'Intonation'</span>
            </div>
          </div>
        </div>
      </div>

      {/* Intonation Transcript */}
      <div className="bg-white rounded-2xl shadow-md border border-[#E5DDD5] overflow-hidden">
        <div className="px-6 py-4 border-b-2" style={{ backgroundColor: skill.bgColor, borderColor: `${skill.color}40` }}>
          <h3 className="text-lg font-extrabold text-[#4A1429]">📝 Transcript</h3>
          <div className="flex flex-wrap gap-4 mt-2 text-xs">
            <span className="flex items-center gap-1.5">
              <span className="font-bold text-[#DC2626] text-base">BIG</span>
              <span className="text-[#6B5D52]">= Over-emphasised (say softer)</span>
            </span>
            <span className="flex items-center gap-1.5">
              <span className="font-bold text-[#DC2626] text-[10px]">small</span>
              <span className="text-[#6B5D52]">= Under-emphasised (say louder)</span>
            </span>
            <span className="flex items-center gap-1.5">
              <span className="font-bold text-gray-900 text-base">Bold</span>
              <span className="text-[#6B5D52]">= Correctly emphasised</span>
            </span>
          </div>
        </div>
        <div className="p-6 space-y-5">
          {intonationTranscriptData.map((entry, i) => (
            <div key={i}>
              <div className="flex items-center gap-1.5 mb-1.5 text-xs text-[#6B5D52] font-mono">
                <span>⏱</span> {entry.time}
              </div>
              <p className="leading-loose">
                {entry.words.map((w, j) => (
                  <IntonationWord key={j} word={w} />
                ))}
              </p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function FluencyDetails({ skill }) {
  const metrics = [
    { label: 'Pace', value: '126 wpm', status: 'Good', statusColor: '#16a34a', score: 80 },
    { label: 'Pausing Score', value: '81%', status: 'Advanced', statusColor: '#2563EB', score: 81 },
    { label: 'Hesitations', value: 'Natural', status: 'Excellent', statusColor: '#16a34a', score: 90 },
  ];

  return (
    <div className="space-y-6">
      <SectionHeader skill={skill} />

      <div className="grid md:grid-cols-3 gap-4">
        {metrics.map((m, i) => (
          <motion.div
            key={i}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: i * 0.1 }}
            className="bg-white rounded-2xl shadow-md border border-[#E5DDD5] p-6 text-center"
          >
            <div className="text-sm font-bold text-[#6B5D52] mb-3">{m.label}</div>
            <div className="text-3xl font-extrabold text-[#4A1429] mb-1">{m.value}</div>
            <div className="text-sm font-bold mb-3" style={{ color: m.statusColor }}>{m.status}</div>
            <div className="w-full h-3 bg-gray-100 rounded-full overflow-hidden">
              <motion.div
                initial={{ width: 0 }}
                animate={{ width: `${m.score}%` }}
                transition={{ duration: 1, delay: i * 0.1 }}
                className="h-full rounded-full"
                style={{ backgroundColor: m.statusColor }}
              />
            </div>
          </motion.div>
        ))}
      </div>

      <div className="bg-white rounded-2xl shadow-md border border-[#E5DDD5] p-6">
        <h3 className="text-lg font-extrabold text-[#4A1429] mb-4">💬 Hesitation Analysis</h3>
        <div className="bg-[#ECFDF5] border-2 border-[#16a34a]/30 rounded-xl p-5">
          <div className="flex items-start gap-4">
            <div className="text-4xl">😃</div>
            <div>
              <div className="font-extrabold text-[#4A1429] mb-1">You nailed it! Hesitations were Natural.</div>
              <p className="text-sm text-[#6B5D52] leading-relaxed">
                Brief pauses indicate thoughtful consideration. Your hesitation frequency and duration were within the natural range for confident speakers.
              </p>
            </div>
          </div>
        </div>

        <div className="mt-6 grid md:grid-cols-2 gap-4 text-sm">
          {[
            'Use connector words to link ideas and improve flow.',
            "Divide long sentences into 'chunks' to control your pace.",
            'Pause naturally after key ideas — it signals confidence.',
            'Reduce filler words like "um" and "uh" with practice.'
          ].map((tip, i) => (
            <div key={i} className="flex items-start gap-3 bg-[#FAF5F0] rounded-lg p-3 border border-[#E5DDD5]">
              <div className="w-6 h-6 rounded-full bg-[#2563EB] text-white flex items-center justify-center text-xs font-bold flex-shrink-0 mt-0.5">{i + 1}</div>
              <p className="text-[#6B5D52] leading-relaxed">{tip}</p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function CollapsibleSection({ title, badge, badgeColor, bgColor, borderColor, children, toggleSection, expandedSections, id }) {
  return (
    <div className="rounded-xl overflow-hidden border-2" style={{ borderColor: borderColor || '#E5DDD5' }}>
      <button
        onClick={() => toggleSection(id)}
        className="w-full flex items-center justify-between p-4 transition-colors"
        style={{ backgroundColor: bgColor || '#FAF5F0' }}
      >
        <div className="flex items-center gap-3">
          <span className="font-bold text-[#4A1429]">{title}</span>
          {badge && (
            <span className="px-3 py-1 text-white text-xs rounded-full font-bold" style={{ backgroundColor: badgeColor }}>
              {badge}
            </span>
          )}
        </div>
        {expandedSections[id] ? <ChevronUp className="w-5 h-5 text-[#4A1429]" /> : <ChevronDown className="w-5 h-5 text-[#4A1429]" />}
      </button>
      <AnimatePresence>
        {expandedSections[id] && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            className="overflow-hidden"
          >
            <div className="p-5 bg-white border-t border-[#E5DDD5]">{children}</div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

function GrammarDetails({ skill, toggleSection, expandedSections }) {
  return (
    <div className="space-y-6">
      <SectionHeader skill={skill} />
      <div className="space-y-3">
        <CollapsibleSection id="cambridge-rec" title="Cambridge Veritas Recommendation" badge="NEW" badgeColor="#1E3A8A" bgColor="#FEF2F2" borderColor="#FCA5A5" toggleSection={toggleSection} expandedSections={expandedSections}>
          <p className="text-[#6B5D52] leading-relaxed text-sm">
            Expanding your vocabulary is essential for effective communication. A broad lexicon allows you to convey thoughts with greater precision. Instead of "good friend," try "compassionate companion" — it expresses your feelings with more creativity and sophistication.
          </p>
        </CollapsibleSection>

        <CollapsibleSection id="grammar-range" title="Your Grammatical Range" badge="Intermediate" badgeColor="#DC2626" bgColor="#FFF7ED" borderColor="#FED7AA" toggleSection={toggleSection} expandedSections={expandedSections}>
          <h4 className="font-bold text-[#4A1429] mb-3">✅ Structures You Used Well</h4>
          <div className="grid md:grid-cols-2 gap-3 text-sm">
            {[
              { type: 'Simple present', example: '"she\'s a psychologist"' },
              { type: 'Past tense', example: '"I first met her"' },
              { type: 'Present perfect', example: '"we\'ve tried making..."' },
              { type: 'Conditional', example: '"she would continue"' },
            ].map((item, i) => (
              <div key={i} className="bg-[#ECFDF5] rounded-lg p-3 border border-[#16a34a]/20">
                <div className="font-bold text-[#059669]">{item.type}</div>
                <div className="text-[#6B5D52] italic">{item.example}</div>
              </div>
            ))}
          </div>
        </CollapsibleSection>

        <CollapsibleSection id="top-errors" title="Your Top Grammatical Errors" bgColor="#FFF5F5" borderColor="#FCA5A5" toggleSection={toggleSection} expandedSections={expandedSections}>
          <div className="space-y-4 text-sm">
            {[
              { error: 'Awkward phrasing', suggestion: 'Rephrase sentences for clarity.', explanation: '"she, I, was she wanted to be an actor" is confusing — simplify your structure.' },
              { error: 'Subject-verb agreement', suggestion: "Use 'are' instead of 'is' for plural subjects.", explanation: '"activities... is" should be "activities... are".' },
            ].map((item, i) => (
              <div key={i} className="bg-[#FFF5F5] rounded-lg p-4 border-l-4 border-[#DC2626]">
                <div className="font-bold text-[#DC2626] mb-1">Error: {item.error}</div>
                <div className="text-[#059669] font-semibold mb-1">✓ Fix: {item.suggestion}</div>
                <div className="text-[#6B5D52]">{item.explanation}</div>
              </div>
            ))}
          </div>
        </CollapsibleSection>
      </div>
    </div>
  );
}

function VocabularyDetails({ skill, toggleSection, expandedSections }) {
  const levels = [
    { level: 'C2', percent: 1, color: '#1E40AF' },
    { level: 'C1', percent: 2, color: '#3B82F6' },
    { level: 'B2', percent: 3, color: '#60A5FA' },
    { level: 'B1', percent: 15, color: '#93C5FD' },
    { level: 'A2', percent: 20, color: '#BFDBFE' },
    { level: 'A1', percent: 59, color: '#DBEAFE' },
  ];

  return (
    <div className="space-y-6">
      <SectionHeader skill={skill} />
      <div className="space-y-3">
        <CollapsibleSection id="vocab-rec" title="Cambridge Veritas Recommendation" badge="NEW" badgeColor="#1E3A8A" bgColor="#FEF2F2" borderColor="#FCA5A5" toggleSection={toggleSection} expandedSections={expandedSections}>
          <p className="text-[#6B5D52] leading-relaxed text-sm">
            A rich vocabulary enables precise, versatile communication. Use a thesaurus to explore synonyms and incorporate high-impact words naturally into your speech.
          </p>
        </CollapsibleSection>

        <CollapsibleSection id="vocab-dist" title="Vocabulary Distribution (CEFR)" bgColor={skill.bgColor} borderColor={`${skill.color}40`} toggleSection={toggleSection} expandedSections={expandedSections}>
          <div className="space-y-3">
            <div className="text-right mb-2">
              <span className="text-3xl font-extrabold text-[#DC2626]">6%</span>
              <span className="text-sm text-[#6B5D52] ml-2">Advanced Vocabulary Used</span>
            </div>
            {levels.map((item) => (
              <div key={item.level} className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0" style={{ backgroundColor: item.color }}>
                  {item.level}
                </div>
                <div className="flex-1">
                  <div className="flex justify-between text-xs mb-1">
                    <span className="text-[#6B5D52]">{item.level}</span>
                    <span className="font-bold text-[#4A1429]">{item.percent}%</span>
                  </div>
                  <div className="h-2.5 bg-gray-100 rounded-full overflow-hidden">
                    <motion.div
                      initial={{ width: 0 }}
                      animate={{ width: `${item.percent}%` }}
                      transition={{ duration: 0.8 }}
                      className="h-full rounded-full"
                      style={{ backgroundColor: item.color }}
                    />
                  </div>
                </div>
              </div>
            ))}
          </div>
        </CollapsibleSection>

        <CollapsibleSection id="areas-improve" title="Words to Upgrade" bgColor="#F5F3FF" borderColor="#7C3AED40" toggleSection={toggleSection} expandedSections={expandedSections}>
          <div className="grid md:grid-cols-2 gap-6">
            <div>
              <h4 className="font-bold text-[#4A1429] mb-3">🔁 Repetitive Words</h4>
              <div className="space-y-2">
                {['she', 'her', 'very'].map((word) => (
                  <div key={word} className="px-4 py-2 bg-[#FFF5F5] rounded-lg border-l-4 border-[#DC2626] font-mono text-[#DC2626] font-bold">
                    "{word}"
                  </div>
                ))}
              </div>
            </div>
            <div>
              <h4 className="font-bold text-[#4A1429] mb-3">⬆️ Better Alternatives</h4>
              <div className="space-y-2 text-sm">
                {[
                  { from: 'liking', to: 'fondness, affection' },
                  { from: 'good', to: 'excellent, remarkable' },
                  { from: 'best', to: 'finest, ultimate' },
                  { from: 'met', to: 'encountered, came across' },
                ].map((item, i) => (
                  <div key={i} className="flex items-center gap-2 bg-[#ECFDF5] rounded-lg p-2 border border-[#16a34a]/20">
                    <span className="text-[#DC2626] font-mono font-bold">{item.from}</span>
                    <span className="text-[#4A1429]">→</span>
                    <span className="text-[#059669] font-semibold">{item.to}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </CollapsibleSection>
      </div>
    </div>
  );
}

function TranscriptSection() {
  const transcript = [
    { time: '00:00', text: 'So, one of my good friends, her name is Sasha.' },
    { time: '00:16', text: "Um, she's a psychologist. I first met her at an audition in Delhi and, uh, we started talking," },
    { time: '00:26', text: "uh, she wanted to be an actor when she first met me, but later decided she would continue her career." },
    { time: '00:36', text: "Some of the activities we do together — we love coffee. We've tried making different types of coffees, different recipes. I have a special thing for her because she understands me." }
  ];
  const highlighted = ['psychologist', 'together', 'coffee', 'recipes', 'special', 'good', 'best'];

  const [isPlaying, setIsPlaying] = useState(false);
  const audioRef = useRef(null);

  const togglePlayback = () => {
    if (!audioRef.current) return;
    if (isPlaying) {
      audioRef.current.pause();
      setIsPlaying(false);
    } else {
      audioRef.current.play();
      setIsPlaying(true);
    }
  };

  const handleAudioEnded = () => setIsPlaying(false);

  return (
    <div className="mt-6 bg-white rounded-2xl shadow-md border border-[#E5DDD5] overflow-hidden">
      {/* Hidden audio element — replace src with the real recording URL when available */}
      <audio ref={audioRef} onEnded={handleAudioEnded} src="" />

      <div className="bg-gradient-to-r from-[#4A1429] to-[#5A1839] px-6 py-4 flex items-center justify-between">
        <h3 className="text-lg font-extrabold text-white">📝 Transcript</h3>
        <button
          onClick={togglePlayback}
          className="flex items-center gap-2 bg-[#D4B038] hover:bg-[#BFA030] text-[#4A1429] font-bold px-4 py-2 rounded-lg transition-colors text-sm"
        >
          {isPlaying ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
          {isPlaying ? 'Pause Recording' : 'Play Recording'}
        </button>
      </div>
      <div className="p-6 space-y-4">
        {transcript.map((entry, i) => (
          <div key={i} className="flex gap-4 items-start">
            <div className="flex-shrink-0 px-2 py-1 bg-[#D4B038] text-[#4A1429] text-xs font-mono font-bold rounded-lg">
              {entry.time}
            </div>
            <p className="text-[#4A1429] leading-relaxed text-sm">
              {entry.text.split(' ').map((word, j) => {
                const clean = word.toLowerCase().replace(/[,.'"-]/g, '');
                return (
                  <span key={j} className={highlighted.includes(clean) ? 'font-bold text-[#A73121] underline decoration-dotted underline-offset-2' : ''}>
                    {word}{' '}
                  </span>
                );
              })}
            </p>
          </div>
        ))}
      </div>
    </div>
  );
}