import 'dart:convert'; import 'package:bonsoir/bonsoir.dart'; import 'package:flutter/material.dart'; import 'package:mobile_scanner/mobile_scanner.dart'; import 'package:playwith_core/playwith_core.dart'; // Core (AvatarWidget, NetworkManager 등) import 'package:playwith_game_quiz/quiz_game.dart'; import 'package:qr_flutter/qr_flutter.dart'; class LobbyScreen extends StatefulWidget { const LobbyScreen({super.key}); @override State createState() => _LobbyScreenState(); } class _LobbyScreenState extends State { final _net = NetworkManager(); final List _logs = []; final ScrollController _scrollController = ScrollController(); @override void initState() { super.initState(); // 로그 리스너 _net.logStream.listen((log) { if (!mounted) return; setState(() { _logs.add(log); if (_logs.length > 100) _logs.removeAt(0); }); WidgetsBinding.instance.addPostFrameCallback((_) { if (_scrollController.hasClients) { _scrollController.animateTo( _scrollController.position.maxScrollExtent, duration: const Duration(milliseconds: 200), curve: Curves.easeOut, ); } }); }); // 게임 시작 신호 감지 _net.messageStream.listen((data) { if (data['type'] == 'GAME_START') { final String gameId = data['gameId']; if (gameId == 'quiz_ox') { _startGameAndNavigate(QuizGame()); } } }); } void _startGameAndNavigate(BaseGame game) { if (!mounted) return; game.onStart(); Navigator.push( context, MaterialPageRoute(builder: (context) { Widget gameView; if (_net.role == NetworkRole.host) { gameView = game.buildHostView(context); } else { gameView = game.buildGuestView(context); } // 게임 위 채팅 오버레이 return Stack( children: [ gameView, const SafeArea(child: GameChatOverlay()), ], ); }), ); } @override Widget build(BuildContext context) { return ListenableBuilder( listenable: _net, builder: (context, child) { return Scaffold( appBar: AppBar( title: const Text('대기실'), centerTitle: true, actions: [ // 연결된 상태라면 나가기 버튼 표시 if (_net.role != NetworkRole.none) IconButton( icon: const Icon(Icons.exit_to_app, color: Colors.red), tooltip: "나가기", onPressed: () => _net.stopNetwork(), ) ], ), body: Column( children: [ // 메인 바디 (연결 상태에 따라 분기) Expanded(flex: 3, child: _buildMainBody()), const Divider(thickness: 1, height: 1), // 하단 디버그 로그 (개발용) _buildDebugConsole(), ], ), ); }, ); } // [Main Body] 상태에 따라 초기화면 vs 대기실 화면 분기 Widget _buildMainBody() { // 1. 아직 연결 안 됨 (초기 화면) if (_net.role == NetworkRole.none) { return _buildInitView(); } // 2. 연결됨 (대기실 - 방장/참가자 통합 UI) return _buildLobbyView(); } // ------------------------------------------------------------------------ // 1. 초기 화면 (방 만들기 / 찾기) // ------------------------------------------------------------------------ Widget _buildInitView() { return Center( child: SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text("게임을 시작해볼까요?", style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)), const SizedBox(height: 40), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ _BigButton( title: "방 만들기\n(Host)", color: Colors.blue[100]!, icon: Icons.add_home_work, onTap: () { _net.startHosting("${_net.me.nickname}의 방"); // 방장은 방 만들자마자 QR 팝업 Future.delayed(const Duration(milliseconds: 500), () { if (mounted && _net.role == NetworkRole.host) _showHostQRDialog(); }); }, ), _BigButton( title: "방 찾기\n(Guest)", color: Colors.green[100]!, icon: Icons.search, onTap: () => _showRoomListDialog(), ), ], ), const SizedBox(height: 30), ElevatedButton.icon( icon: const Icon(Icons.qr_code_scanner), label: const Text("QR 코드로 접속하기"), style: ElevatedButton.styleFrom(padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 15)), onPressed: () => _openQRScanner(), ), const SizedBox(height: 10), TextButton( onPressed: () => _showManualJoinDialog(), child: const Text("IP 주소 직접 입력 (비상용)", style: TextStyle(color: Colors.grey)), ), ], ), ), ); } // ------------------------------------------------------------------------ // 2. 대기실 화면 (통합 UI) // ------------------------------------------------------------------------ Widget _buildLobbyView() { return Column( children: [ // A. 상단 정보 카드 Container( width: double.infinity, padding: const EdgeInsets.all(20), decoration: BoxDecoration( color: Colors.grey[100], border: const Border(bottom: BorderSide(color: Colors.black12)), ), child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(_net.role == NetworkRole.host ? Icons.wifi_tethering : Icons.wifi, color: Colors.blue), const SizedBox(width: 10), Text( _net.role == NetworkRole.host ? "👑 방장 (나)" : "참가자 (나)", style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), ], ), // 방장일 경우 접속 정보 표시 if (_net.role == NetworkRole.host) ...[ const SizedBox(height: 15), Container( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(20), border: Border.all(color: Colors.blue.shade100)), child: Row( mainAxisSize: MainAxisSize.min, children: [ Text("IP: ${_net.hostIp} : ${_net.hostPort}", style: const TextStyle(fontWeight: FontWeight.bold)), const SizedBox(width: 10), InkWell( onTap: () => _showHostQRDialog(), child: const Icon(Icons.qr_code, color: Colors.black87), ) ], ), ), const SizedBox(height: 5), const Text("QR 코드를 눌러 친구를 초대하세요!", style: TextStyle(fontSize: 12, color: Colors.grey)), ] else ...[ // 참가자일 경우 방장 정보 표시 const SizedBox(height: 10), Text("방장 IP: ${_net.hostIp ?? '...'}", style: const TextStyle(color: Colors.grey)), ] ], ), ), // B. 참가자 리스트 (나 + 게스트) Expanded( child: ListView( padding: const EdgeInsets.all(16), children: [ const Text("대기 중인 참가자", style: TextStyle(color: Colors.grey, fontWeight: FontWeight.bold)), const SizedBox(height: 10), // 1. 나 (항상 맨 위) _buildUserTile(_net.me, isMe: true), // 2. 다른 참가자들 ..._net.guestList.map((guest) => _buildUserTile(guest, isMe: false)), // 대기 문구 if (_net.guestList.isEmpty && _net.role == NetworkRole.host) Padding( padding: const EdgeInsets.only(top: 40.0), child: Center( child: Column( children: const [ CircularProgressIndicator(), SizedBox(height: 20), Text("친구를 기다리는 중...", style: TextStyle(color: Colors.grey)), ], ), ), ), ], ), ), // C. 하단 레디 버튼 _buildReadyButton(), ], ); } Widget _buildUserTile(UserInfo user, {required bool isMe}) { return Card( elevation: user.isReady ? 4 : 1, color: user.isReady ? Colors.green[50] : Colors.white, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), side: user.isReady ? const BorderSide(color: Colors.green, width: 2) : BorderSide.none, ), margin: const EdgeInsets.symmetric(vertical: 6), child: ListTile( contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), leading: AvatarWidget(user: user, size: 50), // Core의 AvatarWidget 사용 title: Text( user.nickname + (isMe ? " (나)" : ""), style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16), ), subtitle: Text(isMe ? "준비 버튼을 눌러주세요" : (user.isReady ? "준비 완료!" : "준비 중..."), style: TextStyle(color: Colors.grey[600], fontSize: 12)), trailing: user.isReady ? const Icon(Icons.check_circle, color: Colors.green, size: 32) : const Icon(Icons.hourglass_empty, color: Colors.grey, size: 32), ), ); } Widget _buildReadyButton() { bool isReady = _net.me.isReady; // 조건: 방장이라도 게스트가 없으면 레디 불가 (혼자 게임 불가) // 게스트는 들어오자마자 레디 가능 bool canReady = _net.role == NetworkRole.host ? _net.guestList.isNotEmpty : true; return Container( width: double.infinity, padding: const EdgeInsets.all(20), decoration: BoxDecoration( color: Colors.white, boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 10, offset: const Offset(0, -5))], ), child: ElevatedButton( onPressed: canReady ? () => _net.toggleReady() : () { ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("친구를 초대해야 시작할 수 있습니다!"))); }, style: ElevatedButton.styleFrom( backgroundColor: !canReady ? Colors.grey[300] : (isReady ? Colors.redAccent : Colors.blueAccent), padding: const EdgeInsets.symmetric(vertical: 18), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), elevation: canReady ? 5 : 0, ), child: Text( isReady ? "준비 취소 (WAIT)" : "준비 완료 (READY)", style: TextStyle( fontSize: 22, fontWeight: FontWeight.bold, color: !canReady ? Colors.grey : Colors.white ), ), ), ); } // ------------------------------------------------------------------------ // [Components] 디버그 콘솔 // ------------------------------------------------------------------------ Widget _buildDebugConsole() { return Column( children: [ GestureDetector( onTap: () => _scrollController.jumpTo(_scrollController.position.maxScrollExtent), child: Container( width: double.infinity, padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 10), color: Colors.black87, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: const [ Text("DEBUG LOGS", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 10)), Icon(Icons.keyboard_arrow_down, color: Colors.white, size: 14) ], ), ), ), SizedBox( height: 100, child: Container( color: Colors.black, child: ListView.builder( controller: _scrollController, itemCount: _logs.length, itemBuilder: (context, index) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 1.0), child: Text( _logs[index], style: const TextStyle(color: Colors.greenAccent, fontSize: 10, fontFamily: 'Courier'), ), ); }, ), ), ), ], ); } // ------------------------------------------------------------------------ // [Dialogs] QR, 검색, 수동입력 // ------------------------------------------------------------------------ void _showHostQRDialog() { if (_net.hostIp == null || _net.hostPort == null) return; final qrData = jsonEncode({'ip': _net.hostIp, 'port': _net.hostPort}); showDialog( context: context, builder: (context) => Dialog( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), child: Padding( padding: const EdgeInsets.all(24.0), child: Column( mainAxisSize: MainAxisSize.min, children: [ const Text("친구 초대", style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold)), const SizedBox(height: 20), Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration(border: Border.all(color: Colors.black12), borderRadius: BorderRadius.circular(10)), child: QrImageView(data: qrData, version: QrVersions.auto, size: 220.0), ), const SizedBox(height: 20), SelectableText("IP: ${_net.hostIp}\nPort: ${_net.hostPort}", textAlign: TextAlign.center, style: const TextStyle(color: Colors.grey)), const SizedBox(height: 20), ElevatedButton(onPressed: () => Navigator.pop(context), child: const Text("닫기")) ], ), ), ), ); } void _openQRScanner() { bool isScanCompleted = false; Navigator.of(context).push(MaterialPageRoute( builder: (context) => Scaffold( appBar: AppBar(title: const Text("QR 스캔")), body: MobileScanner( onDetect: (capture) { if (isScanCompleted) return; for (final barcode in capture.barcodes) { if (barcode.rawValue != null) { try { final data = jsonDecode(barcode.rawValue!); if (data['ip'] != null && data['port'] != null) { isScanCompleted = true; Navigator.pop(context); ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("접속 중..."))); _net.joinRoom(data['ip'], data['port']); return; } } catch (e) {} } } }, ), ), )); } void _showRoomListDialog() { showDialog( context: context, builder: (context) => AlertDialog( title: const Text("방 찾기"), content: SizedBox( width: double.maxFinite, height: 300, child: StreamBuilder>( stream: _net.discoverRooms(), builder: (context, snapshot) { if (!snapshot.hasData || snapshot.data!.isEmpty) { return const Center(child: Text("검색 중...\n같은 와이파이인지 확인하세요.")); } return ListView.builder( itemCount: snapshot.data!.length, itemBuilder: (context, index) { final service = snapshot.data![index]; final ip = service.attributes?['ip'] ?? '알 수 없음'; return ListTile( leading: const Icon(Icons.meeting_room), title: Text(service.name.split('#').first), subtitle: Text(ip), onTap: () { Navigator.pop(context); if (service.attributes != null && service.attributes!['ip'] != null) { _net.joinRoom(service.attributes!['ip']!, service.port); } }, ); }, ); }, ), ), actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text("닫기"))], ), ); } void _showManualJoinDialog() { final ipCtrl = TextEditingController(text: "192.168."); final portCtrl = TextEditingController(); showDialog( context: context, builder: (context) => AlertDialog( title: const Text("직접 입력"), content: Column( mainAxisSize: MainAxisSize.min, children: [ TextField(controller: ipCtrl, decoration: const InputDecoration(labelText: "IP Address")), TextField(controller: portCtrl, decoration: const InputDecoration(labelText: "Port")), ], ), actions: [ TextButton(onPressed: () => Navigator.pop(context), child: const Text("취소")), ElevatedButton( onPressed: () { final ip = ipCtrl.text.trim(); final port = int.tryParse(portCtrl.text.trim()); if (ip.isNotEmpty && port != null) { Navigator.pop(context); _net.joinRoom(ip, port); } }, child: const Text("접속"), ), ], ), ); } } class _BigButton extends StatelessWidget { final String title; final Color color; final IconData icon; final VoidCallback onTap; const _BigButton({required this.title, required this.color, required this.icon, required this.onTap}); @override Widget build(BuildContext context) { return GestureDetector( onTap: onTap, child: Container( width: 130, height: 130, decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(20), boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 10, offset: const Offset(0, 5))]), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [Icon(icon, size: 40, color: Colors.black54), const SizedBox(height: 10), Text(title, textAlign: TextAlign.center, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold))]), ), ); } }