import 'package:flutter/material.dart';
import '../../models/maps/prefecture_tile_layout.dart';
import '../../theme/app_theme.dart';

class PrefectureTileMap extends StatelessWidget {
  final Set<String> visitedPrefectures;
  final Function(String) onPrefectureTap;
  final double tileSize;
  final double gap;

  const PrefectureTileMap({
    super.key,
    required this.visitedPrefectures,
    required this.onPrefectureTap,
    this.tileSize = 46.0,
    this.gap = 4.0,
  });

  @override
  Widget build(BuildContext context) {
    // 1. Determine Grid Bounds
    int maxCol = 0;
    int maxRow = 0;
    PrefectureTileLayout.getLayout.forEach((_, pos) {
      if (pos.col + pos.width > maxCol) maxCol = pos.col + pos.width;
      if (pos.row + pos.height > maxRow) maxRow = pos.row + pos.height;
    });

    final double totalWidth = maxCol * (tileSize + gap) - gap;
    final double totalHeight = maxRow * (tileSize + gap) - gap;

    return SizedBox(
      width: totalWidth,
      height: totalHeight,
      child: Stack(
        children: PrefectureTileLayout.getLayout.entries.map((entry) {
          final prefName = entry.key;
          final pos = entry.value;
          final isVisited = visitedPrefectures.contains(prefName) || 
                            visitedPrefectures.any((v) => v.startsWith(prefName)); // Robust check

          return Positioned(
            left: pos.col * (tileSize + gap),
            top: pos.row * (tileSize + gap),
            width: pos.width * tileSize + (pos.width - 1) * gap,
            height: pos.height * tileSize + (pos.height - 1) * gap,
            child: _buildTile(context, prefName, isVisited),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildTile(BuildContext context, String prefName, bool isVisited) {
    final isDark = Theme.of(context).brightness == Brightness.dark;
    
    // Color Logic
    final baseColor = isVisited ? AppTheme.posimaiBlue : (isDark ? Colors.grey[800]! : Colors.grey[300]!);
    final textColor = isVisited ? Colors.white : (isDark ? Colors.grey[400] : Colors.grey[700]);
    final borderColor = isDark ? Colors.grey[700]! : Colors.white;

    return Material(
      color: baseColor,
      borderRadius: BorderRadius.circular(6), // Rounded corners for "Block" look
      child: InkWell(
        onTap: () => onPrefectureTap(prefName),
        borderRadius: BorderRadius.circular(6),
        child: Container(
          alignment: Alignment.center,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(6),
            border: Border.all(color: borderColor, width: 1), // Subtle inner border
          ),
          child: Text(
            prefName,
            style: TextStyle(
              color: textColor,
              fontSize: 12, // Small but legible
              fontWeight: FontWeight.bold,
            ),
            textAlign: TextAlign.center,
          ),
        ),
      ),
    );
  }
}
