// ===========================================================================
// FILE: lib/ui/game/score_board.dart
// ===========================================================================

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
// Import separati e puliti
import '../../logic/game_controller.dart';
import '../../models/game_board.dart';
import '../../core/theme_manager.dart';
import '../../services/audio_service.dart';
import '../../core/app_colors.dart';
import '../../services/storage_service.dart';

class ScoreBoard extends StatefulWidget {
  const ScoreBoard({super.key});

  @override
  State<ScoreBoard> createState() => _ScoreBoardState();
}

class _ScoreBoardState extends State<ScoreBoard> {
  @override
  Widget build(BuildContext context) {
    final controller = context.watch<GameController>();
    final themeManager = context.watch<ThemeManager>();
    final theme = themeManager.currentColors;
    final themeType = themeManager.currentThemeType;

    int redScore = controller.board.scoreRed;
    int blueScore = controller.board.scoreBlue;

    bool isRedTurn = controller.board.currentPlayer == Player.red;
    bool isMuted = AudioService.instance.isMuted;

    String myName = StorageService.instance.playerName.toUpperCase();
    if (myName.isEmpty) myName = "TU";

    String nameRed = myName;
    String nameBlue = themeType == AppThemeType.cyberpunk || themeType == AppThemeType.arcade ? "VERDE" : "BLU";

    if (controller.isOnline) {
      nameRed = controller.onlineHostName.toUpperCase();
      nameBlue = controller.onlineGuestName.toUpperCase();
    } else if (controller.isVsCPU) {
      nameRed = myName;
      nameBlue = "CPU";
    }

    return Container(
      padding: const EdgeInsets.only(top: 10, bottom: 20, left: 20, right: 20),
      decoration: BoxDecoration(
        color: theme.background.withOpacity(0.95),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.3),
            offset: const Offset(0, 4),
            blurRadius: 8,
          ),
        ],
        borderRadius: const BorderRadius.only(
          bottomLeft: Radius.circular(30),
          bottomRight: Radius.circular(30),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          _PlayerScore(color: theme.playerRed, score: redScore, isTurn: isRedTurn, textColor: theme.text, title: nameRed),

          Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                  "TETRAQ",
                  style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.w900,
                      color: theme.text,
                      letterSpacing: 4,
                      shadows: [Shadow(color: Colors.black.withOpacity(0.3), offset: const Offset(1, 2), blurRadius: 2)]
                  )
              ),
              IconButton(
                icon: Icon(isMuted ? Icons.volume_off : Icons.volume_up, color: theme.text.withOpacity(0.7)),
                onPressed: () {
                  setState(() {
                    AudioService.instance.toggleMute();
                  });
                },
              ),
            ],
          ),

          _PlayerScore(color: theme.playerBlue, score: blueScore, isTurn: !isRedTurn, textColor: theme.text, title: nameBlue),
        ],
      ),
    );
  }
}

class _PlayerScore extends StatelessWidget {
  final Color color;
  final int score;
  final bool isTurn;
  final Color textColor;
  final String title;

  const _PlayerScore({required this.color, required this.score, required this.isTurn, required this.textColor, required this.title});

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(title, style: TextStyle(fontWeight: FontWeight.bold, color: isTurn ? color : textColor.withOpacity(0.5), fontSize: 12)),
        const SizedBox(height: 5),
        AnimatedContainer(
          duration: const Duration(milliseconds: 300),
          padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 10),
          decoration: BoxDecoration(
            color: color.withOpacity(isTurn ? 1.0 : 0.2),
            borderRadius: BorderRadius.circular(15),
            border: isTurn ? Border.all(color: Colors.white.withOpacity(0.4), width: 2) : Border.all(color: Colors.transparent, width: 2),
            boxShadow: isTurn ? [
              BoxShadow(color: color.withOpacity(0.5), offset: const Offset(0, 4), blurRadius: 6)
            ] : [],
          ),
          child: Text('$score', style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: isTurn ? Colors.white : textColor.withOpacity(0.5))),
        ),
      ],
    );
  }
}