import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:connectivity_plus/connectivity_plus.dart';

import 'package:marco/helpers/services/app_initializer.dart';
import 'package:marco/view/my_app.dart';
import 'package:marco/helpers/theme/app_notifier.dart';
import 'package:marco/helpers/services/app_logger.dart';
import 'package:marco/view/layouts/offline_screen.dart';

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

  await initLogging();
  logSafe("App starting...");

  try {
    await initializeApp();
    logSafe("App initialized successfully.");

    runApp(
      ChangeNotifierProvider<AppNotifier>(
        create: (_) => AppNotifier(),
        child: const MainWrapper(),
      ),
    );
  } catch (e, stacktrace) {
    logSafe(
      'App failed to initialize.',
      level: LogLevel.error,
      error: e,
      stackTrace: stacktrace,
    );

    runApp(
      const MaterialApp(
        home: Scaffold(
          body: Center(
            child: Text(
              "Failed to initialize the app.",
              style: TextStyle(color: Colors.red),
            ),
          ),
        ),
      ),
    );
  }
}

/// This widget listens to connectivity changes and switches between
/// `MyApp` and `OfflineScreen` automatically.
class MainWrapper extends StatefulWidget {
  const MainWrapper({super.key});

  @override
  State<MainWrapper> createState() => _MainWrapperState();
}

class _MainWrapperState extends State<MainWrapper> {
  // Use a List to store connectivity status as the API now returns a list
  List<ConnectivityResult> _connectivityStatus = [ConnectivityResult.none];
  final Connectivity _connectivity = Connectivity();

  @override
  void initState() {
    super.initState();
    _initializeConnectivity();
    // Listen for changes, the callback now provides a List<ConnectivityResult>
    _connectivity.onConnectivityChanged.listen((List<ConnectivityResult> results) {
      setState(() {
        _connectivityStatus = results;
      });
    });
  }

  Future<void> _initializeConnectivity() async {
    // checkConnectivity() now returns a List<ConnectivityResult>
    final result = await _connectivity.checkConnectivity();
    setState(() {
      _connectivityStatus = result;
    });
  }

  @override
  Widget build(BuildContext context) {
    // Check if any of the connectivity results indicate no internet
    final bool isOffline = _connectivityStatus.contains(ConnectivityResult.none);

    // Show OfflineScreen if no internet
    if (isOffline) {
      return const MaterialApp(
        debugShowCheckedModeBanner: false,
        home: OfflineScreen(),
      );
    }

    // Show main app if online
    return const MyApp();
  }
}