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

import 'package:on_field_work/helpers/services/app_initializer.dart';
import 'package:on_field_work/view/my_app.dart';
import 'package:on_field_work/helpers/theme/app_notifier.dart';
import 'package:on_field_work/helpers/services/app_logger.dart';
import 'package:on_field_work/helpers/services/storage/local_storage.dart';

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

  // Initialize logging system
  await initLogging();
  logSafe("App starting...");

  // ✅ Ensure local storage is ready before enabling remote logging
  await LocalStorage.init();
  logSafe("💡 Local storage initialized (early init for logging).");

  // Now safe to enable remote logging
  enableRemoteLogging();

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

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

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

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

  @override
  Widget build(BuildContext context) {
    // 1. Use FutureBuilder to check the current connectivity status ONCE.
    return FutureBuilder<List<ConnectivityResult>>(
      future: Connectivity().checkConnectivity(),
      builder: (context, initialSnapshot) {
        // If the initial check is still running, display a standard loading screen.
        if (!initialSnapshot.hasData) {
          return const MaterialApp(
            home: Center(child: CircularProgressIndicator()),
          );
        }

        // 2. Once the initial status is known, use StreamBuilder for real-time updates.
        return StreamBuilder<List<ConnectivityResult>>(
          stream: Connectivity().onConnectivityChanged,
          // 💡 CRITICAL: Use the actual result from the FutureBuilder as the initial data.
          initialData: initialSnapshot.data!,
          builder: (context, streamSnapshot) {
            final List<ConnectivityResult> results =
                streamSnapshot.data ?? [ConnectivityResult.none];
            final bool isOffline = results.contains(ConnectivityResult.none);

            // Pass the accurate connectivity status down to MyApp.
            return MyApp(isOffline: isOffline);
          },
        );
      },
    );
  }
}
