<?php
/**
 * Template: Dashboard (native, full parity)
 *
 * Read-only overview mirroring the Cloud dashboard view: a welcome hero, stat
 * cards, a device breakdown with bars, a top-countries table and quick action
 * links. All values come strictly from the consent-stats proxy contract
 * ({ totalConsents, optInRate, devices:{desktop,mobile,tablet}, topCountries:[{country,count}] }).
 * The proxy does NOT return pageviews or the domain, so those are never invented:
 * the domain shown is the local WordPress site host. Data covers the last 30 days.
 *
 * @var array $data JSON data from Cloud API (consent-stats response).
 * @package Biscotti_CMP
 */

defined( 'ABSPATH' ) || exit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template is included inside Biscotti_Admin::render_dynamic_page(); these are function-scoped locals, not globals.

$page_title = __( 'Dashboard', 'biscotti-cmp' );
include __DIR__ . '/partials/page-header.php';

if ( null === $data || ( is_array( $data ) && empty( $data ) && ! isset( $data['totalConsents'] ) ) ) :
	// Distinguish "still loading / no response" from a valid empty-but-present payload.
	if ( empty( $data ) ) :
		include __DIR__ . '/partials/loading-state.php';
		return;
	endif;
endif;

$total_consents = isset( $data['totalConsents'] ) ? absint( $data['totalConsents'] ) : 0;
$opt_in_rate    = isset( $data['optInRate'] ) ? floatval( $data['optInRate'] ) : 0;
$devices        = ( isset( $data['devices'] ) && is_array( $data['devices'] ) ) ? $data['devices'] : array();
$top_countries  = ( isset( $data['topCountries'] ) && is_array( $data['topCountries'] ) ) ? $data['topCountries'] : array();

$site_host = wp_parse_url( home_url(), PHP_URL_HOST );
$site_host = $site_host ? $site_host : '—';
?>

<div class="biscotti-page biscotti-page-dashboard">

	<!-- Hero -->
	<div class="biscotti-dash-hero">
		<h2>🍪 <?php esc_html_e( 'Welcome to Biscotti CMP', 'biscotti-cmp' ); ?></h2>
		<p><?php esc_html_e( 'Manage your consent banners, scan cookies, and generate legally compliant documents — all in one place.', 'biscotti-cmp' ); ?></p>
	</div>

	<p class="biscotti-dash-period description">
		<?php esc_html_e( 'Statistics for the last 30 days.', 'biscotti-cmp' ); ?>
	</p>

	<!-- Stat cards (only values the proxy actually returns + the local site host) -->
	<div class="biscotti-stats-grid">
		<?php
		Biscotti_Template_Renderer::stat_card(
			__( 'Consents', 'biscotti-cmp' ),
			number_format_i18n( $total_consents ),
			'dashicons-yes-alt'
		);
		Biscotti_Template_Renderer::stat_card(
			__( 'Opt-in Rate', 'biscotti-cmp' ),
			number_format_i18n( $opt_in_rate, 1 ) . '%',
			'dashicons-chart-pie'
		);
		Biscotti_Template_Renderer::stat_card(
			__( 'Website', 'biscotti-cmp' ),
			$site_host,
			'dashicons-admin-site-alt3'
		);
		?>
	</div>

	<div class="biscotti-two-col">

		<!-- Device breakdown -->
		<div class="biscotti-card">
			<h3><?php esc_html_e( 'Device Breakdown', 'biscotti-cmp' ); ?></h3>
			<?php
			$device_meta = array(
				'desktop' => array( 'label' => __( 'Desktop', 'biscotti-cmp' ), 'icon' => '🖥', 'color' => '#9B6B3C' ),
				'mobile'  => array( 'label' => __( 'Mobile', 'biscotti-cmp' ), 'icon' => '📱', 'color' => '#8B5A2B' ),
				'tablet'  => array( 'label' => __( 'Tablet', 'biscotti-cmp' ), 'icon' => '📋', 'color' => '#C49A6C' ),
			);
			if ( empty( $devices ) ) :
				?>
				<p class="biscotti-empty-state"><?php esc_html_e( 'No data available.', 'biscotti-cmp' ); ?></p>
				<?php
			else :
				foreach ( $device_meta as $key => $meta ) :
					$pct = isset( $devices[ $key ] ) ? max( 0, min( 100, absint( $devices[ $key ] ) ) ) : 0;
					?>
					<div class="biscotti-device-row">
						<span class="biscotti-device-name"><?php echo esc_html( $meta['icon'] . ' ' . $meta['label'] ); ?></span>
						<span class="biscotti-bar-wrap">
							<span class="biscotti-bar" style="width:<?php echo esc_attr( $pct ); ?>%;background:<?php echo esc_attr( $meta['color'] ); ?>;"></span>
						</span>
						<span class="biscotti-device-pct"><?php echo esc_html( number_format_i18n( $pct ) . '%' ); ?></span>
					</div>
					<?php
				endforeach;
			endif;
			?>
		</div>

		<!-- Top countries -->
		<div class="biscotti-card">
			<h3><?php esc_html_e( 'Top Countries', 'biscotti-cmp' ); ?></h3>
			<?php
			$country_rows = array();
			foreach ( $top_countries as $entry ) {
				$name  = isset( $entry['country'] ) && '' !== $entry['country'] ? $entry['country'] : __( 'Unknown', 'biscotti-cmp' );
				$count = isset( $entry['count'] ) ? absint( $entry['count'] ) : 0;
				$share = $total_consents > 0 ? round( ( $count / $total_consents ) * 100 ) : 0;
				$country_rows[] = array(
					'country' => $name,
					'count'   => number_format_i18n( $count ),
					'share'   => number_format_i18n( $share ) . '%',
				);
			}
			Biscotti_Template_Renderer::data_table(
				array(
					'country' => __( 'Country', 'biscotti-cmp' ),
					'count'   => __( 'Visitors', 'biscotti-cmp' ),
					'share'   => __( 'Share', 'biscotti-cmp' ),
				),
				$country_rows
			);
			?>
		</div>

	</div>

	<!-- Quick actions -->
	<div class="biscotti-card">
		<h3><?php esc_html_e( 'Quick Actions', 'biscotti-cmp' ); ?></h3>
		<div class="biscotti-quick-actions">
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=biscotti-banner' ) ); ?>" class="biscotti-action-btn">🎨 <?php esc_html_e( 'Edit Banner', 'biscotti-cmp' ); ?></a>
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=biscotti-tools' ) ); ?>" class="biscotti-action-btn">🔍 <?php esc_html_e( 'Run Scan', 'biscotti-cmp' ); ?></a>
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=biscotti-legal-wizard' ) ); ?>" class="biscotti-action-btn">📄 <?php esc_html_e( 'Legal Suite', 'biscotti-cmp' ); ?></a>
			<a href="https://app.biscotti-cmp.com" target="_blank" rel="noopener" class="biscotti-action-btn">🚀 <?php esc_html_e( 'Open Full Dashboard', 'biscotti-cmp' ); ?></a>
		</div>
	</div>

</div>
