import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_localizations/flutter_localizations.dart'; // Localization
import 'package:hive_flutter/hive_flutter.dart';
import 'models/sake_item.dart';
import 'models/user_profile.dart';
import 'models/menu_settings.dart';
import 'providers/theme_provider.dart';
import 'screens/main_screen.dart';
import 'services/migration_service.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // Initialize Hive
  await Hive.initFlutter();
  
  // Register Adapters
  Hive.registerAdapter(SakeItemAdapter());
  Hive.registerAdapter(UserProfileAdapter());
  Hive.registerAdapter(MenuSettingsAdapter());
  // Phase 0 New Adapters
  Hive.registerAdapter(DisplayDataAdapter());
  Hive.registerAdapter(HiddenSpecsAdapter());
  Hive.registerAdapter(UserDataAdapter());
  Hive.registerAdapter(GamificationAdapter());
  Hive.registerAdapter(MetadataAdapter());
  Hive.registerAdapter(ItemTypeAdapter());

  // Run Phase 0 Migration (Backup & Convert)
  await MigrationService.runMigration();

  // Open Boxes
  final userProfileBox = await Hive.openBox<UserProfile>('user_profile');
  await Hive.openBox<SakeItem>('sake_items'); // Already opened by Migration, but safe to call again
  await Hive.openBox('settings'); // Generic box for app settings (sort order)
  await Hive.openBox<MenuSettings>('menu_settings'); // Menu display settings

  runApp(
    ProviderScope(
      overrides: [
        userProfileBoxProvider.overrideWithValue(userProfileBox),
      ],
      child: const MyApp(),
    ),
  );
}

class MyApp extends ConsumerWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final lightTheme = ref.watch(lightThemeProvider);
    final darkTheme = ref.watch(darkThemeProvider);
    final themeMode = ref.watch(themeModeProvider);

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Ponshu Room Lite',
      theme: lightTheme,
      darkTheme: darkTheme,
      themeMode: themeMode,
      
       // Localization Fix for DatePicker & Menu
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('ja', 'JP'),
      ],

      home: const MainScreen(),
    );
  }
}
