'use client';

import { Badge } from '@/components/ui/Primitives';
import { cn } from '@/lib/utils';
import { HERMES_INSTANCES, type HermesInstanceFilter, type HermesInstanceId } from '@/lib/hermes';
import { useHermesInstance } from '@/lib/hermes-instance-context';

const OPTIONS: Array<{ id: HermesInstanceFilter; label: string }> = [
  { id: 'all', label: 'All' },
  ...HERMES_INSTANCES.map((inst) => ({ id: inst.id, label: inst.label })),
];

interface HermesInstanceSwitcherProps {
  className?: string;
}

// Segmented control mounted in the Hermes layout header. Persists its
// selection via `useHermesInstance` (localStorage-backed); every Mission
// Control pane reads from the same hook.
export function HermesInstanceSwitcher({ className }: HermesInstanceSwitcherProps) {
  const { selectedInstance, setSelectedInstance } = useHermesInstance();

  return (
    <div
      role="radiogroup"
      aria-label="Hermes instance filter"
      className={cn(
        'inline-flex items-center gap-1 rounded-full border border-[var(--bl-border)] bg-[var(--bl-surface-card)] p-1 text-sm shadow-[var(--bl-shadow-sm)]',
        className,
      )}
    >
      {OPTIONS.map((option) => {
        const active = option.id === selectedInstance;
        return (
          <button
            key={option.id}
            type="button"
            role="radio"
            aria-checked={active}
            onClick={() => setSelectedInstance(option.id)}
            className={cn(
              'rounded-full px-3 py-1 transition-colors',
              active
                ? 'bg-[var(--bl-accent)] text-[var(--bl-text-on-accent,white)]'
                : 'text-[var(--bl-text-secondary)] hover:bg-[var(--bl-surface-muted)]',
            )}
          >
            {option.label}
          </button>
        );
      })}
    </div>
  );
}

// Small per-row badge so table cells can show which instance owns the entity.
// Use `'all'` for entities scoped to both instances (e.g. cross-cutting agents
// like Hermes Core, GitHub link).
const INSTANCE_LABEL: Record<HermesInstanceId | 'all', string> = {
  vijay: 'Vijay',
  bheem: 'Bheem',
  all: 'Both',
};

export function HermesInstanceBadge({ instanceId }: { instanceId: HermesInstanceId | 'all' }) {
  return <Badge variant="info">{INSTANCE_LABEL[instanceId]}</Badge>;
}
