import { formatLastSeen, useConnectionStore } from '@/live';
import { cn } from '@/lib/utils';

/**
 * Subtle WS-status indicator. Sits bottom-left of the monitor route.
 *
 * Three visible states:
 * - **Connected** — small green dot + muted "Live" label.
 * - **Connecting / reconnecting** — amber pulsing dot + status word.
 * - **Disconnected** — red dot + "Offline · last live HH:MM" so the
 *   operator can see how long the gap has been.
 *
 * Designed to be ignorable when everything's fine and unmissable when
 * it isn't — same posture as the design system's "live" pulse.
 */
export function ConnectionChip() {
  const status = useConnectionStore((s) => s.status);
  const lastConnectedAt = useConnectionStore((s) => s.lastConnectedAt);

  return (
    <div
      className={cn(
        'absolute bottom-3 left-3 z-10 flex items-center gap-2',
        'bg-background/90 backdrop-blur-sm border border-border rounded-md px-2.5 py-1.5 shadow-sm',
        'text-xs',
      )}
      aria-live="polite"
      role="status"
    >
      {status === 'connected' && (
        <>
          <span className="size-2 rounded-full bg-green-600" aria-hidden />
          <span className="text-muted-foreground">Live</span>
        </>
      )}
      {(status === 'connecting' || status === 'reconnecting') && (
        <>
          <span className="size-2 rounded-full bg-amber-500 animate-pulse" aria-hidden />
          <span className="text-muted-foreground">
            {status === 'connecting' ? 'Connecting…' : 'Reconnecting…'}
          </span>
        </>
      )}
      {status === 'disconnected' && (
        <>
          <span className="size-2 rounded-full bg-destructive" aria-hidden />
          <span className="text-destructive">
            Offline
            {lastConnectedAt ? <> · last live {formatLastSeen(lastConnectedAt)}</> : null}
          </span>
        </>
      )}
    </div>
  );
}
