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

// Main page
import 'main_page.dart';

// APIs
import '../../plugins/api.dart';

// Dialogs
import '../../dialogs/response_dialog.dart';
import '../../dialogs/yes_no_dialog.dart';
import '../../dialogs/room_setting_dialog.dart';
import '../../dialogs/user_info_team_dialog.dart';
import '../../dialogs/team_name_edit_dialog.dart';
import 'playing_team_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 WaitingRoomTeamPage extends StatefulWidget {
  final int roomSeq;
  final String roomType; // "team"

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

  @override
  State<WaitingRoomTeamPage> createState() => _WaitingRoomTeamPageState();
}

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

  List<String> _teamNameList = [];
  List<Map<String, dynamic>> _userList = [];

  bool _isLoading = true;

  // Server request loading
  bool _isServerRequestLoading = false;

  late DatabaseReference _roomRef;
  Stream<DatabaseEvent>? _roomStream;
  StreamSubscription<DatabaseEvent>? _roomStreamSubscription;

  bool _movedToRunningPage = false;
  bool _kickedOut = false;

  String mySeq = '0';

  // 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();
    FirebaseDatabase.instance.goOnline();
    _initRoomRef(); // (D) Initialize room reference
  }

  @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';

    // Example: room key = "korea-123"
    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();
  }

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

  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) {
          final tempUserSeq = val['user_seq'].toString() ?? '0';
          if (tempUserSeq != '0') {
            if (val is Map) {
              tempList.add({
                'user_seq': val['user_seq'].toString() ?? '0',
                '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;
        numberOfTeams = _toInt(roomInfoData['number_of_teams'], 1);

        // Team names (팀명)
        final tStr = (roomInfoData['team_name_list'] ?? '') as String;
        if (tStr.isNotEmpty) {
          _teamNameList = tStr.split(',').map((e) => e.trim().toUpperCase()).toList();
        } else {
          // Default A, B, C... for the number of teams
          _teamNameList = List.generate(numberOfTeams, (i) => String.fromCharCode(65 + i));
        }

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

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

        _userList = tempList;
        _isLoading = false;
      });

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

      // Parse create_dt -> 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 am 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 is out (방 제한시간 종료)
      if (_roomTimeOut) {
        showResponseDialog(context, 'Notice', 'Room time limit has expired.'); 
        // '안내', '방 제한시간이 종료되었습니다.'
        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 the room (방장이 나갔을 때)
  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 (자동 종료)
  void _onAutoTimeout() {
    setState(() {
      _roomTimeOut = true;
      _roomExitYn = 'Y';
    });
    _requestLeaveRoom(); // 방 나가기 요청
  }

  // Request leave room (방 나가기 요청)
  Future<void> _requestLeaveRoom() async {
    try {
      final reqBody = {"room_seq": "${widget.roomSeq}"};
      final response = await Api.serverRequest(uri: '/room/score/game/leave', body: reqBody);
      // ...
    } catch (e) {
      // ...
    }
    if (mounted) {
      Navigator.pushAndRemoveUntil(
        context,
        MaterialPageRoute(builder: (_) => const MainPage()),
        (route) => false,
      );
    }
  }

  // On back press -> leave the 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, color: Colors.black),
              ),
            ),
            content: const Text(
              'If the master leaves, the room will be deleted.\nAre you sure you 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),
    );

    if (roomMasterYn == 'Y') {
      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: _isServerRequestLoading ? null : _onGameStart,
                child: _isServerRequestLoading
                    ? const CircularProgressIndicator()
                    : AutoSizeText(
                        scaleFactor == 0.8 ? 'Start' : 'Start Game', 
                        // '시작' 또는 '게임 시작'
                        maxLines: 1,
                        style: TextStyle(fontSize: 14 * scaleFactor),
                      ),
              ),
            ),
          ),
        ],
      );
    } else {
      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;
    }

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

    try {
      final me = _userList.firstWhere((u) => (u['user_seq'].toString() ?? '') == 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 button after 3 seconds (3초 후 버튼 활성화)
    Future.delayed(const Duration(seconds: 3), () {
      if (mounted) {
        setState(() {
          _readyButtonEnabled = true;
        });
      }
    });
  }

  // Open room setting (방 설정 열기)
  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,
      "number_of_teams": numberOfTeams,
      "team_name_list": _teamNameList.join(','),
    };

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

  // Start game (게임 시작)
  Future<void> _onGameStart() async {
    setState(() => _isServerRequestLoading = true);

    // Check if anyone is not ready (준비 안된 사람 검사)
    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).'); 
      // '안내', '아직 준비되지 않은 참가자가 있습니다(방장 포함).'
      setState(() => _isServerRequestLoading = false);
      return;
    }

    // Check if someone is not assigned to a team (팀 배정 안된 인원 체크)
    final notTeam = _userList.any((u) => (u['team_name'] ?? '').toString().toUpperCase() == 'WAIT');
    if (notTeam) {
      showResponseDialog(context, 'Notice', 'Someone is not assigned to a team.'); 
      // '안내', '팀 배정이 안된 참가자가 있습니다.'
      setState(() => _isServerRequestLoading = false);
      return;
    }

    final requestBody = {
      "room_seq": "${widget.roomSeq}",
      "room_type": "TEAM",
    };
    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,
            response['response_info']['msg_title'],
            response['response_info']['msg_content'],
          );
        }
      } else {
        showResponseDialog(
          context,
          response['response_info']['msg_title'],
          response['response_info']['msg_content'],
        );
      }
    } catch (e) {
      showResponseDialog(context, 'Error', 'Failed to request game start.'); 
      // '오류', '게임 시작 요청에 실패했습니다.'
    } finally {
      setState(() => _isServerRequestLoading = false);
    }
  }

  // Format countdown display (카운트다운 표시용)
  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);

    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, // e.g. "10:23"
                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: 16, horizontal: 16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildTopButtons(),
                    const SizedBox(height: 20),

                    const Text(
                      'Players by Team', // '팀별 참가자'
                      style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.black),
                    ),
                    const SizedBox(height: 8),
                    _buildTeamSection(),
                    const SizedBox(height: 20),

                    _buildWaitSection(),
                  ],
                ),
              ),
      ),
    );
  }

  // Build team section (팀 섹션)
  Widget _buildTeamSection() {
    final players = _userList.where((u) {
      final t = (u['user_seq'].toString() ?? null);
      return t != null;
    }).toList();

    final Map<String, List<Map<String, dynamic>>> teamMap = {};
    for (final tName in _teamNameList) {
      if (tName == 'WAIT') continue;
      teamMap[tName] = [];
    }

    for (var user in players) {
      final tName = (user['team_name'] ?? '').toString().trim().toUpperCase();
      if (tName.isNotEmpty && tName != 'WAIT' && teamMap.containsKey(tName)) {
        teamMap[tName]!.add(user);
      }
    }

    if (teamMap.isEmpty) {
      return Container(
        padding: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: Colors.black),
          borderRadius: BorderRadius.circular(8),
        ),
        child: const Text(
          'No participants assigned to teams.', // '팀에 배정된 참가자가 없습니다.'
          style: TextStyle(color: Colors.black),
        ),
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: _teamNameList.map((teamName) {
        if (teamName == 'WAIT') return const SizedBox();
        final members = teamMap[teamName]!;

        return Container(
          margin: const EdgeInsets.only(bottom: 16),
          decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(color: Colors.black),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Column(
            children: [
              GestureDetector(
                onTap: () async {
                  if (roomMasterYn == 'Y') {
                    // 팀명 수정 다이얼로그
                    final result = await showDialog(
                      context: context,
                      barrierDismissible: false,
                      builder: (_) => TeamNameEditModal(
                        roomSeq: widget.roomSeq,
                        roomTypeName: 'TEAM',
                        beforeTeamName: teamName,
                        existingTeamNames: _teamNameList,
                      ),
                    );
                    if (result == 'refresh') {
                      // ...
                    }
                  }
                },
                child: Container(
                  width: double.infinity,
                  padding: const EdgeInsets.symmetric(vertical: 8),
                  color: Colors.black,
                  child: Center(
                    child: Text(
                      'Team $teamName', // '팀 $teamName'
                      style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
                    ),
                  ),
                ),
              ),
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                padding: const EdgeInsets.all(8),
                child: Row(children: members.map(_buildSeat).toList()),
              ),
            ],
          ),
        );
      }).toList(),
    );
  }

  // Build wait section (대기자 섹션)
  Widget _buildWaitSection() {
    final waitList = _userList.where((u) {
      final tName = (u['team_name'] ?? '').toString().toUpperCase();
      return tName == 'WAIT';
    }).toList();

    if (waitList.isEmpty) return const SizedBox();

    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: Colors.black),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          Container(
            width: double.infinity,
            padding: const EdgeInsets.symmetric(vertical: 8),
            color: Colors.black,
            child: const Center(
              child: Text(
                'Waiting', // '대기중'
                style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
              ),
            ),
          ),
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.all(8),
            child: Row(children: waitList.map(_buildSeat).toList()),
          ),
        ],
      ),
    );
  }

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

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

    // Icon for room master or admin
    String roleIcon = '';
    if (isRoomMasterUser) {
      roleIcon = '★ '; // 방장
    } else if (isAdmin) {
      roleIcon = '☆ '; // 사회자
    }

    final displayName = '$roleIcon$userName';

    return GestureDetector(
      onTap: () async {
        final result = await showDialog(
          context: context,
          barrierDismissible: false,
          builder: (_) => UserInfoTeamDialog(
            userData: user,
            isRoomMaster: isMaster,
            roomSeq: widget.roomSeq,
            roomTypeName: widget.roomType.toUpperCase(),
            teamNameList: _teamNameList,
          ),
        );
        if (result == 'refresh') {
          // ...
        }
      },
      child: Container(
        width: 60,
        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: 2),
            Text(
              displayName, 
              style: const TextStyle(fontSize: 12, color: Colors.black),
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
            ),
          ],
        ),
      ),
    );
  }
}
