<?php
/**
 * Sidebar info cards for the SEOvault AI admin dashboard.
 *
 * Replaces the placeholder card with a rotating pool of
 * educational cards that drive users to connect the plugin to the
 * web app and learn about its features.
 *
 * @package SEOvaultSEO
 */

namespace SEOvaultSEO\Admin;

/**
 * Class SidebarCards
 *
 * Renders a stack of info/education cards in the dashboard sidebar.
 * Cards are rotated from a weighted pool on each render. The first
 * card is always a CTA ("Connect") or status ("Connected") card
 * depending on the plugin's connection state; the remaining slots
 * are filled with feature highlight cards.
 */
class SidebarCards {

	/**
	 * Return the full pool of feature card definitions.
	 *
	 * Each card is an associative array with keys:
	 * - id           string  Unique identifier.
	 * - title        string  Card headline (translatable).
	 * - pitch        string  1-2 sentence description (translatable).
	 * - icon         string  Dashicon class name (e.g. 'dashicons-welcome-write-blog').
	 * - weight       string  Rotation priority: 'H', 'M', or 'L'.
	 * - read_more_url string|null  URL to a blog/marketing article, or null.
	 * - accent       string  CSS accent class suffix: 'primary', 'info', 'success', 'warning'.
	 *
	 * @return array<int, array<string, mixed>> Card definitions.
	 */
	private static function get_card_pool(): array {
		$base = 'https://www.seovaultai.com/blog/';

		// ── AI Writing ──────────────────────────────────────────────
		$cards[] = array(
			'id'            => 'ultra_writer',
			'title'         => __( 'Ultra Writer', 'seovault-ai' ),
			'pitch'         => __( 'Generate complete, SEO-optimized articles up to 5,000 words with 13 presets, AI research, and AI-generated images.', 'seovault-ai' ),
			'icon'          => 'dashicons-welcome-write-blog',
			'weight'        => 'H',
			'read_more_url' => $base . 'ultra-writer',
			'accent'        => 'primary',
		);
		$cards[] = array(
			'id'            => 'eeat_articles',
			'title'         => __( 'E-E-A-T Articles', 'seovault-ai' ),
			'pitch'         => __( 'Write expert-level articles with the Experience, Expertise, Authoritativeness, and Trustworthiness pipeline — 9 steps from validation to authenticity check.', 'seovault-ai' ),
			'icon'          => 'dashicons-awards',
			'weight'        => 'H',
			'read_more_url' => $base . 'eeat-articles',
			'accent'        => 'info',
		);
		$cards[] = array(
			'id'            => 'quick_ai_writer',
			'title'         => __( 'Quick AI Writer', 'seovault-ai' ),
			'pitch'         => __( 'Need content fast? Quick AI Writer generates quality articles in seconds — no pipeline setup required.', 'seovault-ai' ),
			'icon'          => 'dashicons-edit-page',
			'weight'        => 'M',
			'read_more_url' => $base . 'quick-ai-writer',
			'accent'        => 'success',
		);
		$cards[] = array(
			'id'            => 'ai_visual_director',
			'title'         => __( 'AI Visual Director', 'seovault-ai' ),
			'pitch'         => __( 'Automatically generate featured images and in-article visuals that match your brand style. Multiple ratios and formats.', 'seovault-ai' ),
			'icon'          => 'dashicons-format-image',
			'weight'        => 'M',
			'read_more_url' => $base . 'ai-visual-director',
			'accent'        => 'warning',
		);
		$cards[] = array(
			'id'            => 'custom_templates',
			'title'         => __( 'Custom Templates', 'seovault-ai' ),
			'pitch'         => __( 'Save your article structures as reusable templates with variables. Build once, generate unlimited variations.', 'seovault-ai' ),
			'icon'          => 'dashicons-layout',
			'weight'        => 'L',
			'read_more_url' => $base . 'custom-templates',
			'accent'        => 'primary',
		);
		$cards[] = array(
			'id'            => 'multilingual_writing',
			'title'         => __( '15 Languages', 'seovault-ai' ),
			'pitch'         => __( 'Write articles in 15 languages with native-quality output. Tone, perspective, and audience level all configurable.', 'seovault-ai' ),
			'icon'          => 'dashicons-translation',
			'weight'        => 'L',
			'read_more_url' => $base . 'multilingual-writing',
			'accent'        => 'info',
		);

		// ── SEO & Content Tools ─────────────────────────────────────
		$cards[] = array(
			'id'            => 'deep_analysis',
			'title'         => __( 'Deep Analysis (DAC)', 'seovault-ai' ),
			'pitch'         => __( 'Get a deep SEO content analysis with LSI keyword extraction, section architecture suggestions, and pain point exploration.', 'seovault-ai' ),
			'icon'          => 'dashicons-analytics',
			'weight'        => 'H',
			'read_more_url' => $base . 'dac-write',
			'accent'        => 'success',
		);
		$cards[] = array(
			'id'            => 'section_architect',
			'title'         => __( 'Section Architect', 'seovault-ai' ),
			'pitch'         => __( 'AI generates a complete article outline for you. Just enter your keyword — get headings, subheadings, and structure in seconds.', 'seovault-ai' ),
			'icon'          => 'dashicons-list-view',
			'weight'        => 'M',
			'read_more_url' => $base . 'section-architect',
			'accent'        => 'warning',
		);
		$cards[] = array(
			'id'            => 'ai_humanizer',
			'title'         => __( 'AI Humanizer', 'seovault-ai' ),
			'pitch'         => __( 'Make AI-generated text sound natural and human. Avoid AI detection penalties while maintaining quality.', 'seovault-ai' ),
			'icon'          => 'dashicons-format-chat',
			'weight'        => 'M',
			'read_more_url' => $base . 'ai-humanizer',
			'accent'        => 'primary',
		);
		$cards[] = array(
			'id'            => 'inspire_me',
			'title'         => __( 'Inspire Me', 'seovault-ai' ),
			'pitch'         => __( 'Stuck for ideas? AI suggests creative angles and approaches for your next article based on your niche.', 'seovault-ai' ),
			'icon'          => 'dashicons-lightbulb',
			'weight'        => 'L',
			'read_more_url' => $base . 'inspire-me',
			'accent'        => 'info',
		);
		$cards[] = array(
			'id'            => 'pain_explorer',
			'title'         => __( 'Pain Explorer', 'seovault-ai' ),
			'pitch'         => __( 'Discover what your audience is struggling with. AI analyzes search intent and surfaces pain points to target.', 'seovault-ai' ),
			'icon'          => 'dashicons-search',
			'weight'        => 'L',
			'read_more_url' => $base . 'pain-explorer',
			'accent'        => 'success',
		);
		$cards[] = array(
			'id'            => 'ai_faq_generator',
			'title'         => __( 'AI FAQ Generator', 'seovault-ai' ),
			'pitch'         => __( 'Automatically generate FAQ sections for your articles. Boost your chances of appearing in AI answers and featured snippets.', 'seovault-ai' ),
			'icon'          => 'dashicons-format-status',
			'weight'        => 'M',
			'read_more_url' => $base . 'ai-faq-generator',
			'accent'        => 'warning',
		);
		$cards[] = array(
			'id'            => 'tldr_summary',
			'title'         => __( 'TL;DR Summary', 'seovault-ai' ),
			'pitch'         => __( 'Auto-generate concise summaries for your long-form content. Great for readability and AI citation readiness.', 'seovault-ai' ),
			'icon'          => 'dashicons-text',
			'weight'        => 'L',
			'read_more_url' => $base . 'tldr-summary',
			'accent'        => 'primary',
		);
		$cards[] = array(
			'id'            => 'citation_link_building',
			'title'         => __( 'Citation/Link Building', 'seovault-ai' ),
			'pitch'         => __( 'AI finds and suggests authoritative external sources to cite in your articles. Build trust and credibility with every post.', 'seovault-ai' ),
			'icon'          => 'dashicons-admin-links',
			'weight'        => 'M',
			'read_more_url' => $base . 'citation-link-building',
			'accent'        => 'info',
		);
		$cards[] = array(
			'id'            => 'seo_helper_audit',
			'title'         => __( 'SEO Helper Audit', 'seovault-ai' ),
			'pitch'         => __( 'Real-time SEO audit checklist with focus keyword tracking. Score your content as you write.', 'seovault-ai' ),
			'icon'          => 'dashicons-clipboard',
			'weight'        => 'M',
			'read_more_url' => $base . 'seo-helper',
			'accent'        => 'success',
		);

		// ── AI Visibility ───────────────────────────────────────────
		$cards[] = array(
			'id'            => 'ai_visibility_score',
			'title'         => __( 'AI Visibility Score', 'seovault-ai' ),
			'pitch'         => __( 'See how AI assistants like ChatGPT and Perplexity perceive your content. Get a readiness score with actionable fixes.', 'seovault-ai' ),
			'icon'          => 'dashicons-visibility',
			'weight'        => 'H',
			'read_more_url' => $base . 'ai-visibility',
			'accent'        => 'warning',
		);
		$cards[] = array(
			'id'            => 'citation_simulator',
			'title'         => __( 'Citation Simulator', 'seovault-ai' ),
			'pitch'         => __( 'Simulate how AI models would cite your pages. Identify content gaps before they cost you traffic.', 'seovault-ai' ),
			'icon'          => 'dashicons-search',
			'weight'        => 'H',
			'read_more_url' => $base . 'citation-simulator',
			'accent'        => 'primary',
		);
		$cards[] = array(
			'id'            => 'crawler_signals',
			'title'         => __( 'Crawler Signals', 'seovault-ai' ),
			'pitch'         => __( 'See which AI crawlers (GPTBot, ClaudeBot, PerplexityBot, etc.) are visiting your site. Track retrieval vs training visits by URL.', 'seovault-ai' ),
			'icon'          => 'dashicons-buddicons-buddypress-logo',
			'weight'        => 'M',
			'read_more_url' => $base . 'crawler-signals',
			'accent'        => 'info',
		);
		$cards[] = array(
			'id'            => 'ai_referral_signals',
			'title'         => __( 'AI Referral Signals', 'seovault-ai' ),
			'pitch'         => __( 'Track AI bot traffic from Google Analytics 4. See which posts get cited and which AI sources send you visitors.', 'seovault-ai' ),
			'icon'          => 'dashicons-chart-line',
			'weight'        => 'M',
			'read_more_url' => $base . 'ai-referral-signals',
			'accent'        => 'success',
		);
		$cards[] = array(
			'id'            => 'google_search_signals',
			'title'         => __( 'Google Search Signals', 'seovault-ai' ),
			'pitch'         => __( 'Import Google Search Console data to see top pages, query insights, and opportunity pages for AI optimization.', 'seovault-ai' ),
			'icon'          => 'dashicons-google',
			'weight'        => 'M',
			'read_more_url' => $base . 'google-search-signals',
			'accent'        => 'warning',
		);
		$cards[] = array(
			'id'            => 'schema_readiness',
			'title'         => __( 'Schema Readiness', 'seovault-ai' ),
			'pitch'         => __( 'Detect schema types on your pages, find conflicts, and safely inject missing structured data for AI comprehension.', 'seovault-ai' ),
			'icon'          => 'dashicons-code-standards',
			'weight'        => 'L',
			'read_more_url' => $base . 'schema-readiness',
			'accent'        => 'primary',
		);
		$cards[] = array(
			'id'            => 'robots_txt_ai',
			'title'         => __( 'Robots.txt for AI', 'seovault-ai' ),
			'pitch'         => __( 'Analyze your robots.txt for AI bot access. See which crawlers are allowed or blocked, and apply fixes with one click.', 'seovault-ai' ),
			'icon'          => 'dashicons-shield',
			'weight'        => 'L',
			'read_more_url' => $base . 'robots-txt-ai',
			'accent'        => 'info',
		);
		$cards[] = array(
			'id'            => 'llms_txt_publishing',
			'title'         => __( 'llms.txt Publishing', 'seovault-ai' ),
			'pitch'         => __( 'Publish and manage your llms.txt file directly from the web app. Control what AI models know about your site.', 'seovault-ai' ),
			'icon'          => 'dashicons-media-text',
			'weight'        => 'L',
			'read_more_url' => $base . 'llms-txt',
			'accent'        => 'success',
		);

		// ── Link Management ─────────────────────────────────────────
		$cards[] = array(
			'id'            => 'autolinks',
			'title'         => __( 'Autolinks', 'seovault-ai' ),
			'pitch'         => __( 'AI-powered internal linking that finds the best link opportunities across your entire site and inserts them automatically.', 'seovault-ai' ),
			'icon'          => 'dashicons-admin-links',
			'weight'        => 'H',
			'read_more_url' => $base . 'autolinks',
			'accent'        => 'warning',
		);
		$cards[] = array(
			'id'            => 'broken_link_checker',
			'title'         => __( 'Broken Link Checker', 'seovault-ai' ),
			'pitch'         => __( 'Scan your entire WordPress site for broken links, redirects, and blocked resources. Filter by status type.', 'seovault-ai' ),
			'icon'          => 'dashicons-warning',
			'weight'        => 'M',
			'read_more_url' => $base . 'link-checker',
			'accent'        => 'primary',
		);

		// ── Site & Team Management ──────────────────────────────────
		$cards[] = array(
			'id'            => 'multi_site_management',
			'title'         => __( 'Multi-Site Management', 'seovault-ai' ),
			'pitch'         => __( 'Connect up to 25 WordPress sites to one workspace. Switch between sites, manage SEO, and generate content — all from one dashboard.', 'seovault-ai' ),
			'icon'          => 'dashicons-admin-multisite',
			'weight'        => 'H',
			'read_more_url' => $base . 'multi-site-management',
			'accent'        => 'success',
		);
		$cards[] = array(
			'id'            => 'team_workspaces',
			'title'         => __( 'Team Workspaces', 'seovault-ai' ),
			'pitch'         => __( 'Invite team members with roles (admin, editor, viewer). Collaborate on SEO and content generation across your organization.', 'seovault-ai' ),
			'icon'          => 'dashicons-groups',
			'weight'        => 'M',
			'read_more_url' => $base . 'team-workspaces',
			'accent'        => 'warning',
		);
		$cards[] = array(
			'id'            => 'brand_kits',
			'title'         => __( 'Brand Kits', 'seovault-ai' ),
			'pitch'         => __( 'Define your brand voice, tone, persona, and style DNA. AI-generated content will match your brand automatically.', 'seovault-ai' ),
			'icon'          => 'dashicons-palmtree',
			'weight'        => 'M',
			'read_more_url' => $base . 'brand-kits',
			'accent'        => 'primary',
		);
		$cards[] = array(
			'id'            => 'google_analytics_connect',
			'title'         => __( 'Google Analytics Connect', 'seovault-ai' ),
			'pitch'         => __( 'Connect Google Analytics 4 to unlock AI referral signals, search performance data, and crawler insights.', 'seovault-ai' ),
			'icon'          => 'dashicons-chart-pie',
			'weight'        => 'L',
			'read_more_url' => $base . 'google-analytics-connect',
			'accent'        => 'info',
		);

		return $cards;
	}

	/**
	 * Weight mapping for card rotation priority.
	 *
	 * 'H' = 3, 'M' = 2, 'L' = 1. Higher weight means the card is
	 * more likely to appear near the top of the shuffled result.
	 */
	private const WEIGHT_MAP = array(
		'H' => 3,
		'M' => 2,
		'L' => 1,
	);

	/**
	 * Pick a subset of cards from the pool using a weighted shuffle.
	 *
	 * Each card is assigned a sort key of `wp_rand() / PHP_INT_MAX / weight`,
	 * then the pool is sorted ascending by that key. Higher-weight cards
	 * produce smaller keys on average, so they land near the top more often.
	 * No card appears more than once.
	 *
	 * @param array $pool  The full card pool.
	 * @param int   $count Number of cards to pick.
	 * @return array<int, array<string, mixed>> Picked cards.
	 */
	private static function pick_cards( array $pool, int $count ): array {
		if ( empty( $pool ) || $count <= 0 ) {
			return array();
		}

		// Build a weighted shuffle: assign each card a random key
		// divided by its weight, then sort ascending.
		$scored = array();
		foreach ( $pool as $card ) {
			$weight   = self::WEIGHT_MAP[ $card['weight'] ] ?? 1;
			$scored[] = array(
				'card'  => $card,
				'score' => ( wp_rand() / (float) PHP_INT_MAX ) / $weight,
			);
		}

		usort(
			$scored,
			static function ( $a, $b ) {
				return $a['score'] <=> $b['score'];
			}
		);

		$shuffled = array_column( $scored, 'card' );

		if ( $count >= count( $shuffled ) ) {
			return $shuffled;
		}

		return array_slice( $shuffled, 0, $count );
	}

	/**
	 * Web app URL for the primary CTA / connect button.
	 */
	private const WEB_APP_URL = 'https://app.seovaultai.com/workspace';

	/**
	 * Web app billing URL.
	 */
	private const WEB_APP_BILLING_URL = 'https://app.seovaultai.com/billing';

	/**
	 * Marketing / learn-more placeholder URL.
	 */
	private const LEARN_MORE_URL = 'https://www.seovaultai.com/features';

	/**
	 * Render the full sidebar card stack.
	 *
	 * Outputs the CTA/status card first, followed by feature cards
	 * selected via pick_cards(). All output is properly escaped.
	 *
	 * @param bool $is_connected Whether the plugin is connected to the web app.
	 * @return void
	 */
	public static function render( bool $is_connected ): void {
		if ( ! $is_connected ) {
			self::render_cta_card();
		} else {
			self::render_connected_card();
		}

		$pool = self::get_card_pool();
		$deck = self::pick_cards( $pool, count( $pool ) );

		$card_count = count( $deck );
		?>
		<div class="seovaultseo-card-deck" data-card-count="<?php echo esc_attr( (string) $card_count ); ?>">
			<?php
			foreach ( $deck as $index => $card ) {
				self::render_card( $card, $index );
			}
			?>
			<div class="seovaultseo-card-deck-dots"></div>
		</div>
		<?php
	}

	/**
	 * Render a single feature card from a definition array.
	 *
	 * Outputs the HTML structure with icon, title, pitch, and action
	 * buttons. All output is properly escaped.
	 *
	 * @param array    $card  Card definition array.
	 * @param int|null $index Optional position of the card within the deck.
	 * @return void
	 */
	private static function render_card( array $card, ?int $index = null ): void {
		$accent  = isset( $card['accent'] ) ? $card['accent'] : 'primary';
		$icon    = isset( $card['icon'] ) ? $card['icon'] : 'dashicons-info';
		$title   = isset( $card['title'] ) ? $card['title'] : '';
		$pitch   = isset( $card['pitch'] ) ? $card['pitch'] : '';
		$url     = isset( $card['read_more_url'] ) ? $card['read_more_url'] : null;
		$card_id = isset( $card['id'] ) ? $card['id'] : '';
		?>
		<div class="seovaultseo-info-card seovaultseo-card-accent-<?php echo esc_attr( $accent ); ?>"
			<?php
			if ( null !== $index ) :
				?>
				data-card-index="<?php echo esc_attr( (string) $index ); ?>"<?php endif; ?>
			<?php
			if ( '' !== $card_id ) :
				?>
				data-card-id="<?php echo esc_attr( $card_id ); ?>"<?php endif; ?>>
			<div class="seovaultseo-card-icon">
				<span class="dashicons <?php echo esc_attr( $icon ); ?>"></span>
			</div>
			<h3 class="seovaultseo-card-title"><?php echo esc_html( $title ); ?></h3>
			<p class="seovaultseo-card-desc"><?php echo esc_html( $pitch ); ?></p>
			<div class="seovaultseo-card-actions">
				<?php if ( null !== $url && '' !== $url ) : ?>
					<a href="<?php echo esc_url( $url ); ?>"
						class="seovaultseo-card-readmore"
						target="_blank" rel="noopener noreferrer">
						<?php esc_html_e( 'Read More', 'seovault-ai' ); ?> <span class="dashicons dashicons-arrow-right-alt"></span>
					</a>
				<?php endif; ?>
				<a href="<?php echo esc_url( self::WEB_APP_URL ); ?>"
					class="seovaultseo-card-tryit"
					target="_blank" rel="noopener noreferrer">
					<?php esc_html_e( 'Try in Web App', 'seovault-ai' ); ?> <span aria-hidden="true">→</span>
				</a>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the primary CTA card (shown when not connected).
	 *
	 * Headline, subtext, primary "Connect" button, and a
	 * "Learn More" secondary link.
	 *
	 * @return void
	 */
	private static function render_cta_card(): void {
		?>
		<div class="seovaultseo-info-card seovaultseo-card-accent-primary seovaultseo-card-cta">
			<div class="seovaultseo-card-icon">
				<span class="dashicons dashicons-admin-plugins"></span>
			</div>
			<h3 class="seovaultseo-card-title"><?php esc_html_e( 'Connect to SEOvault AI', 'seovault-ai' ); ?></h3>
			<p class="seovaultseo-card-desc"><?php esc_html_e( 'Use 30+ cloud-based AI SEO tools, AI article generation, and AI visibility monitoring.', 'seovault-ai' ); ?></p>
			<div class="seovaultseo-card-actions">
				<a href="<?php echo esc_url( self::WEB_APP_URL ); ?>"
					class="button button-primary seovaultseo-card-btn"
					target="_blank" rel="noopener noreferrer">
					<?php esc_html_e( 'Connect', 'seovault-ai' ); ?>
				</a>
				<a href="<?php echo esc_url( self::LEARN_MORE_URL ); ?>"
					class="seovaultseo-card-readmore"
					target="_blank" rel="noopener noreferrer">
					<?php esc_html_e( 'Learn More', 'seovault-ai' ); ?> <span class="dashicons dashicons-external"></span>
				</a>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the compact connected status card (shown when connected).
	 *
	 * Green checkmark, status text, "Open Web App" and "Billing" buttons.
	 *
	 * @return void
	 */
	private static function render_connected_card(): void {
		?>
		<div class="seovaultseo-info-card seovaultseo-card-accent-success seovaultseo-card-connected">
			<div class="seovaultseo-card-icon seovaultseo-card-icon-connected">
				<span class="dashicons dashicons-yes-alt"></span>
			</div>
			<h3 class="seovaultseo-card-title"><?php esc_html_e( 'Connected to SEOvault AI', 'seovault-ai' ); ?></h3>
			<p class="seovaultseo-card-desc"><?php esc_html_e( 'Manage your optional web-service account and usage.', 'seovault-ai' ); ?></p>
			<div class="seovaultseo-card-actions">
				<a href="<?php echo esc_url( self::WEB_APP_URL ); ?>"
					class="button button-primary seovaultseo-card-btn"
					target="_blank" rel="noopener noreferrer">
					<?php esc_html_e( 'Open Web App', 'seovault-ai' ); ?>
				</a>
				<a href="<?php echo esc_url( self::WEB_APP_BILLING_URL ); ?>"
					class="button seovaultseo-card-btn-secondary"
					target="_blank" rel="noopener noreferrer">
					<?php esc_html_e( 'Billing', 'seovault-ai' ); ?>
				</a>
			</div>
		</div>
		<?php
	}
}
