<?php
/**
 * Dashboard page — schema health at a glance
 *
 * Single screen, no tabs: status strip (what the site is emitting),
 * health summary, needs-attention checks, passing checks.
 * All content is driven by BW_Schema_Service_Health — the dashboard
 * renders findings, it does not define tasks of its own.
 *
 * Styles: admin/css/dashboard.css (enqueued by BW_Schema_Admin).
 *
 * @package BW_Schema
 * @since 3.1.0
 */

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

class BW_Schema_Page_Dashboard extends BW_Schema_Page {

	/**
	 * Initialize page properties
	 *
	 * @return void
	 */
	protected function init() {
		$this->slug        = 'bw-schema';
		$this->title       = __( 'Solomon Schema', 'bw-schema' );
		$this->icon        = 'dashicons-chart-bar';
		$this->parent_slug = null; // Top-level menu
	}

	/**
	 * Render page content
	 *
	 * @return void
	 */
	protected function render() {
		$checks  = BW_Schema_Service_Health::run_checks();
		$summary = BW_Schema_Service_Health::get_summary();

		$attention = array_values( array_filter( $checks, function ( $c ) {
			return ! $c['passing'];
		} ) );
		$passing   = array_values( array_filter( $checks, function ( $c ) {
			return $c['passing'];
		} ) );

		echo '<p class="bws-tagline">' . esc_html__( 'Schema Markup Made Simple', 'bw-schema' ) . '</p>';

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display-only flag from the wizard redirect
		if ( isset( $_GET['bws-setup'] ) && 'done' === $_GET['bws-setup'] ) {
			echo '<div class="notice notice-success"><p>';
			esc_html_e( 'Setup complete! Your configuration is live — the health checks below reflect it.', 'bw-schema' );
			echo '</p></div>';
		}

		$this->render_status_strip();
		$this->render_health_summary( $summary );
		$this->render_attention_checks( $attention );
		$this->render_passing_checks( $passing, empty( $attention ) );
		$this->render_footer();
	}

	/**
	 * Render the status strip: is schema being emitted, and what
	 *
	 * @return void
	 */
	private function render_status_strip() {
		$active   = false;
		$emitting = array();

		try {
			$schema = BW_Schema_Cache::get_schema();
			$active = ! empty( $schema );

			if ( $active ) {
				$emitting[] = $schema['@type'] ?? 'Organization';
			}
		} catch ( Throwable $e ) {
			$active = false;
		}

		if ( $active ) {
			$team_count = BW_Schema_Service_People::get_team_member_count();
			if ( $team_count > 0 ) {
				/* translators: %d: number of team members */
				$emitting[] = sprintf( __( 'Person ×%d', 'bw-schema' ), $team_count );
			}
			if ( count( BW_Schema_Service_Content::get_article_post_types() ) > 0 ) {
				$emitting[] = __( 'Articles', 'bw-schema' );
			}
			if ( BW_Schema_Service_Content::is_breadcrumbs_enabled() ) {
				$emitting[] = __( 'Breadcrumbs', 'bw-schema' );
			}
		}

		$test_url = 'https://validator.schema.org/#url=' . rawurlencode( home_url( '/' ) );
		?>
		<div class="bws-card bws-status-strip">
			<div class="bws-status-main">
				<span class="bws-status-dot <?php echo $active ? 'is-active' : 'is-inactive'; ?>"></span>
				<span class="bws-status-label">
					<?php echo $active
						? esc_html__( 'Schema output: Active', 'bw-schema' )
						: esc_html__( 'Schema output: Inactive', 'bw-schema' ); ?>
				</span>
				<?php if ( ! empty( $emitting ) ) : ?>
					<span class="bws-status-emitting">
						<?php
						printf(
							/* translators: %s: list of schema types being emitted */
							esc_html__( 'Emitting: %s', 'bw-schema' ),
							esc_html( implode( ' · ', $emitting ) )
						);
						?>
					</span>
				<?php else : ?>
					<span class="bws-status-emitting">
						<?php esc_html_e( 'Complete your organization profile to start emitting schema.', 'bw-schema' ); ?>
					</span>
				<?php endif; ?>
			</div>
			<a class="button" href="<?php echo esc_url( $test_url ); ?>" target="_blank" rel="noopener noreferrer">
				<?php esc_html_e( 'Validate with Schema.org', 'bw-schema' ); ?>
				<span aria-hidden="true">↗</span>
			</a>
		</div>
		<?php
	}

	/**
	 * Render the health summary bar
	 *
	 * @param array $summary Summary from the health service
	 * @return void
	 */
	private function render_health_summary( $summary ) {
		$all_passing = ( $summary['passing'] === $summary['total'] );
		?>
		<div class="bws-health-summary">
			<span class="bws-health-label">
				<?php
				printf(
					/* translators: 1: passing count, 2: total count */
					esc_html__( 'Site health: %1$s of %2$s checks passing', 'bw-schema' ),
					'<strong>' . esc_html( $summary['passing'] ) . '</strong>',
					esc_html( $summary['total'] )
				);
				?>
			</span>
			<span class="bws-progress" role="progressbar"
				aria-valuenow="<?php echo esc_attr( round( $summary['percentage'] ) ); ?>"
				aria-valuemin="0" aria-valuemax="100">
				<span class="bws-progress-fill <?php echo $all_passing ? 'is-complete' : ''; ?>"
					style="width: <?php echo esc_attr( round( $summary['percentage'] ) ); ?>%"></span>
			</span>
		</div>
		<?php
	}

	/**
	 * Render the needs-attention check list
	 *
	 * @param array $attention Failing checks
	 * @return void
	 */
	private function render_attention_checks( $attention ) {
		if ( empty( $attention ) ) {
			?>
			<div class="bws-card bws-all-clear">
				<span class="bws-all-clear-icon" aria-hidden="true">✓</span>
				<div>
					<strong><?php esc_html_e( 'All checks passing', 'bw-schema' ); ?></strong>
					<p><?php esc_html_e( 'Your schema setup is complete. New checks appear here automatically when content changes introduce gaps.', 'bw-schema' ); ?></p>
				</div>
			</div>
			<?php
			return;
		}
		?>
		<h2 class="bws-section-title"><?php esc_html_e( 'Needs attention', 'bw-schema' ); ?></h2>
		<div class="bws-checks">
			<?php foreach ( $attention as $check ) : ?>
				<?php $this->render_check_row( $check ); ?>
			<?php endforeach; ?>
		</div>
		<?php
	}

	/**
	 * Render the passing check list (collapsible)
	 *
	 * @param array $passing  Passing checks
	 * @param bool  $expanded Whether to expand by default
	 * @return void
	 */
	private function render_passing_checks( $passing, $expanded ) {
		if ( empty( $passing ) ) {
			return;
		}
		?>
		<details class="bws-passing" <?php echo $expanded ? 'open' : ''; ?>>
			<summary>
				<?php
				printf(
					/* translators: %d: number of passing checks */
					esc_html( _n( 'Passing check (%d)', 'Passing checks (%d)', count( $passing ), 'bw-schema' ) ),
					count( $passing )
				);
				?>
			</summary>
			<div class="bws-checks">
				<?php foreach ( $passing as $check ) : ?>
					<?php $this->render_check_row( $check ); ?>
				<?php endforeach; ?>
			</div>
		</details>
		<?php
	}

	/**
	 * Render one check row
	 *
	 * @param array $check Check result from the health service
	 * @return void
	 */
	private function render_check_row( $check ) {
		$state = $check['passing'] ? 'pass' : 'warn';
		?>
		<a class="bws-check is-<?php echo esc_attr( $state ); ?>" href="<?php echo esc_url( $check['link'] ); ?>">
			<span class="bws-check-icon" aria-hidden="true"><?php echo $check['passing'] ? '✓' : '!'; ?></span>
			<span class="bws-check-body">
				<span class="bws-check-title"><?php echo esc_html( $check['title'] ); ?></span>
				<span class="bws-check-detail"><?php echo esc_html( $check['detail'] ); ?></span>
			</span>
			<?php if ( ! $check['passing'] ) : ?>
				<span class="bws-badge bws-badge-<?php echo esc_attr( $check['priority'] ); ?>">
					<?php echo esc_html( $this->priority_label( $check['priority'] ) ); ?>
				</span>
				<span class="bws-check-effort"><?php echo esc_html( $check['effort'] ); ?></span>
			<?php endif; ?>
			<?php if ( ! empty( $check['progress'] ) ) : ?>
				<span class="bws-check-progress"><?php echo esc_html( $check['progress'] ); ?></span>
			<?php endif; ?>
			<span class="bws-check-go" aria-hidden="true">→</span>
		</a>
		<?php
	}

	/**
	 * Translated label for a priority slug
	 *
	 * @param string $priority high|medium|low
	 * @return string
	 */
	private function priority_label( $priority ) {
		switch ( $priority ) {
			case 'high':
				return __( 'High', 'bw-schema' );
			case 'medium':
				return __( 'Medium', 'bw-schema' );
			default:
				return __( 'Low', 'bw-schema' );
		}
	}

	/**
	 * Render the dashboard footer
	 *
	 * @return void
	 */
	private function render_footer() {
		?>
		<p class="bws-footer">
			<strong>Solomon Schema</strong> v<?php echo esc_html( BW_SCHEMA_VERSION ); ?>
			· <a href="https://bowden.works" target="_blank" rel="noopener noreferrer">Bowden Works</a>
			· <a href="<?php echo esc_url( admin_url( 'admin.php?page=bw-schema-help' ) ); ?>"><?php esc_html_e( 'Documentation', 'bw-schema' ); ?></a>
		</p>
		<?php
	}
}
