<?php
/**
 * Handles admin metabox UI tabs with explicit WebPage title and description inputs.
 *
 * @package FAQ_Magic
 */

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

class Qcld_Faq_Data_Metabox
{

	private static $collected_faqs = array();
	private static $schema_rendered = false;

	public function __construct()
	{
		add_action('wp_ajax_qcld_faq_data_json_preview', array(__CLASS__, 'ajax_json_preview'));
		add_action('wp_ajax_qcld_faq_generate_ai', array(__CLASS__, 'ajax_generate_ai'));
		add_action('add_meta_boxes', array($this, 'add_faq_metabox'));
		add_action('save_post', array($this, 'save_faq_metabox_data'));
		add_action('admin_enqueue_scripts', array($this, 'enqueue_metabox_assets'));
		add_action('admin_enqueue_scripts', array($this, 'enqueue_settings_assets'));
		add_action('wp_head', array($this, 'render_frontend_schema'));
		add_action('wp_footer', array($this, 'render_frontend_schema')); // Backup for shortcode-collected data
		add_shortcode('qcld-faq', array($this, 'render_faq_shortcode'));
	}

	public function add_faq_metabox()
	{
		$screens = array('post', 'page');
		foreach ($screens as $screen) {
			add_meta_box(
				'qcld_faq_data_settings',
				__('FAQ — Schema & Questions', 'seo-help'),
				array($this, 'render_metabox'),
				$screen,
				'normal',
				'high'
			);
		}
	}

	/**
	 * Render the Tabbed Metabox HTML UI.
	 */
	public function render_metabox($post)
	{
		wp_nonce_field('qcld_faq_data_save_meta', 'qcld_faq_data_nonce');

		// Fetch existing custom metadata
		$enable_schema = get_post_meta($post->ID, '_qcld_faq_data_enable_schema', true);
		$webpage_title = get_post_meta($post->ID, '_qcld_faq_data_webpage_title', true);
		$webpage_desc = get_post_meta($post->ID, '_qcld_faq_data_webpage_desc', true);
		$faqs = get_post_meta($post->ID, '_qcld_faq_data_items', true);

		if (!is_array($faqs)) {
			$faqs = array();
		}

		// Fallback defaults from post object
		$default_title = get_the_title($post->ID);
		$default_desc = has_excerpt($post->ID) ? wp_strip_all_tags($post->post_excerpt) : wp_strip_all_tags(wp_trim_words($post->post_content, 30));
		?>
		<div class="qcld-faq-data-meta-container">

			<!-- Tab Navigation Menu -->
			<h2 class="nav-tab-wrapper qcld-faq-data-tabs">
				<a href="#faq-tab-faqs" class="nav-tab nav-tab-active" data-tab="faqs">
					<span class="dashicons dashicons-editor-help"></span> <?php esc_html_e('FAQs', 'seo-help'); ?>
				</a>
				<a href="#faq-tab-webpage" class="nav-tab" data-tab="webpage">
					<span class="dashicons dashicons-admin-page"></span> <?php esc_html_e('WebPage Meta', 'seo-help'); ?>
				</a>
				<a href="#faq-tab-openai" class="nav-tab" data-tab="openai">
					<span class="dashicons dashicons-rest-api"></span>
					<?php esc_html_e('Generate FAQ with AI', 'seo-help'); ?>
				</a>
				<a href="#faq-tab-json" class="nav-tab" id="qcld-faq-data-json-tab-trigger" data-tab="json">
					<span class="dashicons dashicons-code-standards"></span>
					<?php esc_html_e('JSON-LD Preview', 'seo-help'); ?>
				</a>
			</h2>

			<!-- Schema Injection Toggle -->
			<div class="qcld-faq-data-toggle-row">
				<label class="qc-faq-switch-label">
					<div class="qc-faq-switch">
						<input type="checkbox" id="qcld_faq_data_enable_schema" name="qcld_faq_data_enable_schema" value="1" <?php checked($enable_schema, '1'); ?> />
						<span class="qc-faq-slider"></span>
					</div>
					<strong><?php esc_html_e('Inject JSON-LD Structured Data into this page', 'seo-help'); ?></strong>
				</label>
			</div>

			<!-- TAB 1: FAQs Panel -->
			<div id="faq-tab-faqs" class="qcld-faq-data-tab-content qcld-faq-data-tab-active-content">
				<div class="qcld-faq-data-repeater-panel">
					<div class="qcld-faq-data-sortable-list">
						<?php if (!empty($faqs)): ?>
							<?php foreach ($faqs as $faq): ?>
								<div class="qcld-faq-data-row">
									<div class="qcld-faq-data-row-header">
										<span class="dashicons dashicons-sort qcld-faq-data-drag-handle"></span>
										<button type="button" class="qcld-faq-data-remove-btn">&times;</button>
									</div>
									<div class="qcld-faq-data-row-body">
										<div class="qcld-faq-data-field-group">
											<label><?php esc_html_e('Question', 'seo-help'); ?></label>
											<input type="text" name="qcld_faq_data_questions[]"
												value="<?php echo esc_attr($faq['question']); ?>" class="large-text faq-input-sync"
												required />
										</div>
										<div class="qcld-faq-data-field-group">
											<label><?php esc_html_e('Answer', 'seo-help'); ?></label>
											<textarea name="qcld_faq_data_answers[]" class="large-text faq-input-sync" rows="3"
												required><?php echo esc_textarea($faq['answer']); ?></textarea>
										</div>
									</div>
								</div>
							<?php endforeach; ?>
						<?php endif; ?>
					</div>
					<div class="qcld-faq-data-actions">
						<button type="button" id="qcld-faq-data-add-row" class="button button-secondary">
							<span class="dashicons dashicons-plus-alt2"></span>
							<?php esc_html_e('Add FAQ Item', 'seo-help'); ?>
						</button>
					</div>
				</div>
			</div>

			<!-- TAB 2: WebPage Schema Options Panel -->
			<div id="faq-tab-webpage" class="qcld-faq-data-tab-content" style="display:none;">
				<div class="qcld-faq-data-webpage-panel">

					<!-- WebPage Custom Title Field -->
					<div class="qcld-faq-data-field-group">
						<label
							for="qcld_faq_data_webpage_title"><strong><?php esc_html_e('WebPage Title', 'seo-help'); ?></strong></label>
						<p class="description">
							<?php esc_html_e('Overrides default post title in the schema object context.', 'seo-help'); ?>
						</p>
						<input type="text" id="qcld_faq_data_webpage_title" name="qcld_faq_data_webpage_title"
							value="<?php echo esc_attr($webpage_title); ?>" class="large-text faq-input-sync"
							placeholder="<?php echo esc_attr($default_title); ?>" />
					</div>

					<!-- WebPage Custom Description Field -->
					<div class="qcld-faq-data-field-group">
						<label
							for="qcld_faq_data_webpage_desc"><strong><?php esc_html_e('WebPage Description', 'seo-help'); ?></strong></label>
						<p class="description">
							<?php esc_html_e('Overrides default post content excerpt summary statement.', 'seo-help'); ?></p>
						<textarea id="qcld_faq_data_webpage_desc" name="qcld_faq_data_webpage_desc"
							class="large-text faq-input-sync" rows="3"
							placeholder="<?php echo esc_attr($default_desc); ?>"><?php echo esc_textarea($webpage_desc); ?></textarea>
					</div>


				</div>
			</div>

			<!-- TAB 3: AI Generator Panel -->
			<div id="faq-tab-openai" class="qcld-faq-data-tab-content" style="display:none;">
				<div class="qcld-faq-data-openai-panel">
					<?php 
					$openai_key = get_option('qcld_seohelp_api_key');
					$gemini_key = get_option('qcld_gemini_api_key');
					$openrouter_key = get_option('qcld_seohelp_openrouter_api_key');
					if (empty($openai_key) && empty($gemini_key) && empty($openrouter_key)): 
					?>
						<div class="notice notice-warning inline">
							<p><?php printf(esc_html('Please add an OpenAI API key on the %1$sSEO Help Settings Page%2$s, a Gemini API key or OpenRouter API Key on the %3$sAI Settings Page%2$s to use this feature.', 'seo-help'), '<a href="'.esc_url(admin_url('admin.php?page=seo-help')).'" target="_blank">',  '</a>', '<a href="'.esc_url(admin_url('admin.php?page=seo-help#qcld_seohelp_tab-2')).'" target="_blank">'); ?></p>
						</div>
					<?php else: ?>
						<div class="qcld-faq-data-field-group">
							<label><strong><?php esc_html_e('AI Provider', 'seo-help'); ?></strong></label>
							<div class="qcld-faq-ai-provider-toggle">
								<?php if (!empty($openai_key)): ?>
									<label>
										<input type="radio" name="qcld_faq_ai_provider" value="openai" <?php checked(get_option('qcld_ai_settings_open_ai') !== 'gemini' && get_option('qcld_ai_settings_open_ai') !== 'openrouter'); ?>>
										<?php esc_html_e('OpenAI', 'seo-help'); ?>
									</label>
								<?php endif; ?>
								<?php if (!empty($gemini_key)): ?>
									<label>
										<input type="radio" name="qcld_faq_ai_provider" value="gemini" <?php checked(get_option('qcld_ai_settings_open_ai') === 'gemini'); ?>>
										<?php esc_html_e('Gemini', 'seo-help'); ?>
									</label>
								<?php endif; ?>
								<?php if (!empty($openrouter_key)): ?>
									<label>
										<input type="radio" name="qcld_faq_ai_provider" value="openrouter" <?php checked(get_option('qcld_ai_settings_open_ai') === 'openrouter'); ?>>
										<?php esc_html_e('OpenRouter', 'seo-help'); ?>
									</label>
								<?php endif; ?>
							</div>
						</div>
						<div class="qcld-faq-data-field-group">
							<label><strong><?php esc_html_e('Generation Source', 'seo-help'); ?></strong></label>
							<div class="qcld-faq-ai-source-toggle">
								<input type="radio" id="ai-source-prompt" name="qcld_faq_ai_source" value="prompt" checked>
								<label for="ai-source-prompt"><?php esc_html_e('Custom Topic', 'seo-help'); ?></label>
								
								<input type="radio" id="ai-source-content" name="qcld_faq_ai_source" value="content">
								<label for="ai-source-content"><?php esc_html_e('Analyze Content', 'seo-help'); ?></label>
								
								<span class="qcld-faq-ai-toggle-glider"></span>
							</div>
						</div>
						<div id="qcld-faq-ai-prompt-wrap" class="qcld-faq-data-field-group">
							<label for="qcld_faq_ai_prompt"><strong><?php esc_html_e('Custom Prompt / Topic', 'seo-help'); ?></strong></label>
							<p class="description"><?php esc_html_e('Briefly describe the topic or content you want FAQs for.', 'seo-help'); ?></p>
							<textarea id="qcld_faq_ai_prompt" class="large-text" rows="3" placeholder="<?php esc_attr_e('e.g. Benefits of organic coffee, how to install a solar panel...', 'seo-help'); ?>"></textarea>
						</div>
						<div class="qcld-faq-data-field-group">
							<label for="qcld_faq_ai_count"><strong><?php esc_html_e('Number of FAQ Items', 'seo-help'); ?></strong></label>
							<input type="number" id="qcld_faq_ai_count" value="3" min="1" max="10" />
						</div>
						<div class="qcld-faq-data-actions">
							<button type="button" id="qcld-faq-generate-ai-btn" class="button button-primary">
								<span class="dashicons dashicons-admin-generic qcld-spin" style="display:none;"></span>
								<?php esc_html_e('Generate FAQ Items', 'seo-help'); ?>
							</button>
						</div>
						<div id="qcld-faq-ai-feedback" style="margin-top:10px;"></div>
					<?php endif; ?>
				</div>
			</div>

			<!-- TAB 4: Code JSON Schema Live Preview Panel -->
			<div id="faq-tab-json" class="qcld-faq-data-tab-content" style="display:none;">
				<div class="qcld-faq-data-json-panel">
					<p class="description">
						<?php esc_html_e('This is a real-time valid preview of the generated structural JSON-LD data blocks injected on render.', 'seo-help'); ?>
					</p>
					<pre id="qcld-faq-data-json-preview"></pre>
				</div>
			</div>

		</div>

		<!-- Repeater Component Item Handling Template -->
		<script type="text/html" id="qcld-faq-data-template">
					<div class="qcld-faq-data-row" style="display: none;">
						<div class="qcld-faq-data-row-header">
							<span class="dashicons dashicons-sort qcld-faq-data-drag-handle"></span>
							<button type="button" class="qcld-faq-data-remove-btn">&times;</button>
						</div>
						<div class="qcld-faq-data-row-body">
							<div class="qcld-faq-data-field-group">
								<label><?php esc_html_e('Question', 'seo-help'); ?></label>
								<input type="text" name="qcld_faq_data_questions[]" value="" class="large-text faq-input-sync" required />
							</div>
							<div class="qcld-faq-data-field-group">
								<label><?php esc_html_e('Answer', 'seo-help'); ?></label>
								<textarea name="qcld_faq_data_answers[]" class="large-text faq-input-sync" rows="3" required></textarea>
							</div>
						</div>
					</div>
				</script>
		<?php
	}

	/**
	 * Process and sanitize data entries on database save hook action events.
	 */
	public function save_faq_metabox_data($post_id)
	{
		if (!isset($_POST['qcld_faq_data_nonce']) || !wp_verify_nonce($_POST['qcld_faq_data_nonce'], 'qcld_faq_data_save_meta')) {
			return;
		}
		if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
			return;
		}
		if (!current_user_can('edit_post', $post_id)) {
			return;
		}

		// Save Tab Options
		if ( isset($_POST['qcld_faq_data_enable_schema']) ) {
			update_post_meta($post_id, '_qcld_faq_data_enable_schema', isset($_POST['qcld_faq_data_enable_schema']) ? '1' : '0');
		}
		if ( isset($_POST['qcld_faq_data_webpage_title']) ) {
			update_post_meta($post_id, '_qcld_faq_data_webpage_title', sanitize_text_field($_POST['qcld_faq_data_webpage_title']));
		}
		if ( isset($_POST['qcld_faq_data_webpage_desc']) ) {
			update_post_meta($post_id, '_qcld_faq_data_webpage_desc', sanitize_text_field($_POST['qcld_faq_data_webpage_desc']));
		}

		// Save dynamic values
		$faq_items = array();
		if (isset($_POST['qcld_faq_data_questions']) && isset($_POST['qcld_faq_data_answers'])) {
			$questions = array_map('sanitize_text_field', $_POST['qcld_faq_data_questions']);
			$answers = array_map('wp_kses_post', $_POST['qcld_faq_data_answers']);

			foreach ($questions as $index => $question) {
				if (!empty($question) && !empty($answers[$index])) {
					$faq_items[] = array(
						'question' => $question,
						'answer' => $answers[$index],
					);
				}
			}

			if (!empty($faq_items)) {
				update_post_meta($post_id, '_qcld_faq_data_items', $faq_items);
			} else {
				delete_post_meta($post_id, '_qcld_faq_data_items');
			}
		}
	}

	public static function ajax_json_preview()
	{
		check_ajax_referer('seo-help', 'security');

		if ( ! current_user_can( 'manage_options' ) ) {
		    wp_send_json_error( esc_html( 'Unauthorized', 'seo-help' ) );
		    wp_die();
		}

		if (is_array($faqs)) {
			wp_send_json_success($faqs);
		} else {
			wp_send_json_error(array('message' => __('Failed to parse AI response.', 'seo-help')));
		}
	}

	public static function ajax_generate_ai()
	{
		check_ajax_referer('seo-help', 'security');
		// Basic security check
		if (!current_user_can('edit_posts')) {
			wp_send_json_error(array('message' => __('Permission denied.', 'seo-help')));
		}

		$prompt 			= isset($_POST['prompt']) ? sanitize_text_field($_POST['prompt']) : '';
		$content_context 	= isset($_POST['page_content']) ? wp_kses_post($_POST['page_content']) : '';
		$count 				= isset($_POST['count']) ? intval($_POST['count']) : 0;
		$provider 			= isset($_POST['provider']) ? sanitize_text_field(wp_unslash($_POST['provider'])) : '';
		$openai_key 		= get_option('qcld_seohelp_api_key');
		$gemini_key 		= get_option('qcld_gemini_api_key');

		if (!in_array($provider, array('openai', 'gemini'), true)) {
			$provider = get_option('qcld_ai_settings_open_ai') === 'gemini' ? 'gemini' : 'openai';
		}

		if ($provider === 'gemini' && empty($gemini_key)) {
			wp_send_json_error(array('message' => __('Gemini API Key is missing.', 'seo-help')));
		}

		if ($provider === 'openai' && empty($openai_key)) {
			wp_send_json_error(array('message' => __('OpenAI API Key is missing.', 'seo-help')));
		}

		if (empty($prompt) && empty($content_context)) {
			wp_send_json_error(array('message' => __('Please provide a topic or ensure the page has content.', 'seo-help')));
		}

		//$system_prompt = "You are a helpful assistant that generates FAQ items in JSON format. Generate exactly {$count} FAQ items based on the user's input. Each item must have a 'question' and an 'answer'. Return ONLY a JSON array of objects.";

		$system_prompt = "You are a helpful assistant that generates FAQ items in JSON format from a given article. Generate exactly {$count} FAQ items based on the following article in the language it is provided. Each item must have a 'question' and an 'answer'. The FAQ items must be factual and based only on the following article. Return ONLY a JSON array of objects.";
		
		$user_input = $prompt;
		if (!empty($content_context)) {
			$user_input = "Generate FAQs based on this content: \n\n" . $content_context;
			if (!empty($prompt)) {
				$user_input .= "\n\nAdditional instructions: " . $prompt;
			}
		}

		if ($provider === 'gemini') {
			$gemini_model = get_option('qcld_gemini_model') ? get_option('qcld_gemini_model') : 'gemini-1.5-flash';
			$gemini_version = get_option('qcld_gemini_api_version') ? get_option('qcld_gemini_api_version') : 'v1beta';
			$api_url = "https://generativelanguage.googleapis.com/{$gemini_version}/models/{$gemini_model}:generateContent?key=" . urlencode($gemini_key);
			$generation_config = array('temperature' => 0.7);

			$args = array(
				'headers' => array('Content-Type' => 'application/json'),
				'body'    => json_encode(array(
					'contents' => array(
						array(
							'role' => 'user',
							'parts' => array(
								array('text' => $system_prompt . "\n\n" . $user_input),
							),
						),
					),
					'generation_config' => $generation_config,
				)),
				'timeout' => 30,
			);
		} else {
			$api_url = 'https://api.openai.com/v1/chat/completions';
			$args = array(
				'headers' => array(
					'Authorization' => 'Bearer ' . $openai_key,
					'Content-Type'  => 'application/json',
				),
				'body'    => json_encode(array(
					'model'    => 'gpt-3.5-turbo',
					'messages' => array(
						array('role' => 'system', 'content' => $system_prompt),
						array('role' => 'user', 'content' => $user_input),
					),
					'temperature' => 0.7,
				)),
				'timeout' => 30,
			);
		}

		$response = wp_remote_post($api_url, $args);

		if (is_wp_error($response)) {
			wp_send_json_error(array('message' => $response->get_error_message()));
		}

		$body = json_decode(wp_remote_retrieve_body($response), true);
		if (isset($body['error'])) {
			wp_send_json_error(array('message' => $body['error']['message']));
		}

		$content = $provider === 'gemini'
			? (isset($body['candidates'][0]['content']['parts'][0]['text']) ? $body['candidates'][0]['content']['parts'][0]['text'] : '')
			: (isset($body['choices'][0]['message']['content']) ? $body['choices'][0]['message']['content'] : '');
		$faqs = json_decode($content, true);

		if (!is_array($faqs)) {
			// Try to find JSON in the response if it returned text too
			if (preg_match('/\[.*\]/s', $content, $matches)) {
				$faqs = json_decode($matches[0], true);
			}
		}

		if (is_array($faqs)) {
			wp_send_json_success($faqs);
		} else {
			wp_send_json_error(array('message' => __('Failed to parse AI response.', 'seo-help')));
		}
	}

	/**
	 * Render the Global Settings Page for FAQ Schema
	 */
	public static function render_settings_page()
	{
		if (isset($_POST['submit']) && isset($_POST['qcld_faq_settings_nonce']) && wp_verify_nonce($_POST['qcld_faq_settings_nonce'], 'qcld_faq_settings_save')) {
			update_option('qcld_faq_primary_color', sanitize_hex_color($_POST['qcld_faq_primary_color']));
			update_option('qcld_faq_header_text_color', sanitize_hex_color($_POST['qcld_faq_header_text_color']));
			update_option('qcld_faq_content_text_color', sanitize_hex_color($_POST['qcld_faq_content_text_color']));
			$style_val = isset($_POST['qcld_faq_default_style']) ? sanitize_text_field($_POST['qcld_faq_default_style']) : 'style-1';
			if ($style_val !== 'style-1') {
				$style_val = 'style-1';
			}
			update_option('qcld_faq_default_style', $style_val);
			update_option('qcld_faq_ai_author', sanitize_text_field($_POST['qcld_faq_ai_author']));
			update_option('qcld_faq_ai_org', sanitize_text_field($_POST['qcld_faq_ai_org']));
			update_option('qcld_faq_ai_meta_enabled', isset($_POST['qcld_faq_ai_meta_enabled']) ? '1' : '0');
			if (isset($_POST['qcld_seohelp_api_key'])) {
				update_option('qcld_seohelp_api_key', sanitize_text_field($_POST['qcld_seohelp_api_key']));
			}
			update_option('qcld_faq_open_first', isset($_POST['qcld_faq_open_first']) ? '1' : '0');
			update_option('qcld_faq_ignore_webpage_schema', isset($_POST['qcld_faq_ignore_webpage_schema']) ? '1' : '0');
			update_option('qcld_faq_auto_webpage_schema', isset($_POST['qcld_faq_auto_webpage_schema']) ? '1' : '0');
			update_option('qcld_faq_use_excerpt_as_desc', isset($_POST['qcld_faq_use_excerpt_as_desc']) ? '1' : '0');
			update_option('qcld_faq_cleanup_on_uninstall', isset($_POST['qcld_faq_cleanup_on_uninstall']) ? '1' : '0');
			update_option('qcld_faq_disable_schema_globally', isset($_POST['qcld_faq_disable_schema_globally']) ? '1' : '0');
			echo '<div class="updated"><p>' . esc_html('Settings saved.', 'seo-help') . '</p></div>';
		}

		if (isset($_POST['qcld_faq_reset_action']) && isset($_POST['qcld_faq_settings_reset_nonce']) && wp_verify_nonce($_POST['qcld_faq_settings_reset_nonce'], 'qcld_faq_settings_reset')) {
			$options_to_reset = array(
				'qcld_faq_primary_color',
				'qcld_faq_header_text_color',
				'qcld_faq_content_text_color',
				'qcld_faq_default_style',
				'qcld_faq_open_first',
				'qcld_faq_ai_meta_enabled',
				'qcld_faq_ai_author',
				'qcld_faq_ai_org',
				'qcld_faq_ignore_webpage_schema',
				'qcld_faq_auto_webpage_schema',
				'qcld_faq_use_excerpt_as_desc',
				'qcld_faq_disable_schema_globally',
				'qcld_faq_cleanup_on_uninstall'
			);
			foreach ($options_to_reset as $opt) {
				delete_option($opt);
			}
			echo '<div class="updated settings-error notice is-dismissible"><p>' . esc_html('All settings have been reset to default values.', 'seo-help') . '</p></div>';
		}

		$primary_color = get_option('qcld_faq_primary_color', '#4f46e5');
		$disable_globally = get_option('qcld_faq_disable_schema_globally', '0');
		?>
		<div class="wrap qcld-seo-help qcld-dashboard-wrap">
			<div class="qcld-row">
				<div class="qcld-col-md-9">

					<div class="qcld-faq-settings-container">
					<h3><?php esc_html_e('FAQ Schema Settings', 'seo-help'); ?></h3>

				<form method="post" action="">
					<?php wp_nonce_field('qcld_faq_settings_save', 'qcld_faq_settings_nonce'); ?>
					<?php wp_nonce_field('qcld_faq_settings_reset', 'qcld_faq_settings_reset_nonce'); ?>

					<table class="form-table" role="presentation">


						<tr>
							<th scope="row" style="padding-top: 30px;"><strong><?php esc_html_e('AI & Authority Meta', 'seo-help'); ?></strong></th>
							<td style="padding-top: 30px;">
								<label class="qc-faq-switch-label">
									<div class="qc-faq-switch">
										<input type="checkbox" name="qcld_faq_ai_meta_enabled" value="1" <?php checked(get_option('qcld_faq_ai_meta_enabled', '1'), '1'); ?>>
										<span class="qc-faq-slider"></span>
									</div>
									<strong><?php esc_html_e('Enable AI Trust Signals', 'seo-help'); ?></strong>
								</label>
								<p class="description">
									<?php esc_html_e('Provide these details to help AI assistants (Gemini, ChatGPT) verify the authority of your FAQs.', 'seo-help'); ?>
								</p>
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e('Author Name', 'seo-help'); ?></th>
							<td>
								<input type="text" name="qcld_faq_ai_author"
									value="<?php echo esc_attr(get_option('qcld_faq_ai_author', get_bloginfo('name'))); ?>"
									class="regular-text">
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e('Organization Name', 'seo-help'); ?></th>
							<td>
								<input type="text" name="qcld_faq_ai_org"
									value="<?php echo esc_attr(get_option('qcld_faq_ai_org', get_bloginfo('name'))); ?>"
									class="regular-text">
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e('OpenAI API Key', 'seo-help'); ?></th>
							<td>
								<p class="description"><?php printf(esc_html('The OpenAI API key is managed on the %1$sSEO Help Settings Page%2$s.', 'seo-help'), '<a href="' . esc_url(admin_url('admin.php?page=seo-help')) . '">', '</a>'); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e('Global Schema Toggle', 'seo-help'); ?></th>
							<td>
								<label class="qc-faq-switch-label">
									<div class="qc-faq-switch">
										<input type="checkbox" name="qcld_faq_disable_schema_globally" value="1" <?php checked(get_option('qcld_faq_disable_schema_globally', '0'), '1'); ?>>
										<span class="qc-faq-slider"></span>
									</div>
									<strong><?php esc_html_e('Disable JSON-LD injection globally', 'seo-help'); ?></strong>
								</label>
								<p class="description">
									<?php esc_html_e('Check this to stop all automated FAQ schema injection regardless of individual post settings.', 'seo-help'); ?>
								</p>
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e('Schema Compatibility', 'seo-help'); ?></th>
							<td>
								<label class="qc-faq-switch-label" style="margin-bottom: 15px;">
									<div class="qc-faq-switch">
										<input type="checkbox" name="qcld_faq_auto_webpage_schema" value="1" <?php checked(get_option('qcld_faq_auto_webpage_schema', '1'), '1'); ?>>
										<span class="qc-faq-slider"></span>
									</div>
									<strong><?php esc_html_e('Smart Fallback: Generate WebPage schema if missing', 'seo-help'); ?></strong>
								</label>
								<p class="description" style="margin-bottom: 20px;"><?php esc_html_e('Intelligently detects Yoast or RankMath. If they are missing, we generate a WebPage schema to ensure your FAQs have proper context.', 'seo-help'); ?></p>

								<label class="qc-faq-switch-label">
									<div class="qc-faq-switch">
										<input type="checkbox" name="qcld_faq_ignore_webpage_schema" value="1" <?php checked(get_option('qcld_faq_ignore_webpage_schema', '0'), '1'); ?>>
										<span class="qc-faq-slider"></span>
									</div>
									<strong><?php esc_html_e('Force Disable WebPage Schema', 'seo-help'); ?></strong>
								</label>
								<p class="description"><?php esc_html_e('Completely bypasses our WebPage schema generation, regardless of other plugins.', 'seo-help'); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e('Metadata Defaults', 'seo-help'); ?></th>
							<td>
								<label class="qc-faq-switch-label">
									<div class="qc-faq-switch">
										<input type="checkbox" name="qcld_faq_use_excerpt_as_desc" value="1" <?php checked(get_option('qcld_faq_use_excerpt_as_desc', '1'), '1'); ?>>
										<span class="qc-faq-slider"></span>
									</div>
									<strong><?php esc_html_e('Use Post Excerpt as default description', 'seo-help'); ?></strong>
								</label>
								<p class="description"><?php esc_html_e('If enabled and no custom schema description is provided, we will automatically use the post excerpt.', 'seo-help'); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e('Data Hygiene', 'seo-help'); ?></th>
							<td>
								<label class="qc-faq-switch-label">
									<div class="qc-faq-switch">
										<input type="checkbox" name="qcld_faq_cleanup_on_uninstall" value="1" <?php checked(get_option('qcld_faq_cleanup_on_uninstall', '0'), '1'); ?>>
										<span class="qc-faq-slider"></span>
									</div>
									<strong><?php esc_html_e('Clean data on uninstall', 'seo-help'); ?></strong>
								</label>
								<p class="description"><?php esc_html_e('If enabled, all FAQ questions, answers, and schema settings will be permanently deleted from your database when you delete this plugin.', 'seo-help'); ?></p>
							</td>
						</tr>


						<tr style="border-top: 1px solid #eee;">
							<th scope="row"><?php esc_html_e('Accordion Style', 'seo-help'); ?></th>
							<td>
								<select name="qcld_faq_default_style">
									<option value="style-1" <?php selected(get_option('qcld_faq_default_style', 'style-1'), 'style-1'); ?>><?php esc_html_e('Style 1: Modern Card', 'seo-help'); ?></option>
									<option value="style-2" disabled><?php esc_html_e('Style 2: Minimalist (Pro Feature)', 'seo-help'); ?></option>
									<option value="style-3" disabled><?php esc_html_e('Style 3: Solid Header (Pro Feature)', 'seo-help'); ?></option>
									<option value="style-4" disabled><?php esc_html_e('Style 4: Gradient Accent (Pro Feature)', 'seo-help'); ?></option>
									<option value="style-5" disabled><?php esc_html_e('Style 5: Clean Underline (Pro Feature)', 'seo-help'); ?></option>
								</select>
								<p class="description">
									<?php esc_html_e('Choose the default look for your FAQ accordions.', 'seo-help'); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e('Initial State', 'seo-help'); ?></th>
							<td>
								<label class="qc-faq-switch-label">
									<div class="qc-faq-switch">
										<input type="checkbox" name="qcld_faq_open_first" value="1" <?php checked(get_option('qcld_faq_open_first', '0'), '1'); ?>>
										<span class="qc-faq-slider"></span>
									</div>
									<strong><?php esc_html_e('Open first item by default', 'seo-help'); ?></strong>
								</label>
								<p class="description"><?php esc_html_e('If enabled, the first FAQ item will be automatically expanded on page load.', 'seo-help'); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e('Primary Accent Color', 'seo-help'); ?></th>
							<td>
								<input type="text" name="qcld_faq_primary_color"
									value="<?php echo esc_attr(get_option('qcld_faq_primary_color', '#4f46e5')); ?>"
									class="qcld-color-picker">
								<p class="description">
									<?php esc_html_e('Used for icons, active states, and highlights.', 'seo-help'); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e('Header Text Color', 'seo-help'); ?></th>
							<td>
								<input type="text" name="qcld_faq_header_text_color"
									value="<?php echo esc_attr(get_option('qcld_faq_header_text_color', '#1e293b')); ?>"
									class="qcld-color-picker">
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e('Answer Text Color', 'seo-help'); ?></th>
							<td>
								<input type="text" name="qcld_faq_content_text_color"
									value="<?php echo esc_attr(get_option('qcld_faq_content_text_color', '#64748b')); ?>"
									class="qcld-color-picker">
							</td>
						</tr>
					</table>

					<div class="qcld-faq-how-to-guide">
						<p class="qcld-faq-how-to-text">
							<?php esc_html_e('Go to Edit a Page or Post and scroll down to add FAQs manually or generate FAQs with AI.', 'seo-help'); ?>
						</p>
						<div class="qcld-faq-how-to-image">
							<img src="<?php echo esc_url(qcld_seohelp_assets_url . '/faq/screenshots-1.jpg'); ?>" alt="Add FAQ Screenshot" />
						</div>
					</div>

					<div class="qcld-faq-usage-guide">
						<h3>
							<!-- <span class="qcld-faq-badge-pro">PRO</span> -->
							<?php esc_html_e('Shortcode Usage Guide', 'seo-help'); ?>
						</h3>

						<p class="qcld-faq-usage-section-title"><?php esc_html_e('Basic Examples:', 'seo-help'); ?></p>
						<div class="qcld-faq-code-block">
							<code class="qcld-faq-code-basic">[qcld-faq]</code>
							<p class="description" style="margin-bottom: 15px;">
								<?php esc_html_e('Standard accordion for the current post.', 'seo-help'); ?></p>

							<code class="qcld-faq-code-basic">[qcld-faq type="all"]</code>
							<p class="description" style="margin-bottom: 15px;">
								<?php esc_html_e('Aggregate and display all FAQs from every post on your site.', 'seo-help'); ?>
							</p>

							<code class="qcld-faq-code-basic">[qcld-faq post_id="123"]</code>
							<p class="description">
								<?php esc_html_e('Show FAQs from a specific post (e.g., ID 123).', 'seo-help'); ?></p>
						</div>

						<p class="qcld-faq-usage-section-title">
							<?php esc_html_e('Advanced Design Parameters:', 'seo-help'); ?></p>
						<div class="qcld-faq-code-block">
							<code class="qcld-faq-code-adv">[qcld-faq style="style-4"]</code>
							<p class="description" style="margin-bottom: 15px;">
								<?php esc_html_e('Force a specific style (options: style-1, style-2, style-3, style-4, style-5).', 'seo-help'); ?>
							</p>

							<code class="qcld-faq-code-adv">[qcld-faq open_first="1"]</code>
							<p class="description" style="margin-bottom: 15px;">
								<?php esc_html_e('Ensure the first item is expanded even if the global setting is disabled.', 'seo-help'); ?>
							</p>
							
							<code
								class="qcld-faq-code-adv">[qcld-faq primary="#10b981" header_text="#ffffff" style="style-3"]</code>
							<p class="description">
								<?php esc_html_e('Full design override: Custom primary color, custom header text color, and style selection.', 'seo-help'); ?>
							</p>
						</div>
					</div>

					<div class="qcld-faq-help-link-container" style="margin-top: 25px; margin-bottom: 25px;">
						<a href="#" id="qcld-faq-help-modal-trigger" style="display: inline-flex; align-items: center; gap: 8px; font-weight: 700; text-decoration: none; color: #ffffff; font-size: 14px; background: #4f46e5; padding: 10px 20px; border-radius: 8px; transition: all 0.2s ease; box-shadow: 0 4px 6px -1px rgba(79, 70, 229, 0.2);">
							<span class="dashicons dashicons-editor-help" style="font-size: 20px; width: 20px; height: 20px; line-height: 20px;"></span>
							<?php esc_html_e('FAQ — Schema & Questions All Features Help Guide', 'seo-help'); ?>
						</a>
					</div>

					<!-- Modern Help Modal Popup Structure -->
					<div id="qcld-faq-help-modal-overlay" class="qcld-faq-modal-overlay">
						<div class="qcld-faq-modal-container">
							
							<div class="qcld-faq-modal-header">
								<h3>
									<span class="dashicons dashicons-admin-generic" style="font-size: 24px; width: 24px; height: 24px; line-height: 24px;"></span>
									<?php esc_html_e('FAQ — Schema & Questions Guide', 'seo-help'); ?>
								</h3>
								<button type="button" id="qcld-faq-help-modal-close" class="qcld-faq-modal-close-btn">&times;</button>
							</div>

							<div class="qcld-faq-modal-body">
								
								<!-- Modal Sidebar Tab Menu -->
								<div class="qcld-faq-modal-sidebar">
									<button type="button" class="qcld-faq-modal-tab-btn is-active" data-target="faq-modal-tab-overview">
										<span class="dashicons dashicons-visibility"></span> <?php esc_html_e('Overview', 'seo-help'); ?>
									</button>
									<button type="button" class="qcld-faq-modal-tab-btn" data-target="faq-modal-tab-ai">
										<span class="dashicons dashicons-admin-customizer"></span> <?php esc_html_e('AI Generation', 'seo-help'); ?>
									</button>
									<button type="button" class="qcld-faq-modal-tab-btn" data-target="faq-modal-tab-eeat">
										<span class="dashicons dashicons-shield"></span> <?php esc_html_e('E-E-A-T Signals', 'seo-help'); ?>
									</button>
									<button type="button" class="qcld-faq-modal-tab-btn" data-target="faq-modal-tab-styles">
										<span class="dashicons dashicons-art"></span> <?php esc_html_e('Accordion Styles', 'seo-help'); ?>
									</button>
									<button type="button" class="qcld-faq-modal-tab-btn" data-target="faq-modal-tab-shortcodes">
										<span class="dashicons dashicons-editor-code"></span> <?php esc_html_e('Shortcodes', 'seo-help'); ?>
									</button>
								</div>

								<!-- Modal Main Content Area -->
								<div class="qcld-faq-modal-content-area">
									
									<!-- Tab 1: Overview -->
									<div id="faq-modal-tab-overview" class="qcld-faq-modal-tab-content is-active">
										<div class="qcld-faq-feature-card">
											<h3><span class="qcld-faq-help-badge"><?php esc_html_e('Feature', 'seo-help'); ?></span> <?php esc_html_e('Schema Generator & Metabox Integration', 'seo-help'); ?></h3>
											<p><?php esc_html_e('Every individual post, page, or custom post type features an interactive FAQ metabox on its editor page. Adding FAQ items automatically constructs valid structural JSON-LD data blocks injected on render.', 'seo-help'); ?></p>
										</div>
										<div class="qcld-faq-feature-card">
											<h3><span class="qcld-faq-help-badge"><?php esc_html_e('Benefit', 'seo-help'); ?></span> <?php esc_html_e('Search Engine Rich Snippets', 'seo-help'); ?></h3>
											<p><?php esc_html_e('By outputting structured schema data, Google, Bing, and other search engines are prompted to display rich results/collapsible accordions under your site listing, drastically increasing organic CTR (click-through rates) and driving premium conversions.', 'seo-help'); ?></p>
										</div>
										
										<div class="qcld-faq-screenshots-gallery">
											<h4 class="qcld-faq-screenshots-title">
												<span class="dashicons dashicons-format-gallery" style="color: #4f46e5;"></span>
												<?php esc_html_e('Feature Screenshots:', 'seo-help'); ?>
											</h4>
											<div class="qcld-faq-screenshots-list">
												<div class="qcld-faq-screenshot-item">
													<img src="<?php echo esc_url(plugins_url('assets/faq/screenshots-1.jpg', dirname(__FILE__))); ?>" alt="FAQ Editor Panel" />
													<div class="qcld-faq-screenshot-caption">
														<span class="dashicons dashicons-editor-justify" style="color: #4f46e5; font-size: 16px; width: 16px; height: 16px; line-height: 16px;"></span>
														<?php esc_html_e('FAQ Editor Repeater', 'seo-help'); ?>
													</div>
												</div>
												<div class="qcld-faq-screenshot-item">
													<img src="<?php echo esc_url(plugins_url('assets/faq/Screenshots-2.jpg', dirname(__FILE__))); ?>" alt="AI Generator Integration" />
													<div class="qcld-faq-screenshot-caption">
														<span class="dashicons dashicons-admin-customizer" style="color: #4f46e5; font-size: 16px; width: 16px; height: 16px; line-height: 16px;"></span>
														<?php esc_html_e('AI Auto-Generator', 'seo-help'); ?>
													</div>
												</div>
												<div class="qcld-faq-screenshot-item">
													<img src="<?php echo esc_url(plugins_url('assets/faq/screenshots-3.jpg', dirname(__FILE__))); ?>" alt="Structured Schema Preview" />
													<div class="qcld-faq-screenshot-caption">
														<span class="dashicons dashicons-visibility" style="color: #4f46e5; font-size: 16px; width: 16px; height: 16px; line-height: 16px;"></span>
														<?php esc_html_e('Live JSON Schema Preview', 'seo-help'); ?>
													</div>
												</div>
												<div class="qcld-faq-screenshot-item">
													<img src="<?php echo esc_url(plugins_url('assets/faq/screenshots-4.jpg', dirname(__FILE__))); ?>" alt="Global FAQ Settings" />
													<div class="qcld-faq-screenshot-caption">
														<span class="dashicons dashicons-admin-generic" style="color: #4f46e5; font-size: 16px; width: 16px; height: 16px; line-height: 16px;"></span>
														<?php esc_html_e('Settings & Custom Styling', 'seo-help'); ?>
													</div>
												</div>
											</div>
										</div>
									</div>

									<!-- Tab 2: AI Generation -->
									<div id="faq-modal-tab-ai" class="qcld-faq-modal-tab-content">
										<div class="qcld-faq-feature-card">
											<h3><span class="qcld-faq-help-badge"><?php esc_html_e('AI Generator', 'seo-help'); ?></span> <?php esc_html_e('AI-Powered Auto Generation Panel', 'seo-help'); ?></h3>
											<p><?php esc_html_e('Don\'t waste hours writing FAQs. The metabox includes a native AI Generator panel powered by Gemini and OpenAI. Simply pick your provider, enter a topic, or toggle the "Analyze Content" option to let the AI scan your article and write factual, matching FAQ items instantly!', 'seo-help'); ?></p>
										</div>
										<div class="qcld-faq-feature-card">
											<h3><span class="qcld-faq-help-badge"><?php esc_html_e('How-To', 'seo-help'); ?></span> <?php esc_html_e('Instant Database & UI Injection', 'seo-help'); ?></h3>
											<p><?php esc_html_e('Once generated, the system renders a live editable preview. Click to insert them, and they immediately populate your editor repeater. You can modify, re-order, or delete questions and answers before saving.', 'seo-help'); ?></p>
										</div>
									</div>

									<!-- Tab 3: E-E-A-T Signals -->
									<div id="faq-modal-tab-eeat" class="qcld-faq-modal-tab-content">
										<div class="qcld-faq-feature-card">
											<h3><span class="qcld-faq-help-badge"><?php esc_html_e('Trust', 'seo-help'); ?></span> <?php esc_html_e('Authoritative E-E-A-T Schema Signals', 'seo-help'); ?></h3>
											<p><?php esc_html_e('Google\'s E-E-A-T (Experience, Expertise, Authoritativeness, and Trustworthiness) guidelines place huge importance on content metadata. If enabled, this plugin automatically maps DatePublished, DateModified, Author name, and Publisher details directly into the WebPage schema JSON graphs.', 'seo-help'); ?></p>
										</div>
										<div class="qcld-faq-feature-card">
											<h3><span class="qcld-faq-help-badge"><?php esc_html_e('LLM Ready', 'seo-help'); ?></span> <?php esc_html_e('AI Crawler Trust Validation', 'seo-help'); ?></h3>
											<p><?php esc_html_e('AI crawlers (like Gemini, ChatGPT, and perplexity) crawl structured schema to answer conversational prompts. Providing author/publisher metadata validates your content\'s integrity, ensuring search engines trust and recommend your page.', 'seo-help'); ?></p>
										</div>
									</div>

									<!-- Tab 4: Accordion Styles -->
									<div id="faq-modal-tab-styles" class="qcld-faq-modal-tab-content">
										<div class="qcld-faq-feature-card">
											<h3><span class="qcld-faq-help-badge"><?php esc_html_e('Design', 'seo-help'); ?></span> <?php esc_html_e('Interactive Design Accent Customization', 'seo-help'); ?></h3>
											<p><?php esc_html_e('Choose from five premium styled layouts matching any theme:', 'seo-help'); ?></p>
											<ul style="list-style-type: disc; padding-left: 20px; font-size: 13px; color: #475569; margin-top: 8px;">
												<li><strong>Style 1: Modern Card</strong> — Clean separated card rows with soft borders and dynamic shadows.</li>
												<li><strong>Style 2: Minimalist</strong> — Elegant, thin border separators with neat expand icons.</li>
												<li><strong>Style 3: Solid Header</strong> — Heavy solid filled background blocks ideal for high contrast designs.</li>
												<li><strong>Style 4: Gradient Accent</strong> — Smooth left accent bars with multi-color transitions.</li>
												<li><strong>Style 5: Clean Underline</strong> — Ultra-thin minimalist separators with full-width answers.</li>
											</ul>
										</div>
									</div>

									<!-- Tab 5: Shortcodes -->
									<div id="faq-modal-tab-shortcodes" class="qcld-faq-modal-tab-content">
										<div class="qcld-faq-feature-card">
											<h3><span class="qcld-faq-help-badge"><?php esc_html_e('Deploy', 'seo-help'); ?></span> <?php esc_html_e('Deploy Anywhere on Your Site', 'seo-help'); ?></h3>
											<p><?php esc_html_e('Simply paste shortcodes anywhere inside page builders, Gutenberg blocks, or widgets to render beautiful styled interactive accordions.', 'seo-help'); ?></p>
											
											<span class="qcld-faq-code-snippet">[qcld-faq]</span>
											<span class="qcld-faq-code-snippet">[qcld-faq type="all"]</span>
											<span class="qcld-faq-code-snippet">[qcld-faq style="style-4" open_first="1"]</span>
											<span class="qcld-faq-code-snippet">[qcld-faq primary="#10b981" header_text="#ffffff" style="style-3"]</span>
										</div>
									</div>

								</div>
							</div>

						</div>
					</div>

					<p class="submit">
						<input type="submit" name="submit" id="submit" class="button button-primary"
							value="<?php esc_html_e('Save Settings', 'seo-help'); ?>">
						
						<button type="submit" name="qcld_faq_reset_action" class="button button-default" onclick="return confirm('<?php esc_attr_e('Are you sure you want to reset all FAQ settings to their defaults? This will revert all colors and styles.', 'seo-help'); ?>');">
							<?php esc_html_e('Reset to Defaults', 'seo-help'); ?>
						</button>
					</p>
				</form>

			</div>
				</div>
				<!-- Sidebar -->
				<?php qcld_seohelp_render_sidebar(); ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the JSON-LD Schema on the front-end if enabled.
	 */
	public function render_frontend_schema()
	{
		if (self::$schema_rendered) {
			return;
		}

		if (get_option('qcld_faq_disable_schema_globally', '0') === '1') {
			return;
		}

		global $post;
		$faqs_to_render = self::$collected_faqs;

		// If no FAQs collected via shortcode yet, check the current post
		if (empty($faqs_to_render) && is_singular() && $post) {
			$enable_schema = get_post_meta($post->ID, '_qcld_faq_data_enable_schema', true);
			if ($enable_schema === '1') {
				$items = get_post_meta($post->ID, '_qcld_faq_data_items', true);
				if (is_array($items)) {
					$faqs_to_render = $items;
				}
			}
		}

		if (empty($faqs_to_render)) {
			return;
		}

		self::$schema_rendered = true;

		$page_url = is_singular() ? get_permalink($post->ID) : home_url(add_query_arg(array(), $GLOBALS['wp']->request));
		$graph = array();

		// WebPage Object (only if singular and NOT ignored)
		$should_render_webpage = (is_singular() && $post && get_option('qcld_faq_ignore_webpage_schema', '0') !== '1');
		
		// Intelligent Fallback Logic
		if ( $should_render_webpage && get_option('qcld_faq_auto_webpage_schema', '1') === '1' ) {
			// If Yoast or RankMath are active, they likely already output a WebPage object.
			if ( defined('WPSEO_VERSION') || defined('RANK_MATH_VERSION') ) {
				$should_render_webpage = false;
			}
		}

		if ($should_render_webpage) {
			$webpage_title = get_post_meta($post->ID, '_qcld_faq_data_webpage_title', true);
			$webpage_desc = get_post_meta($post->ID, '_qcld_faq_data_webpage_desc', true);

			$final_title = $webpage_title ? $webpage_title : get_the_title($post->ID);
			
			$final_desc = '';
			if ( ! empty( $webpage_desc ) ) {
				$final_desc = $webpage_desc;
			} elseif ( get_option('qcld_faq_use_excerpt_as_desc', '1') === '1' ) {
				$final_desc = has_excerpt($post->ID) ? wp_strip_all_tags($post->post_excerpt) : wp_strip_all_tags(wp_trim_words($post->post_content, 30));
			}

			$webpage = array(
				"@type" => "WebPage",
				"@id" => $page_url,
				"url" => $page_url,
				"name" => $final_title,
				"description" => $final_desc,
			);

			// Add AI Meta if enabled
			if (get_option('qcld_faq_ai_meta_enabled', '1') === '1') {
				$webpage["inLanguage"] = get_locale();
				$webpage["datePublished"] = get_the_date('c', $post->ID);
				$webpage["dateModified"] = get_the_modified_date('c', $post->ID);
				$webpage["author"] = array(
					"@type" => "Person",
					"name" => get_option('qcld_faq_ai_author', get_bloginfo('name'))
				);
				$webpage["publisher"] = array(
					"@type" => "Organization",
					"name" => get_option('qcld_faq_ai_org', get_bloginfo('name')),
					"logo" => array(
						"@type" => "ImageObject",
						"url" => get_site_icon_url()
					)
				);
			}

	
			$graph[] = $webpage;
		}

		// FAQPage Object
		$faq_items = array();
		foreach ($faqs_to_render as $faq) {
			if (!empty($faq['question']) && !empty($faq['answer'])) {
				$faq_items[] = array(
					"@type" => "Question",
					"name" => $faq['question'],
					"acceptedAnswer" => array(
						"@type" => "Answer",
						"text" => $faq['answer'],
					),
				);
			}
		}

		if (!empty($faq_items)) {
			$graph[] = array(
				"@type" => "FAQPage",
				"@id" => $page_url . "#faq",
				"mainEntity" => $faq_items,
			);
		}

		$schema = array(
			"@context" => "https://schema.org",
			"@graph" => $graph,
		);

		echo "\n<!-- FAQ Magic JSON-LD -->\n";
		echo '<script type="application/ld+json">' . wp_json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . '</script>';
		echo "\n<!-- / FAQ Magic JSON-LD -->\n";
	}

	/**
	 * Render the FAQ list via [qcld-faq] shortcode.
	 * Supports [qcld-faq post_id="123"] or [qcld-faq type="all"] or [qcld-faq style="style-2"]
	 */
	public function render_faq_shortcode($atts)
	{
		$atts = shortcode_atts(array(
			'post_id' => '',
			'type' => 'single', // 'single' or 'all'
			'style' => get_option('qcld_faq_default_style', 'style-1'),
			'open_first' => get_option('qcld_faq_open_first', '0'),
			'primary' => get_option('qcld_faq_primary_color', '#4f46e5'),
			'header_text' => get_option('qcld_faq_header_text_color', '#1e293b'),
			'content_text' => get_option('qcld_faq_content_text_color', '#64748b'),
		), $atts, 'qcld-faq');

		$faqs_to_show = array();
		// ... (rest of query logic remains same)
		if ($atts['type'] === 'all') {
			$query = new WP_Query(array(
				'post_type' => array('post', 'page'),
				'posts_per_page' => -1,
				'meta_query' => array(array('key' => '_qcld_faq_data_items', 'compare' => 'EXISTS')),
			));
			if ($query->have_posts()) {
				while ($query->have_posts()) {
					$query->the_post();
					$items = get_post_meta(get_the_ID(), '_qcld_faq_data_items', true);
					if (is_array($items)) {
						$faqs_to_show = array_merge($faqs_to_show, $items);
					}
				}
				wp_reset_postdata();
			}
		} else {
			$target_post_id = !empty($atts['post_id']) ? intval($atts['post_id']) : get_the_ID();
			if (!$target_post_id)
				return '';
			$items = get_post_meta($target_post_id, '_qcld_faq_data_items', true);
			if (is_array($items)) {
				$faqs_to_show = $items;
			}
		}

		if (empty($faqs_to_show))
			return '';
		self::$collected_faqs = array_merge(self::$collected_faqs, $faqs_to_show);

		$container_id = 'qc-faq-' . wp_generate_password(6, false);
		ob_start();
		?>
		<?php
		wp_enqueue_style('qcld-faq-style', plugins_url('assets/css/faq-style.css', dirname(__FILE__)), array(), '1.2.0');
		wp_enqueue_script('qcld-faq-script', plugins_url('assets/js/faq-script.js', dirname(__FILE__)), array('jquery'), '1.2.0', true);
		?>
		<div class="qcld-faq-accordion-wrapper <?php echo esc_attr($atts['style']); ?>"
			id="<?php echo esc_attr($container_id); ?>">
			<?php foreach ($faqs_to_show as $index => $faq): 
				$is_first_and_open = ( $index === 0 && $atts['open_first'] === '1' );
				$item_class = $is_first_and_open ? 'is-active' : '';
				$content_style = $is_first_and_open ? 'style="display: block;"' : '';
			?>
				<div class="qcld-faq-accordion-item <?php echo esc_attr($item_class); ?>">
					<div class="qcld-faq-accordion-header" tabindex="0" role="button" aria-expanded="<?php echo $is_first_and_open ? 'true' : 'false'; ?>">
						<span class="qcld-faq-accordion-icon"></span>
						<span class="qcld-faq-accordion-title"><?php echo esc_html($faq['question']); ?></span>
						<span class="qcld-faq-accordion-arrow"></span>
					</div>
					<div class="qcld-faq-accordion-content" <?php echo wp_kses_post($content_style); ?>>
						<div class="qcld-faq-accordion-inner">
							<?php echo wp_kses_post(wpautop($faq['answer'])); ?>
						</div>
					</div>
				</div>
			<?php endforeach; ?>
		</div>

		<?php
		$custom_css = "
			#{$container_id} {
				--qc-faq-primary: {$atts['primary']};
				--qc-faq-header-text: {$atts['header_text']};
				--qc-faq-content-text: {$atts['content_text']};
				--qc-faq-bg: #ffffff;
				--qc-faq-header-bg: #f8fafc;
				--qc-faq-border: #e2e8f0;
				--qc-faq-radius: 12px;
			}";
		wp_add_inline_style('qcld-faq-style', $custom_css);
		return ob_get_clean();
	}
	public function enqueue_metabox_assets($hook)
	{
		if (!in_array($hook, array('post.php', 'post-new.php'), true)) {
			return;
		}
		wp_enqueue_script('jquery-ui-sortable');
		wp_enqueue_style('qcld-faq-data-admin-css', plugins_url('assets/css/faq-admin.css', dirname(__FILE__)), array(), '1.2.0');
		wp_enqueue_script('qcld-faq-data-admin-js', plugins_url('assets/js/faq-admin.js', dirname(__FILE__)), array('jquery', 'jquery-ui-sortable'), '1.2.0', true);

		// Pass contextual site settings dynamically down to jQuery for real-time JSON engine processing
		global $post;
		$default_desc = has_excerpt($post->ID) ? wp_strip_all_tags($post->post_excerpt) : wp_strip_all_tags(wp_trim_words($post->post_content, 30));

		wp_localize_script('qcld-faq-data-admin-js', 'faqMagicContext', array(
			'pageUrl' 		=> get_permalink($post->ID),
			'pageTitle' 	=> get_the_title($post->ID),
			'nonce' 		=> wp_create_nonce('seo-help'),
			'defaultDesc' 	=> $default_desc
		));
	}

	/**
	 * Enqueue assets for the settings page.
	 */
	public function enqueue_settings_assets($hook)
	{
		if (strpos($hook, 'qcld-faq-settings') === false) {
			return;
		}
		wp_enqueue_style('wp-color-picker');
		wp_enqueue_style('qcld-faq-data-admin-css', plugins_url('assets/css/faq-admin.css', dirname(__FILE__)), array(), '1.2.0');
		wp_enqueue_script('qcld-faq-settings-js', plugins_url('assets/js/faq-settings.js', dirname(__FILE__)), array('wp-color-picker', 'jquery'), '1.2.0', true);
	}
}
new Qcld_Faq_Data_Metabox();
