// Version: 1.0.0 | Created: 2026-04-02
// Shared avatar widget used throughout the app. Displays a cached network
// image when an HTTP avatar URL is available, or falls back to a coloured
// circle with the first letter of the display name.
//
// The [avatarUrl] MUST be a resolved HTTP URL — never pass an mxc:// URI.

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';

class MatrixAvatar extends StatelessWidget {
  const MatrixAvatar({
    super.key,
    required this.name,
    this.avatarUrl,
    this.radius = 20,
  });

  /// Display name used for the initials fallback.
  final String name;

  /// Resolved HTTP URL for the avatar image. Must NOT be an mxc:// URI.
  final String? avatarUrl;

  /// Radius of the [CircleAvatar].
  final double radius;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final initials = name.isNotEmpty ? name[0].toUpperCase() : '?';

    if (avatarUrl != null) {
      return CircleAvatar(
        radius: radius,
        backgroundImage: CachedNetworkImageProvider(avatarUrl!),
        backgroundColor: theme.colorScheme.surfaceContainerHighest,
      );
    }

    return CircleAvatar(
      radius: radius,
      backgroundColor: theme.colorScheme.primary.withAlpha(51),
      child: Text(
        initials,
        style: TextStyle(
          fontSize: radius * 0.7,
          fontWeight: FontWeight.bold,
          color: theme.colorScheme.primary,
        ),
      ),
    );
  }
}
