import { useQuery } from '@tanstack/react-query'
import { useEffect, useState, useRef } from 'react'
import { useSearchParams } from 'react-router-dom'
import { useBreadcrumb } from '../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../config/breadcrumbConfig'
import { Terminal, RefreshCw, Download, Filter, ChevronDown, Wifi, WifiOff, AlertTriangle, X, ScrollText } from 'lucide-react'
import { api } from '../lib/api'

export default function Logs() {
  useBreadcrumb(breadcrumbConfig['/logs'])
  const [searchParams, setSearchParams] = useSearchParams()
  // Default components to merge
  const defaultComponents = [
    'activitystatus',
    'appearances',
    'cachemanager',
    'celebritydiscover',
    'celebritynightly',
    'celebrityresolutionfetch',
    'coppermine',
    'dashboard',
    'database',
    'dateutils',
    'dependencyupdater',
    'discovery',
    'downloadermonitor',
    'downloadmanager',
    'duomanager',
    'easynewsclient',
    'easynewsmonitor',
    'embeddinggenerator',
    'facerecognition',
    'filesrouter',
    'forum',
    'forumadapter',
    'immichface',
    'instagram',
    'instagramclient',
    'mediaidentifier',
    'maintenance',
    'media_downloader',
    'movemanager',
    'notifier',
    'paidcontent',
    'passkeymanager',
    'perceptual_duplicate_detector',
    'plex',
    'podchaser',
    'privategallerycrypto',
    'redditmonitor',
    'scheduler',
    'semanticsearch',
    'servicehealthmonitor',
    'settingsmanager',
    'snapchatclient',
    'snapchatdirect',
    'taddy',
    'thumbnailcachebuilder',
    'tiktok',
    'tmdb',
    'totpmanager',
    'tvdb',
    'twofactorauth',
    'universalvideodownloader',
    'youtubemonitor',
    'cloudbackup',
    'cloudflare.fastdl',
    'cloudflare.imginn',
    'cloudflare.imginn-stories',
    'taskcheckpoint'
  ]

  // Fetch config for hidden modules
  const { data: logConfig } = useQuery({
    queryKey: ['config'],
    queryFn: () => api.getConfig(),
    staleTime: 30000,
  })
  const hiddenModules: string[] = Array.isArray(logConfig?.hidden_modules) ? logConfig.hidden_modules : []

  // Map log component names to module IDs
  const componentToModule: Record<string, string[]> = {
    'instagram': ['instagram', 'instagram_client'],
    'instagramclient': ['instagram_client'],
    'snapchatdirect': ['snapchat'],
    'snapchatclient': ['snapchat_client'],
    'tiktok': ['tiktok'],
    'forum': ['forums'],
    'forumadapter': ['forums'],
    'coppermine': ['coppermine'],
  }

  // Components to hide from the dropdown (test/debug logs + hidden modules)
  const hiddenComponents = [
    'test',
    'tests',
    'testing',
    'test_websocket',
    ...Object.entries(componentToModule)
      .filter(([_, modules]) => modules.every(m => hiddenModules.includes(m)))
      .map(([comp]) => comp),
  ]

  // URL parameters for filtering
  const urlFilter = searchParams.get('filter')
  const urlTime = searchParams.get('time')
  const urlLevel = searchParams.get('level')

  const [realTimeUpdates, setRealTimeUpdates] = useState(true)
  const [selectedComponents, setSelectedComponents] = useState<string[]>(defaultComponents)
  const [levelFilter, setLevelFilter] = useState<string[]>(() => {
    // If URL has level=error, only show errors
    if (urlLevel?.toLowerCase() === 'error') {
      return ['ERROR']
    }
    return ['ERROR', 'WARNING', 'INFO', 'SUCCESS']
  })
  const [showFilters, setShowFilters] = useState(false)
  const [showComponentSelector, setShowComponentSelector] = useState(false)
  const [highlightTimestamp, setHighlightTimestamp] = useState<string | null>(urlTime)
  const logsEndRef = useRef<HTMLDivElement>(null)
  const logsContainerRef = useRef<HTMLDivElement>(null)
  const componentSelectorRef = useRef<HTMLDivElement>(null)
  const highlightedLogRef = useRef<HTMLDivElement>(null)

  // Clear URL filter banner
  const clearUrlFilter = () => {
    setSearchParams({})
    setHighlightTimestamp(null)
    setLevelFilter(['ERROR', 'WARNING', 'INFO', 'SUCCESS'])
  }

  const { data: mergedLogs, refetch } = useQuery({
    queryKey: ['mergedLogs', selectedComponents, urlTime],
    queryFn: () => api.getMergedLogs(1000, selectedComponents, urlTime || undefined),
    enabled: selectedComponents.length > 0,
    refetchInterval: realTimeUpdates && !urlTime ? 2000 : false, // Poll every 2 seconds when enabled (but not when filtering by time)
  })


  // Scroll to highlighted log entry when timestamp is set
  useEffect(() => {
    if (highlightTimestamp && highlightedLogRef.current && logsContainerRef.current) {
      // Small delay to ensure DOM is updated
      setTimeout(() => {
        highlightedLogRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' })
      }, 300)
    }
  }, [highlightTimestamp, mergedLogs])

  // Track if we've scrolled to bottom on initial load
  const [hasScrolledToBottom, setHasScrolledToBottom] = useState(false)

  // Close component selector when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (componentSelectorRef.current && !componentSelectorRef.current.contains(event.target as Node)) {
        setShowComponentSelector(false)
      }
    }

    if (showComponentSelector) {
      document.addEventListener('mousedown', handleClickOutside)
      return () => document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [showComponentSelector])

  const allLogs = mergedLogs?.logs || []
  const availableComponents = mergedLogs?.available_components || []

  const parseLogEntry = (log: string) => {
    // Parse format: 2025-11-13 11:24:40.123456 [MediaDownloader.Component] [Module] [LEVEL] message
    // Also handles: 2025-11-13 11:24:40 [MediaDownloader.Component] [Module] [LEVEL] message (without microseconds)
    // Also handles: 2025-11-13 11:24:40 [MediaDownloader] [Module] [LEVEL] message
    const matchWithComponent = log.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d+)?) \[MediaDownloader\.([^\]]+)\] \[([^\]]+)\] \[([^\]]+)\] (.+)$/)
    if (matchWithComponent) {
      return {
        timestamp: matchWithComponent[1],
        component: matchWithComponent[2],
        module: matchWithComponent[3],
        level: matchWithComponent[4],
        message: matchWithComponent[5],
      }
    }

    // Try without component (just [MediaDownloader])
    const matchWithoutComponent = log.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d+)?) \[MediaDownloader\] \[([^\]]+)\] \[([^\]]+)\] (.+)$/)
    if (matchWithoutComponent) {
      return {
        timestamp: matchWithoutComponent[1],
        component: 'Core',
        module: matchWithoutComponent[2],
        level: matchWithoutComponent[3],
        message: matchWithoutComponent[4],
      }
    }

    return null
  }

  // Strip microseconds from log line for display (keeps sorting accurate in backend)
  const formatLogForDisplay = (log: string) => {
    // Replace timestamp with microseconds (2025-12-07 11:30:42.123456) with just seconds
    return log.replace(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\.\d+/, '$1')
  }

  const getLogLevel = (log: string) => {
    const parsed = parseLogEntry(log)
    if (parsed) return parsed.level.toLowerCase()

    if (log.includes('[ERROR]')) return 'error'
    if (log.includes('[WARNING]')) return 'warning'
    if (log.includes('[SUCCESS]')) return 'success'
    if (log.includes('[DEBUG]')) return 'debug'
    return 'info'
  }

  const getLogColor = (level: string) => {
    const colors = {
      error: 'text-red-500 dark:text-red-400 font-semibold',
      critical: 'text-red-600 dark:text-red-300 font-bold',
      warning: 'text-amber-500 dark:text-amber-300 font-medium',
      success: 'text-emerald-400 dark:text-emerald-300',
      debug: 'text-slate-400 dark:text-slate-500',
      info: 'text-blue-300 dark:text-blue-200',
    }
    return colors[level as keyof typeof colors] || colors.info
  }

  const getLevelBadgeColor = (level: string) => {
    const colors = {
      error: 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-300',
      critical: 'bg-red-200 dark:bg-red-900/50 text-red-900 dark:text-red-200',
      warning: 'bg-amber-100 dark:bg-amber-900/30 text-amber-800 dark:text-amber-300',
      success: 'bg-emerald-100 dark:bg-emerald-900/30 text-emerald-800 dark:text-emerald-300',
      debug: 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400',
      info: 'bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300',
    }
    return colors[level as keyof typeof colors] || colors.info
  }

  // Check if a log entry matches the URL filter (module/component name)
  const matchesUrlFilter = (log: string) => {
    if (!urlFilter) return true
    const lowerFilter = urlFilter.toLowerCase()
    const parsed = parseLogEntry(log)
    if (parsed) {
      return parsed.module.toLowerCase().includes(lowerFilter) ||
             parsed.component.toLowerCase().includes(lowerFilter)
    }
    // Fallback: check if filter appears in the log line
    return log.toLowerCase().includes(lowerFilter)
  }

  // Check if a log entry's timestamp is close to the URL time (within 2 minutes)
  const isNearTimestamp = (log: string) => {
    if (!highlightTimestamp) return false
    const parsed = parseLogEntry(log)
    if (!parsed) return false

    try {
      const logTime = new Date(parsed.timestamp.replace(' ', 'T'))
      const targetTime = new Date(highlightTimestamp)
      const diffMs = Math.abs(logTime.getTime() - targetTime.getTime())
      // Within 2 minutes (120000ms)
      return diffMs <= 120000
    } catch {
      return false
    }
  }

  const filteredLogs = allLogs.filter(log => {
    const level = getLogLevel(log).toUpperCase()
    // Apply level filter
    if (!levelFilter.includes(level)) return false
    // Apply URL module filter if present
    if (urlFilter && !matchesUrlFilter(log)) return false
    return true
  })

  // Scroll to bottom (most recent logs) on initial load
  useEffect(() => {
    // Only auto-scroll on initial load, not on every update
    // Don't scroll if there's a highlight timestamp (user came from error link)
    if (!hasScrolledToBottom && !highlightTimestamp && filteredLogs.length > 0 && logsEndRef.current) {
      setTimeout(() => {
        logsEndRef.current?.scrollIntoView({ behavior: 'auto' })
        setHasScrolledToBottom(true)
      }, 100)
    }
  }, [filteredLogs.length, hasScrolledToBottom, highlightTimestamp])

  const toggleLevelFilter = (level: string) => {
    setLevelFilter(prev =>
      prev.includes(level)
        ? prev.filter(l => l !== level)
        : [...prev, level]
    )
  }

  const toggleComponent = (component: string) => {
    setSelectedComponents(prev =>
      prev.includes(component)
        ? prev.filter(c => c !== component)
        : [...prev, component]
    )
  }

  const downloadLogs = () => {
    const blob = new Blob([filteredLogs.join('\n')], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    const componentName = selectedComponents.length > 0 ? selectedComponents.join('-') : 'merged'
    a.download = `media-downloader-${componentName}-${new Date().toISOString().split('T')[0]}.log`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  const getComponentDisplayName = (comp: string) => {
    const names: { [key: string]: string } = {
      // Core Services
      'api': 'API',
      'scheduler': 'Scheduler',
      'database': 'Database',
      'dashboard': 'Dashboard',
      'settingsmanager': 'Settings',
      'activitystatus': 'Activity Status',
      'cachemanager': 'Cache',
      'logcleanup': 'Log Cleanup',
      'maintenance': 'Maintenance',

      // Download Core
      'mediadownloader': 'Media Downloader',
      'media_downloader': 'Media Downloader',
      'downloader': 'Media Downloader',
      'movemanager': 'Move Manager',
      'thumbnailcachebuilder': 'Thumbnail Cache',
      'downloadmanager': 'Download Manager',
      'downloadermonitor': 'Download Monitor',
      'universalvideodownloader': 'Video Downloader',
      'filesrouter': 'File Manager',
      'mediaidentifier': 'Media Identifier',

      // Platform Downloaders
      'instagram': 'Instagram',
      'instagramclient': 'Instagram',
      'tiktok': 'TikTok',
      'snapchat': 'Snapchat (Legacy)',
      'snapchatclient': 'Snapchat',
      'snapchatdirect': 'Snapchat',
      'forum': 'Forums',
      'forumadapter': 'Forums',
      'coppermine': 'Coppermine',
      'youtubedownloader': 'YouTube',
      'youtubemonitor': 'YouTube Monitor',
      'easynewsclient': 'Easynews Client',
      'easynewsmonitor': 'Easynews Monitor',
      'redditmonitor': 'Reddit Monitor',

      // Face Recognition
      'facerecognition': 'Face Recognition',
      'immichface': 'Immich Faces',
      'perceptual_duplicate_detector': 'Duplicate Detector',

      // Internet Discovery
      'celebritydiscover': 'Discovery',
      'celebritynightly': 'Discovery Nightly',
      'celebrityresolutionfetch': 'Discovery Resolution',
      'celebritydatefetch': 'Discovery Dates',
      'celebrityenrichment': 'Discovery Enrichment',
      'discovery': 'Discovery',

      // Authentication
      'duomanager': 'Duo 2FA',
      'twofactorauth': '2FA',
      'passkeymanager': 'Passkeys',
      'totpmanager': 'TOTP',

      // Search & AI
      'semanticsearch': 'Semantic Search',
      'embeddinggenerator': 'Embeddings',
      'autotagger': 'Auto Tagger',

      // Appearances & Media APIs
      'appearances': 'Appearances',
      'tmdb': 'TMDb',
      'tvdb': 'TVDB',
      'imdb': 'IMDb',
      'paidcontent': 'Paid Content',
      'privategallerycrypto': 'Private Gallery Crypto',
      'podchaser': 'Podchaser',
      'taddy': 'Taddy',
      'plex': 'Plex',

      // Cloud & Backup
      'cloudbackup': 'Cloud Backup',
      'cloud backup': 'Cloud Backup',

      // Cloudflare
      'cloudflare.fastdl': 'Cloudflare (FastDL)',
      'cloudflare.imginn': 'Cloudflare (ImgInn)',
      'cloudflare.imginn-stories': 'Cloudflare (ImgInn Stories)',

      // Task System
      'taskcheckpoint': 'Task Checkpoint',

      // Utilities
      'notifier': 'Notifications',
      'servicehealthmonitor': 'Health Monitor',
      'dependencyupdater': 'Dependencies',
      'dateutils': 'Date Utils',
      'querybuilder': 'Query Builder',

      // Legacy
      'web-api': 'API (Legacy)',
      'web-frontend': 'Frontend (Legacy)',
      'service': 'Service (Legacy)',
    }

    // Clean up any remaining hyphens/underscores in unmapped names
    const displayName = names[comp.toLowerCase()]
    if (displayName) {
      return displayName
    }

    // Fallback: convert hyphens/underscores to spaces and capitalize
    return comp
      .replace(/[-_]/g, ' ')
      .split(' ')
      .map(word => word.charAt(0).toUpperCase() + word.slice(1))
      .join(' ')
  }

  return (
    <div className="space-y-4 md:space-y-6 pb-safe">
      {/* URL Filter Banner */}
      {(urlFilter || urlLevel) && (
        <div className="card-glass rounded-xl bg-gradient-to-r from-amber-500/10 to-orange-500/10 border border-amber-500/30 p-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <AlertTriangle className="w-5 h-5 text-amber-600 dark:text-amber-400" />
              <div>
                <h3 className="text-sm font-semibold text-amber-900 dark:text-amber-100">
                  Filtered View
                </h3>
                <p className="text-xs text-amber-700 dark:text-amber-300">
                  {urlFilter && `Showing logs from: ${urlFilter}`}
                  {urlFilter && urlLevel && ' • '}
                  {urlLevel && `Level: ${urlLevel.toUpperCase()}`}
                  {highlightTimestamp && ` • Around: ${new Date(highlightTimestamp).toLocaleString()}`}
                </p>
              </div>
            </div>
            <button
              onClick={clearUrlFilter}
              className="p-1.5 text-amber-600 dark:text-amber-400 hover:bg-amber-100 dark:hover:bg-amber-900/30 rounded-lg transition-colors"
              title="Clear filter"
            >
              <X className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}

      {/* Header - Mobile Optimized */}
      <div className="flex flex-col space-y-3 md:space-y-0 md:flex-row md:items-center md:justify-between">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
            <ScrollText className="w-8 h-8 text-slate-500" />
            System Logs
            {realTimeUpdates && (
              <span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300 rounded-full">
                <span className="live-dot"></span>
                Live
              </span>
            )}
          </h1>
          <p className="text-slate-600 dark:text-slate-400 mt-1">
            Monitor application activity{realTimeUpdates ? ' - Updates every 2 seconds' : ''}
          </p>
        </div>
        <div className="flex items-center space-x-2">
          {/* Component Selector */}
          {availableComponents && availableComponents.length > 0 && (
            <div className="relative" ref={componentSelectorRef}>
              <button
                onClick={() => setShowComponentSelector(!showComponentSelector)}
                className="px-3 md:px-4 py-2.5 md:py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors touch-manipulation flex items-center space-x-2"
              >
                <span>
                  {selectedComponents.length === 0
                    ? 'Select Components'
                    : `${selectedComponents.length} selected`}
                </span>
                <ChevronDown className={`w-4 h-4 transition-transform ${showComponentSelector ? 'rotate-180' : ''}`} />
              </button>

              {showComponentSelector && (
                <div className="absolute left-0 md:left-auto md:right-0 mt-2 w-64 bg-card border border-border rounded-xl shadow-lg z-10 max-h-96 overflow-y-auto">
                  <div className="p-3 border-b border-border">
                    <button
                      onClick={() => {
                        if (selectedComponents.length === availableComponents.length) {
                          setSelectedComponents([])
                        } else {
                          setSelectedComponents([...availableComponents])
                        }
                      }}
                      className="text-xs text-primary hover:underline"
                    >
                      {selectedComponents.length === availableComponents.length ? 'Deselect All' : 'Select All'}
                    </button>
                  </div>
                  <div className="p-2">
                    {availableComponents
                      .filter((comp) => !hiddenComponents.includes(comp.toLowerCase()))
                      .sort((a, b) => getComponentDisplayName(a).localeCompare(getComponentDisplayName(b)))
                      .map((comp) => (
                        <label
                          key={comp}
                          className="flex items-center space-x-2 px-2 py-2 hover:bg-secondary rounded-lg cursor-pointer touch-manipulation transition-colors"
                        >
                          <input
                            type="checkbox"
                            checked={selectedComponents.includes(comp)}
                            onChange={() => toggleComponent(comp)}
                            className="rounded border-border text-primary focus:ring-primary"
                          />
                          <span className="text-sm text-foreground">
                            {getComponentDisplayName(comp)}
                          </span>
                        </label>
                      ))}
                  </div>
                </div>
              )}
            </div>
          )}

          <button
            onClick={() => setRealTimeUpdates(!realTimeUpdates)}
            className={`p-2.5 md:px-4 md:py-2 border rounded-xl transition-colors touch-manipulation ${
              realTimeUpdates
                ? 'bg-green-600 border-green-600 text-white hover:bg-green-700'
                : 'bg-card border-border text-foreground hover:bg-secondary'
            }`}
            aria-label={realTimeUpdates ? 'Disable real-time updates' : 'Enable real-time updates'}
            title={realTimeUpdates ? 'Real-time updates ON' : 'Real-time updates OFF'}
          >
            {realTimeUpdates ? (
              <Wifi className="w-5 h-5 md:w-4 md:h-4" />
            ) : (
              <WifiOff className="w-5 h-5 md:w-4 md:h-4" />
            )}
          </button>
          <button
            onClick={() => refetch()}
            className="p-2.5 md:px-4 md:py-2 bg-card border border-border rounded-xl hover:bg-secondary transition-colors touch-manipulation"
            aria-label="Refresh logs"
          >
            <RefreshCw className="w-5 h-5 md:w-4 md:h-4" />
          </button>
          <button
            onClick={downloadLogs}
            className="p-2.5 md:px-4 md:py-2 bg-primary text-primary-foreground rounded-xl hover:bg-primary/90 transition-colors touch-manipulation btn-hover-lift"
            aria-label="Export logs"
          >
            <Download className="w-5 h-5 md:w-4 md:h-4" />
          </button>
        </div>
      </div>

      {/* Stats - Mobile Grid */}
      <div className="grid grid-cols-3 md:grid-cols-5 gap-2 md:gap-4">
        <div className="card-glass-hover rounded-xl p-3 md:p-4">
          <div className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-1">Total</div>
          <div className="text-xl md:text-2xl font-bold text-foreground animate-count-up">
            {allLogs.length}
          </div>
        </div>
        <div className="card-glass-hover rounded-xl p-3 md:p-4">
          <div className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-1">Errors</div>
          <div className="text-xl md:text-2xl font-bold text-red-600 dark:text-red-400">
            {allLogs.filter((l) => getLogLevel(l).toUpperCase() === 'ERROR').length}
          </div>
        </div>
        <div className="card-glass-hover rounded-xl p-3 md:p-4">
          <div className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-1">Warnings</div>
          <div className="text-xl md:text-2xl font-bold text-amber-600 dark:text-amber-400">
            {allLogs.filter((l) => getLogLevel(l).toUpperCase() === 'WARNING').length}
          </div>
        </div>
        <div className="card-glass-hover rounded-xl p-3 md:p-4">
          <div className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-1">Success</div>
          <div className="text-xl md:text-2xl font-bold text-emerald-600 dark:text-emerald-400">
            {allLogs.filter((l) => getLogLevel(l).toUpperCase() === 'SUCCESS').length}
          </div>
        </div>
        <div className="card-glass-hover rounded-xl p-3 md:p-4 col-span-3 md:col-span-1">
          <div className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-1">Filtered</div>
          <div className="text-xl md:text-2xl font-bold text-blue-600 dark:text-blue-400">
            {filteredLogs.length}
          </div>
        </div>
      </div>

      {/* Filter Bar - Collapsible on Mobile */}
      <div className="card-glass-hover rounded-xl p-4 space-y-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2 text-slate-700 dark:text-slate-300">
            <Filter className="w-4 h-4" />
            <span className="text-sm font-medium">Filter by Level</span>
          </div>
          <div className="flex items-center gap-2">
            {levelFilter.length < 5 && (
              <button
                onClick={() => setLevelFilter(['ERROR', 'WARNING', 'INFO', 'SUCCESS', 'DEBUG'])}
                className="text-xs text-blue-600 dark:text-blue-400 hover:underline"
              >
                Reset all
              </button>
            )}
            <button
              onClick={() => setShowFilters(!showFilters)}
              className="md:hidden p-1"
            >
              <ChevronDown className={`w-5 h-5 text-slate-500 transition-transform ${showFilters ? 'rotate-180' : ''}`} />
            </button>
          </div>
        </div>

        <div className={`${showFilters ? 'block' : 'hidden md:block'}`}>
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-2">
            {['ERROR', 'WARNING', 'INFO', 'SUCCESS', 'DEBUG'].map(level => (
              <button
                key={level}
                onClick={() => toggleLevelFilter(level)}
                className={`px-4 py-2 text-sm font-medium rounded-lg transition-all touch-manipulation ${
                  levelFilter.includes(level)
                    ? getLevelBadgeColor(level.toLowerCase())
                    : 'bg-slate-100 dark:bg-slate-700 text-slate-400 dark:text-slate-500 border border-slate-200 dark:border-slate-600'
                }`}
              >
                {level}
              </button>
            ))}
          </div>
        </div>

        {/* Active Filters Display */}
        {levelFilter.length < 5 && levelFilter.length > 0 && (
          <div className="flex items-center gap-2 flex-wrap pt-2 border-t border-slate-200 dark:border-slate-700">
            <span className="text-xs text-slate-500 dark:text-slate-400">Active filters:</span>
            {levelFilter.map(level => (
              <span key={level} className={`text-xs px-2 py-1 rounded-md flex items-center gap-1 ${getLevelBadgeColor(level.toLowerCase())}`}>
                {level}
                <button onClick={() => toggleLevelFilter(level)} className="hover:opacity-70">×</button>
              </span>
            ))}
          </div>
        )}
      </div>

      {/* Log Viewer - iOS Safe Area & Touch Optimized */}
      <div className="card-glass-hover rounded-xl overflow-hidden">
        <div className="bg-secondary/50 px-4 py-3 border-b border-border flex items-center justify-between">
          <div className="flex items-center space-x-3 min-w-0 flex-1">
            <Terminal className="w-5 h-5 text-muted-foreground flex-shrink-0" />
            <div className="min-w-0">
              <div className="text-sm font-semibold text-foreground truncate">
                {selectedComponents.length > 0 ? (
                  `Merged Logs (${selectedComponents.length} components)`
                ) : (
                  'Select components to view logs'
                )}
              </div>
              {selectedComponents.length > 0 && (
                <div className="text-xs text-muted-foreground font-mono truncate">
                  {selectedComponents.map(c => getComponentDisplayName(c)).join(', ')}
                </div>
              )}
            </div>
          </div>
        </div>
        <div
          ref={logsContainerRef}
          className="bg-gray-950 dark:bg-black text-gray-100 p-3 md:p-4 font-mono text-[11px] md:text-xs overflow-y-auto overflow-x-auto custom-scrollbar"
          style={{
            fontFamily: 'Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
            height: 'calc(100vh - 32rem)',
            minHeight: '400px',
            maxHeight: '600px',
            WebkitOverflowScrolling: 'touch'
          }}
        >
          {filteredLogs.length > 0 ? (
            filteredLogs.map((log, index) => {
              const level = getLogLevel(log)
              const color = getLogColor(level)
              const isHighlighted = isNearTimestamp(log)

              // Add background highlight for errors and warnings
              let bgClass = 'hover:bg-gray-900 dark:hover:bg-gray-900/50'
              if (isHighlighted) {
                // Highlighted entry from URL filter - use a distinct yellow/gold highlight
                bgClass = 'bg-yellow-500/30 hover:bg-yellow-500/40 border-l-4 border-yellow-400 pl-2 ring-1 ring-yellow-500/50'
              } else if (level === 'error' || level === 'critical') {
                bgClass = 'bg-red-950/30 hover:bg-red-950/40 border-l-4 border-red-500 pl-2'
              } else if (level === 'warning') {
                bgClass = 'bg-amber-950/20 hover:bg-amber-950/30 border-l-4 border-amber-500 pl-2'
              } else if (level === 'success') {
                bgClass = 'hover:bg-emerald-950/20'
              }

              return (
                <div
                  key={index}
                  ref={isHighlighted ? highlightedLogRef : undefined}
                  className={`py-1 transition-colors whitespace-pre-wrap break-all md:break-normal ${color} ${bgClass}`}
                >
                  {formatLogForDisplay(log)}
                </div>
              )
            })
          ) : (
            <div className="flex flex-col items-center justify-center h-full text-muted-foreground py-12">
              <Terminal className="w-12 h-12 mb-3 opacity-50" />
              <p className="text-sm text-center px-4">No logs match the current filters</p>
              <button
                onClick={() => setLevelFilter(['ERROR', 'WARNING', 'INFO', 'SUCCESS', 'DEBUG'])}
                className="mt-3 px-4 py-2 text-sm text-primary hover:text-primary/80 touch-manipulation transition-colors"
              >
                Reset filters
              </button>
            </div>
          )}
          <div ref={logsEndRef} />
        </div>
      </div>
    </div>
  )
}
