<?php
/**
 * Email preview view for admin interface.
 *
 * @package Awesomemotive\Rewardswp\Views\Admin
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Views\Admin;

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

use Awesomemotive\Rewardswp\Interfaces\ViewInterface;
use Awesomemotive\Rewardswp\Models\Email;
use Awesomemotive\Rewardswp\Services\AssetsService;

class EmailPreviewView implements ViewInterface {
	/**
	 * Assets service instance.
	 *
	 * @since 1.1.0
	 *
	 * @var AssetsService
	 */
	private AssetsService $assets_service;

	/**
	 * Constructor.
	 *
	 * @since 1.1.0
	 *
	 * @param AssetsService $assets_service Assets service instance.
	 */
	public function __construct( AssetsService $assets_service ) {
		$this->assets_service = $assets_service;
	}

	/**
	 * Render the email preview template.
	 *
	 * @since 1.1.0
	 *
	 * @param array $args {
	 *     @type Email $email The email object to preview.
	 *     @type string $rendered_content The fully rendered email content.
	 * }
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {
		$email            = $args['email'] ?? null;
		$rendered_content = $args['rendered_content'] ?? '';
		$display_title    = $args['display_title'] ?? null;

		if ( ! $email instanceof Email ) {
			wp_die( esc_html__( 'Invalid email object.', 'rewardswp' ) );
		}

		// Use provided display title or fallback to auto-generated
		$email_display_title = $display_title ?? ucwords( str_replace( '_', ' ', $email->name ) );
		$list_url            = admin_url( 'admin.php?page=rewardswp-emails' );
		$edit_url            = admin_url( 'admin.php?page=rewardswp-emails&action=edit&email_id=' . $email->id );

		// Check if this is iframe mode (for embedded preview)
		// This is a GET request in admin area for navigation purposes only, nonce verification is not required.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$get_iframe = isset( $_GET['iframe'] ) ? sanitize_text_field( wp_unslash( $_GET['iframe'] ) ) : '';
		$is_iframe = '1' === $get_iframe;

		?>
		<!DOCTYPE html>
		<?php if ( $is_iframe ) : ?>
		<html lang="en">
		<?php else : ?>
		<html <?php language_attributes(); ?>>
		<?php endif; ?>
		<head>
			<meta charset="<?php echo esc_attr( $is_iframe ? 'UTF-8' : get_bloginfo( 'charset' ) ); ?>">
			<meta name="viewport" content="width=device-width, initial-scale=1">
			<title><?php
			echo esc_html(
				sprintf(
					/* translators: %s: Email display title. */
					__( 'Preview: %s', 'rewardswp' ),
					$email_display_title
				)
			);
			?></title>
			
			<?php if ( $is_iframe ) : ?>
			<!-- Minimal mode: Completely isolated from WordPress -->
			<style>
				/* Reset all WordPress and admin styles */
				* {
					box-sizing: border-box;
				}
				
				html {
					margin: 0 !important;
					padding: 0 !important;
					background: #ffffff !important;
				}
				
				body {
					margin: 0 !important;
					padding: 0 !important;
					/* Let email template define its own background */
					font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif !important;
					line-height: 1.6 !important;
					color: #374151 !important;
					font-size: 14px !important;
				}
				
				/* Hide WordPress admin elements */
				#wpadminbar,
				#adminmenumain,
				#wpfooter,
				.wp-toolbar,
				.admin-bar,
				.wrap,
				.rewardswp-container {
					display: none !important;
				}
				
				/* Email content styles */
				h1, h2, h3, h4, h5, h6 {
					margin-top: 0 !important;
					margin-bottom: 16px !important;
					font-weight: 600 !important;
					line-height: 1.25 !important;
				}
				
				p {
					margin-bottom: 16px !important;
				}
				
				a {
					color: #3b82f6 !important;
					text-decoration: underline !important;
				}
				
				img {
					max-width: 100% !important;
					height: auto !important;
				}
				
				table {
					width: 100% !important;
					border-collapse: collapse !important;
				}
				
				/* Responsive styles */
				@media (max-width: 600px) {
					body {
						padding: 12px !important;
						font-size: 13px !important;
					}
				}
			</style>
			<script>
				// Auto-resize iframe to content height
				function resizeIframe() {
					try {
						// Safely get height, fallback to 300 if elements don't exist
						const body = document.body;
						const html = document.documentElement;
						
						if (!body || !html) {
							return;
						}
						
						const height = Math.max(
							body.scrollHeight || 300,
							body.offsetHeight || 300,
							html.clientHeight || 300,
							html.scrollHeight || 300,
							html.offsetHeight || 300
						);
						
						// Send height to parent window
						if (window.parent && window.parent !== window) {
							window.parent.postMessage({
								type: 'iframe-resize',
								height: height + 20 // Add some padding
							}, '*');
						}
					} catch (e) {
						// Silently fail if there are any errors
						console.warn('Resize iframe error:', e);
					}
				}
				
				// Listen for resize requests from parent
				window.addEventListener('message', function(event) {
					if (event.data && event.data.type === 'request-height') {
						resizeIframe();
					}
				});
				
				// Resize on load only (remove other listeners to avoid conflicts)
				window.addEventListener('load', function() {
					setTimeout(resizeIframe, 200);
				});
				
				// Initial resize call
				setTimeout(resizeIframe, 100);
			</script>
			<?php else : ?>
			<!-- Full mode: Load bundled Tailwind utilities -->
			<?php
			// Enqueue admin CSS for full mode preview using AssetsService.
			// If not already registered, this will register and enqueue automatically.
			$this->assets_service->enqueue_style( $this->assets_service::ADMIN_STYLE_HANDLE, 'admin-styles.css' );
			wp_head();
			?>

			<style>
				/* Email client simulation styles */
				.email-client {
					background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
					min-height: 100vh;
					font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
				}
				
				.email-window {
					background: white;
					border-radius: 12px;
					box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
					overflow: hidden;
				}
				
				.email-header {
					background: #f8fafc;
					border-bottom: 1px solid #e2e8f0;
					padding: 12px 20px;
				}
				
				.email-toolbar {
					background: #f1f5f9;
					border-bottom: 1px solid #e2e8f0;
					padding: 12px 20px;
					display: flex;
					align-items: center;
					gap: 16px;
				}
				
				.toolbar-button {
					display: inline-flex;
					align-items: center;
					gap: 6px;
					padding: 6px 12px;
					background: white;
					border: 1px solid #d1d5db;
					border-radius: 6px;
					text-decoration: none;
					color: #374151;
					font-size: 14px;
					font-weight: 500;
					transition: all 0.2s;
				}
				
				.toolbar-button:hover {
					background: #f9fafb;
					border-color: #9ca3af;
				}
				
				.email-content-area {
					background: white;
				}
				
				.email-content {
					padding: 24px;
					line-height: 1.6;
					color: #374151;
				}
				
				.email-meta {
					background: #f8fafc;
					border-top: 1px solid #e2e8f0;
					padding: 20px;
					font-size: 14px;
					color: #6b7280;
				}
				
				/* Print styles */
				@media print {
					.email-client {
						background: white !important;
					}
					.email-window {
						box-shadow: none !important;
						border: 1px solid #ddd;
					}
					.email-header,
					.email-toolbar,
					.email-meta {
						display: none !important;
					}
				}
				
				/* Responsive styles */
				@media (max-width: 768px) {
					.email-window {
						margin: 16px;
						border-radius: 8px;
					}
					.toolbar-button {
						padding: 8px;
						font-size: 12px;
					}
					.toolbar-button span {
						display: none;
					}
				}
				
				/* Email content specific styles */
				.email-content h1,
				.email-content h2,
				.email-content h3,
				.email-content h4,
				.email-content h5,
				.email-content h6 {
					margin-top: 0;
					margin-bottom: 1rem;
					font-weight: 600;
					line-height: 1.25;
				}
				
				.email-content p {
					margin-bottom: 1rem;
					line-height: 1.6;
				}
				
				.email-content a {
					color: #3b82f6 !important;
					text-decoration: underline !important;
					font-weight: normal !important;
					border: none !important;
					box-shadow: none !important;
					outline: none !important;
					background: transparent !important;
					display: inline !important;
					box-sizing: border-box !important;
				}
				
				a:hover {
					color: #2563eb !important;
					text-decoration: underline !important;
					background: transparent !important;
				}
				
				a:focus {
					outline: 2px solid #3b82f6 !important;
					outline-offset: 2px !important;
					background: transparent !important;
				}
				
				/* Protect email button styles from admin interference */
				a.rewardswp-button-link {
					color: #ffffff !important;
					text-decoration: none !important;
					background-color: #3b82f6 !important;
					border-radius: 0.5rem !important;
					padding: 1rem 2rem !important;
					display: inline-block !important;
					font-weight: 600 !important;
					border: none !important;
					box-shadow: none !important;
					outline: none !important;
					font-size: inherit !important;
					line-height: normal !important;
				}
				
				a.rewardswp-button-link:hover {
					background-color: #2563eb !important;
					color: #ffffff !important;
					text-decoration: none !important;
				}
				
				a.rewardswp-button-link:focus {
					outline: 2px solid #3b82f6 !important;
					outline-offset: 2px !important;
					background-color: #2563eb !important;
					color: #ffffff !important;
				}
			</style>
			<?php endif; ?>
		</head>
		<body class="<?php echo $is_iframe ? 'bg-white m-0 p-4' : 'email-client'; ?>">
			<?php if ( $is_iframe ) : ?>
				<!-- Iframe Mode: Just the email content -->
				<div>
					<?php
					// Simple content output for iframe - just the email content
					// We output directly since this is controlled email template content
					echo $rendered_content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Controlled email template content
					?>
				</div>
			<?php else : ?>
				<!-- Full Page Mode: Complete email client simulation -->
				<div class="min-h-screen py-8 px-4">
					<div class="max-w-4xl mx-auto">
						
						<!-- Email Client Header -->
						<div class="mb-6 text-center">
							<h1 class="text-2xl font-bold text-white mb-2">
								<?php esc_html_e( 'Email Preview', 'rewardswp' ); ?>
							</h1>
							<p class="text-blue-100">
								<?php
								echo esc_html(
									sprintf(
										/* translators: %s: Email display title. */
										__( 'Preview of: %s', 'rewardswp' ),
										$email_display_title
									)
								);
								?>
							</p>
						</div>
						
						<!-- Email Window -->
						<div class="email-window">
							
							<!-- Email Header -->
							<div class="email-header">
								<div class="flex items-center justify-between">
									<div class="flex items-center space-x-3">
										<div class="w-3 h-3 bg-red-500 rounded-full"></div>
										<div class="w-3 h-3 bg-yellow-500 rounded-full"></div>
										<div class="w-3 h-3 bg-green-500 rounded-full"></div>
									</div>
									<div class="text-sm text-gray-600 font-medium">
										<?php esc_html_e( 'RewardsWP Email Client', 'rewardswp' ); ?>
									</div>
									<div class="w-16"></div> <!-- Spacer -->
								</div>
							</div>
							
							<!-- Email Toolbar -->
							<div class="email-toolbar">
								<a href="<?php echo esc_url( $list_url ); ?>" class="toolbar-button">
									<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
										<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
									</svg>
									<?php esc_html_e( 'Back to List', 'rewardswp' ); ?>
								</a>
								
								<a href="<?php echo esc_url( $edit_url ); ?>" class="toolbar-button">
									<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
										<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
									</svg>
									<?php esc_html_e( 'Edit Email', 'rewardswp' ); ?>
								</a>
								
								<button onclick="window.print()" class="toolbar-button">
									<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
										<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"></path>
									</svg>
									<?php esc_html_e( 'Print', 'rewardswp' ); ?>
								</button>
								
								<div class="ml-auto flex items-center space-x-2">
									<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
										<?php esc_html_e( 'Preview Mode', 'rewardswp' ); ?>
									</span>
								</div>
							</div>
						
							<!-- Email Subject Line -->
							<div class="bg-blue-50 border-b border-blue-200 px-6 py-4">
								<div class="text-sm text-gray-600 mb-1">
									<?php esc_html_e( 'Subject:', 'rewardswp' ); ?>
								</div>
								<div class="text-lg font-semibold text-gray-900">
									<?php echo esc_html( $email->subject ); ?>
								</div>
							</div>
							
							<!-- Email Content -->
							<div class="email-content-area">
								<div class="email-content">
									<?php
									// Output email content directly to preserve CSS styles
									echo $rendered_content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Controlled email template content
									?>
								</div>
							</div>
							
							<!-- Email Footer Meta -->
							<div class="email-meta">
								<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
									<div>
										<strong><?php esc_html_e( 'Template:', 'rewardswp' ); ?></strong>
										<?php echo esc_html( $email_display_title ); ?>
									</div>
									<div>
										<strong><?php esc_html_e( 'Status:', 'rewardswp' ); ?></strong>
										<span class="<?php echo $email->is_enabled ? 'text-green-600' : 'text-red-600'; ?>">
											<?php echo $email->is_enabled ? esc_html__( 'Enabled', 'rewardswp' ) : esc_html__( 'Disabled', 'rewardswp' ); ?>
										</span>
									</div>
									<div>
										<strong><?php esc_html_e( 'Last Updated:', 'rewardswp' ); ?></strong>
										<?php echo esc_html( mysql2date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $email->created_at ) ); ?>
									</div>
									<div>
										<strong><?php esc_html_e( 'Preview Generated:', 'rewardswp' ); ?></strong>
										<?php echo esc_html( current_time( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) ) ); ?>
									</div>
								</div>
							</div>
							
						</div>
						
						<!-- Notice about placeholders -->
						<div class="mt-6 bg-yellow-50 border border-yellow-200 rounded-lg p-4">
							<div class="flex">
								<svg class="w-5 h-5 text-yellow-400 mt-0.5 mr-3" fill="currentColor" viewBox="0 0 20 20">
									<path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path>
								</svg>
								<div>
									<h4 class="text-sm font-medium text-yellow-800 mb-1">
										<?php esc_html_e( 'Preview Notice', 'rewardswp' ); ?>
									</h4>
									<p class="text-sm text-yellow-700">
										<?php esc_html_e( 'This is a preview with sample data. Actual emails will have real member data, referral links, and dynamic content based on the context.', 'rewardswp' ); ?>
									</p>
								</div>
							</div>
						</div>
					</div>
				</div>
				
				<script>
				// Print media styles
				window.addEventListener('beforeprint', function() {
					document.body.style.background = 'white';
				});
				window.addEventListener('afterprint', function() {
					document.body.style.background = '';
				});
				</script>
			<?php endif; ?>
		</body>
		</html>
		<?php
	}
}