games_app/prediqo_mobile/lib/features/faq/presentation/faq_screen.dart

520 lines
19 KiB
Dart

/// Help presentation: searchable FAQ list with category filters + PDF guides.
library;
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../core/config/app_config.dart';
import '../../../core/di/injection.dart';
import '../../../core/errors/app_exception.dart';
import '../../../core/theme/app_colors.dart';
import '../../../data/models/faq_models.dart';
import '../../../domain/repositories/faq_repository.dart';
import '../../../l10n/app_strings.dart';
import '../../../shared/widgets/pred_card.dart';
import '../../../shared/widgets/pred_skeleton.dart';
import '../../../shared/widgets/section_error.dart';
import '../../../shared/widgets/tloto_gradient_app_bar.dart';
import '../../welcome/utils/welcome_navigation.dart';
class FaqScreen extends StatefulWidget {
const FaqScreen({super.key, this.initialCategory});
/// Optional FAQ category slug (e.g. `predictions`) from `/faq?category=...`.
final String? initialCategory;
@override
State<FaqScreen> createState() => _FaqScreenState();
}
class _FaqScreenState extends State<FaqScreen> {
final _repo = sl<FaqRepository>();
final _searchController = TextEditingController();
Timer? _searchDebounce;
List<FaqEntryModel> _entries = [];
List<FaqCategoryModel> _categories = [];
String? _selectedCategory;
bool _loading = true;
bool _searching = false;
bool _retrying = false;
String? _error;
String? _activeSearch;
int _loadGen = 0;
Future<void>? _sameKeyInFlight;
String? _sameKey;
@override
void initState() {
super.initState();
_selectedCategory = widget.initialCategory;
_searchController.addListener(_onSearchTextChanged);
final cachedCats = _repo.peekCategories();
if (cachedCats != null && cachedCats.isNotEmpty) {
_categories = cachedCats;
}
final cached = _repo.peekLast(category: _selectedCategory);
if (cached != null && cached.isNotEmpty) {
_entries = cached;
_loading = false;
}
_bootstrap();
}
Future<void> _bootstrap({bool force = false}) async {
try {
final cats = await _repo.listCategories(force: force);
if (!mounted) return;
setState(() => _categories = cats);
} catch (_) {
// Soft-fail categories: entries can still load.
}
await _load(
search: _normalizedSearch(_searchController.text),
category: _selectedCategory,
force: force,
);
}
String? _normalizedSearch(String raw) {
final q = raw.trim();
return q.isEmpty ? null : q;
}
void _onSearchTextChanged() {
if (!mounted) return;
setState(() {}); // refresh clear icon
_searchDebounce?.cancel();
_searchDebounce = Timer(const Duration(milliseconds: 350), () {
if (!mounted) return;
final next = _normalizedSearch(_searchController.text);
if (next == _activeSearch) return;
_load(search: next, category: _selectedCategory, force: true);
});
}
void _submitSearch([String? raw]) {
_searchDebounce?.cancel();
final next = _normalizedSearch(raw ?? _searchController.text);
_load(search: next, category: _selectedCategory, force: true);
}
@override
void dispose() {
_searchDebounce?.cancel();
_searchController.removeListener(_onSearchTextChanged);
_searchController.dispose();
super.dispose();
}
Future<void> _load({
String? search,
String? category,
bool force = false,
}) {
final cat = category;
final key = '${cat ?? ''}|${search ?? ''}';
if (_sameKeyInFlight != null && _sameKey == key) return _sameKeyInFlight!;
final gen = ++_loadGen;
final keepVisible = _entries.isNotEmpty;
final future = () async {
setState(() {
_activeSearch = search;
_retrying = force;
if (keepVisible) {
_searching = true;
if (!force) _error = null;
} else {
_loading = true;
if (!force) _error = null;
}
});
try {
final entries = await _repo.listEntries(
search: search,
category: cat,
force: force,
);
if (!mounted || gen != _loadGen) return;
setState(() {
_entries = entries;
_loading = false;
_searching = false;
_retrying = false;
_error = null;
});
} catch (_) {
if (!mounted || gen != _loadGen) return;
setState(() {
_loading = false;
_searching = false;
_retrying = false;
if (_entries.isEmpty) {
_error = AppException.connectionFailedMessage;
}
});
}
}();
_sameKey = key;
_sameKeyInFlight = future.whenComplete(() {
if (_sameKey == key) {
_sameKeyInFlight = null;
_sameKey = null;
}
});
return _sameKeyInFlight!;
}
void _clearSearch() {
_searchDebounce?.cancel();
_searchController.clear();
_load(search: null, category: _selectedCategory, force: true);
}
void _selectCategory(String? slug) {
if (_selectedCategory == slug) return;
setState(() => _selectedCategory = slug);
_load(
search: _normalizedSearch(_searchController.text),
category: slug,
force: true,
);
}
FaqCategoryModel? get _activeCategoryModel {
final slug = _selectedCategory;
if (slug == null) return null;
for (final c in _categories) {
if (c.slug == slug) return c;
}
return null;
}
Future<void> _openPdf(FaqCategoryDocument doc) async {
final base = sl<AppConfig>().apiBaseUrl.replaceAll(RegExp(r'/$'), '');
final path = doc.url.startsWith('/') ? doc.url : '/${doc.url}';
final uri = Uri.parse('$base$path');
final ok = await launchUrl(uri, mode: LaunchMode.externalApplication);
if (!ok && mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(context.strings.faqPdfOpenFailed)),
);
}
}
String _categoryLabel(AppStrings s, FaqCategoryModel cat) {
switch (cat.slug) {
case 'account':
return s.faqCatAccount;
case 'deposits':
return s.faqCatDeposits;
case 'withdrawals':
return s.faqCatWithdrawals;
case 'predictions':
return s.faqCatPredictions;
case 'referral':
return s.faqCatReferral;
case 'bonus':
return s.faqCatBonus;
case 'security':
return s.faqCatSecurity;
default:
return cat.name;
}
}
@override
Widget build(BuildContext context) {
final s = context.strings;
final isDark = Theme.of(context).brightness == Brightness.dark;
final bottomInset = MediaQuery.paddingOf(context).bottom;
final keyboardInset = MediaQuery.viewInsetsOf(context).bottom;
final muted = isDark ? AppColors.textMuted : const Color(0xFF94A3B8);
final secondary =
isDark ? AppColors.textSecondary : const Color(0xFF475569);
const physics = AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
);
final listPadding = EdgeInsets.fromLTRB(
20,
12,
20,
24 + bottomInset + keyboardInset,
);
final activeCat = _activeCategoryModel;
return AnnotatedRegion<SystemUiOverlayStyle>(
value: TlotoGradientAppBar.overlayStyle,
child: Scaffold(
key: const Key('faq_screen'),
body: Column(
children: [
TlotoGradientAppBar(
title: s.faqTitle,
showBack: true,
onBack: () => popToWelcomeOrPrevious(context),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),
child: PredCard(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
child: TextField(
key: const Key('faq_search'),
controller: _searchController,
textInputAction: TextInputAction.search,
decoration: InputDecoration(
hintText: s.searchFaq,
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
prefixIcon: const Icon(Icons.search_rounded),
suffixIcon: _searchController.text.isNotEmpty
? IconButton(
icon: const Icon(Icons.clear_rounded),
onPressed: _clearSearch,
)
: null,
),
onSubmitted: _submitSearch,
),
),
),
if (_categories.isNotEmpty)
Padding(
key: const Key('faq_category_chips'),
padding: const EdgeInsets.fromLTRB(20, 10, 20, 0),
child: Wrap(
spacing: 8,
runSpacing: 8,
children: [
ChoiceChip(
label: Text(s.faqAllCategories),
selected: _selectedCategory == null,
onSelected: (_) => _selectCategory(null),
),
..._categories.map(
(cat) => ChoiceChip(
label: Text(_categoryLabel(s, cat)),
selected: _selectedCategory == cat.slug,
onSelected: (_) => _selectCategory(cat.slug),
),
),
],
),
),
if (_searching)
const LinearProgressIndicator(
minHeight: 2,
color: AppColors.primary,
),
Expanded(
child: RefreshIndicator(
onRefresh: () => _bootstrap(force: true),
child: _error != null && _entries.isEmpty
? ListView(
physics: physics,
padding: listPadding,
children: [
SectionError(
message: _error!,
retrying: _retrying,
onRetry: () => _bootstrap(force: true),
),
],
)
: _loading && _entries.isEmpty
? ListView(
physics: physics,
padding: listPadding,
children: const [
PredSkeletonCard(height: 72),
SizedBox(height: 10),
PredSkeletonCard(height: 72),
SizedBox(height: 10),
PredSkeletonCard(height: 72),
],
)
: ListView(
physics: physics,
padding: listPadding,
children: [
if (activeCat != null && activeCat.hasDownloads)
_FaqDownloadsCard(
category: activeCat,
onOpenFr: activeCat.pdfFr != null
? () => _openPdf(activeCat.pdfFr!)
: null,
onOpenEn: activeCat.pdfEn != null
? () => _openPdf(activeCat.pdfEn!)
: null,
),
if (activeCat != null && activeCat.hasDownloads)
const SizedBox(height: 14),
if (_entries.isEmpty)
Padding(
padding: const EdgeInsets.only(top: 32),
child: Column(
children: [
Icon(
Icons.help_outline_rounded,
size: 48,
color: muted,
),
const SizedBox(height: 12),
Text(
s.noFaqResults,
textAlign: TextAlign.center,
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(color: secondary),
),
],
),
)
else
..._entries.map(
(entry) => Padding(
padding: const EdgeInsets.only(bottom: 8),
child: PredCard(
padding: EdgeInsets.zero,
child: Theme(
data: Theme.of(context).copyWith(
dividerColor: Colors.transparent,
),
child: ExpansionTile(
tilePadding:
const EdgeInsets.symmetric(
horizontal: 14,
vertical: 2,
),
childrenPadding:
const EdgeInsets.fromLTRB(
14,
0,
14,
14,
),
title: Text(
entry.question,
style: Theme.of(context)
.textTheme
.titleSmall
?.copyWith(
fontWeight: FontWeight.w700,
),
),
subtitle: entry.category.isNotEmpty
? Text(
entry.category,
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(
color: muted,
),
)
: null,
children: [
Align(
alignment: Alignment.centerLeft,
child: Text(
entry.answer,
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(
color: secondary,
),
),
),
],
),
),
),
),
),
],
),
),
),
],
),
),
);
}
}
class _FaqDownloadsCard extends StatelessWidget {
const _FaqDownloadsCard({
required this.category,
this.onOpenFr,
this.onOpenEn,
});
final FaqCategoryModel category;
final VoidCallback? onOpenFr;
final VoidCallback? onOpenEn;
@override
Widget build(BuildContext context) {
final s = context.strings;
final isDark = Theme.of(context).brightness == Brightness.dark;
final desc = category.description?.trim();
return PredCard(
key: const Key('faq_downloads_card'),
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
s.faqDownloadsTitle,
style: Theme.of(context).textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w800,
),
),
if (desc != null && desc.isNotEmpty) ...[
const SizedBox(height: 6),
Text(
desc,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: isDark
? AppColors.textSecondary
: const Color(0xFF475569),
),
),
],
const SizedBox(height: 12),
if (onOpenFr != null)
SizedBox(
width: double.infinity,
child: FilledButton.icon(
key: const Key('faq_download_fr'),
onPressed: onOpenFr,
icon: const Icon(Icons.picture_as_pdf_rounded, size: 18),
label: Text(s.faqDownloadFr),
),
),
if (onOpenFr != null && onOpenEn != null) const SizedBox(height: 8),
if (onOpenEn != null)
SizedBox(
width: double.infinity,
child: FilledButton.tonalIcon(
key: const Key('faq_download_en'),
onPressed: onOpenEn,
icon: const Icon(Icons.picture_as_pdf_rounded, size: 18),
style: FilledButton.styleFrom(
foregroundColor: AppColors.primary,
backgroundColor: AppColors.primary.withValues(alpha: 0.18),
),
label: Text(s.faqDownloadEn),
),
),
],
),
);
}
}