feat: implement splash and onboarding flows, update app assets, and add project design documentation

This commit is contained in:
Hamza-Ayed
2026-07-24 04:15:07 +03:00
parent 9f7bc31408
commit 213b459912
208 changed files with 23801 additions and 1066 deletions
@@ -1,6 +1,7 @@
import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter/foundation.dart';
import '../data/maps_repository.dart';
import '../data/models/place_model.dart';
@@ -62,10 +63,11 @@ class DestinationCubit extends Cubit<DestinationState> {
Future<void> _search(String query) async {
try {
final results = await _mapsRepo.autocomplete(query);
final results = await _mapsRepo.search(query);
emit(state.copyWith(results: results, searching: false));
} catch (e) {
emit(state.copyWith(searching: false, error: e.toString()));
emit(state.copyWith(
searching: false, error: e.toString(), clearError: false));
}
}
@@ -74,10 +76,27 @@ class DestinationCubit extends Cubit<DestinationState> {
if (query.trim().length < 2) return;
emit(state.copyWith(searching: true, clearError: true));
try {
final results = await _mapsRepo.autocomplete(query);
final results = await _mapsRepo.search(query);
emit(state.copyWith(results: results, searching: false));
} catch (e) {
emit(state.copyWith(searching: false, error: e.toString()));
} catch (e, st) {
debugPrint('Map Search Error: $e\n$st');
emit(state.copyWith(
searching: false, error: e.toString(), clearError: false));
}
}
Future<void> searchVoiceDirectly(String query,
{double? lat, double? lng}) async {
_debounce?.cancel();
if (query.trim().isEmpty) return;
emit(state.copyWith(searching: true, clearError: true));
try {
final results = await _mapsRepo.voiceSearch(query, lat: lat, lng: lng);
emit(state.copyWith(results: results, searching: false));
} catch (e, st) {
debugPrint('Map Voice Search Error: $e\n$st');
emit(state.copyWith(
searching: false, error: e.toString(), clearError: false));
}
}
@@ -82,15 +82,22 @@ class HomeCubit extends Cubit<HomeState> {
);
final loc = LatLng(pos.latitude, pos.longitude);
// جلب العنوان العكسي للموقع الحالي.
final place = await _mapsRepo.reverseGeocode(pos.latitude, pos.longitude);
// نوسّط الكاميرا على الموقع فوراً — لا ننتظر العنوان العكسي.
emit(state.copyWith(
loading: false,
currentLocation: loc,
cameraTarget: loc,
pickup: place,
));
// العنوان العكسي تحسين إضافي: فشله يجب ألّا يمنع توسيط الخريطة.
try {
final place = await _mapsRepo.reverseGeocode(pos.latitude, pos.longitude);
emit(state.copyWith(pickup: place));
} catch (_) {
emit(state.copyWith(
pickup: PlaceModel(name: '', lat: loc.latitude, lng: loc.longitude),
));
}
} catch (e) {
emit(state.copyWith(
loading: false,
@@ -0,0 +1,79 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../core/storage/saved_places_store.dart';
class SavedPlacesState {
final List<SavedPlace> places;
final bool loading;
final String? error;
const SavedPlacesState({
this.places = const [],
this.loading = false,
this.error,
});
SavedPlacesState copyWith({
List<SavedPlace>? places,
bool? loading,
String? error,
}) {
return SavedPlacesState(
places: places ?? this.places,
loading: loading ?? this.loading,
error: error,
);
}
}
class SavedPlacesCubit extends Cubit<SavedPlacesState> {
final SavedPlacesStore _store;
SavedPlacesCubit(this._store) : super(const SavedPlacesState());
Future<void> load() async {
emit(state.copyWith(loading: true, error: null));
try {
final places = await _store.getAll();
emit(SavedPlacesState(places: places));
} catch (e) {
emit(state.copyWith(loading: false, error: e.toString()));
}
}
Future<void> addPlace(SavedPlace place) async {
try {
await _store.add(place);
await load();
} catch (e) {
emit(state.copyWith(error: e.toString()));
}
}
Future<void> removePlace(String id) async {
try {
await _store.remove(id);
await load();
} catch (e) {
emit(state.copyWith(error: e.toString()));
}
}
Future<void> setFavorite(String id, FavoriteType type) async {
try {
await _store.setFavorite(id, type);
await load();
} catch (e) {
emit(state.copyWith(error: e.toString()));
}
}
Future<void> clearFavorite(FavoriteType type) async {
try {
await _store.clearFavorite(type);
await load();
} catch (e) {
emit(state.copyWith(error: e.toString()));
}
}
}
@@ -1,34 +1,40 @@
import '../../../core/api/antlaq_api.dart';
import '../../../core/api/api_client.dart';
import 'models/place_model.dart';
import 'models/route_model.dart';
/// نقطة وصول وحيدة لبيانات الخرائط — كل نداء يمرّ عبر سيرفرنا
/// (docs/23 §4) لحماية المفتاح وتفعيل التخزين المؤقت على Redis.
/// نقطة وصول وحيدة لبيانات الخرائط والبحث الصوتي الذكي عبر الباك إند.
class MapsRepository {
final ApiClient _api;
MapsRepository(this._api);
final AntlaqApi _api;
final ApiClient? _apiClient;
/// بحث مكاني — يمرّ عبر `GET /maps/geocode`.
Future<List<PlaceModel>> autocomplete(String query) async {
if (query.trim().length < 2) return [];
final r = await _api.dio.get(
'/maps/geocode',
queryParameters: {'q': query.trim(), 'country': 'JO'},
);
final items = (r.data['items'] ?? r.data ?? []) as List;
return items
.map((e) => PlaceModel.fromJson(e as Map<String, dynamic>))
.toList();
MapsRepository(this._api, [this._apiClient]);
/// بحث صوتي ذكي يمر عبر الباك إند (Gemini AI).
Future<List<PlaceModel>> voiceSearch(String text, {double? lat, double? lng}) async {
if (text.trim().isEmpty) return [];
try {
if (_apiClient != null) {
final res = await _apiClient.dio.post('/maps/voice-search', data: {
'text': text,
if (lat != null) 'lat': lat,
if (lng != null) 'lng': lng,
});
final list = res.data as List?;
if (list != null) {
return list
.map((e) => PlaceModel.fromJson(e as Map<String, dynamic>))
.toList();
}
}
} catch (_) {}
return search(text);
}
/// بحث حرّ (geocode).
Future<List<PlaceModel>> geocode(String query) async {
/// بحث أماكن — يمر عبر GET /api/geocoding/search.
Future<List<PlaceModel>> search(String query) async {
if (query.trim().length < 2) return [];
final r = await _api.dio.get(
'/maps/geocode',
queryParameters: {'q': query.trim(), 'country': 'JO'},
);
final items = (r.data['items'] ?? r.data ?? []) as List;
final items = await _api.search(query);
return items
.map((e) => PlaceModel.fromJson(e as Map<String, dynamic>))
.toList();
@@ -36,48 +42,44 @@ class MapsRepository {
/// تفكيك عنوان عكسي (إحداثيات → نص).
Future<PlaceModel> reverseGeocode(double lat, double lng) async {
final r = await _api.dio.get(
'/maps/reverse',
queryParameters: {'lat': lat, 'lng': lng},
);
final j = r.data as Map<String, dynamic>;
final j = await _api.reverse(lat, lng);
final name = (j['name_ar'] ?? j['name'] ?? j['formattedAddress'] ?? '') as String;
final addr = (j['address'] ?? j['full_address'] ?? j['formattedAddress'] ?? '') as String;
return PlaceModel.fromJson({
'name': j['formattedAddress'] ?? '',
'address': j['formattedAddress'],
'lat': lat,
'lng': lng,
'name': name,
'full_address': addr.isNotEmpty ? addr : name,
'latitude': lat,
'longitude': lng,
});
}
/// تفاصيل مكان بالـ placeId — يمرّ عبر geocode.
Future<PlaceModel> placeDetails(String placeId) async {
final r = await _api.dio.get(
'/maps/geocode',
queryParameters: {'q': placeId, 'country': 'JO'},
);
final items = (r.data['items'] ?? r.data ?? []) as List;
if (items.isEmpty) {
throw Exception('Place not found');
}
return PlaceModel.fromJson(items.first as Map<String, dynamic>);
}
/// حساب المسار بين نقطتين.
/// حساب المسار بين نقطتين عبر الباك إند (GET /maps/route).
Future<RouteModel> getRoute({
required double fromLat,
required double fromLng,
required double toLat,
required double toLng,
}) async {
final r = await _api.dio.get(
'/maps/route',
queryParameters: {
'fromLat': fromLat,
'fromLng': fromLng,
'toLat': toLat,
'toLng': toLng,
},
try {
if (_apiClient != null) {
final res = await _apiClient.dio.get('/maps/route', queryParameters: {
'fromLat': fromLat,
'fromLng': fromLng,
'toLat': toLat,
'toLng': toLng,
});
if (res.data != null && res.data is Map<String, dynamic>) {
return RouteModel.fromJson(res.data as Map<String, dynamic>);
}
}
} catch (_) {}
final j = await _api.route(
fromLat: fromLat,
fromLng: fromLng,
toLat: toLat,
toLng: toLng,
);
return RouteModel.fromJson(r.data as Map<String, dynamic>);
return RouteModel.fromJson(j);
}
}
@@ -0,0 +1,32 @@
import 'package:equatable/equatable.dart';
import 'package:intaleq_maps/intaleq_maps.dart';
/// باب/مدخل مكان — من استجابة انطلق.
class Gate extends Equatable {
final String nameAr;
final String nameEn;
final double lat;
final double lng;
final bool isMainGate;
const Gate({
required this.nameAr,
required this.nameEn,
required this.lat,
required this.lng,
this.isMainGate = false,
});
factory Gate.fromJson(Map<String, dynamic> j) => Gate(
nameAr: (j['name_ar'] ?? '') as String,
nameEn: (j['name_en'] ?? '') as String,
lat: (j['latitude'] as num).toDouble(),
lng: (j['longitude'] as num).toDouble(),
isMainGate: j['is_main_gate'] as bool? ?? false,
);
LatLng get latLng => LatLng(lat, lng);
@override
List<Object?> get props => [nameAr, nameEn, lat, lng, isMainGate];
}
@@ -1,12 +1,17 @@
import 'package:equatable/equatable.dart';
import 'gate_model.dart';
/// نموذج مكان من نتائج البحث (autocomplete / geocode).
/// نموذج مكان من نتائج بحث انطلق (geocode / search).
class PlaceModel extends Equatable {
final String? placeId;
final String name;
final String? address;
final double lat;
final double lng;
final String? category;
final double? totalScore;
final String? source;
final List<Gate> gates;
const PlaceModel({
this.placeId,
@@ -14,32 +19,53 @@ class PlaceModel extends Equatable {
this.address,
required this.lat,
required this.lng,
this.category,
this.totalScore,
this.source,
this.gates = const [],
});
factory PlaceModel.fromJson(Map<String, dynamic> j) => PlaceModel(
placeId: j['placeId'] as String?,
name: (j['description'] ?? j['name'] ?? '') as String,
address: j['address'] as String?,
lat: (j['lat'] as num).toDouble(),
lng: (j['lng'] as num).toDouble(),
);
factory PlaceModel.fromGeocode(Map<String, dynamic> j) => PlaceModel(
placeId: j['placeId'] as String?,
name: (j['name'] ?? j['formattedAddress'] ?? '') as String,
address: j['formattedAddress'] as String?,
lat: (j['lat'] as num).toDouble(),
lng: (j['lng'] as num).toDouble(),
);
/// استجابة انطلق الحقيقية — الحقول الم标准.
factory PlaceModel.fromJson(Map<String, dynamic> j) {
final lat = (j['latitude'] ?? j['location']?['lat'] ?? 0) as num;
final lng = (j['longitude'] ?? j['location']?['lng'] ?? 0) as num;
return PlaceModel(
placeId: j['id'] as String?,
name: (j['name'] ?? '') as String,
address: (j['full_address'] ?? j['address']) as String?,
lat: lat.toDouble(),
lng: lng.toDouble(),
category: j['category'] as String?,
totalScore: (j['totalScore'] as num?)?.toDouble(),
source: j['source'] as String?,
gates: (j['gates'] as List?)
?.map((g) => Gate.fromJson(g as Map<String, dynamic>))
.toList() ??
const [],
);
}
Map<String, dynamic> toJson() => {
if (placeId != null) 'placeId': placeId,
if (placeId != null) 'id': placeId,
'name': name,
if (address != null) 'address': address,
'lat': lat,
'lng': lng,
if (address != null) 'full_address': address,
'latitude': lat,
'longitude': lng,
if (category != null) 'category': category,
if (totalScore != null) 'totalScore': totalScore,
if (source != null) 'source': source,
};
/// هل لهذا المكان أبواب متعددة?
bool get hasMultipleGates => gates.length > 1;
/// الباب الرئيسي إن وُجد.
Gate? get mainGate => gates.cast<Gate?>().firstWhere(
(g) => g!.isMainGate,
orElse: () => null,
);
@override
List<Object?> get props => [placeId, name, address, lat, lng];
List<Object?> get props =>
[placeId, name, address, lat, lng, category, totalScore, source, gates];
}
@@ -1,25 +1,44 @@
import 'package:equatable/equatable.dart';
import 'package:intaleq_maps/intaleq_maps.dart';
/// خطاب polyline مشفر ومسافة/وقت تقريبيان.
/// استجابة مسار من انطلق — مع polyline مشفر وإطار خريطة.
class RouteModel extends Equatable {
final int distanceMeters;
final int durationSeconds;
final String? polyline;
final String? routeName;
final String? startName;
final String? endName;
final List<String>? tags;
final List<double>? bbox;
final double? trafficFactor;
const RouteModel({
required this.distanceMeters,
required this.durationSeconds,
this.polyline,
this.routeName,
this.startName,
this.endName,
this.tags,
this.bbox,
this.trafficFactor,
});
/// استجابة مسار انطلق الحقيقية (تُمرر عبر الباك إند كما هي).
factory RouteModel.fromJson(Map<String, dynamic> j) {
final dist = j['distanceMeters'] ?? j['distance'];
final dur = j['durationSeconds'] ?? j['duration'];
final dist = (j['distance'] ?? 0) as num;
final dur = (j['duration'] ?? 0) as num;
return RouteModel(
distanceMeters: dist is int ? dist : int.tryParse('$dist') ?? 0,
durationSeconds: dur is int ? dur : int.tryParse('$dur') ?? 0,
polyline: j['polyline'] as String?,
distanceMeters: dist.toInt(),
durationSeconds: dur.toInt(),
polyline: j['points'] as String?,
routeName: j['routeName'] as String?,
startName: j['startName'] as String?,
endName: j['endName'] as String?,
tags: (j['tags'] as List?)?.cast<String>(),
bbox: (j['bbox'] as List?)?.map((e) => (e as num).toDouble()).toList(),
trafficFactor: (j['trafficFactor'] as num?)?.toDouble(),
);
}
@@ -36,39 +55,49 @@ class RouteModel extends Equatable {
return '$h h ${rem > 0 ? '$rem min' : ''}';
}
/// تحويل bbox إلى LatLngBounds لضبط الكاميرا مع حماية للمواقع القريبة على iOS.
LatLngBounds? getLatLngBounds() {
if (bbox == null || bbox!.length < 4) return null;
var minLat = bbox![1];
var minLng = bbox![0];
var maxLat = bbox![3];
var maxLng = bbox![2];
// إذا كانت المسافة بين النقاط قريبة جداً (أقل من 0.002 درجة)، نضمن توسعاً أمنياً أدنى لمنع عطل وقفل كاميرا MapLibre على iOS
if ((maxLat - minLat).abs() < 0.002) {
minLat -= 0.001;
maxLat += 0.001;
}
if ((maxLng - minLng).abs() < 0.002) {
minLng -= 0.001;
maxLng += 0.001;
}
return LatLngBounds(
southwest: LatLng(minLat, minLng),
northeast: LatLng(maxLat, maxLng),
);
}
/// فك الـ polyline عبر PolylineUtils من الباكيج.
List<LatLng> decodePolyline() {
if (polyline == null || polyline!.isEmpty) return [];
return _decodeEncodedPolyline(polyline!);
return PolylineUtils.decode(polyline!);
}
/// فك تشفير polyline وفقاً لخوارزمية Google.
static List<LatLng> _decodeEncodedPolyline(String encoded) {
final List<LatLng> poly = [];
int index = 0, lat = 0, lng = 0;
while (index < encoded.length) {
int b, shift = 0, result = 0;
do {
b = encoded.codeUnitAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
lat += ((result & 1) != 0) ? ~(result >> 1) : (result >> 1);
shift = 0;
result = 0;
do {
b = encoded.codeUnitAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
lng += ((result & 1) != 0) ? ~(result >> 1) : (result >> 1);
poly.add(LatLng(lat / 1e5, lng / 1e5));
}
return poly;
}
/// هل المسار مباشر (لا أضلاع)?
bool get isStraightLine => tags?.contains('straight-line') ?? false;
@override
List<Object?> get props => [distanceMeters, durationSeconds, polyline];
List<Object?> get props => [
distanceMeters,
durationSeconds,
polyline,
routeName,
startName,
endName,
tags,
bbox,
trafficFactor,
];
}
File diff suppressed because it is too large Load Diff
+417 -150
View File
@@ -1,17 +1,44 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../core/l10n/app_localizations.dart';
import 'package:go_router/go_router.dart';
import 'package:intaleq_maps/intaleq_maps.dart';
import '../../../core/l10n/app_localizations.dart';
import '../../../core/design/tokens.dart';
import '../../auth/cubit/auth_cubit.dart';
import '../../auth/cubit/auth_state.dart';
import '../../../core/ui/tripz_button.dart';
import '../../../core/design/tokens.dart';
import '../../trip/bloc/trip_bloc.dart';
import '../../trip/bloc/trip_state.dart';
import '../../trip/bloc/trip_event.dart';
import '../cubit/home_cubit.dart';
import '../cubit/saved_places_cubit.dart';
import '../data/models/place_model.dart';
import '../data/maps_repository.dart';
import '../../../core/storage/saved_places_store.dart';
import '../../../core/di.dart';
/// زر عائم دائري صغير — للقائمة وإعادة التوسيط فوق الخريطة.
class _MapCircleButton extends StatelessWidget {
const _MapCircleButton({required this.icon, required this.onPressed});
final IconData icon;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
return Container(
decoration: BoxDecoration(
color: cs.surface,
shape: BoxShape.circle,
boxShadow: const [T.shadowSm],
),
child: IconButton(
icon: Icon(icon, color: cs.onSurface),
onPressed: onPressed,
),
);
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@@ -22,144 +49,333 @@ class HomeScreen extends StatefulWidget {
class _HomeScreenState extends State<HomeScreen> {
IntaleqMapController? _mapController;
bool _isSelectingOnMap = false;
@override
void initState() {
super.initState();
// فحص رحلة نشطة عند فتح الشاشة.
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<TripBloc>().add(const TripCheckActive());
context.read<SavedPlacesCubit>().load();
});
}
String _timeBasedGreeting(String? name, AppLocalizations l10n) {
final hour = DateTime.now().hour;
final isMorning = hour >= 5 && hour < 12;
final isAr = Localizations.localeOf(context).languageCode == 'ar';
final prefix = isMorning
? (isAr ? 'صباح الخير' : 'Good morning')
: (isAr ? 'مساء الخير' : 'Good evening');
final firstName = (name != null && name.trim().isNotEmpty)
? name.trim().split(' ').first
: '';
return firstName.isNotEmpty ? '$prefix، $firstName' : prefix;
}
String _whereToPrompt(String? name, AppLocalizations l10n) {
final firstName = (name != null && name.trim().isNotEmpty)
? name.trim().split(' ').first
: '';
if (firstName.isNotEmpty) {
final isAr = Localizations.localeOf(context).languageCode == 'ar';
return isAr ? 'إلى أين يا $firstName؟' : 'Where to, $firstName?';
}
return l10n.whereTo;
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final cs = Theme.of(context).colorScheme;
final isDark = Theme.of(context).brightness == Brightness.dark;
return BlocListener<TripBloc, TripState>(
listenWhen: (prev, cur) => prev.trip?.status != cur.trip?.status,
listener: (context, state) {
if (state.trip != null && !state.isCompleted) {
// رحلة نشطة — انتقل للتتبع.
context.push('/trip-tracking');
}
},
child: Scaffold(
backgroundColor: cs.surface,
// الخريطة تملأ الشاشة حتى الحافة العلوية (docs/29 §3.6) — كل العناصر
// العائمة فوقها تعيش داخل SafeArea الخاصة بها لا الشاشة كلها.
extendBodyBehindAppBar: true,
body: Stack(
children: [
// الخريطة
BlocBuilder<HomeCubit, HomeState>(
builder: (context, state) {
final center = state.currentLocation ?? const LatLng(31.9539, 35.9106);
return IntaleqMap(
apiKey: '',
initialCameraPosition: CameraPosition(target: center, zoom: 15),
myLocationEnabled: true,
zoomControlsEnabled: false,
compassEnabled: false,
onMapCreated: (controller) => _mapController = controller,
markers: _buildMarkers(state),
onCameraMove: (position) {
context.read<HomeCubit>().updateCameraTarget(position.target);
},
);
},
),
// زر إعادة التوسيط
// ── الخريطة (75% من الشاشة) ──
Positioned(
right: T.pagePadding,
bottom: 180,
child: FloatingActionButton.small(
heroTag: 'recenter',
backgroundColor: cs.surface,
onPressed: () {
final loc = context.read<HomeCubit>().state.currentLocation;
if (loc != null) {
_mapController?.animateCamera(CameraUpdate.newLatLngZoom(loc, 15));
top: 0,
left: 0,
right: 0,
height: MediaQuery.of(context).size.height * 0.75,
child: BlocConsumer<HomeCubit, HomeState>(
listenWhen: (prev, cur) =>
prev.currentLocation == null && cur.currentLocation != null,
buildWhen: (prev, cur) =>
prev.currentLocation != cur.currentLocation ||
prev.pickup != cur.pickup ||
prev.destination != cur.destination,
listener: (context, state) {
if (state.currentLocation != null && _mapController != null) {
_mapController!.animateCamera(
CameraUpdate.newLatLngZoom(state.currentLocation!, 16),
);
}
},
child: Icon(Icons.my_location_rounded, color: cs.onSurface),
builder: (context, state) {
final center =
state.currentLocation ?? const LatLng(31.9539, 35.9106);
return IntaleqMap(
apiKey: '',
initialCameraPosition:
CameraPosition(target: center, zoom: 15),
mapType:
isDark ? IntaleqMapType.normal : IntaleqMapType.light,
myLocationEnabled: true,
myLocationButtonEnabled: false,
zoomControlsEnabled: false,
compassEnabled: false,
onMapCreated: (controller) {
_mapController = controller;
if (state.currentLocation != null) {
Future.delayed(const Duration(milliseconds: 300), () {
controller.animateCamera(
CameraUpdate.newLatLngZoom(
state.currentLocation!, 16),
);
});
}
},
markers: _buildMarkers(state),
onCameraMove: (position) {
context
.read<HomeCubit>()
.updateCameraTarget(position.target);
},
);
},
),
),
// الشريط السفلي
Positioned(
left: T.pagePadding,
right: T.pagePadding,
bottom: T.pagePadding,
child: Card(
elevation: 2,
child: Padding(
padding: const EdgeInsets.all(T.pagePadding),
child: BlocBuilder<HomeCubit, HomeState>(
builder: (context, state) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
BlocBuilder<AuthCubit, AuthState>(
builder: (context, authState) {
final name = authState.user?.name ?? '';
if (name.isNotEmpty) {
return Padding(
padding: const EdgeInsets.only(bottom: T.s12),
child: Text(
l10n.welcome(name),
style: Theme.of(context).textTheme.titleMedium,
),
);
}
return const SizedBox.shrink();
},
),
if (state.destination != null)
_DestinationPreview(
destination: state.destination!,
// زر القائمة أعلى-بداية
PositionedDirectional(
top: MediaQuery.of(context).padding.top + T.s8,
start: T.pagePadding,
child: _MapCircleButton(
icon: Icons.menu_rounded,
onPressed: () => _showLogoutDialog(context, l10n),
),
),
// زر إعادة التوسيط عائم أعلى البطاقة السفلية
PositionedDirectional(
end: T.pagePadding,
bottom: (_isSelectingOnMap ? 100 : MediaQuery.of(context).size.height * 0.28) + T.s16,
child: BlocBuilder<HomeCubit, HomeState>(
builder: (context, state) {
return _MapCircleButton(
icon: Icons.my_location_rounded,
onPressed: state.currentLocation == null
? () {}
: () => _mapController?.animateCamera(
CameraUpdate.newLatLngZoom(
state.currentLocation!, 16),
),
);
},
),
),
if (_isSelectingOnMap)
// علامة المركز (دبوس) لاختيار الموقع
Positioned(
top: (MediaQuery.of(context).size.height * 0.75) / 2 - 20,
left: MediaQuery.of(context).size.width / 2 - 20,
child: const Icon(Icons.location_on, size: 40, color: Colors.black),
),
// ── البطاقة السفلية: «إلى أين؟» والأماكن المحفوظة ──
if (!_isSelectingOnMap)
Positioned(
left: 0,
right: 0,
bottom: 0,
height: MediaQuery.of(context).size.height * 0.30,
child: Container(
width: double.infinity,
padding: const EdgeInsets.fromLTRB(
T.pagePadding, T.s24, T.pagePadding, T.s16),
decoration: BoxDecoration(
color: cs.surface,
borderRadius: const BorderRadius.vertical(
top: Radius.circular(T.r24),
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.1),
blurRadius: 20,
offset: const Offset(0, -5),
)
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// التحية الزمنية مع اسم الراكب بتصميم أنيق
BlocBuilder<AuthCubit, AuthState>(
builder: (context, authState) {
final greeting = _timeBasedGreeting(authState.user?.name, l10n);
return Text(
greeting,
style: Theme.of(context)
.textTheme
.titleLarge
?.copyWith(
fontWeight: FontWeight.w800,
color: cs.onSurface,
letterSpacing: -0.5,
),
);
},
),
const SizedBox(height: T.s24),
// حقل «إلى أين؟»
BlocBuilder<AuthCubit, AuthState>(
builder: (context, authState) {
final searchPrompt = _whereToPrompt(authState.user?.name, l10n);
return Material(
color: cs.surfaceContainerLowest,
elevation: 2,
shadowColor: cs.shadow.withValues(alpha: 0.05),
borderRadius: BorderRadius.circular(T.r16),
child: InkWell(
borderRadius: BorderRadius.circular(T.r16),
onTap: () => _openDestinationSearch(context),
onClear: () => context.read<HomeCubit>().clearTripData(),
)
else
TripzButton(
label: l10n.whereTo,
style: TripzButtonStyle.secondary,
icon: Icons.search_rounded,
onPressed: () => _openDestinationSearch(context),
child: Container(
height: 60,
padding: const EdgeInsets.symmetric(horizontal: T.s16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(T.r16),
border: Border.all(
color: cs.outlineVariant.withValues(alpha: 0.5),
width: 1,
),
),
child: Row(
children: [
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: cs.primaryContainer.withValues(alpha: 0.5),
shape: BoxShape.circle,
),
child: Icon(
Icons.search_rounded,
color: cs.primary,
size: 22,
),
),
const SizedBox(width: T.s16),
Expanded(
child: Text(
searchPrompt,
style: Theme.of(context)
.textTheme
.titleMedium
?.copyWith(
color: cs.onSurface,
fontWeight: FontWeight.w700,
fontSize: 18,
),
),
),
],
),
),
),
if (state.destination != null) ...[
const SizedBox(height: T.s12),
TripzButton(
label: l10n.requestRide,
onPressed: () => _openRoutePreview(context, state),
),
],
],
);
},
);
},
),
const Spacer(),
Divider(color: cs.outlineVariant.withValues(alpha: 0.3), height: 1),
const SizedBox(height: T.s12),
// الأماكن المحفوظة (سطر أفقي أنيق)
BlocBuilder<SavedPlacesCubit, SavedPlacesState>(
builder: (context, savedState) {
final items = savedState.places.take(3).toList();
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_buildQuickAction(context, Icons.home_rounded, l10n.homePlace, items.isNotEmpty ? items.first : null),
Container(width: 1, height: 32, color: cs.outlineVariant.withValues(alpha: 0.3)),
_buildQuickAction(context, Icons.work_rounded, l10n.workPlace, items.length > 1 ? items[1] : null),
Container(width: 1, height: 32, color: cs.outlineVariant.withValues(alpha: 0.3)),
_buildQuickAction(context, Icons.star_rounded, l10n.favorites, items.length > 2 ? items[2] : null),
],
);
},
),
const SizedBox(height: T.s8),
],
),
),
)
else
// زر تأكيد الوجهة في وضع اختيار الخريطة
Positioned(
left: 0,
right: 0,
bottom: 0,
child: Container(
padding: const EdgeInsets.fromLTRB(
T.pagePadding, T.s16, T.pagePadding, T.s32),
decoration: BoxDecoration(
color: cs.surface,
borderRadius: const BorderRadius.vertical(
top: Radius.circular(T.r24),
),
boxShadow: const [T.shadowLg],
),
child: FilledButton(
onPressed: _confirmMapDestination,
style: FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(T.r12),
),
),
child: Text('تأكيد الوجهة', style: Theme.of(context).textTheme.titleMedium?.copyWith(color: cs.onPrimary)),
),
),
),
),
// حالة التحميل
BlocBuilder<HomeCubit, HomeState>(
builder: (context, state) {
if (state.loading) {
return Container(
color: Colors.black26,
child: const Center(child: CircularProgressIndicator()),
);
}
return const SizedBox.shrink();
},
),
],
),
),
);
}
void _onPlaceTap(BuildContext context, SavedPlace place) {
context.read<HomeCubit>().setDestination(PlaceModel(
name: place.name,
address: place.address,
lat: place.lat,
lng: place.lng,
));
final state = context.read<HomeCubit>().state;
if (state.pickup != null) {
_openRoutePreview(context, state);
}
}
Set<Marker> _buildMarkers(HomeState state) {
final markers = <Marker>{};
if (state.pickup != null) {
@@ -184,14 +400,65 @@ class _HomeScreenState extends State<HomeScreen> {
}
void _openDestinationSearch(BuildContext context) {
context.push<PlaceModel>('/destination').then((place) {
if (place != null && mounted) {
context.read<HomeCubit>().setDestination(place);
_openRoutePreview(context, context.read<HomeCubit>().state);
final homeCubit = context.read<HomeCubit>();
final pickup = homeCubit.state.pickup;
final currentLocation = homeCubit.state.currentLocation;
context.push<dynamic>('/destination', extra: {
'currentLocation': currentLocation,
}).then((result) {
if (!mounted) return;
if (result is Map && result['pickFromMap'] == true) {
setState(() {
_isSelectingOnMap = true;
});
return;
}
final place = result as PlaceModel?;
if (place != null && pickup != null) {
homeCubit.setDestination(place);
// ignore: use_build_context_synchronously
context.push('/route-preview', extra: {
'pickup': pickup,
'destination': place,
});
}
});
}
Future<void> _confirmMapDestination() async {
final homeCubit = context.read<HomeCubit>();
final target = homeCubit.state.cameraTarget;
if (target == null) return;
// We reverse geocode the target to get the address name
final repo = getIt<MapsRepository>();
try {
final place = await repo.reverseGeocode(target.latitude, target.longitude);
setState(() {
_isSelectingOnMap = false;
});
homeCubit.setDestination(place);
if (homeCubit.state.pickup != null) {
_openRoutePreview(context, homeCubit.state);
}
} catch (_) {
// In case of error, still set it with empty name
setState(() {
_isSelectingOnMap = false;
});
homeCubit.setDestination(PlaceModel(
name: 'موقع محدد على الخريطة',
lat: target.latitude,
lng: target.longitude,
));
if (homeCubit.state.pickup != null) {
_openRoutePreview(context, homeCubit.state);
}
}
}
void _openRoutePreview(BuildContext context, HomeState state) {
if (state.pickup == null || state.destination == null) return;
context.push('/route-preview', extra: {
@@ -199,59 +466,59 @@ class _HomeScreenState extends State<HomeScreen> {
'destination': state.destination,
});
}
}
class _DestinationPreview extends StatelessWidget {
final PlaceModel destination;
final VoidCallback onTap;
final VoidCallback onClear;
void _showLogoutDialog(BuildContext context, AppLocalizations l10n) {
final cs = Theme.of(context).colorScheme;
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text(l10n.logout),
content: Text(l10n.logout),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: Text(l10n.cancel),
),
FilledButton(
onPressed: () async {
Navigator.pop(ctx);
await context.read<AuthCubit>().logout();
if (context.mounted) context.go('/phone');
},
style: FilledButton.styleFrom(backgroundColor: cs.error),
child: Text(l10n.logout),
),
],
),
);
}
const _DestinationPreview({
required this.destination,
required this.onTap,
required this.onClear,
});
@override
Widget build(BuildContext context) {
Widget _buildQuickAction(
BuildContext context, IconData icon, String label, SavedPlace? place) {
final cs = Theme.of(context).colorScheme;
return InkWell(
onTap: onTap,
onTap: place != null ? () => _onPlaceTap(context, place) : null,
borderRadius: BorderRadius.circular(T.r12),
child: Container(
padding: const EdgeInsets.all(T.s12),
decoration: BoxDecoration(
color: cs.surfaceContainerHighest,
borderRadius: BorderRadius.circular(T.r12),
),
child: Row(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: T.s12, vertical: T.s8),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.location_on_outlined, color: cs.error, size: 20),
const SizedBox(width: T.s8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
destination.name,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w500),
maxLines: 1,
overflow: TextOverflow.ellipsis,
Icon(icon,
color: place != null
? cs.primary
: cs.onSurfaceVariant.withValues(alpha: 0.5),
size: 28),
const SizedBox(height: T.s4),
Text(
label,
style: Theme.of(context).textTheme.labelMedium?.copyWith(
color: place != null
? cs.onSurface
: cs.onSurfaceVariant.withValues(alpha: 0.5),
fontWeight:
place != null ? FontWeight.w600 : FontWeight.normal,
),
if (destination.address != null)
Text(
destination.address!,
style: Theme.of(context).textTheme.bodySmall?.copyWith(color: cs.onSurfaceVariant),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
IconButton(
onPressed: onClear,
icon: Icon(Icons.close_rounded, color: cs.onSurfaceVariant, size: 20),
visualDensity: VisualDensity.compact,
),
],
),
@@ -1,8 +1,9 @@
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../core/l10n/app_localizations.dart';
import 'package:go_router/go_router.dart';
import 'package:intaleq_maps/intaleq_maps.dart';
import '../../../core/l10n/app_localizations.dart';
import '../../../core/design/tokens.dart';
import '../../../core/ui/tripz_button.dart';
import '../../trip/bloc/trip_bloc.dart';
@@ -10,9 +11,15 @@ import '../../trip/bloc/trip_state.dart';
import '../../trip/bloc/trip_event.dart';
import '../cubit/quote_cubit.dart';
import '../data/models/place_model.dart';
import '../data/models/route_model.dart';
import '../data/maps_repository.dart';
import '../../../core/di.dart';
import 'widgets/ride_class_card.dart';
/// شاشة معاينة المسار + اختيار فئة الرحلة + تأكيد الطلب.
List<LatLng> _decodePolyline(String encoded) {
return PolylineUtils.decode(encoded);
}
class RoutePreviewScreen extends StatefulWidget {
final PlaceModel pickup;
final PlaceModel destination;
@@ -29,10 +36,16 @@ class RoutePreviewScreen extends StatefulWidget {
class _RoutePreviewScreenState extends State<RoutePreviewScreen> {
IntaleqMapController? _mapController;
RouteModel? _route;
List<LatLng> _polylinePoints = [];
bool _routeLoading = true;
String? _routeError;
final _promoController = TextEditingController();
@override
void initState() {
super.initState();
_fetchRoute();
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<QuoteCubit>().fetchQuote(
pickupLat: widget.pickup.lat,
@@ -45,11 +58,59 @@ class _RoutePreviewScreenState extends State<RoutePreviewScreen> {
});
}
@override
void dispose() {
_promoController.dispose();
super.dispose();
}
Future<void> _fetchRoute() async {
setState(() {
_routeLoading = true;
_routeError = null;
});
try {
final repo = getIt<MapsRepository>();
final route = await repo.getRoute(
fromLat: widget.pickup.lat,
fromLng: widget.pickup.lng,
toLat: widget.destination.lat,
toLng: widget.destination.lng,
);
final points = await compute(_decodePolyline, route.polyline ?? '');
if (!mounted) return;
setState(() {
_route = route;
_polylinePoints = points;
_routeLoading = false;
});
_fitCamera();
} catch (e) {
if (!mounted) return;
setState(() {
_routeError = e.toString();
_routeLoading = false;
});
}
}
void _fitCamera() {
if (_mapController == null) return;
final bounds = _route?.getLatLngBounds();
if (bounds != null) {
_mapController!.moveCamera(CameraUpdate.newLatLngBounds(bounds));
} else {
_mapController!.moveCamera(CameraUpdate.newLatLngZoom(
LatLng(widget.pickup.lat, widget.pickup.lng),
15,
));
}
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final cs = Theme.of(context).colorScheme;
final pickupLoc = LatLng(widget.pickup.lat, widget.pickup.lng);
final destLoc = LatLng(widget.destination.lat, widget.destination.lng);
@@ -58,185 +119,295 @@ class _RoutePreviewScreenState extends State<RoutePreviewScreen> {
prev.requestStatus != cur.requestStatus &&
cur.requestStatus == TripRequestStatus.searching,
listener: (context, state) {
// تم إنشاء الرحلة — انتقل للتتبع.
context.pushReplacement('/trip-tracking');
},
child: Scaffold(
body: Column(
body: Stack(
children: [
// الخريطة مع المسار
Expanded(
flex: 2,
child: Stack(
children: [
IntaleqMap(
apiKey: '',
initialCameraPosition: CameraPosition(
target: LatLng(
(pickupLoc.latitude + destLoc.latitude) / 2,
(pickupLoc.longitude + destLoc.longitude) / 2,
),
zoom: 14,
// الخريطة بكامل الشاشة
if (_routeLoading)
const Center(child: CircularProgressIndicator())
else if (_routeError != null)
Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(l10n.errorGeneric),
const SizedBox(height: T.s12),
TripzButton(
label: l10n.retry,
onPressed: _fetchRoute,
),
myLocationEnabled: false,
zoomControlsEnabled: false,
compassEnabled: false,
onMapCreated: (c) => _mapController = c,
markers: {
Marker(
markerId: const MarkerId('pickup'),
position: pickupLoc,
icon: InlqBitmap.defaultMarkerWithHue(210),
anchor: const Offset(0.5, 1.0),
),
Marker(
markerId: const MarkerId('destination'),
position: destLoc,
icon: InlqBitmap.defaultMarkerWithHue(0),
anchor: const Offset(0.5, 1.0),
),
},
polylines: {
Polyline(
polylineId: const PolylineId('route'),
points: [pickupLoc, destLoc],
color: cs.primary,
width: 4,
),
},
],
),
)
else
IntaleqMap(
apiKey: '',
initialCameraPosition: CameraPosition(
target: LatLng(
(pickupLoc.latitude + destLoc.latitude) / 2,
(pickupLoc.longitude + destLoc.longitude) / 2,
),
Positioned(
top: MediaQuery.of(context).padding.top + T.s8,
left: T.s12,
child: FloatingActionButton.small(
heroTag: 'back',
backgroundColor: cs.surface,
onPressed: () => context.pop(),
child: const Icon(Icons.arrow_back_rounded),
zoom: 14,
),
mapType: Theme.of(context).brightness == Brightness.dark
? IntaleqMapType.normal
: IntaleqMapType.light,
myLocationEnabled: false,
zoomControlsEnabled: false,
compassEnabled: false,
onMapCreated: (c) {
_mapController = c;
_fitCamera();
},
markers: {
Marker(
markerId: const MarkerId('pickup'),
position: pickupLoc,
icon: InlqBitmap.defaultMarkerWithHue(210),
anchor: const Offset(0.5, 1.0),
),
Marker(
markerId: const MarkerId('destination'),
position: destLoc,
icon: InlqBitmap.defaultMarkerWithHue(0),
anchor: const Offset(0.5, 1.0),
),
},
polylines: {
// حماية محرك C++ من الانهيار إذا كانت النقاط أقل من 2
if (_polylinePoints.length >= 2)
Polyline(
polylineId: const PolylineId('route'),
points: _polylinePoints,
color: cs.primary,
width: T.polylineWidth,
),
),
Positioned(
top: MediaQuery.of(context).padding.top + T.s8,
right: T.s12,
child: BlocBuilder<QuoteCubit, QuoteState>(
builder: (context, state) {
if (state.quote == null) return const SizedBox.shrink();
return Container(
padding: const EdgeInsets.symmetric(horizontal: T.s12, vertical: T.s8),
decoration: BoxDecoration(
color: cs.surface,
borderRadius: BorderRadius.circular(T.r12),
boxShadow: [T.shadowSm],
),
child: Text(
l10n.routeSummary(
state.quote!.distanceText ?? '',
state.quote!.durationText ?? '',
),
style: Theme.of(context).textTheme.labelLarge,
),
);
},
),
),
],
},
),
// زر الرجوع العائم (Top Left)
Positioned(
top: MediaQuery.of(context).padding.top + T.s8,
left: T.s12,
child: FloatingActionButton.small(
heroTag: 'back',
backgroundColor: cs.surface.withValues(alpha: 0.9),
elevation: 4,
onPressed: () => context.pop(),
child: Icon(Icons.arrow_back_rounded, color: cs.onSurface),
),
),
// قائمة فئات الرحلة
Expanded(
flex: 3,
// ملخص المسار العائم (Top Right)
Positioned(
top: MediaQuery.of(context).padding.top + T.s12,
right: T.s12,
child: BlocBuilder<QuoteCubit, QuoteState>(
builder: (context, state) {
if (state.quote == null) return const SizedBox.shrink();
return Container(
padding: const EdgeInsets.symmetric(
horizontal: T.s16, vertical: T.s12),
decoration: BoxDecoration(
color: cs.surface.withValues(alpha: 0.95),
borderRadius: BorderRadius.circular(T.r24),
boxShadow: const [T.shadowSm],
),
child: Text(
l10n.routeSummary(
state.quote!.distanceText ?? '',
state.quote!.durationText ?? '',
),
style: Theme.of(context).textTheme.labelLarge?.copyWith(
fontWeight: FontWeight.w700,
color: cs.onSurface,
),
),
);
},
),
),
// Bottom Sheet: فئات الرحلات
Align(
alignment: Alignment.bottomCenter,
child: Container(
color: cs.surface,
child: BlocBuilder<QuoteCubit, QuoteState>(
builder: (context, state) {
if (state.loading) {
return const Center(child: CircularProgressIndicator());
}
if (state.error != null) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(l10n.errorGeneric),
const SizedBox(height: T.s12),
TripzButton(
label: l10n.retry,
onPressed: () => context.read<QuoteCubit>().fetchQuote(
pickupLat: widget.pickup.lat,
pickupLng: widget.pickup.lng,
pickupAddress: widget.pickup.name,
dropoffLat: widget.destination.lat,
dropoffLng: widget.destination.lng,
dropoffAddress: widget.destination.name,
constraints: BoxConstraints(
maxHeight: MediaQuery.of(context).size.height * 0.55,
),
decoration: BoxDecoration(
color: cs.surface,
borderRadius: const BorderRadius.vertical(
top: Radius.circular(24),
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.1),
blurRadius: 20,
offset: const Offset(0, -5),
)
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// شريط السحب (Grab handle)
const SizedBox(height: T.s12),
Container(
width: 40,
height: 5,
decoration: BoxDecoration(
color: cs.outlineVariant.withValues(alpha: 0.5),
borderRadius: BorderRadius.circular(10),
),
),
const SizedBox(height: T.s12),
Expanded(
child: BlocBuilder<QuoteCubit, QuoteState>(
builder: (context, state) {
if (state.loading) {
return const Center(
child: CircularProgressIndicator());
}
if (state.error != null) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(l10n.errorGeneric,
style: Theme.of(context)
.textTheme
.bodyLarge
?.copyWith(color: cs.error)),
const SizedBox(height: T.s12),
TripzButton(
label: l10n.retry,
onPressed: () => context
.read<QuoteCubit>()
.fetchQuote(
pickupLat: widget.pickup.lat,
pickupLng: widget.pickup.lng,
pickupAddress: widget.pickup.name,
dropoffLat: widget.destination.lat,
dropoffLng: widget.destination.lng,
dropoffAddress:
widget.destination.name,
),
),
),
],
),
);
}
],
),
);
}
final classes = state.quote?.classes ?? [];
if (classes.isEmpty) {
return Center(child: Text(l10n.noResults));
}
final classes = state.quote?.classes ?? [];
if (classes.isEmpty) {
return Center(child: Text(l10n.noResults));
}
return Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(T.pagePadding, T.s16, T.pagePadding, T.s8),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: Text(l10n.rideClasses, style: Theme.of(context).textTheme.titleMedium),
),
),
Expanded(
child: ListView.separated(
padding: const EdgeInsets.symmetric(horizontal: T.pagePadding),
itemCount: classes.length,
separatorBuilder: (_, __) => const SizedBox(height: T.s8),
itemBuilder: (context, index) {
final cls = classes[index];
return RideClassCard(
quoteClass: cls,
selected: state.selectedClass == cls.vehicleClass,
onTap: () => context.read<QuoteCubit>().selectClass(cls.vehicleClass),
);
},
),
),
SafeArea(
child: Padding(
padding: const EdgeInsets.all(T.pagePadding),
child: Column(
children: [
_PaymentRow(
method: state.paymentMethod,
onChanged: (m) => context.read<QuoteCubit>().setPaymentMethod(m),
),
const SizedBox(height: T.s12),
// زر طلب الرحلة — يستخدم TripBloc
BlocBuilder<TripBloc, TripState>(
builder: (context, tripState) {
final isLoading = tripState.requestStatus == TripRequestStatus.loading;
return SizedBox(
width: double.infinity,
child: TripzButton(
label: isLoading ? l10n.loading : l10n.requestRide,
onPressed: (state.selectedClass != null && !isLoading)
? () => _requestTrip(context, state)
: null,
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: T.pagePadding),
child: Text(
l10n.rideClasses,
style: Theme.of(context)
.textTheme
.titleLarge
?.copyWith(
fontWeight: FontWeight.w800,
letterSpacing: -0.5,
),
),
),
const SizedBox(height: T.s12),
Expanded(
child: ListView.separated(
padding: const EdgeInsets.symmetric(
horizontal: T.pagePadding),
itemCount: classes.length,
separatorBuilder: (_, __) =>
const SizedBox(height: T.s12),
itemBuilder: (context, index) {
final cls = classes[index];
return RideClassCard(
quoteClass: cls,
selected: state.selectedClass ==
cls.vehicleClass,
onTap: () => context
.read<QuoteCubit>()
.selectClass(cls.vehicleClass),
);
},
),
],
),
),
),
],
);
},
),
// شريط الدفع وكود الخصم
Container(
padding: const EdgeInsets.fromLTRB(
T.pagePadding, T.s12, T.pagePadding, T.s8),
decoration: BoxDecoration(
color: cs.surface,
border: Border(
top: BorderSide(
color: cs.outlineVariant
.withValues(alpha: 0.3),
),
),
),
child: Column(
children: [
_PaymentRow(
method: state.paymentMethod,
onChanged: (m) => context
.read<QuoteCubit>()
.setPaymentMethod(m),
),
const SizedBox(height: T.s12),
_PromoRow(
controller: _promoController,
onApply: (code) => context
.read<QuoteCubit>()
.setCouponCode(code),
),
],
),
),
// زر طلب الرحلة
SafeArea(
top: false,
child: Padding(
padding: const EdgeInsets.fromLTRB(
T.pagePadding, 0, T.pagePadding, T.s12),
child: BlocBuilder<TripBloc, TripState>(
builder: (context, tripState) {
final isLoading =
tripState.requestStatus ==
TripRequestStatus.loading;
return TripzButton(
label: isLoading
? l10n.loading
: l10n.requestRide,
onPressed:
(state.selectedClass != null &&
!isLoading)
? () =>
_requestTrip(context, state)
: null,
);
},
),
),
),
],
);
},
),
),
],
),
),
),
@@ -274,7 +445,8 @@ class _PaymentRow extends StatelessWidget {
final cs = Theme.of(context).colorScheme;
return Container(
padding: const EdgeInsets.symmetric(horizontal: T.pagePadding, vertical: T.s12),
padding: const EdgeInsets.symmetric(
horizontal: T.pagePadding, vertical: T.s12),
decoration: BoxDecoration(
color: cs.surfaceContainerHighest,
borderRadius: BorderRadius.circular(T.r12),
@@ -282,11 +454,14 @@ class _PaymentRow extends StatelessWidget {
child: Row(
children: [
Icon(
method == 'wallet' ? Icons.account_balance_wallet_outlined : Icons.money_rounded,
method == 'wallet'
? Icons.account_balance_wallet_outlined
: Icons.money_rounded,
color: cs.onSurfaceVariant,
),
const SizedBox(width: T.s12),
Text(l10n.paymentMethod, style: Theme.of(context).textTheme.bodyMedium),
Text(l10n.paymentMethod,
style: Theme.of(context).textTheme.bodyMedium),
const Spacer(),
DropdownButton<String>(
value: method,
@@ -294,7 +469,8 @@ class _PaymentRow extends StatelessWidget {
isDense: true,
items: [
DropdownMenuItem(value: 'cash', child: Text(l10n.cash)),
DropdownMenuItem(value: 'wallet', child: Text(l10n.walletPayment)),
DropdownMenuItem(
value: 'wallet', child: Text(l10n.walletPayment)),
],
onChanged: (v) {
if (v != null) onChanged(v);
@@ -305,3 +481,60 @@ class _PaymentRow extends StatelessWidget {
);
}
}
class _PromoRow extends StatefulWidget {
final TextEditingController controller;
final ValueChanged<String?> onApply;
const _PromoRow({required this.controller, required this.onApply});
@override
State<_PromoRow> createState() => _PromoRowState();
}
class _PromoRowState extends State<_PromoRow> {
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final cs = Theme.of(context).colorScheme;
return Container(
padding:
const EdgeInsets.symmetric(horizontal: T.pagePadding, vertical: T.s8),
decoration: BoxDecoration(
color: cs.surfaceContainerHighest,
borderRadius: BorderRadius.circular(T.r12),
),
child: Row(
children: [
Icon(
Icons.local_offer_outlined,
color: cs.onSurfaceVariant,
),
const SizedBox(width: T.s12),
Expanded(
child: TextField(
controller: widget.controller,
decoration: InputDecoration(
hintText: l10n.couponCode,
border: InputBorder.none,
isDense: true,
contentPadding: EdgeInsets.zero,
),
style: Theme.of(context).textTheme.bodyMedium,
),
),
TripzButton(
label: l10n.confirm,
style: TripzButtonStyle.text,
fullWidth: false,
onPressed: () {
final code = widget.controller.text.trim();
widget.onApply(code.isEmpty ? null : code);
},
),
],
),
);
}
}
@@ -23,52 +23,64 @@ class RideClassCard extends StatelessWidget {
return InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(T.r12),
borderRadius: BorderRadius.circular(T.r16),
child: Container(
padding: const EdgeInsets.all(T.pagePadding),
padding: const EdgeInsets.symmetric(horizontal: T.s16, vertical: T.s12),
decoration: BoxDecoration(
color: selected ? cs.primaryContainer : cs.surfaceContainerHighest,
borderRadius: BorderRadius.circular(T.r12),
color: selected ? cs.primaryContainer.withValues(alpha: 0.2) : Colors.transparent,
borderRadius: BorderRadius.circular(T.r16),
border: Border.all(
color: selected ? cs.primary : Colors.transparent,
width: 2,
color: selected ? cs.primary : cs.outlineVariant.withValues(alpha: 0.3),
width: selected ? 2 : 1,
),
),
child: Row(
children: [
// أيقونة المركبة
Container(
width: 48,
height: 48,
width: 56,
height: 56,
decoration: BoxDecoration(
color: selected ? cs.primary : cs.surface,
color: selected ? cs.primary.withValues(alpha: 0.1) : cs.surfaceContainerHighest,
shape: BoxShape.circle,
),
child: Icon(
Icons.directions_car_filled_rounded,
color: selected ? cs.onPrimary : cs.onSurfaceVariant,
size: 24,
child: Center(
child: Icon(
Icons.directions_car_filled_rounded,
color: selected ? cs.primary : cs.onSurfaceVariant,
size: 32,
),
),
),
const SizedBox(width: T.s12),
const SizedBox(width: T.s16),
// اسم الفئة + السعة
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
quoteClass.name,
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
fontWeight: FontWeight.w600,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
color: cs.onSurface,
),
),
const SizedBox(height: 2),
Text(
l10n.capacity(quoteClass.capacity),
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: cs.onSurfaceVariant,
),
Row(
children: [
Icon(Icons.person_outline_rounded,
size: 14, color: cs.onSurfaceVariant),
const SizedBox(width: 4),
Text(
l10n.capacity(quoteClass.capacity),
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: cs.onSurfaceVariant,
fontWeight: FontWeight.w500,
),
),
],
),
],
),
@@ -77,19 +89,21 @@ class RideClassCard extends StatelessWidget {
// الوقت التقديري + السعر
Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
quoteClass.estimatedTimeText,
style: Theme.of(context).textTheme.labelMedium?.copyWith(
color: cs.onSurfaceVariant,
'${quoteClass.price} ${quoteClass.currency}',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w800,
color: selected ? cs.primary : cs.onSurface,
),
),
const SizedBox(height: 2),
Text(
'${quoteClass.price} ${quoteClass.currency}',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
color: selected ? cs.primary : cs.onSurface,
quoteClass.estimatedTimeText,
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: cs.onSurfaceVariant,
fontWeight: FontWeight.w600,
),
),
],