class MyApp extends StatefulWidget {
  const MyApp({super.key});
  @override
  State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  late final AuthNotifier _auth;
  late final GoRouter _router;
  @override
  void initState() {
    super.initState();
    _auth = AuthNotifier();
    _router = GoRouter(
      // This makes go_router re-check redirect whenever auth/ready changes
      refreshListenable: _auth,
      routes: [
        GoRoute(path: '/', builder: (_, __) => const HomeView()),
        GoRoute(path: '/login', builder: (_, __) => const LoginView()),
        GoRoute(path: '/loading', builder: (_, __) => const LoadingView()),
        GoRoute(
          path: '/wallet/:walletId',
          builder: (_, state) =>
              WalletView(walletId: state.pathParameters['walletId']!),
        ),
      ],
      redirect: (context, state) {
        final inLogin = state.matchedLocation == '/login';
        final inLoading = state.matchedLocation == '/loading';
        switch (_auth.phase) {
          case AuthPhase.loading:
            // While SDK/user are loading, keep users on /loading
            return inLoading ? null : '/loading';
          case AuthPhase.unauthenticated:
            // If not logged in, force /login except when already there
            return inLogin ? null : '/login';
          case AuthPhase.authenticated:
            // If logged in, keep them off /login and /loading
            if (inLogin || inLoading) return '/';
            return null;
        }
      },
    );
  }
  @override
  void dispose() {
    _auth.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      title: 'Flutter Demo',
      routerDelegate: _router.routerDelegate,
      routeInformationParser: _router.routeInformationParser,
      routeInformationProvider: _router.routeInformationProvider,
      builder: (context, child) {
        if (child == null) return const SizedBox.shrink();
        return Stack(
          children: [
            child,
            // Keep Dynamic overlay/widget above your pages
            DynamicSDK.instance.dynamicWidget,
          ],
        );
      },
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
    );
  }
}