import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:monitoring/screens/home_screen.dart';
import 'package:monitoring/screens/splash_screen.dart';
import 'package:shared_preferences/shared_preferences.dart';

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

void main() => runApp(const MonitoringSantriApp());

class MonitoringSantriApp extends StatelessWidget {
  const MonitoringSantriApp({super.key});

  void _handleLogin(String token, Map<String, dynamic> user) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('token', token);
    await prefs.setString('user', jsonEncode(user));

    navigatorKey.currentState!.pushAndRemoveUntil(
      MaterialPageRoute(builder: (_) => HomeScreen(token: token, user: user)),
      (route) => false,
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Santri Login App',
      theme: ThemeData(primarySwatch: Colors.indigo),
      debugShowCheckedModeBanner: false,
      navigatorKey: navigatorKey,
      home: SplashScreen(onLoginSuccess: _handleLogin),
    );
  }
}
