import { useEffect, useState } from 'react'
import api from '../api/client'
import { useSettingsStore } from '../stores/settings'
import StatusBadge from './StatusBadge'
import TerminalModal from './TerminalModal'
import {
  X, Cpu, MemoryStick, HardDrive, Clock, Network, Server, Monitor,
  Container, Database, FolderTree, Settings, Download, Trash2, Copy, Check,
  MonitorSmartphone, Terminal, Cable, ExternalLink, Plus, Unplug,
} from 'lucide-react'

const buildTabs = (hasPBS) => [
  { id: 'overview', label: 'Uebersicht' },
  { id: 'vms', label: 'Virtuelle Maschinen' },
  { id: 'containers', label: 'Container' },
  { id: 'storage', label: 'Storage' },
  { id: 'zfs', label: 'ZFS' },
  ...(hasPBS ? [{ id: 'pbs', label: 'Backup Server' }] : []),
  { id: 'tunnel', label: 'Tunnel' },
  { id: 'services', label: 'Dienste' },
  { id: 'updates', label: 'Updates' },
  { id: 'backups', label: 'Backups' },
  { id: 'agent', label: 'Agent' },
]

export default function ProxmoxPanel({ agentId, customers, onClose, onReload }) {
  const [data, setData] = useState(null)
  const [tab, setTab] = useState('overview')
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    setLoading(true)
    setTab('overview')
    api.getAgent(agentId).then(setData).finally(() => setLoading(false))
  }, [agentId])

  useEffect(() => {
    if (!data) return
    const iv = setInterval(() => {
      api.getAgent(agentId).then(setData)
    }, 30000)
    return () => clearInterval(iv)
  }, [agentId, data])

  if (loading) return <Panel onClose={onClose}><div className="p-6 text-gray-500">Laden...</div></Panel>
  if (!data) return <Panel onClose={onClose}><div className="p-6 text-red-400">Nicht gefunden</div></Panel>

  const { agent, system_data: sys, status } = data
  const proxmox = sys?.proxmox
  const pbs = sys?.pbs
  const cust = agent.customer_id ? customers.find((c) => c.id === agent.customer_id) : null
  const tabs = buildTabs(pbs?.available)

  if (!proxmox?.available) {
    return <Panel onClose={onClose}><div className="p-6 text-red-400">Keine Proxmox-Daten verfuegbar</div></Panel>
  }

  return (
    <Panel onClose={onClose}>
      {/* Header */}
      <div className="px-6 py-4 bg-gradient-to-r from-gray-800 to-gray-900 border-b border-gray-700">
        <div className="flex items-start justify-between">
          <div>
            <div className="flex items-center gap-3">
              <h2 className="text-lg font-bold text-white">{agent.name}</h2>
              <StatusBadge status={status} />
            </div>
            <CustomerAssign agent={agent} customers={customers} current={cust} onReload={onReload} />
            <div className="text-xs text-gray-500 mt-1">
              {agent.hostname} &middot; IP: {agent.ip} &middot; PVE {proxmox.version || '—'}
            </div>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={async () => {
                if (!confirm(`Server "${agent.name}" wirklich loeschen?`)) return
                await api.deleteAgent(agent.id)
                if (onReload) onReload()
                onClose()
              }}
              className="text-gray-500 hover:text-red-400 transition-colors"
              title="Server loeschen"
            >
              <Trash2 className="w-4 h-4" />
            </button>
            <button onClick={onClose} className="text-gray-400 hover:text-white">
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Tabs */}
        <div className="flex gap-1 mt-4 overflow-x-auto text-xs">
          {tabs.map((t) => (
            <button
              key={t.id}
              onClick={() => setTab(t.id)}
              className={`px-3 py-1.5 rounded-t whitespace-nowrap transition-colors ${
                tab === t.id
                  ? 'bg-gray-900 text-orange-400 border-t border-x border-gray-700'
                  : 'text-gray-400 hover:text-gray-200'
              }`}
            >
              {t.label}
            </button>
          ))}
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-6 space-y-4">
        {!sys ? (
          <div className="text-gray-500">Keine Systemdaten</div>
        ) : tab === 'overview' ? (
          <OverviewTab sys={sys} proxmox={proxmox} />
        ) : tab === 'vms' ? (
          <VmsTab proxmox={proxmox} />
        ) : tab === 'containers' ? (
          <ContainersTab proxmox={proxmox} />
        ) : tab === 'storage' ? (
          <StorageTab proxmox={proxmox} />
        ) : tab === 'zfs' ? (
          <ZfsTab proxmox={proxmox} />
        ) : tab === 'tunnel' ? (
          <TunnelTab agentId={agentId} agent={data?.agent} webguiPort={8006} />
        ) : tab === 'services' ? (
          <ServicesTab sys={sys} />
        ) : tab === 'updates' ? (
          <UpdatesTab sys={sys} />
        ) : tab === 'pbs' ? (
          <PBSTab pbs={pbs} agentId={agentId} sys={sys} />
        ) : tab === 'backups' ? (
          <BackupsTab sys={sys} />
        ) : tab === 'agent' ? (
          <AgentTab agent={data?.agent} status={data?.status} />
        ) : null}
      </div>
    </Panel>
  )
}

function CustomerAssign({ agent, customers, current, onReload }) {
  const [editing, setEditing] = useState(false)
  const [saving, setSaving] = useState(false)

  const handleChange = async (e) => {
    const val = e.target.value
    setSaving(true)
    try {
      if (val === '') {
        await api.unassignCustomer(agent.id)
      } else {
        await api.assignCustomer(agent.id, parseInt(val))
      }
      if (onReload) onReload()
    } catch (err) {
      console.error(err)
    } finally {
      setSaving(false)
      setEditing(false)
    }
  }

  return (
    <div className="text-xs text-gray-400 mt-1">
      {!editing ? (
        <button
          onClick={() => setEditing(true)}
          className="hover:text-orange-400 transition-colors"
        >
          Kunde: {current ? `${current.number} — ${current.name}` : 'Kein Kunde'}
        </button>
      ) : (
        <select
          onChange={handleChange}
          defaultValue={current?.id || ''}
          disabled={saving}
          className="bg-gray-800 border border-gray-600 rounded px-2 py-0.5 text-xs text-white focus:outline-none focus:border-orange-500"
          onBlur={() => setEditing(false)}
          autoFocus
        >
          <option value="">Kein Kunde</option>
          {customers.map(c => (
            <option key={c.id} value={c.id}>{c.number} — {c.name}</option>
          ))}
        </select>
      )}
    </div>
  )
}

function Panel({ onClose, children }) {
  return (
    <>
      <div className="fixed inset-0 z-40 bg-black/50" onClick={onClose} />
      <div className="fixed inset-y-0 right-0 z-50 w-full max-w-5xl bg-gray-900 border-l border-gray-800 flex flex-col shadow-2xl animate-slide-in">
        {children}
      </div>
      <style>{`
        @keyframes slideIn { from { transform: translateX(100%); } to { transform: translateX(0); } }
        .animate-slide-in { animation: slideIn 0.2s ease-out; }
      `}</style>
    </>
  )
}

function MetricCard({ icon: Icon, label, value, sub, bar, barColor }) {
  return (
    <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 p-4">
      <div className="flex items-center gap-2 text-gray-500 mb-2">
        {Icon && <Icon className="w-4 h-4" />}
        <span className="text-xs uppercase">{label}</span>
      </div>
      <div className="text-xl font-bold text-white">{value}</div>
      {sub && <div className="text-xs text-gray-500 mt-0.5">{sub}</div>}
      {bar !== undefined && bar !== null && (
        <div className="mt-2 h-1.5 bg-gray-700 rounded overflow-hidden">
          <div className={`h-full rounded ${barColor || 'bg-blue-500'}`} style={{ width: `${Math.min(bar, 100)}%` }} />
        </div>
      )}
    </div>
  )
}

function StatusCard({ icon: Icon, value, label }) {
  return (
    <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 p-3 text-center">
      <div className="flex justify-center mb-2">
        {Icon && <Icon className="w-5 h-5 text-gray-500" />}
      </div>
      <div className="text-lg font-bold text-white">{value}</div>
      <div className="text-xs text-gray-500 uppercase">{label}</div>
    </div>
  )
}

function OverviewTab({ sys, proxmox }) {
  const rootDisk = sys.disks?.find((d) => d.mount_point === '/')
  const diskPct = rootDisk && rootDisk.total_bytes > 0
    ? (rootDisk.used_bytes / rootDisk.total_bytes * 100) : null
  const ramPct = sys.memory?.total_bytes > 0
    ? (sys.memory.used_bytes / sys.memory.total_bytes * 100) : null
  const cpuPct = sys.cpu?.usage_percent

  const barColor = (v) => v > 90 ? 'bg-red-500' : v > 70 ? 'bg-yellow-500' : v > 50 ? 'bg-orange-500' : 'bg-green-500'

  const vmsRunning = proxmox.vms?.filter(vm => vm.status === 'running').length || 0
  const vmsTotal = proxmox.vms?.length || 0
  const ctRunning = proxmox.containers?.filter(ct => ct.status === 'running').length || 0
  const ctTotal = proxmox.containers?.length || 0
  const storageCount = proxmox.storage?.length || 0
  const zfsCount = proxmox.zfs_pools?.length || 0

  return (
    <>
      <h3 className="text-sm font-medium text-gray-300">System-Metriken</h3>
      <div className="grid grid-cols-2 gap-3">
        <MetricCard icon={Cpu} label="CPU Auslastung" value={cpuPct != null ? `${cpuPct.toFixed(1)}%` : '—'}
          sub={sys.cpu?.model} bar={cpuPct} barColor={barColor(cpuPct || 0)} />
        <MetricCard icon={MemoryStick} label="RAM Auslastung" value={ramPct != null ? `${ramPct.toFixed(1)}%` : '—'}
          sub={sys.memory ? `${formatBytes(sys.memory.used_bytes)} / ${formatBytes(sys.memory.total_bytes)}` : ''}
          bar={ramPct} barColor={barColor(ramPct || 0)} />
        <MetricCard icon={HardDrive} label="Festplatte" value={diskPct != null ? `${diskPct.toFixed(1)}%` : '—'}
          sub={rootDisk ? `${formatBytes(rootDisk.used_bytes)} / ${formatBytes(rootDisk.total_bytes)}` : ''}
          bar={diskPct} barColor={barColor(diskPct || 0)} />
        <MetricCard icon={Clock} label="Uptime" value={sys.uptime_seconds ? formatUptime(sys.uptime_seconds) : '—'} />
      </div>

      <h3 className="text-sm font-medium text-gray-300 mt-4">Proxmox-Info</h3>
      <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 p-4">
        <div className="grid grid-cols-2 gap-4">
          <div>
            <div className="text-xs text-gray-500 uppercase">PVE Version</div>
            <div className="text-white font-medium">{proxmox.version || '—'}</div>
          </div>
          <div>
            <div className="text-xs text-gray-500 uppercase">Node Name</div>
            <div className="text-white font-medium">{proxmox.node || '—'}</div>
          </div>
          <div>
            <div className="text-xs text-gray-500 uppercase">Cluster Name</div>
            <div className="text-white font-medium">{proxmox.cluster?.name || '—'}</div>
          </div>
        </div>
      </div>

      {/* Subscription */}
      {proxmox.subscription && (
        <>
          <h3 className="text-sm font-medium text-gray-300 mt-4">Subscription</h3>
          <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 p-4">
            <div className="flex items-center justify-between">
              <div>
                <div className="text-white font-medium">{proxmox.subscription.productname || 'Proxmox VE'}</div>
                {proxmox.subscription.key && (
                  <div className="text-xs text-gray-500 mt-1 font-mono">{proxmox.subscription.key}</div>
                )}
              </div>
              <div className="text-right">
                <div className={`text-sm font-bold ${
                  proxmox.subscription.status === 'Active' ? 'text-green-400' : 'text-red-400'
                }`}>
                  {proxmox.subscription.status || 'Unknown'}
                </div>
                {proxmox.subscription.next_due_date && (
                  <div className="text-xs text-gray-500">bis {proxmox.subscription.next_due_date}</div>
                )}
              </div>
            </div>
          </div>
        </>
      )}

      <h3 className="text-sm font-medium text-gray-300 mt-4">Kurzuebersicht</h3>
      <div className="grid grid-cols-4 gap-3">
        <StatusCard icon={Monitor} value={`${vmsRunning}/${vmsTotal}`} label="VMs" />
        <StatusCard icon={Container} value={`${ctRunning}/${ctTotal}`} label="Container" />
        <StatusCard icon={Database} value={storageCount} label="Storage" />
        <StatusCard icon={FolderTree} value={zfsCount} label="ZFS Pools" />
      </div>
    </>
  )
}

function VmsTab({ proxmox }) {
  const vms = proxmox.vms || []
  
  // Sort: running first, then by name
  const sortedVms = [...vms].sort((a, b) => {
    if (a.status === 'running' && b.status !== 'running') return -1
    if (a.status !== 'running' && b.status === 'running') return 1
    return a.name.localeCompare(b.name)
  })

  return (
    <>
      <h3 className="text-sm font-medium text-gray-300">Virtuelle Maschinen ({vms.length})</h3>
      {sortedVms.length === 0 ? (
        <div className="text-gray-500">Keine VMs gefunden</div>
      ) : (
        <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-gray-500 text-xs border-b border-gray-700">
                <th className="px-3 py-2">VMID</th>
                <th className="px-3 py-2">Name</th>
                <th className="px-3 py-2">Status</th>
                <th className="px-3 py-2">CPU</th>
                <th className="px-3 py-2">RAM</th>
                <th className="px-3 py-2">Disk</th>
                <th className="px-3 py-2">Uptime</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-700/50">
              {sortedVms.map((vm) => (
                <tr key={vm.vmid}>
                  <td className="px-3 py-2 text-gray-400">{vm.vmid}</td>
                  <td className="px-3 py-2 text-white font-medium">{vm.name}</td>
                  <td className="px-3 py-2">
                    <StatusBadge status={vm.status} />
                  </td>
                  <td className="px-3 py-2 text-gray-400">
                    {vm.cpu_usage != null ? `${vm.cpu_usage.toFixed(1)}%` : '—'}
                  </td>
                  <td className="px-3 py-2 text-gray-400">
                    {vm.memory_used && vm.memory_max ? 
                      `${formatBytes(vm.memory_used)} / ${formatBytes(vm.memory_max)}` : '—'}
                  </td>
                  <td className="px-3 py-2 text-gray-400">
                    {vm.disk_used != null && vm.disk_max ? 
                      `${formatBytes(vm.disk_used)} / ${formatBytes(vm.disk_max)}` : '—'}
                  </td>
                  <td className="px-3 py-2 text-gray-400">
                    {vm.uptime ? formatUptime(vm.uptime) : '—'}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </>
  )
}

function ContainersTab({ proxmox }) {
  const containers = proxmox.containers || []
  
  // Sort: running first, then by name
  const sortedCt = [...containers].sort((a, b) => {
    if (a.status === 'running' && b.status !== 'running') return -1
    if (a.status !== 'running' && b.status === 'running') return 1
    return a.name.localeCompare(b.name)
  })

  return (
    <>
      <h3 className="text-sm font-medium text-gray-300">Container ({containers.length})</h3>
      {sortedCt.length === 0 ? (
        <div className="text-gray-500">Keine Container gefunden</div>
      ) : (
        <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-gray-500 text-xs border-b border-gray-700">
                <th className="px-3 py-2">VMID</th>
                <th className="px-3 py-2">Name</th>
                <th className="px-3 py-2">Status</th>
                <th className="px-3 py-2">CPU</th>
                <th className="px-3 py-2">RAM</th>
                <th className="px-3 py-2">Uptime</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-700/50">
              {sortedCt.map((ct) => (
                <tr key={ct.vmid}>
                  <td className="px-3 py-2 text-gray-400">{ct.vmid}</td>
                  <td className="px-3 py-2 text-white font-medium">{ct.name}</td>
                  <td className="px-3 py-2">
                    <StatusBadge status={ct.status} />
                  </td>
                  <td className="px-3 py-2 text-gray-400">
                    {ct.cpu_usage != null ? `${ct.cpu_usage.toFixed(1)}%` : '—'}
                  </td>
                  <td className="px-3 py-2 text-gray-400">
                    {ct.memory_used && ct.memory_max ? 
                      `${formatBytes(ct.memory_used)} / ${formatBytes(ct.memory_max)}` : '—'}
                  </td>
                  <td className="px-3 py-2 text-gray-400">
                    {ct.uptime ? formatUptime(ct.uptime) : '—'}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </>
  )
}

function StorageTab({ proxmox }) {
  const storage = proxmox.storage || []

  return (
    <>
      <h3 className="text-sm font-medium text-gray-300">Storage ({storage.length})</h3>
      {storage.length === 0 ? (
        <div className="text-gray-500">Keine Storage-Pools gefunden</div>
      ) : (
        <div className="space-y-3">
          {storage.map((s) => {
            const usedPct = s.total && s.total > 0 ? (s.used / s.total * 100) : 0
            const barColor = usedPct > 90 ? 'bg-red-500' : usedPct > 70 ? 'bg-yellow-500' : 'bg-green-500'
            
            return (
              <div key={s.storage} className="bg-gray-800/50 rounded-lg border border-gray-700/50 p-4">
                <div className="flex items-start justify-between mb-2">
                  <div>
                    <div className="text-white font-medium">{s.storage}</div>
                    <div className="text-xs text-gray-500">{s.type} • {s.content}</div>
                  </div>
                  <div className="text-right">
                    <StatusBadge status={s.active ? 'online' : 'offline'} />
                  </div>
                </div>
                
                {s.total && (
                  <>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="text-gray-400">{formatBytes(s.used)} / {formatBytes(s.total)}</span>
                      <span className="text-gray-400">{usedPct.toFixed(1)}%</span>
                    </div>
                    <div className="w-full h-2 bg-gray-700 rounded overflow-hidden">
                      <div className={`h-full rounded ${barColor}`} style={{ width: `${usedPct}%` }} />
                    </div>
                  </>
                )}
              </div>
            )
          })}
        </div>
      )}
    </>
  )
}

function ZfsTab({ proxmox }) {
  const zfsPools = proxmox.zfs_pools || []

  return (
    <>
      <h3 className="text-sm font-medium text-gray-300">ZFS Pools ({zfsPools.length})</h3>
      {zfsPools.length === 0 ? (
        <div className="text-gray-500">Keine ZFS-Pools gefunden</div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {zfsPools.map((pool) => {
            const healthColor = pool.health === 'ONLINE' ? 'text-green-400' : 
                               pool.health === 'DEGRADED' ? 'text-yellow-400' : 'text-red-400'
            const healthBg = pool.health === 'ONLINE' ? 'bg-green-500' : 
                            pool.health === 'DEGRADED' ? 'bg-yellow-500' : 'bg-red-500'
            
            return (
              <div key={pool.name} className="bg-gray-800/50 rounded-lg border border-gray-700/50 p-4">
                <div className="flex items-start justify-between mb-3">
                  <div className="text-white font-medium">{pool.name}</div>
                  <div className={`text-xs font-bold ${healthColor}`}>{pool.health}</div>
                </div>
                
                {(() => {
                  const usedPct = pool.size > 0 ? (pool.allocated / pool.size * 100) : 0
                  const pctColor = usedPct > 90 ? 'bg-red-500' : usedPct > 70 ? 'bg-yellow-500' : 'bg-green-500'
                  return (
                    <>
                      <div className="space-y-2 text-sm">
                        <div className="flex justify-between">
                          <span className="text-gray-500">Groesse:</span>
                          <span className="text-gray-300">{formatBytes(pool.size)}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-500">Belegt:</span>
                          <span className="text-gray-300">{formatBytes(pool.allocated)} ({usedPct.toFixed(1)}%)</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-500">Frei:</span>
                          <span className="text-gray-300">{formatBytes(pool.free)}</span>
                        </div>
                        {pool.fragmentation && (
                          <div className="flex justify-between">
                            <span className="text-gray-500">Fragmentierung:</span>
                            <span className="text-gray-300">{pool.fragmentation}</span>
                          </div>
                        )}
                      </div>

                      <div className="mt-3 w-full h-2 bg-gray-700 rounded overflow-hidden">
                        <div className={`h-full rounded ${pctColor}`} style={{ width: `${Math.min(usedPct, 100)}%` }} />
                      </div>

                      {pool.scrub_status && (
                        <div className="mt-3 pt-3 border-t border-gray-700">
                          <div className="text-xs text-gray-500">{pool.scrub_status}</div>
                        </div>
                      )}
                    </>
                  )
                })()}
              </div>
            )
          })}
        </div>
      )}
    </>
  )
}

function ServicesTab({ sys }) {
  const services = sys.services || []
  
  // Sort: running first
  const sortedServices = [...services].sort((a, b) => {
    const aRunning = a.running || a.status === 'running'
    const bRunning = b.running || b.status === 'running'
    if (aRunning && !bRunning) return -1
    if (!aRunning && bRunning) return 1
    return a.name.localeCompare(b.name)
  })

  return (
    <>
      <h3 className="text-sm font-medium text-gray-300">Systemd Dienste ({services.length})</h3>
      {sortedServices.length === 0 ? (
        <div className="text-gray-500">Keine Dienste gefunden</div>
      ) : (
        <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-gray-500 text-xs border-b border-gray-700">
                <th className="px-3 py-2">Name</th>
                <th className="px-3 py-2">Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-700/50">
              {sortedServices.map((svc, i) => {
                const running = svc.running || svc.status === 'running'
                return (
                  <tr key={i}>
                    <td className="px-3 py-2 text-white">{svc.name}</td>
                    <td className="px-3 py-2">
                      <StatusBadge status={running ? 'running' : 'stopped'} />
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
        </div>
      )}
    </>
  )
}

function UpdatesTab({ sys }) {
  const pendingUpdates = sys.pending_updates || []

  return (
    <>
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-medium text-gray-300">Updates</h3>
        <div className="text-sm text-orange-400">
          {pendingUpdates.length} Updates verfuegbar
        </div>
      </div>
      
      {pendingUpdates.length === 0 ? (
        <div className="text-gray-500">Keine Updates verfuegbar</div>
      ) : (
        <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-gray-500 text-xs border-b border-gray-700">
                <th className="px-3 py-2">Package</th>
                <th className="px-3 py-2">Current Version</th>
                <th className="px-3 py-2">New Version</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-700/50">
              {pendingUpdates.map((update, i) => (
                <tr key={i}>
                  <td className="px-3 py-2 text-white font-medium">{update.package}</td>
                  <td className="px-3 py-2 text-gray-400">{update.current_version}</td>
                  <td className="px-3 py-2 text-orange-400">{update.new_version}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </>
  )
}

function AgentTab({ agent, status }) {
  return (
    <>
      <h3 className="text-sm font-medium text-gray-300">Agent Information</h3>
      <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 p-4 space-y-3">
        <div className="grid grid-cols-2 gap-4">
          <div>
            <div className="text-xs text-gray-500 uppercase">Agent Version</div>
            <div className="text-white">{agent?.agent_version || '—'}</div>
          </div>
          <div>
            <div className="text-xs text-gray-500 uppercase">Status</div>
            <StatusBadge status={status} />
          </div>
          <div>
            <div className="text-xs text-gray-500 uppercase">Last Heartbeat</div>
            <div className="text-white text-xs">
              {agent?.last_heartbeat ? new Date(agent.last_heartbeat).toLocaleString('de-DE') : '—'}
            </div>
          </div>
          <div>
            <div className="text-xs text-gray-500 uppercase">Agent ID</div>
            <div className="text-white text-xs font-mono">{agent?.id?.substring(0, 12)}...</div>
          </div>
        </div>
      </div>
    </>
  )
}

function TunnelTab({ agentId, agent, webguiPort = 8006 }) {
  const [tunnels, setTunnels] = useState([])
  const [loading, setLoading] = useState(true)
  const [creating, setCreating] = useState(null)
  const [customOpen, setCustomOpen] = useState(false)
  const [customHost, setCustomHost] = useState('127.0.0.1')
  const [customPort, setCustomPort] = useState('')
  const [error, setError] = useState('')
  const [sshCopied, setSshCopied] = useState(null)
  const [terminalOpen, setTerminalOpen] = useState(false)

  const backendHost = useSettingsStore.getState().getBackendHost()

  const loadTunnels = () => {
    api.getTunnels(agentId)
      .then((resp) => {
        const list = resp?.tunnels || resp?.data?.tunnels || resp?.data || resp || []
        setTunnels(Array.isArray(list) ? list : [])
      })
      .catch(() => setTunnels([]))
      .finally(() => setLoading(false))
  }

  useEffect(() => { loadTunnels() }, [agentId])
  useEffect(() => {
    if (tunnels.length > 0) {
      const iv = setInterval(loadTunnels, 10000)
      return () => clearInterval(iv)
    }
  }, [tunnels.length, agentId])

  const openTunnel = async (targetHost, targetPort, label) => {
    setError('')
    setCreating(label)
    try {
      const resp = await api.openTunnel(agentId, targetHost, targetPort)
      const data = resp?.data || resp
      loadTunnels()
      if (data?.proxy_port) {
        setTimeout(() => {
          if (targetPort === webguiPort) {
            window.open(`https://${backendHost}:${data.proxy_port}`, '_blank')
          } else if (targetPort === 22) {
            const cmd = `ssh root@${backendHost} -p ${data.proxy_port}`
            navigator.clipboard.writeText(cmd).catch(() => {})
            setSshCopied(data.proxy_port)
            setTimeout(() => setSshCopied(null), 4000)
          }
        }, 1000)
      }
      return data
    } catch (e) {
      setError(e.message)
    } finally {
      setCreating(null)
    }
  }

  const closeTunnel = async (tunnelId) => {
    try {
      await api.closeTunnel(agentId, tunnelId)
      setTunnels((prev) => prev.filter((t) => t.id !== tunnelId && t.tunnel_id !== tunnelId))
    } catch (e) {
      setError(e.message)
    }
  }

  const handleCustom = () => {
    const port = parseInt(customPort)
    if (!port || port < 1 || port > 65535) return
    openTunnel(customHost, port, 'custom')
    setCustomOpen(false)
    setCustomPort('')
  }

  return (
    <div className="space-y-4">
      {terminalOpen && (
        <TerminalModal agentId={agentId} agentName={agent?.name} onClose={() => setTerminalOpen(false)} />
      )}

      {/* Schnellzugriff */}
      <div className="flex items-center gap-3 flex-wrap">
        <span className="text-sm text-gray-400">Schnellzugriff:</span>
        <button
          onClick={() => openTunnel('127.0.0.1', webguiPort, 'webgui')}
          disabled={creating === 'webgui'}
          className="flex items-center gap-1.5 px-3 py-1.5 bg-orange-600 hover:bg-orange-700 disabled:bg-orange-800 disabled:opacity-50 rounded text-sm text-white transition-colors"
        >
          <MonitorSmartphone className="w-4 h-4" />
          {creating === 'webgui' ? 'Verbinde...' : `WebGUI (${webguiPort})`}
        </button>
        <button
          onClick={() => openTunnel('127.0.0.1', 22, 'ssh')}
          disabled={creating === 'ssh'}
          className="flex items-center gap-1.5 px-3 py-1.5 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-800 disabled:opacity-50 rounded text-sm text-white transition-colors"
        >
          <Terminal className="w-4 h-4" />
          {creating === 'ssh' ? 'Verbinde...' : 'SSH (22)'}
        </button>
        <button
          onClick={() => setTerminalOpen(true)}
          className="flex items-center gap-1.5 px-3 py-1.5 bg-green-700 hover:bg-green-600 rounded text-sm text-white transition-colors"
        >
          <Terminal className="w-4 h-4" />
          Web Terminal
        </button>
        <button
          onClick={() => setCustomOpen(!customOpen)}
          className="flex items-center gap-1.5 px-3 py-1.5 bg-gray-700 hover:bg-gray-600 rounded text-sm text-gray-300 transition-colors"
        >
          <Plus className="w-4 h-4" />
          Benutzerdefiniert
        </button>
      </div>

      {/* Custom Form */}
      {customOpen && (
        <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 p-4 flex items-end gap-3">
          <div>
            <label className="block text-xs text-gray-400 mb-1">Ziel-Host</label>
            <input type="text" value={customHost} onChange={(e) => setCustomHost(e.target.value)}
              className="bg-gray-900 border border-gray-700 rounded px-3 py-2 text-sm text-white w-40 focus:outline-none focus:border-orange-500" />
          </div>
          <div>
            <label className="block text-xs text-gray-400 mb-1">Port</label>
            <input type="number" value={customPort} onChange={(e) => setCustomPort(e.target.value)}
              placeholder="z.B. 8080"
              className="bg-gray-900 border border-gray-700 rounded px-3 py-2 text-sm text-white w-28 focus:outline-none focus:border-orange-500"
              onKeyDown={(e) => e.key === 'Enter' && handleCustom()} />
          </div>
          <button onClick={handleCustom}
            className="px-4 py-2 bg-green-600 hover:bg-green-700 rounded text-sm text-white transition-colors">
            Verbinden
          </button>
        </div>
      )}

      {/* SSH auto-kopiert Bestätigung */}
      {sshCopied && (
        <div className="text-sm text-green-400 bg-green-900/20 rounded px-3 py-2 border border-green-800/50 flex items-center gap-2">
          <Terminal className="w-4 h-4" />
          SSH-Befehl kopiert — in CMD/Terminal einfuegen und ausfuehren
        </div>
      )}
      {error && <div className="text-sm text-red-400 bg-red-900/20 rounded px-3 py-2 border border-red-800/50">{error}</div>}

      {/* Aktive Tunnel */}
      <div>
        <h3 className="text-sm font-medium text-gray-300 mb-2">Aktive Tunnel</h3>
        {loading ? (
          <div className="text-gray-500 text-sm">Laden...</div>
        ) : tunnels.length === 0 ? (
          <div className="text-gray-500 bg-gray-800/30 rounded-lg border border-gray-800 px-4 py-6 text-center text-sm">
            Keine aktiven Tunnel
          </div>
        ) : (
          <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 overflow-hidden">
            <table className="w-full text-sm">
              <thead>
                <tr className="text-left text-gray-500 text-xs border-b border-gray-700">
                  <th className="px-3 py-2">Ziel</th>
                  <th className="px-3 py-2">Lokaler Zugang</th>
                  <th className="px-3 py-2">Status</th>
                  <th className="px-3 py-2">Erstellt</th>
                  <th className="px-3 py-2 text-right">Aktionen</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-700/50">
                {tunnels.map((t) => {
                  const tid = t.id || t.tunnel_id
                  const proxyPort = t.proxy_port || t.local_port
                  const target = t.target_host && t.target_port ? `${t.target_host}:${t.target_port}` : '—'
                  const isWebGUI = t.target_port === webguiPort || t.target_port === String(webguiPort)
                  const isSSH = t.target_port === 22 || t.target_port === '22'

                  return (
                    <tr key={tid}>
                      <td className="px-3 py-2.5 text-white font-mono text-xs">{target}</td>
                      <td className="px-3 py-2.5">
                        <div className="flex items-center gap-2">
                          <span className="text-gray-400 font-mono text-xs">{backendHost}:{proxyPort}</span>
                          {isWebGUI && proxyPort && (
                            <a href={`https://${backendHost}:${proxyPort}`} target="_blank" rel="noopener"
                              className="text-orange-400 hover:text-orange-300" title="WebGUI oeffnen">
                              <ExternalLink className="w-3.5 h-3.5" />
                            </a>
                          )}
                          {isSSH && proxyPort && (
                            <button
                              onClick={() => {
                                const cmd = `ssh root@${backendHost} -p ${proxyPort}`
                                navigator.clipboard.writeText(cmd).catch(() => {})
                                setSshCopied(proxyPort)
                                setTimeout(() => setSshCopied(null), 3000)
                              }}
                              className={`inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded transition-colors ${
                                sshCopied === proxyPort
                                  ? 'bg-green-900/30 text-green-400 border border-green-700/50'
                                  : 'bg-blue-900/30 text-blue-400 border border-blue-700/50 hover:bg-blue-900/50'
                              }`}
                            >
                              <Terminal className="w-3 h-3" />
                              {sshCopied === proxyPort ? 'Kopiert!' : 'SSH kopieren'}
                            </button>
                          )}
                        </div>
                      </td>
                      <td className="px-3 py-2.5">
                        <span className="inline-flex items-center gap-1.5 text-xs text-green-400">
                          <span className="w-1.5 h-1.5 rounded-full bg-green-400 animate-pulse" />
                          aktiv
                        </span>
                      </td>
                      <td className="px-3 py-2.5 text-gray-500 text-xs">
                        {t.created_at ? new Date(t.created_at).toLocaleString('de-DE') : '—'}
                      </td>
                      <td className="px-3 py-2.5 text-right">
                        <button onClick={() => closeTunnel(tid)}
                          className="text-red-400 hover:text-red-300 p-1 rounded hover:bg-red-900/30 transition-colors" title="Tunnel schliessen">
                          <Unplug className="w-4 h-4" />
                        </button>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <div className="text-xs text-gray-600">
        Tunnel werden ueber den RMM-Backend-Server ({backendHost}) geroutet. WebGUI-Tunnel oeffnen automatisch ein neues Browserfenster.
      </div>
    </div>
  )
}

function BackupsTab({ sys }) {
  const backups = sys?.backups || {}
  const jobs = backups.jobs || []
  const tasks = backups.tasks || []

  const totalJobs = jobs.filter(j => j.enabled === 1 || j.enabled === true).length
  const okTasks = tasks.filter(t => t.status === 'OK').length
  const failedTasks = tasks.filter(t => t.status && t.status !== 'OK').length
  const successRate = tasks.length > 0 ? Math.round((okTasks / tasks.length) * 100) : null

  return (
    <div className="space-y-4">
      {/* Stats */}
      <div className="grid grid-cols-4 gap-3">
        <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 p-3 text-center">
          <div className="text-gray-500 text-xs mb-1">Jobs (aktiv)</div>
          <div className="text-xl font-bold text-white">{totalJobs}</div>
        </div>
        <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 p-3 text-center">
          <div className="text-gray-500 text-xs mb-1">Aufgaben (30d)</div>
          <div className="text-xl font-bold text-white">{tasks.length}</div>
        </div>
        <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 p-3 text-center">
          <div className="text-gray-500 text-xs mb-1">Erfolgreich</div>
          <div className="text-xl font-bold text-emerald-400">{okTasks}</div>
        </div>
        <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 p-3 text-center">
          <div className="text-gray-500 text-xs mb-1">Erfolgsrate</div>
          <div className={`text-xl font-bold ${successRate === 100 ? 'text-emerald-400' : successRate === null ? 'text-gray-500' : successRate >= 90 ? 'text-yellow-400' : 'text-red-400'}`}>
            {successRate !== null ? `${successRate}%` : '--'}
          </div>
        </div>
      </div>

      {/* Backup Jobs */}
      <h3 className="text-sm font-medium text-gray-300">Backup Jobs</h3>
      {jobs.length === 0 ? (
        <div className="text-gray-500">Keine Backup-Jobs konfiguriert</div>
      ) : (
        <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-gray-500 text-xs border-b border-gray-700">
                <th className="px-3 py-2">ID</th>
                <th className="px-3 py-2">Storage</th>
                <th className="px-3 py-2">Schedule</th>
                <th className="px-3 py-2">Modus</th>
                <th className="px-3 py-2">VMs/CTs</th>
                <th className="px-3 py-2">Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-700/50">
              {jobs.map((j, i) => (
                <tr key={i}>
                  <td className="px-3 py-2 text-white font-mono text-xs">{j.id || i}</td>
                  <td className="px-3 py-2 text-gray-400">{j.storage || '—'}</td>
                  <td className="px-3 py-2 text-gray-400 text-xs">{j.schedule || '—'}</td>
                  <td className="px-3 py-2 text-gray-400">{j.mode || '—'}</td>
                  <td className="px-3 py-2 text-gray-400 text-xs">{j.vmid || j.all ? 'Alle' : '—'}</td>
                  <td className="px-3 py-2">
                    <span className={`text-xs ${j.enabled ? 'text-green-400' : 'text-gray-500'}`}>
                      {j.enabled ? 'Aktiv' : 'Inaktiv'}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Task History */}
      <h3 className="text-sm font-medium text-gray-300">Letzte Backup-Aufgaben</h3>
      {tasks.length === 0 ? (
        <div className="text-gray-500">Keine Backup-Aufgaben in den letzten 30 Tagen</div>
      ) : (
        <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-gray-500 text-xs border-b border-gray-700">
                <th className="px-3 py-2">Zeitpunkt</th>
                <th className="px-3 py-2">Typ</th>
                <th className="px-3 py-2">VMID</th>
                <th className="px-3 py-2">Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-700/50">
              {tasks.slice(0, 50).map((t, i) => (
                <tr key={i}>
                  <td className="px-3 py-2 text-gray-400 text-xs">
                    {t.starttime ? new Date(t.starttime * 1000).toLocaleString('de-DE') : '—'}
                  </td>
                  <td className="px-3 py-2 text-gray-400 text-xs">{t.type || 'vzdump'}</td>
                  <td className="px-3 py-2 text-gray-400">{t.id || '—'}</td>
                  <td className="px-3 py-2">
                    <span className={`text-xs font-medium px-2 py-0.5 rounded ${
                      t.status === 'OK'
                        ? 'bg-green-900/40 text-green-400 border border-green-700/50'
                        : 'bg-red-900/40 text-red-400 border border-red-700/50'
                    }`}>
                      {t.status || '—'}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {failedTasks > 0 && (
        <div className="text-sm text-red-400 bg-red-900/20 rounded px-3 py-2 border border-red-800/50">
          {failedTasks} fehlgeschlagene Backup(s) in den letzten 30 Tagen
        </div>
      )}
    </div>
  )
}

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

function formatUptime(seconds) {
  const d = Math.floor(seconds / 86400)
  const h = Math.floor((seconds % 86400) / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  if (d > 0) return `${d}d ${h}h`
  return `${h}h ${m}m`
}

function PBSTab({ pbs, agentId, sys }) {
  const [loading, setLoading] = useState({})
  const [feedback, setFeedback] = useState({})

  if (!pbs?.available) return <div className="p-4 text-gray-500">Keine PBS-Daten verfuegbar</div>

  const formatBytes = (b) => {
    if (!b) return '—'
    if (b >= 1099511627776) return `${(b / 1099511627776).toFixed(1)} TB`
    if (b >= 1073741824) return `${(b / 1073741824).toFixed(1)} GB`
    if (b >= 1048576) return `${(b / 1048576).toFixed(1)} MB`
    return `${b} B`
  }

  const formatTs = (ts) => ts ? new Date(ts * 1000).toLocaleString('de-DE') : '—'
  const formatDuration = (s) => {
    if (!s) return '—'
    if (s < 60) return `${s}s`
    if (s < 3600) return `${Math.floor(s/60)}m ${s%60}s`
    return `${Math.floor(s/3600)}h ${Math.floor((s%3600)/60)}m`
  }
  const taskStatusColor = (s) => {
    if (!s) return 'text-gray-500'
    if (s === 'OK' || s.startsWith('OK')) return 'text-green-400'
    if (s.toLowerCase().includes('err') || s.toLowerCase().includes('fail')) return 'text-red-400'
    if (s === 'running') return 'text-blue-400'
    return 'text-yellow-400'
  }

  const pbsAction = async (datastore, action) => {
    const key = `${datastore}-${action}`
    const cmds = {
      gc:     `/usr/sbin/proxmox-backup-manager garbage-collection start ${datastore}`,
      verify: `/usr/sbin/proxmox-backup-manager verify ${datastore}`,
      prune:  `/usr/sbin/proxmox-backup-manager prune-datastore ${datastore}`,
    }
    setLoading(l => ({ ...l, [key]: true }))
    setFeedback(f => ({ ...f, [key]: null }))
    try {
      await api.execCommand(agentId, cmds[action], 60)
      setFeedback(f => ({ ...f, [key]: 'ok' }))
    } catch (e) {
      setFeedback(f => ({ ...f, [key]: 'err' }))
    } finally {
      setLoading(l => ({ ...l, [key]: false }))
      setTimeout(() => setFeedback(f => ({ ...f, [key]: null })), 4000)
    }
  }

  const totalBackups = pbs.datastores?.reduce((s, d) => s + (d.backup_count || 0), 0) || 0
  const runningTasks = pbs.tasks?.filter(t => t.running)?.length || 0

  const StatCard = ({ icon, value, label, iconColor, highlight }) => (
    <div className={`flex-1 bg-[#1a2235] rounded-xl border p-3 flex flex-col items-center gap-1.5 ${highlight ? 'border-blue-500/50' : 'border-gray-700/40'}`}>
      <div className={`text-xl ${iconColor}`}>{icon}</div>
      <div className="text-xl font-bold text-white">{value}</div>
      <div className="text-xs text-gray-400">{label}</div>
    </div>
  )

  return (
    <div className="space-y-6">
      {/* Titel */}
      <div>
        <div className="text-lg font-semibold text-white">Backup Server</div>
        {pbs.version && <div className="text-xs text-gray-500 mt-0.5">PBS {pbs.version}</div>}
      </div>

      {/* Stat-Karten */}
      <div className="flex gap-2">
        <StatCard
          icon={<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><ellipse cx="12" cy="5" rx="9" ry="3" strokeWidth="2"/><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 5v14a9 3 0 0018 0V5M3 12a9 3 0 0018 0"/></svg>}
          value={pbs.datastores?.length || 0}
          label="Datastores"
          iconColor="text-orange-400"
        />
        <StatCard
          icon={<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8"/></svg>}
          value={totalBackups}
          label="Backups"
          iconColor="text-blue-400"
        />
        <StatCard
          icon={<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>}
          value={pbs.sync_jobs ?? 0}
          label="Sync Jobs"
          iconColor="text-green-400"
        />
        <StatCard
          icon={<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" strokeWidth="2"/><polyline points="12 6 12 12 16 14" strokeWidth="2"/></svg>}
          value={runningTasks > 0 ? runningTasks : '—'}
          label="Laufend"
          iconColor={runningTasks > 0 ? "text-blue-400" : "text-gray-600"}
          highlight={runningTasks > 0}
        />
      </div>

      {/* Datastores */}
      {pbs.datastores?.length > 0 && (
        <div className="space-y-3">
          <h3 className="text-sm font-semibold text-white">Datastores</h3>
          {pbs.datastores.map((ds) => {
            const usedPct = ds.total > 0 ? (ds.used / ds.total * 100) : 0
            const barColor = usedPct > 90 ? 'bg-red-500' : usedPct > 70 ? 'bg-yellow-500' : 'bg-green-500'
            const gc = pbs.gc?.find(g => g.datastore === ds.name)
            const mkKey = (a) => `${ds.name}-${a}`
            const ActionBtn = ({ action, label, cls }) => {
              const k = mkKey(action)
              const fb = feedback[k]
              return (
                <button
                  onClick={() => pbsAction(ds.name, action)}
                  disabled={loading[k]}
                  className={`flex-1 py-1.5 rounded text-sm font-semibold transition-all ${cls} disabled:opacity-50`}
                >
                  {loading[k] ? '...' : fb === 'ok' ? 'Gestartet' : fb === 'err' ? 'Fehler' : label}
                </button>
              )
            }
            return (
              <div key={ds.name} className="bg-[#1a2235] rounded-xl border border-gray-700/40 p-4 space-y-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <svg className="w-4 h-4 text-orange-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4" />
                    </svg>
                    <span className="text-white font-semibold">{ds.name}</span>
                  </div>
                  {ds.backup_count > 0 && <span className="text-sm text-gray-400">{ds.backup_count} Backups</span>}
                </div>
                <div>
                  <div className="flex justify-between text-xs text-gray-400 mb-1.5">
                    <span>{formatBytes(ds.used)} / {formatBytes(ds.total)}</span>
                    <span>{usedPct.toFixed(1)}%</span>
                  </div>
                  <div className="h-2 bg-gray-700 rounded-full overflow-hidden">
                    <div className={`h-full rounded-full ${barColor}`} style={{ width: `${Math.min(usedPct, 100)}%` }} />
                  </div>
                </div>
                {gc?.status && (
                  <div className="text-xs text-gray-500 flex gap-3">
                    <span>GC: <span className={gc.status === 'ok' ? 'text-green-400' : gc.status === 'running' ? 'text-blue-400' : 'text-gray-500'}>{gc.status}</span></span>
                    {gc.last_run > 0 && <span>Letzter Lauf: {formatTs(gc.last_run)}</span>}
                    {gc.duration > 0 && <span>({formatDuration(gc.duration)})</span>}
                  </div>
                )}
                <div className="flex gap-2 pt-1">
                  <ActionBtn action="gc"     label="GC"     cls="bg-yellow-600 hover:bg-yellow-500 text-white" />
                  <ActionBtn action="verify" label="Verify" cls="bg-gray-600 hover:bg-gray-500 text-white" />
                  <ActionBtn action="prune"  label="Prune"  cls="bg-orange-700 hover:bg-orange-600 text-white" />
                </div>
              </div>
            )
          })}
        </div>
      )}

      {/* Tasks */}
      {pbs.tasks?.length > 0 && (
        <div className="space-y-2">
          <h3 className="text-sm font-semibold text-white">Letzte Tasks</h3>
          <div className="bg-gray-800/50 rounded-lg border border-gray-700/50 overflow-hidden">
            <table className="w-full text-xs">
              <thead>
                <tr className="text-left text-gray-500 border-b border-gray-700">
                  <th className="px-4 py-2">Typ</th>
                  <th className="px-4 py-2">Start</th>
                  <th className="px-4 py-2">Dauer</th>
                  <th className="px-4 py-2 text-right">Status</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-700/50">
                {pbs.tasks.map((t, i) => (
                  <tr key={i} className={`hover:bg-gray-700/20 ${t.running ? 'bg-blue-900/10' : ''}`}>
                    <td className="px-4 py-2 font-mono">
                      <span className={t.running ? 'text-blue-300 font-semibold' : 'text-gray-300'}>{t.type || '—'}</span>
                      {t.running && <span className="ml-2 text-[10px] font-bold px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400 border border-blue-500/30">RUNNING</span>}
                    </td>
                    <td className="px-4 py-2 text-gray-400">{formatTs(t.start_time)}</td>
                    <td className="px-4 py-2 text-gray-400">{t.running ? <span className="text-blue-400 animate-pulse">läuft...</span> : formatDuration(t.duration)}</td>
                    <td className={`px-4 py-2 text-right font-medium ${taskStatusColor(t.status)}`}>{t.status || '—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  )
}
