import { useEffect, useState } from 'react';
import { api } from '../../api/client';
import ComradeIndicators from '../Presence/ComradeIndicators';
import { usePresence } from '../../context/PresenceContext';
import '../Presence/Presence.css';
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);
  const { othersOnline } = usePresence();

  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${othersOnline ? ' system-status-bar--comrades-online' : ''}`}>
      <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>
      <ComradeIndicators />
      <a
        href="/docs/"
        target="_blank"
        rel="noopener noreferrer"
        className="status-pill"
        style={{ textDecoration: 'none', color: 'var(--neon-cyan)' }}
      >
        📖 DOCS
      </a>
    </div>
  );
}
