import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:mohem_flutter_app/api/login_api_client.dart'; import 'package:mohem_flutter_app/api/offers_and_discounts_api_client.dart'; import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/colors.dart'; import 'package:mohem_flutter_app/classes/consts.dart'; import 'package:mohem_flutter_app/classes/utils.dart'; import 'package:mohem_flutter_app/config/routes.dart'; import 'package:mohem_flutter_app/extensions/int_extensions.dart'; import 'package:mohem_flutter_app/extensions/string_extensions.dart'; import 'package:mohem_flutter_app/generated/locale_keys.g.dart'; import 'package:mohem_flutter_app/models/offers_and_discounts/wala_plus_category_model.dart'; import 'package:mohem_flutter_app/models/offers_and_discounts/wala_plus_retailer_model.dart'; import 'package:mohem_flutter_app/widgets/info_chip_widget.dart'; import 'package:shimmer/shimmer.dart'; class DashboardScreenForDependet extends StatefulWidget { const DashboardScreenForDependet({Key? key}) : super(key: key); @override State createState() => _DashboardScreenForDependetState(); } class _DashboardScreenForDependetState extends State { List retailersList = []; List _filteredRetailersList = []; List categoriesList = []; String currentCategoryId = ""; String selectedTypeFilter = "all"; bool isNearestOffers = true; bool isLoading = true; bool isLoadingMore = false; bool isCategoriesLoading = true; bool hasMore = true; bool _isFetchingPage = false; int currentPage = 1; int totalPages = 1; final int pageSize = 10; String searchQuery = ""; final TextEditingController _searchController = TextEditingController(); final ScrollController _scrollController = ScrollController(); bool _hasRegisteredMobileLoginInfo = false; List get _availableTypeFilters { Set types = {}; for (WalaPlusRetailerModel r in retailersList) { String? t = r.normalizedType; if (t != null && t.isNotEmpty) { types.add(t); } } List list = ['all', 'instore', 'online']; for (String t in types) { if (!list.contains(t)) { list.add(t); } } return list; } String _getTypeFilterTitle(String type) { if (type == 'all') { return LocaleKeys.allCategories.tr(); } else if (type == 'instore') { return LocaleKeys.inStore.tr(); } else if (type == 'online') { return LocaleKeys.online.tr(); } return type.isNotEmpty ? (type[0].toUpperCase() + type.substring(1)) : type; } IconData _getTypeFilterIcon(String type) { if (type == 'instore') { return Icons.storefront_rounded; } else if (type == 'online') { return Icons.language_rounded; } return Icons.tune_rounded; } @override void initState() { super.initState(); _scrollController.addListener(_scrollListener); _loadDependentName(); WidgetsBinding.instance.addPostFrameCallback((_) async { if (mounted) { await _registerMobileLoginInfo(); await fetchCategories(); await fetchOffers(categoryId: currentCategoryId.isEmpty ? "all" : currentCategoryId); } }); } Future _registerMobileLoginInfo() async { if (_hasRegisteredMobileLoginInfo) return; if (!ApiConsts.isDependetLogin) return; _hasRegisteredMobileLoginInfo = true; try { int loginType = AppState().dependentLoginType ?? 1; String nationalId = AppState().getUserName ?? ""; String dob = AppState().dependentDob ?? ""; String name = AppState().dependentName ?? ""; String mobile = AppState().postParamsObject?.mobileNumber ?? ""; String tokenID = (AppState().postParamsObject?.tokenID != null && AppState().postParamsObject!.tokenID!.isNotEmpty) ? AppState().postParamsObject!.tokenID! : (AppState().authenticationTokenID ?? ""); if (tokenID.isEmpty) { tokenID = await Utils.getStringFromPrefs("P_DEP_TOKEN_ID"); } int sessionId = AppState().postParamsObject?.pSessionId ?? 0; String email = AppState().postParamsObject?.pEmailAddress ?? ""; String deviceToken = AppState().getIsHuawei ? AppState().getHuaweiPushToken : (AppState().getDeviceToken ?? ""); await LoginApiClient().insertMobileLoginInfoDependent( loginType: loginType, nationalId: nationalId, dob: dob, dependentName: name, mobileNumber: mobile, tokenID: tokenID, sessionId: sessionId, email: email, deviceToken: deviceToken, context: context, ); } catch (e) { if (kDebugMode) { print("Error calling insertMobileLoginInfoDependent: $e"); } } } void _loadDependentName() { if (AppState().dependentName != null && AppState().dependentName!.isNotEmpty && mounted) { setState(() {}); } } @override void dispose() { _scrollController.removeListener(_scrollListener); _scrollController.dispose(); _searchController.dispose(); super.dispose(); } void _scrollListener() { if (!_scrollController.hasClients) return; double maxScroll = _scrollController.position.maxScrollExtent; double currentScroll = _scrollController.position.pixels; // Trigger only when user scrolls to within 35px of the very bottom if (currentScroll >= maxScroll - 35) { if (!isLoading && !isLoadingMore && !_isFetchingPage && hasMore) { fetchNextPage(); } } } Future fetchCategories() async { setState(() { isCategoriesLoading = true; }); try { List list = await OffersAndDiscountsApiClient().getWalaPlusCategories(context: context); if (list.isEmpty) { await Future.delayed(const Duration(milliseconds: 600)); list = await OffersAndDiscountsApiClient().getWalaPlusCategories(context: context); } if (mounted) { List fullList = []; bool hasAll = list.any((c) => (c.id == "all" || c.name?.toLowerCase() == "all" || c.name == "الجميع" || c.name == "الكل")); if (!hasAll) { fullList.add(WalaPlusCategoryModel(id: "all", name: LocaleKeys.allCategories.tr())); } fullList.addAll(list); setState(() { categoriesList = fullList; if (currentCategoryId.isEmpty) { currentCategoryId = "all"; } }); } } catch (e) { debugPrint("Error fetching WalaPlus categories (attempt 1): $e"); try { await Future.delayed(const Duration(milliseconds: 600)); List retryList = await OffersAndDiscountsApiClient().getWalaPlusCategories(context: context); if (mounted && retryList.isNotEmpty) { List fullList = []; bool hasAll = retryList.any((c) => (c.id == "all" || c.name?.toLowerCase() == "all" || c.name == "الجميع" || c.name == "الكل")); if (!hasAll) { fullList.add(WalaPlusCategoryModel(id: "all", name: LocaleKeys.allCategories.tr())); } fullList.addAll(retryList); setState(() { categoriesList = fullList; if (currentCategoryId.isEmpty) { currentCategoryId = "all"; } }); return; } } catch (retryEx) { debugPrint("Error fetching WalaPlus categories (attempt 2): $retryEx"); } if (mounted && categoriesList.isEmpty) { setState(() { categoriesList = [WalaPlusCategoryModel(id: "all", name: LocaleKeys.allCategories.tr())]; if (currentCategoryId.isEmpty) { currentCategoryId = "all"; } }); } } finally { if (mounted) { setState(() { isCategoriesLoading = false; }); } } } Future fetchOffers({String? categoryId}) async { String targetCategoryId = categoryId ?? (currentCategoryId.isEmpty ? "all" : currentCategoryId); setState(() { isLoading = true; currentPage = 1; hasMore = true; }); try { String catParam = (targetCategoryId == "all" || targetCategoryId == "0") ? "" : targetCategoryId; print("Fetching WalaPlus retailers: category='$catParam', page=1, per_page=$pageSize"); WalaPlusRetailersResponse? response = await OffersAndDiscountsApiClient().getWalaPlusRetailers( categoryId: catParam, page: 1, perPage: pageSize, geoLocation: isNearestOffers ? "24.9485,46.977" : null, context: context, ); retailersList = response?.retailers ?? []; currentPage = 1; totalPages = response?.pagesCount ?? 1; hasMore = currentPage < totalPages && (response?.retailers?.isNotEmpty ?? false); _runFilter(_searchController.text); } catch (e) { print("Error fetching WalaPlus retailers: $e"); retailersList = []; _runFilter(_searchController.text); } finally { if (mounted) { setState(() { isLoading = false; }); } } } Future fetchNextPage() async { if (isLoading || isLoadingMore || _isFetchingPage || !hasMore) return; _isFetchingPage = true; setState(() { isLoadingMore = true; }); try { int nextPage = currentPage + 1; String catParam = (currentCategoryId == "all" || currentCategoryId == "0") ? "" : currentCategoryId; print("Fetching WalaPlus retailers next page: $nextPage of $totalPages, category: '$catParam'"); WalaPlusRetailersResponse? response = await OffersAndDiscountsApiClient().getWalaPlusRetailers( categoryId: catParam, page: nextPage, perPage: pageSize, geoLocation: isNearestOffers ? "24.9485,46.977" : null, context: context, ); List newRetailers = response?.retailers ?? []; if (newRetailers.isNotEmpty) { currentPage = nextPage; totalPages = response?.pagesCount ?? totalPages; hasMore = currentPage < totalPages; retailersList.addAll(newRetailers); _runFilter(_searchController.text); } else { hasMore = false; } } catch (e) { print("Error fetching next page of WalaPlus retailers: $e"); } finally { _isFetchingPage = false; if (mounted) { setState(() { isLoadingMore = false; }); } } } Future _onRefresh() async { await Future.wait([fetchCategories(), fetchOffers(categoryId: currentCategoryId.isEmpty ? "all" : currentCategoryId)]); } void _runFilter([String? query]) { if (query != null) { searchQuery = query; } List temp = retailersList; if (selectedTypeFilter != "all" && selectedTypeFilter.isNotEmpty) { temp = temp.where((WalaPlusRetailerModel item) { String? norm = item.normalizedType; if (selectedTypeFilter == "online") { return norm == "online"; } else if (selectedTypeFilter == "instore") { return norm == "instore"; } else { return norm == selectedTypeFilter || (item.type?.trim().toLowerCase() == selectedTypeFilter); } }).toList(); } if (searchQuery.trim().isNotEmpty) { String q = searchQuery.trim().toLowerCase(); temp = temp.where((WalaPlusRetailerModel item) { String name = (item.name ?? "").toLowerCase(); String title = (item.offerTitle ?? "").toLowerCase(); String desc = (item.description ?? "").toLowerCase(); String city = item.displayCity.toLowerCase(); return name.contains(q) || title.contains(q) || desc.contains(q) || city.contains(q); }).toList(); } _filteredRetailersList = temp; setState(() {}); } void _openRetailer(WalaPlusRetailerModel item) { Navigator.pushNamed(context, AppRoutes.walaPlusRetailerDetails, arguments: item); } void _performLogout() { Utils.confirmDialog( context, LocaleKeys.areYouSureWantToLogOut.tr(), onTap: () { ApiConsts.selectedMemberType = MemberType.employee; ApiConsts.ISDependetLogin = false; AppState().setPostParamsInitConfig(); Navigator.pushNamedAndRemoveUntil(context, AppRoutes.login, (Route route) => false); }, ); } @override Widget build(BuildContext context) { bool isAr = AppState().isArabic(context); return Scaffold( backgroundColor: Colors.white, appBar: AppBar( backgroundColor: Colors.white, elevation: 0, surfaceTintColor: Colors.transparent, automaticallyImplyLeading: false, titleSpacing: 0, title: Padding( padding: const EdgeInsets.symmetric(horizontal: 16), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ InkWell( borderRadius: BorderRadius.circular(10), onTap: () { if (Navigator.canPop(context)) { Navigator.pop(context); } else { _performLogout(); } }, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 8), child: Icon(isAr ? Icons.arrow_forward_ios_rounded : Icons.arrow_back_ios_new_rounded, size: 20, color: const Color(0xFF1E293B)), ), ), const SizedBox(width: 8), SvgPicture.asset("assets/icons/mazaya_brand.svg", height: 48, fit: BoxFit.contain), ], ), Row( mainAxisSize: MainAxisSize.min, children: [ if (!ApiConsts.isDependetLogin) ...[ IconButton( icon: Image.asset( 'assets/icons/ic_add_dependents.png', width: 24, height: 24, color: const Color(0xFF1E293B), errorBuilder: (context, error, stackTrace) => SvgPicture.asset('assets/icons/ic_dependents_top.svg', width: 24, height: 24, colorFilter: const ColorFilter.mode(Color(0xFF1E293B), BlendMode.srcIn)), ), tooltip: LocaleKeys.addDependents.tr(), onPressed: () { Navigator.pushNamed(context, AppRoutes.familyMembers, arguments: {'fromMazaya': true}); }, ), ], IconButton( icon: const Icon(Icons.home_rounded, size: 26, color: Color(0xFF1E293B)), onPressed: () { if (ApiConsts.isDependetLogin) { _onRefresh(); } else { Navigator.popUntil(context, ModalRoute.withName(AppRoutes.dashboard)); } }, ), ], ), ], ), ), ), body: SafeArea( child: RefreshIndicator( onRefresh: _onRefresh, color: MyColors.textMixColor, child: SingleChildScrollView( controller: _scrollController, physics: const AlwaysScrollableScrollPhysics(parent: BouncingScrollPhysics()), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Search Input Card _buildSearchBar(isAr), // "Browse Categories" Header _buildBrowseCategoriesHeader(isAr), // Categories Section if (categoriesList.isNotEmpty) _buildCategoriesList(isAr) else _buildCategoriesShimmer(), // Type Filter Chips (All, In Store, Online) _buildTypeFilterChips(isAr), const SizedBox(height: 16), // Offers Grid if (isLoading) _buildRetailersShimmer() else if (_filteredRetailersList.isNotEmpty) ...[ GridView.builder( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 0.85, crossAxisSpacing: 12, mainAxisSpacing: 16), itemCount: _filteredRetailersList.length, itemBuilder: (context, index) { return _buildOfferCard(_filteredRetailersList[index], isAr); }, ), if (isLoadingMore) ...[ 16.height, Center(child: Padding(padding: const EdgeInsets.symmetric(vertical: 12), child: Image.asset("assets/images/logos/loading_mohemm_logo.gif", height: 48.0, width: 48.0))), ], ] else Padding(padding: const EdgeInsets.only(top: 40), child: Center(child: LocaleKeys.noOffersAvailable.tr().toText14(color: const Color(0xFF64748B)))), ], ), ), ), ), ); } Widget _buildSearchBar(bool isAr) { return Container( width: double.infinity, height: 70, padding: const EdgeInsets.only(top: 14, right: 16, bottom: 14, left: 16), decoration: BoxDecoration( color: const Color(0xFFFFFFFF), borderRadius: BorderRadius.circular(16), border: Border.all(color: const Color(0xFFE8E8E8), width: 1.0), boxShadow: [BoxShadow(color: const Color(0xFF000000).withOpacity(0.0314), offset: const Offset(0, 2), blurRadius: 5, spreadRadius: 0)], ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ LocaleKeys.search.tr().toText12(isBold: true, color: const Color(0xFF2A333C)), const SizedBox(height: 2), TextField( controller: _searchController, onChanged: _runFilter, decoration: InputDecoration( isDense: true, contentPadding: EdgeInsets.zero, hintText: LocaleKeys.searchItems.tr(), hintStyle: const TextStyle(color: Color(0xFFACAFB1), fontSize: 14, fontWeight: FontWeight.w400, height: 1.2), border: InputBorder.none, ), style: const TextStyle(color: Color(0xFF2A333C), fontSize: 14, fontWeight: FontWeight.w400), ), ], ), ); } Widget _buildBrowseCategoriesHeader(bool isAr) { return Padding(padding: const EdgeInsets.only(top: 22, bottom: 14), child: LocaleKeys.browseCategories.tr().toText18(isBold: true, color: const Color(0xFF1E293B))); } Widget _buildCategoriesList(bool isAr) { return SizedBox( height: 136.0, width: double.infinity, child: ListView.separated( scrollDirection: Axis.horizontal, physics: const BouncingScrollPhysics(), padding: EdgeInsets.zero, itemCount: categoriesList.length, separatorBuilder: (_, __) => const SizedBox(width: 14), itemBuilder: (BuildContext context, int index) { WalaPlusCategoryModel item = categoriesList[index]; bool isSelected = (item.id == "all" && (currentCategoryId == "all" || currentCategoryId.isEmpty)) || (currentCategoryId.isNotEmpty && currentCategoryId == item.id); String title = (item.id == "all") ? LocaleKeys.allCategories.tr() : (item.name ?? ""); return InkWell( borderRadius: BorderRadius.circular(18), onTap: () { if (currentCategoryId != item.id) { setState(() { currentCategoryId = item.id ?? ""; }); fetchOffers(categoryId: currentCategoryId); } }, child: SizedBox( width: 84, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ _buildCategoryCard(item, isSelected), const SizedBox(height: 8), title.toText13( // isBold: true, color: const Color(0xFF1E293B), maxlines: 2, overflow: TextOverflow.ellipsis, ), ], ), ), ); }, ), ); } Widget _buildTypeFilterChips(bool isAr) { List types = _availableTypeFilters; return Padding( padding: const EdgeInsets.only(top: 14, bottom: 2), child: SizedBox( height: 38, child: ListView.separated( scrollDirection: Axis.horizontal, physics: const BouncingScrollPhysics(), itemCount: types.length, separatorBuilder: (BuildContext _, int __) => const SizedBox(width: 8), itemBuilder: (BuildContext context, int index) { String typeKey = types[index]; bool isSelected = selectedTypeFilter == typeKey; String title = _getTypeFilterTitle(typeKey); IconData icon = _getTypeFilterIcon(typeKey); return InkWell( borderRadius: BorderRadius.circular(6), onTap: () { if (selectedTypeFilter != typeKey) { setState(() { selectedTypeFilter = typeKey; }); _runFilter(); } }, child: Container( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), alignment: Alignment.center, decoration: BoxDecoration(borderRadius: BorderRadius.circular(6), color: isSelected ? MyColors.darkIconColor : MyColors.lightGreyEAColor), child: Row( mainAxisSize: MainAxisSize.min, children: [ Icon(icon, size: 14, color: isSelected ? MyColors.white : MyColors.black), const SizedBox(width: 5), title.toText12(color: isSelected ? MyColors.white : MyColors.black), ], ), ), ); }, ), ), ); } Widget _buildCategoryCard(WalaPlusCategoryModel item, bool isSelected) { const double cardSize = 84.0; const double borderRadiusVal = 18.0; const double borderWidthVal = 2.8; const Color activeBorderColor = Color(0xFF00A86B); bool isAll = (item.id == "all" || item.id == "0" || (item.name ?? "").toLowerCase() == "all" || item.name == "الجميع" || item.name == "الكل"); Widget imageContent; if (isAll) { imageContent = Image.asset('assets/images/cat_all.png', width: double.infinity, height: double.infinity, fit: BoxFit.cover, errorBuilder: (_, __, ___) => _getFallbackCategoryAsset(item)); } else { String categoryImageUrl = item.categoryImageUrl.isNotEmpty ? item.categoryImageUrl : (item.image?.trim() ?? ""); if (categoryImageUrl.isNotEmpty) { if (categoryImageUrl.toLowerCase().endsWith('.svg') || item.isSvg) { imageContent = SvgPicture.network( categoryImageUrl, width: double.infinity, height: double.infinity, fit: BoxFit.cover, placeholderBuilder: (_) => const Center(child: SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2, color: Color(0xFF00A86B)))), ); } else { imageContent = Image.network(categoryImageUrl, width: double.infinity, height: double.infinity, fit: BoxFit.cover, errorBuilder: (_, __, ___) => _getFallbackCategoryAsset(item)); } } else { imageContent = _getFallbackCategoryAsset(item); } } return Container( width: cardSize, height: cardSize, decoration: BoxDecoration( color: Colors.transparent, borderRadius: BorderRadius.circular(borderRadiusVal), border: isSelected ? Border.all(color: activeBorderColor, width: borderWidthVal) : null, ), child: ClipRRect(borderRadius: BorderRadius.circular(isSelected ? (borderRadiusVal - borderWidthVal) : borderRadiusVal), child: imageContent), ); } Widget _getFallbackCategoryAsset(WalaPlusCategoryModel item) { String name = (item.name ?? "").toLowerCase(); if (item.id == "all" || item.id == "0" || name == "all" || name == "الكل" || name == "الجميع") { return Image.asset('assets/images/cat_all.png', width: double.infinity, height: double.infinity, fit: BoxFit.cover, errorBuilder: (_, __, ___) => _buildFallbackCategoryIconWidget(item)); } else if (name.contains("shop") || name.contains("retail") || name.contains("تسوق") || name.contains("تجزئة")) { return Image.asset('assets/images/cat_retail.png', width: double.infinity, height: double.infinity, fit: BoxFit.cover, errorBuilder: (_, __, ___) => _buildFallbackCategoryIconWidget(item)); } else if (name.contains("food") || name.contains("restaurant") || name.contains("مطاعم") || name.contains("أغذية") || name.contains("cafe") || name.contains("مقهى")) { return Image.asset('assets/images/cat_food.png', width: double.infinity, height: double.infinity, fit: BoxFit.cover, errorBuilder: (_, __, ___) => _buildFallbackCategoryIconWidget(item)); } else if (name.contains("fitness") || name.contains("wellness") || name.contains("sport") || name.contains("gym") || name.contains("رياضة") || name.contains("لياقة") || name.contains("صحة")) { return Image.asset('assets/images/cat_fitness.png', width: double.infinity, height: double.infinity, fit: BoxFit.cover, errorBuilder: (_, __, ___) => _buildFallbackCategoryIconWidget(item)); } return _buildFallbackCategoryIconWidget(item); } Widget _buildFallbackCategoryIconWidget(WalaPlusCategoryModel item) { return Container(color: Colors.transparent, alignment: Alignment.center, child: _getFallbackCategoryIcon(item, const Color(0xFF168A89))); } Widget _getFallbackCategoryIcon(WalaPlusCategoryModel item, Color iconColor) { String name = (item.name ?? "").toLowerCase(); IconData iconData = Icons.grid_view_rounded; Color color = iconColor; if (item.id == "all" || name == "all" || name == "الكل" || name == "الجميع") { iconData = Icons.confirmation_number_outlined; color = const Color(0xFFE52332); } else if (name.contains("finance") || name.contains("بنوك") || name.contains("مالي")) { iconData = Icons.account_balance_rounded; } else if (name.contains("entertain") || name.contains("activities") || name.contains("أنشطة") || name.contains("ترفيه")) { iconData = Icons.theater_comedy_rounded; } else if (name.contains("educat") || name.contains("تعليم")) { iconData = Icons.menu_book_rounded; } else if (name.contains("shop") || name.contains("retail") || name.contains("تسوق") || name.contains("تجزئة")) { iconData = Icons.shopping_bag_outlined; } else if (name.contains("health") || name.contains("medical") || name.contains("صحة") || name.contains("طبي")) { iconData = Icons.health_and_safety_outlined; } else if (name.contains("beauty") || name.contains("جمال") || name.contains("عناية")) { iconData = Icons.face_retouching_natural_rounded; } else if (name.contains("fitness") || name.contains("sport") || name.contains("gym") || name.contains("رياضة") || name.contains("لياقة")) { iconData = Icons.fitness_center_rounded; } else if (name.contains("hotel") || name.contains("travel") || name.contains("فندق") || name.contains("فنادق") || name.contains("سفر")) { iconData = Icons.hotel_rounded; } else if (name.contains("service") || name.contains("خدمات")) { iconData = Icons.build_circle_outlined; } else if (name.contains("food") || name.contains("restaurant") || name.contains("مطاعم") || name.contains("أغذية")) { iconData = Icons.restaurant_rounded; } else if (name.contains("home") || name.contains("منزل")) { iconData = Icons.home_rounded; } return Icon(iconData, color: color, size: 26); } String _getDiscountBadge(WalaPlusRetailerModel item) { if (item.offerTitle != null) { RegExp percentRegex = RegExp(r'(\d+%)'); Match? match = percentRegex.firstMatch(item.offerTitle!); if (match != null) { return match.group(1)!; } } if (item.name != null) { RegExp percentRegex = RegExp(r'(\d+%)'); Match? match = percentRegex.firstMatch(item.name!); if (match != null) { return match.group(1)!; } } return ""; } Widget _buildMerchantMIcon() { return Container(color: const Color(0xFFED1C24), alignment: Alignment.center, child: "M".toText10(isBold: true, color: Colors.white)); } Widget _buildOfferCard(WalaPlusRetailerModel item, bool isAr) { String? bannerUrl = (item.imageThumb != null && item.imageThumb!.isNotEmpty) ? item.imageThumb : item.image; String? logoUrl = (item.logoThumb != null && item.logoThumb!.isNotEmpty) ? item.logoThumb : item.logo; String discountText = _getDiscountBadge(item); String offerSubtitle = ""; if (discountText.isNotEmpty) { if (item.offerTitle != null && item.offerTitle!.toLowerCase().contains("off")) { offerSubtitle = item.offerTitle!; } else { offerSubtitle = LocaleKeys.offDiscount.tr(args: [discountText]); } } else if (item.offerTitle != null && item.offerTitle!.trim().isNotEmpty) { offerSubtitle = item.offerTitle!.trim(); } String? typeText = item.getDisplayType(); bool isOnline = item.isOnlineStore; String validityText = item.getDisplayValidity(); String usageText = ""; if (item.displayUsage.isNotEmpty) { usageText = item.displayUsage.replaceAll('usage:', LocaleKeys.usageLabel.tr()).replaceAll('Usage :', LocaleKeys.usageLabel.tr()); } String cityText = item.getDisplayCity(isAr: isAr); if (cityText.trim().isEmpty) { cityText = item.displayCity; } return InkWell( borderRadius: BorderRadius.circular(20), onTap: () => _openRetailer(item), child: Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(20), boxShadow: [BoxShadow(color: const Color(0xFF0D1720).withOpacity(0.0392), offset: const Offset(0, 5), blurRadius: 18, spreadRadius: 0)], ), padding: const EdgeInsets.all(10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Inset image with rounded corners ClipRRect( borderRadius: BorderRadius.circular(14), child: SizedBox( height: 120, width: double.infinity, child: Stack( fit: StackFit.expand, children: [ // Banner Image (bannerUrl != null && bannerUrl.isNotEmpty) ? Image.network( bannerUrl, fit: BoxFit.cover, errorBuilder: (_, __, ___) => Container(color: const Color(0xFFF1F5F9), child: const Icon(Icons.image_outlined, color: Color(0xFF94A3B8), size: 32)), ) : Container(color: const Color(0xFFF1F5F9), child: const Icon(Icons.image_outlined, color: Color(0xFF94A3B8), size: 32)), // Gradient overlay at bottom of image Positioned( bottom: 0, left: 0, right: 0, height: 50, child: Container( decoration: BoxDecoration(gradient: LinearGradient(begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: [Colors.black.withOpacity(0.75), Colors.transparent])), ), ), // Discount badge at top right (flush with edge, pill on start side) if (discountText.isNotEmpty) PositionedDirectional( top: 20, end: 0, child: Container( padding: const EdgeInsetsDirectional.only(start: 14, end: 10, top: 4, bottom: 4), decoration: const BoxDecoration(color: Color(0xFFED1C24), borderRadius: BorderRadiusDirectional.only(topStart: Radius.circular(20), bottomStart: Radius.circular(20))), child: discountText.toText14(isBold: true, color: Colors.white), ), ), // Brand logo & name at bottom left PositionedDirectional( bottom: 8, start: 8, end: 8, child: Row( children: [ Container( width: 18, height: 18, decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(4)), clipBehavior: Clip.antiAlias, child: (logoUrl != null && logoUrl.isNotEmpty) ? Image.network(logoUrl, fit: BoxFit.contain, errorBuilder: (_, __, ___) => _buildMerchantMIcon()) : _buildMerchantMIcon(), ), const SizedBox(width: 5), Expanded(child: (item.name ?? "").toText11(isBold: true, maxLine: 1, color: Colors.white)), ], ), ), ], ), ), ), const SizedBox(height: 8), // Retailer Name / Bundle Title (item.name ?? "").toText14(isBold: true, maxlines: 1, overflow: TextOverflow.ellipsis, color: const Color(0xFF1E293B)), if (offerSubtitle.isNotEmpty) ...[const SizedBox(height: 2), offerSubtitle.toText14(maxlines: 1, overflow: TextOverflow.ellipsis, isBold: true, color: const Color(0xFF1E293B))], // Badges Row: Type, Validity, Location & Usage if ((typeText != null && typeText.trim().isNotEmpty) || validityText.trim().isNotEmpty || cityText.trim().isNotEmpty || usageText.trim().isNotEmpty) ...[ const SizedBox(height: 6), Wrap( spacing: 5, runSpacing: 4, children: [ // Type Chip (Online or In Store) if (typeText != null && typeText.trim().isNotEmpty) InfoChipWidget( text: typeText, icon: isOnline ? Icons.language_rounded : Icons.storefront_rounded, backgroundColor: isOnline ? const Color(0xFFEFF6FF) : const Color(0xFFF5F3FF), textColor: isOnline ? const Color(0xFF2563EB) : const Color(0xFF7C3AED), ), // Validity badge if (validityText.trim().isNotEmpty) InfoChipWidget(text: validityText, backgroundColor: const Color(0xFFE6F7F0), textColor: const Color(0xFF00A651)), // Location Badge if (cityText.trim().isNotEmpty) InfoChipWidget( text: cityText, svgIcon: "assets/icons/location.svg", isBold: false, backgroundColor: const Color(0xFFF3F4F6), textColor: const Color(0xFF4B5563), iconColor: const Color(0xFF64748B), iconTextGap: 2.5, ), // Usage badge if (usageText.trim().isNotEmpty) InfoChipWidget(text: usageText, backgroundColor: const Color(0xFFFEF3C7), textColor: const Color(0xFFB45309)), ], ), ], ], ), ), ); } Widget _buildRetailersShimmer() { return Shimmer.fromColors( baseColor: const Color(0xFFE2E8F0), highlightColor: const Color(0xFFF8FAFC), child: GridView.builder( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 0.72, crossAxisSpacing: 12, mainAxisSpacing: 16), itemCount: 4, itemBuilder: (_, __) { return Container( decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(20)), padding: const EdgeInsets.all(10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container(height: 105, width: double.infinity, decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(14))), const SizedBox(height: 8), Container(height: 14, width: 110, decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(4))), const SizedBox(height: 4), Container(height: 12, width: 80, decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(4))), const SizedBox(height: 6), Wrap( spacing: 5, runSpacing: 4, children: [ Container(height: 16, width: 50, decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(10))), Container(height: 16, width: 45, decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(10))), Container(height: 16, width: 45, decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(10))), ], ), ], ), ); }, ), ); } Widget _buildCategoriesShimmer() { return SizedBox( height: 136.0, child: Shimmer.fromColors( baseColor: const Color(0xFFE2E8F0), highlightColor: const Color(0xFFF8FAFC), child: ListView.separated( shrinkWrap: true, scrollDirection: Axis.horizontal, physics: const NeverScrollableScrollPhysics(), padding: EdgeInsets.zero, itemCount: 5, separatorBuilder: (BuildContext _, int __) => const SizedBox(width: 14), itemBuilder: (BuildContext _, int index) { return SizedBox( width: 84, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Container(width: 84, height: 84, decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(18))), const SizedBox(height: 8), Container(width: 65, height: 11, decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(4))), const SizedBox(height: 4), Container(width: 42, height: 11, decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(4))), ], ), ); }, ), ), ); } }