feat: session start screen, question context input, and G4F-style AI multi-provider fallback

This commit is contained in:
Alma Alexyz
2026-08-31 13:43:45 +05:00
parent c99e36e9ac
commit a24fdaee97
11 changed files with 857 additions and 99 deletions
+244 -39
View File
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../models/history_entry_model.dart';
import '../models/word_model.dart';
import '../services/ai_oracle_service.dart';
import '../services/words_repository.dart';
import 'gradient_star_badge.dart';
@@ -10,7 +11,10 @@ class WordCardWidget extends StatefulWidget {
final VoidCallback? onNext;
final VoidCallback? onPrevious;
final VoidCallback? onRandom;
final String? positionTitle; // Optional title for spread positions
final String? positionTitle;
final String? question;
final String? initialAiInterpretation;
final String? historyEntryId;
const WordCardWidget({
super.key,
@@ -19,6 +23,9 @@ class WordCardWidget extends StatefulWidget {
this.onPrevious,
this.onRandom,
this.positionTitle,
this.question,
this.initialAiInterpretation,
this.historyEntryId,
});
@override
@@ -27,35 +34,51 @@ class WordCardWidget extends StatefulWidget {
class _WordCardWidgetState extends State<WordCardWidget> {
final _repo = WordsRepository();
final _aiService = AiOracleService();
bool _savedToHistory = false;
String? _currentHistoryId;
String? _aiInterpretation;
bool _isLoadingAi = false;
@override
void initState() {
super.initState();
_currentHistoryId = widget.historyEntryId;
_aiInterpretation = widget.initialAiInterpretation;
_savedToHistory = widget.historyEntryId != null;
}
@override
void didUpdateWidget(covariant WordCardWidget oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.word.id != widget.word.id ||
oldWidget.word.sessionNumber != widget.word.sessionNumber) {
_savedToHistory = false;
_savedToHistory = widget.historyEntryId != null;
_currentHistoryId = widget.historyEntryId;
_aiInterpretation = widget.initialAiInterpretation;
_isLoadingAi = false;
}
}
Color _getPosColor(String pos) {
switch (pos.toLowerCase()) {
case 'существительное':
return const Color(0xFF64B5F6); // Celestial Blue
return const Color(0xFF64B5F6);
case 'глагол':
return const Color(0xFF81C784); // Vital Green
return const Color(0xFF81C784);
case 'прилагательное':
return const Color(0xFFFFD54F); // Golden
return const Color(0xFFFFD54F);
case 'наречие':
case 'наречие-местоимение':
return const Color(0xFFBA68C8); // Mystic Violet
return const Color(0xFFBA68C8);
case 'местоимение':
case 'местоименное прил.':
return const Color(0xFF4DD0E1); // Cyan
return const Color(0xFF4DD0E1);
case 'предлог':
case 'союз':
case 'частица':
return const Color(0xFFFF8A65); // Coral Ember
return const Color(0xFFFF8A65);
default:
return const Color(0xFF90A4AE);
}
@@ -63,8 +86,9 @@ class _WordCardWidgetState extends State<WordCardWidget> {
Future<void> _recordToHistory() async {
if (_savedToHistory) return;
final newId = DateTime.now().millisecondsSinceEpoch.toString();
final entry = HistoryEntry(
id: DateTime.now().millisecondsSinceEpoch.toString(),
id: newId,
timestamp: DateTime.now(),
word: widget.word.word,
sessionNumber: widget.word.sessionNumber,
@@ -72,10 +96,15 @@ class _WordCardWidgetState extends State<WordCardWidget> {
symbolicMeaning: widget.word.description,
readingType: widget.positionTitle ?? 'Жребий номера',
positionTitle: widget.positionTitle,
question: widget.question,
aiInterpretation: _aiInterpretation,
);
await _repo.addHistoryEntry(entry);
if (!mounted) return;
setState(() => _savedToHistory = true);
setState(() {
_savedToHistory = true;
_currentHistoryId = newId;
});
HapticFeedback.mediumImpact();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
@@ -95,6 +124,47 @@ class _WordCardWidgetState extends State<WordCardWidget> {
);
}
Future<void> _fetchAiInterpretation() async {
setState(() => _isLoadingAi = true);
HapticFeedback.mediumImpact();
try {
final result = await _aiService.interpret(
word: widget.word,
question: widget.question ?? '',
positionTitle: widget.positionTitle,
);
if (mounted) {
setState(() {
_aiInterpretation = result;
_isLoadingAi = false;
});
// Update history if already saved, or save now
if (_currentHistoryId != null) {
await _repo.updateHistoryEntry(
_currentHistoryId!,
aiInterpretation: result,
question: widget.question,
);
} else {
await _recordToHistory();
}
}
} catch (e) {
if (mounted) {
setState(() => _isLoadingAi = false);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Ошибка генерации: $e'),
behavior: SnackBarBehavior.floating,
),
);
}
}
}
void _copyToClipboard(BuildContext context) {
final now = DateTime.now();
final day = now.day.toString().padLeft(2, '0');
@@ -103,13 +173,18 @@ class _WordCardWidgetState extends State<WordCardWidget> {
final hour = now.hour.toString().padLeft(2, '0');
final min = now.minute.toString().padLeft(2, '0');
final text =
var text =
'✨ Оракул 999 — Толкование символа ✨\n'
'Дата и время: $day.$month.$year $hour:$min\n'
'${widget.question != null && widget.question!.isNotEmpty ? "Вопрос: «${widget.question}»\n" : ""}'
'Знак №${widget.word.formattedSessionNumber}: ${widget.word.word.toUpperCase()}\n'
'Аспект: ${widget.word.partOfSpeech} • ${widget.word.category}\n\n'
'🔮 Символическое значение:\n${widget.word.description}';
if (_aiInterpretation != null) {
text += '\n\n🤖 AI Трактовка:\n$_aiInterpretation';
}
Clipboard.setData(ClipboardData(text: text));
HapticFeedback.lightImpact();
ScaffoldMessenger.of(context).showSnackBar(
@@ -161,15 +236,51 @@ class _WordCardWidgetState extends State<WordCardWidget> {
],
),
),
padding: const EdgeInsets.all(22),
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// Question context banner if present
if (widget.question != null && widget.question!.trim().isNotEmpty) ...[
Container(
margin: const EdgeInsets.only(bottom: 12),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: const Color(0xFF2A2D4A).withValues(alpha: 0.7),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: const Color(0xFFFFD54F).withValues(alpha: 0.35),
),
),
child: Row(
children: [
const Icon(
Icons.help_outline_rounded,
size: 16,
color: Color(0xFFFFD54F),
),
const SizedBox(width: 8),
Expanded(
child: Text(
'Вопрос: «${widget.question}»',
style: const TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: Color(0xFFFFF9C4),
fontStyle: FontStyle.italic,
),
),
),
],
),
),
],
// Optional spread position banner (e.g. "Исток / Прошлое")
if (widget.positionTitle != null) ...[
Container(
margin: const EdgeInsets.only(bottom: 12),
margin: const EdgeInsets.only(bottom: 10),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
decoration: BoxDecoration(
color: const Color(0xFFFFD54F).withValues(alpha: 0.15),
@@ -226,12 +337,12 @@ class _WordCardWidgetState extends State<WordCardWidget> {
],
),
const SizedBox(height: 14),
const SizedBox(height: 12),
// Big Word Title
Center(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6.0),
padding: const EdgeInsets.symmetric(vertical: 4.0),
child: Text(
widget.word.word.toUpperCase(),
textAlign: TextAlign.center,
@@ -284,17 +395,17 @@ class _WordCardWidgetState extends State<WordCardWidget> {
),
),
const SizedBox(height: 16),
const SizedBox(height: 14),
Divider(
height: 1,
color: isDark ? Colors.white12 : Colors.black12,
),
const SizedBox(height: 14),
const SizedBox(height: 12),
// Symbolic Divination Meaning Box
// Base Symbolic Divination Meaning Box
Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: isDark
? const Color(0xFF141729)
@@ -303,38 +414,31 @@ class _WordCardWidgetState extends State<WordCardWidget> {
border: Border.all(
color: const Color(0xFFFFD54F).withValues(alpha: 0.2),
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: isDark ? 0.2 : 0.05),
blurRadius: 6,
offset: const Offset(0, 2),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
const Row(
children: [
const GradientStar(size: 16),
const SizedBox(width: 8),
GradientStar(size: 15),
SizedBox(width: 8),
Text(
'СИМВОЛИЧЕСКОЕ ЗНАЧЕНИЕ',
'СИМВОЛИЧЕСКИЙ СМЫСЛ',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w900,
letterSpacing: 1.0,
color: const Color(0xFFFFD54F),
color: Color(0xFFFFD54F),
),
),
],
),
const SizedBox(height: 10),
const SizedBox(height: 8),
Text(
widget.word.description,
style: theme.textTheme.bodyLarge?.copyWith(
height: 1.5,
fontSize: 14.5,
style: theme.textTheme.bodyMedium?.copyWith(
height: 1.45,
fontSize: 13.5,
color: isDark ? const Color(0xFFE2E4F0) : const Color(0xFF2C3042),
),
),
@@ -342,7 +446,108 @@ class _WordCardWidgetState extends State<WordCardWidget> {
),
),
const SizedBox(height: 18),
const SizedBox(height: 12),
// AI Interpretation Block / Button
if (_aiInterpretation != null) ...[
Container(
width: double.infinity,
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
const Color(0xFF2A2145),
const Color(0xFF1A1B35),
],
),
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: const Color(0xFFBA68C8).withValues(alpha: 0.6),
width: 1.2,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Row(
children: [
Icon(Icons.psychology_rounded, size: 18, color: Color(0xFFE1BEE7)),
SizedBox(width: 8),
Text(
'AI ТРАКТОВКА ОРАКУЛА (G4F)',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w900,
letterSpacing: 0.8,
color: Color(0xFFE1BEE7),
),
),
],
),
InkWell(
onTap: _fetchAiInterpretation,
child: const Padding(
padding: EdgeInsets.all(4.0),
child: Icon(Icons.refresh_rounded, size: 16, color: Color(0xFFE1BEE7)),
),
),
],
),
const SizedBox(height: 8),
Text(
_aiInterpretation!,
style: const TextStyle(
fontSize: 13.5,
height: 1.5,
color: Color(0xFFF3E5F5),
),
),
],
),
),
const SizedBox(height: 12),
] else ...[
// Button to generate AI interpretation
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
onPressed: _isLoadingAi ? null : _fetchAiInterpretation,
icon: _isLoadingAi
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFBA68C8)),
),
)
: const Icon(Icons.auto_awesome, size: 16, color: Color(0xFFBA68C8)),
label: Text(
_isLoadingAi ? 'Синтез толкования...' : 'Спросить AI Оракула (G4F-трактовка)',
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 12.5,
color: Color(0xFFE1BEE7),
),
),
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 10),
side: BorderSide(
color: const Color(0xFFBA68C8).withValues(alpha: 0.5),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
),
),
),
),
const SizedBox(height: 12),
],
// Navigation Controls Row
Row(
@@ -353,7 +558,7 @@ class _WordCardWidgetState extends State<WordCardWidget> {
icon: const Icon(Icons.arrow_back_ios_new_rounded, size: 14),
label: const Text('Пред.'),
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 12),
padding: const EdgeInsets.symmetric(vertical: 11),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
),
@@ -366,7 +571,7 @@ class _WordCardWidgetState extends State<WordCardWidget> {
onPressed: widget.onRandom,
icon: const GradientStar(size: 20),
style: IconButton.styleFrom(
padding: const EdgeInsets.all(12),
padding: const EdgeInsets.all(11),
backgroundColor: const Color(0xFF2A2D4A),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
@@ -383,7 +588,7 @@ class _WordCardWidgetState extends State<WordCardWidget> {
icon: const Text('След.'),
label: const Icon(Icons.arrow_forward_ios_rounded, size: 14),
style: FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 12),
padding: const EdgeInsets.symmetric(vertical: 11),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
),