import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:window_manager/window_manager.dart';
import 'providers/price_provider.dart';
import 'providers/update_provider.dart';
import 'screens/home_screen.dart';
import 'services/notification_service.dart';
import 'widgets/loading_screen.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Load environment variables
  await dotenv.load(fileName: ".env");

  // Initialize notification service
  await NotificationService().initialize();
  await NotificationService().requestPermissions();

  // Initialize window manager for desktop only (not web)
  if (!kIsWeb && (defaultTargetPlatform == TargetPlatform.windows ||
      defaultTargetPlatform == TargetPlatform.macOS ||
      defaultTargetPlatform == TargetPlatform.linux)) {
    await windowManager.ensureInitialized();

    WindowOptions windowOptions = const WindowOptions(
      size: Size(1400, 900),
      minimumSize: Size(1000, 700),
      center: true,
      backgroundColor: Color(0xFF0A0E27),
      skipTaskbar: false,
      titleBarStyle: TitleBarStyle.hidden,
      title: 'rmtPocketWatcher',
    );

    windowManager.waitUntilReadyToShow(windowOptions, () async {
      await windowManager.show();
      await windowManager.focus();
      
      // Initialize window service after window is ready
      // Context will be set later from the home screen
    });
  }

  runApp(const MyApp());
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _isInitialized = false;

  void _onInitializationComplete() {
    setState(() {
      _isInitialized = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => PriceProvider()),
        ChangeNotifierProvider(create: (_) => UpdateProvider()),
      ],
      child: MaterialApp(
        title: 'rmtPocketWatcher',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          colorScheme: const ColorScheme.dark(
            primary: Color(0xFF50E3C2), // Cyan accent
            secondary: Color(0xFF50E3C2),
            surface: Color(0xFF1A1F3A), // Main background
            onSurface: Colors.white,
          ),
          scaffoldBackgroundColor: const Color(0xFF0A0E27),
          useMaterial3: true,
          fontFamily: 'monospace', // Terminal-style font
        ),
        home: _isInitialized 
          ? const HomeScreen() 
          : SplashScreen(onInitializationComplete: _onInitializationComplete),
      ),
    );
  }
}
