import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hive_flutter/hive_flutter.dart';
import '../models/user_profile.dart';

// Provider for the Display Mode
final displayModeProvider = NotifierProvider<DisplayModeNotifier, String>(DisplayModeNotifier.new);

class DisplayModeNotifier extends Notifier<String> {
  late UserProfile _profile;
  late Box<UserProfile> _box;

  @override
  String build() {
    // SplashScreenで開済みのboxに直接アクセス
    _box = Hive.box<UserProfile>('user_profile');
    _profile = _box.get('current_user') ?? UserProfile(createdAt: DateTime.now());
    return _profile.displayMode;
  }

  Future<void> setDisplayMode(String mode) async {
    state = mode;
    _profile.displayMode = mode;
    _profile.updatedAt = DateTime.now();

    // Save to box (use put if not yet in box, otherwise save)
    if (_profile.isInBox) {
      await _profile.save();
    } else {
      await _box.put('current_user', _profile);
    }
  }

  void toggle() {
    setDisplayMode(state == 'list' ? 'grid' : 'list');
  }
}
