import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../integrations/mattermost/mattermost_push_host_integration.dart';
import '../integrations/mattermost/mattermost_push_plugin_client.dart';
import '../integrations/proto_socket/proto_socket_client.dart';
import '../integrations/proto_socket/proto_socket_endpoint_config.dart';
import '../integrations/proto_socket/proto_socket_lifecycle.dart';
import 'nomadcode_client_app.dart';

MattermostPushHostIntegration? _mattermostHost;
final _navigatorKey = GlobalKey<NavigatorState>();

/// proto-socket lifecycle wired with the concrete connector. Bootstrap does
/// NOT auto-connect; an explicit configuration switch owns startup timing.
final _protoSocketLifecycle = ProtoSocketLifecycle(
  connector: RealProtoSocketConnector(),
);
ProtoSocketEndpointConfig? _protoSocketConfig;

MattermostPushHostIntegration _ensureMattermostHost() {
  return _mattermostHost ??= MattermostPushHostIntegration(
    pushClient: MattermostPushPluginClient(),
  );
}

Future<void> applyFullscreenMode() async {
  await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      systemNavigationBarColor: Colors.transparent,
      systemNavigationBarDividerColor: Colors.transparent,
    ),
  );
}

Future<void> bootstrapNomadCodeClient() async {
  await applyFullscreenMode();
  if (!kIsWeb) {
    await Firebase.initializeApp();
    await _ensureMattermostHost().initialize();
  }

  _protoSocketConfig = ProtoSocketEndpointConfig.fromEnv(const {});
}

Future<void> runNomadCodeClient() async {
  WidgetsFlutterBinding.ensureInitialized();
  await bootstrapNomadCodeClient();
  runApp(
    NomadCodeClientApp(
      mattermostHost: _mattermostHost,
      navigatorKey: _navigatorKey,
      protoSocketLifecycle: _protoSocketLifecycle,
      protoSocketConfig: _protoSocketConfig,
    ),
  );
}
