import { Wifi, WifiOff, Loader2, AlertTriangle } from "lucide-react";

type State = "idle" | "connecting" | "open" | "reconnecting" | "closed";

export function ConnectionPill({
  label,
  state,
  attempt = 0,
}: {
  label: string;
  state: State;
  attempt?: number;
}) {
  const cfg = {
    open: { icon: Wifi, cls: "border-bull/40 bg-bull-soft text-bull", text: "Live" },
    connecting: { icon: Loader2, cls: "border-warning/40 bg-warning/10 text-warning", text: "Connecting" },
    reconnecting: {
      icon: Loader2,
      cls: "border-warning/40 bg-warning/10 text-warning",
      text: `Reconnecting${attempt > 1 ? ` · #${attempt}` : ""}`,
    },
    idle: { icon: WifiOff, cls: "border-border bg-muted text-muted-foreground", text: "Idle" },
    closed: { icon: AlertTriangle, cls: "border-bear/40 bg-bear-soft text-bear", text: "Offline" },
  }[state];
  const Icon = cfg.icon;
  const spin = state === "connecting" || state === "reconnecting";
  return (
    <span
      className={`inline-flex items-center gap-1.5 rounded-md border px-2 py-1 text-[10px] font-semibold uppercase tracking-wider ${cfg.cls}`}
      title={`${label}: ${cfg.text}`}
    >
      <span className="relative flex h-1.5 w-1.5">
        {state === "open" && (
          <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-bull opacity-75" />
        )}
        <span
          className={`relative inline-flex h-1.5 w-1.5 rounded-full ${
            state === "open" ? "bg-bull" : state === "closed" ? "bg-bear" : "bg-warning"
          }`}
        />
      </span>
      <Icon className={`h-3 w-3 ${spin ? "animate-spin" : ""}`} />
      <span>
        {label} · {cfg.text}
      </span>
    </span>
  );
}
