import 'dart:async';
import 'dart:io' show Platform;

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:just_audio_background/just_audio_background.dart';

import 'app/app.dart';
import 'data/local/hive_boxes.dart';
import 'data/local/models/app_settings.dart';
import 'data/services/notification_inbox_service.dart';
import 'data/services/notification_orchestrator_service.dart';
import 'data/services/remote_push_service.dart';
import 'data/services/background_sync_service.dart';
import 'data/services/notification_service.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize Hive and open all boxes
  await initHive();

  // Load environment variables
  await dotenv.load(fileName: '.env');

  // Seed default settings and checklist items on first launch
  await seedDefaults();

  // Ensure intl DateFormat locale data is ready before any localized formatting.
  await initializeDateFormatting('id_ID');

  // Initialize local notifications for adzan/iqamah scheduling
  await NotificationService.instance.init();
  if (Platform.isAndroid || Platform.isIOS) {
    await BackgroundSyncService.instance.init();
    await BackgroundSyncService.instance.registerPeriodicSync();
  }
  await RemotePushService.instance.init();

  // Run passive notification checks at startup (inbox cleanup/content sync).
  final settingsBox = Hive.box<AppSettings>(HiveBoxes.settings);
  final settings = settingsBox.get('default') ?? AppSettings();
  // Cleanup legacy mirrored prayer inbox items.
  await NotificationInboxService.instance.removeByType('prayer');
  unawaited(NotificationService.instance.syncHabitNotifications(
    settings: settings,
  ));
  unawaited(NotificationOrchestratorService.instance.runPassivePass(
    settings: settings,
  ));

  await JustAudioBackground.init(
    androidNotificationChannelId: 'com.jamshalat.app.audio',
    androidNotificationChannelName: 'Murattal Playback',
    androidNotificationOngoing: true,
  );

  runApp(
    const ProviderScope(
      child: App(),
    ),
  );
}
