import { __, _n, sprintf } from '@wordpress/i18n';
import type { Counts } from '../../shared/api/types/status';
import { formatNumber } from '../../shared/lib/numbers';

function otherProblemsText( counts: Counts ): string {
	const { blocked, moved } = counts;

	if ( blocked > 0 && moved > 0 ) {
		return sprintf(
			/* translators: 1: number of links that could not be checked, 2: number of links that moved */
			_n(
				'%1$s more could not be checked and %2$s has moved.',
				'%1$s more could not be checked and %2$s have moved.',
				moved,
				'aiplaz-link-checkup'
			),
			formatNumber( blocked ),
			formatNumber( moved )
		);
	}

	if ( blocked > 0 ) {
		return sprintf(
			/* translators: %s: number of links */
			__( '%s more could not be checked.', 'aiplaz-link-checkup' ),
			formatNumber( blocked )
		);
	}

	if ( moved > 0 ) {
		return sprintf(
			/* translators: %s: number of links */
			_n(
				'%s has moved.',
				'%s have moved.',
				moved,
				'aiplaz-link-checkup'
			),
			formatNumber( moved )
		);
	}

	return '';
}

function retryingText( retrying: number ): string {
	if ( retrying === 0 ) {
		return '';
	}

	return sprintf(
		/* translators: %s: number of links */
		_n(
			'%s link is being checked again before it is reported.',
			'%s links are being checked again before they are reported.',
			retrying,
			'aiplaz-link-checkup'
		),
		formatNumber( retrying )
	);
}

export function healthLede( counts: Counts ): string {
	const allLinks = formatNumber( counts.total );
	const otherProblems =
		`${ otherProblemsText( counts ) } ${ retryingText( counts.retrying ) }`.trim();

	if ( counts.broken > 0 ) {
		const outOf = sprintf(
			/* translators: %s: number of links on the site */
			__( 'Out of %s links on your site.', 'aiplaz-link-checkup' ),
			allLinks
		);

		return `${ outOf } ${ otherProblems }`.trim();
	}

	const allChecked = sprintf(
		/* translators: %s: number of links on the site */
		__( 'All %s links were checked.', 'aiplaz-link-checkup' ),
		allLinks
	);
	const verdict =
		otherProblems === ''
			? __( 'Everything works.', 'aiplaz-link-checkup' )
			: otherProblems;

	return `${ allChecked } ${ verdict }`;
}

export function healthHeadline( brokenCount: number ): string {
	if ( brokenCount === 0 ) {
		return __( 'No broken links', 'aiplaz-link-checkup' );
	}

	return sprintf(
		/* translators: %s: number of broken links */
		_n(
			'%s broken link',
			'%s broken links',
			brokenCount,
			'aiplaz-link-checkup'
		),
		formatNumber( brokenCount )
	);
}
