import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';

import '../../../../core/network/ws_client.dart';
import '../../../../core/theme/app_theme.dart';
import '../../../../core/widgets/game_ui.dart';
import '../../../../core/widgets/player_avatar.dart';
import '../bloc/game_bloc.dart';
import '../bloc/game_state.dart';
import 'game_screen.dart';

part 'private_table_screen.parts.dart';

/// میز خصوصی: اتاق انتظار (کد، بازیکنان، شروع) سپس صحنه‌ی بازی (روی همان اتصال).
class PrivateTableScreen extends StatelessWidget {
  const PrivateTableScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<GameBloc, GameUiState>(
      listenWhen:
          (a, b) =>
              (a.notice != b.notice && b.notice != null) ||
              (!a.tableClosed && b.tableClosed),
      listener: (context, state) {
        if (state.tableClosed) {
          if (context.canPop()) context.pop();
          return;
        }
        if (state.notice != null) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(state.notice!),
              duration: const Duration(seconds: 2),
            ),
          );
          context.read<GameBloc>().clearNotice();
        }
      },
      builder: (context, state) {
        if (state.state != null) {
          return const GameScreen(prize: 0);
        }
        return _LobbyView(state: state);
      },
    );
  }
}
