import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../core/routes.dart';
import '../auth/auth_notifier.dart';
import '../auth/auth_state.dart';

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

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

class _SplashScreenState extends ConsumerState<SplashScreen> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _navigate();
    });
  }

  Future<void> _navigate() async {
    // Jalankan delay splash screen
    await Future.delayed(const Duration(milliseconds: 1500));
    
    // Mengecek apakah sudah login
    await ref.read(authProvider.notifier).checkAuthStatus();
    
    if (!mounted) return;
    
    final state = ref.read(authProvider);
    if (state is AuthSuccess) {
      Navigator.of(context).pushReplacementNamed(AppRoutes.main);
    } else {
      Navigator.of(context).pushReplacementNamed(AppRoutes.landing); // kembali ke landing/login
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: Hero(
          tag: 'appLogo',
          child: Image.asset(
            'assets/images/logo_jamur.png',
            height: 180,
            width: 180,
            fit: BoxFit.contain,
          ),
        ),
      ),
    );
  }
}
