<?php
/**
 * What this site has been sending.
 *
 * One partial at two densities — compact on the WordPress dashboard, fuller
 * above the message log — so the two cannot come to disagree about what a
 * number means.
 *
 * @package TextTango
 *
 * @var array<string, mixed> $args {
 *     @type array<string, mixed>  $stats    From Stats::summary().
 *     @type bool                  $compact  Whether this is the dashboard widget.
 *     @type array<string, string> $tones    Status => badge tone, from the log.
 *     @type array<string, string> $windows  Days => URL, for the period selector.
 *     @type array<string, string> $links    Label => URL, for the footer.
 * }
 */

declare( strict_types=1 );

defined( 'ABSPATH' ) || exit;

use TextTango\Analytics\Chart;
use TextTango\Analytics\Stats;

$texttango_stats   = (array) ( $args['stats'] ?? array() );
$texttango_compact = ! empty( $args['compact'] );
$texttango_total   = (int) ( $texttango_stats['total'] ?? 0 );
$texttango_days    = (int) ( $texttango_stats['days'] ?? Stats::WINDOW );
$texttango_events  = (array) ( $texttango_stats['events'] ?? array() );
$texttango_status  = (array) ( $texttango_stats['statuses'] ?? array() );
$texttango_tones   = (array) ( $args['tones'] ?? array() );
$texttango_credits = (int) ( $texttango_stats['credits'] ?? 0 );
$texttango_shares  = Chart::shares( $texttango_status );

/*
 * The chart's viewBox, chosen from the surface rather than fixed. It is scaled
 * to whatever width it is given, and the axis labels scale with it — see
 * Chart::area() for why one box cannot serve both of these.
 */
$texttango_box = $texttango_compact ? Chart::WIDGET_BOX : Chart::PAGE_BOX;
?>
<div class="texttango-ui tt-analytics">

	<div class="tt-analytics-chart">
		<?php
		echo wp_kses(
			Chart::area(
				(array) ( $texttango_stats['series'] ?? array() ),
				sprintf(
					/* translators: %s: number of days. */
					__( 'Messages sent over the last %s days', 'texttango' ),
					number_format_i18n( $texttango_days )
				),
				(int) $texttango_box[0],
				(int) $texttango_box[1]
			),
			Chart::allowed_html()
		);
		?>
	</div>

	<div class="tt-analytics-section">
		<div class="tt-flex tt-flex-wrap tt-items-center tt-gap-6">
			<div class="tt-grow tt-grid <?php echo $texttango_credits > 0 ? 'tt-grid-cols-4' : 'tt-grid-cols-3'; ?> tt-gap-4">
				<div>
					<div class="tt-eyebrow"><?php esc_html_e( 'Sent', 'texttango' ); ?></div>
					<div class="tt-analytics-figure"><?php echo esc_html( number_format_i18n( $texttango_total ) ); ?></div>
				</div>
				<div>
					<div class="tt-eyebrow"><?php esc_html_e( 'Delivered', 'texttango' ); ?></div>
					<div class="tt-analytics-figure"><?php echo esc_html( number_format_i18n( (float) ( $texttango_stats['rate'] ?? 0 ) ) ); ?>%</div>
				</div>
				<div>
					<div class="tt-eyebrow"><?php esc_html_e( 'Spent', 'texttango' ); ?></div>
					<div class="tt-analytics-figure"><?php echo esc_html( number_format_i18n( (float) ( $texttango_stats['spend'] ?? 0 ), 2 ) ); ?></div>
				</div>

				<?php
				/*
				 * Credits sit beside spend rather than inside it. The message log
				 * records a money cost returned by the delivery webhook; a campaign
				 * records credits, which is recipients times segments. Adding the two
				 * would give a total in no unit at all.
				 *
				 * Shown only when a campaign has actually gone out, so a store that
				 * sends none never sees a column of zeros it has to work out.
				 */
				?>
				<?php if ( $texttango_credits > 0 ) : ?>
					<div>
						<div class="tt-eyebrow"><?php esc_html_e( 'Credits', 'texttango' ); ?></div>
						<div class="tt-analytics-figure"><?php echo esc_html( number_format_i18n( $texttango_credits ) ); ?></div>
					</div>
				<?php endif; ?>
			</div>

			<?php if ( array() !== $texttango_shares ) : ?>
				<div class="tt-flex tt-shrink-0 tt-items-center tt-gap-3">
					<?php
					echo wp_kses(
						Chart::donut( $texttango_status, $texttango_tones, __( 'Messages by status', 'texttango' ) ),
						Chart::allowed_html()
					);
					?>
					<ul class="tt-m-0 tt-list-none tt-p-0">
						<?php foreach ( $texttango_shares as $texttango_key => $texttango_share ) : ?>
							<li class="tt-m-0 tt-flex tt-items-center tt-gap-2 tt-text-xs tt-text-slate-600">
								<span class="tt-legend-dot tt-legend-dot-<?php echo esc_attr( (string) ( $texttango_tones[ $texttango_key ] ?? 'off' ) ); ?>"></span>
								<span><?php echo esc_html( (string) $texttango_key ); ?></span>
								<span class="tt-text-slate-400"><?php echo esc_html( number_format_i18n( $texttango_share ) ); ?>%</span>
							</li>
						<?php endforeach; ?>
					</ul>
				</div>
			<?php endif; ?>
		</div>

		<?php if ( 0 === $texttango_total ) : ?>
			<p class="tt-mt-3 tt-mb-0 tt-text-sm tt-text-slate-500">
				<?php
				echo esc_html(
					sprintf(
						/* translators: %s: number of days. */
						_n( 'Nothing sent in the last %s day.', 'Nothing sent in the last %s days.', $texttango_days, 'texttango' ),
						number_format_i18n( $texttango_days )
					)
				);
				?>
			</p>
		<?php endif; ?>
	</div>

	<?php if ( ! $texttango_compact && array() !== $texttango_events ) : ?>
		<div class="tt-analytics-section">
			<div class="tt-eyebrow tt-mb-3"><?php esc_html_e( 'Busiest events', 'texttango' ); ?></div>
			<?php foreach ( array_slice( $texttango_events, 0, 5, true ) as $texttango_event => $texttango_count ) : ?>
				<?php $texttango_width = $texttango_total > 0 ? min( 100, ( (int) $texttango_count / $texttango_total ) * 100 ) : 0; ?>
				<div class="tt-mb-2 tt-flex tt-items-center tt-gap-3">
					<span class="tt-w-44 tt-shrink-0 tt-truncate tt-text-xs tt-text-slate-700"><?php echo esc_html( (string) $texttango_event ); ?></span>
					<span class="tt-h-2 tt-grow tt-overflow-hidden tt-rounded-full tt-bg-slate-100">
						<span class="tt-block tt-h-2 tt-rounded-full tt-bg-brand-500" style="width: <?php echo esc_attr( (string) round( $texttango_width, 1 ) ); ?>%"></span>
					</span>
					<span class="tt-w-12 tt-shrink-0 tt-text-right tt-text-xs tt-text-slate-500"><?php echo esc_html( number_format_i18n( (int) $texttango_count ) ); ?></span>
				</div>
			<?php endforeach; ?>
		</div>
	<?php endif; ?>

	<div class="tt-analytics-section tt-flex tt-flex-wrap tt-items-center tt-justify-between tt-gap-3">
		<?php if ( array() !== (array) ( $args['windows'] ?? array() ) ) : ?>
			<nav class="tt-periods" aria-label="<?php esc_attr_e( 'Period', 'texttango' ); ?>">
				<?php foreach ( (array) $args['windows'] as $texttango_window => $texttango_url ) : ?>
					<?php $texttango_now = (int) $texttango_window === $texttango_days; ?>
					<a
						class="tt-period<?php echo $texttango_now ? ' tt-period-current' : ''; ?>"
						href="<?php echo esc_url( (string) $texttango_url ); ?>"
						<?php echo $texttango_now ? 'aria-current="page"' : ''; ?>
					>
						<?php
						echo esc_html(
							sprintf(
								/* translators: %s: number of days. */
								_n( '%s day', '%s days', (int) $texttango_window, 'texttango' ),
								number_format_i18n( (int) $texttango_window )
							)
						);
						?>
					</a>
				<?php endforeach; ?>
			</nav>
		<?php endif; ?>

		<p class="tt-m-0 tt-text-xs tt-text-slate-400">
			<?php esc_html_e( 'Sandbox messages are not counted.', 'texttango' ); ?>

			<?php
			/*
			 * Said, because the alternative is a figure that is quietly short.
			 *
			 * A campaign's cost comes back from TextTango on the poll that sees it
			 * finish, so there is a window — and, right after an upgrade, a backlog
			 * — where Spent is missing some of it. Showing the total without
			 * mentioning that is the exact bug this note exists alongside: a number
			 * that looks complete and is not.
			 */
			?>
			<?php if ( (int) ( $texttango_stats['unpriced'] ?? 0 ) > 0 ) : ?>
				<?php
				echo esc_html(
					sprintf(
						/* translators: %s: number of campaigns. */
						_n(
							'Spent does not yet include %s campaign TextTango has not priced.',
							'Spent does not yet include %s campaigns TextTango has not priced.',
							(int) $texttango_stats['unpriced'],
							'texttango'
						),
						number_format_i18n( (int) $texttango_stats['unpriced'] )
					)
				);
				?>
			<?php endif; ?>
			<?php
			/*
			 * Only once the figures are actually old. The Analytics screen computes
			 * them as it renders, so this would read "Counted 0 seconds ago" every
			 * time — a caveat about staleness on a screen that has none. It earns
			 * its place on the cached dashboard widget.
			 */
			$texttango_age = time() - (int) ( $texttango_stats['at'] ?? 0 );
			?>
			<?php if ( (int) ( $texttango_stats['at'] ?? 0 ) > 0 && $texttango_age >= MINUTE_IN_SECONDS ) : ?>
				<?php
				/*
				 * Said plainly, because these are cached. A merchant who has just
				 * sent something and does not see it here should know why rather
				 * than conclude the send failed.
				 */
				echo esc_html(
					sprintf(
						/* translators: %s: human-readable time difference, e.g. "2 mins". */
						__( 'Counted %s ago.', 'texttango' ),
						human_time_diff( (int) $texttango_stats['at'] )
					)
				);
				?>
			<?php endif; ?>
		</p>
	</div>

	<?php if ( array() !== (array) ( $args['links'] ?? array() ) ) : ?>
		<div class="tt-analytics-footer">
			<?php foreach ( (array) $args['links'] as $texttango_label => $texttango_href ) : ?>
				<a class="tt-analytics-link" href="<?php echo esc_url( (string) $texttango_href ); ?>"><?php echo esc_html( (string) $texttango_label ); ?></a>
			<?php endforeach; ?>
		</div>
	<?php endif; ?>
</div>
