diff --git a/lib/controllers/placar_controller.dart b/lib/controllers/placar_controller.dart index a4bb478..c7b96df 100644 --- a/lib/controllers/placar_controller.dart +++ b/lib/controllers/placar_controller.dart @@ -24,20 +24,17 @@ class ShotRecord { this.points, }); - // 👇 Para o Auto-Save converter em Texto Map toJson() => { 'relativeX': relativeX, 'relativeY': relativeY, 'isMake': isMake, 'playerId': playerId, 'playerName': playerName, 'zone': zone, 'points': points, }; - // 👇 Para o Auto-Save ler do Texto factory ShotRecord.fromJson(Map json) => ShotRecord( relativeX: json['relativeX'], relativeY: json['relativeY'], isMake: json['isMake'], playerId: json['playerId'], playerName: json['playerName'], zone: json['zone'], points: json['points'], ); } -// 👇 AGORA É UM CHANGENOTIFIER (Gestor de Estado Profissional) 👇 class PlacarController extends ChangeNotifier { final String gameId; final String myTeam; @@ -80,8 +77,10 @@ class PlacarController extends ChangeNotifier { String? pendingAction; String? pendingPlayerId; List matchShots = []; + + // 👇 LISTA PARA O HISTÓRICO (PLAY-BY-PLAY) + List playByPlay = []; - // 👇 O CRONÓMETRO AGORA TEM VIDA PRÓPRIA (ValueNotifier) PARA NÃO ENCRAVAR A APP 👇 ValueNotifier durationNotifier = ValueNotifier(const Duration(minutes: 10)); Timer? timer; bool isRunning = false; @@ -98,7 +97,7 @@ class PlacarController extends ChangeNotifier { myCourt.clear(); myBench.clear(); oppCourt.clear(); oppBench.clear(); playerNames.clear(); playerStats.clear(); playerNumbers.clear(); - matchShots.clear(); myFouls = 0; opponentFouls = 0; + matchShots.clear(); playByPlay.clear(); myFouls = 0; opponentFouls = 0; final gameResponse = await supabase.from('games').select().eq('id', gameId).single(); @@ -179,11 +178,10 @@ class PlacarController extends ChangeNotifier { )); } - // 👇 AUTO-SAVE: SE O JOGO FOI ABAIXO A MEIO, RECUPERA TUDO AQUI! 👇 await _loadLocalBackup(); isLoading = false; - notifyListeners(); // Substitui o antigo onUpdate! + notifyListeners(); } catch (e) { debugPrint("Erro ao retomar jogo: $e"); isLoading = false; @@ -215,9 +213,6 @@ class PlacarController extends ChangeNotifier { } } - // ========================================================================= - // 👇 AS DUAS FUNÇÕES MÁGICAS DO AUTO-SAVE 👇 - // ========================================================================= Future _saveLocalBackup() async { try { final prefs = await SharedPreferences.getInstance(); @@ -229,6 +224,7 @@ class PlacarController extends ChangeNotifier { 'playerStats': playerStats, 'myCourt': myCourt, 'myBench': myBench, 'oppCourt': oppCourt, 'oppBench': oppBench, 'matchShots': matchShots.map((s) => s.toJson()).toList(), + 'playByPlay': playByPlay, // 👇 Guarda o histórico }; await prefs.setString('backup_$gameId', jsonEncode(backupData)); } catch (e) { @@ -257,6 +253,8 @@ class PlacarController extends ChangeNotifier { List decodedShots = data['matchShots']; matchShots = decodedShots.map((s) => ShotRecord.fromJson(s)).toList(); + + playByPlay = List.from(data['playByPlay'] ?? []); // 👇 Carrega o histórico debugPrint("🔄 AUTO-SAVE RECUPERADO COM SUCESSO!"); } @@ -268,11 +266,11 @@ class PlacarController extends ChangeNotifier { void toggleTimer(BuildContext context) { if (isRunning) { timer?.cancel(); - _saveLocalBackup(); // Grava no telemóvel quando pausa! + _saveLocalBackup(); } else { timer = Timer.periodic(const Duration(seconds: 1), (timer) { if (durationNotifier.value.inSeconds > 0) { - durationNotifier.value -= const Duration(seconds: 1); // 👈 Só o relógio atualiza, a app não pisca! + durationNotifier.value -= const Duration(seconds: 1); } else { timer.cancel(); isRunning = false; @@ -281,9 +279,9 @@ class PlacarController extends ChangeNotifier { durationNotifier.value = const Duration(minutes: 10); myFouls = 0; opponentFouls = 0; myTimeoutsUsed = 0; opponentTimeoutsUsed = 0; - _saveLocalBackup(); // Grava mudança de período + _saveLocalBackup(); } - notifyListeners(); // Aqui sim, redesenhamos o ecrã para mudar o Quarto + notifyListeners(); } }); } @@ -364,7 +362,7 @@ class PlacarController extends ChangeNotifier { matchShots.add(ShotRecord(relativeX: relativeX, relativeY: relativeY, isMake: isMake, playerId: playerId, playerName: name, zone: zone, points: points)); - _saveLocalBackup(); // 👈 Grava logo para não perder o cesto! + _saveLocalBackup(); notifyListeners(); } @@ -389,7 +387,7 @@ class PlacarController extends ChangeNotifier { commitStat(pendingAction!, pendingPlayerId!); isSelectingShotLocation = false; pendingAction = null; pendingPlayerId = null; - _saveLocalBackup(); // 👈 Grava logo + _saveLocalBackup(); notifyListeners(); } @@ -428,6 +426,9 @@ class PlacarController extends ChangeNotifier { bool isOpponent = playerData.startsWith("player_opp_"); String playerId = playerData.replaceAll("player_my_", "").replaceAll("player_opp_", ""); final stats = playerStats[playerId]!; + final name = playerNames[playerId] ?? "Jogador"; + + String logText = ""; if (action.startsWith("add_pts_")) { int pts = int.parse(action.split("_").last); @@ -435,6 +436,7 @@ class PlacarController extends ChangeNotifier { stats["pts"] = stats["pts"]! + pts; if (pts == 2 || pts == 3) { stats["fgm"] = stats["fgm"]! + 1; stats["fga"] = stats["fga"]! + 1; } if (pts == 1) { stats["ftm"] = stats["ftm"]! + 1; stats["fta"] = stats["fta"]! + 1; } + logText = "marcou $pts pontos 🏀"; } else if (action.startsWith("sub_pts_")) { int pts = int.parse(action.split("_").last); @@ -449,24 +451,33 @@ class PlacarController extends ChangeNotifier { if (stats["ftm"]! > 0) stats["ftm"] = stats["ftm"]! - 1; if (stats["fta"]! > 0) stats["fta"] = stats["fta"]! - 1; } + logText = "teve $pts pontos retirados ❌"; } - else if (action == "miss_1") { stats["fta"] = stats["fta"]! + 1; } - else if (action == "miss_2" || action == "miss_3") { stats["fga"] = stats["fga"]! + 1; } - else if (action == "add_orb") { stats["orb"] = stats["orb"]! + 1; stats["rbs"] = stats["rbs"]! + 1; } - else if (action == "add_drb") { stats["drb"] = stats["drb"]! + 1; stats["rbs"] = stats["rbs"]! + 1; } - else if (action == "add_ast") { stats["ast"] = stats["ast"]! + 1; } - else if (action == "add_stl") { stats["stl"] = stats["stl"]! + 1; } - else if (action == "add_tov") { stats["tov"] = stats["tov"]! + 1; } - else if (action == "add_blk") { stats["blk"] = stats["blk"]! + 1; } + else if (action == "miss_1") { stats["fta"] = stats["fta"]! + 1; logText = "falhou lance livre ❌"; } + else if (action == "miss_2" || action == "miss_3") { stats["fga"] = stats["fga"]! + 1; logText = "falhou lançamento ❌"; } + else if (action == "add_orb") { stats["orb"] = stats["orb"]! + 1; stats["rbs"] = stats["rbs"]! + 1; logText = "ganhou ressalto ofensivo 🔄"; } + else if (action == "add_drb") { stats["drb"] = stats["drb"]! + 1; stats["rbs"] = stats["rbs"]! + 1; logText = "ganhou ressalto defensivo 🛡️"; } + else if (action == "add_ast") { stats["ast"] = stats["ast"]! + 1; logText = "fez uma assistência 🤝"; } + else if (action == "add_stl") { stats["stl"] = stats["stl"]! + 1; logText = "roubou a bola 🥷"; } + else if (action == "add_tov") { stats["tov"] = stats["tov"]! + 1; logText = "perdeu a bola (turnover) 🤦"; } + else if (action == "add_blk") { stats["blk"] = stats["blk"]! + 1; logText = "fez um desarme (bloco) ✋"; } else if (action == "add_foul") { stats["fls"] = stats["fls"]! + 1; if (isOpponent) { opponentFouls++; } else { myFouls++; } + logText = "cometeu falta ⚠️"; } else if (action == "sub_foul") { if (stats["fls"]! > 0) stats["fls"] = stats["fls"]! - 1; if (isOpponent) { if (opponentFouls > 0) opponentFouls--; } else { if (myFouls > 0) myFouls--; } + logText = "teve falta anulada 🔄"; } - _saveLocalBackup(); // 👈 Grava na memória! + + if (logText.isNotEmpty) { + String time = "${durationNotifier.value.inMinutes.toString().padLeft(2, '0')}:${durationNotifier.value.inSeconds.remainder(60).toString().padLeft(2, '0')}"; + playByPlay.insert(0, "P$currentQuarter - $time: $name $logText"); + } + + _saveLocalBackup(); } Future saveGameStats(BuildContext context) async { @@ -570,7 +581,6 @@ class PlacarController extends ChangeNotifier { await supabase.from('shot_locations').delete().eq('game_id', gameId); if (batchShots.isNotEmpty) await supabase.from('shot_locations').insert(batchShots); - // 👇 SE O SUPABASE GUARDOU COM SUCESSO, LIMPA A MEMÓRIA DO TELEMÓVEL! 👇 final prefs = await SharedPreferences.getInstance(); await prefs.remove('backup_$gameId'); @@ -590,5 +600,4 @@ class PlacarController extends ChangeNotifier { timer?.cancel(); super.dispose(); } - } \ No newline at end of file diff --git a/lib/pages/PlacarPage.dart b/lib/pages/PlacarPage.dart index d743c65..a21ef03 100644 --- a/lib/pages/PlacarPage.dart +++ b/lib/pages/PlacarPage.dart @@ -5,60 +5,7 @@ import 'dart:math' as math; import '../utils/size_extension.dart'; import '../classe/theme.dart'; import '../controllers/placar_controller.dart'; -// Se tiveres um ficheiro de widgets à parte, mantém. Se os widgets já estão aqui, podes remover esta linha: -// import '../widgets/placar_widgets.dart'; -import 'package:playmaker/zone_map_dialog.dart'; - -// 👇 NOVA FUNÇÃO: POP-UP DE ASSISTÊNCIA 👇 -void showAssistDialog(BuildContext context, PlacarController controller, bool isOpponent, String scorerId, double sf) { - // 1. Descobrir quem está em campo na equipa que marcou - final teamCourt = isOpponent ? controller.oppCourt : controller.myCourt; - final prefix = isOpponent ? "player_opp_" : "player_my_"; - - // 2. Remover o marcador (ele não pode assistir a si mesmo) e remover os lugares "vazios" (fake_) - final possibleAssistants = teamCourt.where((id) => id != scorerId && !id.startsWith("fake_")).toList(); - - if (possibleAssistants.isEmpty) return; // Se ele estiver sozinho em campo, não faz nada. - - showDialog( - context: context, - barrierDismissible: false, // Força o utilizador a escolher uma opção - builder: (ctx) => AlertDialog( - backgroundColor: Theme.of(context).colorScheme.surface, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15 * sf)), - title: Text("Houve Assistência?", style: TextStyle(color: Theme.of(context).colorScheme.onSurface, fontWeight: FontWeight.bold, fontSize: 18 * sf)), - content: SingleChildScrollView( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - ...possibleAssistants.map((id) { - final name = controller.playerNames[id] ?? "Desconhecido"; - final number = controller.playerNumbers[id] ?? "0"; - return ListTile( - leading: CircleAvatar( - backgroundColor: isOpponent ? AppTheme.oppTeamRed : AppTheme.myTeamBlue, - child: Text(number, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)), - ), - title: Text(name, style: TextStyle(color: Theme.of(context).colorScheme.onSurface, fontWeight: FontWeight.bold)), - onTap: () { - Navigator.pop(ctx); // Fecha o pop-up - controller.commitStat("add_ast", "$prefix$id"); // Regista a assistência! - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Assistência: $name'), duration: const Duration(seconds: 1), backgroundColor: AppTheme.successGreen)); - }, - ); - }), - Divider(color: Colors.grey.withOpacity(0.3)), - ListTile( - leading: const CircleAvatar(backgroundColor: Colors.grey, child: Icon(Icons.person_off, color: Colors.white)), - title: Text("Isolado (Sem assistência)", style: TextStyle(color: Theme.of(context).colorScheme.onSurface, fontStyle: FontStyle.italic)), - onTap: () => Navigator.pop(ctx), // Fecha sem fazer nada - ) - ], - ), - ), - ), - ); -} +import '../widgets/placar_widgets.dart'; class PlacarPage extends StatefulWidget { final String gameId, myTeam, opponentTeam; @@ -80,7 +27,6 @@ class _PlacarPageState extends State { @override void initState() { super.initState(); - // Força o ecrã deitado SystemChrome.setPreferredOrientations([ DeviceOrientation.landscapeRight, DeviceOrientation.landscapeLeft, @@ -216,14 +162,11 @@ class _PlacarPageState extends State { GestureDetector( onTapDown: (details) { if (_controller.isSelectingShotLocation) { - // 👇 1. Guarda os dados ANTES de limpar a seleção bool isMake = _controller.pendingAction?.startsWith("add_pts_") ?? false; String? pData = _controller.pendingPlayerId; - // 👇 2. Regista o lançamento no campo _controller.registerShotLocation(context, details.localPosition, Size(w, h)); - // 👇 3. Se foi cesto, lança o pop-up de assistência! if (isMake && pData != null) { bool isOpp = pData.startsWith("player_opp_"); String pId = pData.replaceAll("player_my_", "").replaceAll("player_opp_", ""); @@ -300,31 +243,70 @@ class _PlacarPageState extends State { ), ), - // BOTÕES LATERAIS (SAVE & HEATMAP) + // ========================================================= + // 👇 BOTÕES LATERAIS SUPERIORES 👇 + // ========================================================= + // Esquerda: Gravar Jogo & Histórico (Play-by-play) Positioned( top: 50 * sf, left: 12 * sf, - child: _buildCornerBtn( - heroTag: 'btn_save_exit', icon: Icons.save_alt, color: AppTheme.oppTeamRed, size: cornerBtnSize, isLoading: _controller.isSaving, - onTap: () async { - await _controller.saveGameStats(context); - if (context.mounted) Navigator.pop(context); - } + child: Column( + children: [ + _buildCornerBtn(heroTag: 'btn_save_exit', icon: Icons.save_alt, color: AppTheme.oppTeamRed, size: cornerBtnSize, isLoading: _controller.isSaving, onTap: () async { await _controller.saveGameStats(context); if (context.mounted) Navigator.pop(context); }), + SizedBox(height: 10 * sf), + _buildCornerBtn(heroTag: 'btn_history', icon: Icons.history, color: Colors.blueGrey, size: cornerBtnSize, onTap: () => showDialog(context: context, builder: (ctx) => PlayByPlayDialog(controller: _controller))), + ], ), ), + + // Direita: Mapa de Calor & Box Score Positioned( top: 50 * sf, right: 12 * sf, - child: _buildCornerBtn(heroTag: 'btn_heatmap', icon: Icons.local_fire_department, color: Colors.orange.shade800, size: cornerBtnSize, onTap: () => _showHeatmap(context)), + child: Column( + children: [ + _buildCornerBtn(heroTag: 'btn_heatmap', icon: Icons.local_fire_department, color: Colors.orange.shade800, size: cornerBtnSize, onTap: () => _showHeatmap(context)), + SizedBox(height: 10 * sf), + _buildCornerBtn(heroTag: 'btn_boxscore', icon: Icons.table_chart, color: Colors.indigo, size: cornerBtnSize, onTap: () => showDialog(context: context, builder: (ctx) => BoxScoreDialog(controller: _controller))), + ], + ), ), - // CONTROLOS EQUIPA CASA (ESQUERDA) + // ========================================================= + // 👇 POP-UPS DE SUPLENTES (FLUTUAM ACIMA DOS BOTÕES) 👇 + // ========================================================= + if (_controller.showMyBench) + Positioned( + bottom: 180 * sf, + left: 12 * sf, + child: BenchPopup(controller: _controller, isOpponent: false, sf: sf), + ), + + if (_controller.showOppBench) + Positioned( + bottom: 180 * sf, + right: 12 * sf, + child: BenchPopup(controller: _controller, isOpponent: true, sf: sf), + ), + + // ========================================================= + // 👇 BOTÕES DA EQUIPA DA CASA (ESQUERDA) 👇 + // ========================================================= Positioned( - bottom: 55 * sf, left: 12 * sf, + bottom: 55 * sf, + left: 12 * sf, child: Column( mainAxisSize: MainAxisSize.min, children: [ - if (_controller.showMyBench) BenchPlayersList(controller: _controller, isOpponent: false, sf: sf), - SizedBox(height: 12 * sf), - _buildCornerBtn(heroTag: 'btn_sub_home', icon: Icons.swap_horiz, color: AppTheme.myTeamBlue, size: cornerBtnSize, onTap: () { _controller.showMyBench = !_controller.showMyBench; _controller.notifyListeners(); }), + _buildCornerBtn( + heroTag: 'btn_sub_home', + icon: Icons.swap_horiz, + color: AppTheme.myTeamBlue, + size: cornerBtnSize, + onTap: () { + _controller.showMyBench = !_controller.showMyBench; + _controller.showOppBench = false; + _controller.notifyListeners(); + } + ), SizedBox(height: 12 * sf), _buildCornerBtn( heroTag: 'btn_to_home', @@ -337,15 +319,26 @@ class _PlacarPageState extends State { ), ), - // CONTROLOS EQUIPA VISITANTE (DIREITA) + // ========================================================= + // 👇 BOTÕES DA EQUIPA VISITANTE (DIREITA) 👇 + // ========================================================= Positioned( - bottom: 55 * sf, right: 12 * sf, + bottom: 55 * sf, + right: 12 * sf, child: Column( mainAxisSize: MainAxisSize.min, children: [ - if (_controller.showOppBench) BenchPlayersList(controller: _controller, isOpponent: true, sf: sf), - SizedBox(height: 12 * sf), - _buildCornerBtn(heroTag: 'btn_sub_away', icon: Icons.swap_horiz, color: AppTheme.oppTeamRed, size: cornerBtnSize, onTap: () { _controller.showOppBench = !_controller.showOppBench; _controller.notifyListeners(); }), + _buildCornerBtn( + heroTag: 'btn_sub_away', + icon: Icons.swap_horiz, + color: AppTheme.oppTeamRed, + size: cornerBtnSize, + onTap: () { + _controller.showOppBench = !_controller.showOppBench; + _controller.showMyBench = false; + _controller.notifyListeners(); + } + ), SizedBox(height: 12 * sf), _buildCornerBtn( heroTag: 'btn_to_away', @@ -369,716 +362,4 @@ class _PlacarPageState extends State { }, ); } -} - -// ============================================================================ -// 1. PLACAR SUPERIOR (COM CRONÓMETRO DE ALTA PERFORMANCE) -// ============================================================================ -class TopScoreboard extends StatelessWidget { - final PlacarController controller; - final double sf; - - const TopScoreboard({super.key, required this.controller, required this.sf}); - - @override - Widget build(BuildContext context) { - return Container( - padding: EdgeInsets.symmetric(vertical: 6 * sf, horizontal: 20 * sf), - decoration: BoxDecoration( - color: AppTheme.placarDarkSurface, - borderRadius: BorderRadius.only(bottomLeft: Radius.circular(22 * sf), bottomRight: Radius.circular(22 * sf)), - border: Border.all(color: Colors.white, width: 2.0 * sf), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - _buildTeamSection(controller.myTeam, controller.myScore, controller.myFouls, controller.myTimeoutsUsed, AppTheme.myTeamBlue, false, sf), - SizedBox(width: 20 * sf), - Column( - mainAxisSize: MainAxisSize.min, - children: [ - Container( - padding: EdgeInsets.symmetric(horizontal: 14 * sf, vertical: 4 * sf), - decoration: BoxDecoration(color: AppTheme.placarTimerBg, borderRadius: BorderRadius.circular(9 * sf)), - child: ValueListenableBuilder( - valueListenable: controller.durationNotifier, - builder: (context, duration, child) { - String formatTime = "${duration.inMinutes.toString().padLeft(2, '0')}:${duration.inSeconds.remainder(60).toString().padLeft(2, '0')}"; - return Text(formatTime, style: TextStyle(color: Colors.white, fontSize: 24 * sf, fontWeight: FontWeight.w900, fontFamily: 'monospace', letterSpacing: 1.5 * sf)); - } - ), - ), - SizedBox(height: 4 * sf), - Text("PERÍODO ${controller.currentQuarter}", style: TextStyle(color: AppTheme.warningAmber, fontSize: 12 * sf, fontWeight: FontWeight.w900)), - ], - ), - SizedBox(width: 20 * sf), - _buildTeamSection(controller.opponentTeam, controller.opponentScore, controller.opponentFouls, controller.opponentTimeoutsUsed, AppTheme.oppTeamRed, true, sf), - ], - ), - ); - } - - Widget _buildTeamSection(String name, int score, int fouls, int timeouts, Color color, bool isOpp, double sf) { - int displayFouls = fouls > 5 ? 5 : fouls; - final timeoutIndicators = Row( - mainAxisSize: MainAxisSize.min, - children: List.generate(3, (index) => Container( - margin: EdgeInsets.symmetric(horizontal: 2.5 * sf), width: 10 * sf, height: 10 * sf, - decoration: BoxDecoration(shape: BoxShape.circle, color: index < timeouts ? AppTheme.warningAmber : Colors.grey.shade600, border: Border.all(color: Colors.white54, width: 1.0 * sf)), - )), - ); - List content = [ - Column(children: [_scoreBox(score, color, sf), SizedBox(height: 5 * sf), timeoutIndicators]), - SizedBox(width: 12 * sf), - Column( - crossAxisAlignment: isOpp ? CrossAxisAlignment.start : CrossAxisAlignment.end, - children: [ - Text(name.toUpperCase(), style: TextStyle(color: Colors.white, fontSize: 16 * sf, fontWeight: FontWeight.w900, letterSpacing: 1.0 * sf)), - SizedBox(height: 3 * sf), - Text("FALTAS: $displayFouls", style: TextStyle(color: displayFouls >= 5 ? AppTheme.actionMiss : AppTheme.warningAmber, fontSize: 11 * sf, fontWeight: FontWeight.bold)), - ], - ) - ]; - return Row(crossAxisAlignment: CrossAxisAlignment.center, children: isOpp ? content : content.reversed.toList()); - } - - Widget _scoreBox(int score, Color color, double sf) => Container( - width: 45 * sf, height: 35 * sf, alignment: Alignment.center, - decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(6 * sf)), - child: Text(score.toString(), style: TextStyle(color: Colors.white, fontSize: 20 * sf, fontWeight: FontWeight.w900)), - ); -} - -// ============================================================================ -// 2. BANCO DE SUPLENTES (COM TRADUTOR DE NOME) -// ============================================================================ -class BenchPlayersList extends StatelessWidget { - final PlacarController controller; - final bool isOpponent; - final double sf; - - const BenchPlayersList({super.key, required this.controller, required this.isOpponent, required this.sf}); - - @override - Widget build(BuildContext context) { - final bench = isOpponent ? controller.oppBench : controller.myBench; - final teamColor = isOpponent ? AppTheme.oppTeamRed : AppTheme.myTeamBlue; - final prefix = isOpponent ? "bench_opp_" : "bench_my_"; - - return Column( - mainAxisSize: MainAxisSize.min, - children: bench.map((playerId) { - final playerName = controller.playerNames[playerId] ?? "Erro"; - final num = controller.playerNumbers[playerId] ?? "0"; - final int fouls = controller.playerStats[playerId]?["fls"] ?? 0; - final bool isFouledOut = fouls >= 5; - - String shortName = playerName.length > 8 ? "${playerName.substring(0, 7)}." : playerName; - - Widget avatarUI = Container( - margin: EdgeInsets.only(bottom: 7 * sf), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Container( - decoration: BoxDecoration( - shape: BoxShape.circle, - border: Border.all(color: Colors.white, width: 1.5 * sf), - boxShadow: [BoxShadow(color: Colors.black45, blurRadius: 4 * sf, offset: Offset(0, 2.0 * sf))] - ), - child: CircleAvatar( - radius: 18 * sf, - backgroundColor: isFouledOut ? Colors.grey.shade800 : teamColor, - child: Text(num, style: TextStyle(color: isFouledOut ? Colors.red.shade300 : Colors.white, fontSize: 14 * sf, fontWeight: FontWeight.bold, decoration: isFouledOut ? TextDecoration.lineThrough : TextDecoration.none)), - ), - ), - SizedBox(height: 4 * sf), - Text(shortName, style: TextStyle(color: Colors.white, fontSize: 10 * sf, fontWeight: FontWeight.bold), overflow: TextOverflow.ellipsis), - ], - ), - ); - - if (isFouledOut) { - return GestureDetector(onTap: () => ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('🛑 $playerName não pode voltar (Expulso).'), backgroundColor: AppTheme.actionMiss)), child: avatarUI); - } - - return Draggable( - data: "$prefix$playerId", - feedback: Material(color: Colors.transparent, child: CircleAvatar(radius: 22 * sf, backgroundColor: teamColor, child: Text(num, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16 * sf)))), - childWhenDragging: Opacity(opacity: 0.5, child: SizedBox(width: 36 * sf, height: 36 * sf)), - child: avatarUI, - ); - }).toList(), - ); - } -} - -// ============================================================================ -// 3. CARTÃO DO JOGADOR NO CAMPO -// ============================================================================ -class PlayerCourtCard extends StatelessWidget { - final PlacarController controller; - final String playerId; - final bool isOpponent; - final double sf; - - const PlayerCourtCard({super.key, required this.controller, required this.playerId, required this.isOpponent, required this.sf}); - - @override - Widget build(BuildContext context) { - final teamColor = isOpponent ? AppTheme.oppTeamRed : AppTheme.myTeamBlue; - - final realName = controller.playerNames[playerId] ?? "Erro"; - final stats = controller.playerStats[playerId]!; - final number = controller.playerNumbers[playerId]!; - final prefix = isOpponent ? "player_opp_" : "player_my_"; - - return Draggable( - data: "$prefix$playerId", - feedback: Material( - color: Colors.transparent, - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), - decoration: BoxDecoration(color: teamColor.withOpacity(0.9), borderRadius: BorderRadius.circular(6)), - child: Text(realName, style: const TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold)), - ), - ), - childWhenDragging: Opacity(opacity: 0.5, child: _playerCardUI(number, realName, stats, teamColor, false, false, sf)), - child: DragTarget( - onAcceptWithDetails: (details) { - final action = details.data; - - if (action == "add_pts_2" || action == "add_pts_3" || action == "miss_2" || action == "miss_3") { - bool isMake = action.startsWith("add_"); - bool is3Pt = action.endsWith("_3"); - - showDialog( - context: context, - builder: (ctx) => ZoneMapDialog( - playerName: realName, - isMake: isMake, - is3PointAction: is3Pt, - onZoneSelected: (zone, points, relX, relY) { - Navigator.pop(ctx); - controller.registerShotFromPopup(context, action, "$prefix$playerId", zone, points, relX, relY); - - // 👇 NOVA LÓGICA: SE FOI CESTO, PERGUNTA A ASSISTÊNCIA 👇 - if (isMake) { - showAssistDialog(context, controller, isOpponent, playerId, sf); - } - }, - ), - ); - } - else if (action.startsWith("add_") || action.startsWith("sub_") || action.startsWith("miss_")) { - controller.handleActionDrag(context, action, "$prefix$playerId"); - } - else if (action.startsWith("bench_")) { - controller.handleSubbing(context, action, playerId, isOpponent); - } - }, - builder: (context, candidateData, rejectedData) { - bool isSubbing = candidateData.any((data) => data != null && (data.startsWith("bench_my_") || data.startsWith("bench_opp_"))); - bool isActionHover = candidateData.any((data) => data != null && (data.startsWith("add_") || data.startsWith("sub_") || data.startsWith("miss_"))); - return _playerCardUI(number, realName, stats, teamColor, isSubbing, isActionHover, sf); - }, - ), - ); - } - - Widget _playerCardUI(String number, String displayNameStr, Map stats, Color teamColor, bool isSubbing, bool isActionHover, double sf) { - bool isFouledOut = stats["fls"]! >= 5; - Color bgColor = isFouledOut ? Colors.red.shade100 : Colors.white; - Color borderColor = isFouledOut ? AppTheme.actionMiss : Colors.transparent; - - if (isSubbing) { bgColor = Colors.blue.shade50; borderColor = AppTheme.myTeamBlue; } - else if (isActionHover && !isFouledOut) { bgColor = Colors.orange.shade50; borderColor = AppTheme.actionPoints; } - - int fgm = stats["fgm"]!; int fga = stats["fga"]!; - String fgPercent = fga > 0 ? ((fgm / fga) * 100).toStringAsFixed(0) : "0"; - String displayName = displayNameStr.length > 12 ? "${displayNameStr.substring(0, 10)}..." : displayNameStr; - - return Container( - padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4), - decoration: BoxDecoration(color: bgColor, borderRadius: BorderRadius.circular(8), border: Border.all(color: borderColor, width: 1.5), boxShadow: const [BoxShadow(color: Colors.black26, blurRadius: 4, offset: Offset(0, 2))]), - child: ClipRRect( - borderRadius: BorderRadius.circular(6 * sf), - child: IntrinsicHeight( - child: Row( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Container( - padding: EdgeInsets.symmetric(horizontal: 10 * sf), - color: isFouledOut ? Colors.grey[700] : teamColor, - alignment: Alignment.center, - child: Text(number, style: TextStyle(color: Colors.white, fontSize: 18 * sf, fontWeight: FontWeight.bold)), - ), - Padding( - padding: EdgeInsets.symmetric(horizontal: 8 * sf, vertical: 4 * sf), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Text(displayName, style: TextStyle(fontSize: 14 * sf, fontWeight: FontWeight.bold, color: isFouledOut ? AppTheme.actionMiss : Colors.black87, decoration: isFouledOut ? TextDecoration.lineThrough : TextDecoration.none)), - SizedBox(height: 1.5 * sf), - Text("${stats["pts"]} Pts | FG: $fgm/$fga ($fgPercent%)", style: TextStyle(fontSize: 10 * sf, color: isFouledOut ? AppTheme.actionMiss : Colors.grey[700], fontWeight: FontWeight.w600)), - Text("${stats["ast"]} Ast | ${stats["orb"]! + stats["drb"]!} Rbs | ${stats["fls"]} Fls", style: TextStyle(fontSize: 10 * sf, color: isFouledOut ? AppTheme.actionMiss : Colors.grey[500], fontWeight: FontWeight.w600)), - ], - ), - ), - ], - ), - ), - ), - ); - } -} - -// ============================================================================ -// 4. PAINEL DE BOTÕES DE AÇÃO -// ============================================================================ -class ActionButtonsPanel extends StatelessWidget { - final PlacarController controller; - final double sf; - - const ActionButtonsPanel({super.key, required this.controller, required this.sf}); - - @override - Widget build(BuildContext context) { - final double baseSize = 58 * sf; - final double feedSize = 73 * sf; - final double gap = 5 * sf; - - return Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - _columnBtn([ - _dragAndTargetBtn("M1", AppTheme.actionMiss, "miss_1", baseSize, feedSize, sf), - _dragAndTargetBtn("1", AppTheme.actionPoints, "add_pts_1", baseSize, feedSize, sf), - _dragAndTargetBtn("1", AppTheme.actionPoints, "sub_pts_1", baseSize, feedSize, sf, isX: true), - _dragAndTargetBtn("STL", AppTheme.actionSteal, "add_stl", baseSize, feedSize, sf), - ], gap), - SizedBox(width: gap * 1), - _columnBtn([ - _dragAndTargetBtn("M2", AppTheme.actionMiss, "miss_2", baseSize, feedSize, sf), - _dragAndTargetBtn("2", AppTheme.actionPoints, "add_pts_2", baseSize, feedSize, sf), - _dragAndTargetBtn("2", AppTheme.actionPoints, "sub_pts_2", baseSize, feedSize, sf, isX: true), - _dragAndTargetBtn("AST", AppTheme.actionAssist, "add_ast", baseSize, feedSize, sf), - ], gap), - SizedBox(width: gap * 1), - _columnBtn([ - _dragAndTargetBtn("M3", AppTheme.actionMiss, "miss_3", baseSize, feedSize, sf), - _dragAndTargetBtn("3", AppTheme.actionPoints, "add_pts_3", baseSize, feedSize, sf), - _dragAndTargetBtn("3", AppTheme.actionPoints, "sub_pts_3", baseSize, feedSize, sf, isX: true), - _dragAndTargetBtn("TOV", AppTheme.actionMiss, "add_tov", baseSize, feedSize, sf), - ], gap), - SizedBox(width: gap * 1), - _columnBtn([ - _dragAndTargetBtn("ORB", AppTheme.actionRebound, "add_orb", baseSize, feedSize, sf, icon: Icons.sports_basketball), - _dragAndTargetBtn("DRB", AppTheme.actionRebound, "add_drb", baseSize, feedSize, sf, icon: Icons.sports_basketball), - _dragAndTargetBtn("BLK", AppTheme.actionBlock, "add_blk", baseSize, feedSize, sf, icon: Icons.front_hand), - ], gap), - ], - ); - } - - Widget _columnBtn(List children, double gap) { - return Column( - mainAxisSize: MainAxisSize.min, - children: children.map((c) => Padding(padding: EdgeInsets.only(bottom: gap), child: c)).toList() - ); - } - - Widget _dragAndTargetBtn(String label, Color color, String actionData, double baseSize, double feedSize, double sf, {IconData? icon, bool isX = false}) { - return Draggable( - data: actionData, - feedback: _circle(label, color, icon, true, baseSize, feedSize, sf, isX: isX), - childWhenDragging: Opacity( - opacity: 0.5, - child: _circle(label, color, icon, false, baseSize, feedSize, sf, isX: isX) - ), - child: DragTarget( - onAcceptWithDetails: (details) {}, - builder: (context, candidateData, rejectedData) { - bool isHovered = candidateData.any((data) => data != null && data.startsWith("player_")); - return Transform.scale( - scale: isHovered ? 1.15 : 1.0, - child: Container( - decoration: isHovered ? BoxDecoration(shape: BoxShape.circle, boxShadow: [BoxShadow(color: Colors.white, blurRadius: 10 * sf, spreadRadius: 3 * sf)]) : null, - child: _circle(label, color, icon, false, baseSize, feedSize, sf, isX: isX) - ), - ); - } - ), - ); - } - - Widget _circle(String label, Color color, IconData? icon, bool isFeed, double baseSize, double feedSize, double sf, {bool isX = false}) { - double size = isFeed ? feedSize : baseSize; - Widget content; - bool isPointBtn = label == "1" || label == "2" || label == "3" || label == "M1" || label == "M2" || label == "M3"; - bool isBlkBtn = label == "BLK"; - - if (isPointBtn) { - content = Stack( - alignment: Alignment.center, - children: [ - Container(width: size * 0.75, height: size * 0.75, decoration: const BoxDecoration(color: Colors.black, shape: BoxShape.circle)), - Icon(Icons.sports_basketball, color: color, size: size * 0.9), - Stack( - children: [ - Text(label, style: TextStyle(fontSize: size * 0.38, fontWeight: FontWeight.w900, foreground: Paint()..style = PaintingStyle.stroke..strokeWidth = size * 0.05..color = Colors.white, decoration: TextDecoration.none)), - Text(label, style: TextStyle(fontSize: size * 0.38, fontWeight: FontWeight.w900, color: Colors.black, decoration: TextDecoration.none)), - ], - ), - ], - ); - } else if (isBlkBtn) { - content = Stack( - alignment: Alignment.center, - children: [ - Icon(Icons.front_hand, color: const Color.fromARGB(207, 56, 52, 52), size: size * 0.75), - Stack( - alignment: Alignment.center, - children: [ - Text(label, style: TextStyle(fontSize: size * 0.28, fontWeight: FontWeight.w900, foreground: Paint()..style = PaintingStyle.stroke..strokeWidth = size * 0.05..color = Colors.black, decoration: TextDecoration.none)), - Text(label, style: TextStyle(fontSize: size * 0.28, fontWeight: FontWeight.w900, color: Colors.white, decoration: TextDecoration.none)), - ], - ), - ], - ); - } else if (icon != null) { - content = Icon(icon, color: Colors.white, size: size * 0.5); - } else { - content = Text(label, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: size * 0.35, decoration: TextDecoration.none)); - } - - return Stack( - clipBehavior: Clip.none, - alignment: Alignment.bottomRight, - children: [ - Container( - width: size, height: size, - decoration: (isPointBtn || isBlkBtn) - ? const BoxDecoration(color: Colors.transparent) - : BoxDecoration(gradient: RadialGradient(colors: [color.withOpacity(0.7), color], radius: 0.8), shape: BoxShape.circle, boxShadow: [BoxShadow(color: Colors.black38, blurRadius: 6 * sf, offset: Offset(0, 3 * sf))]), - alignment: Alignment.center, - child: content, - ), - if (isX) Positioned(top: 0, right: 0, child: Container(decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), child: Icon(Icons.cancel, color: Colors.red, size: size * 0.4))), - ], - ); - } -} - -// ============================================================================ -// MAPA DE CALOR -// ============================================================================ -class HeatmapDialog extends StatefulWidget { - final List shots; - final String myTeamName; - final String oppTeamName; - final List myPlayers; - final List oppPlayers; - final Map> playerStats; - - const HeatmapDialog({ - super.key, - required this.shots, - required this.myTeamName, - required this.oppTeamName, - required this.myPlayers, - required this.oppPlayers, - required this.playerStats, - }); - - @override - State createState() => _HeatmapDialogState(); -} - -class _HeatmapDialogState extends State { - bool _isMapVisible = false; - String _selectedTeam = ''; - String _selectedPlayer = ''; - - @override - Widget build(BuildContext context) { - final Color headerColor = const Color(0xFFE88F15); - final Color yellowBackground = const Color(0xFFDFAB00); - - final double screenHeight = MediaQuery.of(context).size.height; - final double dialogHeight = screenHeight * 0.95; - final double dialogWidth = dialogHeight * 1.0; - - return Dialog( - backgroundColor: yellowBackground, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), - clipBehavior: Clip.antiAlias, - insetPadding: const EdgeInsets.all(10), - child: SizedBox( - height: dialogHeight, - width: dialogWidth, - child: _isMapVisible ? _buildMapScreen(headerColor) : _buildSelectionScreen(headerColor), - ), - ); - } - - Widget _buildSelectionScreen(Color headerColor) { - return Column( - children: [ - Container( - height: 40, - color: headerColor, - width: double.infinity, - child: Stack( - alignment: Alignment.center, - children: [ - const Text( - "ESCOLHE A EQUIPA OU UM JOGADOR", - style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.bold), - ), - Positioned( - right: 8, - child: InkWell( - onTap: () => Navigator.pop(context), - child: Container( - padding: const EdgeInsets.all(4), - decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), - child: Icon(Icons.close, color: headerColor, size: 16), - ), - ), - ) - ], - ), - ), - - Expanded( - child: Padding( - padding: const EdgeInsets.all(8.0), - child: Row( - children: [ - Expanded( - child: _buildTeamColumn( - teamName: widget.myTeamName, - players: widget.myPlayers, - teamColor: AppTheme.myTeamBlue, - ), - ), - const SizedBox(width: 8), - Expanded( - child: _buildTeamColumn( - teamName: widget.oppTeamName, - players: widget.oppPlayers, - teamColor: AppTheme.oppTeamRed, - ), - ), - ], - ), - ), - ), - ], - ); - } - - Widget _buildTeamColumn({required String teamName, required List players, required Color teamColor}) { - List realPlayers = players.where((p) => !p.startsWith("Sem ")).toList(); - - return Container( - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(8), - ), - child: Column( - children: [ - InkWell( - onTap: () => setState(() { - _selectedTeam = teamName; - _selectedPlayer = 'Todos'; - _isMapVisible = true; - }), - child: Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(vertical: 10), - decoration: BoxDecoration( - color: teamColor, - borderRadius: const BorderRadius.only(topLeft: Radius.circular(8), topRight: Radius.circular(8)), - ), - child: Column( - children: [ - Text(teamName.toUpperCase(), style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16)), - const SizedBox(height: 4), - Container( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2), - decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(12)), - child: const Text("MAPA GERAL DA EQUIPA", style: TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.bold)), - ), - ], - ), - ), - ), - Expanded( - child: ListView.separated( - itemCount: realPlayers.length, - separatorBuilder: (context, index) => const Divider(height: 1, color: Colors.black12), - itemBuilder: (context, index) { - String p = realPlayers[index]; - int pts = widget.playerStats[p]?['pts'] ?? 0; - - return ListTile( - dense: true, - visualDensity: VisualDensity.compact, - leading: Icon(Icons.person, color: teamColor), - title: Text(p, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: Colors.black87)), - trailing: Text("$pts Pts", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: teamColor)), - onTap: () => setState(() { - _selectedTeam = teamName; - _selectedPlayer = p; - _isMapVisible = true; - }), - ); - }, - ), - ), - ], - ), - ); - } - - Widget _buildMapScreen(Color headerColor) { - List filteredShots = widget.shots.where((s) { - if (_selectedPlayer != 'Todos') return s.playerName == _selectedPlayer; - if (_selectedTeam == widget.myTeamName) return widget.myPlayers.contains(s.playerName); - if (_selectedTeam == widget.oppTeamName) return widget.oppPlayers.contains(s.playerName); - return true; - }).toList(); - - String titleText = _selectedPlayer == 'Todos' - ? "MAPA GERAL: ${_selectedTeam.toUpperCase()}" - : "MAPA: ${_selectedPlayer.toUpperCase()}"; - - return Column( - children: [ - Container( - height: 40, - color: headerColor, - width: double.infinity, - child: Stack( - alignment: Alignment.center, - children: [ - Positioned( - left: 8, - child: InkWell( - onTap: () => setState(() => _isMapVisible = false), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), - decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12)), - child: Row( - children: [ - Icon(Icons.arrow_back, color: headerColor, size: 14), - const SizedBox(width: 4), - Text("VOLTAR", style: TextStyle(color: headerColor, fontWeight: FontWeight.bold, fontSize: 12)), - ], - ), - ), - ), - ), - Text( - titleText, - style: const TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.bold), - ), - Positioned( - right: 8, - child: InkWell( - onTap: () => Navigator.pop(context), - child: Container( - padding: const EdgeInsets.all(4), - decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), - child: Icon(Icons.close, color: headerColor, size: 16), - ), - ), - ) - ], - ), - ), - Expanded( - child: LayoutBuilder( - builder: (context, constraints) { - return Stack( - children: [ - CustomPaint( - size: Size(constraints.maxWidth, constraints.maxHeight), - painter: HeatmapCourtPainter(), - ), - ...filteredShots.map((shot) => Positioned( - left: (shot.relativeX * constraints.maxWidth) - 8, - top: (shot.relativeY * constraints.maxHeight) - 8, - child: CircleAvatar( - radius: 8, - backgroundColor: shot.isMake ? AppTheme.successGreen : AppTheme.actionMiss, - child: Icon(shot.isMake ? Icons.check : Icons.close, size: 10, color: Colors.white) - ), - )), - ], - ); - }, - ), - ), - ], - ); - } -} - -class HeatmapCourtPainter extends CustomPainter { - @override - void paint(Canvas canvas, Size size) { - final double w = size.width; - final double h = size.height; - final double basketX = w / 2; - - final Paint whiteStroke = Paint()..color = Colors.white..style = PaintingStyle.stroke..strokeWidth = 2.0; - final Paint blackStroke = Paint()..color = Colors.black87..style = PaintingStyle.stroke..strokeWidth = 2.0; - - final double margin = w * 0.10; - final double length = h * 0.35; - final double larguraDoArco = (w / 2) - margin; - final double alturaDoArco = larguraDoArco * 0.30; - final double totalArcoHeight = alturaDoArco * 4; - - canvas.drawLine(Offset(margin, 0), Offset(margin, length), whiteStroke); - canvas.drawLine(Offset(w - margin, 0), Offset(w - margin, length), whiteStroke); - canvas.drawLine(Offset(0, length), Offset(margin, length), whiteStroke); - canvas.drawLine(Offset(w - margin, length), Offset(w, length), whiteStroke); - canvas.drawArc(Rect.fromCenter(center: Offset(basketX, length), width: larguraDoArco * 2, height: totalArcoHeight), 0, math.pi, false, whiteStroke); - - double sXL = basketX + (larguraDoArco * math.cos(math.pi * 0.75)); - double sYL = length + ((totalArcoHeight / 2) * math.sin(math.pi * 0.75)); - double sXR = basketX + (larguraDoArco * math.cos(math.pi * 0.25)); - double sYR = length + ((totalArcoHeight / 2) * math.sin(math.pi * 0.25)); - - canvas.drawLine(Offset(sXL, sYL), Offset(0, h * 0.85), whiteStroke); - canvas.drawLine(Offset(sXR, sYR), Offset(w, h * 0.85), whiteStroke); - - final double pW = w * 0.28; - final double pH = h * 0.38; - canvas.drawRect(Rect.fromLTWH(basketX - pW / 2, 0, pW, pH), blackStroke); - - final double ftR = pW / 2; - canvas.drawArc(Rect.fromCircle(center: Offset(basketX, pH), radius: ftR), 0, math.pi, false, blackStroke); - for (int i = 0; i < 10; i++) { - canvas.drawArc(Rect.fromCircle(center: Offset(basketX, pH), radius: ftR), math.pi + (i * 2 * (math.pi / 20)), math.pi / 20, false, blackStroke); - } - - canvas.drawLine(Offset(basketX - pW / 2, pH), Offset(sXL, sYL), blackStroke); - canvas.drawLine(Offset(basketX + pW / 2, pH), Offset(sXR, sYR), blackStroke); - - canvas.drawArc(Rect.fromCircle(center: Offset(basketX, h), radius: w * 0.12), math.pi, math.pi, false, blackStroke); - canvas.drawCircle(Offset(basketX, h * 0.12), w * 0.02, blackStroke); - canvas.drawLine(Offset(basketX - w * 0.08, h * 0.12 - 5), Offset(basketX + w * 0.08, h * 0.12 - 5), blackStroke); - } - - @override - bool shouldRepaint(covariant CustomPainter oldDelegate) => false; } \ No newline at end of file diff --git a/lib/widgets/placar_widgets.dart b/lib/widgets/placar_widgets.dart index b6efd28..9563fbb 100644 --- a/lib/widgets/placar_widgets.dart +++ b/lib/widgets/placar_widgets.dart @@ -1,9 +1,10 @@ import 'package:flutter/material.dart'; +import 'dart:math' as math; + import '../classe/theme.dart'; import '../controllers/placar_controller.dart'; import 'package:playmaker/zone_map_dialog.dart'; -// POP-UP DE ASSISTÊNCIA void showAssistDialog(BuildContext context, PlacarController controller, bool isOpponent, String scorerId, double sf) { final teamCourt = isOpponent ? controller.oppCourt : controller.myCourt; final prefix = isOpponent ? "player_opp_" : "player_my_"; @@ -52,7 +53,6 @@ void showAssistDialog(BuildContext context, PlacarController controller, bool is ); } -// 1. PLACAR SUPERIOR class TopScoreboard extends StatelessWidget { final PlacarController controller; final double sf; @@ -129,69 +129,91 @@ class TopScoreboard extends StatelessWidget { ); } -// 2. BANCO DE SUPLENTES -class BenchPlayersList extends StatelessWidget { +class BenchPopup extends StatelessWidget { final PlacarController controller; final bool isOpponent; final double sf; - const BenchPlayersList({super.key, required this.controller, required this.isOpponent, required this.sf}); + const BenchPopup({super.key, required this.controller, required this.isOpponent, required this.sf}); @override Widget build(BuildContext context) { final bench = isOpponent ? controller.oppBench : controller.myBench; final teamColor = isOpponent ? AppTheme.oppTeamRed : AppTheme.myTeamBlue; final prefix = isOpponent ? "bench_opp_" : "bench_my_"; + final teamName = isOpponent ? controller.opponentTeam : controller.myTeam; - return Column( - mainAxisSize: MainAxisSize.min, - children: bench.map((playerId) { - final playerName = controller.playerNames[playerId] ?? "Erro"; - final num = controller.playerNumbers[playerId] ?? "0"; - final int fouls = controller.playerStats[playerId]?["fls"] ?? 0; - final bool isFouledOut = fouls >= 5; - - String shortName = playerName.length > 8 ? "${playerName.substring(0, 7)}." : playerName; - - Widget avatarUI = Container( - margin: EdgeInsets.only(bottom: 7 * sf), - child: Column( - mainAxisSize: MainAxisSize.min, + return Container( + width: 280 * sf, + padding: EdgeInsets.all(12 * sf), + decoration: BoxDecoration( + color: AppTheme.placarDarkSurface.withOpacity(0.95), + borderRadius: BorderRadius.circular(16 * sf), + border: Border.all(color: teamColor, width: 2 * sf), + boxShadow: [BoxShadow(color: Colors.black54, blurRadius: 10 * sf, spreadRadius: 2 * sf)], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Container( - decoration: BoxDecoration( - shape: BoxShape.circle, - border: Border.all(color: Colors.white, width: 1.5 * sf), - boxShadow: [BoxShadow(color: Colors.black45, blurRadius: 4 * sf, offset: Offset(0, 2.0 * sf))] - ), - child: CircleAvatar( - radius: 18 * sf, - backgroundColor: isFouledOut ? Colors.grey.shade800 : teamColor, - child: Text(num, style: TextStyle(color: isFouledOut ? Colors.red.shade300 : Colors.white, fontSize: 14 * sf, fontWeight: FontWeight.bold, decoration: isFouledOut ? TextDecoration.lineThrough : TextDecoration.none)), - ), - ), - SizedBox(height: 4 * sf), - Text(shortName, style: TextStyle(color: Colors.white, fontSize: 10 * sf, fontWeight: FontWeight.bold), overflow: TextOverflow.ellipsis), + Text("SUPLENTES: ${teamName.toUpperCase()}", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 12 * sf)), + InkWell( + onTap: () { + if (isOpponent) { controller.showOppBench = false; } + else { controller.showMyBench = false; } + controller.notifyListeners(); + }, + child: Icon(Icons.close, color: Colors.white70, size: 20 * sf), + ) ], ), - ); + Divider(color: Colors.white24, height: 16 * sf), + + Wrap( + spacing: 12 * sf, + runSpacing: 12 * sf, + alignment: WrapAlignment.center, + children: bench.map((playerId) { + final playerName = controller.playerNames[playerId] ?? "Erro"; + final num = controller.playerNumbers[playerId] ?? "0"; + final int fouls = controller.playerStats[playerId]?["fls"] ?? 0; + final bool isFouledOut = fouls >= 5; - if (isFouledOut) { - return GestureDetector(onTap: () => ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('🛑 $playerName não pode voltar (Expulso).'), backgroundColor: AppTheme.actionMiss)), child: avatarUI); - } + String shortName = playerName.length > 8 ? "${playerName.substring(0, 7)}." : playerName; - return Draggable( - data: "$prefix$playerId", - feedback: Material(color: Colors.transparent, child: CircleAvatar(radius: 22 * sf, backgroundColor: teamColor, child: Text(num, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16 * sf)))), - childWhenDragging: Opacity(opacity: 0.5, child: SizedBox(width: 36 * sf, height: 36 * sf)), - child: avatarUI, - ); - }).toList(), + Widget avatarUI = Column( + mainAxisSize: MainAxisSize.min, + children: [ + CircleAvatar( + radius: 20 * sf, + backgroundColor: isFouledOut ? Colors.grey.shade800 : teamColor, + child: Text(num, style: TextStyle(color: isFouledOut ? Colors.red.shade300 : Colors.white, fontSize: 16 * sf, fontWeight: FontWeight.bold, decoration: isFouledOut ? TextDecoration.lineThrough : TextDecoration.none)), + ), + SizedBox(height: 4 * sf), + Text(shortName, style: TextStyle(color: Colors.white, fontSize: 10 * sf, fontWeight: FontWeight.bold), overflow: TextOverflow.ellipsis), + ], + ); + + if (isFouledOut) { + return GestureDetector(onTap: () => ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('🛑 $playerName expulso!'), backgroundColor: AppTheme.actionMiss)), child: avatarUI); + } + + return Draggable( + data: "$prefix$playerId", + feedback: Material(color: Colors.transparent, child: CircleAvatar(radius: 26 * sf, backgroundColor: teamColor, child: Text(num, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18 * sf)))), + childWhenDragging: Opacity(opacity: 0.3, child: avatarUI), + child: avatarUI, + ); + }).toList(), + ), + ], + ), ); } } -// 3. CARTÃO DO JOGADOR NO CAMPO class PlayerCourtCard extends StatelessWidget { final PlacarController controller; final String playerId; @@ -237,7 +259,10 @@ class PlayerCourtCard extends StatelessWidget { onZoneSelected: (zone, points, relX, relY) { Navigator.pop(ctx); controller.registerShotFromPopup(context, action, "$prefix$playerId", zone, points, relX, relY); - if (isMake) showAssistDialog(context, controller, isOpponent, playerId, sf); + + if (isMake) { + showAssistDialog(context, controller, isOpponent, playerId, sf); + } }, ), ); @@ -252,6 +277,7 @@ class PlayerCourtCard extends StatelessWidget { builder: (context, candidateData, rejectedData) { bool isSubbing = candidateData.any((data) => data != null && (data.startsWith("bench_my_") || data.startsWith("bench_opp_"))); bool isActionHover = candidateData.any((data) => data != null && (data.startsWith("add_") || data.startsWith("sub_") || data.startsWith("miss_"))); + return _playerCardUI(number, realName, stats, teamColor, isSubbing, isActionHover, sf); }, ), @@ -307,7 +333,6 @@ class PlayerCourtCard extends StatelessWidget { } } -// 4. PAINEL DE BOTÕES DE AÇÃO class ActionButtonsPanel extends StatelessWidget { final PlacarController controller; final double sf; @@ -441,4 +466,455 @@ class ActionButtonsPanel extends StatelessWidget { ], ); } +} + +class HeatmapDialog extends StatefulWidget { + final List shots; + final String myTeamName; + final String oppTeamName; + final List myPlayers; + final List oppPlayers; + final Map> playerStats; + + const HeatmapDialog({ + super.key, + required this.shots, + required this.myTeamName, + required this.oppTeamName, + required this.myPlayers, + required this.oppPlayers, + required this.playerStats, + }); + + @override + State createState() => _HeatmapDialogState(); +} + +class _HeatmapDialogState extends State { + bool _isMapVisible = false; + String _selectedTeam = ''; + String _selectedPlayer = ''; + + @override + Widget build(BuildContext context) { + final Color headerColor = const Color(0xFFE88F15); + final Color yellowBackground = const Color(0xFFDFAB00); + + final double screenHeight = MediaQuery.of(context).size.height; + final double dialogHeight = screenHeight * 0.95; + final double dialogWidth = dialogHeight * 1.0; + + return Dialog( + backgroundColor: yellowBackground, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + clipBehavior: Clip.antiAlias, + insetPadding: const EdgeInsets.all(10), + child: SizedBox( + height: dialogHeight, + width: dialogWidth, + child: _isMapVisible ? _buildMapScreen(headerColor) : _buildSelectionScreen(headerColor), + ), + ); + } + + Widget _buildSelectionScreen(Color headerColor) { + return Column( + children: [ + Container( + height: 40, + color: headerColor, + width: double.infinity, + child: Stack( + alignment: Alignment.center, + children: [ + const Text( + "ESCOLHE A EQUIPA OU UM JOGADOR", + style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.bold), + ), + Positioned( + right: 8, + child: InkWell( + onTap: () => Navigator.pop(context), + child: Container( + padding: const EdgeInsets.all(4), + decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), + child: Icon(Icons.close, color: headerColor, size: 16), + ), + ), + ) + ], + ), + ), + + Expanded( + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Row( + children: [ + Expanded( + child: _buildTeamColumn( + teamName: widget.myTeamName, + players: widget.myPlayers, + teamColor: AppTheme.myTeamBlue, + ), + ), + const SizedBox(width: 8), + Expanded( + child: _buildTeamColumn( + teamName: widget.oppTeamName, + players: widget.oppPlayers, + teamColor: AppTheme.oppTeamRed, + ), + ), + ], + ), + ), + ), + ], + ); + } + + Widget _buildTeamColumn({required String teamName, required List players, required Color teamColor}) { + List realPlayers = players.where((p) => !p.startsWith("Sem ")).toList(); + + return Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(8), + ), + child: Column( + children: [ + InkWell( + onTap: () => setState(() { + _selectedTeam = teamName; + _selectedPlayer = 'Todos'; + _isMapVisible = true; + }), + child: Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 10), + decoration: BoxDecoration( + color: teamColor, + borderRadius: const BorderRadius.only(topLeft: Radius.circular(8), topRight: Radius.circular(8)), + ), + child: Column( + children: [ + Text(teamName.toUpperCase(), style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16)), + const SizedBox(height: 4), + Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2), + decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(12)), + child: const Text("MAPA GERAL DA EQUIPA", style: TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.bold)), + ), + ], + ), + ), + ), + Expanded( + child: ListView.separated( + itemCount: realPlayers.length, + separatorBuilder: (context, index) => const Divider(height: 1, color: Colors.black12), + itemBuilder: (context, index) { + String p = realPlayers[index]; + int pts = widget.playerStats[p]?['pts'] ?? 0; + + return ListTile( + dense: true, + visualDensity: VisualDensity.compact, + leading: Icon(Icons.person, color: teamColor), + title: Text(p, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: Colors.black87)), + trailing: Text("$pts Pts", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: teamColor)), + onTap: () => setState(() { + _selectedTeam = teamName; + _selectedPlayer = p; + _isMapVisible = true; + }), + ); + }, + ), + ), + ], + ), + ); + } + + Widget _buildMapScreen(Color headerColor) { + List filteredShots = widget.shots.where((s) { + if (_selectedPlayer != 'Todos') return s.playerName == _selectedPlayer; + if (_selectedTeam == widget.myTeamName) return widget.myPlayers.contains(s.playerName); + if (_selectedTeam == widget.oppTeamName) return widget.oppPlayers.contains(s.playerName); + return true; + }).toList(); + + String titleText = _selectedPlayer == 'Todos' + ? "MAPA GERAL: ${_selectedTeam.toUpperCase()}" + : "MAPA: ${_selectedPlayer.toUpperCase()}"; + + return Column( + children: [ + Container( + height: 40, + color: headerColor, + width: double.infinity, + child: Stack( + alignment: Alignment.center, + children: [ + Positioned( + left: 8, + child: InkWell( + onTap: () => setState(() => _isMapVisible = false), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12)), + child: Row( + children: [ + Icon(Icons.arrow_back, color: headerColor, size: 14), + const SizedBox(width: 4), + Text("VOLTAR", style: TextStyle(color: headerColor, fontWeight: FontWeight.bold, fontSize: 12)), + ], + ), + ), + ), + ), + Text( + titleText, + style: const TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.bold), + ), + Positioned( + right: 8, + child: InkWell( + onTap: () => Navigator.pop(context), + child: Container( + padding: const EdgeInsets.all(4), + decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), + child: Icon(Icons.close, color: headerColor, size: 16), + ), + ), + ) + ], + ), + ), + Expanded( + child: LayoutBuilder( + builder: (context, constraints) { + return Stack( + children: [ + CustomPaint( + size: Size(constraints.maxWidth, constraints.maxHeight), + painter: HeatmapCourtPainter(), + ), + ...filteredShots.map((shot) => Positioned( + left: (shot.relativeX * constraints.maxWidth) - 8, + top: (shot.relativeY * constraints.maxHeight) - 8, + child: CircleAvatar( + radius: 8, + backgroundColor: shot.isMake ? AppTheme.successGreen : AppTheme.actionMiss, + child: Icon(shot.isMake ? Icons.check : Icons.close, size: 10, color: Colors.white) + ), + )), + ], + ); + }, + ), + ), + ], + ); + } +} + +class HeatmapCourtPainter extends CustomPainter { + @override + void paint(Canvas canvas, Size size) { + final double w = size.width; + final double h = size.height; + final double basketX = w / 2; + + final Paint whiteStroke = Paint()..color = Colors.white..style = PaintingStyle.stroke..strokeWidth = 2.0; + final Paint blackStroke = Paint()..color = Colors.black87..style = PaintingStyle.stroke..strokeWidth = 2.0; + + final double margin = w * 0.10; + final double length = h * 0.35; + final double larguraDoArco = (w / 2) - margin; + final double alturaDoArco = larguraDoArco * 0.30; + final double totalArcoHeight = alturaDoArco * 4; + + canvas.drawLine(Offset(margin, 0), Offset(margin, length), whiteStroke); + canvas.drawLine(Offset(w - margin, 0), Offset(w - margin, length), whiteStroke); + canvas.drawLine(Offset(0, length), Offset(margin, length), whiteStroke); + canvas.drawLine(Offset(w - margin, length), Offset(w, length), whiteStroke); + canvas.drawArc(Rect.fromCenter(center: Offset(basketX, length), width: larguraDoArco * 2, height: totalArcoHeight), 0, math.pi, false, whiteStroke); + + double sXL = basketX + (larguraDoArco * math.cos(math.pi * 0.75)); + double sYL = length + ((totalArcoHeight / 2) * math.sin(math.pi * 0.75)); + double sXR = basketX + (larguraDoArco * math.cos(math.pi * 0.25)); + double sYR = length + ((totalArcoHeight / 2) * math.sin(math.pi * 0.25)); + + canvas.drawLine(Offset(sXL, sYL), Offset(0, h * 0.85), whiteStroke); + canvas.drawLine(Offset(sXR, sYR), Offset(w, h * 0.85), whiteStroke); + + final double pW = w * 0.28; + final double pH = h * 0.38; + canvas.drawRect(Rect.fromLTWH(basketX - pW / 2, 0, pW, pH), blackStroke); + + final double ftR = pW / 2; + canvas.drawArc(Rect.fromCircle(center: Offset(basketX, pH), radius: ftR), 0, math.pi, false, blackStroke); + for (int i = 0; i < 10; i++) { + canvas.drawArc(Rect.fromCircle(center: Offset(basketX, pH), radius: ftR), math.pi + (i * 2 * (math.pi / 20)), math.pi / 20, false, blackStroke); + } + + canvas.drawLine(Offset(basketX - pW / 2, pH), Offset(sXL, sYL), blackStroke); + canvas.drawLine(Offset(basketX + pW / 2, pH), Offset(sXR, sYR), blackStroke); + + canvas.drawArc(Rect.fromCircle(center: Offset(basketX, h), radius: w * 0.12), math.pi, math.pi, false, blackStroke); + canvas.drawCircle(Offset(basketX, h * 0.12), w * 0.02, blackStroke); + canvas.drawLine(Offset(basketX - w * 0.08, h * 0.12 - 5), Offset(basketX + w * 0.08, h * 0.12 - 5), blackStroke); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +} + +// ============================================================================ +// 5. CAIXA DE HISTÓRICO (PLAY-BY-PLAY) +// ============================================================================ +class PlayByPlayDialog extends StatelessWidget { + final PlacarController controller; + const PlayByPlayDialog({super.key, required this.controller}); + + @override + Widget build(BuildContext context) { + return Dialog( + backgroundColor: AppTheme.placarDarkSurface, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + child: Container( + width: 400, + height: MediaQuery.of(context).size.height * 0.8, + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text("HISTÓRICO DE JOGADAS", style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold)), + IconButton(icon: const Icon(Icons.close, color: Colors.white), onPressed: () => Navigator.pop(context)) + ], + ), + const Divider(color: Colors.white24), + Expanded( + child: controller.playByPlay.isEmpty + ? const Center(child: Text("Ainda não há jogadas.", style: TextStyle(color: Colors.white54))) + : ListView.separated( + itemCount: controller.playByPlay.length, + separatorBuilder: (_, __) => const Divider(color: Colors.white10), + itemBuilder: (context, index) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4.0), + child: Text( + controller.playByPlay[index], + style: const TextStyle(color: Colors.white, fontSize: 14), + ), + ); + }, + ), + ), + ], + ), + ), + ); + } +} + +// ============================================================================ +// 6. ECRÃ DE BOX SCORE (ESTATÍSTICAS GERAIS) +// ============================================================================ +class BoxScoreDialog extends StatelessWidget { + final PlacarController controller; + const BoxScoreDialog({super.key, required this.controller}); + + @override + Widget build(BuildContext context) { + return Dialog( + backgroundColor: AppTheme.placarDarkSurface, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + child: Container( + width: MediaQuery.of(context).size.width * 0.9, + height: MediaQuery.of(context).size.height * 0.9, + padding: const EdgeInsets.all(16), + child: DefaultTabController( + length: 2, + child: Column( + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text("BOX SCORE", style: TextStyle(color: Colors.white, fontSize: 22, fontWeight: FontWeight.bold)), + IconButton(icon: const Icon(Icons.close, color: Colors.white), onPressed: () => Navigator.pop(context)) + ], + ), + TabBar( + indicatorColor: AppTheme.warningAmber, + labelColor: Colors.white, + unselectedLabelColor: Colors.white54, + tabs: [ + Tab(text: controller.myTeam.toUpperCase()), + Tab(text: controller.opponentTeam.toUpperCase()), + ], + ), + const SizedBox(height: 10), + Expanded( + child: TabBarView( + children: [ + _buildStatsTable(controller.myCourt + controller.myBench, controller), + _buildStatsTable(controller.oppCourt + controller.oppBench, controller), + ], + ), + ), + ], + ), + ), + ), + ); + } + + Widget _buildStatsTable(List teamPlayers, PlacarController ctrl) { + return SingleChildScrollView( + scrollDirection: Axis.vertical, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + headingRowColor: WidgetStateProperty.all(Colors.black26), + columns: const [ + DataColumn(label: Text('JOGADOR', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold))), + DataColumn(label: Text('PTS', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold))), + DataColumn(label: Text('REB', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold))), + DataColumn(label: Text('AST', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold))), + DataColumn(label: Text('STL', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold))), + DataColumn(label: Text('BLK', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold))), + DataColumn(label: Text('TOV', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold))), + DataColumn(label: Text('FLS', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold))), + DataColumn(label: Text('FG', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold))), + ], + rows: teamPlayers.where((id) => !id.startsWith("fake_")).map((id) { + final name = ctrl.playerNames[id] ?? "---"; + final s = ctrl.playerStats[id]!; + final rebs = s['orb']! + s['drb']!; + final fgText = "${s['fgm']}/${s['fga']}"; + return DataRow( + cells: [ + DataCell(Text(name, style: const TextStyle(color: Colors.white))), + DataCell(Text(s['pts'].toString(), style: const TextStyle(color: AppTheme.warningAmber, fontWeight: FontWeight.bold))), + DataCell(Text(rebs.toString(), style: const TextStyle(color: Colors.white))), + DataCell(Text(s['ast'].toString(), style: const TextStyle(color: Colors.white))), + DataCell(Text(s['stl'].toString(), style: const TextStyle(color: Colors.white))), + DataCell(Text(s['blk'].toString(), style: const TextStyle(color: Colors.white))), + DataCell(Text(s['tov'].toString(), style: const TextStyle(color: Colors.redAccent))), + DataCell(Text(s['fls'].toString(), style: const TextStyle(color: Colors.white))), + DataCell(Text(fgText, style: const TextStyle(color: Colors.white54))), + ], + ); + }).toList(), + ), + ), + ); + } } \ No newline at end of file