import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart'; // For WidgetsBinding
import 'package:flutter/scheduler.dart'; // For SchedulerPhase

class LogManager {
  static final LogManager _instance = LogManager._internal();
  factory LogManager() => _instance;
  LogManager._internal();

  final ValueNotifier<List<String>> logs = ValueNotifier([]);

  void addLog(String message) {
    try {
      final timestamp = DateTime.now().toString().split(' ')[1].split('.')[0];
      final logMessage = "[$timestamp] $message";

      // 빌드 중에 호출될 경우를 대비해 스케줄링
      if (WidgetsBinding.instance.schedulerPhase ==
          SchedulerPhase.persistentCallbacks) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          logs.value = [logMessage, ...logs.value];
        });
      } else {
        logs.value = [logMessage, ...logs.value];
      }
    } catch (e) {
      print('LogManager Error: $e');
    }
  }

  void clear() {
    logs.value = [];
  }
}
