import 'package:flutter/material.dart';
import 'dart:async';
import 'package:firebase_database/firebase_database.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'main_page.dart';
import '../../plugins/api.dart';
import '../../dialogs/response_dialog.dart';
import '../../dialogs/yes_no_dialog.dart';
import '../../dialogs/room_setting_dialog.dart';
import '../../dialogs/user_info_private_dialog.dart';
import 'playing_private_page.dart';

// Ads
import '../../plugins/admob.dart';

// Config
import '../../config/config.dart';
// Font size auto-scale
import 'package:auto_size_text/auto_size_text.dart';

class WaitingRoomPrivatePage extends StatefulWidget {
  final int roomSeq;
  final String roomType; // "private"

  const WaitingRoomPrivatePage({
    Key? key,
    required this.roomSeq,
    required this.roomType,
  }) : super(key: key);

  @override
  State<WaitingRoomPrivatePage> createState() => _WaitingRoomPrivatePageState();
}

class _WaitingRoomPrivatePageState extends State<WaitingRoomPrivatePage> {
  // Room settings (방 설정)
  String roomMasterYn = 'N'; // 방장 여부
  String roomTitle = '';
  String roomIntro = '';
  String openYn = 'Y';
  String roomPw = '';
  int runningTime = 1;
  int numberOfPeople = 10;
  String scoreOpenRange = 'PRIVATE';

  // Firebase Realtime Database (FRD)
  late DatabaseReference _roomRef;
  Stream<DatabaseEvent>? _roomStream;
  StreamSubscription<DatabaseEvent>? _roomStreamSubscription;

  // User list (유저 목록)
  List<Map<String, dynamic>> _userList = [];

  bool _isLoading = true;      // 로딩중
  bool _movedToRunningPage = false; // 진행중 화면 이동 중복 방지
  bool _kickedOut = false;     // 강퇴 안내 중복 방지

  String mySeq = '0';          // 내 user_seq

  // Ready button 3-second delay (준비 버튼 3초 딜레이)
  bool _readyButtonEnabled = true;

  // One-hour countdown (1시간 카운트다운)
  Timer? _countdownTimer;
  Duration _remaining = const Duration(hours: 1); 
  DateTime? _createDt;
  bool _roomTimeOut = false;
  String _roomExitYn = 'N';

  // Save room master seq (방장 SEQ)
  String _masterSeqString = '0';

  // Adjust font size by screen width (화면 크기에 따라 폰트 크기 조절)
  double scaleFactor = 1.0;
  double buttonScaleFactor = 1.0;

  @override
  void initState() {
    super.initState();
    // Restore FRD connection (FRD 연결 복원)
    FirebaseDatabase.instance.goOnline();
    _initRoomRef(); // (B) Initialize room info (방 정보 초기화)
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    _roomStreamSubscription?.cancel();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _updateScaleFactor();
  }

  // Adjust font size by screen width (화면 크기에 따라 폰트 크기 조절)
  void _updateScaleFactor() {
    final screenWidth = MediaQuery.of(context).size.width;
    const baseWidth = 450.0;
    setState(() {
      scaleFactor = (screenWidth / baseWidth).clamp(0.8, 1.2);
      buttonScaleFactor = (screenWidth / baseWidth).clamp(0.6, 1.2);
    });
  }

  Future<void> _initRoomRef() async {
    final prefs = await SharedPreferences.getInstance();
    mySeq = prefs.getInt('my_user_seq')?.toString() ?? '0';

    final roomKey = 'korea-${widget.roomSeq}';
    _roomRef = FirebaseDatabase.instance.ref('rooms/$roomKey');

    // onDisconnect + connect_yn='Y'
    final myUserRef = _roomRef.child('userInfo').child('_${mySeq}');
    if (_roomRef.child('userList').child(mySeq) == true) {
      myUserRef.onDisconnect().update({'connect_yn': 'N'});
    }
    await myUserRef.update({'connect_yn': 'Y'});

    _listenRoomData();
  }

  void _listenRoomData() {
    _roomStream = _roomRef.onValue;
    _roomStreamSubscription = _roomStream?.listen((event) {
      final snapshot = event.snapshot;
      if (!snapshot.exists) {
        setState(() {
          _isLoading = false;
          roomTitle = 'No Room Info'; // '방 정보 없음'
          _userList = [];
        });
        _roomMasterLeave(); // 방장 나갔을 때 처리
        return;
      }

      final data = snapshot.value as Map<dynamic, dynamic>? ?? {};
      final roomInfoData = data['roomInfo'] as Map<dynamic, dynamic>? ?? {};
      final userInfoDynamic = data['userInfo'] as Map<dynamic, dynamic>? ?? {};

      final roomStatus = (roomInfoData['room_status'] ?? 'WAIT').toString().toUpperCase();

      final tempList = <Map<String, dynamic>>[];
      // userList
      if (userInfoDynamic is Map) {
        userInfoDynamic.forEach((key, val) {
          if (val is Map) {
            final tempUserSeq = val['user_seq'].toString() ?? '0';
            if (tempUserSeq != '0') {
              tempList.add({
                'user_seq': tempUserSeq,
                'participant_type': val['participant_type'] ?? '',
                'nickname': val['nickname'] ?? 'User', // '유저'
                'team_name': val['team_name'] ?? '',
                'score': val['score'] ?? 0,
                'profile_img': val['profile_img'] ?? '',
                'introduce_myself': val['introduce_myself'] ?? '',
                'ready_yn': (val['ready_yn'] ?? 'N').toString().toUpperCase(),
                'connect_yn': (val['connect_yn'] ?? 'Y').toString().toUpperCase(),
              });
            }
          }
        });
      }

      setState(() {
        roomTitle = (roomInfoData['room_title'] ?? '') as String;
        roomIntro = (roomInfoData['room_intro'] ?? '') as String;
        openYn = (roomInfoData['open_yn'] ?? 'Y') as String;
        roomPw = (roomInfoData['room_pw'] ?? '') as String;
        runningTime = _toInt(roomInfoData['running_time'], 1);
        numberOfPeople = _toInt(roomInfoData['number_of_people'], 10);
        scoreOpenRange = (roomInfoData['score_open_range'] ?? 'PRIVATE') as String;

        // Check if I'm the room master (방장 여부)
        roomMasterYn = 'N';
        final masterSeq = roomInfoData['master_user_seq'].toString();
        if (masterSeq != null && masterSeq == mySeq) {
          roomMasterYn = 'Y';
        }

        if (masterSeq != null) {
          _masterSeqString = masterSeq;
        } else {
          _masterSeqString = '';
        }

        _userList = tempList;
        _isLoading = false;
      });

      // If room status is RUNNING, move to playing page (진행중이면 이동)
      if (roomStatus == 'RUNNING' && !_movedToRunningPage) {
        _movedToRunningPage = true;
        Navigator.pushAndRemoveUntil(
          context,
          MaterialPageRoute(
            builder: (_) => PlayingPrivatePage(
              roomSeq: widget.roomSeq,
              roomTitle: roomTitle,
            ),
          ),
          (route) => false,
        );
        return;
      }

      // 1-hour countdown (1시간 카운트다운)
      final createDtStr = (roomInfoData['create_dt'] ?? '') as String;
      if (createDtStr.isNotEmpty) {
        final dotIndex = createDtStr.indexOf('.');
        final isoStr = createDtStr.substring(0, dotIndex);
        final dt = DateTime.tryParse(isoStr);
        if (dt != null) {
          setState(() {
            _createDt = dt;
          });
          _startCountdownTimer();
        }
      }

      // Check if I'm kicked out (강퇴 여부)
      final amIStillHere = _userList.any((u) => (u['user_seq'].toString() ?? '0') == mySeq);
      if (!amIStillHere && !_kickedOut && roomMasterYn != 'Y') {
        _kickedOut = true;
        if (_roomExitYn == 'N') {
          showResponseDialog(context, 'Notice', 'You have been kicked out.'); 
          // '안내', '강퇴되었습니다.'
        }
        Future.delayed(Duration.zero, () async {
          Navigator.pushAndRemoveUntil(
            context,
            MaterialPageRoute(builder: (_) => const MainPage()),
            (route) => false,
          );
        });
      }

      // Check if room time has ended (방 제한시간 종료)
      if (_roomTimeOut) {
        showResponseDialog(context, 'Notice', 'Room time limit has ended.'); 
        // '안내', '방 제한시간이 종료되었습니다.'
        Future.delayed(Duration.zero, () async {
          Navigator.pushAndRemoveUntil(
            context,
            MaterialPageRoute(builder: (_) => const MainPage()),
            (route) => false,
          );
        });
      }
    }, onError: (error) {
      setState(() {
        _isLoading = false;
        roomTitle = 'Error occurred'; // '오류 발생'
      });
    });
  }

  // When the master leaves (방장이 나갔을 때)
  void _roomMasterLeave() {
    Future.delayed(Duration.zero, () async {
      await showResponseDialog(context, 'Notice', 'The master has left the room.'); 
      // '안내', '방장이 나갔습니다.'
      Navigator.pushAndRemoveUntil(
        context,
        MaterialPageRoute(builder: (_) => const MainPage()),
        (route) => false,
      );
    });
  }

  // Start 1-hour countdown (1시간 카운트다운 시작)
  void _startCountdownTimer() {
    if (_countdownTimer != null && _countdownTimer!.isActive) {
      return; 
    }
    if (_createDt == null) return;

    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      final endTime = _createDt!.add(const Duration(hours: 1));
      final now = DateTime.now();
      final diff = endTime.difference(now);

      if (diff.isNegative) {
        timer.cancel();
        _remaining = const Duration(seconds: 0);
        _onAutoTimeout();
      } else {
        setState(() {
          _remaining = diff;
        });
      }
    });
  }

  // Auto timeout after 1 hour (1시간 만료 후 자동 종료)
  void _onAutoTimeout() {
    setState(() {
      _roomTimeOut = true;
      _roomExitYn = 'Y';
    });
    _requestLeaveRoom();
  }

  // Request to leave the room (방 나가기 요청)
  Future<void> _requestLeaveRoom() async {
    try {
      final reqBody = {"room_seq": "${widget.roomSeq}"};
      final response = await Api.serverRequest(uri: '/room/score/game/leave', body: reqBody);
      // if result ok -> move to main
    } catch (e) {
      await showResponseDialog(context, 'Error', 'Failed to leave the room.'); 
      // '오류', '방 나가기 처리 실패'
    }
    if (mounted) {
      Navigator.pushAndRemoveUntil(
        context,
        MaterialPageRoute(builder: (_) => const MainPage()),
        (route) => false,
      );
    }
  }

  /// On back press -> leave room (뒤로가기 → 방 나가기)
  Future<bool> _onLeaveRoom() async {
    if (roomMasterYn == 'Y') {
      final confirm = await showDialog<bool>(
        context: context,
        barrierDismissible: false,
        builder: (_) {
          return AlertDialog(
            backgroundColor: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
              side: const BorderSide(color: Colors.black, width: 2),
            ),
            title: const Center(
              child: Text(
                'Leave Room', // '방 나가기'
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
            ),
            content: const Text(
              'If the master leaves, the room will be deleted.\nDo you really want to leave?', 
              // '방장이 나가면 방은 삭제됩니다.\n정말 나가시겠습니까?'
              style: TextStyle(fontSize: 14),
            ),
            actionsAlignment: MainAxisAlignment.spaceEvenly,
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context, false),
                style: TextButton.styleFrom(
                  backgroundColor: Colors.black,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                ),
                child: const Text('Cancel'), // '취소'
              ),
              TextButton(
                onPressed: () {
                  final myUserRef = _roomRef.child('userInfo').child('_${mySeq}');
                  myUserRef.onDisconnect().cancel();
                  Navigator.pop(context, true);
                },
                style: TextButton.styleFrom(
                  backgroundColor: Colors.black,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                ),
                child: const Text('OK'), // '확인'
              ),
            ],
          );
        },
      );
      if (confirm != true) return false;

      // leave API
      setState(() {
        _roomExitYn = 'Y';
      });
      await _requestLeaveRoom();
    } else {
      // 일반 사용자
      setState(() {
        _roomExitYn = 'Y';
      });
      await _requestLeaveRoom();
    }
    return false;
  }

  int _toInt(dynamic val, int defaultVal) {
    if (val == null) return defaultVal;
    if (val is int) return val;
    if (val is String) {
      return int.tryParse(val) ?? defaultVal;
    }
    return defaultVal;
  }

  /// Top buttons (상단 버튼)
  Widget _buildTopButtons() {
    if (_isLoading) return const SizedBox();

    final me = _userList.firstWhere((u) => (u['user_seq'].toString() ?? '0') == mySeq, orElse: () => {});
    final myReadyYn = (me['ready_yn'] ?? 'N').toString().toUpperCase();
    final bool isReady = (myReadyYn == 'Y');
    final readyLabel = 'Ready'; // '준비'

    final btnStyle = ElevatedButton.styleFrom(
      backgroundColor: Colors.white,
      foregroundColor: Colors.black,
      side: const BorderSide(color: Colors.black, width: 1),
      padding: EdgeInsets.zero,
      minimumSize: Size(0, 30),
      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
    );

    if (roomMasterYn == 'Y') {
      // Master => 3 buttons (방장 => 3개)
      return Row(
        children: [
          Expanded(
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 4),
              child: ElevatedButton(
                style: btnStyle,
                onPressed: _onOpenRoomSetting,
                child: AutoSizeText(
                  'Settings', // '방 설정'
                  maxLines: 1,
                  style: TextStyle(fontSize: 14 * scaleFactor),
                ),
              ),
            ),
          ),
          Expanded(
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 4),
              child: ElevatedButton(
                style: btnStyle,
                onPressed: _readyButtonEnabled ? _onToggleReady : null,
                child: AutoSizeText(
                  readyLabel,
                  maxLines: 1,
                  style: TextStyle(
                    fontSize: 14 * scaleFactor,
                    color: isReady ? Colors.red : Colors.black,
                  ),
                ),
              ),
            ),
          ),
          Expanded(
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 4),
              child: ElevatedButton(
                style: btnStyle,
                onPressed: _onGameStart,
                child: AutoSizeText(
                  scaleFactor == 0.8 ? 'Start' : 'Start Game', 
                  // '시작' 혹은 '게임 시작'
                  maxLines: 1,
                  style: TextStyle(fontSize: 14 * scaleFactor),
                ),
              ),
            ),
          ),
        ],
      );
    } else {
      // Normal => 2 buttons (일반 => 2개)
      return Row(
        children: [
          Expanded(
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 8),
              child: ElevatedButton(
                style: btnStyle,
                onPressed: _onOpenRoomSetting,
                child: AutoSizeText(
                  'Settings', // '방 설정'
                  maxLines: 1,
                  style: TextStyle(fontSize: 14 * scaleFactor),
                ),
              ),
            ),
          ),
          Expanded(
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 8),
              child: ElevatedButton(
                style: btnStyle,
                onPressed: _readyButtonEnabled ? _onToggleReady : null,
                child: AutoSizeText(
                  readyLabel,
                  maxLines: 1,
                  style: TextStyle(
                    fontSize: 14 * scaleFactor,
                    color: isReady ? Colors.red : Colors.black,
                  ),
                ),
              ),
            ),
          ),
        ],
      );
    }
  }

  // Toggle ready (준비 토글)
  Future<void> _onToggleReady() async {
    if (!_readyButtonEnabled) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Please wait a moment before pressing again. (3s delay)'), 
            // '잠시 후에 다시 눌러주세요. (3초 대기)'
            duration: Duration(seconds: 1),
          ),
        );
      }
      return;
    }

    // Disable button (버튼 비활성화)
    setState(() {
      _readyButtonEnabled = false;
    });

    try {
      final me = _userList.firstWhere((u) => (u['user_seq'].toString() ?? '0') == mySeq, orElse: () => {});
      final myReadyYn = (me['ready_yn'] ?? 'N').toString().toUpperCase();
      final isReady = (myReadyYn == 'Y');
      final newYn = isReady ? 'N' : 'Y';

      final userRef = _roomRef.child('userInfo').child('_${mySeq}');
      await userRef.update({"ready_yn": newYn});
    } catch (e) {
      showResponseDialog(context, 'Error', 'Failed to set READY state.'); 
      // '오류', 'READY 설정 실패했습니다.'
    }

    // Re-enable after 3 seconds (3초 후 다시 버튼 활성화)
    Future.delayed(const Duration(seconds: 3), () {
      if (mounted) {
        setState(() {
          _readyButtonEnabled = true;
        });
      }
    });
  }

  // Open room settings (방 설정)
  Future<void> _onOpenRoomSetting() async {
    final roomInfo = {
      "room_seq": "${widget.roomSeq}",
      "room_master_yn": roomMasterYn,
      "room_title": roomTitle,
      "room_intro": roomIntro,
      "open_yn": openYn,
      "room_pw": roomPw,
      "running_time": runningTime,
      "room_type": widget.roomType,
      "number_of_people": numberOfPeople,
      "score_open_range": scoreOpenRange,
    };

    final result = await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => RoomSettingModal(roomInfo: roomInfo),
    );
    if (result == 'refresh') {
      // ...
    }
  }

  // Start game (게임 시작)
  Future<void> _onGameStart() async {
    final notReady = _userList.any((u) => (u['ready_yn'] ?? 'N').toString().toUpperCase() != 'Y');
    if (notReady) {
      showResponseDialog(context, 'Notice', 'Someone is not ready yet (including the master).'); 
      // '안내', 'READY되지 않은 참가자가 있습니다(방장 포함).'
      return;
    }

    final requestBody = {
      "room_seq": "${widget.roomSeq}",
      "room_type": "PRIVATE",
    };
    try {
      final response = await Api.serverRequest(uri: '/room/score/game/start', body: requestBody);
      if (response['result'] == 'OK') {
        final resp = response['response'] ?? {};
        if (resp['result'] == 'OK') {
          // Move to running room (진행중 방으로 이동)
        } else {
          showResponseDialog(context, 'Error', 'Failed to start the game.'); 
          // '오류', '게임 시작 실패했습니다.'
        }
      } else {
        showResponseDialog(context, 'Error', 'Failed to start the game.');
      }
    } catch (e) {
      showResponseDialog(context, 'Error', 'Failed to start the game.');
    }
  }

  // Format countdown (카운트다운 표시용)
  String _formatDuration(Duration d) {
    final mm = d.inMinutes.remainder(60).toString().padLeft(2, '0');
    final ss = d.inSeconds.remainder(60).toString().padLeft(2, '0');
    return '$mm:$ss';
  }

  @override
  Widget build(BuildContext context) {
    final countdownStr = _formatDuration(_remaining); // 예: "10:23"

    return WillPopScope(
      onWillPop: () => _onLeaveRoom(),
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.black,
          elevation: 0,
          // Room title + remaining time (방 제목 + 남은시간)
          title: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              // Left: room title (방 제목)
              Expanded(
                child: Text(
                  roomTitle.isNotEmpty ? roomTitle : 'Room Title', // '방 제목'
                  style: const TextStyle(color: Colors.white),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              const SizedBox(width: 4),
              // Right: countdown (남은시간)
              Text(
                countdownStr,
                style: const TextStyle(color: Colors.white),
              ),
            ],
          ),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
            onPressed: () => _onLeaveRoom(),
          ),
        ),
        bottomNavigationBar: AdBannerWidget(),
        body: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : SingleChildScrollView(
                padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildTopButtons(),
                    const SizedBox(height: 20),

                    const Text(
                      'Participants', // '참가자'
                      style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    _buildPlayerSection(),
                  ],
                ),
              ),
      ),
    );
  }

  // Build player section (참가자 목록 섹션)
  Widget _buildPlayerSection() {
    final playerList = _userList.where((u) {
      final t = (u['user_seq'].toString() ?? null);
      return t != null;
    }).toList();

    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: Colors.black),
        borderRadius: BorderRadius.circular(8),
      ),
      child: playerList.isEmpty
          ? const Text('No participants.') // '참가자가 없습니다.'
          : SingleChildScrollView(
              child: Wrap(
                spacing: 16,
                runSpacing: 16,
                alignment: WrapAlignment.center,
                children: playerList.map(_buildSeat).toList(),
              ),
            ),
    );
  }

  // Build seat (개별 유저 박스)
  Widget _buildSeat(Map<String, dynamic> userData) {
    final userName = userData['nickname'] ?? 'User'; // '유저'
    final profileImg = userData['profile_img'] ?? '';
    final readyYn = (userData['ready_yn'] ?? 'N').toString().toUpperCase();
    final connectYn = (userData['connect_yn'] ?? 'Y').toString().toUpperCase();
    final bool isReady = (readyYn == 'Y');
    final bool isDisconnected = (connectYn == 'N');
    final bool isMaster = (roomMasterYn == 'Y');

    // Check if user is the room master (방장인지 확인)
    final isRoomMasterUser = (userData['user_seq']?.toString() ?? '') == _masterSeqString;
    // Check if user is admin (사회자인지 확인)
    final participantType = (userData['participant_type'] ?? '').toString().toUpperCase();
    final isAdmin = (participantType == 'ADMIN');

    // Icon for room master/admin (아이콘)
    String roleIcon = '';
    if (isRoomMasterUser) {
      roleIcon = '★ '; // 방장
    } else if (isAdmin) {
      roleIcon = '☆ '; // 사회자
    }
    print('profileImg: ${Config.baseUrl}/images$profileImg');

    final displayName = '$roleIcon$userName';

    return GestureDetector(
      onTap: () async {
        final result = await showDialog(
          context: context,
          barrierDismissible: false,
          builder: (_) => UserInfoPrivateDialog(
            userData: userData,
            isRoomMaster: isMaster,
            roomSeq: widget.roomSeq,
            roomTypeName: 'PRIVATE',
          ),
        );
        if (result == 'refresh') {
          // ...
        }
      },
      child: Container(
        margin: const EdgeInsets.only(right: 8),
        child: Column(
          children: [
            Container(
              width: 50,
              height: 50,
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(
                  color: isDisconnected
                      ? Colors.orange
                      : (isReady ? Colors.red : Colors.black),
                  width: isDisconnected ? 2 : (isReady ? 2 : 1),
                ),
                borderRadius: BorderRadius.circular(20),
                boxShadow: [
                  if (isReady)
                    BoxShadow(
                      color: Colors.redAccent.withOpacity(0.6),
                      blurRadius: 8,
                      spreadRadius: 2,
                    ),
                  if (isDisconnected)
                    BoxShadow(
                      color: Colors.orangeAccent.withOpacity(0.6),
                      blurRadius: 8,
                      spreadRadius: 2,
                    ),
                ],
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(20),
                child: isDisconnected
                    ? const Center(
                        child: Text(
                          '!', 
                          // '!'
                          style: TextStyle(
                            fontSize: 20,
                            color: Colors.orange,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      )
                    : Image.network(
                        '${Config.baseUrl}/images$profileImg',
                        fit: BoxFit.cover,
                        errorBuilder: (_, __, ___) => const Center(
                          child: Text(
                            'No\nImage', 
                            // '이미지\n불가'
                            textAlign: TextAlign.center,
                            style: TextStyle(fontSize: 10),
                          ),
                        ),
                      ),
              ),
            ),
            const SizedBox(height: 4),
            Text(
              displayName,
              style: const TextStyle(fontSize: 12, color: Colors.black),
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
            ),
          ],
        ),
      ),
    );
  }
}
