<?php
/**
 * Utility functions for CampaignInfo block.
 *
 * @package AmbassadorHub\Fundraisers\Blocks\CampaignInfo
 */

namespace AmbassadorHub\Fundraisers\Blocks\CampaignInfo;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Truncate HTML content to a given number of characters, preserving tags.
 *
 * @param string $html
 * @param int    $limit
 * @return string
 */
function truncate_html( string $html, int $limit ): string {
	if ( mb_strlen( wp_strip_all_tags( $html ) ) <= $limit ) {
		return $html;
	}
	$text      = wp_strip_all_tags( $html );
	$truncated = mb_substr( $text, 0, $limit );
	// Try to avoid cutting in the middle of a word
	$truncated = preg_replace( '/\s+\S*$/u', '', $truncated );
	return esc_html( $truncated ) . '…';
}
