const STATUS_COLOR = {
  online:  'bg-ap-green',
  warning: 'bg-ap-yellow',
  offline: 'bg-ap-red',
};

function barColor(pct) {
  if (pct > 80) return 'bg-ap-red';
  if (pct >= 50) return 'bg-ap-yellow';
  return 'bg-ap-green';
}

function MetricBar({ label, value }) {
  return (
    <div className="flex items-center gap-2">
      <span className="font-mono text-[10px] text-ap-silver-dim w-7 shrink-0">
        {label}
      </span>
      <div className="flex-1 h-1 bg-white/10">
        <div
          className={`h-full ${barColor(value)}`}
          style={{ width: `${Math.min(value, 100)}%` }}
        />
      </div>
      <span className="font-mono text-[10px] text-ap-silver-dim w-8 text-right shrink-0">
        {value}%
      </span>
    </div>
  );
}

function SystemCard({ system }) {
  const { name, status, cpu, mem, uptime } = system;

  return (
    <div className="bg-ap-dark p-2.5 border border-white/5">
      {/* Name + status dot */}
      <div className="flex items-center justify-between gap-2 mb-2">
        <span className="font-mono text-xs font-semibold truncate text-ap-silver">
          {name}
        </span>
        <span
          className={`inline-block w-2 h-2 shrink-0 ${STATUS_COLOR[status] ?? 'bg-ap-silver-dim'}`}
        />
      </div>

      {/* Metrics */}
      <div className="flex flex-col gap-1.5">
        <MetricBar label="CPU" value={cpu} />
        <MetricBar label="MEM" value={mem} />
      </div>

      {/* Uptime */}
      <p className="font-mono text-[10px] text-ap-silver-dim mt-2">
        UP: {uptime}
      </p>
    </div>
  );
}

export default function SystemHealth({ systems }) {
  return (
    <div className="panel h-full flex flex-col">
      {/* Header */}
      <div className="panel-header">
        <span className="dot" />
        <span>System Health</span>
      </div>

      {/* Grid */}
      <div className="grid grid-cols-2 gap-2 p-3 flex-1 content-start">
        {systems.map((system) => (
          <SystemCard key={system.name} system={system} />
        ))}
      </div>
    </div>
  );
}
