<?php
/**
 * Post Link Meta Box.
 *
 * Sidebar widget on the post-edit screen showing this post's internal-link
 * health at a glance: how many internal links point INTO this post, how many
 * point OUT, broken-link count for this post, and a one-click "Fix this in
 * Link Architect" affordance if the post is orphaned.
 *
 * READ-ONLY against the cached Link Health report. If no scan has run yet, we
 * show a small prompt to run one — we do NOT trigger a full-site scan from
 * the editor, which would be unacceptable on bigger sites. This keeps the
 * post-edit screen fast under all conditions.
 *
 * @package Platform\Helm\Modules\Link_Health
 */

declare( strict_types = 1 );

namespace Platform\Helm\Modules\Link_Health;

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

final class PostLinkMetaBox {

	private const META_BOX_ID = 'platform_helm_post_link_summary';

	public function __construct( private HealthAnalyzer $analyzer ) {}

	public function register_hooks(): void {
		add_action( 'add_meta_boxes', [ $this, 'register_meta_box' ] );
	}

	public function register_meta_box(): void {
		$types = $this->summarised_post_types();
		foreach ( $types as $type ) {
			add_meta_box(
				self::META_BOX_ID,
				__( '🔗 Link Summary', 'platform-helm' ),
				[ $this, 'render' ],
				$type,
				'side',
				'default'
			);
		}
	}

	public function render( \WP_Post $post ): void {
		// Only meaningful for published posts — drafts have no scan data.
		if ( 'publish' !== $post->post_status ) {
			$this->render_unpublished();
			return;
		}

		$summary = $this->analyzer->get_post_summary( (int) $post->ID );
		if ( null === $summary ) {
			$this->render_no_scan();
			return;
		}

		$this->render_summary( (int) $post->ID, $summary );
	}

	/**
	 * @param array{inbound:int,outbound:int,broken:int,is_orphan:bool,generated_at:int} $summary
	 */
	private function render_summary( int $post_id, array $summary ): void {
		$age_text = $summary['generated_at'] > 0
			? sprintf(
				/* translators: %s: human-readable time difference */
				__( 'Last scanned %s ago', 'platform-helm' ),
				human_time_diff( $summary['generated_at'], time() )
			)
			: '';
		?>
		<style>
		.phelm-pls-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:6px;margin:6px 0;}
		.phelm-pls-stat{background:#F7F9FC;border:1px solid #E5EAF2;border-radius:6px;padding:8px 6px;text-align:center;}
		.phelm-pls-stat-value{font-size:18px;font-weight:700;color:#0047AB;line-height:1.1;font-variant-numeric:tabular-nums;}
		.phelm-pls-stat-label{font-size:10px;color:#5C6B82;text-transform:uppercase;letter-spacing:.3px;margin-top:2px;font-weight:600;}
		.phelm-pls-stat--warn .phelm-pls-stat-value{color:#B85C00;}
		.phelm-pls-stat--warn{background:#FFF8EA;border-color:#FFE5B0;}
		.phelm-pls-orphan{margin-top:10px;padding:8px 10px;background:#FFF8EA;border:1px solid #FFE5B0;border-radius:6px;font-size:12px;color:#5C4400;}
		.phelm-pls-orphan a{font-weight:600;color:#0047AB;text-decoration:none;}
		.phelm-pls-orphan a:hover{text-decoration:underline;}
		.phelm-pls-meta{font-size:10.5px;color:#8A95A8;margin-top:8px;text-align:right;}
		.phelm-pls-empty{font-size:12px;color:#5C6B82;margin:6px 0;line-height:1.5;}
		.phelm-pls-empty a{color:#0047AB;font-weight:600;text-decoration:none;}
		</style>
		<div class="phelm-pls">
			<div class="phelm-pls-grid">
				<div class="phelm-pls-stat">
					<div class="phelm-pls-stat-value"><?php echo esc_html( number_format_i18n( $summary['inbound'] ) ); ?></div>
					<div class="phelm-pls-stat-label"><?php esc_html_e( 'In', 'platform-helm' ); ?></div>
				</div>
				<div class="phelm-pls-stat">
					<div class="phelm-pls-stat-value"><?php echo esc_html( number_format_i18n( $summary['outbound'] ) ); ?></div>
					<div class="phelm-pls-stat-label"><?php esc_html_e( 'Out', 'platform-helm' ); ?></div>
				</div>
				<div class="phelm-pls-stat <?php echo $summary['broken'] > 0 ? 'phelm-pls-stat--warn' : ''; ?>">
					<div class="phelm-pls-stat-value"><?php echo esc_html( number_format_i18n( $summary['broken'] ) ); ?></div>
					<div class="phelm-pls-stat-label"><?php esc_html_e( 'Broken', 'platform-helm' ); ?></div>
				</div>
			</div>

			<?php if ( $summary['is_orphan'] ) :
				$fix_url = $this->fix_in_architect_url( $post_id );
				?>
				<div class="phelm-pls-orphan">
					<strong><?php esc_html_e( 'Orphaned.', 'platform-helm' ); ?></strong>
					<?php esc_html_e( 'No other posts link to this one.', 'platform-helm' ); ?>
					<?php if ( '' !== $fix_url ) : ?>
						<br><a href="<?php echo esc_url( $fix_url ); ?>"><?php esc_html_e( 'Fix this in Link Architect →', 'platform-helm' ); ?></a>
					<?php endif; ?>
				</div>
			<?php endif; ?>

			<?php if ( '' !== $age_text ) : ?>
				<div class="phelm-pls-meta"><?php echo esc_html( $age_text ); ?></div>
			<?php endif; ?>
		</div>
		<?php
	}

	private function render_no_scan(): void {
		$scan_url = admin_url( 'admin.php?page=' . HealthPage::PAGE_SLUG );
		?>
		<p class="phelm-pls-empty">
			<?php esc_html_e( 'No link-health scan yet.', 'platform-helm' ); ?>
			<a href="<?php echo esc_url( $scan_url ); ?>"><?php esc_html_e( 'Run a scan →', 'platform-helm' ); ?></a>
		</p>
		<?php
	}

	private function render_unpublished(): void {
		?>
		<p class="phelm-pls-empty" style="font-size:12px;color:#5C6B82;margin:6px 0;">
			<?php esc_html_e( 'Link summary is available once this post is published.', 'platform-helm' ); ?>
		</p>
		<?php
	}

	/**
	 * Build the "Fix this in Link Architect" deep link for an orphan post.
	 * Returns empty if Architect is disabled or the post has no permalink.
	 */
	private function fix_in_architect_url( int $post_id ): string {
		$opts    = get_option( 'platform_helm_settings', [] );
		$enabled = is_array( $opts ) && ! empty( $opts['module_link_architect'] );
		if ( ! $enabled ) {
			return '';
		}
		$permalink = get_permalink( $post_id );
		if ( ! $permalink ) {
			return '';
		}
		return add_query_arg(
			[ 'prefill_url' => rawurlencode( $permalink ) ],
			admin_url( 'admin.php?page=platform-helm-link-architect' )
		);
	}

	/**
	 * Which post types get the meta box. Filterable, defaults to the same
	 * types the Health Analyzer scans (post + page).
	 *
	 * @return string[]
	 */
	private function summarised_post_types(): array {
		/** Filter: which post types show the per-post Link Summary meta box. */
		$types = apply_filters( 'platform_helm_post_link_summary_types', [ 'post', 'page' ] );
		return is_array( $types ) ? array_values( array_filter( $types, 'is_string' ) ) : [ 'post' ];
	}
}
