<?php
/**
 * Settings Images class for the image generation page.
 *
 * @package AgenticWP
 */

namespace Agentic_WP;

defined( 'ABSPATH' ) || exit;

/**
 * Image generation admin page.
 *
 * @since 1.0.0
 */
class Settings_Images extends Settings_Base {

	/**
	 * PayPal hosted button ID for donations.
	 *
	 * @var string
	 */
	private const PAYPAL_HOSTED_BUTTON_ID = 'DJ9GULXH8TZWC';

	/**
	 * Initialize images page and register hooks.
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'add_admin_menu' ), 11 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_images_assets' ) );
	}

	/**
	 * Add Images submenu page.
	 *
	 * @return void
	 */
	public function add_admin_menu(): void {
		add_submenu_page(
			'agenticwp-dashboard',
			__( 'Image Generator', 'agenticwp' ),
			__( 'Images', 'agenticwp' ),
			'upload_files',
			'agenticwp-images',
			array( $this, 'render_images_page' )
		);
	}

	/**
	 * Enqueue images page-specific assets.
	 *
	 * @param string $hook Current admin page hook.
	 * @return void
	 */
	public function enqueue_images_assets( string $hook ): void {
		if ( 'agentic-wp_page_agenticwp-images' !== $hook ) {
			return;
		}

		$plugin_file = dirname( __DIR__ ) . '/agenticwp.php';
		$version     = get_file_data( $plugin_file, array( 'Version' => 'Version' ) )['Version'] ?: '1.0.0';
		$base_url    = plugin_dir_url( $plugin_file );

		wp_enqueue_style(
			'agenticwp-images',
			$base_url . 'assets/css/admin/images.css',
			array(),
			$version
		);

		wp_enqueue_script(
			'agenticwp-images-generator',
			$base_url . 'assets/js/admin/images-generator.js',
			array( 'jquery' ),
			$version,
			true
		);

		wp_enqueue_script(
			'agenticwp-tip-jar',
			$base_url . 'assets/js/admin/tip-jar.js',
			array(),
			$version,
			true
		);
		wp_localize_script( 'agenticwp-tip-jar', 'agenticwp_tip_jar', array( 'version' => $version ) );

		wp_localize_script(
			'agenticwp-images-generator',
			'agenticwpImages',
			array(
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( 'agenticwp_image_nonce' ),
				'i18n'    => array(
					'generating'       => __( 'Generating image...', 'agenticwp' ),
					'saving'           => __( 'Saving to Media Library...', 'agenticwp' ),
					'error'            => __( 'An error occurred. Please try again.', 'agenticwp' ),
					'promptRequired'   => __( 'Please enter a prompt to generate an image.', 'agenticwp' ),
					'transparentWarn'  => __( 'Transparent backgrounds require PNG or WebP format.', 'agenticwp' ),
					'rateLimitError'   => __( 'Too many requests. Please wait a moment and try again.', 'agenticwp' ),
					'invalidKeyError'  => __( 'API key is invalid or missing. Please check Settings.', 'agenticwp' ),
					'moderationError'  => __( 'This prompt was flagged by content moderation. Please try a different prompt.', 'agenticwp' ),
					'uploadLimitError' => __( 'Generated image exceeds upload limit. Try a lower quality setting.', 'agenticwp' ),
					'networkError'     => __( 'Network error. Please check your connection and try again.', 'agenticwp' ),
					'serviceError'     => __( 'OpenAI service is temporarily unavailable. Please try again later.', 'agenticwp' ),
				),
			)
		);
	}

	/**
	 * Render the images page.
	 *
	 * @return void
	 */
	public function render_images_page(): void {
		$has_api_key = ! empty( Settings::get_api_key() );
		?>
		<div class="wrap agenticwp-images-wrap">
			<header class="agenticwp-images-header">
				<div class="agenticwp-header-content">
					<h1><?php esc_html_e( 'Image Generator', 'agenticwp' ); ?></h1>
					<p class="agenticwp-header-description"><?php esc_html_e( 'Create AI-generated images using OpenAI\'s image generation model.', 'agenticwp' ); ?></p>
				</div>
			</header>
			<?php $this->render_tip_jar_banner(); ?>

			<?php if ( ! $has_api_key ) : ?>
				<?php $this->render_api_key_warning(); ?>
			<?php else : ?>
				<?php $this->render_generator_form(); ?>
				<?php $this->render_preview_area(); ?>
				<?php $this->render_history_section(); ?>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Render the API key warning message.
	 *
	 * @return void
	 */
	private function render_api_key_warning(): void {
		$settings_url = admin_url( 'admin.php?page=agenticwp-settings' );
		?>
		<div class="agenticwp-notice agenticwp-notice-warning">
			<span class="dashicons dashicons-warning"></span>
			<div class="agenticwp-notice-content">
				<p>
					<?php
					printf(
						/* translators: %s: Link to settings page */
						esc_html__( 'An OpenAI API key is required to generate images. Please configure your API key in %s.', 'agenticwp' ),
						'<a href="' . esc_url( $settings_url ) . '">' . esc_html__( 'Settings', 'agenticwp' ) . '</a>'
					);
					?>
				</p>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the image generator form.
	 *
	 * @return void
	 */
	private function render_generator_form(): void {
		?>
		<div class="agenticwp-generator-section">
			<div class="agenticwp-bento-grid">
				<!-- Left column: Templates (span-7) -->
				<div class="agenticwp-bento-card agenticwp-span-7 agenticwp-templates-cell">
					<h3 id="agenticwp-templates-heading"><?php esc_html_e( 'Quick Start Templates', 'agenticwp' ); ?></h3>
					<div class="agenticwp-template-cards" role="group" aria-labelledby="agenticwp-templates-heading">
						<button type="button" class="agenticwp-template-card" data-template="blog-header" data-size="1536x1024" data-prompt="<?php echo esc_attr__( 'A clean, professional blog header image with a soft gradient background transitioning from light blue to white. Minimalist modern design with plenty of negative space on the right side for text overlay. Subtle geometric shapes or abstract elements floating in the background. Soft diffused lighting, contemporary corporate aesthetic, 4K quality, sharp details', 'agenticwp' ); ?>" aria-label="<?php esc_attr_e( 'Blog Header template - Wide format for articles', 'agenticwp' ); ?>" aria-pressed="false">
							<span class="dashicons dashicons-welcome-write-blog" aria-hidden="true"></span>
							<span class="agenticwp-template-name"><?php esc_html_e( 'Blog Header', 'agenticwp' ); ?></span>
							<span class="agenticwp-template-desc"><?php esc_html_e( 'Wide format for articles', 'agenticwp' ); ?></span>
						</button>
						<button type="button" class="agenticwp-template-card" data-template="social-media" data-size="1024x1536" data-prompt="<?php echo esc_attr__( 'Eye-catching social media graphic with vibrant, bold colors and strong visual contrast. Dynamic composition with energetic geometric shapes, gradients, and modern design elements. Bright saturated palette with complementary colors. Central focal point with room for text overlay. Trendy contemporary style perfect for Instagram or Facebook posts, high resolution, crisp edges', 'agenticwp' ); ?>" aria-label="<?php esc_attr_e( 'Social Media template - Portrait posts and stories', 'agenticwp' ); ?>" aria-pressed="false">
							<span class="dashicons dashicons-share" aria-hidden="true"></span>
							<span class="agenticwp-template-name"><?php esc_html_e( 'Social Media', 'agenticwp' ); ?></span>
							<span class="agenticwp-template-desc"><?php esc_html_e( 'Portrait posts & stories', 'agenticwp' ); ?></span>
						</button>
						<button type="button" class="agenticwp-template-card" data-template="product-shot" data-size="1024x1024" data-prompt="<?php echo esc_attr__( 'Professional product photography on a pure white seamless background. Three-point studio lighting setup with soft key light, fill light, and rim light for depth. Product centered in frame with subtle reflection on surface below. Commercial e-commerce style, ultra sharp focus, color accurate, no text or watermarks, magazine-quality advertising aesthetic', 'agenticwp' ); ?>" data-background="opaque" aria-label="<?php esc_attr_e( 'Product Shot template - E-commerce ready', 'agenticwp' ); ?>" aria-pressed="false">
							<span class="dashicons dashicons-products" aria-hidden="true"></span>
							<span class="agenticwp-template-name"><?php esc_html_e( 'Product Shot', 'agenticwp' ); ?></span>
							<span class="agenticwp-template-desc"><?php esc_html_e( 'E-commerce ready', 'agenticwp' ); ?></span>
						</button>
						<button type="button" class="agenticwp-template-card" data-template="hero-banner" data-size="1536x1024" data-prompt="<?php echo esc_attr__( 'Dramatic cinematic hero banner with epic wide-angle composition. Rich atmospheric depth with volumetric lighting rays cutting through subtle haze. Bold visual storytelling with strong leading lines drawing the eye across the frame. Deep shadows and bright highlights creating contrast. Moody color grading with teal and orange tones. Ultra-wide format perfect for website headers, 8K quality, photorealistic', 'agenticwp' ); ?>" aria-label="<?php esc_attr_e( 'Hero Banner template - Full-width website hero', 'agenticwp' ); ?>" aria-pressed="false">
							<span class="dashicons dashicons-cover-image" aria-hidden="true"></span>
							<span class="agenticwp-template-name"><?php esc_html_e( 'Hero Banner', 'agenticwp' ); ?></span>
							<span class="agenticwp-template-desc"><?php esc_html_e( 'Full-width website hero', 'agenticwp' ); ?></span>
						</button>
						<button type="button" class="agenticwp-template-card" data-template="abstract-art" data-size="1024x1024" data-prompt="<?php echo esc_attr__( 'Modern abstract art composition featuring fluid organic shapes blending seamlessly together. Vibrant gradient color palette with smooth transitions between purple, blue, pink, and orange hues. Dynamic sense of movement and flow with overlapping translucent layers. Contemporary digital art style suitable for backgrounds or wall art. High resolution with fine texture details, artistic and sophisticated', 'agenticwp' ); ?>" aria-label="<?php esc_attr_e( 'Abstract Art template - Decorative backgrounds', 'agenticwp' ); ?>" aria-pressed="false">
							<span class="dashicons dashicons-art" aria-hidden="true"></span>
							<span class="agenticwp-template-name"><?php esc_html_e( 'Abstract Art', 'agenticwp' ); ?></span>
							<span class="agenticwp-template-desc"><?php esc_html_e( 'Decorative backgrounds', 'agenticwp' ); ?></span>
						</button>
						<button type="button" class="agenticwp-template-card" data-template="illustration" data-size="1024x1024" data-prompt="<?php echo esc_attr__( 'Charming hand-drawn style illustration with warm, inviting color palette of soft oranges, creams, and earthy tones. Whimsical artistic details with visible brush strokes and organic imperfections. Friendly, approachable aesthetic with a storybook quality. Gentle shading and soft edges. Perfect for blog posts, marketing materials, or children-friendly content. Artistic, cozy, and nostalgic feeling', 'agenticwp' ); ?>" aria-label="<?php esc_attr_e( 'Illustration template - Hand-drawn style art', 'agenticwp' ); ?>" aria-pressed="false">
							<span class="dashicons dashicons-admin-customizer" aria-hidden="true"></span>
							<span class="agenticwp-template-name"><?php esc_html_e( 'Illustration', 'agenticwp' ); ?></span>
							<span class="agenticwp-template-desc"><?php esc_html_e( 'Hand-drawn style art', 'agenticwp' ); ?></span>
						</button>
					</div>
				</div>

				<!-- Right column: Prompt + Settings (span-5) -->
				<div class="agenticwp-span-5 agenticwp-prompt-column">
					<!-- Prompt input card -->
					<div class="agenticwp-bento-card agenticwp-prompt-cell">
						<label for="agenticwp-image-prompt" class="agenticwp-label"><?php esc_html_e( 'Image Description', 'agenticwp' ); ?></label>
						<textarea id="agenticwp-image-prompt" class="agenticwp-prompt-textarea" rows="4" placeholder="<?php echo esc_attr__( 'Describe the image you want to generate... e.g., "A serene mountain landscape at sunset with a lake in the foreground, photorealistic style"', 'agenticwp' ); ?>"></textarea>
						<div class="agenticwp-prompt-footer">
							<span class="agenticwp-char-count"><span id="agenticwp-char-count">0</span> / 32,000</span>
							<button type="button" class="agenticwp-tips-toggle" aria-expanded="false">
								<span class="dashicons dashicons-lightbulb"></span>
								<?php esc_html_e( 'Prompt Tips', 'agenticwp' ); ?>
							</button>
						</div>
						<div class="agenticwp-prompt-tips" hidden>
							<ul>
								<li><?php esc_html_e( 'Be specific about style, lighting, and composition', 'agenticwp' ); ?></li>
								<li><?php esc_html_e( 'Include art style references (e.g., "oil painting", "digital art", "photorealistic")', 'agenticwp' ); ?></li>
								<li><?php esc_html_e( 'Describe colors, mood, and atmosphere', 'agenticwp' ); ?></li>
								<li><?php esc_html_e( 'Mention perspective (e.g., "aerial view", "close-up", "wide angle")', 'agenticwp' ); ?></li>
							</ul>
						</div>
					</div>

					<!-- Settings + Generate card -->
					<div class="agenticwp-bento-card agenticwp-settings-cell">
						<div class="agenticwp-options-grid">
							<div class="agenticwp-option-compact">
								<label for="agenticwp-image-size"><?php esc_html_e( 'Size', 'agenticwp' ); ?></label>
								<select id="agenticwp-image-size" class="agenticwp-select-compact">
									<option value="1024x1024"><?php esc_html_e( 'Square', 'agenticwp' ); ?></option>
									<option value="1536x1024"><?php esc_html_e( 'Landscape', 'agenticwp' ); ?></option>
									<option value="1024x1536"><?php esc_html_e( 'Portrait', 'agenticwp' ); ?></option>
								</select>
							</div>
							<div class="agenticwp-option-compact">
								<label for="agenticwp-image-quality"><?php esc_html_e( 'Quality', 'agenticwp' ); ?></label>
								<select id="agenticwp-image-quality" class="agenticwp-select-compact">
									<option value="low" selected><?php esc_html_e( 'Low', 'agenticwp' ); ?></option>
									<option value="medium"><?php esc_html_e( 'Medium', 'agenticwp' ); ?></option>
									<option value="high"><?php esc_html_e( 'High', 'agenticwp' ); ?></option>
								</select>
							</div>
							<div class="agenticwp-option-compact">
								<label for="agenticwp-image-format"><?php esc_html_e( 'Format', 'agenticwp' ); ?></label>
								<select id="agenticwp-image-format" class="agenticwp-select-compact">
									<option value="png"><?php esc_html_e( 'PNG', 'agenticwp' ); ?></option>
									<option value="jpeg"><?php esc_html_e( 'JPEG', 'agenticwp' ); ?></option>
									<option value="webp" selected><?php esc_html_e( 'WebP', 'agenticwp' ); ?></option>
								</select>
							</div>
							<div class="agenticwp-option-compact">
								<label for="agenticwp-image-background"><?php esc_html_e( 'Background', 'agenticwp' ); ?></label>
								<select id="agenticwp-image-background" class="agenticwp-select-compact">
									<option value="auto"><?php esc_html_e( 'Auto', 'agenticwp' ); ?></option>
									<option value="transparent"><?php esc_html_e( 'Transparent', 'agenticwp' ); ?></option>
									<option value="opaque"><?php esc_html_e( 'Opaque', 'agenticwp' ); ?></option>
								</select>
							</div>
						</div>
						<button type="button" id="agenticwp-generate-btn" class="button button-primary agenticwp-generate-btn-full">
							<span class="dashicons dashicons-format-image"></span>
							<?php esc_html_e( 'Generate Image', 'agenticwp' ); ?>
						</button>
					</div>
				</div>
			</div>

			<!-- Generating overlay (positioned absolute over bento grid) -->
			<div id="agenticwp-generating-section" class="agenticwp-generating-overlay" hidden aria-live="polite" aria-atomic="true" role="status">
				<div class="agenticwp-generating-container">
					<div class="agenticwp-generating-animation" aria-hidden="true">
						<div class="agenticwp-generating-orb"></div>
						<div class="agenticwp-generating-rings">
							<div class="agenticwp-generating-ring"></div>
							<div class="agenticwp-generating-ring"></div>
							<div class="agenticwp-generating-ring"></div>
						</div>
					</div>
					<div class="agenticwp-generating-text">
						<span class="agenticwp-generating-title"><?php esc_html_e( 'Creating your image', 'agenticwp' ); ?></span>
						<span class="agenticwp-generating-subtitle"><?php esc_html_e( 'This usually takes 10-30 seconds. Higher quality images take longer.', 'agenticwp' ); ?></span>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the preview area for generated images.
	 *
	 * @return void
	 */
	private function render_preview_area(): void {
		?>
		<div id="agenticwp-preview-section" class="agenticwp-preview-section" hidden>
			<h3><?php esc_html_e( 'Generated Image', 'agenticwp' ); ?></h3>
			<div class="agenticwp-preview-container">
				<div class="agenticwp-preview-image-wrapper">
					<img id="agenticwp-preview-image" src="" alt="<?php esc_attr_e( 'Generated image preview', 'agenticwp' ); ?>">
				</div>
				<div class="agenticwp-preview-actions">
					<button type="button" id="agenticwp-save-btn" class="button button-primary">
						<span class="dashicons dashicons-media-default"></span>
						<?php esc_html_e( 'Save to Media Library', 'agenticwp' ); ?>
					</button>
					<button type="button" id="agenticwp-download-btn" class="button button-secondary">
						<span class="dashicons dashicons-download"></span>
						<?php esc_html_e( 'Download', 'agenticwp' ); ?>
					</button>
					<button type="button" id="agenticwp-regenerate-btn" class="button button-secondary">
						<span class="dashicons dashicons-update"></span>
						<?php esc_html_e( 'Regenerate', 'agenticwp' ); ?>
					</button>
					<button type="button" id="agenticwp-discard-btn" class="button button-link-delete">
						<?php esc_html_e( 'Discard', 'agenticwp' ); ?>
					</button>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the recent generations history section.
	 *
	 * @return void
	 */
	private function render_history_section(): void {
		?>
		<div id="agenticwp-history-section" class="agenticwp-history-section">
			<h3><?php esc_html_e( 'Recent Generations', 'agenticwp' ); ?></h3>
			<div id="agenticwp-history-grid" class="agenticwp-history-grid">
				<p class="agenticwp-history-loading"><?php esc_html_e( 'Loading recent images...', 'agenticwp' ); ?></p>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the tip jar banner.
	 *
	 * @return void
	 */
	private function render_tip_jar_banner(): void {
		?>
		<div class="agenticwp-tip-jar" data-tip-jar>
			<div class="agenticwp-tip-jar-icon"><span class="dashicons dashicons-heart"></span></div>
			<div class="agenticwp-tip-jar-content">
				<span class="agenticwp-tip-jar-title"><?php esc_html_e( 'Enjoying Agentic WP?', 'agenticwp' ); ?></span>
				<span class="agenticwp-tip-jar-message"><?php esc_html_e( 'Your support helps fund new features and improvements.', 'agenticwp' ); ?></span>
			</div>
			<div class="agenticwp-tip-jar-action">
				<form action="https://www.paypal.com/donate/?hosted_button_id=<?php echo esc_attr( self::PAYPAL_HOSTED_BUTTON_ID ); ?>" method="post" target="_blank">
					<input type="image" src="https://www.paypalobjects.com/en_AU/i/btn/btn_donate_SM.gif" name="submit" title="<?php esc_attr_e( 'Donate with PayPal', 'agenticwp' ); ?>" alt="<?php esc_attr_e( 'Donate with PayPal button', 'agenticwp' ); ?>">
				</form>
			</div>
			<button type="button" class="agenticwp-tip-jar-dismiss" aria-label="<?php esc_attr_e( 'Dismiss tip jar', 'agenticwp' ); ?>">
				<span class="dashicons dashicons-no-alt"></span>
			</button>
		</div>
		<?php
	}
}
