"use client"

import React, { useMemo, useCallback, useState, useEffect, useRef } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { cn } from '../../lib/utils'
import { Search, Filter, Download, SortAsc, SortDesc, BarChart3, Cpu, Clock, Zap } from 'lucide-react'

// Memory konfigürasyonu için tip tanımları  
interface MemoryConfig {
  chunkSize?: number
  maxMemoryItems?: number
  cacheStrategy?: 'lru' | 'fifo' | 'lfu'
  compression?: boolean
  autoCleanup?: boolean
  cleanupThreshold?: number
  streamingMode?: boolean
  enableAnalytics?: boolean
  analyticsCallback?: (stats: MemoryStats) => void
  // Yeni özellikler
  variableHeight?: boolean
  preloadStrategy?: 'none' | 'aggressive' | 'smart'
  performanceTracking?: boolean
  enableSearch?: boolean
  enableSort?: boolean
  enableFilter?: boolean
  enableExport?: boolean
  animations?: boolean
}

// Performance metrikleri için tip tanımı
interface MemoryPerformanceMetrics {
  fps: number
  renderTime: number
  memoryLeaks: number
  scrollPerformance: number
  lastUpdate: number
}

// Search/Sort/Filter için tip tanımları
interface TableFeatures<T> {
  searchTerm?: string
  sortConfig?: {
    key: keyof T
    direction: 'asc' | 'desc'
  }
  filters?: Array<{
    key: keyof T
    value: any
    operator: 'equals' | 'contains' | 'greaterThan' | 'lessThan'
  }>
}

// Height measurement için tip tanımı
interface ItemHeightInfo {
  index: number
  height: number
  offset: number
}

// Memory istatistikleri için tip tanımı
interface MemoryStats {
  memoryUsage: number
  itemCount: number
  cacheHitRate: number
  compressionRatio?: number
  lastCleanup?: number
  performance?: MemoryPerformanceMetrics
}

// Ana component props
export interface MemoryEfficientDataProps<T = any> {
  data: T[]
  config?: MemoryConfig
  renderItem: (item: T, index: number) => React.ReactNode
  height?: number
  onMemoryUpdate?: (stats: MemoryStats) => void
  className?: string
  // Yeni özellikler
  itemHeight?: number | ((item: T, index: number) => number)
  onSearch?: (searchTerm: string) => T[]
  onSort?: (data: T[], key: keyof T, direction: 'asc' | 'desc') => T[]
  onFilter?: (data: T[], filters: TableFeatures<T>['filters']) => T[]
  onExport?: (data: T[], format: 'csv' | 'json' | 'xlsx') => void
  searchPlaceholder?: string
  emptyStateMessage?: string
  loadingComponent?: React.ReactNode
  errorComponent?: React.ReactNode
}

// Cache node yapısı
interface CacheNode<T> {
  data: T[]
  timestamp: number
  accessCount: number
  compressed?: boolean
}

// Memory cache sınıfı
class MemoryCache<T> {
  private cache = new Map<string, CacheNode<T>>()
  private maxSize: number
  private strategy: 'lru' | 'fifo' | 'lfu'

  constructor(maxSize: number, strategy: 'lru' | 'fifo' | 'lfu' = 'lru') {
    this.maxSize = maxSize
    this.strategy = strategy
  }

  set(key: string, data: T[], compressed = false): void {
    if (this.cache.size >= this.maxSize) {
      this.evict()
    }

    this.cache.set(key, {
      data,
      timestamp: Date.now(),
      accessCount: 0,
      compressed
    })
  }


  private evict(): void {
    if (this.cache.size === 0) return

    let keyToDelete: string | null = null

    switch (this.strategy) {
      case 'lru':
        // En eski erişileni sil
        let oldestTime = Infinity
        for (const [key, node] of this.cache) {
          if (node.timestamp < oldestTime) {
            oldestTime = node.timestamp
            keyToDelete = key
          }
        }
        break

      case 'lfu':
        // En az kullanılanı sil
        let minAccess = Infinity
        for (const [key, node] of this.cache) {
          if (node.accessCount < minAccess) {
            minAccess = node.accessCount
            keyToDelete = key
          }
        }
        break

      case 'fifo':
        // İlk gireni sil
        keyToDelete = this.cache.keys().next().value || null
        break
    }

    if (keyToDelete) {
      this.cache.delete(keyToDelete)
    }
  }

  clear(): void {
    this.cache.clear()
  }

  getStats(): { size: number; hitRate: number; memoryUsage: number } {
    let totalMemory = 0
    for (const [, node] of this.cache) {
      totalMemory += JSON.stringify(node.data).length * 2 // Rough memory calculation
    }
    
    return {
      size: this.cache.size,
      hitRate: this.calculateHitRate(),
      memoryUsage: totalMemory
    }
  }

  private hitCount = 0
  private missCount = 0

  private calculateHitRate(): number {
    const total = this.hitCount + this.missCount
    return total === 0 ? 0 : this.hitCount / total
  }

  // Hit/miss tracking için güncelle
  get(key: string): T[] | null {
    const node = this.cache.get(key)
    if (!node) {
      this.missCount++
      return null
    }

    this.hitCount++
    node.accessCount++
    node.timestamp = Date.now()
    return node.data
  }
}

// Performance Tracker sınıfı
class PerformanceTracker {
  private frames: number[] = []
  private renderTimes: number[] = []
  private startTime = 0
  private lastFrameTime = 0

  startRender(): void {
    this.startTime = performance.now()
  }

  endRender(): void {
    const renderTime = performance.now() - this.startTime
    this.renderTimes.push(renderTime)
    
    // Son 60 render time'ı tut
    if (this.renderTimes.length > 60) {
      this.renderTimes.shift()
    }
  }

  recordFrame(): void {
    const now = performance.now()
    if (this.lastFrameTime > 0) {
      const fps = 1000 / (now - this.lastFrameTime)
      this.frames.push(fps)
      
      // Son 60 frame'i tut
      if (this.frames.length > 60) {
        this.frames.shift()
      }
    }
    this.lastFrameTime = now
  }

  getMetrics(): MemoryPerformanceMetrics {
    const avgFPS = this.frames.length > 0 
      ? this.frames.reduce((a, b) => a + b, 0) / this.frames.length 
      : 0

    const avgRenderTime = this.renderTimes.length > 0
      ? this.renderTimes.reduce((a, b) => a + b, 0) / this.renderTimes.length
      : 0

    return {
      fps: Math.round(avgFPS),
      renderTime: Math.round(avgRenderTime * 100) / 100,
      memoryLeaks: this.detectMemoryLeaks(),
      scrollPerformance: this.calculateScrollPerformance(),
      lastUpdate: Date.now()
    }
  }

  private detectMemoryLeaks(): number {
    // Basit memory leak detection
    return this.renderTimes.filter(time => time > 16).length // 16ms = 60fps threshold
  }

  private calculateScrollPerformance(): number {
    // Scroll performance hesaplama (0-100 score)
    const avgFPS = this.frames.length > 0 
      ? this.frames.reduce((a, b) => a + b, 0) / this.frames.length 
      : 60

    return Math.min(100, Math.max(0, (avgFPS / 60) * 100))
  }
}

// Variable Height Manager sınıfı
class VariableHeightManager {
  private heights = new Map<number, number>()
  private defaultHeight: number
  private totalHeight = 0
  private measuredCount = 0

  constructor(defaultHeight = 60) {
    this.defaultHeight = defaultHeight
  }

  setItemHeight(index: number, height: number): void {
    const oldHeight = this.heights.get(index) || this.defaultHeight
    this.heights.set(index, height)
    
    if (!this.heights.has(index)) {
      this.measuredCount++
    }
    
    this.totalHeight += height - oldHeight
  }

  getItemHeight(index: number): number {
    return this.heights.get(index) || this.defaultHeight
  }

  getOffsetForIndex(index: number): number {
    let offset = 0
    for (let i = 0; i < index; i++) {
      offset += this.getItemHeight(i)
    }
    return offset
  }

  getTotalHeight(itemCount: number): number {
    if (this.measuredCount === 0) {
      return itemCount * this.defaultHeight
    }
    
    const measuredHeight = Array.from(this.heights.values())
      .reduce((sum, height) => sum + height, 0)
    const averageHeight = measuredHeight / this.measuredCount
    const unmeasuredCount = itemCount - this.measuredCount
    
    return measuredHeight + (unmeasuredCount * averageHeight)
  }

  getVisibleRange(scrollTop: number, containerHeight: number, itemCount: number): { start: number; end: number } {
    let start = 0
    let currentOffset = 0
    
    // Scroll position'a kadar olan itemları say
    while (start < itemCount && currentOffset < scrollTop) {
      currentOffset += this.getItemHeight(start)
      start++
    }
    
    start = Math.max(0, start - 1)
    
    // Görünür alan boyunca devam et
    let end = start
    const targetOffset = scrollTop + containerHeight
    currentOffset = this.getOffsetForIndex(start)
    
    while (end < itemCount && currentOffset < targetOffset) {
      currentOffset += this.getItemHeight(end)
      end++
    }
    
    return { start, end: Math.min(itemCount, end + 1) }
  }
}

// Ana Memory Efficient Data Component
export function MemoryEfficientData<T = any>({
  data,
  config = {},
  renderItem,
  height = 400,
  onMemoryUpdate,
  className,
  // Yeni props
  itemHeight = 60,
  onSearch,
  onSort,
  onFilter,
  onExport,
  searchPlaceholder = "Ara...",
  emptyStateMessage = "Veri bulunamadı",
  loadingComponent,
  errorComponent
}: MemoryEfficientDataProps<T>) {
  const {
    chunkSize = 1000,
    maxMemoryItems = 10000,
    cacheStrategy = 'lru',
    compression = false,
    autoCleanup = true,
    cleanupThreshold = 0.8,
    streamingMode = false,
    enableAnalytics = false,
    analyticsCallback,
    // Yeni konfigürasyonlar
    variableHeight = false,
    preloadStrategy = 'smart',
    performanceTracking = false,
    enableSearch = false,
    enableSort = false,
    enableFilter = false,
    enableExport = false,
    animations = true
  } = config

  // State yönetimi
  const [visibleRange, setVisibleRange] = useState({ start: 0, end: Math.min(chunkSize, data.length) })
  const [memoryStats, setMemoryStats] = useState<MemoryStats>({
    memoryUsage: 0,
    itemCount: 0,
    cacheHitRate: 0.95
  })
  const [tableFeatures, setTableFeatures] = useState<TableFeatures<T>>({
    searchTerm: '',
    sortConfig: undefined,
    filters: []
  })
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Refs
  const containerRef = useRef<HTMLDivElement>(null)
  const cacheRef = useRef(new MemoryCache<T>(Math.floor(maxMemoryItems / chunkSize), cacheStrategy))
  const scrollTimeoutRef = useRef<NodeJS.Timeout | undefined>(undefined)
  const performanceTrackerRef = useRef(new PerformanceTracker())
  const heightManagerRef = useRef(new VariableHeightManager(typeof itemHeight === 'number' ? itemHeight : 60))
  const itemRefs = useRef<Map<number, HTMLDivElement>>(new Map())

  // İşlenmiş data'yı hesapla (search, sort, filter)
  const processedData = useMemo(() => {
    let result = [...data]
    
    try {
      setIsLoading(true)
      
      // Search functionality
      if (enableSearch && tableFeatures.searchTerm && onSearch) {
        result = onSearch(tableFeatures.searchTerm)
      }
      
      // Filter functionality
      if (enableFilter && tableFeatures.filters && tableFeatures.filters.length > 0 && onFilter) {
        result = onFilter(result, tableFeatures.filters)
      }
      
      // Sort functionality
      if (enableSort && tableFeatures.sortConfig && onSort) {
        result = onSort(result, tableFeatures.sortConfig.key, tableFeatures.sortConfig.direction)
      }
      
      setError(null)
      return result
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Veri işlenirken hata oluştu')
      return data
    } finally {
      setIsLoading(false)
    }
  }, [data, tableFeatures, enableSearch, enableFilter, enableSort, onSearch, onFilter, onSort])

  // Visible data'yı memoize et
  const visibleData = useMemo(() => {
    if (performanceTracking) {
      performanceTrackerRef.current.startRender()
    }
    
    const start = visibleRange.start
    const end = Math.min(visibleRange.end, processedData.length)
    
    // Cache'den kontrol et
    const cacheKey = `${start}-${end}-${JSON.stringify(tableFeatures)}`
    const cachedData = cacheRef.current.get(cacheKey)
    
    if (cachedData && cachedData.length === (end - start)) {
      if (performanceTracking) {
        performanceTrackerRef.current.endRender()
      }
      return cachedData
    }

    // Yeni data slice'ını oluştur
    const newData = processedData.slice(start, end)
    
    // Cache'e kaydet
    cacheRef.current.set(cacheKey, newData, compression)
    
    if (performanceTracking) {
      performanceTrackerRef.current.endRender()
    }
    
    return newData
  }, [processedData, visibleRange, compression, tableFeatures, performanceTracking])

  // Item height measurement
  const measureItemHeight = useCallback((index: number, element: HTMLDivElement) => {
    if (!variableHeight) return
    
    const height = element.getBoundingClientRect().height
    heightManagerRef.current.setItemHeight(index, height)
    
    // Force re-render if height changed significantly
    const oldHeight = heightManagerRef.current.getItemHeight(index)
    if (Math.abs(height - oldHeight) > 5) {
      // Recalculate visible range
      const container = containerRef.current
      if (container) {
        handleScroll({ currentTarget: container } as React.UIEvent<HTMLDivElement>)
      }
    }
  }, [variableHeight])

  // Scroll handler
  const handleScroll = useCallback((e: React.UIEvent<HTMLDivElement>) => {
    if (performanceTracking) {
      performanceTrackerRef.current.recordFrame()
    }
    
    const scrollTop = e.currentTarget.scrollTop
    const containerHeight = e.currentTarget.clientHeight
    
    let newStart: number, newEnd: number
    
    if (variableHeight) {
      // Variable height kullan
      const range = heightManagerRef.current.getVisibleRange(scrollTop, containerHeight, processedData.length)
      newStart = range.start
      newEnd = range.end
    } else {
      // Fixed height kullan
      const itemHeightValue = typeof itemHeight === 'number' ? itemHeight : 60
      const startIndex = Math.floor(scrollTop / itemHeightValue)
      const visibleCount = Math.ceil(containerHeight / itemHeightValue)
      
      // Buffer ekle
      const bufferSize = Math.floor(visibleCount * 0.5)
      newStart = Math.max(0, startIndex - bufferSize)
      newEnd = Math.min(processedData.length, startIndex + visibleCount + bufferSize)
    }

    // Preloading strategy
    if (preloadStrategy === 'aggressive') {
      const extraBuffer = Math.floor((newEnd - newStart) * 0.5)
      newStart = Math.max(0, newStart - extraBuffer)
      newEnd = Math.min(processedData.length, newEnd + extraBuffer)
    } else if (preloadStrategy === 'smart') {
      // Scroll direction'a göre preload
      const currentScroll = scrollTop
      const lastScroll = scrollTimeoutRef.current ? parseInt(scrollTimeoutRef.current as any) : 0
      const isScrollingDown = currentScroll > lastScroll
      
      if (isScrollingDown) {
        newEnd = Math.min(processedData.length, newEnd + Math.floor((newEnd - newStart) * 0.2))
      } else {
        newStart = Math.max(0, newStart - Math.floor((newEnd - newStart) * 0.2))
      }
    }

    // Throttle scroll updates
    if (scrollTimeoutRef.current) {
      clearTimeout(scrollTimeoutRef.current)
    }

    scrollTimeoutRef.current = setTimeout(() => {
      setVisibleRange({ start: newStart, end: newEnd })
    }, 16) // ~60fps
  }, [processedData.length, variableHeight, itemHeight, preloadStrategy, performanceTracking])

  // Search handler
  const handleSearch = useCallback((searchTerm: string) => {
    setTableFeatures(prev => ({ ...prev, searchTerm }))
  }, [])

  // Sort handler
  const handleSort = useCallback((key: keyof T) => {
    setTableFeatures(prev => {
      const currentDirection = prev.sortConfig?.key === key && prev.sortConfig?.direction === 'asc' ? 'desc' : 'asc'
      return {
        ...prev,
        sortConfig: { key, direction: currentDirection }
      }
    })
  }, [])

  // Filter handler
  const handleFilter = useCallback((filters: TableFeatures<T>['filters']) => {
    setTableFeatures(prev => ({ ...prev, filters }))
  }, [])

  // Export handler
  const handleExport = useCallback((format: 'csv' | 'json' | 'xlsx') => {
    if (onExport) {
      onExport(processedData, format)
    }
  }, [processedData, onExport])

  // Memory statistics'i güncelle
  useEffect(() => {
    const cacheStats = cacheRef.current.getStats()
    const performanceMetrics = performanceTracking ? performanceTrackerRef.current.getMetrics() : undefined
    
    const newStats: MemoryStats = {
      memoryUsage: cacheStats.memoryUsage,
      itemCount: visibleData.length,
      cacheHitRate: cacheStats.hitRate,
      compressionRatio: compression ? 0.7 : 1.0,
      lastCleanup: Date.now(),
      performance: performanceMetrics
    }

    setMemoryStats(newStats)
    
    if (enableAnalytics && analyticsCallback) {
      analyticsCallback(newStats)
    }

    if (onMemoryUpdate) {
      onMemoryUpdate(newStats)
    }
  }, [visibleData, enableAnalytics, analyticsCallback, onMemoryUpdate, compression, performanceTracking])

  // Auto cleanup effect
  useEffect(() => {
    if (!autoCleanup) return

    const cleanupInterval = setInterval(() => {
      const memoryUsage = (visibleData.length / maxMemoryItems)
      if (memoryUsage > cleanupThreshold) {
        // Basit cleanup - cache'i temizle
        cacheRef.current.clear()
      }
    }, 5000) // Her 5 saniyede kontrol et

    return () => clearInterval(cleanupInterval)
  }, [autoCleanup, cleanupThreshold, maxMemoryItems, visibleData.length])

  // Loading ve Error states için render
  if (error && errorComponent) {
    return errorComponent
  }

  if (isLoading && loadingComponent) {
    return loadingComponent
  }

  // Total height hesapla
  const totalHeight = variableHeight 
    ? heightManagerRef.current.getTotalHeight(processedData.length)
    : processedData.length * (typeof itemHeight === 'number' ? itemHeight : 60)

  // Offset hesapla
  const offsetY = variableHeight
    ? heightManagerRef.current.getOffsetForIndex(visibleRange.start)
    : visibleRange.start * (typeof itemHeight === 'number' ? itemHeight : 60)

  return (
    <div className={cn("flex flex-col", className)}>
      {/* Control Bar */}
      {(enableSearch || enableSort || enableFilter || enableExport) && (
        <motion.div 
          className="flex items-center gap-2 p-3 border-b bg-muted/5"
          initial={animations ? { opacity: 0, y: -10 } : {}}
          animate={animations ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.2 }}
        >
          {enableSearch && (
            <div className="relative flex-1 max-w-sm">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <input
                type="text"
                placeholder={searchPlaceholder}
                value={tableFeatures.searchTerm}
                onChange={(e) => handleSearch(e.target.value)}
                className="w-full pl-10 pr-4 py-2 border rounded-md bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
              />
            </div>
          )}
          
          <div className="flex items-center gap-1">
            {enableFilter && (
              <button
                onClick={() => {/* Filter modal açılacak */}}
                className="p-2 hover:bg-muted rounded-md transition-colors"
                title="Filtrele"
              >
                <Filter className="h-4 w-4" />
              </button>
            )}
            
            {enableExport && (
              <div className="relative">
                <button
                  onClick={() => handleExport('csv')}
                  className="p-2 hover:bg-muted rounded-md transition-colors"
                  title="Dışa Aktar"
                >
                  <Download className="h-4 w-4" />
                </button>
              </div>
            )}
          </div>
        </motion.div>
      )}

      {/* Data Container */}
      <div
        ref={containerRef}
        className="overflow-auto border rounded-lg bg-background"
        style={{ height: typeof height === 'number' ? height - (enableSearch || enableSort || enableFilter || enableExport ? 60 : 0) : height }}
        onScroll={handleScroll}
      >
        {processedData.length === 0 ? (
          <motion.div 
            className="flex items-center justify-center h-full text-muted-foreground"
            initial={animations ? { opacity: 0 } : {}}
            animate={animations ? { opacity: 1 } : {}}
          >
            {emptyStateMessage}
          </motion.div>
        ) : (
          <div style={{ height: totalHeight, position: 'relative' }}>
            <motion.div 
              style={{ 
                transform: `translateY(${offsetY}px)`,
                position: 'absolute',
                width: '100%'
              }}
              animate={animations ? { y: offsetY } : {}}
              transition={animations ? { duration: 0.1, ease: "linear" } : {}}
            >
              <AnimatePresence mode="popLayout">
                {visibleData.map((item, index) => {
                  const globalIndex = visibleRange.start + index
                  const itemHeightValue = typeof itemHeight === 'function' 
                    ? itemHeight(item, globalIndex)
                    : (typeof itemHeight === 'number' ? itemHeight : 60)

                  return (
                    <motion.div
                      key={globalIndex}
                      ref={(el) => {
                        if (el && variableHeight) {
                          itemRefs.current.set(globalIndex, el)
                          measureItemHeight(globalIndex, el)
                        }
                      }}
                      style={variableHeight ? {} : { height: itemHeightValue }}
                      initial={animations ? { opacity: 0, y: 20 } : {}}
                      animate={animations ? { opacity: 1, y: 0 } : {}}
                      exit={animations ? { opacity: 0, y: -20 } : {}}
                      transition={animations ? { duration: 0.2 } : {}}
                      layout={animations}
                    >
                      {renderItem(item, globalIndex)}
                    </motion.div>
                  )
                })}
              </AnimatePresence>
            </motion.div>
          </div>
        )}
      </div>

      {/* Performance Monitor */}
      {performanceTracking && memoryStats.performance && (
        <div className="p-2 border-t bg-muted/5 text-xs text-muted-foreground flex items-center gap-4">
          <div className="flex items-center gap-1">
            <Zap className="h-3 w-3" />
            <span>FPS: {memoryStats.performance.fps}</span>
          </div>
          <div className="flex items-center gap-1">
            <Clock className="h-3 w-3" />
            <span>Render: {memoryStats.performance.renderTime}ms</span>
          </div>
          <div className="flex items-center gap-1">
            <Cpu className="h-3 w-3" />
            <span>Scroll: {memoryStats.performance.scrollPerformance}%</span>
          </div>
          <div className="flex items-center gap-1">
            <BarChart3 className="h-3 w-3" />
            <span>Cache: {Math.round(memoryStats.cacheHitRate * 100)}%</span>
          </div>
        </div>
      )}
    </div>
  )
}

// Real-time Performance Monitor Component
interface RealTimePerformanceMonitorProps {
  memoryStats?: MemoryStats
  className?: string
  showChart?: boolean
  updateInterval?: number
}

export function RealTimePerformanceMonitor({
  memoryStats,
  className,
  showChart = false,
  updateInterval = 1000
}: RealTimePerformanceMonitorProps) {
  const [history, setHistory] = useState<MemoryStats[]>([])
  const [isActive, setIsActive] = useState(true)

  useEffect(() => {
    if (!memoryStats || !isActive) return

    setHistory(prev => {
      const newHistory = [...prev, memoryStats]
      // Son 60 entry'yi tut (1 dakika)
      return newHistory.length > 60 ? newHistory.slice(-60) : newHistory
    })
  }, [memoryStats, isActive])

  const formatBytes = (bytes: number) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  const getPerformanceColor = (value: number, threshold: { good: number; warning: number }) => {
    if (value >= threshold.good) return 'text-green-500'
    if (value >= threshold.warning) return 'text-yellow-500'
    return 'text-red-500'
  }

  if (!memoryStats) {
    return (
      <div className={cn("p-4 border rounded-lg bg-muted/5", className)}>
        <div className="text-center text-muted-foreground">
          Performance monitoring devre dışı
        </div>
      </div>
    )
  }

  return (
    <motion.div 
      className={cn("p-4 border rounded-lg bg-background space-y-4", className)}
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
    >
      <div className="flex items-center justify-between">
        <h3 className="font-semibold flex items-center gap-2">
          <BarChart3 className="h-4 w-4" />
          Gerçek Zamanlı Performans
        </h3>
        <button
          onClick={() => setIsActive(!isActive)}
          className={cn(
            "px-3 py-1 text-xs rounded-md transition-colors",
            isActive 
              ? "bg-green-500/10 text-green-500 hover:bg-green-500/20" 
              : "bg-muted text-muted-foreground hover:bg-muted/80"
          )}
        >
          {isActive ? 'Aktif' : 'Durduruldu'}
        </button>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {/* FPS */}
        <div className="space-y-1">
          <div className="text-xs text-muted-foreground">FPS</div>
          <div className={cn(
            "text-lg font-mono font-bold",
            memoryStats.performance ? getPerformanceColor(memoryStats.performance.fps, { good: 55, warning: 30 }) : ''
          )}>
            {memoryStats.performance?.fps || 0}
          </div>
        </div>

        {/* Render Time */}
        <div className="space-y-1">
          <div className="text-xs text-muted-foreground">Render Süresi</div>
          <div className={cn(
            "text-lg font-mono font-bold",
            memoryStats.performance ? getPerformanceColor(100 - memoryStats.performance.renderTime, { good: 84, warning: 70 }) : ''
          )}>
            {memoryStats.performance?.renderTime.toFixed(2) || 0}ms
          </div>
        </div>

        {/* Memory Usage */}
        <div className="space-y-1">
          <div className="text-xs text-muted-foreground">Bellek Kullanımı</div>
          <div className="text-lg font-mono font-bold">
            {formatBytes(memoryStats.memoryUsage)}
          </div>
        </div>

        {/* Cache Hit Rate */}
        <div className="space-y-1">
          <div className="text-xs text-muted-foreground">Cache Hit Rate</div>
          <div className={cn(
            "text-lg font-mono font-bold",
            getPerformanceColor(memoryStats.cacheHitRate * 100, { good: 85, warning: 70 })
          )}>
            {Math.round(memoryStats.cacheHitRate * 100)}%
          </div>
        </div>
      </div>

      {/* Memory Leaks & Scroll Performance */}
      {memoryStats.performance && (
        <div className="grid grid-cols-2 gap-4 pt-2 border-t">
          <div className="space-y-1">
            <div className="text-xs text-muted-foreground">Memory Leaks</div>
            <div className={cn(
              "text-sm font-mono",
              memoryStats.performance.memoryLeaks > 5 ? 'text-red-500' : 'text-green-500'
            )}>
              {memoryStats.performance.memoryLeaks} detection
            </div>
          </div>
          <div className="space-y-1">
            <div className="text-xs text-muted-foreground">Scroll Performance</div>
            <div className={cn(
              "text-sm font-mono",
              getPerformanceColor(memoryStats.performance.scrollPerformance, { good: 85, warning: 70 })
            )}>
              {memoryStats.performance.scrollPerformance}%
            </div>
          </div>
        </div>
      )}

      {/* Mini Chart */}
      {showChart && history.length > 1 && (
        <div className="pt-2 border-t">
          <div className="text-xs text-muted-foreground mb-2">FPS Geçmişi (Son 60 güncelleme)</div>
          <div className="h-16 flex items-end gap-1">
            {history.slice(-30).map((stat, index) => {
              const fps = stat.performance?.fps || 0
              const height = Math.max(4, (fps / 60) * 100)
              const color = fps >= 55 ? 'bg-green-500' : fps >= 30 ? 'bg-yellow-500' : 'bg-red-500'
              
              return (
                <motion.div
                  key={index}
                  className={cn("w-1 rounded-t-sm", color)}
                  style={{ height: `${height}%` }}
                  initial={{ height: 0 }}
                  animate={{ height: `${height}%` }}
                  transition={{ duration: 0.2 }}
                />
              )
            })}
          </div>
        </div>
      )}
    </motion.div>
  )
}

// Memory Analytics Component (Backward compatibility)
interface MemoryAnalyticsProps {
  onStatsUpdate?: (stats: MemoryStats) => void
  showRealTime?: boolean
  className?: string
}

export function MemoryAnalytics({
  onStatsUpdate,
  showRealTime = false,
  className
}: MemoryAnalyticsProps) {
  const [stats, setStats] = useState<MemoryStats>({
    memoryUsage: 0,
    itemCount: 0,
    cacheHitRate: 0.95
  })

  // Mock real-time updates for backward compatibility
  useEffect(() => {
    if (!showRealTime) return

    const interval = setInterval(() => {
      const newStats: MemoryStats = {
        memoryUsage: Math.random() * 50 * 1024 * 1024,
        itemCount: Math.floor(Math.random() * 50000),
        cacheHitRate: 0.9 + Math.random() * 0.1,
        lastCleanup: Date.now(),
        performance: {
          fps: Math.floor(30 + Math.random() * 30),
          renderTime: Math.random() * 16,
          memoryLeaks: Math.floor(Math.random() * 3),
          scrollPerformance: 70 + Math.random() * 30,
          lastUpdate: Date.now()
        } as MemoryPerformanceMetrics
      }
      
      setStats(newStats)
      if (onStatsUpdate) {
        onStatsUpdate(newStats)
      }
    }, 1000)

    return () => clearInterval(interval)
  }, [showRealTime, onStatsUpdate])

  return <RealTimePerformanceMonitor memoryStats={stats} className={className} showChart={showRealTime} />
}

// Utility hook for streaming data
export function useStreamingData<T>(
  initialData: T[] = [],
  streamingConfig?: { interval?: number; maxItems?: number }
) {
  const [data, setData] = useState<T[]>(initialData)
  const { interval = 1000, maxItems = 10000 } = streamingConfig || {}

  const addItem = useCallback((newItem: T) => {
    setData(prev => {
      const newData = [...prev, newItem]
      return newData.length > maxItems ? newData.slice(-maxItems) : newData
    })
  }, [maxItems])

  const clearData = useCallback(() => {
    setData([])
  }, [])

  return { data, addItem, clearData }
}

// Export types
export type { 
  MemoryConfig, 
  MemoryStats, 
  MemoryAnalyticsProps, 
  MemoryPerformanceMetrics, 
  TableFeatures, 
  ItemHeightInfo,
  RealTimePerformanceMonitorProps
}