import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; import '../ui/app_shell.dart'; import '../ui/async_state_views.dart'; import '../../features/auth/data/auth_providers.dart'; import '../../features/auth/presentation/login_screen.dart'; import '../../features/profile/presentation/profile_screen.dart'; import '../../features/recipes/presentation/recipes_screen.dart'; final appRouterProvider = Provider((ref) { final authState = ref.watch(authStateProvider); return GoRouter( initialLocation: '/', redirect: (context, state) { final isLoading = authState.isLoading; final token = authState.valueOrNull; final isLoggedIn = token != null && token.isNotEmpty; final location = state.matchedLocation; final isSplash = location == '/'; final isLogin = location == '/login'; // Keep user on splash while auth state is being resolved from storage. if (isLoading) { return isSplash ? null : '/'; } // Redirect away from splash once auth is known. if (isSplash) { return isLoggedIn ? '/recipes' : '/login'; } // Unauthenticated user trying to reach a protected route. if (!isLoggedIn && !isLogin) { return '/login'; } // Authenticated user landing on login. if (isLoggedIn && isLogin) { return '/recipes'; } return null; }, routes: [ GoRoute( path: '/', builder: (context, state) => const Scaffold( body: LoadingStateView(label: 'Startar...'), ), ), GoRoute( path: '/login', builder: (context, state) => const LoginScreen(), ), ShellRoute( builder: (context, state, child) { return AppShell(location: state.uri.path, child: child); }, routes: [ GoRoute( path: '/recipes', builder: (context, state) => const RecipesScreen(), ), GoRoute( path: '/profile', builder: (context, state) => const ProfileScreen(), ), ], ), ], ); });