'use client'

import { useState, useEffect, useCallback, useMemo } from 'react'
import { useAuthStore, type UserRole, type AuthUser } from '@/lib/auth-store'
import { api } from '@/lib/api'
import { 
  SERVICE_TYPES, PERSONNEL_SUB_TYPES, IMAGE_SUB_TYPES, STATUS_COLORS, STATUS_LABELS, SENTIMENT_COLORS, ROLE_LABELS,
  type Review, type ReviewPhoto, type SupervisorResponse, type Notification
} from '@/lib/types'
import { useToast } from '@/hooks/use-toast'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { Sheet, SheetContent, SheetTrigger, SheetTitle } from '@/components/ui/sheet'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, DropdownMenuSeparator } from '@/components/ui/dropdown-menu'
import { Checkbox } from '@/components/ui/checkbox'
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Progress } from '@/components/ui/progress'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Skeleton } from '@/components/ui/skeleton'
import {
  BarChart, Bar, LineChart, Line, PieChart, Pie, Cell,
  XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer
} from 'recharts'
import { motion, AnimatePresence } from 'framer-motion'
import { format, formatDistanceToNow, parseISO } from 'date-fns'
import { es } from 'date-fns/locale'
import {
  Headset, Star, Home, MessageSquarePlus, User, LayoutDashboard,
  Users, UserPlus, BarChart3, FileText, Bell, Menu, LogOut,
  ChevronLeft, Clock, AlertTriangle, CheckCircle, XCircle,
  Eye, Send, Camera, Upload, Search, Filter, Download,
  Settings, Shield, TrendingUp, TrendingDown, Activity,
  MessageSquare, ThumbsUp, ThumbsDown, ArrowLeft, Plus,
  Loader2, Check, X, ChevronRight, Info, Lock, Phone,
  Mail, Calendar, Tag, Image, Paperclip, Edit, Key, UserCheck, Trash2, ArrowLeftRight
} from 'lucide-react'

// ==================== TYPES ====================
type View = 'login' | 'customer-home' | 'customer-new-review' | 'customer-review-detail' |
  'supervisor-dashboard' | 'supervisor-respond' | 'supervisor-customers' | 'supervisor-register-customer' |
  'manager-dashboard' | 'manager-reviews' | 'manager-review-detail' | 'manager-reports' | 'profile' |
  'admin-users' | 'admin-assignments' | 'admin-cleanup'

// ==================== STAR RATING COMPONENT ====================
function StarRating({ value, onChange, size = 40, readOnly = false }: {
  value: number
  onChange?: (v: number) => void
  size?: number
  readOnly?: boolean
}) {
  const [hovered, setHovered] = useState(0)

  return (
    <div className="flex gap-1">
      {[1, 2, 3, 4, 5].map((star) => (
        <button
          key={star}
          type="button"
          disabled={readOnly}
          className={`transition-all duration-150 ${readOnly ? 'cursor-default' : 'cursor-pointer hover:scale-110'}`}
          onMouseEnter={() => !readOnly && setHovered(star)}
          onMouseLeave={() => !readOnly && setHovered(0)}
          onClick={() => !readOnly && onChange?.(star === value ? 0 : star)}
        >
          <Star
            size={size}
            className={`transition-colors duration-150 ${
              (hovered || value) >= star
                ? 'fill-[#FF9B2E] text-[#FF9B2E]'
                : 'fill-gray-200 text-gray-300'
            }`}
          />
        </button>
      ))}
    </div>
  )
}

// ==================== TIME ELAPSED HELPER ====================
function timeElapsed(dateStr: string): string {
  try {
    return formatDistanceToNow(parseISO(dateStr), { addSuffix: true, locale: es })
  } catch {
    return dateStr
  }
}

function formatDate(dateStr: string): string {
  try {
    return format(parseISO(dateStr), "d 'de' MMMM, yyyy", { locale: es })
  } catch {
    return dateStr
  }
}

// Helper: get photo URL that works in standalone production
// In standalone mode, /uploads/* is NOT served as static files,
// so we route through /api/files/* which reads from disk directly
// We include the auth token as a query param because <img> tags
// cannot send Authorization headers
function getPhotoUrl(storageKey: string): string {
  const cleanKey = storageKey.startsWith('/') ? storageKey.slice(1) : storageKey
  const token = useAuthStore.getState().token
  return `/api/files/${cleanKey}${token ? `?token=${encodeURIComponent(token)}` : ''}`
}

function formatShortDate(dateStr: string): string {
  try {
    return format(parseISO(dateStr), 'dd/MM/yyyy')
  } catch {
    return dateStr
  }
}

// ==================== CHART COLORS ====================
const CHART_COLORS = ['#2D5BFF', '#FF9B2E', '#1B2559', '#0D47A1', '#6B7280', '#FFD166']
const PIE_COLORS = ['#2D5BFF', '#FF9B2E', '#EF4444']

// ==================== MAIN APP ====================
export default function CustomerServiceApp() {
  const { user, token, isAuthenticated, login, logout, updateUser } = useAuthStore()
  const { toast } = useToast()

  const [currentView, setCurrentView] = useState<View>('login')
  const [selectedReviewId, setSelectedReviewId] = useState<string | null>(null)
  const [sidebarOpen, setSidebarOpen] = useState(false)
  const [unreadCount, setUnreadCount] = useState(0)

  // Data states
  const [myReviews, setMyReviews] = useState<Review[]>([])
  const [allReviews, setAllReviews] = useState<Review[]>([])
  const [reviewDetail, setReviewDetail] = useState<Review | null>(null)
  const [supervisorDashboard, setSupervisorDashboard] = useState<any>(null)
  const [managerDashboard, setManagerDashboard] = useState<any>(null)
  const [customers, setCustomers] = useState<any[]>([])
  const [notifications, setNotifications] = useState<Notification[]>([])
  const [reportSummary, setReportSummary] = useState<any>(null)
  const [reportBySupervisor, setReportBySupervisor] = useState<any>(null)
  const [reportRatings, setReportRatings] = useState<any>(null)
  const [loading, setLoading] = useState(false)
  const [managerReviewsTotal, setManagerReviewsTotal] = useState(0)
  const [managerReviewsPage, setManagerReviewsPage] = useState(1)

  // Filter states for manager reviews
  const [managerStatusFilter, setManagerStatusFilter] = useState('all')
  const [managerSentimentFilter, setManagerSentimentFilter] = useState('all')
  const [managerServiceTypeFilter, setManagerServiceTypeFilter] = useState('all')
  const [customerSearch, setCustomerSearch] = useState('')

  // Admin data states
  const [adminUsers, setAdminUsers] = useState<any[]>([])
  const [adminManagers, setAdminManagers] = useState<any[]>([])
  const [adminAdmins, setAdminAdmins] = useState<any[]>([])
  const [adminSupervisors, setAdminSupervisors] = useState<any[]>([])
  const [cleanupOptions, setCleanupOptions] = useState<any[]>([])
  const [adminUserTab, setAdminUserTab] = useState<'customers' | 'supervisors' | 'managers' | 'admins'>('customers')
  const [adminEditUser, setAdminEditUser] = useState<any>(null)
  const [adminResetPwdUser, setAdminResetPwdUser] = useState<any>(null)
  const [adminAssignUser, setAdminAssignUser] = useState<any>(null)

  // Get default view based on role
  const getDefaultView = useCallback((role: UserRole): View => {
    switch (role) {
      case 'CUSTOMER': return 'customer-home'
      case 'SUPERVISOR': return 'supervisor-dashboard'
      case 'MANAGER': return 'manager-dashboard'
      case 'ADMIN': return 'admin-users'
      default: return 'login'
    }
  }, [])

  // Refresh user profile on mount (to get company field if cached session is stale)
  useEffect(() => {
    if (isAuthenticated && user) {
      api.getMe().then((data) => {
        if (data.user) {
          updateUser({
            company: data.user.company,
            phone: data.user.phone,
          })
        }
      }).catch(() => { /* ignore */ })
    }
  }, [])

  // Set initial view when auth changes
  useEffect(() => {
    if (isAuthenticated && user) {
      if (currentView === 'login') {
        setCurrentView(getDefaultView(user.role))
      }
      fetchUnreadCount()
    } else {
      setCurrentView('login')
    }
  }, [isAuthenticated, user, getDefaultView])

  // Poll unread count
  useEffect(() => {
    if (!isAuthenticated) return
    const interval = setInterval(fetchUnreadCount, 30000)
    return () => clearInterval(interval)
  }, [isAuthenticated])

  const fetchUnreadCount = async () => {
    try {
      const data = await api.getUnreadCount()
      setUnreadCount(data.count)
    } catch { /* ignore */ }
  }

  // Navigate helper
  const navigate = (view: View, reviewId?: string) => {
    setCurrentView(view)
    if (reviewId) setSelectedReviewId(reviewId)
    setSidebarOpen(false)
  }

  // ==================== DATA FETCHERS ====================
  const fetchMyReviews = async () => {
    setLoading(true)
    try {
      const data = await api.getMyReviews()
      setMyReviews(data.reviews || [])
    } catch (err: any) {
      toast({ title: 'Error', description: err.message, variant: 'destructive' })
    } finally {
      setLoading(false)
    }
  }

  const fetchAllReviews = async (params?: Record<string, string>) => {
    setLoading(true)
    try {
      const data = await api.getReviews(params)
      setAllReviews(data.reviews || [])
      setManagerReviewsTotal(data.total || 0)
    } catch (err: any) {
      toast({ title: 'Error', description: err.message, variant: 'destructive' })
    } finally {
      setLoading(false)
    }
  }

  const fetchReviewDetail = async (id: string) => {
    setLoading(true)
    try {
      const data = await api.getReview(id)
      setReviewDetail(data.review)
    } catch (err: any) {
      toast({ title: 'Error', description: err.message, variant: 'destructive' })
    } finally {
      setLoading(false)
    }
  }

  const fetchSupervisorDashboard = async () => {
    setLoading(true)
    try {
      const data = await api.getSupervisorDashboard()
      setSupervisorDashboard(data)
    } catch (err: any) {
      toast({ title: 'Error', description: err.message, variant: 'destructive' })
    } finally {
      setLoading(false)
    }
  }

  const fetchManagerDashboard = async () => {
    setLoading(true)
    try {
      const data = await api.getManagerDashboard()
      setManagerDashboard(data)
    } catch (err: any) {
      toast({ title: 'Error', description: err.message, variant: 'destructive' })
    } finally {
      setLoading(false)
    }
  }

  const fetchCustomers = async (search?: string) => {
    setLoading(true)
    try {
      const params: Record<string, string> = {}
      if (search) params.search = search
      const data = await api.getCustomers(params)
      setCustomers(data.customers || [])
    } catch (err: any) {
      toast({ title: 'Error', description: err.message, variant: 'destructive' })
    } finally {
      setLoading(false)
    }
  }

  const fetchNotifications = async () => {
    try {
      const data = await api.getNotifications()
      setNotifications(data.notifications || [])
    } catch { /* ignore */ }
  }

  const fetchReports = async () => {
    setLoading(true)
    try {
      const [summary, bySupervisor, ratings] = await Promise.all([
        api.getReportSummary(),
        api.getReportBySupervisor(),
        api.getReportRatings(),
      ])
      setReportSummary(summary)
      setReportBySupervisor(bySupervisor)
      setReportRatings(ratings)
    } catch (err: any) {
      toast({ title: 'Error', description: err.message, variant: 'destructive' })
    } finally {
      setLoading(false)
    }
  }

  const fetchAdminUsers = async () => {
    setLoading(true)
    try {
      const [custData, supData, mgrData, admData] = await Promise.all([
        api.getCustomers(),
        api.getSupervisors(),
        api.getManagers().catch(() => ({ managers: [] })),
        api.getAdmins().catch(() => ({ admins: [] })),
      ])
      setAdminUsers(custData.customers || [])
      setAdminSupervisors(supData.supervisors || [])
      setAdminManagers(mgrData.managers || [])
      setAdminAdmins(admData.admins || [])
    } catch (err: any) {
      toast({ title: 'Error', description: err.message, variant: 'destructive' })
    } finally {
      setLoading(false)
    }
  }

  const fetchCleanupData = async () => {
    setLoading(true)
    try {
      const data = await api.getCleanupOptions()
      setCleanupOptions(data.cleanupOptions || [])
    } catch (err: any) {
      toast({ title: 'Error', description: err.message, variant: 'destructive' })
    } finally {
      setLoading(false)
    }
  }

  // Load data when view changes
  useEffect(() => {
    if (!isAuthenticated) return
    switch (currentView) {
      case 'customer-home': fetchMyReviews(); break
      case 'customer-review-detail':
        if (selectedReviewId) fetchReviewDetail(selectedReviewId)
        break
      case 'supervisor-dashboard': fetchSupervisorDashboard(); break
      case 'supervisor-respond':
        if (selectedReviewId) fetchReviewDetail(selectedReviewId)
        break
      case 'supervisor-customers': fetchCustomers(); break
      case 'manager-dashboard': fetchManagerDashboard(); break
      case 'manager-reviews': {
        const params: Record<string, string> = { page: managerReviewsPage.toString() }
        if (managerStatusFilter !== 'all') params.status = managerStatusFilter
        if (managerSentimentFilter !== 'all') params.sentiment = managerSentimentFilter
        if (managerServiceTypeFilter !== 'all') params.serviceType = managerServiceTypeFilter
        fetchAllReviews(params)
        break
      }
      case 'manager-review-detail':
        if (selectedReviewId) fetchReviewDetail(selectedReviewId)
        // Load supervisors for reassignment dropdown
        if (user?.role === 'ADMIN' || user?.role === 'MANAGER') {
          api.getSupervisors().then(d => setAdminSupervisors(d.supervisors || [])).catch(() => {})
        }
        break
      case 'manager-reports': fetchReports(); break
      case 'admin-users': fetchAdminUsers(); break
      case 'admin-assignments': fetchAdminUsers(); break
      case 'admin-cleanup': fetchCleanupData(); break
    }
  }, [currentView, selectedReviewId, managerReviewsPage, managerStatusFilter, managerSentimentFilter, managerServiceTypeFilter])

  // ==================== APP LAYOUT COMPUTED VALUES ====================
  const navItems = useMemo(() => {
    if (!user) return []
    switch (user.role) {
      case 'CUSTOMER':
        return [
          { icon: Home, label: 'Inicio', view: 'customer-home' as View },
          { icon: MessageSquarePlus, label: 'Nueva Observación', view: 'customer-new-review' as View },
          { icon: User, label: 'Mi Perfil', view: 'profile' as View },
        ]
      case 'SUPERVISOR':
        return [
          { icon: LayoutDashboard, label: 'Panel', view: 'supervisor-dashboard' as View },
          { icon: Users, label: 'Clientes', view: 'supervisor-customers' as View },
          { icon: UserPlus, label: 'Registrar Cliente', view: 'supervisor-register-customer' as View },
          { icon: User, label: 'Mi Perfil', view: 'profile' as View },
        ]
      case 'MANAGER':
        return [
          { icon: LayoutDashboard, label: 'Panel', view: 'manager-dashboard' as View },
          { icon: FileText, label: 'Reseñas', view: 'manager-reviews' as View },
          { icon: BarChart3, label: 'Reportes', view: 'manager-reports' as View },
          { icon: User, label: 'Mi Perfil', view: 'profile' as View },
        ]
      case 'ADMIN':
        return [
          { icon: Users, label: 'Gestión Usuarios', view: 'admin-users' as View },
          { icon: UserCheck, label: 'Asignaciones', view: 'admin-assignments' as View },
          { icon: Trash2, label: 'Limpieza', view: 'admin-cleanup' as View },
          { icon: FileText, label: 'Reseñas', view: 'manager-reviews' as View },
          { icon: User, label: 'Mi Perfil', view: 'profile' as View },
        ]
      default: return []
    }
  }, [user])

  const pageTitle = useMemo(() => {
    switch (currentView) {
      case 'customer-home': return 'Inicio'
      case 'customer-new-review': return 'Nueva Observación'
      case 'customer-review-detail': return 'Detalle de Reseña'
      case 'supervisor-dashboard': return 'Panel de Supervisión'
      case 'supervisor-respond': return 'Responder Reseña'
      case 'supervisor-customers': return 'Clientes'
      case 'supervisor-register-customer': return 'Registrar Cliente'
      case 'manager-dashboard': return 'Panel de Gerencia'
      case 'manager-reviews': return 'Todas las Reseñas'
      case 'manager-review-detail': return 'Detalle de Reseña'
      case 'manager-reports': return 'Reportes'
      case 'admin-users': return 'Gestión de Usuarios'
      case 'admin-assignments': return 'Asignaciones'
      case 'admin-cleanup': return 'Limpieza de Datos'
      case 'profile': return 'Mi Perfil'
      default: return ''
    }
  }, [currentView])

  // ==================== LOGIN SCREEN ====================
  if (!isAuthenticated) {
    return <LoginScreen />
  }

  // ==================== APP LAYOUT ====================
  const SidebarContent = () => (
    <div className="flex flex-col h-full bg-white/72 backdrop-blur-[18px] border-r border-white/40 text-[#1B2559]">
      {/* Logo */}
      <div className="p-4 border-b border-[#C7D4F0]">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-lg flex items-center justify-center">
            <img src="/totes-logo.png" alt="Totes" className="w-10 h-10 rounded-lg object-contain" />
          </div>
          <div>
            <h1 className="font-[family-name:var(--font-dm-serif)] text-lg leading-tight text-[#1B2559]">Totes Ltda.</h1>
            <h1 className="text-xs text-[#6B7280] font-[family-name:var(--font-plus-jakarta)] uppercase tracking-wider">Atención al Cliente</h1>
          </div>
        </div>
      </div>

      {/* Navigation */}
      <nav className="flex-1 p-3 space-y-1">
        {navItems.map((item) => (
          <button
            key={item.view}
            onClick={() => navigate(item.view)}
            className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 ${
              currentView === item.view
                ? 'bg-gradient-to-br from-[#FF9B2E] to-[#FFB347] text-white shadow-md font-bold'
                : 'text-[#1B2559] hover:bg-[#2D5BFF]/8 hover:text-[#2D5BFF]'
            }`}
          >
            <item.icon className="w-5 h-5" />
            {item.label}
          </button>
        ))}
      </nav>

      {/* User Info & Logout */}
      <div className="p-3 border-t border-[#C7D4F0]">
        <div className="flex items-center gap-3 px-3 py-2 mb-2">
          <Avatar className="w-8 h-8">
            <AvatarFallback className="bg-[#2D5BFF] text-white text-xs">
              {user?.name?.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase()}
            </AvatarFallback>
          </Avatar>
          <div className="flex-1 min-w-0">
            <p className="text-sm font-medium text-[#1B2559] truncate">{user?.name}</p>
            <p className="text-xs text-[#6B7280]">{ROLE_LABELS[user?.role as UserRole]}</p>
          </div>
        </div>
        <Button
          variant="ghost"
          className="w-full justify-start gap-3 text-[#6B7280] hover:text-[#2D5BFF] hover:bg-[#2D5BFF]/8"
          onClick={() => { logout(); setCurrentView('login') }}
        >
          <LogOut className="w-4 h-4" />
          Cerrar Sesión
        </Button>
      </div>
    </div>
  )

  return (
    <div className="flex h-screen bg-gradient-to-b from-[#F8FAFF] to-[#EEF3FF]">
      {/* Desktop Sidebar */}
      <aside className="hidden md:flex md:w-64 md:flex-col md:fixed md:inset-y-0">
        <SidebarContent />
      </aside>

      {/* Mobile Sidebar */}
      <Sheet open={sidebarOpen} onOpenChange={setSidebarOpen}>
        <SheetContent side="left" className="p-0 w-64">
          <SheetTitle className="sr-only">Menú de Navegación</SheetTitle>
          <SidebarContent />
        </SheetContent>
      </Sheet>

      {/* Main Content */}
      <main className="flex-1 md:ml-64 flex flex-col min-h-screen">
        {/* Top Bar */}
        <header className="sticky top-0 z-40 bg-white border-b border-[#E2E8F0] shadow-[0_8px_24px_rgba(15,23,42,0.06)]">
          <div className="flex items-center justify-between h-14 px-4">
            <div className="flex items-center gap-3">
              <Button
                variant="ghost"
                size="icon"
                className="md:hidden"
                onClick={() => setSidebarOpen(true)}
              >
                <Menu className="w-5 h-5" />
              </Button>
              {(currentView !== getDefaultView(user?.role as UserRole)) && (
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => navigate(getDefaultView(user?.role as UserRole))}
                >
                  <ChevronLeft className="w-5 h-5" />
                </Button>
              )}
              <h2 className="text-lg font-semibold text-[#1B2559] font-[family-name:var(--font-plus-jakarta)]">{pageTitle}</h2>
            </div>
            <div className="flex items-center gap-2">
              {/* Notifications */}
              <Dialog>
                <DialogTrigger asChild>
                  <Button variant="ghost" size="icon" className="relative" onClick={fetchNotifications}>
                    <Bell className="w-5 h-5" />
                    {unreadCount > 0 && (
                      <span className="absolute -top-1 -right-1 w-5 h-5 bg-[#FF9B2E] text-white text-xs rounded-full flex items-center justify-center">
                        {unreadCount > 9 ? '9+' : unreadCount}
                      </span>
                    )}
                  </Button>
                </DialogTrigger>
                <DialogContent className="max-w-md">
                  <DialogHeader>
                    <DialogTitle>Notificaciones</DialogTitle>
                    <DialogDescription>Tus notificaciones recientes</DialogDescription>
                  </DialogHeader>
                  <ScrollArea className="max-h-96">
                    {notifications.length === 0 ? (
                      <p className="text-sm text-gray-500 text-center py-4">No hay notificaciones</p>
                    ) : (
                      <div className="space-y-2">
                        {notifications.map((n) => (
                          <div
                            key={n.id}
                            className={`p-3 rounded-lg border ${n.isRead ? 'bg-white' : 'bg-blue-50 border-blue-200'}`}
                          >
                            <div className="flex items-start justify-between gap-2">
                              <div>
                                <p className="text-sm font-medium">{n.title}</p>
                                <p className="text-xs text-gray-500 mt-0.5">{n.message}</p>
                                <p className="text-xs text-gray-400 mt-1">{timeElapsed(n.createdAt)}</p>
                              </div>
                              {!n.isRead && (
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="text-xs shrink-0"
                                  onClick={async () => {
                                    await api.markNotificationRead(n.id)
                                    fetchNotifications()
                                    fetchUnreadCount()
                                  }}
                                >
                                  <Check className="w-3 h-3" />
                                </Button>
                              )}
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </ScrollArea>
                  {notifications.length > 0 && (
                    <Button
                      variant="outline"
                      size="sm"
                      className="w-full"
                      onClick={async () => {
                        await api.markAllNotificationsRead()
                        fetchNotifications()
                        fetchUnreadCount()
                        toast({ title: 'Notificaciones marcadas como leídas' })
                      }}
                    >
                      Marcar todas como leídas
                    </Button>
                  )}
                </DialogContent>
              </Dialog>

              {/* User Menu */}
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" className="flex items-center gap-2">
                    <Avatar className="w-8 h-8">
                      <AvatarFallback className="bg-[#2D5BFF] text-white text-xs">
                        {user?.name?.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase()}
                      </AvatarFallback>
                    </Avatar>
                    <span className="hidden sm:block text-sm">{user?.name}</span>
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuItem onClick={() => navigate('profile')}>
                    <User className="w-4 h-4 mr-2" />
                    Mi Perfil
                  </DropdownMenuItem>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem onClick={() => { logout(); setCurrentView('login') }}>
                    <LogOut className="w-4 h-4 mr-2" />
                    Cerrar Sesión
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </div>
        </header>

        {/* Page Content */}
        <div className="flex-1 p-4 md:p-6 overflow-auto">
          <AnimatePresence mode="wait">
            <motion.div
              key={currentView}
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -10 }}
              transition={{ duration: 0.2 }}
            >
              {renderView()}
            </motion.div>
          </AnimatePresence>
        </div>
      </main>
    </div>
  )

  // ==================== VIEW ROUTER ====================
  function renderView() {
    switch (currentView) {
      case 'customer-home': return <CustomerHome />
      case 'customer-new-review': return <CustomerNewReview />
      case 'customer-review-detail': return <CustomerReviewDetail />
      case 'supervisor-dashboard': return <SupervisorDashboard />
      case 'supervisor-respond': return <SupervisorRespond />
      case 'supervisor-customers': return <SupervisorCustomers />
      case 'supervisor-register-customer': return <SupervisorRegisterCustomer />
      case 'manager-dashboard': return <ManagerDashboard />
      case 'manager-reviews': return <ManagerReviews />
      case 'manager-review-detail': return <ManagerReviewDetail />
      case 'manager-reports': return <ManagerReports />
      case 'admin-users': return <AdminUsers />
      case 'admin-assignments': return <AdminAssignments />
      case 'admin-cleanup': return <AdminCleanup />
      case 'profile': return <ProfileView />
      default: return null
    }
  }

  // ==================== LOGIN SCREEN ====================
  function LoginScreen() {
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const [loginLoading, setLoginLoading] = useState(false)
    const [error, setError] = useState('')

    const handleLogin = async (e: React.FormEvent) => {
      e.preventDefault()
      setError('')
      setLoginLoading(true)
      try {
        const data = await api.login(email, password)
        login(
          {
            id: data.user.id,
            email: data.user.email,
            name: data.user.name,
            company: data.user.company,
            role: data.user.role as UserRole,
          },
          data.token
        )
        toast({ title: '¡Bienvenido!', description: `Hola, ${data.user.name}` })
      } catch (err: any) {
        setError(err.message || 'Error al iniciar sesión')
      } finally {
        setLoginLoading(false)
      }
    }

    const fillCredentials = (e: string, p: string) => {
      setEmail(e)
      setPassword(p)
    }

    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-b from-[#F8FAFF] to-[#EEF3FF] p-4">
        <motion.div
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.4 }}
          className="w-full max-w-md"
        >
          <Card className="shadow-xl border border-white/50 rounded-2xl overflow-hidden bg-white/78 backdrop-blur-[16px]">
            <CardHeader className="text-center pb-2 bg-[#E9EEFF] text-[#1B2559]">
              <div className="mx-auto w-20 h-20 rounded-2xl flex items-center justify-center mb-4 shadow-lg overflow-hidden bg-white/10">
                <img src="/totes-logo.png" alt="Totes" className="w-16 h-16 object-contain" />
              </div>
              <CardTitle className="text-2xl font-bold font-[family-name:var(--font-dm-serif)]">Totes Ltda.</CardTitle>
              <CardDescription className="text-[#6B7280]">Sistema de Atención al Cliente</CardDescription>
            </CardHeader>
            <CardContent className="pt-4">
              <form onSubmit={handleLogin} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="email">Correo electrónico</Label>
                  <div className="relative">
                    <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                    <Input
                      id="email"
                      type="email"
                      placeholder="correo@empresa.com"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      className="pl-10"
                      required
                    />
                  </div>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="password">Contraseña</Label>
                  <div className="relative">
                    <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                    <Input
                      id="password"
                      type="password"
                      placeholder="••••••••"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      className="pl-10"
                      required
                    />
                  </div>
                </div>
                {error && (
                  <motion.div
                    initial={{ opacity: 0, y: -5 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="flex items-center gap-2 p-3 rounded-lg bg-red-50 border border-red-200 text-red-700 text-sm"
                  >
                    <AlertTriangle className="w-4 h-4 shrink-0" />
                    {error}
                  </motion.div>
                )}
                <Button
                  type="submit"
                  className="w-full bg-gradient-to-br from-[#FF9B2E] to-[#FFB347] hover:from-[#FFB347] hover:to-[#FF9B2E] text-white"
                  disabled={loginLoading}
                  size="lg"
                >
                  {loginLoading ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      Iniciando sesión...
                    </>
                  ) : (
                    'Iniciar Sesión'
                  )}
                </Button>
              </form>
            </CardContent>
            <CardFooter className="flex-col gap-4">
              <Separator />
              <div className="w-full">
                <p className="text-xs text-gray-500 text-center mb-3">Credenciales de demostración:</p>
                <div className="grid gap-2">
                  <button
                    onClick={() => fillCredentials('cliente1@empresa.com.bo', 'password123')}
                    className="flex items-center gap-2 p-2 rounded-lg border border-[#FFE0B5] hover:bg-[#FFF5E6] transition-colors text-sm text-left"
                  >
                    <div className="w-8 h-8 rounded-full bg-[#FFF5E6] flex items-center justify-center shrink-0">
                      <User className="w-4 h-4 text-[#FF9B2E]" />
                    </div>
                    <div>
                      <p className="font-medium text-gray-900">Cliente</p>
                      <p className="text-xs text-gray-500">cliente1@empresa.com.bo</p>
                    </div>
                  </button>
                  <button
                    onClick={() => fillCredentials('supervisor1@totes.com.bo', 'password123')}
                    className="flex items-center gap-2 p-2 rounded-lg border border-[#FFE0B5] hover:bg-[#FFF5E6] transition-colors text-sm text-left"
                  >
                    <div className="w-8 h-8 rounded-full bg-[#E9EEFF] flex items-center justify-center shrink-0">
                      <Shield className="w-4 h-4 text-[#2D5BFF]" />
                    </div>
                    <div>
                      <p className="font-medium text-gray-900">Supervisor</p>
                      <p className="text-xs text-gray-500">supervisor1@totes.com.bo</p>
                    </div>
                  </button>
                  <button
                    onClick={() => fillCredentials('gerencia@totes.com.bo', 'password123')}
                    className="flex items-center gap-2 p-2 rounded-lg border border-[#1B2559] hover:bg-[#E9EEFF] transition-colors text-sm text-left"
                  >
                    <div className="w-8 h-8 rounded-full bg-[#E9EEFF] flex items-center justify-center shrink-0">
                      <BarChart3 className="w-4 h-4 text-[#2D5BFF]" />
                    </div>
                    <div>
                      <p className="font-medium text-gray-900">Gerencia</p>
                      <p className="text-xs text-gray-500">gerencia@totes.com.bo</p>
                    </div>
                  </button>
                  <button
                    onClick={() => fillCredentials('admin@totes.com.bo', '%%S0p0rt326')}
                    className="flex items-center gap-3 p-3 rounded-xl hover:bg-white/50 transition-colors w-full text-left"
                  >
                    <div className="w-8 h-8 rounded-full bg-purple-100 flex items-center justify-center shrink-0">
                      <Shield className="w-4 h-4 text-purple-600" />
                    </div>
                    <div>
                      <p className="font-medium text-gray-900">Administrador</p>
                      <p className="text-xs text-gray-500">admin</p>
                    </div>
                  </button>
                </div>
              </div>
              <p className="text-xs text-gray-400 text-center">
                © {new Date().getFullYear()} Totes Ltda. — Atención al Cliente
              </p>
            </CardFooter>
          </Card>
        </motion.div>
      </div>
    )
  }

  // ==================== CUSTOMER HOME ====================
  function CustomerHome() {
    const getGreeting = () => {
      const hour = new Date().getHours()
      if (hour >= 5 && hour < 12) return 'Buenos días'
      if (hour >= 12 && hour < 18) return 'Buenas tardes'
      return 'Buenas noches'
    }

    return (
      <div className="space-y-6 max-w-4xl mx-auto">
        {/* Welcome */}
        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
          <div>
            <h1 className="font-[family-name:var(--font-dm-serif)] text-2xl font-bold text-[#1B2559]">
              {getGreeting()}, {user?.name}
            </h1>
            {user?.company && (
              <p className="text-[#2D5BFF] mt-1 font-[family-name:var(--font-plus-jakarta)] text-base font-semibold tracking-wide">{user.company}</p>
            )}
          </div>
          <Button
            onClick={() => navigate('customer-new-review')}
            className="bg-gradient-to-br from-[#FF9B2E] to-[#FFB347] hover:from-[#FFB347] hover:to-[#FF9B2E] text-white shadow-lg shadow-[rgba(45,91,255,0.08)]"
            size="lg"
          >
            <Star className="w-5 h-5 mr-2" />
            Nueva Observación
          </Button>
        </div>

        {/* Reviews List */}
        <div>
          <h2 className="text-lg font-semibold text-gray-900 mb-4">Mis Reseñas</h2>
          {loading ? (
            <div className="space-y-3">
              {[1, 2, 3].map(i => (
                <Skeleton key={i} className="h-32 w-full rounded-xl" />
              ))}
            </div>
          ) : myReviews.length === 0 ? (
            <Card className="text-center py-12">
              <CardContent>
                <MessageSquare className="w-12 h-12 text-gray-300 mx-auto mb-4" />
                <p className="text-gray-500">Aún no tienes reseñas</p>
                <p className="text-sm text-gray-400 mt-1">¡Califica tu primera experiencia!</p>
                <Button
                  onClick={() => navigate('customer-new-review')}
                  className="mt-4 bg-gradient-to-br from-[#FF9B2E] to-[#FFB347] hover:from-[#FFB347] hover:to-[#FF9B2E] text-white"
                >
                  <Plus className="w-4 h-4 mr-2" />
                  Crear Observación
                </Button>
              </CardContent>
            </Card>
          ) : (
            <div className="grid gap-4">
              {myReviews.map((review) => (
                <Card
                  key={review.id}
                  className="cursor-pointer hover:shadow-md transition-shadow border-l-4"
                  style={{ borderLeftColor: review.sentiment === 'NEGATIVE' ? '#EF4444' : '#2D5BFF' }}
                  onClick={() => {
                    setSelectedReviewId(review.id)
                    navigate('customer-review-detail')
                  }}
                >
                  <CardContent className="p-4">
                    <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1">
                          <StarRating value={review.rating} readOnly size={18} />
                          <Badge className={STATUS_COLORS[review.status as keyof typeof STATUS_COLORS]}>
                            {STATUS_LABELS[review.status as keyof typeof STATUS_LABELS]}
                          </Badge>
                        </div>
                        <h3 className="font-semibold text-gray-900 truncate">{review.title}</h3>
                        <p className="text-sm text-gray-500 mt-1 line-clamp-2">{review.content}</p>
                        <div className="flex items-center gap-3 mt-2 text-xs text-gray-400">
                          <span className="flex items-center gap-1">
                            <Tag className="w-3 h-3" />
                            {review.serviceType}
                          </span>
                          <span className="flex items-center gap-1">
                            <Calendar className="w-3 h-3" />
                            {formatShortDate(review.serviceDate)}
                          </span>
                          <span>{timeElapsed(review.createdAt)}</span>
                        </div>
                      </div>
                      <ChevronRight className="w-5 h-5 text-gray-300 shrink-0" />
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </div>
      </div>
    )
  }

  // ==================== NEW REVIEW ====================
  function CustomerNewReview() {
    const [rating, setRating] = useState(0)
    const [title, setTitle] = useState('')
    const [content, setContent] = useState('')
    const [serviceType, setServiceType] = useState('')
    const [subType, setSubType] = useState('')
    const [serviceDate, setServiceDate] = useState('')
    const [photos, setPhotos] = useState<File[]>([])
    const [submitting, setSubmitting] = useState(false)
    const [submitted, setSubmitted] = useState(false)

    const isPersonnelService = serviceType === 'Asistencia del personal Totes'
    const isImageService = serviceType === 'Imagen del personal'
    const isOtherService = serviceType !== '' && !isPersonnelService && !isImageService

    const handlePhotoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      const files = Array.from(e.target.files || [])
      const remaining = 3 - photos.length
      const toAdd = files.slice(0, remaining)
      setPhotos(prev => [...prev, ...toAdd])
    }

    const removePhoto = (index: number) => {
      setPhotos(prev => prev.filter((_, i) => i !== index))
    }

    const handleServiceTypeChange = (value: string) => {
      setServiceType(value)
      setSubType('')
    }

    const handleSubmit = async (e: React.FormEvent) => {
      e.preventDefault()
      if (!rating || !serviceType || !serviceDate) {
        toast({ title: 'Campos incompletos', description: 'Por favor completa todos los campos requeridos', variant: 'destructive' })
        return
      }
      if ((isPersonnelService || isImageService) && !subType) {
        toast({ title: 'Campos incompletos', description: 'Por favor selecciona la aclaración de la observación', variant: 'destructive' })
        return
      }
      if (isOtherService && !content) {
        toast({ title: 'Campos incompletos', description: 'Por favor describe tu observación', variant: 'destructive' })
        return
      }
      setSubmitting(true)
      try {
        await api.createReview({
          rating,
          title: title || `${serviceType}${subType ? ` - ${subType}` : ''}`,
          content: content || (subType || 'Sin comentarios adicionales'),
          serviceDate,
          serviceType,
          subType: subType || undefined,
        }, photos.length > 0 ? photos : undefined)
        setSubmitted(true)
      } catch (err: any) {
        toast({ title: 'Error', description: err.message, variant: 'destructive' })
      } finally {
        setSubmitting(false)
      }
    }

    if (submitted) {
      return (
        <motion.div
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          className="max-w-lg mx-auto text-center py-16"
        >
          <motion.div
            initial={{ scale: 0 }}
            animate={{ scale: 1 }}
            transition={{ delay: 0.2, type: 'spring', stiffness: 200 }}
          >
            <div className="w-20 h-20 rounded-full bg-orange-50 flex items-center justify-center mx-auto mb-6">
              <CheckCircle className="w-10 h-10 text-[#FF9B2E]" />
            </div>
          </motion.div>
          <h2 className="text-2xl font-bold text-gray-900 mb-2">¡Observación registrada!</h2>
          <p className="text-gray-600 mb-6 max-w-md mx-auto">
            Se asignará su observación al supervisor correspondiente y se tomará acciones necesarias con el área de recursos humanos.
          </p>
          <Button onClick={() => { setSubmitted(false); navigate('customer-home') }} className="bg-gradient-to-br from-[#FF9B2E] to-[#FFB347] hover:from-[#FFB347] hover:to-[#FF9B2E] text-white">
            <Home className="w-4 h-4 mr-2" />
            Volver al Inicio
          </Button>
        </motion.div>
      )
    }

    return (
      <div className="max-w-2xl mx-auto">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Star className="w-5 h-5 text-[#FF9B2E]" />
              Registrar Observación
            </CardTitle>
            <CardDescription>Su opinión es importante para mejorar nuestro servicio</CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-6">
              {/* Step 1 */}
              <div className="space-y-2">
                <Label className="text-base font-semibold flex items-center gap-2">
                  <span className="w-6 h-6 rounded-full bg-[#FF9B2E] text-white text-sm flex items-center justify-center font-bold">1</span>
                  Observación al servicio *
                </Label>
                <Select value={serviceType} onValueChange={handleServiceTypeChange}>
                  <SelectTrigger>
                    <SelectValue placeholder="Selecciona el tipo de servicio" />
                  </SelectTrigger>
                  <SelectContent>
                    {SERVICE_TYPES.map((type) => (
                      <SelectItem key={type} value={type}>{type}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* Step 2 */}
              {serviceType && (
                <motion.div
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: 'auto' }}
                  className="space-y-2"
                >
                  <Label className="text-base font-semibold flex items-center gap-2">
                    <span className="w-6 h-6 rounded-full bg-[#FF9B2E] text-white text-sm flex items-center justify-center font-bold">2</span>
                    Aclaración de la observación *
                  </Label>
                  {isPersonnelService && (
                    <Select value={subType} onValueChange={setSubType}>
                      <SelectTrigger>
                        <SelectValue placeholder="Selecciona el tipo de incidencia" />
                      </SelectTrigger>
                      <SelectContent>
                        {PERSONNEL_SUB_TYPES.map((type) => (
                          <SelectItem key={type} value={type}>{type}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  )}
                  {isImageService && (
                    <Select value={subType} onValueChange={setSubType}>
                      <SelectTrigger>
                        <SelectValue placeholder="Selecciona el tipo de incidencia" />
                      </SelectTrigger>
                      <SelectContent>
                        {IMAGE_SUB_TYPES.map((type) => (
                          <SelectItem key={type} value={type}>{type}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  )}
                  {isOtherService && (
                    <Textarea
                      value={content}
                      onChange={(e) => setContent(e.target.value)}
                      placeholder="Detalle y aclare su observación..."
                      rows={4}
                      required
                    />
                  )}
                </motion.div>
              )}

              {/* Step 3 */}
              <div className="space-y-2">
                <Label className="text-base font-semibold flex items-center gap-2">
                  <span className="w-6 h-6 rounded-full bg-[#FF9B2E] text-white text-sm flex items-center justify-center font-bold">3</span>
                  Calificación *
                </Label>
                <div className="flex justify-center py-4">
                  <StarRating value={rating} onChange={setRating} size={48} />
                </div>
                {rating > 0 && (
                  <motion.p
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    className={`text-center text-sm font-medium ${rating <= 2 ? 'text-[#EF4444]' : 'text-[#2D5BFF]'}`}
                  >
                    {rating === 1 ? 'Muy malo' : rating === 2 ? 'Malo' : rating === 3 ? 'Regular' : rating === 4 ? 'Bueno' : 'Excelente'}
                  </motion.p>
                )}
              </div>

              {/* Service Date */}
              <div className="space-y-2">
                <Label htmlFor="service-date">Fecha del servicio *</Label>
                <Input
                  id="service-date"
                  type="date"
                  value={serviceDate}
                  onChange={(e) => setServiceDate(e.target.value)}
                  max={new Date().toISOString().split('T')[0]}
                  required
                />
              </div>

              {/* Photos */}
              <div className="space-y-2">
                <Label>Fotos (máximo 3)</Label>
                <div className="flex flex-wrap gap-3">
                  {photos.map((photo, i) => (
                    <div key={i} className="relative w-24 h-24 rounded-lg border-2 border-orange-200 overflow-hidden group">
                      <img
                        src={URL.createObjectURL(photo)}
                        alt={`Foto ${i + 1}`}
                        className="w-full h-full object-cover"
                      />
                      <button
                        type="button"
                        onClick={() => removePhoto(i)}
                        className="absolute top-1 right-1 w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
                      >
                        <X className="w-3 h-3" />
                      </button>
                    </div>
                  ))}
                  {photos.length < 3 && (
                    <label className="w-24 h-24 rounded-lg border-2 border-dashed border-gray-300 flex flex-col items-center justify-center cursor-pointer hover:border-orange-400 hover:bg-orange-50 transition-colors">
                      <Upload className="w-6 h-6 text-gray-400" />
                      <span className="text-xs text-gray-400 mt-1">Agregar</span>
                      <input
                        type="file"
                        accept="image/*"
                        onChange={handlePhotoChange}
                        className="hidden"
                        multiple
                      />
                    </label>
                  )}
                </div>
                <p className="text-xs text-gray-400">Arrastra o selecciona hasta 3 fotos (máx. 5MB cada una)</p>
              </div>

              {/* Submit */}
              <div className="flex gap-3">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => navigate('customer-home')}
                  className="flex-1"
                >
                  Cancelar
                </Button>
                <Button
                  type="submit"
                  className="flex-1 bg-gradient-to-br from-[#FF9B2E] to-[#FFB347] hover:from-[#FFB347] hover:to-[#FF9B2E] text-white"
                  disabled={submitting || !rating || !serviceType || !serviceDate}
                >
                  {submitting ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      Enviando...
                    </>
                  ) : (
                    <>
                      <Send className="w-4 h-4 mr-2" />
                      Enviar Observación
                    </>
                  )}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      </div>
    )
  }

  // ==================== CUSTOMER REVIEW DETAIL ====================
  function CustomerReviewDetail() {
    if (loading || !reviewDetail) {
      return (
        <div className="max-w-2xl mx-auto space-y-4">
          <Skeleton className="h-8 w-48" />
          <Skeleton className="h-64 w-full rounded-xl" />
        </div>
      )
    }

    const review = reviewDetail
    const response = review.responses?.[0]

    return (
      <div className="max-w-2xl mx-auto space-y-6">
        <Button variant="ghost" onClick={() => navigate('customer-home')} className="gap-2">
          <ArrowLeft className="w-4 h-4" />
          Volver a mis reseñas
        </Button>

        <Card>
          <CardHeader>
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
              <div>
                <div className="flex items-center gap-2 mb-2">
                  <Badge variant="outline" className="text-xs">{review.reviewCode}</Badge>
                  <Badge className={STATUS_COLORS[review.status as keyof typeof STATUS_COLORS]}>
                    {STATUS_LABELS[review.status as keyof typeof STATUS_LABELS]}
                  </Badge>
                  <Badge variant="outline" className={review.sentiment === 'NEGATIVE' ? 'text-red-600 border-red-200' : 'text-[#2D5BFF] border-blue-200'}>
                    {review.sentiment === 'NEGATIVE' ? 'Negativa' : 'Positiva'}
                  </Badge>
                </div>
                <CardTitle>{review.title}</CardTitle>
              </div>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center gap-2">
              <span className="text-sm font-medium text-gray-500">Calificación:</span>
              <StarRating value={review.rating} readOnly size={24} />
            </div>

            <div>
              <h4 className="text-sm font-medium text-gray-500 mb-1">Comentario</h4>
              <p className="text-gray-900 whitespace-pre-wrap">{review.content}</p>
            </div>

            <div className="grid grid-cols-2 gap-4 text-sm">
              <div>
                <span className="text-gray-500">Tipo de servicio:</span>
                <p className="font-medium">{review.serviceType}</p>
              </div>
              <div>
                <span className="text-gray-500">Fecha del servicio:</span>
                <p className="font-medium">{formatShortDate(review.serviceDate)}</p>
              </div>
              {review.subType && (
                <div>
                  <span className="text-gray-500">Aclaración:</span>
                  <p className="font-medium">{review.subType}</p>
                </div>
              )}
              <div>
                <span className="text-gray-500">Creada:</span>
                <p className="font-medium">{timeElapsed(review.createdAt)}</p>
              </div>
            </div>

            {/* Photos */}
            {review.photos && review.photos.length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-gray-500 mb-2">Fotos</h4>
                <div className="flex flex-wrap gap-3">
                  {review.photos.map((photo: ReviewPhoto) => (
                    <div key={photo.id} className="w-32 h-32 rounded-lg border overflow-hidden">
                      <img
                        src={getPhotoUrl(photo.storageKey)}
                        alt={photo.fileName}
                        className="w-full h-full object-cover"
                        onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; (e.target as HTMLImageElement).parentElement!.innerHTML = '<div class="w-full h-full bg-gray-100 flex items-center justify-center"><svg class="w-8 h-8 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg></div>' }}
                      />
                    </div>
                  ))}
                </div>
              </div>
            )}

            <Separator />

            {/* Response */}
            {response ? (
              <div className="bg-[#E9EEFF] border border-[#E2E8F0] rounded-lg p-4">
                <div className="flex items-center gap-2 mb-3">
                  <div className="w-8 h-8 rounded-full bg-[#2D5BFF]/20 flex items-center justify-center">
                    <Headset className="w-4 h-4 text-[#2D5BFF]" />
                  </div>
                  <div>
                    <p className="text-sm font-semibold text-[#2D5BFF]">
                      Respuesta del Supervisor
                    </p>
                    <p className="text-xs text-[#2D5BFF]/70">{timeElapsed(response.createdAt)}</p>
                  </div>
                </div>
                <p className="text-sm text-[#1B2559] whitespace-pre-wrap">{response.responseToClient}</p>
              </div>
            ) : (
              <div className="bg-[#FFF5E6] border border-[#FFE0B5] rounded-lg p-4 text-center">
                <Clock className="w-6 h-6 text-[#FFB347] mx-auto mb-2" />
                <p className="text-sm font-medium text-[#7A3D00]">Pendiente de respuesta</p>
                <p className="text-xs text-[#7A3D00]/70 mt-1">Un supervisor revisará tu reseña pronto</p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    )
  }

  // ==================== SUPERVISOR DASHBOARD ====================
  function SupervisorDashboard() {
    if (loading && !supervisorDashboard) {
      return (
        <div className="space-y-4">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {[1, 2, 3, 4].map(i => <Skeleton key={i} className="h-28 rounded-xl" />)}
          </div>
          <Skeleton className="h-64 rounded-xl" />
        </div>
      )
    }

    const dash = supervisorDashboard

    return (
      <div className="space-y-6">
        {/* KPI Cards */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <Card className="border-l-4 border-l-red-500">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs font-medium text-gray-500 uppercase">Pendientes</p>
                  <p className="text-2xl font-bold text-gray-900 mt-1">{dash?.pendingCount ?? 0}</p>
                </div>
                <div className="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
                  <AlertTriangle className="w-5 h-5 text-red-600" />
                </div>
              </div>
            </CardContent>
          </Card>
          <Card className="border-l-4 border-l-amber-500">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs font-medium text-gray-500 uppercase">En Proceso</p>
                  <p className="text-2xl font-bold text-gray-900 mt-1">{dash?.acknowledgedCount ?? 0}</p>
                </div>
                <div className="w-10 h-10 rounded-full bg-amber-100 flex items-center justify-center">
                  <Clock className="w-5 h-5 text-amber-600" />
                </div>
              </div>
            </CardContent>
          </Card>
          <Card className="border-l-4 border-l-[#2D5BFF]">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs font-medium text-[#6B7280] uppercase">Resueltas este mes</p>
                  <p className="text-2xl font-bold text-[#1B2559] mt-1">{dash?.resolvedThisMonth ?? 0}</p>
                </div>
                <div className="w-10 h-10 rounded-full bg-[#E9EEFF] flex items-center justify-center">
                  <CheckCircle className="w-5 h-5 text-[#2D5BFF]" />
                </div>
              </div>
            </CardContent>
          </Card>
          <Card className="border-l-4 border-l-[#FF9B2E]">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs font-medium text-[#6B7280] uppercase">Tiempo Prom.</p>
                  <p className="text-2xl font-bold text-[#1B2559] mt-1">{dash?.avgResponseTimeHours ? `${dash.avgResponseTimeHours.toFixed(1)}h` : '—'}</p>
                </div>
                <div className="w-10 h-10 rounded-full bg-[#FFF5E6] flex items-center justify-center">
                  <Activity className="w-5 h-5 text-[#FF9B2E]" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Assigned Reviews with Tabs */}
        <Card>
          <Tabs defaultValue="pending">
            <CardHeader className="pb-3">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                <TabsList className="w-full sm:w-auto">
                  <TabsTrigger value="pending" className="gap-1">
                    <AlertTriangle className="w-4 h-4" />
                    Pendientes
                    {dash?.assignedReviews && dash.assignedReviews.filter((r: any) => r.status === 'PENDING' || r.status === 'ACKNOWLEDGED').length > 0 && (
                      <Badge className="ml-1 bg-red-500 text-white text-xs px-1.5 py-0">
                        {dash.assignedReviews.filter((r: any) => r.status === 'PENDING' || r.status === 'ACKNOWLEDGED').length}
                      </Badge>
                    )}
                  </TabsTrigger>
                  <TabsTrigger value="all" className="gap-1">
                    <FileText className="w-4 h-4" />
                    Todas
                  </TabsTrigger>
                  <TabsTrigger value="resolved" className="gap-1">
                    <CheckCircle className="w-4 h-4" />
                    Resueltas
                  </TabsTrigger>
                </TabsList>
              </div>
            </CardHeader>
            <CardContent>
              <TabsContent value="pending">
                {dash?.assignedReviews && dash.assignedReviews.filter((r: any) => r.status === 'PENDING' || r.status === 'ACKNOWLEDGED').length > 0 ? (
                  <div className="space-y-3 max-h-96 overflow-y-auto">
                    {dash.assignedReviews
                      .filter((r: any) => r.status === 'PENDING' || r.status === 'ACKNOWLEDGED')
                      .sort((a: any, b: any) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())
                      .map((review: any) => (
                        <div
                          key={review.id}
                          className={`flex flex-col sm:flex-row sm:items-center justify-between p-3 rounded-lg border gap-3 ${
                            review.sentiment === 'NEGATIVE' ? 'border-red-100 bg-red-50' : 'border-blue-100 bg-blue-50'
                          }`}
                        >
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-1">
                              <StarRating value={review.rating} readOnly size={14} />
                              <Badge className={STATUS_COLORS[review.status as keyof typeof STATUS_COLORS]}>
                                {STATUS_LABELS[review.status as keyof typeof STATUS_LABELS]}
                              </Badge>
                              {review.sentiment === 'NEGATIVE' && (
                                <Badge variant="outline" className="text-red-600 border-red-200 text-xs">Negativa</Badge>
                              )}
                            </div>
                            <p className="font-medium text-sm text-gray-900 truncate">{review.title}</p>
                            <div className="flex items-center gap-2 text-xs text-gray-500 mt-1">
                              <span>{review.customer?.name || 'Cliente'}</span>
                              <span>•</span>
                              <span className="flex items-center gap-1"><Tag className="w-3 h-3" />{review.serviceType}</span>
                              <span>•</span>
                              <span>{timeElapsed(review.createdAt)}</span>
                            </div>
                          </div>
                          <div className="flex gap-2 shrink-0">
                            {review.status === 'PENDING' && (
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={async () => {
                                  try {
                                    await api.acknowledgeReview(review.id)
                                    fetchSupervisorDashboard()
                                    toast({ title: 'Reseña reconocida' })
                                  } catch (err: any) {
                                    toast({ title: 'Error', description: err.message, variant: 'destructive' })
                                  }
                                }}
                              >
                                <Check className="w-4 h-4 mr-1" />
                                Reconocer
                              </Button>
                            )}
                            <Button
                              size="sm"
                              className="bg-gradient-to-br from-[#FF9B2E] to-[#FFB347] hover:from-[#FFB347] hover:to-[#FF9B2E] text-white"
                              onClick={() => {
                                setSelectedReviewId(review.id)
                                navigate('supervisor-respond')
                              }}
                            >
                              <Eye className="w-4 h-4 mr-1" />
                              Gestionar
                            </Button>
                          </div>
                        </div>
                      ))}
                  </div>
                ) : (
                  <div className="text-center py-8">
                    <CheckCircle className="w-10 h-10 text-blue-400 mx-auto mb-3" />
                    <p className="text-gray-500">¡No hay reseñas pendientes!</p>
                  </div>
                )}
              </TabsContent>

              <TabsContent value="all">
                {dash?.assignedReviews && dash.assignedReviews.length > 0 ? (
                  <div className="space-y-3 max-h-96 overflow-y-auto">
                    {dash.assignedReviews
                      .sort((a: any, b: any) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
                      .map((review: any) => (
                        <div
                          key={review.id}
                          className="flex flex-col sm:flex-row sm:items-center justify-between p-3 rounded-lg border border-gray-200 hover:bg-gray-50 transition-colors gap-3"
                        >
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-1">
                              <StarRating value={review.rating} readOnly size={14} />
                              <Badge className={STATUS_COLORS[review.status as keyof typeof STATUS_COLORS]}>
                                {STATUS_LABELS[review.status as keyof typeof STATUS_LABELS]}
                              </Badge>
                              {review.sentiment === 'NEGATIVE' && (
                                <Badge variant="outline" className="text-red-600 border-red-200 text-xs">Negativa</Badge>
                              )}
                            </div>
                            <p className="font-medium text-sm text-gray-900 truncate">{review.title}</p>
                            <div className="flex items-center gap-2 text-xs text-gray-500 mt-1">
                              <span>{review.customer?.name || 'Cliente'}</span>
                              <span>•</span>
                              <span className="flex items-center gap-1"><Tag className="w-3 h-3" />{review.serviceType}</span>
                              <span>•</span>
                              <span>{timeElapsed(review.createdAt)}</span>
                            </div>
                          </div>
                          <Button
                            size="sm"
                            variant="outline"
                            className="border-[#2D5BFF] text-[#2D5BFF] hover:bg-[#E9EEFF]"
                            onClick={() => {
                              setSelectedReviewId(review.id)
                              navigate('supervisor-respond')
                            }}
                          >
                            <Eye className="w-4 h-4 mr-1" />
                            Gestionar
                          </Button>
                        </div>
                      ))}
                  </div>
                ) : (
                  <div className="text-center py-8">
                    <FileText className="w-10 h-10 text-gray-300 mx-auto mb-3" />
                    <p className="text-gray-500">No hay reseñas asignadas</p>
                  </div>
                )}
              </TabsContent>

              <TabsContent value="resolved">
                {dash?.assignedReviews && dash.assignedReviews.filter((r: any) => r.status === 'RESOLVED').length > 0 ? (
                  <div className="space-y-3 max-h-96 overflow-y-auto">
                    {dash.assignedReviews
                      .filter((r: any) => r.status === 'RESOLVED')
                      .sort((a: any, b: any) => new Date(b.resolvedAt || b.createdAt).getTime() - new Date(a.resolvedAt || a.createdAt).getTime())
                      .map((review: any) => (
                        <div
                          key={review.id}
                          className="flex flex-col sm:flex-row sm:items-center justify-between p-3 rounded-lg border border-green-100 bg-green-50 gap-3"
                        >
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-1">
                              <StarRating value={review.rating} readOnly size={14} />
                              <Badge className={STATUS_COLORS[review.status as keyof typeof STATUS_COLORS]}>
                                {STATUS_LABELS[review.status as keyof typeof STATUS_LABELS]}
                              </Badge>
                            </div>
                            <p className="font-medium text-sm text-gray-900 truncate">{review.title}</p>
                            <div className="flex items-center gap-2 text-xs text-gray-500 mt-1">
                              <span>{review.customer?.name || 'Cliente'}</span>
                              <span>•</span>
                              <span>{review.resolvedAt ? `Resuelta ${timeElapsed(review.resolvedAt)}` : timeElapsed(review.createdAt)}</span>
                            </div>
                          </div>
                          <Button
                            size="sm"
                            variant="outline"
                            className="border-green-600 text-green-700 hover:bg-green-100"
                            onClick={() => {
                              setSelectedReviewId(review.id)
                              navigate('supervisor-respond')
                            }}
                          >
                            <Eye className="w-4 h-4 mr-1" />
                            Ver Detalle
                          </Button>
                        </div>
                      ))}
                  </div>
                ) : (
                  <div className="text-center py-8">
                    <CheckCircle className="w-10 h-10 text-gray-300 mx-auto mb-3" />
                    <p className="text-gray-500">No hay reseñas resueltas aún</p>
                  </div>
                )}
              </TabsContent>
            </CardContent>
          </Tabs>
        </Card>
      </div>
    )
  }

  // ==================== SUPERVISOR RESPOND ====================
  function SupervisorRespond() {
    const [actionTaken, setActionTaken] = useState('')
    const [internalNote, setInternalNote] = useState('')
    const [responseToClient, setResponseToClient] = useState('')
    const [submitting, setSubmitting] = useState(false)
    const [changingStatus, setChangingStatus] = useState(false)

    if (loading || !reviewDetail) {
      return (
        <div className="max-w-3xl mx-auto space-y-4">
          <Skeleton className="h-8 w-48" />
          <Skeleton className="h-64 rounded-xl" />
          <Skeleton className="h-48 rounded-xl" />
        </div>
      )
    }

    const review = reviewDetail
    const existingResponses = review.responses || []

    const handleStatusChange = async (newStatus: string) => {
      setChangingStatus(true)
      try {
        await api.updateReviewStatus(review.id, newStatus)
        toast({ title: 'Estado actualizado', description: `Ahora: ${STATUS_LABELS[newStatus as keyof typeof STATUS_LABELS]}` })
        fetchReviewDetail(review.id)
      } catch (err: any) {
        toast({ title: 'Error', description: err.message, variant: 'destructive' })
      } finally {
        setChangingStatus(false)
      }
    }

    const handleSubmitResponse = async (e: React.FormEvent) => {
      e.preventDefault()
      if (!actionTaken || !responseToClient) {
        toast({ title: 'Campos incompletos', description: 'Acciones tomadas y respuesta al cliente son requeridas', variant: 'destructive' })
        return
      }
      setSubmitting(true)
      try {
        await api.respondToReview(review.id, {
          actionTaken,
          internalNote: internalNote || 'Sin notas internas',
          responseToClient,
        })
        setActionTaken('')
        setInternalNote('')
        setResponseToClient('')
        toast({ title: '¡Respuesta enviada!', description: 'El cliente ha sido notificado' })
        fetchReviewDetail(review.id)
      } catch (err: any) {
        toast({ title: 'Error', description: err.message, variant: 'destructive' })
      } finally {
        setSubmitting(false)
      }
    }

    return (
      <div className="max-w-3xl mx-auto space-y-6">
        <Button variant="ghost" onClick={() => navigate('supervisor-dashboard')} className="gap-2">
          <ArrowLeft className="w-4 h-4" />
          Volver al panel
        </Button>

        {/* Review Info Card with Status Selector */}
        <Card>
          <CardHeader>
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
              <div>
                <div className="flex items-center gap-2 mb-2">
                  <Badge variant="outline" className="text-xs">{review.reviewCode}</Badge>
                  <Badge className={STATUS_COLORS[review.status as keyof typeof STATUS_COLORS]}>
                    {STATUS_LABELS[review.status as keyof typeof STATUS_LABELS]}
                  </Badge>
                  <Badge variant="outline" className={review.sentiment === 'NEGATIVE' ? 'text-red-600 border-red-200' : 'text-[#2D5BFF] border-blue-200'}>
                    {review.sentiment === 'NEGATIVE' ? 'Negativa' : 'Positiva'}
                  </Badge>
                </div>
                <CardTitle>{review.title}</CardTitle>
              </div>
              {/* Status Change Selector */}
              <div className="flex items-center gap-2">
                <Label className="text-sm text-gray-500 whitespace-nowrap">Cambiar estado:</Label>
                <Select
                  value={review.status}
                  onValueChange={handleStatusChange}
                  disabled={changingStatus}
                >
                  <SelectTrigger className="w-40">
                    {changingStatus ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="PENDING">Pendiente</SelectItem>
                    <SelectItem value="ACKNOWLEDGED">En Proceso</SelectItem>
                    <SelectItem value="RESOLVED">Resuelto</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center gap-2">
              <span className="text-sm text-gray-500">Calificación:</span>
              <StarRating value={review.rating} readOnly size={20} />
            </div>
            <div className="grid grid-cols-2 gap-3 text-sm">
              <div>
                <span className="text-gray-500">Cliente:</span>
                <p className="font-medium">{review.customer?.name || 'N/A'}</p>
              </div>
              <div>
                <span className="text-gray-500">Email:</span>
                <p className="font-medium">{review.customer?.email || 'N/A'}</p>
              </div>
              <div>
                <span className="text-gray-500">Tipo de servicio:</span>
                <p className="font-medium">{review.serviceType}</p>
              </div>
              {review.subType && (
                <div>
                  <span className="text-gray-500">Aclaración:</span>
                  <p className="font-medium">{review.subType}</p>
                </div>
              )}
              <div>
                <span className="text-gray-500">Fecha:</span>
                <p className="font-medium">{formatShortDate(review.serviceDate)}</p>
              </div>
            </div>
            <div>
              <h4 className="text-sm font-medium text-gray-500 mb-1">Comentario del cliente</h4>
              <p className="text-gray-900 bg-gray-50 rounded-lg p-3 whitespace-pre-wrap">{review.content}</p>
            </div>

            {/* Photos */}
            {review.photos && review.photos.length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-gray-500 mb-2">Fotos adjuntas</h4>
                <div className="flex flex-wrap gap-3">
                  {review.photos.map((photo: ReviewPhoto) => (
                    <div key={photo.id} className="w-32 h-32 rounded-lg border overflow-hidden">
                      <img src={getPhotoUrl(photo.storageKey)} alt={photo.fileName} className="w-full h-full object-cover" onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }} />
                    </div>
                  ))}
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Previous Responses / History */}
        {existingResponses.length > 0 && (
          <Card className="border-blue-200">
            <CardHeader>
              <CardTitle className="text-[#2D5BFF] flex items-center gap-2">
                <MessageSquare className="w-5 h-5" />
                Historial de Respuestas ({existingResponses.length})
              </CardTitle>
              <CardDescription>Seguimiento de acciones y comunicaciones</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4 max-h-96 overflow-y-auto">
                {existingResponses.map((resp: SupervisorResponse, idx: number) => (
                  <div key={resp.id} className={`bg-blue-50 border border-blue-200 rounded-lg p-4 space-y-2 ${idx < existingResponses.length - 1 ? 'mb-3' : ''}`}>
                    <div className="flex items-center justify-between gap-2">
                      <div className="flex items-center gap-2 text-sm">
                        <Avatar className="w-6 h-6">
                          <AvatarFallback className="bg-[#2D5BFF] text-white text-xs">
                            {resp.supervisor?.name?.split(' ').map((n: string) => n[0]).join('').slice(0, 2).toUpperCase() || 'SV'}
                          </AvatarFallback>
                        </Avatar>
                        <span className="font-medium text-[#1B2559]">{resp.supervisor?.name || 'Supervisor'}</span>
                        <span className="text-gray-400">•</span>
                        <span className="text-[#2D5BFF] text-xs">{timeElapsed(resp.createdAt)}</span>
                      </div>
                      {idx === 0 && existingResponses.length > 1 && (
                        <Badge variant="outline" className="text-xs">Más reciente</Badge>
                      )}
                    </div>
                    <div>
                      <p className="text-xs text-gray-500 font-medium uppercase tracking-wide mb-1">Acciones tomadas</p>
                      <p className="text-sm text-gray-900">{resp.actionTaken}</p>
                    </div>
                    <div>
                      <p className="text-xs text-gray-500 font-medium uppercase tracking-wide mb-1 flex items-center gap-1">
                        Nota interna
                        <Badge variant="outline" className="text-xs px-1 py-0">Privado</Badge>
                      </p>
                      <p className="text-sm text-gray-600 bg-gray-100 rounded p-2">{resp.internalNote}</p>
                    </div>
                    <div>
                      <p className="text-xs text-gray-500 font-medium uppercase tracking-wide mb-1">Respuesta al cliente</p>
                      <p className="text-sm text-gray-900 bg-white rounded p-2 border border-blue-100">{resp.responseToClient}</p>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}

        {/* Add New Response / Follow-up Form - Always visible */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              {existingResponses.length > 0 ? (
                <>
                  <Plus className="w-5 h-5 text-[#FF9B2E]" />
                  Agregar Seguimiento
                </>
              ) : (
                <>
                  <MessageSquare className="w-5 h-5 text-[#2D5BFF]" />
                  Responder Reseña
                </>
              )}
            </CardTitle>
            {existingResponses.length > 0 && (
              <CardDescription>
                Agrega un nuevo seguimiento con acciones adicionales o actualizaciones para el cliente
              </CardDescription>
            )}
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmitResponse} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="action-taken">Acciones tomadas *</Label>
                <Textarea
                  id="action-taken"
                  value={actionTaken}
                  onChange={(e) => setActionTaken(e.target.value)}
                  placeholder="Describe las acciones que se tomaron para resolver el problema..."
                  rows={3}
                  required
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="internal-note" className="flex items-center gap-1">
                  Nota interna
                  <Badge variant="outline" className="text-xs ml-1 bg-amber-50 text-amber-700 border-amber-200">Privado - Solo supervisores y gerencia</Badge>
                </Label>
                <Textarea
                  id="internal-note"
                  value={internalNote}
                  onChange={(e) => setInternalNote(e.target.value)}
                  placeholder="Notas internas (no visibles para el cliente). Puedes registrar observaciones, seguimientos, escalamientos..."
                  rows={3}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="response-client" className="flex items-center gap-1">
                  Respuesta al cliente *
                  <Badge variant="outline" className="text-xs ml-1 bg-blue-50 text-blue-700 border-blue-200">Visible para el cliente</Badge>
                </Label>
                <Textarea
                  id="response-client"
                  value={responseToClient}
                  onChange={(e) => setResponseToClient(e.target.value)}
                  placeholder="Escribe tu respuesta para el cliente. Esta información será visible para él..."
                  rows={4}
                  required
                />
              </div>
              <div className="flex flex-col sm:flex-row gap-3">
                <Button
                  type="submit"
                  className="bg-gradient-to-br from-[#FF9B2E] to-[#FFB347] hover:from-[#FFB347] hover:to-[#FF9B2E] text-white flex-1"
                  disabled={submitting}
                >
                  {submitting ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Send className="w-4 h-4 mr-2" />}
                  {existingResponses.length > 0 ? 'Enviar Seguimiento' : 'Enviar Respuesta'}
                </Button>
                {review.status === 'RESOLVED' && (
                  <Button
                    type="button"
                    variant="outline"
                    className="text-[#FF9B2E] border-[#FF9B2E] hover:bg-[#FFF5E6]"
                    onClick={() => handleStatusChange('ACKNOWLEDGED')}
                    disabled={changingStatus}
                  >
                    Reabrir Reseña
                  </Button>
                )}
              </div>
            </form>
          </CardContent>
        </Card>
      </div>
    )
  }

  // ==================== SUPERVISOR CUSTOMERS ====================
  function SupervisorCustomers() {
    const [searchValue, setSearchValue] = useState('')

    const handleSearch = () => {
      fetchCustomers(searchValue || undefined)
    }

    return (
      <div className="space-y-6">
        {/* Actions */}
        <div className="flex flex-col sm:flex-row gap-3">
          <div className="flex-1 flex gap-2">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <Input
                value={searchValue}
                onChange={(e) => setSearchValue(e.target.value)}
                placeholder="Buscar clientes..."
                className="pl-10"
                onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
              />
            </div>
            <Button variant="outline" onClick={handleSearch}>
              <Search className="w-4 h-4" />
            </Button>
          </div>
          <Button
            onClick={() => navigate('supervisor-register-customer')}
            className="bg-gradient-to-br from-[#FF9B2E] to-[#FFB347] hover:from-[#FFB347] hover:to-[#FF9B2E] text-white"
          >
            <UserPlus className="w-4 h-4 mr-2" />
            Registrar Cliente
          </Button>
        </div>

        {/* Customers Table */}
        <Card>
          <CardContent className="p-0">
            {loading ? (
              <div className="p-6 space-y-3">
                {[1, 2, 3, 4, 5].map(i => <Skeleton key={i} className="h-12 w-full" />)}
              </div>
            ) : customers.length === 0 ? (
              <div className="text-center py-12">
                <Users className="w-10 h-10 text-gray-300 mx-auto mb-3" />
                <p className="text-gray-500">No se encontraron clientes</p>
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Nombre</TableHead>
                    <TableHead className="hidden sm:table-cell">Email</TableHead>
                    <TableHead className="hidden md:table-cell">Empresa</TableHead>
                    <TableHead className="hidden md:table-cell">Supervisor</TableHead>
                    <TableHead className="hidden md:table-cell">Reseñas</TableHead>
                    <TableHead>Estado</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {customers.map((cust: any) => (
                    <TableRow key={cust.id}>
                      <TableCell className="font-medium">{cust.name}</TableCell>
                      <TableCell className="hidden sm:table-cell text-gray-500">{cust.email}</TableCell>
                      <TableCell className="hidden md:table-cell text-gray-500">{cust.company || '—'}</TableCell>
                      <TableCell className="hidden md:table-cell text-gray-500">{cust.assignedBy?.name || '—'}</TableCell>
                      <TableCell className="hidden md:table-cell">{cust._count?.reviews ?? 0}</TableCell>
                      <TableCell>
                        <Badge variant={cust.isActive ? 'default' : 'secondary'} className={cust.isActive ? 'bg-blue-100 text-blue-800' : ''}>
                          {cust.isActive ? 'Activo' : 'Inactivo'}
                        </Badge>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>
      </div>
    )
  }

  // ==================== REGISTER CUSTOMER ====================
  function SupervisorRegisterCustomer() {
    const [name, setName] = useState('')
    const [email, setEmail] = useState('')
    const [company, setCompany] = useState('')
    const [phone, setPhone] = useState('')
    const [password, setPassword] = useState('')
    const [submitting, setSubmitting] = useState(false)

    const handleSubmit = async (e: React.FormEvent) => {
      e.preventDefault()
      if (!name || !email || !password) {
        toast({ title: 'Campos incompletos', variant: 'destructive' })
        return
      }
      setSubmitting(true)
      try {
        await api.createCustomer({ name, email, company: company || undefined, phone: phone || undefined, password })
        toast({ title: '¡Cliente registrado!', description: `${name} ha sido creado exitosamente` })
        navigate('supervisor-customers')
      } catch (err: any) {
        toast({ title: 'Error', description: err.message, variant: 'destructive' })
      } finally {
        setSubmitting(false)
      }
    }

    return (
      <div className="max-w-lg mx-auto">
        <Button variant="ghost" onClick={() => navigate('supervisor-customers')} className="gap-2 mb-4">
          <ArrowLeft className="w-4 h-4" />
          Volver a clientes
        </Button>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <UserPlus className="w-5 h-5 text-[#2D5BFF]" />
              Registrar Nuevo Cliente
            </CardTitle>
            <CardDescription>Completa los datos del nuevo cliente</CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="cust-name">Nombre completo *</Label>
                <div className="relative">
                  <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <Input id="cust-name" value={name} onChange={(e) => setName(e.target.value)} placeholder="Juan Pérez" className="pl-10" required />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="cust-email">Correo electrónico *</Label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <Input id="cust-email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="correo@empresa.com" className="pl-10" required />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="cust-company">Empresa</Label>
                <div className="relative">
                  <Input id="cust-company" value={company} onChange={(e) => setCompany(e.target.value)} placeholder="Nombre de la empresa" />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="cust-phone">Teléfono</Label>
                <div className="relative">
                  <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <Input id="cust-phone" value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+52 555 123 4567" className="pl-10" />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="cust-password">Contraseña pre-asignada *</Label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <Input id="cust-password" type="text" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="contraseña123" className="pl-10" required />
                </div>
                <p className="text-xs text-gray-400">El cliente podrá cambiarla después</p>
              </div>
              <Button type="submit" className="w-full bg-gradient-to-br from-[#FF9B2E] to-[#FFB347] hover:from-[#FFB347] hover:to-[#FF9B2E] text-white" disabled={submitting}>
                {submitting ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <UserPlus className="w-4 h-4 mr-2" />}
                Registrar Cliente
              </Button>
            </form>
          </CardContent>
        </Card>
      </div>
    )
  }

  // ==================== MANAGER DASHBOARD ====================
  function ManagerDashboard() {
    if (loading && !managerDashboard) {
      return (
        <div className="space-y-4">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {[1, 2, 3, 4].map(i => <Skeleton key={i} className="h-28 rounded-xl" />)}
          </div>
          <div className="grid md:grid-cols-2 gap-4">
            <Skeleton className="h-64 rounded-xl" />
            <Skeleton className="h-64 rounded-xl" />
          </div>
        </div>
      )
    }

    const dash = managerDashboard

    // Prepare chart data
    const ratingDistData = dash?.ratingDistribution
      ? Object.entries(dash.ratingDistribution).map(([key, value]) => ({
          rating: `${key} ⭐`,
          cantidad: value as number,
        }))
      : []

    const monthlyTrendData = dash?.monthlyTrend || []

    const statusPieData = dash?.reviewsByStatus
      ? Object.entries(dash.reviewsByStatus).map(([key, value], i) => ({
          name: STATUS_LABELS[key as keyof typeof STATUS_LABELS] || key,
          value: value as number,
          color: PIE_COLORS[i % PIE_COLORS.length],
        }))
      : []

    return (
      <div className="space-y-6">
        {/* KPI Cards */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <Card className="border-l-4 border-l-[#2D5BFF]">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs font-medium text-gray-500 uppercase">Total Reseñas</p>
                  <p className="text-2xl font-bold text-gray-900 mt-1">{dash?.totalReviews ?? 0}</p>
                </div>
                <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
                  <MessageSquare className="w-5 h-5 text-[#2D5BFF]" />
                </div>
              </div>
            </CardContent>
          </Card>
          <Card className="border-l-4 border-l-[#FF9B2E]">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs font-medium text-gray-500 uppercase">Calificación Prom.</p>
                  <p className="text-2xl font-bold text-gray-900 mt-1">{dash?.averageRating?.toFixed(1) ?? '—'}</p>
                </div>
                <div className="w-10 h-10 rounded-full bg-orange-100 flex items-center justify-center">
                  <Star className="w-5 h-5 text-[#FF9B2E]" />
                </div>
              </div>
            </CardContent>
          </Card>
          <Card className="border-l-4 border-l-cyan-500">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs font-medium text-gray-500 uppercase">NPS</p>
                  <p className="text-2xl font-bold text-gray-900 mt-1">{dash?.nps ?? 0}</p>
                </div>
                <div className="w-10 h-10 rounded-full bg-cyan-100 flex items-center justify-center">
                  <TrendingUp className="w-5 h-5 text-cyan-600" />
                </div>
              </div>
            </CardContent>
          </Card>
          <Card className="border-l-4 border-l-red-500">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs font-medium text-gray-500 uppercase">Negativas</p>
                  <p className="text-2xl font-bold text-gray-900 mt-1">{dash?.reviewsBySentiment?.NEGATIVE ?? 0}</p>
                </div>
                <div className="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
                  <ThumbsDown className="w-5 h-5 text-red-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Charts Row */}
        <div className="grid md:grid-cols-2 gap-6">
          {/* Rating Distribution */}
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Distribución de Calificaciones</CardTitle>
            </CardHeader>
            <CardContent>
              {ratingDistData.length > 0 ? (
                <ResponsiveContainer width="100%" height={250}>
                  <BarChart data={ratingDistData}>
                    <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                    <XAxis dataKey="rating" tick={{ fontSize: 12 }} />
                    <YAxis allowDecimals={false} tick={{ fontSize: 12 }} />
                    <Tooltip />
                    <Bar dataKey="cantidad" fill="#2D5BFF" radius={[4, 4, 0, 0]} />
                  </BarChart>
                </ResponsiveContainer>
              ) : (
                <p className="text-center text-gray-400 py-8">Sin datos</p>
              )}
            </CardContent>
          </Card>

          {/* Status Pie Chart */}
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Reseñas por Estado</CardTitle>
            </CardHeader>
            <CardContent>
              {statusPieData.length > 0 ? (
                <ResponsiveContainer width="100%" height={250}>
                  <PieChart>
                    <Pie
                      data={statusPieData}
                      cx="50%"
                      cy="50%"
                      innerRadius={50}
                      outerRadius={80}
                      paddingAngle={5}
                      dataKey="value"
                    >
                      {statusPieData.map((entry, i) => (
                        <Cell key={i} fill={entry.color} />
                      ))}
                    </Pie>
                    <Tooltip />
                    <Legend />
                  </PieChart>
                </ResponsiveContainer>
              ) : (
                <p className="text-center text-gray-400 py-8">Sin datos</p>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Monthly Trend */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Tendencia Mensual</CardTitle>
          </CardHeader>
          <CardContent>
            {monthlyTrendData.length > 0 ? (
              <ResponsiveContainer width="100%" height={300}>
                <LineChart data={monthlyTrendData}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                  <XAxis dataKey="month" tick={{ fontSize: 12 }} />
                  <YAxis allowDecimals={false} tick={{ fontSize: 12 }} />
                  <Tooltip />
                  <Legend />
                  <Line type="monotone" dataKey="total" stroke="#2D5BFF" name="Total" strokeWidth={2} />
                  <Line type="monotone" dataKey="negative" stroke="#ef4444" name="Negativas" strokeWidth={2} />
                  <Line type="monotone" dataKey="positive" stroke="#FF9B2E" name="Positivas" strokeWidth={2} />
                </LineChart>
              </ResponsiveContainer>
            ) : (
              <p className="text-center text-gray-400 py-8">Sin datos</p>
            )}
          </CardContent>
        </Card>

        {/* Unattended > 24h Alerts */}
        {dash?.unattendedOver24h && dash.unattendedOver24h.length > 0 && (
          <Card className="border-red-200 bg-red-50">
            <CardHeader>
              <CardTitle className="text-base flex items-center gap-2 text-red-800">
                <AlertTriangle className="w-5 h-5" />
                Alertas: Sin atención por más de 24h
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                {dash.unattendedOver24h.map((review: any) => (
                  <div
                    key={review.id}
                    className="flex items-center justify-between p-3 bg-white rounded-lg border border-red-100"
                  >
                    <div>
                      <p className="font-medium text-sm">{review.title}</p>
                      <p className="text-xs text-gray-500">{review.customer?.name} • {timeElapsed(review.createdAt)}</p>
                    </div>
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => {
                        setSelectedReviewId(review.id)
                        navigate('manager-review-detail')
                      }}
                    >
                      <Eye className="w-4 h-4 mr-1" />
                      Ver
                    </Button>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    )
  }

  // ==================== MANAGER ALL REVIEWS ====================
  function ManagerReviews() {
    return (
      <div className="space-y-6">
        {/* Filters */}
        <Card>
          <CardContent className="p-4">
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              <Select value={managerStatusFilter} onValueChange={(v) => { setManagerStatusFilter(v); setManagerReviewsPage(1) }}>
                <SelectTrigger>
                  <SelectValue placeholder="Estado" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Todos los estados</SelectItem>
                  <SelectItem value="PENDING">Pendiente</SelectItem>
                  <SelectItem value="ACKNOWLEDGED">En Proceso</SelectItem>
                  <SelectItem value="RESOLVED">Resuelto</SelectItem>
                </SelectContent>
              </Select>
              <Select value={managerSentimentFilter} onValueChange={(v) => { setManagerSentimentFilter(v); setManagerReviewsPage(1) }}>
                <SelectTrigger>
                  <SelectValue placeholder="Sentimiento" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Todos</SelectItem>
                  <SelectItem value="POSITIVE">Positiva</SelectItem>
                  <SelectItem value="NEGATIVE">Negativa</SelectItem>
                </SelectContent>
              </Select>
              <Select value={managerServiceTypeFilter} onValueChange={(v) => { setManagerServiceTypeFilter(v); setManagerReviewsPage(1) }}>
                <SelectTrigger>
                  <SelectValue placeholder="Tipo de servicio" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Todos los tipos</SelectItem>
                  {SERVICE_TYPES.map((type) => (
                    <SelectItem key={type} value={type}>{type}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </CardContent>
        </Card>

        {/* Reviews Table */}
        <Card>
          <CardContent className="p-0">
            {loading ? (
              <div className="p-6 space-y-3">
                {[1, 2, 3, 4, 5].map(i => <Skeleton key={i} className="h-12 w-full" />)}
              </div>
            ) : allReviews.length === 0 ? (
              <div className="text-center py-12">
                <FileText className="w-10 h-10 text-gray-300 mx-auto mb-3" />
                <p className="text-gray-500">No se encontraron reseñas</p>
              </div>
            ) : (
              <>
                <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Código</TableHead>
                        <TableHead>Título</TableHead>
                        <TableHead className="hidden md:table-cell">Cliente</TableHead>
                        <TableHead>Calificación</TableHead>
                        <TableHead>Estado</TableHead>
                        <TableHead className="hidden sm:table-cell">Sentimiento</TableHead>
                        <TableHead className="hidden lg:table-cell">Fecha</TableHead>
                        <TableHead></TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {allReviews.map((review) => (
                        <TableRow key={review.id} className="cursor-pointer hover:bg-gray-50" onClick={() => {
                          setSelectedReviewId(review.id)
                          navigate('manager-review-detail')
                        }}>
                          <TableCell className="font-mono text-xs">{review.reviewCode}</TableCell>
                          <TableCell className="font-medium max-w-[200px] truncate">{review.title}</TableCell>
                          <TableCell className="hidden md:table-cell text-gray-500">{review.customer?.name || '—'}</TableCell>
                          <TableCell>
                            <div className="flex items-center gap-0.5">
                              <Star className="w-3 h-3 fill-orange-500 text-orange-500" />
                              <span className="text-sm">{review.rating}</span>
                            </div>
                          </TableCell>
                          <TableCell>
                            <Badge className={STATUS_COLORS[review.status as keyof typeof STATUS_COLORS]}>
                              {STATUS_LABELS[review.status as keyof typeof STATUS_LABELS]}
                            </Badge>
                          </TableCell>
                          <TableCell className="hidden sm:table-cell">
                            <span className={SENTIMENT_COLORS[review.sentiment as keyof typeof SENTIMENT_COLORS]}>
                              {review.sentiment === 'NEGATIVE' ? 'Negativa' : 'Positiva'}
                            </span>
                          </TableCell>
                          <TableCell className="hidden lg:table-cell text-gray-500 text-sm">
                            {formatShortDate(review.createdAt)}
                          </TableCell>
                          <TableCell>
                            <Button variant="ghost" size="sm">
                              <Eye className="w-4 h-4" />
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
                {/* Pagination info */}
                <div className="flex items-center justify-between p-4 border-t">
                  <p className="text-sm text-gray-500">
                    {managerReviewsTotal} reseña(s) encontrada(s)
                  </p>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      disabled={managerReviewsPage <= 1}
                      onClick={() => setManagerReviewsPage(p => Math.max(1, p - 1))}
                    >
                      Anterior
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      disabled={allReviews.length < 10}
                      onClick={() => setManagerReviewsPage(p => p + 1)}
                    >
                      Siguiente
                    </Button>
                  </div>
                </div>
              </>
            )}
          </CardContent>
        </Card>
      </div>
    )
  }

  // ==================== MANAGER REVIEW DETAIL ====================
  function ManagerReviewDetail() {
    const [changingStatus, setChangingStatus] = useState(false)

    if (loading || !reviewDetail) {
      return (
        <div className="max-w-3xl mx-auto space-y-4">
          <Skeleton className="h-8 w-48" />
          <Skeleton className="h-64 rounded-xl" />
        </div>
      )
    }

    const review = reviewDetail

    const handleStatusChange = async (newStatus: string) => {
      setChangingStatus(true)
      try {
        await api.updateReviewStatus(review.id, newStatus)
        toast({ title: 'Estado actualizado', description: `Ahora: ${STATUS_LABELS[newStatus as keyof typeof STATUS_LABELS]}` })
        fetchReviewDetail(review.id)
      } catch (err: any) {
        toast({ title: 'Error', description: err.message, variant: 'destructive' })
      } finally {
        setChangingStatus(false)
      }
    }

    return (
      <div className="max-w-3xl mx-auto space-y-6">
        <div className="flex items-center justify-between">
          <Button variant="ghost" onClick={() => navigate('manager-reviews')} className="gap-2">
            <ArrowLeft className="w-4 h-4" />
            Volver a reseñas
          </Button>
          {(user?.role === 'ADMIN' || user?.role === 'MANAGER') && (
            <Button variant="destructive" size="sm" onClick={async () => {
              if (confirm('¿Está seguro de que desea eliminar esta reseña? Esta acción no se puede deshacer.')) {
                try {
                  await api.deleteReview(review.id)
                  toast({ title: '✅ Reseña eliminada' })
                  navigate('manager-reviews')
                } catch (err: any) { toast({ title: 'Error', description: err.message, variant: 'destructive' }) }
              }
            }}><Trash2 className="w-3.5 h-3.5 mr-1" /> Eliminar</Button>
          )}
        </div>

        <Card>
          <CardHeader>
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
              <div>
                <div className="flex items-center gap-2 mb-2">
                  <Badge variant="outline" className="text-xs">{review.reviewCode}</Badge>
                  <Badge className={STATUS_COLORS[review.status as keyof typeof STATUS_COLORS]}>
                    {STATUS_LABELS[review.status as keyof typeof STATUS_LABELS]}
                  </Badge>
                  <Badge variant="outline" className={review.sentiment === 'NEGATIVE' ? 'text-red-600 border-red-200' : 'text-[#2D5BFF] border-blue-200'}>
                    {review.sentiment === 'NEGATIVE' ? 'Negativa' : 'Positiva'}
                  </Badge>
                </div>
                <CardTitle>{review.title}</CardTitle>
              </div>
              {/* Change Status */}
              <Select
                value={review.status}
                onValueChange={handleStatusChange}
                disabled={changingStatus}
              >
                <SelectTrigger className="w-40">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="PENDING">Pendiente</SelectItem>
                  <SelectItem value="ACKNOWLEDGED">En Proceso</SelectItem>
                  <SelectItem value="RESOLVED">Resuelto</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center gap-2">
              <span className="text-sm text-gray-500">Calificación:</span>
              <StarRating value={review.rating} readOnly size={20} />
            </div>

            <div className="grid grid-cols-2 gap-3 text-sm">
              <div>
                <span className="text-gray-500">Cliente:</span>
                <p className="font-medium">{review.customer?.name || 'N/A'}</p>
              </div>
              <div>
                <span className="text-gray-500">Email:</span>
                <p className="font-medium">{review.customer?.email || 'N/A'}</p>
              </div>
              <div>
                <span className="text-gray-500">Asignado a:</span>
                {user?.role === 'ADMIN' || user?.role === 'MANAGER' ? (
                  <div className="flex items-center gap-2 mt-1">
                    <select id="mgr-reassign-sel" className="border rounded px-2 py-1 text-sm" defaultValue={review.assignedToId || ''}>
                      <option value="">Sin asignar</option>
                      {adminSupervisors.filter((s: any) => s.isActive).map((s: any) => (
                        <option key={s.id} value={s.id}>{s.name}</option>
                      ))}
                    </select>
                    <Button size="sm" variant="outline" onClick={async () => {
                      const sel = document.getElementById('mgr-reassign-sel') as HTMLSelectElement
                      if (sel?.value) {
                        try {
                          await api.reassignReview(review.id, sel.value)
                          toast({ title: '✅ Reseña reasignada' })
                          fetchReviewDetail(review.id)
                        } catch (err: any) { toast({ title: 'Error', description: err.message, variant: 'destructive' }) }
                      }
                    }}>Reasignar</Button>
                  </div>
                ) : (
                  <p className="font-medium">{review.assignedTo?.name || 'Sin asignar'}</p>
                )}
              </div>
              <div>
                <span className="text-gray-500">Tipo de servicio:</span>
                <p className="font-medium">{review.serviceType}</p>
              </div>
              {review.subType && (
                <div>
                  <span className="text-gray-500">Aclaración:</span>
                  <p className="font-medium">{review.subType}</p>
                </div>
              )}
              <div>
                <span className="text-gray-500">Fecha del servicio:</span>
                <p className="font-medium">{formatShortDate(review.serviceDate)}</p>
              </div>
              <div>
                <span className="text-gray-500">Creada:</span>
                <p className="font-medium">{timeElapsed(review.createdAt)}</p>
              </div>
            </div>

            <div>
              <h4 className="text-sm font-medium text-gray-500 mb-1">Comentario</h4>
              <p className="text-gray-900 bg-gray-50 rounded-lg p-3 whitespace-pre-wrap">{review.content}</p>
            </div>

            {/* Photos */}
            {review.photos && review.photos.length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-gray-500 mb-2">Fotos adjuntas</h4>
                <div className="flex flex-wrap gap-3">
                  {review.photos.map((photo: ReviewPhoto) => (
                    <div key={photo.id} className="w-32 h-32 rounded-lg border overflow-hidden">
                      <img src={getPhotoUrl(photo.storageKey)} alt={photo.fileName} className="w-full h-full object-cover" onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }} />
                    </div>
                  ))}
                </div>
              </div>
            )}

            <Separator />

            {/* Supervisor Response */}
            {review.responses && review.responses.length > 0 && (
              <div className="space-y-3">
                <h4 className="font-semibold flex items-center gap-2">
                  <MessageSquare className="w-4 h-4 text-[#2D5BFF]" />
                  Respuesta del Supervisor
                </h4>
                {review.responses.map((resp: SupervisorResponse) => (
                  <div key={resp.id} className="bg-blue-50 border border-blue-200 rounded-lg p-4 space-y-2">
                    <div className="flex items-center gap-2 text-sm">
                      <span className="font-medium text-[#1B2559]">{resp.supervisor?.name || 'Supervisor'}</span>
                      <span className="text-[#2D5BFF]">• {timeElapsed(resp.createdAt)}</span>
                    </div>
                    <div>
                      <p className="text-xs text-gray-500 font-medium">Acciones tomadas:</p>
                      <p className="text-sm">{resp.actionTaken}</p>
                    </div>
                    <div>
                      <p className="text-xs text-gray-500 font-medium">Nota interna:</p>
                      <p className="text-sm text-gray-600 bg-gray-50 rounded p-2">{resp.internalNote}</p>
                    </div>
                    <div>
                      <p className="text-xs text-gray-500 font-medium">Respuesta al cliente:</p>
                      <p className="text-sm">{resp.responseToClient}</p>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    )
  }

  // ==================== MANAGER REPORTS ====================
  function ManagerReports() {
    if (loading && !reportSummary) {
      return (
        <div className="space-y-4">
          <Skeleton className="h-8 w-48" />
          <div className="grid md:grid-cols-2 gap-4">
            <Skeleton className="h-64 rounded-xl" />
            <Skeleton className="h-64 rounded-xl" />
          </div>
        </div>
      )
    }

    const supervisorData = reportBySupervisor?.supervisors || []
    const ratingsData = reportRatings?.distribution || []

    return (
      <div className="space-y-6">
        {/* Summary Stats */}
        {reportSummary && (
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <Card>
              <CardContent className="p-4 text-center">
                <p className="text-xs text-gray-500 uppercase">Total Reseñas</p>
                <p className="text-2xl font-bold mt-1">{reportSummary.totalReviews ?? 0}</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="p-4 text-center">
                <p className="text-xs text-gray-500 uppercase">Calificación Prom.</p>
                <p className="text-2xl font-bold mt-1">{reportSummary.averageRating?.toFixed(1) ?? '—'}</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="p-4 text-center">
                <p className="text-xs text-gray-500 uppercase">Positivas</p>
                <p className="text-2xl font-bold mt-1 text-[#2D5BFF]">{reportSummary.positiveCount ?? 0}</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="p-4 text-center">
                <p className="text-xs text-gray-500 uppercase">Negativas</p>
                <p className="text-2xl font-bold mt-1 text-red-600">{reportSummary.negativeCount ?? 0}</p>
              </CardContent>
            </Card>
          </div>
        )}

        {/* Supervisor Performance */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle className="text-base">Rendimiento por Supervisor</CardTitle>
            <Button variant="outline" size="sm" onClick={() => toast({ title: 'Exportación simulada', description: 'El reporte se descargaría como PDF' })}>
              <Download className="w-4 h-4 mr-2" />
              Exportar
            </Button>
          </CardHeader>
          <CardContent>
            {supervisorData.length > 0 ? (
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Supervisor</TableHead>
                      <TableHead>Asignadas</TableHead>
                      <TableHead>Resueltas</TableHead>
                      <TableHead>Tasa de Resolución</TableHead>
                      <TableHead>Tiempo Prom.</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {supervisorData.map((sup: any) => (
                      <TableRow key={sup.id}>
                        <TableCell className="font-medium">{sup.name}</TableCell>
                        <TableCell>{sup.assignedTotal}</TableCell>
                        <TableCell>{sup.resolvedCount}</TableCell>
                        <TableCell>
                          <div className="flex items-center gap-2">
                            <Progress value={sup.resolutionRate} className="w-16 h-2" />
                            <span className="text-sm">{sup.resolutionRate}%</span>
                          </div>
                        </TableCell>
                        <TableCell>{sup.avgResponseTimeHours?.toFixed(1) ?? '—'}h</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            ) : (
              <p className="text-center text-gray-400 py-8">Sin datos de supervisores</p>
            )}
          </CardContent>
        </Card>

        {/* Rating Distribution Chart */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Distribución de Calificaciones</CardTitle>
          </CardHeader>
          <CardContent>
            {ratingsData.length > 0 ? (
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={ratingsData}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                  <XAxis dataKey="rating" tick={{ fontSize: 12 }} />
                  <YAxis allowDecimals={false} tick={{ fontSize: 12 }} />
                  <Tooltip />
                  <Bar dataKey="count" fill="#2D5BFF" radius={[4, 4, 0, 0]} name="Cantidad" />
                </BarChart>
              </ResponsiveContainer>
            ) : (
              <p className="text-center text-gray-400 py-8">Sin datos</p>
            )}
          </CardContent>
        </Card>

        {/* Sentiment Breakdown */}
        {reportSummary?.sentimentBreakdown && (
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Desglose por Sentimiento</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 gap-4">
                <div className="text-center p-4 bg-blue-50 rounded-lg border border-blue-200">
                  <ThumbsUp className="w-8 h-8 text-[#2D5BFF] mx-auto mb-2" />
                  <p className="text-2xl font-bold text-[#2D5BFF]">{reportSummary.positiveCount ?? 0}</p>
                  <p className="text-sm text-[#2D5BFF]">Positivas</p>
                </div>
                <div className="text-center p-4 bg-red-50 rounded-lg border border-red-200">
                  <ThumbsDown className="w-8 h-8 text-red-600 mx-auto mb-2" />
                  <p className="text-2xl font-bold text-red-700">{reportSummary.negativeCount ?? 0}</p>
                  <p className="text-sm text-red-600">Negativas</p>
                </div>
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    )
  }

  // ==================== PROFILE ====================
  function ProfileView() {
    const [currentPassword, setCurrentPassword] = useState('')
    const [newPassword, setNewPassword] = useState('')
    const [confirmPassword, setConfirmPassword] = useState('')
    const [changingPassword, setChangingPassword] = useState(false)

    const handleChangePassword = async (e: React.FormEvent) => {
      e.preventDefault()
      if (newPassword !== confirmPassword) {
        toast({ title: 'Error', description: 'Las contraseñas no coinciden', variant: 'destructive' })
        return
      }
      if (newPassword.length < 6) {
        toast({ title: 'Error', description: 'La contraseña debe tener al menos 6 caracteres', variant: 'destructive' })
        return
      }
      setChangingPassword(true)
      try {
        await api.changePassword(currentPassword, newPassword)
        toast({ title: '¡Contraseña actualizada!', description: 'Tu contraseña ha sido cambiada exitosamente' })
        setCurrentPassword('')
        setNewPassword('')
        setConfirmPassword('')
      } catch (err: any) {
        toast({ title: 'Error', description: err.message, variant: 'destructive' })
      } finally {
        setChangingPassword(false)
      }
    }

    return (
      <div className="max-w-2xl mx-auto space-y-6">
        {/* User Info */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <User className="w-5 h-5 text-[#2D5BFF]" />
              Información Personal
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center gap-4">
              <Avatar className="w-16 h-16">
                <AvatarFallback className="bg-[#2D5BFF] text-white text-xl">
                  {user?.name?.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase()}
                </AvatarFallback>
              </Avatar>
              <div>
                <h3 className="text-xl font-semibold text-gray-900">{user?.name}</h3>
                <Badge className="bg-blue-100 text-blue-800 border-blue-200 mt-1">
                  {ROLE_LABELS[user?.role as UserRole]}
                </Badge>
              </div>
            </div>
            <Separator />
            <div className="grid gap-3">
              <div className="flex items-center gap-3 text-sm">
                <Mail className="w-4 h-4 text-gray-400" />
                <span className="text-gray-500 w-20">Email:</span>
                <span className="font-medium">{user?.email}</span>
              </div>
              <div className="flex items-center gap-3 text-sm">
                <Phone className="w-4 h-4 text-gray-400" />
                <span className="text-gray-500 w-20">Teléfono:</span>
                <span className="font-medium">{user?.phone || 'No registrado'}</span>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Change Password */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Lock className="w-5 h-5 text-[#2D5BFF]" />
              Cambiar Contraseña
            </CardTitle>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleChangePassword} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="current-pwd">Contraseña actual</Label>
                <Input
                  id="current-pwd"
                  type="password"
                  value={currentPassword}
                  onChange={(e) => setCurrentPassword(e.target.value)}
                  required
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="new-pwd">Nueva contraseña</Label>
                <Input
                  id="new-pwd"
                  type="password"
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                  required
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="confirm-pwd">Confirmar contraseña</Label>
                <Input
                  id="confirm-pwd"
                  type="password"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  required
                />
              </div>
              <Button
                type="submit"
                className="bg-gradient-to-br from-[#FF9B2E] to-[#FFB347] hover:from-[#FFB347] hover:to-[#FF9B2E] text-white"
                disabled={changingPassword}
              >
                {changingPassword ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Lock className="w-4 h-4 mr-2" />}
                Cambiar Contraseña
              </Button>
            </form>
          </CardContent>
        </Card>
      </div>
    )
  }

  // ==================== ADMIN: GESTIÓN DE USUARIOS ====================
  function AdminUsers() {
    const [showCreateForm, setShowCreateForm] = useState(false)
    const [createForm, setCreateForm] = useState({ email: '', name: '', phone: '', password: '', company: '' })
    const [editForm, setEditForm] = useState<any>(null)
    const [resetPwdForm, setResetPwdForm] = useState<any>(null)
    const [adminNewPassword, setAdminNewPassword] = useState('')
    const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
    const [showBulkDeleteConfirm, setShowBulkDeleteConfirm] = useState(false)

    const handleCreate = async (role: string) => {
      try {
        if (role === 'CUSTOMER') {
          await api.createCustomer({ email: createForm.email, name: createForm.name, company: createForm.company, phone: createForm.phone, password: createForm.password })
        } else if (role === 'SUPERVISOR') {
          await api.createSupervisor({ email: createForm.email, name: createForm.name, phone: createForm.phone, password: createForm.password })
        } else if (role === 'MANAGER') {
          await api.createManager({ email: createForm.email, name: createForm.name, phone: createForm.phone, password: createForm.password })
        } else if (role === 'ADMIN') {
          await api.createAdmin({ email: createForm.email, name: createForm.name, phone: createForm.phone, password: createForm.password })
        }
        toast({ title: '✅ Usuario creado exitosamente' })
        setCreateForm({ email: '', name: '', phone: '', password: '', company: '' })
        setShowCreateForm(false)
        fetchAdminUsers()
      } catch (err: any) {
        toast({ title: 'Error', description: err.message, variant: 'destructive' })
      }
    }

    const handleToggleActive = async (id: string, role: string) => {
      try {
        if (role === 'CUSTOMER') await api.toggleCustomer(id)
        else if (role === 'SUPERVISOR') await api.toggleSupervisor(id)
        else if (role === 'MANAGER') await api.toggleManager(id)
        else if (role === 'ADMIN') await api.toggleAdmin(id)
        toast({ title: '✅ Estado actualizado' })
        fetchAdminUsers()
      } catch (err: any) {
        toast({ title: 'Error', description: err.message, variant: 'destructive' })
      }
    }

    const handleResetPassword = async (id: string) => {
      try {
        await api.resetUserPassword(id, adminNewPassword)
        toast({ title: '✅ Contraseña restablecida' })
        setResetPwdForm(null)
        setAdminNewPassword('')
      } catch (err: any) {
        toast({ title: 'Error', description: err.message, variant: 'destructive' })
      }
    }

    const handleDeleteReview = async (id: string) => {
      try {
        await api.deleteReview(id)
        toast({ title: '✅ Reseña eliminada' })
      } catch (err: any) {
        toast({ title: 'Error', description: err.message, variant: 'destructive' })
      }
    }

    const handleBulkDelete = async () => {
      try {
        const result = await api.bulkDeleteUsers(Array.from(selectedIds))
        toast({ title: `✅ ${result.deletedCount} usuario(s) eliminado(s)` })
        setSelectedIds(new Set())
        setShowBulkDeleteConfirm(false)
        fetchAdminUsers()
      } catch (err: any) {
        toast({ title: 'Error', description: err.message, variant: 'destructive' })
      }
    }

    const toggleSelectAll = () => {
      const currentIds = currentList.map((u: any) => u.id)
      const allSelected = currentIds.length > 0 && currentIds.every((id: string) => selectedIds.has(id))
      if (allSelected) {
        setSelectedIds(new Set())
      } else {
        setSelectedIds(new Set(currentIds))
      }
    }

    const toggleSelect = (id: string) => {
      const next = new Set(selectedIds)
      if (next.has(id)) {
        next.delete(id)
      } else {
        next.add(id)
      }
      setSelectedIds(next)
    }

    const tabs = [
      { key: 'customers' as const, label: 'Clientes', count: adminUsers.length },
      { key: 'supervisors' as const, label: 'Supervisores', count: adminSupervisors.length },
      { key: 'managers' as const, label: 'Gerencia', count: adminManagers.length },
      { key: 'admins' as const, label: 'Admins', count: adminAdmins.length },
    ]

    const currentList = adminUserTab === 'customers' ? adminUsers
      : adminUserTab === 'supervisors' ? adminSupervisors
      : adminUserTab === 'managers' ? adminManagers
      : adminAdmins

    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <h2 className="text-xl font-bold text-gray-900">Gestión de Usuarios</h2>
          <div className="flex gap-2">
            {selectedIds.size > 0 && (
              <Button
                variant="destructive"
                onClick={() => setShowBulkDeleteConfirm(true)}
              >
                <Trash2 className="w-4 h-4 mr-2" /> Eliminar Seleccionados ({selectedIds.size})
              </Button>
            )}
            <Button onClick={() => setShowCreateForm(!showCreateForm)} className="bg-gradient-to-br from-[#FF9B2E] to-[#FFB347] hover:from-[#FFB347] hover:to-[#FF9B2E] text-white">
              <UserPlus className="w-4 h-4 mr-2" /> Nuevo Usuario
            </Button>
          </div>
        </div>

        {showCreateForm && (
          <Card className="border-[#FF9B2E]/30 bg-[#FFF8F0]">
            <CardHeader><CardTitle className="text-[#FF9B2E]">Crear Nuevo Usuario</CardTitle></CardHeader>
            <CardContent className="space-y-3">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <input placeholder="Nombre completo" className="w-full border rounded-lg px-3 py-2 text-sm" value={createForm.name} onChange={e => setCreateForm(f => ({ ...f, name: e.target.value }))} />
                <input placeholder="Email" type="email" className="w-full border rounded-lg px-3 py-2 text-sm" value={createForm.email} onChange={e => setCreateForm(f => ({ ...f, email: e.target.value }))} />
                <input placeholder="Teléfono (opcional)" className="w-full border rounded-lg px-3 py-2 text-sm" value={createForm.phone} onChange={e => setCreateForm(f => ({ ...f, phone: e.target.value }))} />
                <input placeholder="Contraseña" type="password" className="w-full border rounded-lg px-3 py-2 text-sm" value={createForm.password} onChange={e => setCreateForm(f => ({ ...f, password: e.target.value }))} />
                {adminUserTab === 'customers' && (
                  <input placeholder="Empresa" className="w-full border rounded-lg px-3 py-2 text-sm" value={createForm.company} onChange={e => setCreateForm(f => ({ ...f, company: e.target.value }))} />
                )}
              </div>
              <div className="flex gap-2">
                <Button onClick={() => handleCreate(adminUserTab === 'customers' ? 'CUSTOMER' : adminUserTab === 'supervisors' ? 'SUPERVISOR' : adminUserTab === 'managers' ? 'MANAGER' : 'ADMIN')} className="bg-gradient-to-br from-[#FF9B2E] to-[#FFB347] text-white">Crear {tabs.find(t => t.key === adminUserTab)?.label.slice(0, -1)}</Button>
                <Button variant="outline" onClick={() => setShowCreateForm(false)}>Cancelar</Button>
              </div>
            </CardContent>
          </Card>
        )}

        {resetPwdForm && (
          <Card className="border-yellow-300 bg-yellow-50">
            <CardHeader><CardTitle className="text-yellow-700 flex items-center gap-2"><Key className="w-5 h-5" /> Restablecer Contraseña</CardTitle></CardHeader>
            <CardContent className="space-y-3">
              <p className="text-sm text-gray-600">Usuario: <strong>{resetPwdForm.name}</strong> ({resetPwdForm.email})</p>
              <input placeholder="Nueva contraseña (mín. 6 caracteres)" type="password" className="w-full border rounded-lg px-3 py-2 text-sm" value={adminNewPassword} onChange={e => setAdminNewPassword(e.target.value)} />
              <div className="flex gap-2">
                <Button onClick={() => handleResetPassword(resetPwdForm.id)} disabled={adminNewPassword.length < 6} className="bg-yellow-600 hover:bg-yellow-700 text-white">Restablecer</Button>
                <Button variant="outline" onClick={() => { setResetPwdForm(null); setAdminNewPassword('') }}>Cancelar</Button>
              </div>
            </CardContent>
          </Card>
        )}

        <div className="flex gap-1 border-b">
          {tabs.map(tab => (
            <button key={tab.key} onClick={() => { setAdminUserTab(tab.key); setSelectedIds(new Set()) }} className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${adminUserTab === tab.key ? 'border-[#FF9B2E] text-[#FF9B2E]' : 'border-transparent text-gray-500 hover:text-gray-700'}`}>
              {tab.label} ({tab.count})
            </button>
          ))}
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead><tr className="border-b bg-gray-50">
              <th className="px-4 py-3 text-left font-medium w-10">
                <Checkbox
                  checked={currentList.length > 0 && currentList.every((u: any) => selectedIds.has(u.id))}
                  onCheckedChange={toggleSelectAll}
                  aria-label="Seleccionar todos"
                />
              </th>
              <th className="px-4 py-3 text-left font-medium">Nombre</th>
              <th className="px-4 py-3 text-left font-medium">Email</th>
              {adminUserTab === 'customers' && <th className="px-4 py-3 text-left font-medium">Empresa</th>}
              {adminUserTab === 'customers' && <th className="px-4 py-3 text-left font-medium">Supervisor</th>}
              <th className="px-4 py-3 text-left font-medium">Estado</th>
              <th className="px-4 py-3 text-left font-medium">Acciones</th>
            </tr></thead>
            <tbody>
              {currentList.map((u: any) => (
                <tr key={u.id} className={`border-b hover:bg-gray-50 ${!u.isActive ? 'opacity-50' : ''} ${selectedIds.has(u.id) ? 'bg-orange-50' : ''}`}>
                  <td className="px-4 py-3">
                    <Checkbox
                      checked={selectedIds.has(u.id)}
                      onCheckedChange={() => toggleSelect(u.id)}
                      aria-label={`Seleccionar ${u.name}`}
                    />
                  </td>
                  <td className="px-4 py-3 font-medium">{u.name}</td>
                  <td className="px-4 py-3 text-gray-600">{u.email}</td>
                  {adminUserTab === 'customers' && <td className="px-4 py-3">{u.company || '-'}</td>}
                  {adminUserTab === 'customers' && <td className="px-4 py-3">{u.assignedBy?.name || <span className="text-gray-400">Sin asignar</span>}</td>}
                  <td className="px-4 py-3">
                    <Badge className={u.isActive ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}>
                      {u.isActive ? 'Activo' : 'Inactivo'}
                    </Badge>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex gap-1">
                      <Button size="sm" variant="outline" onClick={() => setResetPwdForm(u)} title="Restablecer contraseña"><Key className="w-3.5 h-3.5" /></Button>
                      <Button size="sm" variant={u.isActive ? 'destructive' : 'outline'} onClick={() => handleToggleActive(u.id, u.role)}>
                        {u.isActive ? 'Desactivar' : 'Reactivar'}
                      </Button>
                    </div>
                  </td>
                </tr>
              ))}
              {currentList.length === 0 && (
                <tr><td colSpan={7} className="px-4 py-8 text-center text-gray-400">No hay usuarios</td></tr>
              )}
            </tbody>
          </table>
        </div>

        {/* Bulk Delete Confirmation Dialog */}
        <AlertDialog open={showBulkDeleteConfirm} onOpenChange={setShowBulkDeleteConfirm}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>¿Eliminar {selectedIds.size} usuario(s)?</AlertDialogTitle>
              <AlertDialogDescription>
                Esta acción eliminará permanentemente los usuarios seleccionados y todos sus datos asociados (reseñas, respuestas, notificaciones). Esta operación no se puede deshacer.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>Cancelar</AlertDialogCancel>
              <AlertDialogAction
                onClick={handleBulkDelete}
                className="bg-destructive text-white hover:bg-destructive/90"
              >
                Eliminar
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </div>
    )
  }

  // ==================== ADMIN: ASIGNACIONES ====================
  function AdminAssignments() {
    const [assigningCustomerId, setAssigningCustomerId] = useState<string | null>(null)

    const handleAssign = async (customerId: string, supervisorId: string) => {
      try {
        await api.assignSupervisor(customerId, supervisorId || null)
        toast({ title: '✅ Asignación actualizada' })
        setAssigningCustomerId(null)
        fetchAdminUsers()
      } catch (err: any) {
        toast({ title: 'Error', description: err.message, variant: 'destructive' })
      }
    }

    const handleReassignReview = async (reviewId: string, supervisorId: string) => {
      try {
        await api.reassignReview(reviewId, supervisorId)
        toast({ title: '✅ Reseña reasignada' })
        fetchReviewDetail(reviewId)
      } catch (err: any) {
        toast({ title: 'Error', description: err.message, variant: 'destructive' })
      }
    }

    return (
      <div className="space-y-6">
        <h2 className="text-xl font-bold text-gray-900">Asignación de Clientes a Supervisores</h2>

        <Card>
          <CardHeader><CardTitle className="text-[#2D5BFF] flex items-center gap-2"><Users className="w-5 h-5" /> Clientes y sus Supervisores</CardTitle></CardHeader>
          <CardContent>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead><tr className="border-b bg-gray-50">
                  <th className="px-4 py-3 text-left font-medium">Cliente</th>
                  <th className="px-4 py-3 text-left font-medium">Empresa</th>
                  <th className="px-4 py-3 text-left font-medium">Supervisor Asignado</th>
                  <th className="px-4 py-3 text-left font-medium">Acción</th>
                </tr></thead>
                <tbody>
                  {adminUsers.filter((u: any) => u.isActive).map((customer: any) => (
                    <tr key={customer.id} className="border-b hover:bg-gray-50">
                      <td className="px-4 py-3 font-medium">{customer.name}</td>
                      <td className="px-4 py-3 text-gray-600">{customer.company || '-'}</td>
                      <td className="px-4 py-3">
                        {assigningCustomerId === customer.id ? (
                          <select className="border rounded px-2 py-1 text-sm" value={customer.assignedBy?.id || ''} onChange={e => handleAssign(customer.id, e.target.value)}>
                            <option value="">Sin supervisor</option>
                            {adminSupervisors.filter((s: any) => s.isActive).map((s: any) => (
                              <option key={s.id} value={s.id}>{s.name}</option>
                            ))}
                          </select>
                        ) : (
                          <span className={customer.assignedBy ? 'text-gray-900' : 'text-gray-400'}>
                            {customer.assignedBy?.name || 'Sin asignar'}
                          </span>
                        )}
                      </td>
                      <td className="px-4 py-3">
                        <Button size="sm" variant="outline" onClick={() => setAssigningCustomerId(assigningCustomerId === customer.id ? null : customer.id)}>
                          <UserCheck className="w-3.5 h-3.5 mr-1" />
                          {assigningCustomerId === customer.id ? 'Cancelar' : 'Asignar'}
                        </Button>
                      </td>
                    </tr>
                  ))}
                  {adminUsers.filter((u: any) => u.isActive).length === 0 && (
                    <tr><td colSpan={4} className="px-4 py-8 text-center text-gray-400">No hay clientes activos</td></tr>
                  )}
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>

        {/* Reassign Reviews Section */}
        {reviewDetail && user?.role === 'ADMIN' && (
          <Card className="border-blue-200">
            <CardHeader><CardTitle className="text-[#2D5BFF] flex items-center gap-2"><ArrowLeftRight className="w-5 h-5" /> Reasignar Reseña</CardTitle></CardHeader>
            <CardContent className="space-y-3">
              <p className="text-sm"><strong>Reseña:</strong> {reviewDetail.reviewCode} — {reviewDetail.title}</p>
              <p className="text-sm"><strong>Supervisor actual:</strong> {reviewDetail.assignedTo?.name || 'Sin asignar'}</p>
              <div className="flex gap-2 items-center">
                <select id="reassign-select" className="border rounded px-3 py-2 text-sm flex-1" defaultValue="">
                  <option value="" disabled>Seleccionar nuevo supervisor...</option>
                  {adminSupervisors.filter((s: any) => s.isActive).map((s: any) => (
                    <option key={s.id} value={s.id}>{s.name}</option>
                  ))}
                </select>
                <Button onClick={() => {
                  const sel = document.getElementById('reassign-select') as HTMLSelectElement
                  if (sel?.value && reviewDetail) handleReassignReview(reviewDetail.id, sel.value)
                }} className="bg-[#2D5BFF] text-white">Reasignar</Button>
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    )
  }

  // ==================== ADMIN: LIMPIEZA DE DATOS ====================
  function AdminCleanup() {
    const [executing, setExecuting] = useState<string | null>(null)

    const handleCleanup = async (action: string) => {
      if (!confirm('¿Está seguro de que desea ejecutar esta acción? Esta operación no se puede deshacer.')) return
      setExecuting(action)
      try {
        const result = await api.executeCleanup(action)
        toast({ title: '✅ Limpieza completada', description: `${result.result.deletedCount} registros eliminados` })
        fetchCleanupData()
      } catch (err: any) {
        toast({ title: 'Error', description: err.message, variant: 'destructive' })
      } finally {
        setExecuting(null)
      }
    }

    const severityColors: Record<string, string> = {
      low: 'border-green-200 bg-green-50',
      medium: 'border-yellow-200 bg-yellow-50',
      high: 'border-red-200 bg-red-50',
    }

    const severityLabels: Record<string, string> = {
      low: '🟢 Bajo',
      medium: '🟡 Medio',
      high: '🔴 Alto',
    }

    return (
      <div className="space-y-6">
        <h2 className="text-xl font-bold text-gray-900">Limpieza de Datos</h2>
        <p className="text-sm text-gray-500">Herramientas de mantenimiento para eliminar datos temporales, registros de prueba y información obsoleta.</p>

        <div className="grid gap-4">
          {cleanupOptions.map((opt: any) => (
            <Card key={opt.action} className={severityColors[opt.severity] || ''}>
              <CardContent className="p-4">
                <div className="flex items-center justify-between">
                  <div>
                    <h3 className="font-semibold text-gray-900">{opt.label}</h3>
                    <p className="text-sm text-gray-500 mt-1">{opt.count} registros encontrados</p>
                    <p className="text-xs text-gray-400 mt-1">Impacto: {severityLabels[opt.severity] || opt.severity}</p>
                  </div>
                  <Button
                    onClick={() => handleCleanup(opt.action)}
                    disabled={opt.count === 0 || executing === opt.action}
                    variant={opt.severity === 'high' ? 'destructive' : 'outline'}
                  >
                    {executing === opt.action ? 'Ejecutando...' : 'Ejecutar'}
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
          {cleanupOptions.length === 0 && !loading && (
            <Card><CardContent className="p-8 text-center text-gray-400">Cargando opciones de limpieza...</CardContent></Card>
          )}
        </div>
      </div>
    )
  }
}
