import { useScope } from '@/business/scope/hooks';
import { getTenantInitials } from '@/business/scope/selectors';
import { useAuth } from '@/contexts/useAuth';

interface TenantBadgeProps {
  readonly collapsed?: boolean;
}

/**
 * Dynamic active-tenant badge — shows the logo (or initials) and name of the
 * tenant the signed-in user is scoped to (organization/school/campus/class),
 * plus the scope tier. Replaces the static campus-only badge.
 */
export function TenantBadge({ collapsed = false }: TenantBadgeProps) {
  const { user } = useAuth();
  const { tierLabel, activeTenant } = useScope(user);

  if (!activeTenant) {
    return null;
  }

  const mark = activeTenant.logo ? (
    <img
      src={activeTenant.logo}
      alt=""
      className="w-full h-full object-cover rounded-lg"
    />
  ) : (
    <span className="text-white font-bold text-xs">
      {getTenantInitials(activeTenant.name)}
    </span>
  );

  if (collapsed) {
    return (
      <div className="p-2 border-t border-slate-700/50 flex justify-center">
        <div
          className="w-9 h-9 rounded-lg bg-gradient-to-br from-violet-500 to-indigo-600 flex items-center justify-center shadow-md overflow-hidden"
          title={activeTenant.name ?? undefined}
        >
          {mark}
        </div>
      </div>
    );
  }

  return (
    <div className="p-3 border-t border-slate-700/50">
      <div className="bg-slate-800/40 rounded-xl p-3 border border-slate-700/40">
        <div className="flex items-center gap-2">
          <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-violet-500 to-indigo-600 flex items-center justify-center shadow-md overflow-hidden">
            {mark}
          </div>
          <div className="flex-1 min-w-0">
            <p className="text-sm font-bold text-slate-100 truncate">
              {activeTenant.name ?? 'Tenant'}
            </p>
            <p className="text-[10px] text-slate-500 uppercase tracking-wider">
              {tierLabel}
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
