import 'package:flutter/widgets.dart';

/// Rebuilds its whole subtree from scratch on demand — used to apply a social
/// identity switch, which re-registers the social singletons in the locator and
/// needs the widget tree (router, screens, sessions) rebuilt to pick them up.
///
/// [builder] is re-invoked on each restart, so it should read its dependencies
/// fresh (e.g. from the service locator) rather than close over stale ones.
class RestartWidget extends StatefulWidget {
  const RestartWidget({required this.builder, super.key});

  final Widget Function() builder;

  /// Tears down and rebuilds everything under the nearest [RestartWidget].
  static void restart(BuildContext context) =>
      context.findAncestorStateOfType<_RestartWidgetState>()?.restart();

  @override
  State<RestartWidget> createState() => _RestartWidgetState();
}

class _RestartWidgetState extends State<RestartWidget> {
  Key _key = UniqueKey();

  void restart() => setState(() => _key = UniqueKey());

  @override
  Widget build(BuildContext context) =>
      KeyedSubtree(key: _key, child: widget.builder());
}
