/**
 * RoleBadge — small visual showing a user's effective roles.
 *
 * Phase 1 PR 1 (2026-07-22).
 *
 * Renders the primary role as a solid chip plus any auxiliary roles as
 * outline chips. Used on the user detail page and the avatar dropdown so
 * admins can see at a glance what a user is actually allowed to do.
 *
 * Pure presentational — reads from props, no store access. Pass the user
 * object straight from the auth store or from a /api/users fetch.
 */

import React from 'react';
import { Shield } from 'lucide-react';

interface RoleBadgeProps {
  role: string;
  effective_roles?: string[];
  size?: 'sm' | 'md';
  className?: string;
}

const PRIMARY_BG: Record<string, string> = {
  school_admin: 'bg-indigo-500 text-white',
  systems_admin: 'bg-slate-800 text-white',
  teacher: 'bg-emerald-500 text-white',
  student: 'bg-blue-500 text-white',
  parent: 'bg-amber-500 text-white',
  principal: 'bg-purple-500 text-white',
  hr: 'bg-rose-500 text-white',
  bursar: 'bg-cyan-500 text-white',
  librarian: 'bg-amber-700 text-white',
  nurse: 'bg-pink-500 text-white',
  clubs_head: 'bg-lime-600 text-white',
  dining_staff: 'bg-orange-500 text-white',
  driver: 'bg-stone-500 text-white',
  groundsman: 'bg-stone-600 text-white',
  matron: 'bg-fuchsia-500 text-white',
  boarding_master: 'bg-violet-500 text-white',
  security: 'bg-red-700 text-white',
  janitor: 'bg-zinc-500 text-white',
  accountant: 'bg-teal-500 text-white',
};

const humanLabel = (role: string) =>
  role.split('_').map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join(' ');

export const RoleBadge: React.FC<RoleBadgeProps> = ({ role, effective_roles, size = 'md', className = '' }) => {
  const aux = (effective_roles || []).filter((r) => r !== role);
  const sizing = size === 'sm' ? 'px-2 py-0.5 text-[0.65rem]' : 'px-2.5 py-1 text-xs';
  return (
    <div className={`inline-flex flex-wrap items-center gap-1.5 ${className}`}>
      <span
        className={`inline-flex items-center gap-1 rounded-full font-bold uppercase tracking-wider ${sizing} ${PRIMARY_BG[role] || 'bg-zinc-500 text-white'}`}
        title="Primary role"
      >
        <Shield size={size === 'sm' ? 10 : 12} />
        {humanLabel(role)}
      </span>
      {aux.map((r) => (
        <span
          key={r}
          className={`inline-flex items-center rounded-full font-bold uppercase tracking-wider border ${sizing} border-current/30 text-text-secondary`}
          title={`Auxiliary role: ${humanLabel(r)}`}
        >
          + {humanLabel(r)}
        </span>
      ))}
    </div>
  );
};

export default RoleBadge;
