<?php
/**
 * Impact Map.
 *
 * @package Noesia_Commerce_Suite
 */

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

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- View templates receive local variables from their renderer.
$snapshot  = isset( $snapshot ) && is_array( $snapshot ) ? $snapshot : array();
$areas     = isset( $snapshot['areas'] ) && is_array( $snapshot['areas'] ) ? $snapshot['areas'] : array();
$settings  = isset( $settings ) && is_array( $settings ) ? $settings : Noesia_CS_Settings::get_all();
$style     = $settings['impact_map_style'] ?? 'noesia_glass';
if ( 'map' === $style ) {
	$style = 'noesia_glass';
}
$style               = in_array( $style, array( 'noesia_glass', 'dark_map', 'glass', 'compact' ), true ) ? $style : 'noesia_glass';
$size                = in_array( $settings['impact_map_background_size'] ?? 'medium', array( 'small', 'medium', 'large' ), true ) ? $settings['impact_map_background_size'] : 'medium';
$limit               = max( 1, absint( $settings['impact_map_max_visible_areas'] ?? 10 ) );
$areas               = array_slice( $areas, 0, $limit );
$eyebrow             = ! empty( $settings['impact_map_public_eyebrow'] ) ? sanitize_text_field( $settings['impact_map_public_eyebrow'] ) : __( 'Privacy-safe impact snapshot', 'noesia-commerce-suite' );
$title               = ! empty( $settings['impact_map_public_title'] ) ? sanitize_text_field( $settings['impact_map_public_title'] ) : __( 'Our Store Impact', 'noesia-commerce-suite' );
$subtitle            = ! empty( $settings['impact_map_public_subtitle'] ) ? sanitize_text_field( $settings['impact_map_public_subtitle'] ) : __( 'Privacy-safe delivery reach and product activity from verified Woo orders.', 'noesia-commerce-suite' );
$dark_map_image_url  = '';
if ( 'dark_map' === $style && defined( 'NOESIA_CS_PATH' ) && defined( 'NOESIA_CS_URL' ) ) {
	foreach ( array( 'webp', 'jpg', 'jpeg', 'png' ) as $image_extension ) {
		$image_relative_path = 'assets/images/impact-map/world-map-dark.' . $image_extension;
		if ( file_exists( NOESIA_CS_PATH . $image_relative_path ) ) {
			$dark_map_image_url = NOESIA_CS_URL . $image_relative_path;
			break;
		}
	}
}
$wrapper_classes = 'noesia-cs-impact-map noesia-cs-impact-map--' . $style . ' noesia-cs-impact-map--' . $size;
if ( $dark_map_image_url ) {
	$wrapper_classes .= ' noesia-cs-impact-map--has-map-image';
}

$total_orders    = 0;
$total_products  = 0;
foreach ( $areas as $area ) {
	$total_orders   += absint( $area['orders'] ?? 0 );
	$total_products += absint( $area['products'] ?? 0 );
}

if ( ! function_exists( 'noesia_cs_public_country_flag' ) ) {
	/**
	 * Handles the related plugin operation.
	 */
	function noesia_cs_public_country_flag( $country_code ) {
		$country_code = strtoupper( preg_replace( '/[^A-Z]/', '', (string) $country_code ) );
		if ( 2 !== strlen( $country_code ) ) {
			return '◇';
		}
		$flag = '';
		for ( $i = 0; $i < 2; $i++ ) {
			$flag .= html_entity_decode( '&#' . ( 127397 + ord( $country_code[ $i ] ) ) . ';', ENT_NOQUOTES, 'UTF-8' );
		}
		return $flag;
	}
}

if ( ! function_exists( 'noesia_cs_public_area_label' ) ) {
	/**
	 * Handles the related plugin operation.
	 */
	function noesia_cs_public_area_label( $area ) {
		$group_by  = isset( $area['group_by'] ) ? sanitize_key( $area['group_by'] ) : 'country';
		$country   = ! empty( $area['country_label'] ) ? sanitize_text_field( $area['country_label'] ) : sanitize_text_field( $area['country'] ?? '' );
		$region    = sanitize_text_field( $area['region'] ?? '' );
		$city      = sanitize_text_field( $area['city'] ?? '' );

		if ( 'country' === $group_by ) {
			return $country ? $country : sanitize_text_field( $area['label'] ?? '' );
		}

		if ( 'region' === $group_by ) {
			$parts = array_filter( array( $region, $country ) );
			return $parts ? implode( ', ', array_unique( $parts ) ) : sanitize_text_field( $area['label'] ?? '' );
		}

		$parts = array_filter( array( $city, $country ) );
		return $parts ? implode( ', ', array_unique( $parts ) ) : sanitize_text_field( $area['label'] ?? '' );
	}
}
?>
<div class="<?php echo esc_attr( $wrapper_classes ); ?>">
	<?php if ( in_array( $style, array( 'noesia_glass', 'dark_map' ), true ) ) : ?>
		<div class="noesia-cs-impact-map__world" aria-hidden="true">
			<?php if ( 'dark_map' === $style && $dark_map_image_url ) : ?>
				<img class="noesia-cs-impact-map__map-image" src="<?php echo esc_url( $dark_map_image_url ); ?>" alt="" loading="lazy" decoding="async">
			<?php endif; ?>
		</div>
	<?php endif; ?>
	<div class="noesia-cs-impact-map__content">
		<div class="noesia-cs-impact-map__header">
			<div>
				<span class="noesia-cs-impact-map__eyebrow"><?php echo esc_html( $eyebrow ); ?></span>
				<strong><?php echo esc_html( $title ); ?></strong>
				<span><?php echo esc_html( $subtitle ); ?></span>
			</div>
			<?php if ( ! empty( $snapshot['generated_at'] ) ) : ?>
				<div class="noesia-cs-impact-map__stats" aria-label="<?php esc_attr_e( 'Impact summary', 'noesia-commerce-suite' ); ?>">
					<?php if ( 'yes' === ( $settings['impact_map_show_orders'] ?? 'yes' ) ) : ?>
						<div><strong><?php echo esc_html( number_format_i18n( $total_orders ) ); ?></strong><span><?php esc_html_e( 'orders', 'noesia-commerce-suite' ); ?></span></div>
					<?php endif; ?>
					<?php if ( 'yes' === ( $settings['impact_map_show_products'] ?? 'yes' ) ) : ?>
						<div><strong><?php echo esc_html( number_format_i18n( $total_products ) ); ?></strong><span><?php esc_html_e( 'products', 'noesia-commerce-suite' ); ?></span></div>
					<?php endif; ?>
					<div><strong><?php echo esc_html( number_format_i18n( count( $areas ) ) ); ?></strong><span><?php esc_html_e( 'areas', 'noesia-commerce-suite' ); ?></span></div>
				</div>
			<?php endif; ?>
		</div>

		<?php if ( empty( $snapshot['generated_at'] ) ) : ?>
			<p class="noesia-cs-impact-map__empty"><?php esc_html_e( 'Impact Map snapshot has not been generated yet.', 'noesia-commerce-suite' ); ?></p>
		<?php else : ?>
			<div class="noesia-cs-impact-map__meta">
				<span><?php printf( /* translators: %s: dynamic value. */ esc_html__( 'Last refresh: %s', 'noesia-commerce-suite' ), esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), absint( $snapshot['generated_at'] ) ) ) ); ?></span>
				<span><?php printf( /* translators: %d: numeric value. */ esc_html__( 'Privacy threshold: %d orders', 'noesia-commerce-suite' ), absint( $snapshot['threshold'] ) ); ?></span>
				<span><?php printf( /* translators: %s: dynamic value. */ esc_html__( 'Grouped by: %s', 'noesia-commerce-suite' ), esc_html( ucfirst( sanitize_key( $snapshot['group_by'] ?? 'country' ) ) ) ); ?></span>
			</div>

			<div class="noesia-cs-impact-map__grid">
				<?php foreach ( $areas as $area ) : ?>
					<div class="noesia-cs-impact-map__card">
						<div class="noesia-cs-impact-map__area-title">
							<span class="noesia-cs-impact-map__flag"><?php echo esc_html( noesia_cs_public_country_flag( $area['country'] ?? '' ) ); ?></span>
							<strong><?php echo esc_html( noesia_cs_public_area_label( $area ) ); ?></strong>
						</div>
						<?php if ( 'yes' === ( $settings['impact_map_show_orders'] ?? 'yes' ) || 'yes' === ( $settings['impact_map_show_products'] ?? 'yes' ) ) : ?>
							<div class="noesia-cs-impact-map__area-metrics">
								<?php if ( 'yes' === ( $settings['impact_map_show_orders'] ?? 'yes' ) ) : ?>
									<span><strong><?php echo esc_html( number_format_i18n( absint( $area['orders'] ) ) ); ?></strong><?php esc_html_e( 'orders', 'noesia-commerce-suite' ); ?></span>
								<?php endif; ?>
								<?php if ( 'yes' === ( $settings['impact_map_show_products'] ?? 'yes' ) ) : ?>
									<span><strong><?php echo esc_html( number_format_i18n( absint( $area['products'] ) ) ); ?></strong><?php esc_html_e( 'products', 'noesia-commerce-suite' ); ?></span>
								<?php endif; ?>
							</div>
						<?php endif; ?>
						<?php if ( ! empty( $area['top_categories'] ) && 'yes' === ( $settings['impact_map_show_top_categories'] ?? 'yes' ) ) : ?>
							<small><?php printf( /* translators: %s: dynamic value. */ esc_html__( 'Top categories: %s', 'noesia-commerce-suite' ), esc_html( implode( ', ', array_map( 'sanitize_text_field', $area['top_categories'] ) ) ) ); ?></small>
						<?php endif; ?>
						<?php if ( ! empty( $area['top_products'] ) && 'yes' === ( $settings['impact_map_show_top_products'] ?? 'yes' ) ) : ?>
							<small><?php printf( /* translators: %s: dynamic value. */ esc_html__( 'Top products: %s', 'noesia-commerce-suite' ), esc_html( implode( ', ', array_map( 'sanitize_text_field', $area['top_products'] ) ) ) ); ?></small>
						<?php endif; ?>
						<?php if ( 'yes' === ( $settings['impact_map_show_revenue'] ?? 'no' ) && 'no' === ( $settings['privacy_hide_revenue_public'] ?? 'yes' ) ) : ?>
							<small class="noesia-cs-impact-map__revenue"><?php echo wp_kses_post( function_exists( 'wc_price' ) ? wc_price( $area['revenue'] ) : number_format_i18n( $area['revenue'], 2 ) ); ?></small>
						<?php endif; ?>
					</div>
				<?php endforeach; ?>
				<?php if ( empty( $areas ) ) : ?>
					<p class="noesia-cs-impact-map__empty"><?php esc_html_e( 'No public areas meet the configured privacy threshold.', 'noesia-commerce-suite' ); ?></p>
				<?php endif; ?>
			</div>

			<?php if ( ! empty( $snapshot['hidden_areas_count'] ) ) : ?>
				<p class="noesia-cs-impact-map__privacy-note"><?php printf( /* translators: %d: numeric value. */ esc_html__( '%d low-volume areas are hidden by the public privacy threshold.', 'noesia-commerce-suite' ), absint( $snapshot['hidden_areas_count'] ) ); ?></p>
			<?php endif; ?>
		<?php endif; ?>
	</div>
</div>
