import { useAuth } from "../../auth/AuthContext";
import { useRelayStatus } from "../../lib/useRelayStatus";
import { Badge } from "../ui/Badge";
import { Button } from "../ui/Button";
import { LogoutIcon } from "./icons";

function roleTone(role: string | undefined): "accent" | "ok" | "neutral" {
  if (role === "admin") return "accent";
  if (role === "operator") return "ok";
  return "neutral";
}

export function Topbar() {
  const { user, logout } = useAuth();
  const { live, checking } = useRelayStatus();

  const relayClass = live ? "relay relay--live" : "relay relay--down";
  const relayLabel = checking ? "probing" : live ? "live" : "offline";

  return (
    <header className="topbar">
      <div
        className={relayClass}
        title="GuruConnect relay connection"
        aria-label={`Relay ${relayLabel}`}
      >
        <span className="relay__pip" aria-hidden="true" />
        <span>Relay</span>
        <span className="relay__label mono">{relayLabel}</span>
      </div>

      <div className="topbar__spacer" />

      <div className="topbar__user">
        <div className="topbar__id">
          <span className="topbar__username">{user?.username}</span>
        </div>
        <Badge tone={roleTone(user?.role)}>{user?.role ?? "—"}</Badge>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => void logout()}
          aria-label="Log out"
        >
          <LogoutIcon width={15} height={15} />
          Logout
        </Button>
      </div>
    </header>
  );
}
