import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get_it/get_it.dart';
import 'package:hl_lieferservice/bloc/app_bloc.dart';
import 'package:hl_lieferservice/bloc/app_events.dart';
import 'package:hl_lieferservice/data/cache/attachment_cache.dart';
import 'package:hl_lieferservice/data/network/network_locator.dart';
import 'package:hl_lieferservice/feature/settings/bloc/settings_bloc.dart';
import 'package:hl_lieferservice/feature/settings/bloc/settings_event.dart';
import 'package:hl_lieferservice/widget/app.dart';

final locator = GetIt.instance;

void main() {
  // Backend-Migration Phase A: HTTP-Stack + Token-Provider registrieren,
  // bevor irgendein Bloc starten kann. Wirft eine Compile-Sicherheit
  // hin, dass `HolzleitnerApi` ab hier per `locator<HolzleitnerApi>()`
  // verfügbar ist.
  registerNetworking(locator: locator);

  // Persistenter Vorschau-Cache für Attachment-Bilder. Über die gesamte
  // App-Lebensdauer stabil und zustandslos (das Verzeichnis löst er lazy
  // selbst auf), daher hier als Singleton.
  locator.registerSingleton<AttachmentCache>(AttachmentCache());

  runApp(MultiBlocProvider(providers: [
    BlocProvider(create: (context) => AppBloc(),),
    BlocProvider(create: (context) => SettingsBloc())
  ], child: App()));
}

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

  @override
  State<StatefulWidget> createState() => _AppState();
}

class _AppState extends State<App> {
  @override
  void initState() {
    super.initState();
    context.read<AppBloc>().add(AppLoadConfig(path: "hl_server_config.json"));
    context.read<SettingsBloc>().add(LoadSettings());
  }

  @override
  Widget build(BuildContext context) {
    return DeliveryApp();
  }
}