'use client'

import { Package, Building2, MapPin, Truck, Clock, Calendar, Settings } from 'lucide-react'
import React, { useState, useEffect } from 'react'
import { createPortal } from 'react-dom'

import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { formatCurrency } from '@/lib/utils'

// Интерфейс для данных из GraphQL (многоуровневая система)
interface SupplyOrderFromGraphQL {
  id: string
  organizationId: string
  partnerId: string
  partner: {
    id: string
    name?: string
    fullName?: string
    inn: string
    address?: string
    market?: string
    phones?: Array<{ value: string }>
    emails?: Array<{ value: string }>
    type: string
  }
  deliveryDate: string
  status: string
  totalAmount: number
  totalItems: number
  fulfillmentCenterId?: string
  fulfillmentCenter?: {
    id: string
    name?: string
    fullName?: string
    address?: string
  }
  logisticsPartnerId?: string
  logisticsPartner?: {
    id: string
    name?: string
    fullName?: string
  }
  packagesCount?: number
  volume?: number
  responsibleEmployee?: string
  employee?: {
    id: string
    firstName: string
    lastName: string
    position: string
    department?: string
  }
  notes?: string
  routes: Array<{
    id: string
    logisticsId?: string
    fromLocation: string
    toLocation: string
    fromAddress?: string
    toAddress?: string
    price?: number
    status?: string
    createdDate: string
    logistics?: {
      id: string
      fromLocation: string
      toLocation: string
      priceUnder1m3: number
      priceOver1m3: number
      description?: string
    }
  }>
  items: Array<{
    id: string
    quantity: number
    price: number
    totalPrice: number
    product: {
      id: string
      name: string
      article?: string
      description?: string
      price: number
      category?: { name: string }
      sizes?: Array<{ id: string; name: string; quantity: number }>
    }
    productId: string
    recipe?: {
      services?: Array<{
        id: string
        name: string
        price: number
      }>
      fulfillmentConsumables?: Array<{
        id: string
        name: string
        price: number
      }>
      sellerConsumables?: Array<{
        id: string
        name: string
        price: number
      }>
      marketplaceCardId?: string
    }
  }>
  createdAt: string
  updatedAt: string
}

interface MultiLevelSuppliesTableProps {
  supplies?: SupplyOrderFromGraphQL[]
  loading?: boolean
  userRole?: 'SELLER' | 'WHOLESALE' | 'FULFILLMENT' | 'LOGIST'
  activeTab?: string
  onSupplyAction?: (supplyId: string, action: string) => void
  onVolumeChange?: (supplyId: string, volume: number | null) => void
  onPackagesChange?: (supplyId: string, packagesCount: number | null) => void
  onUpdateComplete?: (supplyId: string, field: 'volume' | 'packages') => void
}

// Простые компоненты таблицы
const Table = ({ children, ...props }: { children: React.ReactNode; [key: string]: unknown }) => (
  <div className="w-full" {...props}>
    <table className="w-full">{children}</table>
  </div>
)

const TableHeader = ({ children, ...props }: { children: React.ReactNode; [key: string]: unknown }) => (
  <thead {...props}>{children}</thead>
)
const TableBody = ({ children, ...props }: { children: React.ReactNode; [key: string]: unknown }) => (
  <tbody {...props}>{children}</tbody>
)
const TableRow = ({
  children,
  className,
  ...props
}: {
  children: React.ReactNode
  className?: string
  [key: string]: unknown
}) => (
  <tr className={className} {...props}>
    {children}
  </tr>
)
const TableHead = ({
  children,
  className,
  ...props
}: {
  children: React.ReactNode
  className?: string
  [key: string]: unknown
}) => (
  <th className={`px-4 py-3 text-left ${className}`} {...props}>
    {children}
  </th>
)
const TableCell = ({
  children,
  className,
  ...props
}: {
  children: React.ReactNode
  className?: string
  [key: string]: unknown
}) => (
  <td className={`px-4 py-3 ${className}`} {...props}>
    {children}
  </td>
)

// ActionButtons компонент для кнопок действий поставщика
function ActionButtons({ 
  supplyId, 
  onSupplyAction, 
}: { 
  supplyId: string
  onSupplyAction?: (supplyId: string, action: string) => void 
}) {
  return (
    <div className="flex space-x-2">
      <Button
        type="button"
        size="sm"
        className="glass-button bg-gradient-to-r from-green-500 to-emerald-500 text-white text-xs font-medium h-8 px-3 hover:scale-105 transition-all duration-200"
        onClick={(e) => {
          e.stopPropagation()
          onSupplyAction?.(supplyId, 'approve')
        }}
      >
        Одобрить
      </Button>
      <Button
        type="button"
        size="sm"
        className="bg-gradient-to-r from-red-600 to-red-500 hover:from-red-700 hover:to-red-600 text-white text-xs font-medium h-8 px-3 hover:scale-105 transition-all duration-200 backdrop-blur border border-red-500/30"
        onClick={(e) => {
          e.stopPropagation()
          onSupplyAction?.(supplyId, 'reject')
        }}
      >
        Отклонить
      </Button>
    </div>
  )
}

// Компонент для статуса поставки
function StatusBadge({ status }: { status: string }) {
  const getStatusColor = (status: string) => {
    // ✅ ОБНОВЛЕНО: Новая цветовая схема статусов
    switch (status.toLowerCase()) {
      case 'pending':
        return 'bg-orange-500/20 text-orange-300 border-orange-500/30' // Ожидает поставщика
      case 'supplier_approved':
        return 'bg-blue-500/20 text-blue-300 border-blue-500/30' // Одобрена поставщиком
      case 'logistics_confirmed':
        return 'bg-purple-500/20 text-purple-300 border-purple-500/30' // Логистика подтверждена
      case 'shipped':
        return 'bg-indigo-500/20 text-indigo-300 border-indigo-500/30' // Отгружена
      case 'in_transit':
        return 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30' // В пути
      case 'delivered':
        return 'bg-green-500/20 text-green-300 border-green-500/30' // Доставлена ✅
      case 'cancelled':
        return 'bg-red-500/20 text-red-300 border-red-500/30' // Отменена
      default:
        return 'bg-gray-500/20 text-gray-300 border-gray-500/30'
    }
  }

  const getStatusText = (status: string) => {
    switch (status.toLowerCase()) {
      case 'pending':
        return 'Ожидает поставщика' // ✅ ИСПРАВЛЕНО
      case 'supplier_approved':
        return 'Одобрена поставщиком'
      case 'logistics_confirmed':
        return 'Логистика подтверждена'
      case 'shipped':
        return 'Отгружена'
      case 'in_transit':
        return 'В пути'
      case 'delivered':
        return 'Доставлена'
      case 'cancelled':
        return 'Отменена'
      default:
        return status
    }
  }

  return <Badge className={`${getStatusColor(status)} border text-xs`}>{getStatusText(status)}</Badge>
}

// Компонент контекстного меню для отмены поставки
function ContextMenu({
  isOpen,
  position,
  onClose,
  onCancel,
}: {
  isOpen: boolean
  position: { x: number; y: number }
  onClose: () => void
  onCancel: () => void
}) {
  // console.log('🎨 ContextMenu render:', { isOpen, position })
  if (!isOpen) return null

  const menuContent = (
    <>
      {/* Overlay для закрытия меню */}
      <div className="fixed inset-0" style={{ zIndex: 9998 }} onClick={onClose} />

      {/* Контекстное меню */}
      <div
        className="fixed bg-gray-900 border border-white/20 rounded-lg shadow-xl py-1 min-w-[160px]"
        style={{
          left: position.x,
          top: position.y,
          zIndex: 9999,
          backgroundColor: 'rgb(17, 24, 39)',
          borderColor: 'rgba(255, 255, 255, 0.2)',
        }}
      >
        <button
          onClick={(e) => {
            e.stopPropagation()
            onCancel()
          }}
          className="w-full px-3 py-2 text-left text-red-400 hover:bg-red-500/20 hover:text-red-300 text-sm transition-colors"
        >
          Отменить поставку
        </button>
      </div>
    </>
  )

  // Используем портал для рендера в body
  return typeof window !== 'undefined' ? createPortal(menuContent, document.body) : null
}

// Компонент диалога подтверждения отмены
function CancelConfirmDialog({
  isOpen,
  onClose,
  onConfirm,
  supplyId,
}: {
  isOpen: boolean
  onClose: () => void
  onConfirm: () => void
  supplyId: string | null
}) {
  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="bg-gray-900/95 backdrop-blur border-white/20">
        <DialogHeader>
          <DialogTitle className="text-white">Отменить поставку</DialogTitle>
          <DialogDescription className="text-white/70">
            Вы точно хотите отменить поставку #{supplyId?.slice(-4).toUpperCase()}? Это действие нельзя будет отменить.
          </DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <Button
            variant="outline"
            onClick={onClose}
            className="bg-white/10 border-white/20 text-white hover:bg-white/20"
          >
            Отмена
          </Button>
          <Button onClick={onConfirm} className="bg-red-600 hover:bg-red-700 text-white">
            Да, отменить поставку
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}

// Основной компонент многоуровневой таблицы поставок
export function MultiLevelSuppliesTable({
  supplies = [],
  loading: _loading = false,
  userRole = 'SELLER',
  activeTab,
  onSupplyAction,
  onVolumeChange,
  onPackagesChange,
  onUpdateComplete,
}: MultiLevelSuppliesTableProps) {
  const [expandedSupplies, setExpandedSupplies] = useState<Set<string>>(new Set())
  const [expandedRoutes, setExpandedRoutes] = useState<Set<string>>(new Set())
  const [expandedSuppliers, setExpandedSuppliers] = useState<Set<string>>(new Set())
  const [expandedProducts, setExpandedProducts] = useState<Set<string>>(new Set())
  
  // Локальное состояние для инпутов
  const [inputValues, setInputValues] = useState<{[key: string]: {volume: string, packages: string}}>({})
  // Отслеживание, какие инпуты редактируются (пока не придет ответ от сервера)
  const [pendingUpdates, setPendingUpdates] = useState<Set<string>>(new Set())
  
  // Синхронизация локального состояния с данными поставок
  useEffect(() => {
    setInputValues(prev => {
      const newValues: {[key: string]: {volume: string, packages: string}} = {}
      supplies.forEach(supply => {
        // Не перезаписываем значения для инпутов с ожидающими обновлениями
        const isVolumePending = pendingUpdates.has(`${supply.id}-volume`)
        const isPackagesPending = pendingUpdates.has(`${supply.id}-packages`)
        
        newValues[supply.id] = {
          volume: isVolumePending ? (prev[supply.id]?.volume ?? '') : (supply.volume?.toString() ?? ''),
          packages: isPackagesPending ? (prev[supply.id]?.packages ?? '') : (supply.packagesCount?.toString() ?? ''),
        }
      })
      
      // Проверяем, нужно ли обновление
      const hasChanges = supplies.some(supply => {
        const isVolumePending = pendingUpdates.has(`${supply.id}-volume`)
        const isPackagesPending = pendingUpdates.has(`${supply.id}-packages`)
        
        if (isVolumePending || isPackagesPending) return false
        
        const volumeChanged = prev[supply.id]?.volume !== (supply.volume?.toString() ?? '')
        const packagesChanged = prev[supply.id]?.packages !== (supply.packagesCount?.toString() ?? '')
        
        return volumeChanged || packagesChanged
      })
      
      return hasChanges ? newValues : prev
    })
  }, [supplies, pendingUpdates])

  // Обработчик завершения обновления для сброса pending состояния
  useEffect(() => {
    if (onUpdateComplete) {
      const handleUpdateComplete = (supplyId: string, field: 'volume' | 'packages') => {
        setPendingUpdates(prev => {
          const newSet = new Set(prev)
          newSet.delete(`${supplyId}-${field}`)
          return newSet
        })
      }
      // Эта функция будет вызываться из родительского компонента
      (window as any).__handleUpdateComplete = handleUpdateComplete
    }
  }, [onUpdateComplete])

  // Состояния для контекстного меню
  const [contextMenu, setContextMenu] = useState<{
    isOpen: boolean
    position: { x: number; y: number }
    supplyId: string | null
  }>({
    isOpen: false,
    position: { x: 0, y: 0 },
    supplyId: null,
  })
  const [cancelDialogOpen, setCancelDialogOpen] = useState(false)


  // Массив цветов для различения поставок (с лучшим контрастом)
  const supplyColors = [
    'rgba(96, 165, 250, 0.8)', // Синий
    'rgba(244, 114, 182, 0.8)', // Розовый (заменил зеленый для лучшего контраста)
    'rgba(168, 85, 247, 0.8)', // Фиолетовый
    'rgba(251, 146, 60, 0.8)', // Оранжевый
    'rgba(248, 113, 113, 0.8)', // Красный
    'rgba(34, 211, 238, 0.8)', // Голубой
    'rgba(74, 222, 128, 0.8)', // Зеленый (переместил на 7 позицию)
    'rgba(250, 204, 21, 0.8)', // Желтый
  ]

  const getSupplyColor = (index: number) => supplyColors[index % supplyColors.length]

  // Функция для получения цвета фона строки в зависимости от уровня иерархии
  const getLevelBackgroundColor = (level: number, _supplyIndex: number) => {
    const alpha = 0.08 + level * 0.03 // Больше прозрачности: начальное значение 0.08, шаг 0.03

    // Цвета для разных уровней (соответствуют цветам точек)
    const levelColors = {
      1: 'rgba(96, 165, 250, ', // Синий для поставки
      2: 'rgba(96, 165, 250, ', // Синий для маршрута
      3: 'rgba(74, 222, 128, ', // Зеленый для поставщика
      4: 'rgba(244, 114, 182, ', // Розовый для товара
      5: 'rgba(250, 204, 21, ', // Желтый для рецептуры
    }

    const baseColor = levelColors[level as keyof typeof levelColors] || 'rgba(75, 85, 99, '
    return baseColor + `${alpha})`
  }

  const toggleSupplyExpansion = (supplyId: string) => {
    const newExpanded = new Set(expandedSupplies)
    if (newExpanded.has(supplyId)) {
      newExpanded.delete(supplyId)
    } else {
      newExpanded.add(supplyId)
    }
    setExpandedSupplies(newExpanded)
  }

  const toggleRouteExpansion = (routeId: string) => {
    const newExpanded = new Set(expandedRoutes)
    if (newExpanded.has(routeId)) {
      newExpanded.delete(routeId)
    } else {
      newExpanded.add(routeId)
    }
    setExpandedRoutes(newExpanded)
  }

  const toggleSupplierExpansion = (supplierId: string) => {
    const newExpanded = new Set(expandedSuppliers)
    if (newExpanded.has(supplierId)) {
      newExpanded.delete(supplierId)
    } else {
      newExpanded.add(supplierId)
    }
    setExpandedSuppliers(newExpanded)
  }

  const toggleProductExpansion = (productId: string) => {
    const newExpanded = new Set(expandedProducts)
    if (newExpanded.has(productId)) {
      newExpanded.delete(productId)
    } else {
      newExpanded.add(productId)
    }
    setExpandedProducts(newExpanded)
  }

  const handleCancelSupply = (supplyId: string) => {
    onSupplyAction?.(supplyId, 'cancel')
    setCancelDialogOpen(false)
    setContextMenu({ isOpen: false, position: { x: 0, y: 0 }, supplyId: null })
  }

  const handleContextMenu = (e: React.MouseEvent, supply: SupplyOrderFromGraphQL) => {
    // Проверяем роль и статус - показываем контекстное меню только для SELLER и отменяемых статусов
    if (userRole !== 'SELLER') return

    const canCancel = ['PENDING', 'SUPPLIER_APPROVED'].includes(supply.status.toUpperCase())
    if (!canCancel) return

    setContextMenu({
      isOpen: true,
      position: { x: e.clientX, y: e.clientY },
      supplyId: supply.id,
    })
  }

  const handleCloseContextMenu = () => {
    setContextMenu({ isOpen: false, position: { x: 0, y: 0 }, supplyId: null })
  }

  const handleCancelFromContextMenu = () => {
    setContextMenu({ isOpen: false, position: { x: 0, y: 0 }, supplyId: null })
    setCancelDialogOpen(true)
  }

  const handleConfirmCancel = () => {
    if (contextMenu.supplyId) {
      handleCancelSupply(contextMenu.supplyId)
    }
  }

  // Функция для отображения действий в зависимости от роли пользователя
  const _renderActionButtons = (supply: SupplyOrderFromGraphQL) => {
    const { status, id } = supply

    switch (userRole) {
      case 'WHOLESALE': // Поставщик
        if (status === 'PENDING') {
          return (
            <div className="flex items-center space-x-2">
              <Button
                size="sm"
                onClick={(e) => {
                  e.stopPropagation()
                  onSupplyAction?.(id, 'approve')
                }}
                className="bg-green-500/20 hover:bg-green-500/30 text-green-300 border border-green-500/30"
              >
                Одобрить
              </Button>
              <Button
                size="sm"
                onClick={(e) => {
                  e.stopPropagation()
                  onSupplyAction?.(id, 'reject')
                }}
                className="bg-red-500/20 hover:bg-red-500/30 text-red-300 border border-red-500/30"
              >
                Отклонить
              </Button>
            </div>
          )
        }
        if (status === 'LOGISTICS_CONFIRMED') {
          return (
            <Button
              size="sm"
              onClick={(e) => {
                e.stopPropagation()
                onSupplyAction?.(id, 'ship')
              }}
              className="bg-orange-500/20 hover:bg-orange-500/30 text-orange-300 border border-orange-500/30"
            >
              <Truck className="h-3 w-3 mr-1" />
              Отгрузить
            </Button>
          )
        }
        break

      case 'SELLER': // Селлер
        return (
          <Button
            size="sm"
            variant="outline"
            className="text-red-400 border-red-400 hover:bg-red-400/10"
            onClick={() => handleCancelSupply(id)}
          >
            Отменить
          </Button>
        )

      case 'FULFILLMENT': // Фулфилмент
        if (status === 'SUPPLIER_APPROVED') {
          return (
            <Button
              size="sm"
              onClick={(e) => {
                e.stopPropagation()
                onSupplyAction?.(id, 'accept')
              }}
              className="bg-blue-500/20 hover:bg-blue-500/30 text-blue-300 border border-blue-500/30"
            >
              Принять
            </Button>
          )
        }
        if (status === 'SHIPPED') {
          return (
            <Button
              size="sm"
              onClick={(e) => {
                e.stopPropagation()
                onSupplyAction?.(id, 'receive')
              }}
              className="bg-green-500/20 hover:bg-green-500/30 text-green-300 border border-green-500/30"
            >
              <Package className="h-3 w-3 mr-1" />
              Принять на склад
            </Button>
          )
        }
        break

      case 'LOGIST': // Логист
        if (status === 'CONFIRMED') {
          return (
            <Button
              size="sm"
              onClick={(e) => {
                e.stopPropagation()
                onSupplyAction?.(id, 'confirm_logistics')
              }}
              className="bg-purple-500/20 hover:bg-purple-500/30 text-purple-300 border border-purple-500/30"
            >
              Подтвердить
            </Button>
          )
        }
        break

      default:
        return null
    }

    return null
  }

  // Вычисляемые поля для уровня 1 (агрегированные данные)
  const getSupplyAggregatedData = (supply: SupplyOrderFromGraphQL) => {
    const items = supply.items || []
    const routes = supply.routes || []

    const orderedTotal = items.reduce((sum, item) => sum + (item.quantity || 0), 0)
    /* ОТКАТ: Удаление колонок "Поставлено" и "Брак" */
    const deliveredTotal = 0 // Пока нет данных о поставленном количестве
    const defectTotal = 0 // Пока нет данных о браке
    /* /ОТКАТ */

    const goodsPrice = items.reduce((sum, item) => sum + (item.totalPrice || 0), 0)

    // ✅ ИСПРАВЛЕНО: Расчет услуг ФФ по формуле из CartBlock.tsx
    const servicesPrice = items.reduce((sum, item) => {
      const recipe = item.recipe
      if (!recipe?.services) return sum

      const itemServicesPrice = recipe.services.reduce((serviceSum, service) => {
        return serviceSum + service.price * item.quantity
      }, 0)

      return sum + itemServicesPrice
    }, 0)

    // ✅ ДОБАВЛЕНО: Расчет расходников ФФ
    const ffConsumablesPrice = items.reduce((sum, item) => {
      const recipe = item.recipe
      if (!recipe?.fulfillmentConsumables) return sum

      const itemFFConsumablesPrice = recipe.fulfillmentConsumables.reduce((consumableSum, consumable) => {
        return consumableSum + consumable.price * item.quantity
      }, 0)

      return sum + itemFFConsumablesPrice
    }, 0)

    // ✅ ДОБАВЛЕНО: Расчет расходников селлера
    const sellerConsumablesPrice = items.reduce((sum, item) => {
      const recipe = item.recipe
      if (!recipe?.sellerConsumables) return sum

      const itemSellerConsumablesPrice = recipe.sellerConsumables.reduce((consumableSum, consumable) => {
        // Используем price как pricePerUnit согласно GraphQL схеме
        return consumableSum + consumable.price * item.quantity
      }, 0)

      return sum + itemSellerConsumablesPrice
    }, 0)

    const logisticsPrice = routes.reduce((sum, route) => sum + (route.price || 0), 0)

    const total = goodsPrice + servicesPrice + ffConsumablesPrice + sellerConsumablesPrice + logisticsPrice

    return {
      orderedTotal,
      /* ОТКАТ: Удаление колонок "Поставлено" и "Брак" */
      deliveredTotal,
      defectTotal,
      /* /ОТКАТ */
      goodsPrice,
      servicesPrice,
      ffConsumablesPrice,
      sellerConsumablesPrice,
      logisticsPrice,
      total,
    }
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('ru-RU', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    })
  }

  // Убрано состояние loading - показываем таблицу сразу

  return (
    <>
      <div className="relative">
        {/* Таблица поставок */}
        <Table>
          <TableHeader className="sticky top-0 z-10 backdrop-blur-sm">
            <TableRow className="border-b border-white/20">
              <TableHead className="text-white/90 text-sm font-light whitespace-nowrap">№</TableHead>
              <TableHead className="text-white/90 text-sm font-light whitespace-nowrap">Дата поставки</TableHead>
              <TableHead className="text-white/90 text-sm font-light whitespace-nowrap">Заказано</TableHead>
              {/* 🔒 БЕЗОПАСНОСТЬ: WHOLESALE не видит колонки "Поставлено" и "Брак" */}
              {userRole !== 'WHOLESALE' && (
                <>
                  <TableHead className="text-white/90 text-sm font-light whitespace-nowrap">Поставлено</TableHead>
                  <TableHead className="text-white/90 text-sm font-light whitespace-nowrap">Брак</TableHead>
                </>
              )}
              <TableHead className="text-white/90 text-sm font-light whitespace-nowrap">Цена товаров</TableHead>
              {/* 🆕 НОВЫЕ КОЛОНКИ: Объём и грузовые места между "Цена товаров" и "Статус" */}
              {/* 🔒 ВИДИМОСТЬ: Только для WHOLESALE, FULFILLMENT, LOGIST (НЕ для SELLER) */}
              {(userRole === 'WHOLESALE' || userRole === 'FULFILLMENT' || userRole === 'LOGIST') && (
                <>
                  <TableHead className="text-white/90 text-sm font-light whitespace-nowrap">Объём</TableHead>
                  <TableHead className="text-white/90 text-sm font-light whitespace-nowrap">Грузовые места</TableHead>
                </>
              )}
              {/* 🔒 БЕЗОПАСНОСТЬ: WHOLESALE не видит услуги ФФ, расходники и логистику */}
              {userRole !== 'WHOLESALE' && (
                <TableHead className="text-white/90 text-sm font-light whitespace-nowrap hidden lg:table-cell">
                  Услуги ФФ
                </TableHead>
              )}
              {userRole !== 'WHOLESALE' && (
                <TableHead className="text-white/90 text-sm font-light whitespace-nowrap hidden lg:table-cell">
                  Расходники ФФ
                </TableHead>
              )}
              {userRole !== 'WHOLESALE' && (
                <TableHead className="text-white/90 text-sm font-light whitespace-nowrap hidden lg:table-cell">
                  Расходники селлера
                </TableHead>
              )}
              {userRole !== 'WHOLESALE' && (
                <TableHead className="text-white/90 text-sm font-light whitespace-nowrap hidden lg:table-cell">
                  Логистика до ФФ
                </TableHead>
              )}
              {userRole !== 'WHOLESALE' && (
                <TableHead className="text-white/90 text-sm font-light whitespace-nowrap">
                  Итого
                </TableHead>
              )}
              <TableHead className="text-white/90 text-sm font-light whitespace-nowrap">Статус</TableHead>
            </TableRow>
          </TableHeader>

          <TableBody>
            {supplies.length > 0 &&
              supplies.map((supply, index) => {
                // Защита от неполных данных
                if (!supply.partner) {
                  console.warn('⚠️ Supply without partner:', supply.id)
                  return null
                }

                const isSupplyExpanded = expandedSupplies.has(supply.id)
                const aggregatedData = getSupplyAggregatedData(supply)

                return (
                  <React.Fragment key={supply.id}>
                    {/* УРОВЕНЬ 1: Основная строка поставки */}
                    <TableRow
                      className="border-white/10 hover:bg-white/5 cursor-pointer transition-colors"
                      style={{
                        backgroundColor: getLevelBackgroundColor(1, index),
                      }}
                      onClick={() => {
                        toggleSupplyExpansion(supply.id)
                      }}
                      onMouseUp={(e) => {
                        if (e.button === 2) {
                          // Правая кнопка мыши
                          e.preventDefault()
                          e.stopPropagation()
                          handleContextMenu(e, supply)
                        }
                      }}
                      onContextMenu={(e) => {
                        e.preventDefault()
                        return false
                      }}
                    >
                      <TableCell className="text-white font-mono text-sm relative">
                        {/* ВАРИАНТ 1: Порядковый номер поставки с цветной линией */}
                        {supplies.length - index}
                        <div
                          className="absolute left-0 top-0 w-0.5 h-full"
                          style={{ backgroundColor: getSupplyColor(index) }}
                        ></div>

                        {/* ОТКАТ: ID поставки (последние 4 символа) без цветной линии
                        {supply.id.slice(-4).toUpperCase()}
                        */}
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-1">
                          <Calendar className="h-3 w-3 text-white/40" />
                          <span className="text-white font-semibold text-sm">{formatDate(supply.deliveryDate)}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <span className="text-white font-semibold text-sm">{aggregatedData.orderedTotal}</span>
                      </TableCell>
                      {/* 🔒 БЕЗОПАСНОСТЬ: WHOLESALE не видит колонки "Поставлено" и "Брак" */}
                      {userRole !== 'WHOLESALE' && (
                        <>
                          <TableCell>
                            <span className="text-white/80 text-sm">{aggregatedData.deliveredTotal}</span>
                          </TableCell>
                          <TableCell>
                            <span className="text-white/80 text-sm">{aggregatedData.defectTotal}</span>
                          </TableCell>
                        </>
                      )}
                      <TableCell>
                        <span className="text-green-400 font-semibold text-sm">
                          {formatCurrency(aggregatedData.goodsPrice)}
                        </span>
                      </TableCell>
                      {/* 🆕 НОВЫЕ ЯЧЕЙКИ: Объём и грузовые места с инпутами для WHOLESALE */}
                      {/* 🔒 ВИДИМОСТЬ: Только для WHOLESALE, FULFILLMENT, LOGIST (НЕ для SELLER) */}
                      {(userRole === 'WHOLESALE' || userRole === 'FULFILLMENT' || userRole === 'LOGIST') && (
                        <>
                          <TableCell>
                            {userRole === 'WHOLESALE' && supply.status === 'PENDING' ? (
                              <input
                                type="number"
                                step="0.01"
                                placeholder="0.0 м³"
                                value={inputValues[supply.id]?.volume ?? ''}
                                onChange={(e) => {
                                  const value = e.target.value
                                  // Устанавливаем pending состояние
                                  setPendingUpdates(prev => new Set(prev).add(`${supply.id}-volume`))
                                  // Обновляем локальное состояние немедленно
                                  setInputValues(prev => ({
                                    ...prev,
                                    [supply.id]: {
                                      ...prev[supply.id],
                                      volume: value,
                                    },
                                  }))
                                  // Вызываем обработчик с преобразованным значением
                                  const numValue = value === '' ? null : parseFloat(value)
                                  onVolumeChange?.(supply.id, numValue)
                                }}
                                onFocus={(e) => e.stopPropagation()}
                                onClick={(e) => e.stopPropagation()}
                                onMouseDown={(e) => e.stopPropagation()}
                                className="w-20 bg-white/10 border border-white/20 rounded px-2 py-1 text-white text-sm placeholder:text-white/40 focus:outline-none focus:border-white/40"
                              />
                            ) : (
                              <span className="text-white/80 text-sm">
                                {supply.volume ? `${supply.volume} м³` : '—'}
                              </span>
                            )}
                          </TableCell>
                          <TableCell>
                            {userRole === 'WHOLESALE' && supply.status === 'PENDING' ? (
                              <input
                                type="number"
                                placeholder="0 мест"
                                value={inputValues[supply.id]?.packages ?? ''}
                                onChange={(e) => {
                                  const value = e.target.value
                                  // Устанавливаем pending состояние
                                  setPendingUpdates(prev => new Set(prev).add(`${supply.id}-packages`))
                                  // Обновляем локальное состояние немедленно
                                  setInputValues(prev => ({
                                    ...prev,
                                    [supply.id]: {
                                      ...prev[supply.id],
                                      packages: value,
                                    },
                                  }))
                                  // Вызываем обработчик с преобразованным значением
                                  const numValue = value === '' ? null : parseInt(value)
                                  onPackagesChange?.(supply.id, numValue)
                                }}
                                onFocus={(e) => e.stopPropagation()}
                                onClick={(e) => e.stopPropagation()}
                                onMouseDown={(e) => e.stopPropagation()}
                                className="w-20 bg-white/10 border border-white/20 rounded px-2 py-1 text-white text-sm placeholder:text-white/40 focus:outline-none focus:border-white/40"
                              />
                            ) : (
                              <span className="text-white/80 text-sm">
                                {supply.packagesCount ? `${supply.packagesCount} мест` : '—'}
                              </span>
                            )}
                          </TableCell>
                        </>
                      )}
                      {/* 🔒 БЕЗОПАСНОСТЬ: WHOLESALE не видит услуги ФФ, расходники и логистику */}
                      {userRole !== 'WHOLESALE' && (
                        <TableCell className="hidden lg:table-cell">
                          <span className="text-blue-400 font-semibold text-sm">
                            {formatCurrency(aggregatedData.servicesPrice)}
                          </span>
                        </TableCell>
                      )}
                      {userRole !== 'WHOLESALE' && (
                        <TableCell className="hidden lg:table-cell">
                          <span className="text-blue-400 font-semibold text-sm">
                            {formatCurrency(aggregatedData.ffConsumablesPrice)}
                          </span>
                        </TableCell>
                      )}
                      {userRole !== 'WHOLESALE' && (
                        <TableCell className="hidden lg:table-cell">
                          <span className="text-blue-400 font-semibold text-sm">
                            {formatCurrency(aggregatedData.sellerConsumablesPrice)}
                          </span>
                        </TableCell>
                      )}
                      {userRole !== 'WHOLESALE' && (
                        <TableCell className="hidden lg:table-cell">
                          <span className="text-purple-400 font-semibold text-sm">
                            {formatCurrency(aggregatedData.logisticsPrice)}
                          </span>
                        </TableCell>
                      )}
                      {userRole !== 'WHOLESALE' && (
                        <TableCell>
                          <span className="text-white font-bold text-sm">
                            {formatCurrency(aggregatedData.total)}
                          </span>
                        </TableCell>
                      )}
                      <TableCell>
                        {/* 🔒 УСЛОВНЫЙ РЕНДЕРИНГ: Кнопки действий или статус */}
                        {(() => {
                          const actionButtons = _renderActionButtons(supply)
                          if (actionButtons) {
                            return actionButtons
                          }
                          return <StatusBadge status={supply.status} />
                        })()}
                      </TableCell>
                    </TableRow>

                    {/* ВАРИАНТ 1: Строка с ID поставки между уровнями */}
                    {isSupplyExpanded && (
                      <TableRow className="border-0 bg-white/5">
                        {/* 🔒 БЕЗОПАСНОСТЬ: colSpan учитывает скрытые колонки для WHOLESALE + новые колонки объём/грузовые места */}
                        <TableCell colSpan={userRole === 'WHOLESALE' ? 7 : 9} className="py-2 px-4 relative">
                          <div className="flex items-center space-x-2">
                            <span className="text-white/60 text-xs">ID поставки:</span>
                            <span className="text-white/80 text-xs font-mono">{supply.id.slice(-8).toUpperCase()}</span>
                          </div>
                          <div
                            className="absolute left-0 top-0 w-0.5 h-full"
                            style={{ backgroundColor: getSupplyColor(index) }}
                          ></div>
                        </TableCell>
                      </TableRow>
                    )}

                    {/* ОТКАТ: Без строки ID
                    {/* Строка с ID убрана */}
                    {/* */}

                    {/* УРОВЕНЬ 2: Маршруты поставки - скрыто для WHOLESALE */}
                    {isSupplyExpanded && userRole !== 'WHOLESALE' &&
                      (() => {
                        // ✅ ВРЕМЕННАЯ ЗАГЛУШКА: создаем фиктивный маршрут для демонстрации
                        const mockRoutes =
                          supply.routes && supply.routes.length > 0
                            ? supply.routes
                            : [
                                {
                                  id: `route-${supply.id}`,
                                  createdDate: supply.deliveryDate,
                                  fromLocation: 'Садовод',
                                  toLocation: 'SFERAV Logistics ФФ',
                                  price: 0,
                                },
                              ]

                        return mockRoutes.map((route) => {
                          const isRouteExpanded = expandedRoutes.has(route.id)

                          return (
                            <React.Fragment key={route.id}>
                              <TableRow
                                className="border-white/10 hover:bg-white/5 cursor-pointer transition-colors"
                                style={{ backgroundColor: getLevelBackgroundColor(2, index) }}
                                onClick={() => toggleRouteExpansion(route.id)}
                              >
                                <TableCell className="relative">
                                  <div className="flex items-center space-x-2">
                                    <div className="w-1 h-1 rounded-full bg-blue-400 mr-1"></div>
                                    <MapPin className="h-3 w-3 text-blue-400" />
                                    <span className="text-white font-medium text-sm">Маршрут</span>
                                  </div>
                                  <div
                                    className="absolute left-0 top-0 w-0.5 h-full"
                                    style={{ backgroundColor: getSupplyColor(index) }}
                                  ></div>
                                </TableCell>
                                <TableCell>
                                  {/* ВАРИАНТ 1: Только название локации источника */}
                                  <span className="text-white text-sm font-medium">{route.fromLocation}</span>

                                  {/* ОТКАТ: Полная информация о маршруте
                              <div className="flex flex-col">
                                <span className="text-white text-sm font-medium">
                                  {route.fromLocation} → {route.toLocation}
                                </span>
                                <span className="text-white/60 text-xs">
                                  {formatDate(route.createdDate)}
                                </span>
                              </div>
                              */}
                                </TableCell>
                                <TableCell>
                                  <span className="text-white/80 text-sm">{aggregatedData.orderedTotal}</span>
                                </TableCell>
                                {/* 🔒 БЕЗОПАСНОСТЬ: WHOLESALE не видит колонки "Поставлено" и "Брак" на route level */}
                                {userRole !== 'WHOLESALE' && (
                                  <>
                                    <TableCell>
                                      <span className="text-white/80 text-sm">{aggregatedData.deliveredTotal}</span>
                                    </TableCell>
                                    <TableCell>
                                      <span className="text-white/80 text-sm">{aggregatedData.defectTotal}</span>
                                    </TableCell>
                                  </>
                                )}
                                <TableCell>
                                  <span className="text-green-400 font-medium text-sm">
                                    {formatCurrency(aggregatedData.goodsPrice)}
                                  </span>
                                </TableCell>
                                <TableCell>
                                  <span className="text-blue-400 font-medium text-sm">
                                    {formatCurrency(aggregatedData.servicesPrice)}
                                  </span>
                                </TableCell>
                                <TableCell>
                                  <span className="text-blue-400 font-medium text-sm">
                                    {formatCurrency(aggregatedData.ffConsumablesPrice)}
                                  </span>
                                </TableCell>
                                <TableCell>
                                  <span className="text-blue-400 font-medium text-sm">
                                    {formatCurrency(aggregatedData.sellerConsumablesPrice)}
                                  </span>
                                </TableCell>
                                <TableCell>
                                  <span className="text-purple-400 font-medium text-sm">
                                    {formatCurrency(route.price || 0)}
                                  </span>
                                </TableCell>
                                <TableCell>
                                  <span className="text-white font-semibold text-sm">
                                    {formatCurrency(aggregatedData.total)}
                                  </span>
                                </TableCell>
                                <TableCell></TableCell>
                                <TableCell></TableCell>
                              </TableRow>

                              {/* УРОВЕНЬ 3: Поставщик */}
                              {isRouteExpanded && (
                                <TableRow
                                  className="border-white/10 hover:bg-white/5 cursor-pointer transition-colors"
                                  style={{ backgroundColor: getLevelBackgroundColor(3, index) }}
                                  onClick={() => toggleSupplierExpansion(supply.partner.id)}
                                >
                                  <TableCell className="relative">
                                    <div className="flex items-center space-x-2">
                                      <div className="w-1 h-1 rounded-full bg-green-400 mr-1"></div>
                                      <div className="w-1 h-1 rounded-full bg-green-400 mr-1"></div>
                                      <Building2 className="h-3 w-3 text-green-400" />
                                      <span className="text-white font-medium text-sm">Поставщик</span>
                                    </div>
                                    <div
                                      className="absolute left-0 top-0 w-0.5 h-full"
                                      style={{ backgroundColor: getSupplyColor(index) }}
                                    ></div>
                                  </TableCell>
                                  <TableCell>
                                    {/* ВАРИАНТ 1: Название, управляющий и телефон */}
                                    <div className="flex flex-col">
                                      <span className="text-white text-sm font-medium">
                                        {supply.partner.name || supply.partner.fullName}
                                      </span>
                                      {/* Имя управляющего из пользователей организации */}
                                      {supply.partner.users &&
                                        supply.partner.users.length > 0 &&
                                        supply.partner.users[0].managerName && (
                                          <span className="text-white/60 text-xs">
                                            {supply.partner.users[0].managerName}
                                          </span>
                                        )}
                                      {/* Телефон из БД (JSON поле) */}
                                      {supply.partner.phones &&
                                        Array.isArray(supply.partner.phones) &&
                                        supply.partner.phones.length > 0 && (
                                          <span className="text-white/60 text-[10px]">
                                            {typeof supply.partner.phones[0] === 'string'
                                              ? supply.partner.phones[0]
                                              : supply.partner.phones[0]?.value || supply.partner.phones[0]?.phone}
                                          </span>
                                        )}
                                    </div>

                                    {/* ОТКАТ: Только название поставщика
                                <span className="text-white text-sm font-medium">
                                  {supply.partner.name || supply.partner.fullName}
                                </span>
                                */}
                                  </TableCell>
                                  <TableCell>
                                    <span className="text-white/80 text-sm">{aggregatedData.orderedTotal}</span>
                                  </TableCell>
                                  <TableCell>
                                    <span className="text-green-400 font-medium text-sm">
                                      {formatCurrency(aggregatedData.goodsPrice)}
                                    </span>
                                  </TableCell>
                                  {userRole !== 'WHOLESALE' && (
                                    <>
                                      {/* ОТКАТ: colSpan должен быть 4 вместо 2 */}
                                      <TableCell colSpan={4} className="text-right pr-8">
                                        {/* Агрегированные данные поставщика отображаются только в итого */}
                                      </TableCell>
                                      <TableCell>
                                        <span className="text-white font-semibold text-sm">
                                          {formatCurrency(aggregatedData.total)}
                                        </span>
                                      </TableCell>
                                    </>
                                  )}
                                  <TableCell></TableCell>
                                  <TableCell></TableCell>
                                </TableRow>
                              )}

                              {/* УРОВЕНЬ 4: Товары */}
                              {isRouteExpanded &&
                                expandedSuppliers.has(supply.partner.id) &&
                                (supply.items || []).map((item) => {
                                  const isProductExpanded = expandedProducts.has(item.id)

                                  return (
                                    <React.Fragment key={item.id}>
                                      <TableRow
                                        className="border-white/10 hover:bg-white/5 cursor-pointer transition-colors"
                                        style={{ backgroundColor: getLevelBackgroundColor(4, index) }}
                                        onClick={() => toggleProductExpansion(item.id)}
                                      >
                                        <TableCell className="relative">
                                          <div className="flex items-center space-x-2">
                                            <div className="w-1 h-1 rounded-full bg-pink-400 mr-1"></div>
                                            <div className="w-1 h-1 rounded-full bg-pink-400 mr-1"></div>
                                            <div className="w-1 h-1 rounded-full bg-pink-400 mr-1"></div>
                                            <Package className="h-3 w-3 text-pink-400" />
                                            <span className="text-white font-medium text-sm">Товар</span>
                                          </div>
                                          <div
                                            className="absolute left-0 top-0 w-0.5 h-full"
                                            style={{ backgroundColor: getSupplyColor(index) }}
                                          ></div>
                                        </TableCell>
                                        <TableCell>
                                          <div className="flex flex-col">
                                            <span className="text-white text-sm font-medium">{item.product.name}</span>
                                            <span className="text-white/60 text-[9px]">
                                              Арт: {item.product.article || 'SF-T-925635-494'}
                                              {item.product.category && ` · ${item.product.category.name}`}
                                            </span>
                                          </div>
                                        </TableCell>
                                        <TableCell>
                                          <span className="text-white font-semibold text-sm">{item.quantity}</span>
                                        </TableCell>
                                        <TableCell>
                                          <span className="text-white font-semibold text-sm">-</span>
                                        </TableCell>
                                        <TableCell>
                                          <span className="text-white font-semibold text-sm">-</span>
                                        </TableCell>
                                        <TableCell>
                                          <div className="text-white">
                                            <div className="font-medium text-sm">{formatCurrency(item.totalPrice)}</div>
                                            <div className="text-xs text-white/60 hidden sm:block">
                                              {formatCurrency(item.price)} за шт.
                                            </div>
                                          </div>
                                        </TableCell>
                                        <TableCell>
                                          <span className="text-blue-400 font-medium text-sm">
                                            {formatCurrency(
                                              (item.recipe?.services || []).reduce(
                                                (sum, service) => sum + service.price * item.quantity,
                                                0,
                                              ),
                                            )}
                                          </span>
                                        </TableCell>
                                        <TableCell>
                                          <span className="text-blue-400 font-medium text-sm">
                                            {formatCurrency(
                                              (item.recipe?.fulfillmentConsumables || []).reduce(
                                                (sum, consumable) => sum + consumable.price * item.quantity,
                                                0,
                                              ),
                                            )}
                                          </span>
                                        </TableCell>
                                        <TableCell>
                                          <span className="text-blue-400 font-medium text-sm">
                                            {formatCurrency(
                                              (item.recipe?.sellerConsumables || []).reduce(
                                                (sum, consumable) => sum + consumable.price * item.quantity,
                                                0,
                                              ),
                                            )}
                                          </span>
                                        </TableCell>
                                        <TableCell>
                                          <span className="text-white/60 text-sm">-</span>
                                        </TableCell>
                                        <TableCell>
                                          <span className="text-white font-semibold text-sm">
                                            {formatCurrency(
                                              item.totalPrice +
                                                (item.recipe?.services || []).reduce(
                                                  (sum, service) => sum + service.price * item.quantity,
                                                  0,
                                                ) +
                                                (item.recipe?.fulfillmentConsumables || []).reduce(
                                                  (sum, consumable) => sum + consumable.price * item.quantity,
                                                  0,
                                                ) +
                                                (item.recipe?.sellerConsumables || []).reduce(
                                                  (sum, consumable) => sum + consumable.price * item.quantity,
                                                  0,
                                                ),
                                            )}
                                          </span>
                                        </TableCell>
                                        <TableCell>
                                          <span className="text-xs px-2 py-1 bg-gray-500/20 text-gray-300 border border-gray-500/30 rounded">
                                            {item.recipe?.services?.length ||
                                            item.recipe?.fulfillmentConsumables?.length ||
                                            item.recipe?.sellerConsumables?.length
                                              ? 'Хорошо'
                                              : 'Без рецептуры'}
                                          </span>
                                        </TableCell>
                                        <TableCell></TableCell>
                                      </TableRow>

                                      {/* УРОВЕНЬ 5: Услуги фулфилмента */}
                                      {isProductExpanded &&
                                        item.recipe?.services &&
                                        item.recipe.services.length > 0 &&
                                        item.recipe.services.map((service, serviceIndex) => (
                                          <TableRow
                                            key={`${item.id}-service-${serviceIndex}`}
                                            className="border-white/10"
                                            style={{ backgroundColor: getLevelBackgroundColor(5, index) }}
                                          >
                                            <TableCell className="relative">
                                              <div className="flex items-center space-x-2">
                                                <div className="w-1 h-1 rounded-full bg-pink-400 mr-1"></div>
                                                <div className="w-1 h-1 rounded-full bg-pink-400 mr-1"></div>
                                                <div className="w-1 h-1 rounded-full bg-pink-400 mr-1"></div>
                                                <div className="w-1 h-1 rounded-full bg-pink-400 mr-1"></div>
                                                <Settings className="h-3 w-3 text-pink-400" />
                                                <span className="text-white/80 font-medium text-sm ml-2">Услуги</span>
                                              </div>
                                              <div
                                                className="absolute left-0 top-0 w-0.5 h-full"
                                                style={{ backgroundColor: getSupplyColor(index) }}
                                              ></div>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell className="hidden lg:table-cell">
                                              <span className="text-blue-400 font-medium text-sm">
                                                {service.name} ({formatCurrency(service.price)})
                                              </span>
                                            </TableCell>
                                            <TableCell className="hidden lg:table-cell">
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell className="hidden lg:table-cell">
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell className="hidden lg:table-cell">
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                          </TableRow>
                                        ))}

                                      {/* УРОВЕНЬ 5: Расходники фулфилмента */}
                                      {isProductExpanded &&
                                        item.recipe?.fulfillmentConsumables &&
                                        item.recipe.fulfillmentConsumables.length > 0 &&
                                        item.recipe.fulfillmentConsumables.map((consumable, consumableIndex) => (
                                          <TableRow
                                            key={`${item.id}-ff-consumable-${consumableIndex}`}
                                            className="border-white/10"
                                            style={{ backgroundColor: getLevelBackgroundColor(5, index) }}
                                          >
                                            <TableCell className="relative">
                                              <div className="flex items-center space-x-2">
                                                <div className="w-1 h-1 rounded-full bg-pink-400 mr-1"></div>
                                                <div className="w-1 h-1 rounded-full bg-pink-400 mr-1"></div>
                                                <div className="w-1 h-1 rounded-full bg-pink-400 mr-1"></div>
                                                <div className="w-1 h-1 rounded-full bg-pink-400 mr-1"></div>
                                                <Settings className="h-3 w-3 text-pink-400" />
                                                <span className="text-white/80 font-medium text-sm ml-2">Услуги</span>
                                              </div>
                                              <div
                                                className="absolute left-0 top-0 w-0.5 h-full"
                                                style={{ backgroundColor: getSupplyColor(index) }}
                                              ></div>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell className="hidden lg:table-cell">
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell className="hidden lg:table-cell">
                                              <span className="text-blue-400 font-medium text-sm">
                                                {consumable.name} ({formatCurrency(consumable.price)})
                                              </span>
                                            </TableCell>
                                            <TableCell className="hidden lg:table-cell">
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell className="hidden lg:table-cell">
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                          </TableRow>
                                        ))}

                                      {/* УРОВЕНЬ 5: Расходники селлера */}
                                      {isProductExpanded &&
                                        item.recipe?.sellerConsumables &&
                                        item.recipe.sellerConsumables.length > 0 &&
                                        item.recipe.sellerConsumables.map((consumable, consumableIndex) => (
                                          <TableRow
                                            key={`${item.id}-seller-consumable-${consumableIndex}`}
                                            className="border-white/10"
                                            style={{ backgroundColor: getLevelBackgroundColor(5, index) }}
                                          >
                                            <TableCell className="relative">
                                              <div className="flex items-center space-x-2">
                                                <div className="w-1 h-1 rounded-full bg-pink-400 mr-1"></div>
                                                <div className="w-1 h-1 rounded-full bg-pink-400 mr-1"></div>
                                                <div className="w-1 h-1 rounded-full bg-pink-400 mr-1"></div>
                                                <div className="w-1 h-1 rounded-full bg-pink-400 mr-1"></div>
                                                <Settings className="h-3 w-3 text-pink-400" />
                                                <span className="text-white/80 font-medium text-sm ml-2">Услуги</span>
                                              </div>
                                              <div
                                                className="absolute left-0 top-0 w-0.5 h-full"
                                                style={{ backgroundColor: getSupplyColor(index) }}
                                              ></div>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell className="hidden lg:table-cell">
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell className="hidden lg:table-cell">
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell className="hidden lg:table-cell">
                                              <span className="text-blue-400 font-medium text-sm">
                                                {consumable.name} ({formatCurrency(consumable.price)})
                                              </span>
                                            </TableCell>
                                            <TableCell className="hidden lg:table-cell">
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                            <TableCell>
                                              <span className="text-white/60 text-sm">-</span>
                                            </TableCell>
                                          </TableRow>
                                        ))}

                                      {/* ОТКАТ: Старый вариант с желтыми элементами и colSpan блоком
                                {/* УРОВЕНЬ 5: Рецептура - КОМПАКТНАЯ СТРУКТУРА */}
                                      {/*isProductExpanded && (item.recipe?.services?.length || item.recipe?.fulfillmentConsumables?.length || item.recipe?.sellerConsumables?.length) && (
                                  <TableRow className="border-white/10" style={{ backgroundColor: getLevelBackgroundColor(5, index) }}>
                                    <TableCell colSpan={11} className="p-2">
                                      <div className="border-l-2 border-yellow-500 pl-4 ml-6 py-1">
                                        <div className="flex items-center gap-2">
                                          <div className="w-1.5 h-1.5 rounded-full bg-yellow-500"></div>
                                          <DollarSign className="h-3 w-3 text-yellow-400" />
                                          <div className="text-yellow-100 text-xs font-medium">Рецептура:</div>
                                        </div>
                                      </div>
                                    </TableCell>
                                  </TableRow>
                                )*/}

                                      {/*isProductExpanded && (item.recipe?.services?.length || item.recipe?.fulfillmentConsumables?.length || item.recipe?.sellerConsumables?.length) && (
                                  <TableRow className="border-white/10" style={{ backgroundColor: getLevelBackgroundColor(5, index) }}>
                                    <TableCell colSpan={11} className="p-2">
                                      <div className="ml-8 space-y-1 text-xs text-white/70">
                                        {item.recipe?.services && item.recipe.services.length > 0 && (
                                          <div>
                                            <span className="font-medium">Услуги:</span>{' '}
                                            <span className="text-white/60">
                                              {item.recipe.services.map(service => `${service.name} (${formatCurrency(service.price)})`).join(', ')}
                                            </span>
                                          </div>
                                        )}
                                        {item.recipe?.fulfillmentConsumables && item.recipe.fulfillmentConsumables.length > 0 && (
                                          <div>
                                            <span className="font-medium">Расходники ФФ:</span>{' '}
                                            <span className="text-white/60">
                                              {item.recipe.fulfillmentConsumables.map(consumable => `${consumable.name} (${formatCurrency(consumable.price)})`).join(', ')}
                                            </span>
                                          </div>
                                        )}
                                        {item.recipe?.sellerConsumables && item.recipe.sellerConsumables.length > 0 && (
                                          <div>
                                            <span className="font-medium">Расходники селлера:</span>{' '}
                                            <span className="text-white/60">
                                              {item.recipe.sellerConsumables.map(consumable => `${consumable.name} (${formatCurrency(consumable.price)})`).join(', ')}
                                            </span>
                                          </div>
                                        )}
                                      </div>
                                    </TableCell>
                                  </TableRow>
                                )*/}

                                      {/* Размеры товара (если есть) */}
                                      {isProductExpanded &&
                                        item.product.sizes &&
                                        item.product.sizes.length > 0 &&
                                        item.product.sizes.map((size) => (
                                          <TableRow key={size.id} className="border-white/10">
                                            <TableCell className="pl-20">
                                              <Clock className="h-3 w-3 text-cyan-400" />
                                            </TableCell>
                                            <TableCell className="text-white/60 text-sm">Размер: {size.name}</TableCell>
                                            <TableCell className="text-white/70 font-mono">{size.quantity}</TableCell>
                                            <TableCell
                                              className="text-white/60 font-mono"
                                              colSpan={userRole === 'WHOLESALE' ? 2 : 7}
                                            >
                                              {size.price ? formatCurrency(size.price) : '-'}
                                            </TableCell>
                                            <TableCell></TableCell>
                                          </TableRow>
                                        ))}
                                    </React.Fragment>
                                  )
                                })}
                            </React.Fragment>
                          )
                        })
                      })()}

                    {/* УРОВЕНЬ 3: Поставщик для WHOLESALE (без маршрутов) - СКРЫТ */}
                    {false && isSupplyExpanded && userRole === 'WHOLESALE' && (
                      <TableRow
                        className="border-white/10 hover:bg-white/5 cursor-pointer transition-colors"
                        style={{ backgroundColor: getLevelBackgroundColor(3, index) }}
                        onClick={() => toggleSupplierExpansion(supply.partner.id)}
                      >
                        <TableCell className="relative">
                          <div className="flex items-center space-x-2">
                            <div className="w-1 h-1 rounded-full bg-green-400 mr-1"></div>
                            <Building2 className="h-3 w-3 text-green-400" />
                            <span className="text-white font-medium text-sm">Поставщик</span>
                          </div>
                          <div
                            className="absolute left-0 top-0 w-0.5 h-full"
                            style={{ backgroundColor: getSupplyColor(index) }}
                          ></div>
                        </TableCell>
                        <TableCell>
                          <div className="flex flex-col">
                            <span className="text-white text-sm font-medium">
                              {supply.partner.name || supply.partner.fullName}
                            </span>
                            {supply.partner.users &&
                              supply.partner.users.length > 0 &&
                              supply.partner.users[0].managerName && (
                                <span className="text-white/60 text-xs">
                                  {supply.partner.users[0].managerName}
                                </span>
                              )}
                            {supply.partner.phones &&
                              Array.isArray(supply.partner.phones) &&
                              supply.partner.phones.length > 0 && (
                                <span className="text-white/60 text-[10px]">
                                  {typeof supply.partner.phones[0] === 'string'
                                    ? supply.partner.phones[0]
                                    : supply.partner.phones[0]?.value || supply.partner.phones[0]?.phone}
                                </span>
                              )}
                          </div>
                        </TableCell>
                        <TableCell>
                          <span className="text-white/80 text-sm">{aggregatedData.orderedTotal}</span>
                        </TableCell>
                        {/* 🔒 БЕЗОПАСНОСТЬ: WHOLESALE не видит колонки "Поставлено" и "Брак" на supplier level */}
                        {userRole !== 'WHOLESALE' && (
                          <>
                            <TableCell>
                              <span className="text-white/80 text-sm">{aggregatedData.deliveredTotal}</span>
                            </TableCell>
                            <TableCell>
                              <span className="text-white/80 text-sm">{aggregatedData.defectTotal}</span>
                            </TableCell>
                          </>
                        )}
                        <TableCell>
                          <span className="text-green-400 font-medium text-sm">
                            {formatCurrency(aggregatedData.goodsPrice)}
                          </span>
                        </TableCell>
                        <TableCell></TableCell>
                      </TableRow>
                    )}

                    {/* УРОВЕНЬ 4: Товары для WHOLESALE (без маршрутов) */}
                    {isSupplyExpanded && 
                     userRole === 'WHOLESALE' &&
                     (supply.items || []).map((item) => {
                       const isProductExpanded = expandedProducts.has(item.id)

                       return (
                         <React.Fragment key={item.id}>
                           <TableRow
                             className="border-white/10 hover:bg-white/5 cursor-pointer transition-colors"
                             style={{ backgroundColor: getLevelBackgroundColor(4, index) }}
                             onClick={() => toggleProductExpansion(item.id)}
                           >
                             <TableCell className="relative">
                               <div
                                 className="absolute left-0 top-0 w-0.5 h-full"
                                 style={{ backgroundColor: getSupplyColor(index) }}
                               ></div>
                             </TableCell>
                             <TableCell>
                               <div className="flex flex-col">
                                 <span className="text-white text-sm font-medium">{item.product.name}</span>
                                 <span className="text-white/60 text-[9px]">
                                   Арт: {item.product.article || 'SF-T-925635-494'}
                                   {item.product.category && ` · ${item.product.category.name}`}
                                 </span>
                               </div>
                             </TableCell>
                             <TableCell>
                               <span className="text-white font-semibold text-sm">{item.quantity}</span>
                             </TableCell>
                             {/* 🔒 БЕЗОПАСНОСТЬ: WHOLESALE не видит колонки "Поставлено" и "Брак" на product level */}
                             {userRole !== 'WHOLESALE' && (
                               <>
                                 <TableCell>
                                   <span className="text-white/80 text-sm">0</span>
                                 </TableCell>
                                 <TableCell>
                                   <span className="text-white/80 text-sm">0</span>
                                 </TableCell>
                               </>
                             )}
                             <TableCell>
                               <div className="text-white">
                                 <div className="font-medium text-sm">{formatCurrency(item.totalPrice)}</div>
                                 <div className="text-xs text-white/60 hidden sm:block">
                                   {formatCurrency(item.price)} за шт.
                                 </div>
                               </div>
                             </TableCell>
                             <TableCell>&nbsp;</TableCell>
                             <TableCell>&nbsp;</TableCell>
                           </TableRow>
                         </React.Fragment>
                       )
                     })}

                    {/* ВАРИАНТ 1: Разделитель в виде пустой строки с border */}
                    <tr>
                      {/* 🔒 БЕЗОПАСНОСТЬ: colSpan учитывает скрытые колонки для WHOLESALE + новые колонки объём/грузовые места */}
                      <td
                        colSpan={userRole === 'WHOLESALE' ? 7 : 9}
                        style={{ padding: 0, borderBottom: '1px solid rgba(255, 255, 255, 0.2)' }}
                      ></td>
                    </tr>

                    {/* ОТКАТ: Без разделителя
                    {/* */}
                  </React.Fragment>
                )
              })}
          </TableBody>
        </Table>
      </div>

      {/* Контекстное меню вынесено ЗА ПРЕДЕЛЫ контейнера таблицы */}
      <ContextMenu
        isOpen={contextMenu.isOpen}
        position={contextMenu.position}
        onClose={handleCloseContextMenu}
        onCancel={handleCancelFromContextMenu}
      />

      <CancelConfirmDialog
        isOpen={cancelDialogOpen}
        onClose={() => setCancelDialogOpen(false)}
        onConfirm={handleConfirmCancel}
        supplyId={contextMenu.supplyId}
      />
    </>
  )
}
