import { Link } from '@tanstack/react-router';
import { X } from 'lucide-react';
import { useSessionStore } from '@/stores/sessionStore';
import { leaveRoom } from '@/lib/sync/wsSync';

/** Header chip shown while connected as a player, with a link back to the table + Leave. */
export function PlayerSessionBadge() {
  const intent = useSessionStore((s) => s.joinIntent);
  const status = useSessionStore((s) => s.status);
  const role = useSessionStore((s) => s.role);
  if (!intent || role === 'gm') return null;
  const label = status === 'connected' ? 'Live' : status === 'connecting' ? 'Connecting…' : status;
  return (
    <div data-testid="player-live" className="flex items-center gap-1 rounded-md border border-success/40 bg-success/5 px-2 py-1 text-xs">
      <span className={`inline-flex items-center gap-1 ${status === 'connected' ? 'text-success' : 'text-muted'}`}>
        <span className={`inline-block h-1.5 w-1.5 rounded-full ${status === 'connected' ? 'bg-success' : 'bg-muted'}`} aria-hidden />{label}
      </span>
      <Link to="/play" className="font-mono font-semibold text-accent" title="Open the table">{intent.joinCode}</Link>
      <button onClick={leaveRoom} className="px-1 text-danger" title="Leave session" aria-label="Leave session"><X size={13} aria-hidden /></button>
    </div>
  );
}
