// One agent chip. Two states:
//   state="idle"    — subdued, sits in the AgentsRow of a StationArea
//   state="engaged" — vivid, perches above its assigned task card
//
// Props:
//   agent     — { id, name, role } from station.agents
//   state     — "idle" | "engaged"
//   taskId    — when engaged, the task this chip is tethered to (used for the DOM key
//               and exposed as a data-attribute so TetherLayer can find it)
//   onOpen    — optional click handler; when set, the chip is interactive and opens
//               the agent detail modal. The handler stops propagation so an engaged
//               chip perched over a task card does NOT also open the task modal.

const AgentChip = ({ agent, state = 'idle', taskId = null, onOpen = null }) => {
  const { colorFor, TOKENS } = window.AgentColors || {};
  if (!colorFor || !TOKENS) return null;

  const colorName = colorFor(agent);
  const t = TOKENS[colorName];

  const initial = (agent.name || agent.id || '?').charAt(0).toUpperCase();

  const subdued = state === 'idle';
  const clickable = typeof onOpen === 'function';
  const wrapper = `inline-flex items-center gap-2 rounded-full pl-1 pr-3 py-1 border-2 transition ${
    subdued
      ? `bg-white ${t.border} opacity-60`
      : `${t.bg} ${t.border} shadow-sm`
  } ${clickable ? 'cursor-pointer hover:opacity-100 hover:shadow-md' : ''}`;
  const dot = `w-7 h-7 rounded-full ${t.bg} ${t.text} flex items-center justify-center text-xs font-bold ring-2 ring-white border ${t.border}`;
  const labelClass = `flex flex-col leading-tight ${t.text}`;

  // Stop propagation on BOTH click and pointerdown: an engaged chip is overlaid
  // on its task card, so without this the click/drag falls through to the card
  // (which opened the task modal — the bug this fixes).
  const handleClick = clickable
    ? (e) => { e.stopPropagation(); onOpen(agent); }
    : undefined;
  const stopDown = clickable ? (e) => e.stopPropagation() : undefined;

  return (
    <div
      className={wrapper}
      data-agent-id={agent.id}
      data-state={state}
      data-task-id={taskId || ''}
      onClick={handleClick}
      onPointerDown={stopDown}
      role={clickable ? 'button' : undefined}
      tabIndex={clickable ? 0 : undefined}
      onKeyDown={clickable ? (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); e.stopPropagation(); onOpen(agent); } } : undefined}
      aria-label={clickable ? `View ${agent.name} agent details` : undefined}
    >
      <div className={dot}>{initial}</div>
      <div className={labelClass}>
        <span className="text-[9px] font-bold uppercase tracking-widest opacity-70">
          {agent.role === 'Validator' ? 'Validator' : 'Agent'}
        </span>
        <span className="text-xs font-bold">{agent.name}</span>
      </div>
    </div>
  );
};

if (typeof window !== 'undefined') {
  window.AgentChip = AgentChip;
}
