import 'package:flutter/material.dart';

import 'package:asciineverdie/data/game_text_l10n.dart' as l10n;
import 'package:asciineverdie/src/core/l10n/game_data_l10n.dart';
import 'package:asciineverdie/src/core/model/equipment_slot.dart';
import 'package:asciineverdie/src/core/model/game_state.dart';
import 'package:asciineverdie/src/core/model/hall_of_fame.dart';
import 'package:asciineverdie/src/core/model/item_stats.dart';
import 'package:asciineverdie/src/core/storage/hall_of_fame_storage.dart';
import 'package:asciineverdie/src/features/game/widgets/ascii_animation_card.dart';

/// 명예의 전당 화면 (Phase 10: Hall of Fame Screen)
class HallOfFameScreen extends StatefulWidget {
  const HallOfFameScreen({super.key});

  @override
  State<HallOfFameScreen> createState() => _HallOfFameScreenState();
}

class _HallOfFameScreenState extends State<HallOfFameScreen> {
  final HallOfFameStorage _storage = HallOfFameStorage();
  HallOfFame? _hallOfFame;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadHallOfFame();
  }

  Future<void> _loadHallOfFame() async {
    final hallOfFame = await _storage.load();

    if (mounted) {
      setState(() {
        _hallOfFame = hallOfFame;
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(l10n.uiHallOfFame), centerTitle: true),
      body: SafeArea(
        top: false, // AppBar가 상단 처리
        child: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : _buildContent(),
      ),
    );
  }

  Widget _buildContent() {
    final hallOfFame = _hallOfFame;
    if (hallOfFame == null || hallOfFame.isEmpty) {
      return _buildEmptyState();
    }

    return _buildHallOfFameList(hallOfFame);
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.emoji_events_outlined,
            size: 80,
            color: Colors.grey.shade400,
          ),
          const SizedBox(height: 16),
          Text(
            l10n.hofNoHeroes,
            style: TextStyle(fontSize: 20, color: Colors.grey.shade600),
          ),
          const SizedBox(height: 8),
          Text(
            l10n.hofDefeatGlitchGod,
            style: TextStyle(fontSize: 14, color: Colors.grey.shade500),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildHallOfFameList(HallOfFame hallOfFame) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.amber.shade700, width: 2),
        borderRadius: BorderRadius.circular(8),
      ),
      margin: const EdgeInsets.all(16),
      child: Column(
        children: [
          // 헤더
          Container(
            padding: const EdgeInsets.symmetric(vertical: 12),
            decoration: BoxDecoration(
              color: Colors.amber.shade700,
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(6),
                topRight: Radius.circular(6),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(Icons.emoji_events, color: Colors.white),
                const SizedBox(width: 8),
                Text(
                  l10n.uiHallOfFame.toUpperCase(),
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    letterSpacing: 2,
                  ),
                ),
                const SizedBox(width: 8),
                const Icon(Icons.emoji_events, color: Colors.white),
              ],
            ),
          ),
          // 엔트리 목록
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.all(8),
              itemCount: hallOfFame.entries.length,
              itemBuilder: (context, index) {
                final entry = hallOfFame.entries[index];
                return _HallOfFameEntryCard(entry: entry, rank: index + 1);
              },
            ),
          ),
        ],
      ),
    );
  }
}

/// 명예의 전당 엔트리 카드
class _HallOfFameEntryCard extends StatelessWidget {
  const _HallOfFameEntryCard({required this.entry, required this.rank});

  final HallOfFameEntry entry;
  final int rank;

  void _showDetailDialog(BuildContext context) {
    showDialog<void>(
      context: context,
      builder: (context) => _HallOfFameDetailDialog(entry: entry),
    );
  }

  @override
  Widget build(BuildContext context) {
    final rankColor = _getRankColor(rank);
    final rankIcon = _getRankIcon(rank);

    return Card(
      margin: const EdgeInsets.symmetric(vertical: 4),
      child: InkWell(
        onTap: () => _showDetailDialog(context),
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Row(
            children: [
            // 순위 표시
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: rankColor.withValues(alpha: 0.2),
                shape: BoxShape.circle,
                border: Border.all(color: rankColor, width: 2),
              ),
              child: Center(
                child: rankIcon != null
                    ? Icon(rankIcon, color: rankColor, size: 20)
                    : Text(
                        '$rank',
                        style: TextStyle(
                          color: rankColor,
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                      ),
              ),
            ),
            const SizedBox(width: 12),
            // 캐릭터 정보
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 이름과 레벨
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          '"${entry.characterName}"',
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 8,
                          vertical: 2,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.blue.shade100,
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          l10n.uiLevel(entry.level),
                          style: TextStyle(
                            color: Colors.blue.shade800,
                            fontWeight: FontWeight.bold,
                            fontSize: 12,
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 4),
                  // 종족/클래스
                  Text(
                    '${GameDataL10n.getRaceName(context, entry.race)} '
                    '${GameDataL10n.getKlassName(context, entry.klass)}',
                    style: TextStyle(fontSize: 13, color: Colors.grey.shade700),
                  ),
                  const SizedBox(height: 4),
                  // 통계
                  Row(
                    children: [
                      _buildStatChip(
                        Icons.timer,
                        entry.formattedPlayTime,
                        Colors.green,
                      ),
                      const SizedBox(width: 8),
                      _buildStatChip(
                        Icons.heart_broken,
                        '${entry.totalDeaths}',
                        Colors.red,
                      ),
                      const SizedBox(width: 8),
                      _buildStatChip(
                        Icons.check_circle,
                        '${entry.questsCompleted}Q',
                        Colors.orange,
                      ),
                    ],
                  ),
                ],
              ),
            ),
            // 클리어 날짜
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Icon(
                  Icons.calendar_today,
                  size: 14,
                  color: Colors.grey.shade500,
                ),
                const SizedBox(height: 4),
                Text(
                  entry.formattedClearedDate,
                  style: TextStyle(fontSize: 11, color: Colors.grey.shade600),
                ),
              ],
            ),
          ],
        ),
      ),
    ),
  );
  }

  Widget _buildStatChip(IconData icon, String value, Color color) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, size: 12, color: color),
        const SizedBox(width: 2),
        Text(
          value,
          style: TextStyle(
            fontSize: 11,
            color: color,
            fontWeight: FontWeight.w500,
          ),
        ),
      ],
    );
  }

  Color _getRankColor(int rank) {
    switch (rank) {
      case 1:
        return Colors.amber.shade700;
      case 2:
        return Colors.grey.shade500;
      case 3:
        return Colors.brown.shade400;
      default:
        return Colors.blue.shade400;
    }
  }

  IconData? _getRankIcon(int rank) {
    switch (rank) {
      case 1:
        return Icons.emoji_events;
      case 2:
        return Icons.workspace_premium;
      case 3:
        return Icons.military_tech;
      default:
        return null;
    }
  }
}

/// 게임 클리어 축하 다이얼로그
Future<void> showGameClearDialog(
  BuildContext context, {
  required HallOfFameEntry entry,
  required VoidCallback onNewGame,
  required VoidCallback onViewHallOfFame,
}) {
  return showDialog(
    context: context,
    barrierDismissible: false,
    builder: (context) => _GameClearDialog(
      entry: entry,
      onNewGame: onNewGame,
      onViewHallOfFame: onViewHallOfFame,
    ),
  );
}

/// 게임 클리어 다이얼로그 위젯
class _GameClearDialog extends StatelessWidget {
  const _GameClearDialog({
    required this.entry,
    required this.onNewGame,
    required this.onViewHallOfFame,
  });

  final HallOfFameEntry entry;
  final VoidCallback onNewGame;
  final VoidCallback onViewHallOfFame;

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(Icons.emoji_events, color: Colors.amber, size: 32),
          const SizedBox(width: 8),
          Text(l10n.hofVictory),
          const SizedBox(width: 8),
          const Icon(Icons.emoji_events, color: Colors.amber, size: 32),
        ],
      ),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            l10n.hofDefeatedGlitchGod,
            style: const TextStyle(fontSize: 16),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 16),
          const Divider(),
          const SizedBox(height: 16),
          // 캐릭터 정보
          Text(
            '"${entry.characterName}"',
            style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 4),
          Text(
            '${GameDataL10n.getRaceName(context, entry.race)} ${GameDataL10n.getKlassName(context, entry.klass)}',
            style: TextStyle(color: Colors.grey.shade600),
          ),
          const SizedBox(height: 16),
          // 통계
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              _buildStat(l10n.hofLevel, '${entry.level}'),
              _buildStat(l10n.hofTime, entry.formattedPlayTime),
              _buildStat(l10n.hofDeaths, '${entry.totalDeaths}'),
              _buildStat(l10n.hofQuests, '${entry.questsCompleted}'),
            ],
          ),
          const SizedBox(height: 16),
          Text(
            l10n.hofLegendEnshrined,
            style: const TextStyle(
              fontStyle: FontStyle.italic,
              color: Colors.amber,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () {
            Navigator.of(context).pop();
            onViewHallOfFame();
          },
          child: Text(l10n.hofViewHallOfFame),
        ),
        FilledButton(
          onPressed: () {
            Navigator.of(context).pop();
            onNewGame();
          },
          child: Text(l10n.hofNewGame),
        ),
      ],
    );
  }

  Widget _buildStat(String label, String value) {
    return Column(
      children: [
        Text(
          value,
          style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        Text(
          label,
          style: TextStyle(fontSize: 11, color: Colors.grey.shade600),
        ),
      ],
    );
  }
}

/// 명예의 전당 상세 정보 다이얼로그
class _HallOfFameDetailDialog extends StatelessWidget {
  const _HallOfFameDetailDialog({required this.entry});

  final HallOfFameEntry entry;

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Column(
        children: [
          Text(
            '"${entry.characterName}"',
            style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 4),
          Text(
            '${GameDataL10n.getRaceName(context, entry.race)} '
            '${GameDataL10n.getKlassName(context, entry.klass)} - '
            '${l10n.uiLevel(entry.level)}',
            style: TextStyle(fontSize: 14, color: Colors.grey.shade600),
          ),
        ],
      ),
      content: ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 400, maxHeight: 500),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              // 캐릭터 애니메이션 섹션 (Character Animation Section)
              _buildSection(
                icon: Icons.movie,
                title: l10n.hofCharacterPreview,
                child: _buildAnimationPreview(),
              ),
              const SizedBox(height: 16),
              // 통계 섹션 (Statistics Section)
              _buildSection(
                icon: Icons.analytics,
                title: l10n.hofStats,
                child: _buildStatsGrid(),
              ),
              const SizedBox(height: 16),
              // 전투 스탯 섹션 (Combat Stats Section)
              if (entry.finalStats != null) ...[
                _buildSection(
                  icon: Icons.sports_mma,
                  title: l10n.hofCombatStats,
                  child: _buildCombatStatsGrid(),
                ),
                const SizedBox(height: 16),
              ],
              // 장비 섹션 (Equipment Section)
              if (entry.finalEquipment != null) ...[
                _buildSection(
                  icon: Icons.shield,
                  title: l10n.navEquipment,
                  child: _buildEquipmentList(context),
                ),
                const SizedBox(height: 16),
              ],
              // 스펠 섹션 (Spells Section)
              if (entry.finalSpells != null && entry.finalSpells!.isNotEmpty)
                _buildSection(
                  icon: Icons.auto_fix_high,
                  title: l10n.hofSpells,
                  child: _buildSpellList(context),
                ),
            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(),
          child: Text(l10n.buttonClose),
        ),
      ],
    );
  }

  Widget _buildSection({
    required IconData icon,
    required String title,
    required Widget child,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Icon(icon, size: 18, color: Colors.amber.shade700),
            const SizedBox(width: 8),
            Text(
              title,
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: Colors.amber.shade700,
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        child,
      ],
    );
  }

  /// 캐릭터 애니메이션 미리보기 위젯
  Widget _buildAnimationPreview() {
    // 장비에서 무기와 방패 이름 추출
    String? weaponName;
    String? shieldName;

    if (entry.finalEquipment != null) {
      for (final item in entry.finalEquipment!) {
        if (item.slot == EquipmentSlot.weapon && item.isNotEmpty) {
          weaponName = item.name;
        } else if (item.slot == EquipmentSlot.shield && item.isNotEmpty) {
          shieldName = item.name;
        }
      }
    }

    // AsciiCanvasWidget은 60x8 그리드 사용
    // 다이얼로그 내에서 적절한 크기: 360x80 (비율 7.5:1 유지)
    return Center(
      child: Container(
        decoration: BoxDecoration(
          border: Border.all(color: Colors.amber.shade300),
          borderRadius: BorderRadius.circular(8),
        ),
        child: SizedBox(
          width: 360,
          height: 80,
          child: AsciiAnimationCard(
            taskType: TaskType.kill, // 전투 애니메이션 표시
            raceId: entry.race,
            weaponName: weaponName,
            shieldName: shieldName,
            characterLevel: entry.level,
            monsterLevel: entry.level, // 레벨에 맞는 몬스터 크기
            monsterBaseName: 'Glitch God', // 최종 보스
          ),
        ),
      ),
    );
  }

  Widget _buildStatsGrid() {
    return Wrap(
      spacing: 16,
      runSpacing: 8,
      children: [
        _buildStatItem(Icons.timer, l10n.hofTime, entry.formattedPlayTime),
        _buildStatItem(
          Icons.pest_control,
          l10n.hofMonsters,
          '${entry.monstersKilled}',
        ),
        _buildStatItem(
          Icons.heart_broken,
          l10n.hofDeaths,
          '${entry.totalDeaths}',
        ),
        _buildStatItem(
          Icons.check_circle,
          l10n.hofQuests,
          '${entry.questsCompleted}',
        ),
        _buildStatItem(
          Icons.calendar_today,
          l10n.hofCleared,
          entry.formattedClearedDate,
        ),
      ],
    );
  }

  Widget _buildCombatStatsGrid() {
    final stats = entry.finalStats!;
    return Column(
      children: [
        // 기본 스탯 행 (Basic Stats Row)
        Wrap(
          spacing: 8,
          runSpacing: 4,
          children: [
            _buildCombatStatChip(l10n.statStr, '${stats.str}', Colors.red),
            _buildCombatStatChip(l10n.statCon, '${stats.con}', Colors.orange),
            _buildCombatStatChip(l10n.statDex, '${stats.dex}', Colors.green),
            _buildCombatStatChip(l10n.statInt, '${stats.intelligence}', Colors.blue),
            _buildCombatStatChip(l10n.statWis, '${stats.wis}', Colors.purple),
            _buildCombatStatChip(l10n.statCha, '${stats.cha}', Colors.pink),
          ],
        ),
        const SizedBox(height: 8),
        const Divider(height: 1),
        const SizedBox(height: 8),
        // 공격 스탯 행 (Attack Stats Row)
        Wrap(
          spacing: 8,
          runSpacing: 4,
          children: [
            _buildCombatStatChip(l10n.statAtk, '${stats.atk}', Colors.red.shade700),
            _buildCombatStatChip(l10n.statMAtk, '${stats.magAtk}', Colors.blue.shade700),
            _buildCombatStatChip(
              l10n.statCri,
              '${(stats.criRate * 100).toStringAsFixed(1)}%',
              Colors.amber.shade700,
            ),
          ],
        ),
        const SizedBox(height: 8),
        // 방어 스탯 행 (Defense Stats Row)
        Wrap(
          spacing: 8,
          runSpacing: 4,
          children: [
            _buildCombatStatChip(l10n.statDef, '${stats.def}', Colors.brown),
            _buildCombatStatChip(l10n.statMDef, '${stats.magDef}', Colors.indigo),
            _buildCombatStatChip(
              l10n.statEva,
              '${(stats.evasion * 100).toStringAsFixed(1)}%',
              Colors.teal,
            ),
            _buildCombatStatChip(
              l10n.statBlock,
              '${(stats.blockRate * 100).toStringAsFixed(1)}%',
              Colors.blueGrey,
            ),
          ],
        ),
        const SizedBox(height: 8),
        // HP/MP 행 (Resource Stats Row)
        Wrap(
          spacing: 8,
          runSpacing: 4,
          children: [
            _buildCombatStatChip(l10n.statHp, '${stats.hpMax}', Colors.red.shade400),
            _buildCombatStatChip(l10n.statMp, '${stats.mpMax}', Colors.blue.shade400),
          ],
        ),
      ],
    );
  }

  Widget _buildCombatStatChip(String label, String value, Color color) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(6),
        border: Border.all(color: color.withValues(alpha: 0.3)),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            '$label ',
            style: TextStyle(fontSize: 11, color: color),
          ),
          Text(
            value,
            style: TextStyle(
              fontSize: 11,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem(IconData icon, String label, String value) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: Colors.amber.shade700.withValues(alpha: 0.15),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.amber.shade700.withValues(alpha: 0.3)),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 14, color: Colors.amber.shade600),
          const SizedBox(width: 6),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                value,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 13,
                  color: Colors.amber.shade300,
                ),
              ),
              Text(
                label,
                style: TextStyle(fontSize: 10, color: Colors.amber.shade400),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildEquipmentList(BuildContext context) {
    final equipment = entry.finalEquipment!;

    return Column(
      children: equipment.map((item) {
        if (item.isEmpty) return const SizedBox.shrink();

        final slotLabel = _getSlotLabel(item.slot);
        final slotIcon = _getSlotIcon(item.slot);
        final slotIndex = _getSlotIndex(item.slot);
        final rarityColor = _getRarityColor(item.rarity);

        // 장비 이름 번역
        final translatedName = GameDataL10n.translateEquipString(
          context,
          item.name,
          slotIndex,
        );

        // 주요 스탯 요약
        final statSummary = _buildStatSummary(item.stats, item.slot);

        return Padding(
          padding: const EdgeInsets.symmetric(vertical: 4),
          child: Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: rarityColor.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(6),
              border: Border.all(color: rarityColor.withValues(alpha: 0.3)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 슬롯 + 이름 + 희귀도 표시
                Row(
                  children: [
                    Icon(slotIcon, size: 14, color: rarityColor),
                    const SizedBox(width: 6),
                    Text(
                      slotLabel,
                      style: TextStyle(
                        fontSize: 10,
                        color: Colors.grey.shade500,
                      ),
                    ),
                    const Spacer(),
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 6,
                        vertical: 1,
                      ),
                      decoration: BoxDecoration(
                        color: rarityColor.withValues(alpha: 0.2),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Text(
                        _getRarityLabel(item.rarity),
                        style: TextStyle(
                          fontSize: 9,
                          color: rarityColor,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 4),
                // 장비 이름
                Text(
                  translatedName,
                  style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.w600,
                    color: rarityColor,
                  ),
                ),
                // 스탯 요약
                if (statSummary.isNotEmpty) ...[
                  const SizedBox(height: 4),
                  Wrap(
                    spacing: 6,
                    runSpacing: 2,
                    children: statSummary,
                  ),
                ],
              ],
            ),
          ),
        );
      }).toList(),
    );
  }

  String _getSlotLabel(EquipmentSlot slot) {
    return switch (slot) {
      EquipmentSlot.weapon => l10n.slotWeapon,
      EquipmentSlot.shield => l10n.slotShield,
      EquipmentSlot.helm => l10n.slotHelm,
      EquipmentSlot.hauberk => l10n.slotHauberk,
      EquipmentSlot.brassairts => l10n.slotBrassairts,
      EquipmentSlot.vambraces => l10n.slotVambraces,
      EquipmentSlot.gauntlets => l10n.slotGauntlets,
      EquipmentSlot.gambeson => l10n.slotGambeson,
      EquipmentSlot.cuisses => l10n.slotCuisses,
      EquipmentSlot.greaves => l10n.slotGreaves,
      EquipmentSlot.sollerets => l10n.slotSollerets,
    };
  }

  IconData _getSlotIcon(EquipmentSlot slot) {
    return switch (slot) {
      EquipmentSlot.weapon => Icons.gavel,
      EquipmentSlot.shield => Icons.shield,
      EquipmentSlot.helm => Icons.sports_mma,
      EquipmentSlot.hauberk => Icons.checkroom,
      EquipmentSlot.brassairts => Icons.front_hand,
      EquipmentSlot.vambraces => Icons.back_hand,
      EquipmentSlot.gauntlets => Icons.sports_handball,
      EquipmentSlot.gambeson => Icons.dry_cleaning,
      EquipmentSlot.cuisses => Icons.airline_seat_legroom_normal,
      EquipmentSlot.greaves => Icons.snowshoeing,
      EquipmentSlot.sollerets => Icons.do_not_step,
    };
  }

  int _getSlotIndex(EquipmentSlot slot) {
    return switch (slot) {
      EquipmentSlot.weapon => 0,
      EquipmentSlot.shield => 1,
      _ => 2,
    };
  }

  Color _getRarityColor(ItemRarity rarity) {
    return switch (rarity) {
      ItemRarity.common => Colors.grey.shade600,
      ItemRarity.uncommon => Colors.green.shade600,
      ItemRarity.rare => Colors.blue.shade600,
      ItemRarity.epic => Colors.purple.shade600,
      ItemRarity.legendary => Colors.orange.shade700,
    };
  }

  String _getRarityLabel(ItemRarity rarity) {
    return switch (rarity) {
      ItemRarity.common => l10n.rarityCommon,
      ItemRarity.uncommon => l10n.rarityUncommon,
      ItemRarity.rare => l10n.rarityRare,
      ItemRarity.epic => l10n.rarityEpic,
      ItemRarity.legendary => l10n.rarityLegendary,
    };
  }

  List<Widget> _buildStatSummary(ItemStats stats, EquipmentSlot slot) {
    final widgets = <Widget>[];

    void addStat(String label, String value, Color color) {
      widgets.add(
        Text(
          '$label $value',
          style: TextStyle(fontSize: 10, color: color),
        ),
      );
    }

    // 공격 스탯
    if (stats.atk > 0) addStat(l10n.statAtk, '+${stats.atk}', Colors.red);
    if (stats.magAtk > 0) {
      addStat(l10n.statMAtk, '+${stats.magAtk}', Colors.blue);
    }

    // 방어 스탯
    if (stats.def > 0) addStat(l10n.statDef, '+${stats.def}', Colors.brown);
    if (stats.magDef > 0) {
      addStat(l10n.statMDef, '+${stats.magDef}', Colors.indigo);
    }

    // 확률 스탯
    if (stats.criRate > 0) {
      addStat(l10n.statCri, '+${(stats.criRate * 100).toStringAsFixed(0)}%', Colors.amber);
    }
    if (stats.blockRate > 0) {
      addStat(l10n.statBlock, '+${(stats.blockRate * 100).toStringAsFixed(0)}%', Colors.blueGrey);
    }
    if (stats.evasion > 0) {
      addStat(l10n.statEva, '+${(stats.evasion * 100).toStringAsFixed(0)}%', Colors.teal);
    }
    if (stats.parryRate > 0) {
      addStat(l10n.statParry, '+${(stats.parryRate * 100).toStringAsFixed(0)}%', Colors.cyan);
    }

    // 보너스 스탯
    if (stats.hpBonus > 0) {
      addStat(l10n.statHp, '+${stats.hpBonus}', Colors.red.shade400);
    }
    if (stats.mpBonus > 0) {
      addStat(l10n.statMp, '+${stats.mpBonus}', Colors.blue.shade400);
    }

    // 능력치 보너스
    if (stats.strBonus > 0) {
      addStat(l10n.statStr, '+${stats.strBonus}', Colors.red.shade700);
    }
    if (stats.conBonus > 0) {
      addStat(l10n.statCon, '+${stats.conBonus}', Colors.orange.shade700);
    }
    if (stats.dexBonus > 0) {
      addStat(l10n.statDex, '+${stats.dexBonus}', Colors.green.shade700);
    }
    if (stats.intBonus > 0) {
      addStat(l10n.statInt, '+${stats.intBonus}', Colors.blue.shade700);
    }

    return widgets;
  }

  Widget _buildSpellList(BuildContext context) {
    final spells = entry.finalSpells!;
    return Wrap(
      spacing: 8,
      runSpacing: 4,
      children: spells.map((spell) {
        final name = spell['name'] ?? '';
        final rank = spell['rank'] ?? '';
        // 스펠 이름 번역 적용
        final translatedName = GameDataL10n.getSpellName(context, name);
        return Container(
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
          decoration: BoxDecoration(
            color: Colors.purple.shade50,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: Colors.purple.shade200),
          ),
          child: Text(
            '$translatedName $rank',
            style: TextStyle(fontSize: 12, color: Colors.purple.shade700),
          ),
        );
      }).toList(),
    );
  }
}
