'use client'

import React, { useEffect, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { motion } from 'framer-motion';
import { getApiPath } from '@/lib/basePath';
import LightHeaderLogo from '@/components/brand/LightHeaderLogo';
import { useNavigate } from '@/lib/nextRouterAdapter';
import { useAuth } from '@/lib/AuthContext';
import { fetchUserPlan } from '@/lib/userPlan';
import {
  Mic,
  ChevronRight,
  GraduationCap,
  Briefcase,
  MessageCircle,
  Calendar,
  Crown,
  ArrowRight,
  Infinity,
  TrendingUp,
  Sparkles,
  CreditCard,
  CheckCircle2,
  LogOut,
  XCircle,
  MessageSquarePlus,
} from 'lucide-react';
import TrialDashboard from '@/components/dashboard/TrialDashboard';
import FeedbackModal from '@/components/dashboard/FeedbackModal';
import { appendRegionCurrencyToPath } from '@/lib/regionCurrencyLink';

const planConfig = {
  none:      { label: 'No Active Plan', color: '#6B7280', bg: '#F3F4F6', active: false },
  free:      { label: 'Free Trial',     color: '#059669', bg: '#ECFDF5', active: true  },
  starter:   { label: 'Starter',        color: '#8B6914', bg: '#FEF9E7', active: true  },
  practice:  { label: 'Practice',       color: '#D4B038', bg: '#FFFBEB', active: true  },
  unlimited: { label: 'Unlimited',      color: '#7C3AED', bg: '#F5F3FF', active: true  },
  growth:    { label: 'Growth Pack',    color: '#1D4ED8', bg: '#EFF6FF', active: true  },
  annual:    { label: 'Annual',         color: '#059669', bg: '#ECFDF5', active: true  },
};

const purposeConfig = {
  ielts:    { label: 'IELTS Speaking',    icon: GraduationCap, color: '#4A1429', bg: '#FDF2F8' },
  business: { label: 'Business English',  icon: Briefcase,     color: '#1E3A5F', bg: '#EFF6FF' },
  general:  { label: 'General English',   icon: MessageCircle, color: '#064E3B', bg: '#ECFDF5' },
};

const skillColors = [
  { key: 'pronunciation', label: 'Pronunciation', color: '#EF4444' },
  { key: 'intonation',    label: 'Intonation',    color: '#D4B038' },
  { key: 'fluency',       label: 'Fluency',       color: '#3B82F6' },
  { key: 'grammar',       label: 'Grammar',       color: '#10B981' },
  { key: 'vocabulary',    label: 'Vocabulary',    color: '#8B5CF6' },
];

function formatDate(isoStr) {
  if (!isoStr) return '\u2014';
  return new Date(isoStr).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
}

function resolvePlanKey(planName, planId) {
  // plan_id = 0 is always free trial
  if (Number(planId) === 0) return 'free';
  const lower = String(planName || '').toLowerCase();
  if (lower === 'free trial' || lower === 'free') return 'free';
  if (lower.includes('unlimited')) return 'unlimited';
  if (lower.includes('annual') || lower.includes('year')) return 'annual';
  if (lower.includes('growth') || lower.includes('pack') || lower.includes('pro')) return 'growth';
  if (lower.includes('practice')) return 'practice';
  if (lower.includes('starter') || lower.includes('trial') || lower.includes('try')) return 'starter';
  return 'starter';
}

function resolveFirstName(user) {
  const candidates = [
    user?.first_name,
    user?.full_name,
    user?.name,
    [user?.first_name, user?.last_name].filter(Boolean).join(' '),
    user?.username,
    String(user?.email || '').split('@')[0],
  ];
  for (const candidate of candidates) {
    const text = String(candidate || '').trim();
    if (!text) continue;
    return text.split(/\s+/)[0];
  }
  return '';
}

function ScoreRing({ score, size = 56 }) {
  const r = 22;
  const circ = 2 * Math.PI * r;
  const dash = circ * ((score || 0) / 100);
  return (
    <svg width={size} height={size} viewBox="0 0 56 56" className="-rotate-90">
      <circle cx="28" cy="28" r={r} fill="none" stroke="#F3F4F6" strokeWidth="5" />
      <motion.circle
        cx="28" cy="28" r={r}
        fill="none" stroke="#D4B038" strokeWidth="5" strokeLinecap="round"
        strokeDasharray={circ}
        initial={{ strokeDashoffset: circ }}
        animate={{ strokeDashoffset: circ - dash }}
        transition={{ duration: 1.2, ease: 'easeOut' }}
      />
    </svg>
  );
}

export default function Dashboard() {
  const navigate = useNavigate();
  const [feedbackOpen, setFeedbackOpen] = useState(false);
  const { user, logout, isAuthenticated, isLoadingAuth, navigateToLogin } = useAuth();
  const noActivePlanPath = appendRegionCurrencyToPath('/tools/no-active-plan');

  useEffect(() => {
    if (!isLoadingAuth && !isAuthenticated) navigateToLogin('/tools/signin');
  }, [isLoadingAuth, isAuthenticated, navigateToLogin]);

  const { data: userPlanData = { hasPlan: false }, isLoading: isLoadingPlan } = useQuery({
    queryKey: ['userPlan', user?.id],
    queryFn: () => fetchUserPlan(user?.id),
    enabled: !!user?.id,
    staleTime: 60_000,
    retry: 1,
  });

  const { data: sessions = [], isLoading } = useQuery({
    queryKey: ['dashSessions', user?.id],
    queryFn: async () => {
      if (!user?.id) return [];
      const res = await fetch(getApiPath(`/api/speech/sessions?userId=${user.id}&limit=10&source=tools`));
      const data = await res.json();
      return data.sessions || [];
    },
    initialData: [],
    enabled: !!user?.id,
  });

  if (isLoadingAuth || !isAuthenticated || isLoadingPlan) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-[#FAF5F0]">
        <div className="w-8 h-8 border-4 border-[#E5DDD5] border-t-[#4A1429] rounded-full animate-spin" />
      </div>
    );
  }

  const activePlan = userPlanData?.plan;
  const hasPlan = Boolean(userPlanData?.hasPlan);
  const plan = activePlan ? resolvePlanKey(activePlan.plan_name, activePlan.plan_id) : 'none';
  const isFreeTrial = plan === 'free';
  const planCfg = planConfig[plan] || planConfig.starter;
  const attemptsUsed = activePlan?.completed_tests ?? 0;
  const rawTotal = activePlan?.total_tests ?? 0;
  const rawRemaining = activePlan?.remaining_tests ?? 0;
  const attemptsTotal = rawTotal > 0 ? rawTotal : rawRemaining + attemptsUsed;
  const attemptsLeft = Math.max(0, rawRemaining);
  const progressPct = attemptsTotal > 0 ? Math.min(100, (attemptsUsed / attemptsTotal) * 100) : 0;
  const outOfAttempts = attemptsTotal > 0 && attemptsLeft === 0;
  const isUnlimited = plan === 'annual' || plan === 'unlimited';
  const hasActivePlan = hasPlan && planCfg.active;
  const firstName = resolveFirstName(user) || null;
  const fullName = user?.full_name || user?.name || [user?.first_name, user?.last_name].filter(Boolean).join(' ');
  const displayName = fullName || user?.username || user?.email;
  const lastSession = sessions[0];
  const lastScore = lastSession?.scores?.overall ?? lastSession?.overall ?? null;
  const planStatus = String(activePlan?.status || '').toLowerCase();
  const isRenewalCancelled = planStatus === 'cancelled' || userPlanData?.isRenewalCancelled;
  const hasRazorpaySubscription = String(activePlan?.order_id || '').startsWith('sub_');

  const handleStartTest = () => {
    if (!hasActivePlan) { navigate(noActivePlanPath); return; }
    navigate('/tools/speech-analyser?step=purposes');
  };

  // Free trial users get a dedicated dashboard
  if (isFreeTrial) {
    return (
      <div className="min-h-screen bg-[#FAF5F0]">
        <div className="bg-gradient-to-r from-[#2D0A18] via-[#4A1429] to-[#3A0F20] shadow-xl">
          <div className="max-w-5xl mx-auto px-4 py-4 flex items-center justify-between">
            <LightHeaderLogo />
            <div className="flex items-center gap-4">
              <div className="hidden sm:flex items-center gap-2 bg-white/10 rounded-full px-3 py-1.5">
                <div className="w-6 h-6 rounded-full bg-[#D4B038] flex items-center justify-center text-[#4A1429] font-extrabold text-xs">
                  {(displayName || 'U')[0].toUpperCase()}
                </div>
                <span className="text-white/80 text-xs font-semibold">{displayName}</span>
              </div>
              <button onClick={() => logout(appendRegionCurrencyToPath('/tools/signin'))} className="flex items-center gap-1.5 text-white/50 hover:text-white text-xs transition-colors">
                <LogOut className="w-4 h-4" />
                <span className="hidden sm:block">Log out</span>
              </button>
            </div>
          </div>
        </div>
        <TrialDashboard
          user={user}
          onFeedbackOpen={() => setFeedbackOpen(true)}
          exhausted={outOfAttempts}
          attemptsLeft={attemptsLeft}
          attemptsTotal={attemptsTotal}
          sessions={sessions}
          isLoadingSessions={isLoading}
        />
        <FeedbackModal isOpen={feedbackOpen} onClose={() => setFeedbackOpen(false)} userId={user?.id} />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#FAF5F0]">
      {/* Nav */}
      <div className="bg-gradient-to-r from-[#2D0A18] via-[#4A1429] to-[#3A0F20] shadow-xl">
        <div className="max-w-5xl mx-auto px-4 py-4 flex items-center justify-between">
          <LightHeaderLogo />
          <div className="flex items-center gap-4">
            <div className="hidden sm:flex items-center gap-2 bg-white/10 rounded-full px-3 py-1.5">
              <div className="w-6 h-6 rounded-full bg-[#D4B038] flex items-center justify-center text-[#4A1429] font-extrabold text-xs">
                {(displayName || 'U')[0].toUpperCase()}
              </div>
              <span className="text-white/80 text-xs font-semibold">{displayName}</span>
            </div>
            <button onClick={() => logout(appendRegionCurrencyToPath('/tools/signin'))} className="flex items-center gap-1.5 text-white/50 hover:text-white text-xs transition-colors">
              <LogOut className="w-4 h-4" />
              <span className="hidden sm:block">Log out</span>
            </button>
          </div>
        </div>
      </div>

      <div className="max-w-5xl mx-auto px-4 py-6 space-y-5">
        {/* Hero */}
        <motion.div initial={{ opacity: 0, y: 16 }} animate={{ opacity: 1, y: 0 }}
          className="relative bg-gradient-to-br from-[#4A1429] via-[#5A1839] to-[#3A0F20] rounded-2xl p-5 sm:p-8 overflow-hidden">
          <div className="absolute inset-0 opacity-[0.06]"
            style={{ backgroundImage: 'radial-gradient(circle, #fff 1px, transparent 1px)', backgroundSize: '24px 24px' }} />
          <div className="absolute top-0 right-0 w-48 h-48 rounded-full pointer-events-none"
            style={{ background: 'radial-gradient(circle, rgba(212,176,56,0.15) 0%, transparent 70%)', transform: 'translate(20%,-20%)' }} />
          <div className="relative flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div>
              <div className="flex items-center gap-2 mb-2">
                <Sparkles className="w-4 h-4 text-[#D4B038]" />
                <span className="text-[#D4B038] text-xs font-bold uppercase tracking-widest">Your Dashboard</span>
              </div>
              <h1 className="text-xl sm:text-3xl font-extrabold text-white leading-tight">
                {sessions.length === 0 ? (firstName ? `Welcome ${firstName}!` : 'Welcome!') : (firstName ? `Welcome back ${firstName}!` : 'Welcome back!')}
              </h1>
              <p className="text-white/50 text-sm mt-1">
                {sessions.length > 0 ? `You've completed ${sessions.length} session${sessions.length > 1 ? 's' : ''}. Keep up the great work!` : 'Ready to start your first AI coaching session?'}
              </p>
            </div>
            {lastScore !== null && (
              <div className="flex items-center gap-3 bg-white/10 rounded-2xl px-4 py-3 flex-shrink-0">
                <div className="relative">
                  <ScoreRing score={lastScore} />
                  <div className="absolute inset-0 flex items-center justify-center">
                    <span className="text-sm font-extrabold text-white">{lastScore}</span>
                  </div>
                </div>
                <div>
                  <div className="text-[#D4B038] font-extrabold text-sm">Last Score</div>
                  <div className="text-white/50 text-xs">/ 100</div>
                </div>
              </div>
            )}
          </div>
        </motion.div>

        {/* Plan + Purchase cards */}
        <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.05 }}
          className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <button onClick={() => navigate(hasActivePlan ? '/tools/active-plan' : noActivePlanPath)}
            className={`bg-white rounded-2xl border shadow-sm p-4 text-left hover:shadow-md transition-all group relative overflow-hidden ${outOfAttempts && !isUnlimited ? 'border-red-200' : 'border-[#E5DDD5] hover:border-[#D4B038]'}`}>
            <div className="absolute top-0 right-0 w-28 h-28 rounded-full pointer-events-none opacity-20"
              style={{ background: `radial-gradient(circle, ${planCfg.color}40 0%, transparent 70%)`, transform: 'translate(30%,-30%)' }} />
            <div className="flex items-center justify-between gap-3">
              <div className="flex items-center gap-3 min-w-0">
                <div className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0" style={{ backgroundColor: planCfg.bg }}>
                  <Crown className="w-4 h-4" style={{ color: planCfg.color }} />
                </div>
                <div className="min-w-0">
                  <div className="flex items-center gap-2 flex-wrap">
                    <span className="font-extrabold text-[#4A1429] text-base leading-tight">{planCfg.label} Plan</span>
                    {hasActivePlan ? (
                      isRenewalCancelled ? (
                        <span className="inline-flex items-center gap-1 text-[10px] font-bold text-amber-700 bg-amber-50 border border-amber-100 px-2 py-0.5 rounded-full">
                          <XCircle className="w-2.5 h-2.5" /> Cancelled
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1 text-[10px] font-bold text-emerald-600 bg-emerald-50 border border-emerald-100 px-2 py-0.5 rounded-full">
                          <CheckCircle2 className="w-2.5 h-2.5" /> Active
                        </span>
                      )
                    ) : (
                      <span className="inline-flex items-center gap-1 text-[10px] font-bold text-gray-400 bg-gray-100 px-2 py-0.5 rounded-full">Upgrade</span>
                    )}
                  </div>
                  {activePlan?.expires_at && hasActivePlan && (
                    <div className="text-[11px] text-gray-400 mt-0.5">
                      {isRenewalCancelled ? 'Access until' : isFreeTrial && hasRazorpaySubscription ? 'Auto-pay starts' : 'Renews'} {formatDate(activePlan.expires_at)}
                    </div>
                  )}
                </div>
              </div>
              <div className="flex items-center gap-2 flex-shrink-0">
                {hasActivePlan && (isUnlimited ? (
                  <div className="flex items-center gap-1 bg-purple-50 rounded-xl px-3 py-2">
                    <Infinity className="w-4 h-4 text-purple-500" />
                    <span className="font-extrabold text-purple-600 text-xs">Unlimited</span>
                  </div>
                ) : (
                  <div className="text-right bg-[#FAF5F0] rounded-xl px-3 py-2 border border-[#E5DDD5]">
                    <div className="flex items-baseline gap-1">
                      <span className={`text-lg font-extrabold leading-none ${outOfAttempts ? 'text-red-500' : 'text-[#4A1429]'}`}>{attemptsLeft}</span>
                      <span className="text-[11px] text-gray-400">/ {attemptsTotal}</span>
                    </div>
                    <div className="text-[10px] text-gray-400 mt-0.5">sessions left</div>
                    <div className="w-16 h-1 bg-gray-200 rounded-full overflow-hidden mt-1.5">
                      <motion.div initial={{ width: 0 }} animate={{ width: `${progressPct}%` }} transition={{ duration: 0.9, ease: 'easeOut' }}
                        className="h-full rounded-full" style={{ backgroundColor: outOfAttempts ? '#EF4444' : '#D4B038' }} />
                    </div>
                  </div>
                ))}
                <ChevronRight className="w-4 h-4 text-gray-300 group-hover:text-[#D4B038] transition-colors" />
              </div>
            </div>
          </button>

          <button onClick={() => navigate('/tools/payment-history')}
            className="bg-white rounded-2xl border border-[#E5DDD5] shadow-sm p-4 text-left hover:shadow-md hover:border-[#D4B038] transition-all group relative overflow-hidden">
            <div className="absolute top-0 right-0 w-28 h-28 rounded-full pointer-events-none opacity-20"
              style={{ background: 'radial-gradient(circle, #3B82F640 0%, transparent 70%)', transform: 'translate(30%,-30%)' }} />
            <div className="flex items-center justify-between gap-3 relative">
              <div className="flex items-center gap-3 min-w-0">
                <div className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 bg-blue-50">
                  <CreditCard className="w-4 h-4 text-blue-500" />
                </div>
                <div className="min-w-0">
                  <div className="font-extrabold text-[#4A1429] text-base leading-tight">Purchase History</div>
                  <div className="text-[11px] text-gray-400 mt-0.5">View past transactions & invoices</div>
                </div>
              </div>
              <ChevronRight className="w-4 h-4 text-gray-300 group-hover:text-[#D4B038] transition-colors flex-shrink-0" />
            </div>
          </button>
        </motion.div>

        {/* Start test CTA */}
        <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.15 }}>
          <button onClick={handleStartTest} disabled={outOfAttempts && !isUnlimited}
            className={`w-full font-extrabold py-4 sm:py-5 rounded-2xl text-base transition-all flex items-center justify-center gap-3 shadow-lg ${
              outOfAttempts && !isUnlimited
                ? 'bg-gray-200 text-gray-400 cursor-not-allowed'
                : 'bg-gradient-to-r from-[#D4B038] to-[#C9A830] hover:from-[#C9A830] hover:to-[#BFA030] text-[#4A1429] hover:scale-[1.01]'
            }`}>
            <Mic className={`w-5 h-5 ${outOfAttempts && !isUnlimited ? 'text-gray-400' : 'text-[#4A1429]'}`} />
            {outOfAttempts && !isUnlimited ? 'No Sessions Remaining' : 'Start New AI Coaching Session'}
            {(!outOfAttempts || isUnlimited) && <ArrowRight className="w-5 h-5" />}
          </button>
        </motion.div>

        {/* Recent Sessions */}
        <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}>
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-2">
              <TrendingUp className="w-4 h-4 text-[#D4B038]" />
              <h2 className="text-base font-extrabold text-[#4A1429]">Recent Sessions</h2>
            </div>
            {sessions.length > 0 && (
              <button onClick={() => navigate('/tools/past-results')}
                className="text-xs font-bold text-[#D4B038] hover:text-[#BFA030] flex items-center gap-1 transition-colors bg-[#D4B038]/10 px-3 py-1.5 rounded-full">
                View all <ChevronRight className="w-3.5 h-3.5" />
              </button>
            )}
          </div>

          {isLoading && (
            <div className="flex justify-center py-10">
              <div className="w-6 h-6 border-4 border-[#E5DDD5] border-t-[#4A1429] rounded-full animate-spin" />
            </div>
          )}

          {!isLoading && sessions.length === 0 && (
            <div className="bg-white rounded-2xl border border-[#E5DDD5] overflow-hidden">
              <div className="h-1.5 w-full" style={{ background: 'linear-gradient(90deg, #D4B038, #C49A20)' }} />
              <div className="p-8 sm:p-10 flex flex-col items-center text-center">
                <motion.div
                  animate={{ scale: [1, 1.06, 1] }}
                  transition={{ repeat: Infinity, duration: 2.8, ease: 'easeInOut' }}
                  className="w-20 h-20 rounded-3xl flex items-center justify-center mb-5 shadow-lg"
                  style={{ background: 'linear-gradient(135deg, #4A1429, #6B1E3D)' }}
                >
                  <Mic className="w-9 h-9 text-white" />
                </motion.div>
                <h3 className="text-xl font-extrabold mb-2" style={{ color: '#4A1429' }}>
                  Start your first session to see your results here
                </h3>
                <p className="text-gray-400 text-sm leading-relaxed max-w-sm mb-8">
                  Your scores, skill breakdowns, IELTS prediction, and week-by-week progress will all appear here after your first 4-minute session.
                </p>
                <div className="grid grid-cols-2 gap-3 w-full max-w-sm mb-8">
                  {[
                    { icon: GraduationCap, color: '#4A1429', bg: '#FDF2F8', label: 'IELTS Band Prediction',  sub: 'Predicted score after every session' },
                    { icon: Mic,           color: '#DC2626', bg: '#FEF2F2', label: 'Phoneme Analysis',        sub: 'Find exactly which sounds to fix' },
                    { icon: TrendingUp,    color: '#059669', bg: '#ECFDF5', label: 'Week-by-Week Progress',   sub: 'Watch yourself improve in real time' },
                    { icon: Briefcase,     color: '#1D4ED8', bg: '#EFF6FF', label: 'Grammar & Vocabulary AI', sub: 'Smart corrections after every answer' },
                  ].map((f, i) => {
                    const Icon = f.icon;
                    return (
                      <motion.div key={i} initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: 0.4 + i * 0.08 }}
                        className="rounded-xl p-3 border border-[#E5DDD5] text-left flex items-start gap-2.5"
                      >
                        <div className="w-7 h-7 rounded-lg flex items-center justify-center flex-shrink-0" style={{ backgroundColor: f.bg }}>
                          <Icon className="w-3.5 h-3.5" style={{ color: f.color }} />
                        </div>
                        <div>
                          <p className="text-[11px] font-extrabold leading-tight" style={{ color: '#4A1429' }}>{f.label}</p>
                          <p className="text-[10px] text-gray-400 mt-0.5 leading-tight">{f.sub}</p>
                        </div>
                      </motion.div>
                    );
                  })}
                </div>
                <button
                  onClick={handleStartTest}
                  className="flex items-center gap-2.5 font-extrabold py-3.5 px-8 rounded-2xl text-sm shadow-md"
                  style={{ background: 'linear-gradient(135deg, #4A1429, #6B1E3D)', color: '#D4B038' }}
                >
                  <Mic className="w-4 h-4" />
                  Start my first session now
                </button>
                <p className="text-gray-300 text-xs mt-3">4 minutes · Instant results · No tutor needed</p>
              </div>
            </div>
          )}

          <div className="space-y-3">
            {sessions.map((session, i) => {
              const cfg = purposeConfig[session.purpose] || purposeConfig.general;
              const Icon = cfg.icon;
              const overall = session.scores?.overall ?? session.overall ?? null;
              const scoreNum = typeof overall === 'number' ? overall : null;
              const testLabel = session.test_label || cfg.label;
              return (
                <motion.div key={session.id} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.25 + i * 0.06 }} onClick={() => navigate('/tools/past-results')}
                  className="bg-white rounded-2xl border border-[#E5DDD5] shadow-sm hover:shadow-md hover:border-[#D4B038] transition-all cursor-pointer p-4">
                  <div className="flex items-center gap-4">
                    <div className="w-11 h-11 rounded-xl flex items-center justify-center flex-shrink-0" style={{ backgroundColor: cfg.bg }}>
                      <Icon className="w-5 h-5" style={{ color: cfg.color }} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <span className="font-bold text-[#4A1429] text-sm">{testLabel} · Part {session.part}</span>
                      </div>
                      <div className="text-xs text-gray-400 flex items-center gap-1 mb-2">
                        <Calendar className="w-3 h-3" /> {formatDate(session.created_date)}
                      </div>
                      <div className="flex gap-1">
                        {skillColors.map((skill) => (
                          <div key={skill.key} className="flex-1">
                            <div className="h-2 rounded-full bg-gray-100 overflow-hidden">
                              <motion.div className="h-full rounded-full" style={{ backgroundColor: skill.color }}
                                initial={{ width: 0 }} animate={{ width: `${session.scores?.[skill.key] ?? 0}%` }}
                                transition={{ duration: 0.8, delay: 0.3 + i * 0.06 }} />
                            </div>
                          </div>
                        ))}
                      </div>
                      <div className="flex gap-1 mt-1">
                        {skillColors.map((skill) => (
                          <div key={skill.key} className="flex-1 text-center">
                            <span className="text-[9px] font-bold" style={{ color: skill.color }}>{session.scores?.[skill.key] ?? 0}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                    <div className="flex items-center gap-2 flex-shrink-0">
                      <div className="text-right">
                        {scoreNum !== null ? (
                          <>
                            <div className="text-2xl font-extrabold text-[#4A1429] leading-none">{scoreNum}</div>
                            <div className="text-[10px] text-gray-400 font-semibold">/ 100</div>
                          </>
                        ) : <div className="text-sm text-gray-400">—</div>}
                      </div>
                      <ChevronRight className="w-4 h-4 text-gray-300" />
                    </div>
                  </div>
                </motion.div>
              );
            })}
          </div>
        </motion.div>
      </div>

      {/* Feedback modal */}
      <FeedbackModal isOpen={feedbackOpen} onClose={() => setFeedbackOpen(false)} userId={user?.id} />

      {/* Floating feedback button */}
      <button onClick={() => setFeedbackOpen(true)}
        className="fixed bottom-6 right-5 z-40 flex items-center gap-2 bg-gradient-to-r from-[#4A1429] to-[#5A1839] hover:from-[#5A1839] hover:to-[#6B1E3D] text-[#D4B038] font-extrabold text-xs px-4 py-3 rounded-2xl shadow-2xl hover:scale-105 transition-all border border-[#D4B038]/30">
        <MessageSquarePlus className="w-4 h-4" />
        <span className="hidden sm:inline">Share Feedback</span>
      </button>
    </div>
  );
}
