<?php
defined( 'ABSPATH' ) || exit;

/**
 * Editorial word-count helpers shared by admin UI and runtime surfaces.
 */
final class Costudio_Content_Word_Count {

	private function __construct() {
	}

	public static function count_editorial_words( string $content ): int {
		$clean = self::to_editorial_text( $content );
		if ( '' === $clean ) {
			return 0;
		}

		return count( preg_split( '/\s+/u', $clean ) );
	}

	public static function format_editorial_words( string $content ): string {
		return number_format_i18n( self::count_editorial_words( $content ) );
	}

	private static function to_editorial_text( string $content ): string {
		$content = self::strip_json_ld( $content );
		$content = preg_replace( '/<!--\s*\/?wp:[\s\S]*?-->/u', ' ', $content );
		$content = preg_replace( '/\[IMAGE_LIST\][\s\S]*?\[\/IMAGE_LIST\]/iu', ' ', $content );
		$content = preg_replace( '/^\s*\[IMG:[^\]]+\]\s*$/imu', ' ', $content );
		$content = preg_replace( '/^(Título|Title|Meta Description|Descrição Meta|Meta Descrição|Meta-descrição|Slug|URL Slug|URL):.*$/imu', ' ', $content );
		$content = wp_strip_all_tags( $content );
		$content = html_entity_decode( $content, ENT_QUOTES, get_bloginfo( 'charset' ) ?: 'UTF-8' );
		$content = preg_replace( '/\{\{ref:[a-z0-9\-_]+\}\}/iu', ' ', $content );
		$content = preg_replace( '/[\*\_\#\[\]\(\)\>\`\~\|]/u', ' ', $content );
		$content = preg_replace( '/\s+/u', ' ', trim( $content ) );

		return is_string( $content ) ? $content : '';
	}

	private static function strip_json_ld( string $content ): string {
		$content = preg_replace( '/<script\b[^>]*type=["\']application\/ld\+json["\'][^>]*>[\s\S]*?<\/script>/iu', ' ', $content );
		$content = preg_replace( '/<!--\s*wp:html\s*-->\s*<script\b[^>]*type=["\']application\/ld\+json["\'][^>]*>[\s\S]*?<\/script>\s*<!--\s*\/wp:html\s*-->/iu', ' ', $content );

		return is_string( $content ) ? $content : '';
	}
}
