import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { api } from '../../api/client';
import './VisualComponents.css';

export default function SystemStatusBar() {
  const [serverOk, setServerOk] = useState(true);
  const [agentTotal, setAgentTotal] = useState(0);
  const [agentOnline, setAgentOnline] = useState(0);
  const [buildCount, setBuildCount] = useState(0);

  useEffect(() => {
    const poll = async () => {
      try {
        await api.healthCheck();
        setServerOk(true);
      } catch {
        setServerOk(false);
      }
      try {
        const agents = await api.listAgents();
        setAgentTotal(agents.length);
        setAgentOnline(agents.filter((a) => a.status === 'online').length);
      } catch {
        setAgentTotal(0);
        setAgentOnline(0);
      }
      try {
        const builds = await api.listBuilds();
        setBuildCount(builds.length);
      } catch {
        setBuildCount(0);
      }
    };
    poll();
    const id = setInterval(poll, 15000);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="system-status-bar">
      <span className={`status-pill ${serverOk ? 'ok' : 'bad'}`}>
        <span className="status-pill-dot" />
        SERVER {serverOk ? 'UP' : 'DOWN'}
      </span>
      <span className={`status-pill ${agentOnline > 0 ? 'ok' : agentTotal > 0 ? 'warn' : ''}`}>
        <span className="status-pill-dot" />
        FLEET {agentOnline}/{agentTotal} ONLINE
      </span>
      <span className={`status-pill ${buildCount > 0 ? 'ok' : 'warn'}`}>
        <span className="status-pill-dot" />
        {buildCount} BUILD{buildCount === 1 ? '' : 'S'}
      </span>
      <Link to="/guide" className="status-pill" style={{ marginLeft: 'auto', textDecoration: 'none', color: 'var(--neon-cyan)' }}>
        📖 GUIDE
      </Link>
    </div>
  );
}
