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

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

  @override
  State<IntroPage> createState() => _IntroPageState();
}

class _IntroPageState extends State<IntroPage> {
  @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: () {
          // If it takes too long, navigate to Get Started.
          // This handles poor network conditions gracefully.
          throw TimeoutException('Session restore timed out');
        },
      );
      
      if (mounted) {
        if (user != null) {
           Modular.to.navigate(StaffPaths.home);
        } else {
           Modular.to.navigate(StaffPaths.getStarted); 
        }
      }
    } catch (e) {
      debugPrint('IntroPage: Session check error: $e');
      if (mounted) {
         Modular.to.navigate(StaffPaths.getStarted);
      }
    }
  }

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