صحح الكود
Future<void> _showSavedNumbersSelection() async {
  final hasPermission = await _requestPermissions();
  if (!hasPermission) return;

  final contacts = await FlutterContacts.getContacts(
    withProperties: true,
    withThumbnail: true,
  );
  final selectedNumbers = List<String>.from(_savedNumbers);

  final searchController = TextEditingController();
  var searchQuery = '';

  await showModalBottomSheet<void>(
    context: context,
    isScrollControlled: true,
    backgroundColor: Colors.transparent,
    builder: (context) {
      return Directionality(
        textDirection: TextDirection.rtl, // هذا السطر يجعل كل المحتوى RTL
        child: StatefulBuilder(
          builder: (context, setModal) {
            final filteredContacts = _filterContacts(contacts, searchQuery);

            return Container(
              height: MediaQuery.of(context).size.height * 0.9,
              decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.surface,
                borderRadius: const BorderRadius.vertical(
                  top: Radius.circular(24),
                ),
              padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).viewInsets.bottom,
              ),
              child: Column(
                children: [
                  // Header with search and title
                  Padding(
                    padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
                    child: Row(
                      textDirection: TextDirection.rtl, // تأكيد اتجاه النص للرأس
                      children: [
                        IconButton(
                          icon: Icon(Icons.close_rounded,
                              color: Theme.of(context).colorScheme.onSurface),
                          onPressed: () => Navigator.pop(context),
                          tooltip: 'إغلاق',
                        ),
                        const SizedBox(width: 8),
                        Expanded(
                          child: Text(
                            'اختر الأرقام المحفوظة',
                            textAlign: TextAlign.right, // محاذاة النص لليمين
                            style: Theme.of(context).textTheme.titleLarge?.copyWith(
                                  fontFamily: tajawalFont,
                                  fontWeight: FontWeight.bold,
                                ),
                          ),
                        ),
                      ],
                    ),
                  ),

                  // Search bar
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    child: TextField(
                      textAlign: TextAlign.right, // محاذاة نص البحث لليمين
                      controller: searchController,
                      decoration: InputDecoration(
                        suffixIcon: const Icon(Icons.search), // تغيير الأيقونة للجانب الأيمن
                        hintText: 'ابحث في جهات الاتصال أو الأرقام',
                        isDense: true,
                        filled: true,
                        fillColor: Theme.of(context).colorScheme.surfaceVariant,
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(12),
                          borderSide: BorderSide.none,
                        ),
                        contentPadding:
                            const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
                      ),
                      onChanged: (value) {
                        setModal(() {
                          searchQuery = value.trim();
                        });
                      },
                    ),
                  ),

                  const SizedBox(height: 8),

                  // Contacts count
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: Row(
                      textDirection: TextDirection.rtl,
                      children: [
                        Text(
                          '${filteredContacts.length} جهة اتصال',
                          style: Theme.of(context).textTheme.bodySmall?.copyWith(
                                fontFamily: tajawalFont,
                                color: Theme.of(context).colorScheme.onSurfaceVariant,
                              ),
                        ),
                        const Spacer(),
                        Text(
                          '${selectedNumbers.length} مختارة',
                          style: Theme.of(context).textTheme.bodySmall?.copyWith(
                                fontFamily: tajawalFont,
                                color: Theme.of(context).colorScheme.primary,
                              ),
                        ),
                      ],
                    ),
                  ),

                  const Divider(height: 24, thickness: 1),

                  // Contacts list
                  Expanded(
                    child: filteredContacts.isEmpty
                        ? _buildEmptyState(context)
                        : _buildContactsList(
                            context,
                            filteredContacts,
                            selectedNumbers,
                            setModal,
                          ),
                  ),

                  // Bottom buttons
                  _buildBottomButtons(context, selectedNumbers, setModal),
                ],
              ),
            );
          },
        ),
      );
    },
  );
}

// دالة مساعدة لتصفية جهات الاتصال
List<Contact> _filterContacts(List<Contact> contacts, String query) {
  if (query.isEmpty) return contacts;
  
  return contacts.where((contact) {
    final contactNameLower = contact.displayName.toLowerCase();
    final queryLower = query.toLowerCase();

    final phonesMatch = contact.phones.any(
      (phone) => phone.number.toLowerCase().contains(queryLower),
    );

    return contactNameLower.contains(queryLower) || phonesMatch;
  }).toList();
}

// بناء واجهة الحالة الفارغة
Widget _buildEmptyState(BuildContext context) {
  return Center(
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(Icons.contact_phone_outlined,
            size: 48,
            color: Theme.of(context).colorScheme.outline),
        const SizedBox(height: 16),
        Text(
          'لا توجد جهات اتصال تطابق البحث',
          textAlign: TextAlign.right,
          style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                fontFamily: tajawalFont,
                color: Theme.of(context).colorScheme.onSurfaceVariant,
              ),
        ),
      ],
    ),
  );
}

// بناء قائمة جهات الاتصال
Widget _buildContactsList(
  BuildContext context,
  List<Contact> contacts,
  List<String> selectedNumbers,
  StateSetter setModal,
) {
  return ListView.separated(
    keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
    physics: const ClampingScrollPhysics(),
    itemCount: contacts.length,
    separatorBuilder: (_, __) => const Divider(height: 1, indent: 72),
    itemBuilder: (context, index) {
      final contact = contacts[index];
      final phones = contact.phones;

      return Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: () => _toggleContactSelection(
            phones.first.number,
            selectedNumbers,
            setModal,
          ),
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            child: Row(
              textDirection: TextDirection.rtl, // اتجاه الصف من اليمين لليسار
              children: [
                // Contact avatar
                _buildContactAvatar(context, contact, selectedNumbers, phones),
                const SizedBox(width: 16),
                // Contact info
                _buildContactInfo(context, contact, phones),
              ],
            ),
          ),
        ),
      );
    },
  );
}

// بناء صورة جهة الاتصال
Widget _buildContactAvatar(
  BuildContext context,
  Contact contact,
  List<String> selectedNumbers,
  List<Phone> phones,
) {
  return Stack(
    children: [
      CircleAvatar(
        radius: 24,
        backgroundImage: (contact.thumbnail != null && contact.thumbnail!.isNotEmpty)
            ? MemoryImage(contact.thumbnail!)
            : null,
        child: (contact.thumbnail == null || contact.thumbnail!.isEmpty)
            ? Text(
                contact.initials(),
                style: const TextStyle(
                  fontFamily: tajawalFont,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                  fontSize: 18,
                ),
              )
            : null,
        backgroundColor: Theme.of(context).colorScheme.primary,
      ),
      if (_isContactSelected(phones, selectedNumbers))
        Positioned(
          left: 0, // تغيير الموضع لليسار بدلاً من اليمين
          bottom: 0,
          child: Container(
            padding: const EdgeInsets.all(4),
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.primary,
              shape: BoxShape.circle,
              border: Border.all(
                color: Theme.of(context).colorScheme.surface,
                width: 2,
              ),
            ),
            child: const Icon(Icons.check, size: 14, color: Colors.white),
          ),
        ),
    ],
  );
}

// بناء معلومات جهة الاتصال
Widget _buildContactInfo(BuildContext context, Contact contact, List<Phone> phones) {
  return Expanded(
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.end, // محاذاة النص لليمين
      children: [
        Text(
          contact.displayName,
          textAlign: TextAlign.right,
          style: const TextStyle(
            fontFamily: tajawalFont,
            fontSize: 16,
            fontWeight: FontWeight.w600,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        const SizedBox(height: 4),
        ...phones.map((phone) => Text(
              phone.number,
              textAlign: TextAlign.right,
              style: TextStyle(
                fontFamily: tajawalFont,
                fontSize: 14,
                color: Theme.of(context).colorScheme.onSurfaceVariant,
              ),
            )),
      ],
    ),
  );
}

// بناء أزرار القاع
Widget _buildBottomButtons(
  BuildContext context,
  List<String> selectedNumbers,
  StateSetter setModal,
) {
  return Container(
    padding: const EdgeInsets.all(16),
    decoration: BoxDecoration(
      color: Theme.of(context).colorScheme.surface,
      boxShadow: [
        BoxShadow(
          color: Colors.black.withOpacity(0.1),
          blurRadius: 8,
          offset: const Offset(0, -4),
        ),
      ],
    ),
    child: Row(
      textDirection: TextDirection.rtl, // اتجاه الصف من اليمين لليسار
      children: [
        Expanded(
          child: OutlinedButton(
            style: OutlinedButton.styleFrom(
              padding: const EdgeInsets.symmetric(vertical: 16),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
            ),
            onPressed: () => Navigator.pop(context),
            child: const Text(
              'إلغاء',
              style: TextStyle(fontFamily: tajawalFont),
            ),
          ),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: FilledButton(
            style: FilledButton.styleFrom(
              padding: const EdgeInsets.symmetric(vertical: 16),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
              backgroundColor: Theme.of(context).colorScheme.primary,
            ),
            onPressed: () async {
              _savedNumbers = List.from(selectedNumbers);
              await _saveSavedNumbers();
              Navigator.pop(context);
              _showSnackBar('تم حفظ الأرقام المختارة');
              if (mounted) setState(() {});
            },
            child: const Text(
              'حفظ التغييرات',
              style: TextStyle(
                fontFamily: tajawalFont,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
      ],
    ),
  );
}

// تبديل اختيار جهة الاتصال
void _toggleContactSelection(
  String phoneNumber,
  List<String> selectedNumbers,
  StateSetter setModal,
) {
  final normalized = phoneNumber.replaceAll(RegExp(r'[^\d+]'), '');

  setModal(() {
    if (selectedNumbers.any((num) {
      final n = num.replaceAll(RegExp(r'[^\d+]'), '');
      return n == normalized;
    })) {
      selectedNumbers.removeWhere((num) {
        final n = num.replaceAll(RegExp(r'[^\d+]'), '');
        return n == normalized;
      });
    } else {
      selectedNumbers.add(phoneNumber);
    }
  });
}

// التحقق مما إذا كانت جهة الاتصال مختارة
bool _isContactSelected(List<Phone> phones, List<String> selectedNumbers) {
  return phones.any((phone) {
    final normalized = phone.number.replaceAll(RegExp(r'[^\d+]'), '');
    return selectedNumbers.any((num) {
      final n = num.replaceAll(RegExp(r'[^\d+]'), '');
      return n == normalized;
    });
  });
}