<?php
/**
 * Reusable Avatar Component
 *
 * Provides a consistent avatar display across all block templates.
 *
 * @since 4.2.0
 */

// Ensure we have the required data
if (!isset($user) || !is_object($user) || !isset($user->ID)) {
    return;
}

// Get component options
$options = $options ?? [];
$defaults = [
    'size' => 'medium',
    'shape' => 'circle',
    'class' => '',
    'show_link' => false,
    'link_target' => '_self',
];

$options = wp_parse_args($options, $defaults);

// Map size to pixel values
$size_map = [
    'small' => 50,
    'medium' => 96,
    'large' => 150,
    'xlarge' => 200,
];

$pixel_size = $size_map[$options['size']] ?? 96;

// Get avatar HTML
$avatar_html = wpuf_get_user_avatar($user, [
    'size' => $pixel_size,
    'shape' => $options['shape'],
    'class' => $options['class'],
]);

// Build wrapper classes
$wrapper_classes = ['wpuf-avatar-component'];
if ($options['shape'] === 'square') {
    $wrapper_classes[] = 'wpuf-avatar-square';
} else {
    $wrapper_classes[] = 'wpuf-avatar-circle';
}
$wrapper_classes[] = 'wpuf-avatar-' . $options['size'];

// Build the component HTML
if ($options['show_link']) {
    $author_url = get_author_posts_url($user->ID);
    $target_attr = $options['link_target'] === '_blank' ? ' target="_blank" rel="noopener"' : '';

    printf(
        '<div class="%s">
            <a href="%s"%s>%s</a>
        </div>',
        esc_attr(implode(' ', $wrapper_classes)),
        esc_url($author_url),
        $target_attr,
        $avatar_html
    );
} else {
    printf(
        '<div class="%s">%s</div>',
        esc_attr(implode(' ', $wrapper_classes)),
        $avatar_html
    );
}
