<?php
/**
 * User Bio Block Template
 *
 * @since 4.2.0
 *
 * @var WP_User $user User object
 * @var array $attributes Block attributes
 * @var string $content Block content
 * @var WP_Block $block Block instance
 */

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( ! $user ) {
    return;
}

// Extract attributes with defaults
$character_limit = isset( $attributes['characterLimit'] ) ? intval( $attributes['characterLimit'] ) : 150;
$show_read_more = isset( $attributes['showReadMore'] ) ? $attributes['showReadMore'] : true;
$read_more_text = isset( $attributes['readMoreText'] ) && ! empty( $attributes['readMoreText'] ) ? $attributes['readMoreText'] : __( 'Read More', 'wpuf-pro' );

// Get bio content from user description
$bio_content = $user->description;

// Clean up content
$bio_content = trim( $bio_content );

// If no bio content, don't render anything
if ( empty( $bio_content ) ) {
    return;
}

// Process character limits
$needs_read_more = false;
$truncated_content = $bio_content;

if ( $show_read_more && $character_limit > 0 && strlen( $bio_content ) > $character_limit ) {
    $needs_read_more = true;
    $truncated_content = substr( $bio_content, 0, $character_limit );
}

// Generate unique ID for this block instance
$block_id = 'wpuf-bio-' . wp_generate_uuid4();

// Get block wrapper attributes (includes styling from block editor)
$wrapper_attributes = wpuf_get_block_wrapper_attributes( $attributes, 'bio', [
    'class' => 'wpuf-user-bio',
    'data-user-id' => $user->ID,
    'id' => $block_id,
] );

?>
<div <?php echo $wrapper_attributes; ?>>
    <?php if ( $needs_read_more ) : ?>
        <!-- Truncated content (initially visible) -->
        <div class="wpuf-bio-truncated" data-bio-state="truncated">
            <p class="wpuf-bio-text"><?php echo esc_html( $truncated_content ); ?></p>
        </div>

        <!-- Full content (initially hidden) -->
        <div class="wpuf-bio-full" data-bio-state="full" style="display: none;">
            <p class="wpuf-bio-text"><?php echo esc_html( $bio_content ); ?></p>
        </div>

        <!-- Read More Toggle Link -->
        <a href="#"
            class="wpuf-read-more-toggle"
            data-target="<?php echo esc_attr( $block_id ); ?>"
            data-read-more-text="<?php echo esc_attr( $read_more_text ); ?>"
            data-show-less-text="<?php echo esc_attr__( 'Show Less', 'wpuf-pro' ); ?>"
        >
            <?php echo esc_html( $read_more_text ); ?>
        </a>
    <?php else : ?>
        <!-- Display content without read more functionality -->
        <p class="wpuf-bio-text"><?php echo esc_html( $bio_content ); ?></p>
    <?php endif; ?>
</div>

<?php
// Enqueue frontend JavaScript for read more functionality if needed
if ( $needs_read_more ) {
    wp_enqueue_script(
        'wpuf-user-bio-frontend',
        WPUF_UD_ASSET_URI . '/js/user-bio-frontend.js',
        [],
        WPUF_UD_VERSION,
        true
    );
}
?>
