import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:onsolgo/core/constants.dart';

/// Shows current reader energy (or MAX when unlimited) from `users/{uid}`.
class EnergyUserChip extends StatelessWidget {
  final String uid;
  const EnergyUserChip({super.key, required this.uid});

  static bool _unlimited(Map<String, dynamic> u) {
    return (u['tier'] ?? 'free') != 'free' ||
        safeInt(u['rankLevel']) == 5 ||
        (u['isVerified'] ?? false);
  }

  @override
  Widget build(BuildContext context) {
    if (uid.isEmpty) return const SizedBox.shrink();
    return StreamBuilder<DocumentSnapshot>(
      stream: FirebaseFirestore.instance.collection('users').doc(uid).snapshots(),
      builder: (context, snap) {
        if (!snap.hasData || !snap.data!.exists) return const SizedBox.shrink();
        final u = snap.data!.data() as Map<String, dynamic>;
        final unlimited = _unlimited(u);
        final e = safeInt(u['energy'] ?? 2);
        return Container(
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
          decoration: BoxDecoration(
            color: Colors.black.withValues(alpha: 0.55),
            borderRadius: BorderRadius.circular(20),
            border: Border.all(color: Colors.orangeAccent.withValues(alpha: 0.5)),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.bolt, color: unlimited ? kOnsolGold : Colors.orangeAccent, size: 18),
              const SizedBox(width: 4),
              Text(
                unlimited ? 'ENERGY: MAX' : 'ENERGY: $e/2',
                style: const TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: 12,
                  letterSpacing: 0.5,
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
