<?php
/**
 * Reusable inline HTML fragments for plugin emails.
 *
 * @package WP_PowerSuite\Email
 * @since   1.0.0
 */

namespace WP_PowerSuite\Email;

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

/**
 * Email HTML building blocks — all inline styles, no external CSS.
 */
final class EmailComponents {

	/**
	 * Primary CTA button.
	 *
	 * @param array{color?: string} $opts
	 */
	public static function button( string $url, string $label, array $opts = [] ): string {
		$color = EmailDesign::sanitizeColor( (string) ( $opts['color'] ?? EmailDesign::ACCENT_DEFAULT ), EmailDesign::ACCENT_DEFAULT );
		$url   = esc_url( $url );
		$label = esc_html( $label );

		return '<table role="presentation" cellspacing="0" cellpadding="0" style="margin:16px 0;"><tr><td align="center" style="border-radius:' . EmailDesign::RADIUS_BTN . ';background-color:' . esc_attr( $color ) . ';">'
			. '<a class="wpps-email-btn" href="' . $url . '" style="display:inline-block;padding:11px 22px;font-family:' . EmailDesign::FONT_STACK . ';font-size:' . EmailDesign::FONT_BUTTON . ';font-weight:600;line-height:1.4;color:#ffffff !important;text-decoration:none;border-radius:' . EmailDesign::RADIUS_BTN . ';">'
			. $label . '</a></td></tr></table>';
	}

	/**
	 * Header logo scaled to fit within bounds without stretching.
	 *
	 * @param array{
	 *   max_width?: int,
	 *   max_height?: int,
	 *   margin?: string,
	 *   centered?: bool,
	 * } $opts
	 */
	public static function logo( string $url, string $alt = '', array $opts = [] ): string {
		$url = trim( $url );
		if ( $url === '' ) {
			return '';
		}

		$max_w    = max( 1, (int) ( $opts['max_width'] ?? EmailDesign::LOGO_MAX_WIDTH ) );
		$max_h    = max( 1, (int) ( $opts['max_height'] ?? EmailDesign::LOGO_MAX_HEIGHT ) );
		$margin   = (string) ( $opts['margin'] ?? '0 0 12px' );
		$centered = ! empty( $opts['centered'] );
		$dims     = self::scaledLogoDimensions( $url, $max_w, $max_h );

		$style = 'display:block;border:0;outline:none;text-decoration:none;-ms-interpolation-mode:bicubic;'
			. 'max-width:' . $max_w . 'px;max-height:' . $max_h . 'px;';

		$attrs = '';
		if ( $dims['height'] > 0 ) {
			$style .= 'width:' . $dims['width'] . 'px;height:' . $dims['height'] . 'px;';
			$attrs   = ' width="' . $dims['width'] . '" height="' . $dims['height'] . '"';
		} else {
			$style .= 'width:auto;height:auto;';
		}

		$img = '<img src="' . esc_url( $url ) . '" alt="' . esc_attr( $alt ) . '"' . $attrs
			. ' style="' . esc_attr( $style ) . '" />';

		$p_style = 'margin:' . esc_attr( $margin ) . ';';
		if ( $centered ) {
			$p_style .= 'text-align:center;';
			$img      = str_replace( 'display:block;', 'display:inline-block;', $img );
		}

		return '<p style="' . $p_style . '">' . $img . '</p>';
	}

	/**
	 * @return array{width: int, height: int}
	 */
	private static function scaledLogoDimensions( string $url, int $max_w, int $max_h ): array {
		$natural = self::resolveImageSize( $url );
		if ( $natural === null ) {
			return [ 'width' => 0, 'height' => 0 ];
		}

		[ $natural_w, $natural_h ] = $natural;
		if ( $natural_w <= 0 || $natural_h <= 0 ) {
			return [ 'width' => 0, 'height' => 0 ];
		}

		$scale = min( $max_w / $natural_w, $max_h / $natural_h, 1.0 );

		return [
			'width'  => max( 1, (int) round( $natural_w * $scale ) ),
			'height' => max( 1, (int) round( $natural_h * $scale ) ),
		];
	}

	/**
	 * @return array{0: int, 1: int}|null
	 */
	private static function resolveImageSize( string $url ): ?array {
		if ( function_exists( 'attachment_url_to_postid' ) ) {
			$attachment_id = attachment_url_to_postid( $url );
			if ( $attachment_id ) {
				$metadata = wp_get_attachment_metadata( $attachment_id );
				if ( is_array( $metadata ) && ! empty( $metadata['width'] ) && ! empty( $metadata['height'] ) ) {
					return [ (int) $metadata['width'], (int) $metadata['height'] ];
				}

				$src = wp_get_attachment_image_src( $attachment_id, 'full' );
				if ( is_array( $src ) && ! empty( $src[1] ) && ! empty( $src[2] ) ) {
					return [ (int) $src[1], (int) $src[2] ];
				}
			}
		}

		if ( function_exists( 'wp_getimagesize' ) ) {
			$local_path = self::urlToLocalPath( $url );
			if ( $local_path !== null ) {
				$size = wp_getimagesize( $local_path );
				if ( is_array( $size ) && ! empty( $size[0] ) && ! empty( $size[1] ) ) {
					return [ (int) $size[0], (int) $size[1] ];
				}
			}
		}

		return null;
	}

	/**
	 * Map a site URL to a readable local filesystem path when possible.
	 */
	private static function urlToLocalPath( string $url ): ?string {
		$uploads = wp_get_upload_dir();
		if ( ! empty( $uploads['baseurl'] ) && ! empty( $uploads['basedir'] ) ) {
			$baseurl = trailingslashit( (string) $uploads['baseurl'] );
			if ( str_starts_with( $url, $baseurl ) ) {
				$relative = substr( $url, strlen( $baseurl ) );
				$path     = wp_normalize_path( $uploads['basedir'] . '/' . ltrim( $relative, '/' ) );
				if ( is_readable( $path ) ) {
					return $path;
				}
			}
		}

		$home = home_url( '/' );
		if ( str_starts_with( $url, $home ) ) {
			$relative = ltrim( substr( $url, strlen( untrailingslashit( $home ) ) ), '/' );
			$path     = wp_normalize_path( ABSPATH . $relative );
			if ( is_readable( $path ) ) {
				return $path;
			}
		}

		return null;
	}

	public static function paragraph( string $text, array $opts = [] ): string {
		$margin = $opts['margin'] ?? '0 0 14px';
		$size   = $opts['size'] ?? EmailDesign::FONT_BODY;
		$color  = esc_attr( (string) ( $opts['color'] ?? EmailDesign::TEXT_DEFAULT ) );
		$muted  = ! empty( $opts['muted'] );

		if ( $muted ) {
			$color = esc_attr( EmailDesign::TEXT_MUTED_DEFAULT );
		}

		return '<p class="wpps-email-body-text" style="margin:' . esc_attr( $margin ) . ';font-family:' . EmailDesign::FONT_STACK . ';font-size:' . esc_attr( $size ) . ';line-height:1.55;color:' . $color . ';">' . $text . '</p>';
	}

	/**
	 * @param array<int, array{label: string, value: string}> $rows
	 */
	public static function detailsBox( string $title, array $rows, array $opts = [] ): string {
		$border = esc_attr( (string) ( $opts['border_color'] ?? EmailDesign::TEXT_DEFAULT ) );
		$bg     = esc_attr( (string) ( $opts['bg'] ?? EmailDesign::HIGHLIGHT_BG ) );

		$rows_html = '';
		foreach ( $rows as $row ) {
			$label = isset( $row['label'] ) ? (string) $row['label'] : '';
			$value = isset( $row['value'] ) ? (string) $row['value'] : '';
			if ( $label === '' || $value === '' ) {
				continue;
			}
			$rows_html .= self::detailRow( $label, $value );
		}

		if ( $rows_html === '' ) {
			return '';
		}

		return '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="width:100%;margin:16px 0;border-collapse:collapse;">'
			. '<tr><td style="padding:14px 16px;background-color:' . $bg . ';border-left:3px solid ' . $border . ';border-radius:0 ' . EmailDesign::RADIUS . ' ' . EmailDesign::RADIUS . ' 0;">'
			. '<p style="margin:0 0 10px;font-family:' . EmailDesign::FONT_STACK . ';font-size:' . EmailDesign::FONT_SUBHEAD . ';font-weight:600;color:' . esc_attr( EmailDesign::TEXT_DEFAULT ) . ';text-transform:uppercase;letter-spacing:0.04em;">' . esc_html( $title ) . '</p>'
			. $rows_html
			. '</td></tr></table>';
	}

	public static function detailRow( string $label, string $value, bool $monospace = false ): string {
		$value_style = 'font-size:' . EmailDesign::FONT_BODY . ';line-height:1.45;color:' . EmailDesign::TEXT_DEFAULT . ';word-break:break-word;';
		if ( $monospace ) {
			$value_style .= 'font-family:' . EmailDesign::MONO_STACK . ';font-size:12px;';
		}

		return '<p style="margin:4px 0;font-family:' . EmailDesign::FONT_STACK . ';font-size:' . EmailDesign::FONT_BODY . ';line-height:1.45;color:' . EmailDesign::TEXT_MUTED_DEFAULT . ';">'
			. '<strong style="color:' . EmailDesign::TEXT_DEFAULT . ';font-weight:600;">' . esc_html( $label ) . '</strong> '
			. '<span style="' . esc_attr( $value_style ) . '">' . esc_html( $value ) . '</span></p>';
	}

	/**
	 * Raw detail row HTML (pre-escaped value allowed via trusted HTML in value).
	 */
	public static function detailRowHtml( string $label, string $value_html ): string {
		return '<p style="margin:4px 0;font-family:' . EmailDesign::FONT_STACK . ';font-size:' . EmailDesign::FONT_BODY . ';line-height:1.45;color:' . EmailDesign::TEXT_MUTED_DEFAULT . ';">'
			. '<strong style="color:' . EmailDesign::TEXT_DEFAULT . ';font-weight:600;">' . esc_html( $label ) . '</strong> '
			. $value_html . '</p>';
	}

	/**
	 * @param 'warning'|'success'|'info'|'error' $type
	 */
	public static function notice( string $html, string $type = 'warning' ): string {
		$palettes = [
			'warning' => [ 'bg' => '#fffbeb', 'border' => '#fcd34d', 'text' => '#92400e' ],
			'success' => [ 'bg' => '#f0fdf4', 'border' => '#86efac', 'text' => '#166534' ],
			'info'    => [ 'bg' => '#eff6ff', 'border' => '#93c5fd', 'text' => '#1e40af' ],
			'error'   => [ 'bg' => '#fef2f2', 'border' => '#fca5a5', 'text' => '#991b1b' ],
		];
		$p = $palettes[ $type ] ?? $palettes['warning'];

		return '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="width:100%;margin:16px 0;"><tr><td style="padding:12px 14px;background-color:' . esc_attr( $p['bg'] ) . ';border:1px solid ' . esc_attr( $p['border'] ) . ';border-radius:' . EmailDesign::RADIUS . ';">'
			. '<div style="margin:0;font-family:' . EmailDesign::FONT_STACK . ';font-size:' . EmailDesign::FONT_BODY . ';line-height:1.55;color:' . esc_attr( $p['text'] ) . ';">' . $html . '</div>'
			. '</td></tr></table>';
	}

	public static function codeBlock( string $code, string $label = '', ?string $note = null ): string {
		$label_html = $label !== ''
			? '<p style="margin:0 0 8px;font-family:' . EmailDesign::FONT_STACK . ';font-size:' . EmailDesign::FONT_SMALL . ';font-weight:600;color:' . EmailDesign::TEXT_MUTED_DEFAULT . ';text-transform:uppercase;letter-spacing:0.05em;">' . esc_html( $label ) . '</p>'
			: '';
		$note_html = $note !== null && $note !== ''
			? '<p style="margin:10px 0 0;font-family:' . EmailDesign::FONT_STACK . ';font-size:' . EmailDesign::FONT_SMALL . ';color:' . EmailDesign::TEXT_MUTED_DEFAULT . ';">' . esc_html( $note ) . '</p>'
			: '';

		return '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="width:100%;margin:16px 0;"><tr><td style="padding:18px 16px;background-color:' . EmailDesign::HIGHLIGHT_BG . ';border:1px dashed ' . EmailDesign::BORDER_DEFAULT . ';border-radius:' . EmailDesign::RADIUS . ';text-align:center;">'
			. $label_html
			. '<p class="wpps-email-code" style="margin:0;font-family:' . EmailDesign::MONO_STACK . ';font-size:' . EmailDesign::FONT_CODE . ';font-weight:700;color:' . EmailDesign::TEXT_DEFAULT . ';letter-spacing:5px;line-height:1.3;word-break:break-all;">' . esc_html( $code ) . '</p>'
			. $note_html
			. '</td></tr></table>';
	}

	public static function highlightBlock( string $label, string $text ): string {
		$label_html = $label !== ''
			? '<p style="margin:0 0 6px;font-family:' . EmailDesign::FONT_STACK . ';font-size:' . EmailDesign::FONT_SMALL . ';font-weight:600;color:' . EmailDesign::TEXT_MUTED_DEFAULT . ';text-transform:uppercase;letter-spacing:0.05em;">' . esc_html( $label ) . '</p>'
			: '';

		return '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="width:100%;margin:16px 0;"><tr><td style="padding:14px 16px;background-color:' . EmailDesign::HIGHLIGHT_BG . ';border:1px solid ' . EmailDesign::BORDER_DEFAULT . ';border-radius:' . EmailDesign::RADIUS . ';text-align:center;">'
			. $label_html
			. '<p style="margin:0;font-family:' . EmailDesign::FONT_STACK . ';font-size:15px;font-weight:700;color:' . EmailDesign::TEXT_DEFAULT . ';line-height:1.4;">' . esc_html( $text ) . '</p>'
			. '</td></tr></table>';
	}

	public static function statusBanner( string $label, bool $success = true ): string {
		$bg    = $success ? '#dcfce7' : '#fee2e2';
		$color = $success ? '#166534' : '#991b1b';
		$icon  = $success ? '&#10003;' : '&#10007;';

		return '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="width:100%;margin:0 0 16px;"><tr><td style="padding:12px 14px;background-color:' . esc_attr( $bg ) . ';border-radius:' . EmailDesign::RADIUS . ';text-align:center;">'
			. '<p style="margin:0;font-family:' . EmailDesign::FONT_STACK . ';font-size:15px;font-weight:600;color:' . esc_attr( $color ) . ';line-height:1.4;">'
			. '<span style="margin-right:6px;">' . $icon . '</span>' . esc_html( $label ) . '</p>'
			. '</td></tr></table>';
	}

	/**
	 * Two-column key/value table (stacks on narrow clients).
	 *
	 * @param array<int, array{label: string, value: string, value_html?: string}> $rows
	 */
	public static function keyValueTable( array $rows ): string {
		$rows_html = '';
		foreach ( $rows as $row ) {
			$label = isset( $row['label'] ) ? (string) $row['label'] : '';
			if ( $label === '' ) {
				continue;
			}
			$value_cell = isset( $row['value_html'] )
				? (string) $row['value_html']
				: esc_html( (string) ( $row['value'] ?? '' ) );

			$rows_html .= '<tr>'
				. '<td style="padding:7px 0;border-bottom:1px solid ' . EmailDesign::BORDER_DEFAULT . ';font-family:' . EmailDesign::FONT_STACK . ';font-size:' . EmailDesign::FONT_SUBHEAD . ';color:' . EmailDesign::TEXT_MUTED_DEFAULT . ';text-transform:uppercase;letter-spacing:0.04em;vertical-align:top;">' . esc_html( $label ) . '</td>'
				. '<td style="padding:7px 0;border-bottom:1px solid ' . EmailDesign::BORDER_DEFAULT . ';text-align:right;font-family:' . EmailDesign::FONT_STACK . ';font-size:' . EmailDesign::FONT_BODY . ';color:' . EmailDesign::TEXT_DEFAULT . ';font-weight:500;word-break:break-word;vertical-align:top;">' . $value_cell . '</td>'
				. '</tr>';
		}

		if ( $rows_html === '' ) {
			return '';
		}

		return '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="width:100%;margin:12px 0;border-collapse:collapse;">' . $rows_html . '</table>';
	}

	public static function linkFallback( string $url, string $intro = '' ): string {
		if ( $intro === '' ) {
			$intro = __( 'If the button does not work, copy and paste this URL into your browser:', 'wp-powersuite' );
		}

		return self::paragraph( esc_html( $intro ), [ 'size' => EmailDesign::FONT_SMALL, 'muted' => true, 'margin' => '0 0 6px' ] )
			. '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="width:100%;margin:0 0 14px;"><tr><td style="padding:10px 12px;background-color:' . EmailDesign::HIGHLIGHT_BG . ';border-left:3px solid ' . EmailDesign::HIGHLIGHT_BORDER . ';border-radius:0 6px 6px 0;">'
			. '<p style="margin:0;font-family:' . EmailDesign::MONO_STACK . ';font-size:12px;line-height:1.45;color:' . EmailDesign::TEXT_MUTED_DEFAULT . ';word-break:break-all;">' . esc_html( $url ) . '</p>'
			. '</td></tr></table>';
	}

	public static function divider(): string {
		return '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="width:100%;margin:18px 0;"><tr><td style="border-top:1px solid ' . EmailDesign::BORDER_DEFAULT . ';font-size:0;line-height:0;">&nbsp;</td></tr></table>';
	}

	public static function badge( string $text, array $opts = [] ): string {
		$color = esc_attr( (string) ( $opts['color'] ?? '#92400e' ) );
		$bg    = esc_attr( (string) ( $opts['bg'] ?? '#fffbeb' ) );
		$border = esc_attr( (string) ( $opts['border'] ?? '#fcd34d' ) );

		return '<span style="display:inline-block;margin:0 0 10px;padding:3px 8px;font-family:' . EmailDesign::FONT_STACK . ';font-size:11px;font-weight:600;letter-spacing:0.04em;text-transform:uppercase;color:' . $color . ';background:' . $bg . ';border:1px solid ' . $border . ';border-radius:4px;">' . esc_html( $text ) . '</span>';
	}

	/**
	 * Preformatted log / error excerpt.
	 */
	public static function logBlock( string $title, string $excerpt ): string {
		return '<p style="margin:16px 0 6px;font-family:' . EmailDesign::FONT_STACK . ';font-size:' . EmailDesign::FONT_SUBHEAD . ';font-weight:600;color:#991b1b;text-transform:uppercase;letter-spacing:0.04em;">' . esc_html( $title ) . '</p>'
			. '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="width:100%;margin:0 0 14px;"><tr><td style="padding:12px 14px;background-color:#fef2f2;border-left:3px solid #fca5a5;border-radius:0 ' . EmailDesign::RADIUS . ' ' . EmailDesign::RADIUS . ' 0;">'
			. '<pre style="margin:0;font-family:' . EmailDesign::MONO_STACK . ';font-size:12px;line-height:1.55;color:#7f1d1d;white-space:pre-wrap;word-break:break-word;">' . esc_html( $excerpt ) . '</pre>'
			. '</td></tr></table>';
	}

	/**
	 * Form submission field row.
	 */
	public static function formFieldRow( string $label, string $value_html ): string {
		return '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="width:100%;margin:0 0 8px;border-collapse:collapse;"><tr>'
			. '<td style="padding:10px 0;border-bottom:1px solid ' . EmailDesign::BORDER_DEFAULT . ';">'
			. '<p style="margin:0 0 4px;font-family:' . EmailDesign::FONT_STACK . ';font-size:' . EmailDesign::FONT_SUBHEAD . ';font-weight:600;color:' . EmailDesign::TEXT_DEFAULT . ';">' . esc_html( $label ) . '</p>'
			. '<div style="font-family:' . EmailDesign::FONT_STACK . ';font-size:' . EmailDesign::FONT_BODY . ';line-height:1.5;color:' . EmailDesign::TEXT_MUTED_DEFAULT . ';word-break:break-word;">' . $value_html . '</div>'
			. '</td></tr></table>';
	}
}
