// loading_overlay.dart
import 'package:flutter/material.dart';

class LoadingOverlay {
  static OverlayEntry? _overlayEntry;

  static void show({
    required BuildContext context,
    String message="请稍等...",
    Color barrierColor = Colors.black12,
    Color indicatorColor = Colors.white,
    Widget? customIndicator,
  }) {
    // 先隐藏已存在的loading
    hide();

    _overlayEntry = OverlayEntry(
      builder: (context) => _FullScreenLoading(
        message: message,
        barrierColor: barrierColor,
        indicatorColor: indicatorColor,
        customIndicator: customIndicator,
      ),
    );

    Overlay.of(context).insert(_overlayEntry!);
  }

  static void hide() {
    if (_overlayEntry != null) {
      _overlayEntry?.remove();
      _overlayEntry = null;
    }
  }
}

class _FullScreenLoading extends StatelessWidget {
  final String? message;
  final Color barrierColor;
  final Color indicatorColor;
  final Widget? customIndicator;

  const _FullScreenLoading({
    this.message,
    required this.barrierColor,
    required this.indicatorColor,
    this.customIndicator,
  });

  @override
  Widget build(BuildContext context) {
    return Material(
      color: barrierColor,
      child: Center(
        child: Container(
          padding: EdgeInsets.all(24),
          decoration: BoxDecoration(
            color: Colors.black54,
            borderRadius: BorderRadius.circular(16),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              customIndicator ?? CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(indicatorColor),
                strokeWidth: 3,
              ),
              if (message != null) ...[
                SizedBox(height: 16),
                Text(
                  message!,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                  ),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }
}