import 'dart:async';
import 'package:client_authentication/src/domain/repositories/auth_repository_interface.dart';
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:krow_core/core.dart';

class ClientIntroPage extends StatefulWidget {
  const ClientIntroPage({super.key});

  @override
  State<ClientIntroPage> createState() => _ClientIntroPageState();
}

class _ClientIntroPageState extends State<ClientIntroPage> {
  @override
  void initState() {
    super.initState();
    _checkSession();
  }

  Future<void> _checkSession() async {
    // Check session immediately without artificial delay
    if (!mounted) return;

    try {
      final AuthRepositoryInterface authRepo = Modular.get<AuthRepositoryInterface>();
      // Add a timeout to prevent infinite loading
      final user = await authRepo.restoreSession().timeout(
        const Duration(seconds: 5),
        onTimeout: () {
          throw TimeoutException('Session restore timed out');
        },
      );
      
      if (mounted) {
        if (user != null) {
           Modular.to.navigate(ClientPaths.home);
        } else {
           Modular.to.navigate(ClientPaths.getStarted); 
        }
      }
    } catch (e) {
      debugPrint('ClientIntroPage: Session check error: $e');
      if (mounted) {
         Modular.to.navigate(ClientPaths.getStarted);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).colorScheme.surface,
      body: Center(
        child: Image.asset(
          'assets/logo-blue.png',
          package: 'design_system',
          width: 120,
        ),
      ),
    );
  }
}
