// main.dart
// Entry point of the app and global configuration.
// This file initializes Firebase, sets up localization, and launches the main app widget.

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:trainerbox/firebase_options.dart';
import 'screens/home_screen.dart';
import 'screens/login_screen.dart';
import 'screens/search_tab.dart';
import 'package:intl/date_symbol_data_local.dart';

/// Main entry point for the Flutter application.
void main() async {
  // Ensures that widget binding is initialized before using platform channels.
  WidgetsFlutterBinding.ensureInitialized();
  // Initialize Firebase with platform-specific options.
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  // Initialize date formatting for German locale.
  await initializeDateFormatting('de_DE', null);
  // Start the app.
  runApp(const MyApp());
}

/// The root widget of the application.
class MyApp extends StatefulWidget {
  const MyApp({super.key});

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

/// State for the main app widget, manages login state and routing.
class _MyAppState extends State<MyApp> {
  bool _loggedIn = false;

  /// Called when login is successful.
  void _handleLoginSuccess() {
    setState(() {
      _loggedIn = true;
    });
  }

  /// Called when logout is successful.
  void _handleLogoutSuccess() {
    setState(() {
      _loggedIn = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'TrainerBox',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
        useMaterial3: true,
      ),
      // Show HomeScreen if logged in, otherwise show LoginScreen.
      home: _loggedIn
          ? HomeScreen(onLogoutSuccess: _handleLogoutSuccess)
          : LoginScreen(onLoginSuccess: _handleLoginSuccess),
      // Define named routes for navigation.
      routes: {
        '/search': (context) => SearchTab(
          selectMode: (ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>?)?['selectMode'] ?? false,
          remainingTime: (ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>?)?['remainingTime'] as int?,
        ),
      },
    );
  }
}
