// lib/main.dart

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

import 'screens/home_screen.dart';
import 'screens/home_desktop_screen.dart';
import 'screens/login_screen.dart';
import 'screens/desktop_login_screen.dart';
import 'screens/responsive_layout.dart'; // keep this path if your file is under lib/screens/
import 'core/theme_manager.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await ThemeManager.init(); // load saved theme preference

  // Increase image cache for smoother scrolling and faster re-renders
  PaintingBinding.instance.imageCache.maximumSize = 500;
  PaintingBinding.instance.imageCache.maximumSizeBytes = 200 * 1024 * 1024; // 200 MB

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // Breakpoint used across app: >= => desktop/tablet UI, < => mobile UI
  static const double desktopBreakpoint = 820;

  // Optional: reuse your branded blue swatch if you prefer; simplified here.
  static const MaterialColor primarySwatch = MaterialColor(
    0xFF0B63D6,
    <int, Color>{
      50: Color(0xFFEAF4FF),
      100: Color(0xFFD6EBFF),
      200: Color(0xFFADD6FF),
      300: Color(0xFF85C1FF),
      400: Color(0xFF4FA6FF),
      500: Color(0xFF0B63D6),
      600: Color(0xFF0959C0),
      700: Color(0xFF074EA6),
      800: Color(0xFF05358D),
      900: Color(0xFF04256E),
    },
  );

  static const String _fontFamily = 'Gilroy';

  ThemeData _lightTheme() {
    return ThemeData(
      brightness: Brightness.light,
      fontFamily: _fontFamily,
      primarySwatch: primarySwatch,
      scaffoldBackgroundColor: const Color(0xFFF7F5FB),
      appBarTheme: const AppBarTheme(
        backgroundColor: Colors.white,
        foregroundColor: Colors.black87,
        elevation: 0,
      ),
      elevatedButtonTheme: ElevatedButtonThemeData(
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFF0B63D6),
          foregroundColor: Colors.white,
        ),
      ),
      cardColor: Colors.white,
      useMaterial3: false,
    );
  }

  ThemeData _darkTheme() {
    return ThemeData(
      brightness: Brightness.dark,
      fontFamily: _fontFamily,
      primarySwatch: primarySwatch,
      scaffoldBackgroundColor: const Color(0xFF0B1220),
      appBarTheme: const AppBarTheme(
        backgroundColor: Color(0xFF0B1220),
        foregroundColor: Colors.white,
        elevation: 0,
      ),
      elevatedButtonTheme: ElevatedButtonThemeData(
        style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFF0B63D6)),
      ),
      cardColor: const Color(0xFF0E1620),
      textTheme: ThemeData.dark().textTheme.apply(fontFamily: _fontFamily),
      useMaterial3: false,
    );
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<ThemeMode>(
      valueListenable: ThemeManager.themeMode,
      builder: (context, mode, _) {
        return MaterialApp(
          title: 'Event App',
          debugShowCheckedModeBanner: false,
          theme: _lightTheme(),
          darkTheme: _darkTheme(),
          themeMode: mode,
          home: const StartupScreen(),
        );
      },
    );
  }
}

class StartupScreen extends StatefulWidget {
  const StartupScreen({Key? key}) : super(key: key);

  @override
  State<StartupScreen> createState() => _StartupScreenState();
}

class _StartupScreenState extends State<StartupScreen> {
  bool? _loggedIn;

  @override
  void initState() {
    super.initState();
    _loadLoginState();
  }

  Future<void> _loadLoginState() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final hasEmail = prefs.getString('email') != null && prefs.getString('email')!.isNotEmpty;
      setState(() => _loggedIn = hasEmail);
    } catch (e) {
      // If SharedPreferences fails (common on web with plugin issues), default to not logged in
      print('Error loading login state: $e');
      if (mounted) {
        setState(() => _loggedIn = false);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    // While we check local storage show a loader
    if (_loggedIn == null) {
      return const Scaffold(
        body: Center(child: CircularProgressIndicator()),
      );
    }

    // Use LayoutBuilder so we can inspect the actual window width and choose the proper login/home variant.
    return LayoutBuilder(builder: (context, constraints) {
      final width = constraints.maxWidth;
      final isDesktop = width >= MyApp.desktopBreakpoint;

      // If the user is already logged in, show responsive home (mobile or desktop)
      if (_loggedIn == true) {
        return ResponsiveLayout(
          mobile: HomeScreen(),
          desktop: const HomeDesktopScreen(),
        );
      }

      // Not logged in → show login appropriate for the window size
      return isDesktop ? const DesktopLoginScreen() : const LoginScreen();
    });
  }
}
