import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; // Import screenutil
import 'welcome_screen.dart';
import 'main_screen.dart';
import '../services/auth_service.dart'; // Import AuthService
import '../theme/app_colors.dart';

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

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    super.initState();
    _checkLoginHistory();
  }

  Future<void> _checkLoginHistory() async {
    // Simulate loading time (minimum)
    await Future.delayed(const Duration(seconds: 2));

    if (!mounted) return;

    final AuthService authService = AuthService();
    final String? token = await authService.getAccessToken();

    if (token != null) {
      // 토큰이 있으면 메인 화면으로 (자동 로그인)
      if (mounted) {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => const MainScreen()),
        );
      }
    } else {
      // 토큰이 없으면 웰컴 화면으로
      if (mounted) {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => const WelcomeScreen()),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.highlight,
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset('assets/img/maindog.png', width: 150.w, height: 150.h),
            SizedBox(height: 20.h),
            Text(
              'RUP',
              style: TextStyle(
                fontFamily: 'SCDream',
                fontWeight: FontWeight.bold,
                fontSize: 32.sp,
                color: Colors.white,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
