<?php
/**
 * Admin UI helpers for Email Delivery.
 *
 * @package EmailSmtp
 */

namespace EmailSmtp\Includes;

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

final class AdminUi {

	/**
	 * @param array<string, mixed> $settings
	 * @return array{key: string, label: string, tone: string, detail: string}
	 */
	public static function health_summary( ?ProviderInterface $active, array $settings ): array {
		$connections = ConnectionStore::all( $settings );
		$default_id  = sanitize_key( (string) ( $settings['default_connection_id'] ?? '' ) );
		$default     = $default_id !== '' && isset( $connections[ $default_id ] ) ? $connections[ $default_id ] : null;

		if ( ! empty( $settings['simulation_mode'] ) && (string) $settings['simulation_mode'] !== '0' ) {
			return [
				'key'    => 'simulation',
				'label'  => __( 'Email Simulation on', 'wp-powersuite' ),
				'tone'   => 'warning',
				'detail' => __( 'No email is being delivered. Attempts are still logged when Email Logs is enabled. Turn this off before going live.', 'wp-powersuite' ),
			];
		}

		if ( $connections === [] || ! is_array( $default ) ) {
			return [
				'key'    => 'not_configured',
				'label'  => __( 'Not set up', 'wp-powersuite' ),
				'tone'   => 'warning',
				'detail' => __( 'Add a connection on the Settings tab to start sending email.', 'wp-powersuite' ),
			];
		}

		$provider_id = sanitize_key( (string) ( $default['provider'] ?? 'wordpress' ) );
		$from        = trim( (string) ( $default['from_email'] ?? '' ) );
		$active      = $active ?: ProviderRegistry::get( $provider_id );
		$status      = $active
			? $active->get_connection_status( SettingsSchema::provider_bag( $default, $provider_id ) )
			: 'not_configured';

		if ( $provider_id === 'wordpress' ) {
			return [
				'key'    => 'wordpress',
				'label'  => __( 'Using server mail', 'wp-powersuite' ),
				'tone'   => 'warning',
				'detail' => __( 'Default WordPress mail often lands in spam. Add SMTP or an API connection for production.', 'wp-powersuite' ),
			];
		}

		if ( in_array( $status, [ 'not_configured', 'incomplete' ], true ) ) {
			return [
				'key'    => $status,
				'label'  => __( 'Setup incomplete', 'wp-powersuite' ),
				'tone'   => 'warning',
				'detail' => sprintf(
					/* translators: %s: connection name */
					__( 'Finish credentials for “%s”, then send a test email.', 'wp-powersuite' ),
					(string) ( $default['name'] ?? $provider_id )
				),
			];
		}

		if ( in_array( $status, [ 'failed', 'expired' ], true ) ) {
			return [
				'key'    => $status,
				'label'  => $status === 'expired' ? __( 'Authentication expired', 'wp-powersuite' ) : __( 'Connection failed', 'wp-powersuite' ),
				'tone'   => 'danger',
				'detail' => __( 'Reconnect or fix credentials, then send a test email.', 'wp-powersuite' ),
			];
		}

		if ( $from === '' || ! is_email( $from ) ) {
			return [
				'key'    => 'missing_from',
				'label'  => __( 'Sender missing', 'wp-powersuite' ),
				'tone'   => 'warning',
				'detail' => __( 'Each connection needs a valid From email.', 'wp-powersuite' ),
			];
		}

		return [
			'key'    => 'ready',
			'label'  => __( 'Ready to send', 'wp-powersuite' ),
			'tone'   => 'success',
			'detail' => sprintf(
				/* translators: 1: connection name, 2: from email */
				__( 'Ready — mail routes by From email. Primary: %1$s (%2$s)', 'wp-powersuite' ),
				(string) ( $default['name'] ?? '' ),
				$from
			),
		];
	}

	/**
	 * @param array<string, mixed> $settings
	 * @param array<string, mixed> $diagnostics
	 * @return list<array{id: string, label: string, done: bool, hint: string}>
	 */
	public static function checklist( ?ProviderInterface $active, array $settings, array $diagnostics, bool $email_logs_enabled ): array {
		unset( $active );
		$connections = ConnectionStore::all( $settings );
		$default_id  = sanitize_key( (string) ( $settings['default_connection_id'] ?? '' ) );
		$default     = $connections[ $default_id ] ?? null;
		$provider_id = is_array( $default ) ? sanitize_key( (string) ( $default['provider'] ?? '' ) ) : '';
		$from_ok     = is_array( $default ) && is_email( (string) ( $default['from_email'] ?? '' ) );
		$ready       = false;
		if ( is_array( $default ) && $provider_id !== '' && $provider_id !== 'wordpress' ) {
			$p = ProviderRegistry::get( $provider_id );
			$ready = $p && $p->get_connection_status( SettingsSchema::provider_bag( $default, $provider_id ) ) === 'connected';
		}

		$items = [
			[
				'id'    => 'connection',
				'label' => __( 'Add a connection', 'wp-powersuite' ),
				'done'  => $connections !== [],
				'hint'  => __( 'Pick a provider and save credentials.', 'wp-powersuite' ),
			],
			[
				'id'    => 'credentials',
				'label' => __( 'Credentials complete', 'wp-powersuite' ),
				'done'  => (bool) $ready,
				'hint'  => __( 'API key, SMTP, or OAuth connected.', 'wp-powersuite' ),
			],
			[
				'id'    => 'sender',
				'label' => __( 'From email set', 'wp-powersuite' ),
				'done'  => $from_ok,
				'hint'  => __( 'Use an address on your verified domain.', 'wp-powersuite' ),
			],
			[
				'id'    => 'test',
				'label' => __( 'Test email sent', 'wp-powersuite' ),
				'done'  => ! empty( $diagnostics['last_success_at'] ),
				'hint'  => __( 'Confirm the default connection works.', 'wp-powersuite' ),
			],
			[
				'id'    => 'logs',
				'label' => __( 'Email Logs (optional)', 'wp-powersuite' ),
				'done'  => $email_logs_enabled,
				'hint'  => __( 'Track accepts, failures, and webhooks.', 'wp-powersuite' ),
			],
		];

		if ( $connections !== [] ) {
			$items[] = [
				'id'    => 'dns',
				'label' => __( 'Domain DNS (SPF / DMARC)', 'wp-powersuite' ),
				'done'  => self::dns_checklist_done( $settings ),
				'hint'  => __( 'Publish SPF and DMARC for your From domain.', 'wp-powersuite' ),
			];
		}

		return $items;
	}

	/**
	 * @param array<string, mixed> $settings
	 */
	private static function dns_checklist_done( array $settings ): bool {
		// Cache only — never trigger live DNS during page paint.
		$report = DomainHealth::report_for_settings( $settings, false, false );
		if ( empty( $report['show'] ) || ! empty( $report['pending'] ) ) {
			return false;
		}
		$spf   = false;
		$dmarc = false;
		foreach ( $report['checks'] as $check ) {
			if ( ( $check['id'] ?? '' ) === 'spf' && ( $check['tone'] ?? '' ) === 'success' ) {
				$spf = true;
			}
			if ( ( $check['id'] ?? '' ) === 'dmarc' && ( $check['tone'] ?? '' ) === 'success' ) {
				$dmarc = true;
			}
		}

		return $spf && $dmarc;
	}

	/**
	 * @param array{key?: string} $health
	 */
	public static function normalize_tab( string $tab, array $health ): string {
		$legacy = [
			'delivery'     => 'settings',
			'setup'        => 'settings',
			'sender'       => 'settings',
			'provider'     => 'settings',
			'configure'    => 'settings',
			'logging'      => 'overview',
			'reliability'  => 'settings',
			'advanced'     => 'settings',
			'diagnostics'  => 'settings',
		];
		if ( isset( $legacy[ $tab ] ) ) {
			$tab = $legacy[ $tab ];
		}
		if ( ! in_array( $tab, [ 'settings', 'overview', 'test' ], true ) ) {
			$tab = ( $health['key'] ?? '' ) === 'ready' ? 'overview' : 'settings';
		}

		return $tab;
	}
}
